OpenSceneGraph/examples/osglogo/osglogo.cpp

507 lines
16 KiB
C++
Raw Normal View History

/* OpenSceneGraph example, osglogo.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osg/Material>
#include <osg/Texture2D>
#include <osg/Geometry>
#include <osg/MatrixTransform>
#include <osg/PositionAttitudeTransform>
#include <osg/BlendFunc>
#include <osg/ClearNode>
#include <osg/Version>
#include <osgUtil/Tessellator>
#include <osgUtil/CullVisitor>
#include <osgText/Text>
#include <osgGA/TrackballManipulator>
2017-02-27 18:47:14 +08:00
#include <osgGA/StateSetManipulator>
#include <osgViewer/Viewer>
#include <osgDB/ReadFile>
#include <iostream>
2017-09-21 22:41:21 +08:00
static bool s_useSDF = false;
class MyBillboardTransform : public osg::PositionAttitudeTransform
{
public:
MyBillboardTransform():
_axis(0.0f,0.0f,1.0f),
_normal(0.0f,-1.0f,0.0f)
{
}
bool computeLocalToWorldMatrix(osg::Matrix& matrix,osg::NodeVisitor* nv) const
{
osg::Quat billboardRotation;
osgUtil::CullVisitor* cullvisitor = dynamic_cast<osgUtil::CullVisitor*>(nv);
if (cullvisitor)
{
osg::Vec3 eyevector = cullvisitor->getEyeLocal()-_position;
eyevector.normalize();
osg::Vec3 side = _axis^_normal;
side.normalize();
float angle = atan2(eyevector*_normal,eyevector*side);
billboardRotation.makeRotate(osg::PI_2-angle,_axis);
}
From Mathias Froehlich, "This is a generic optimization that does not depend on any cpu or instruction set. The optimization is based on the observation that matrix matrix multiplication with a dense matrix 4x4 is 4^3 Operations whereas multiplication with a transform, or scale matrix is only 4^2 operations. Which is a gain of a *FACTOR*4* for these special cases. The change implements these special cases, provides a unit test for these implementation and converts uses of the expensiver dense matrix matrix routine with the specialized versions. Depending on the transform nodes in the scenegraph this change gives a noticable improovement. For example the osgforest code using the MatrixTransform is about 20% slower than the same codepath using the PositionAttitudeTransform instead of the MatrixTransform with this patch applied. If I remember right, the sse type optimizations did *not* provide a factor 4 improovement. Also these changes are totally independent of any cpu or instruction set architecture. So I would prefer to have this current kind of change instead of some hand coded and cpu dependent assembly stuff. If we need that hand tuned stuff, these can go on top of this changes which must provide than hand optimized additional variants for the specialized versions to give a even better result in the end. An other change included here is a change to rotation matrix from quaterion code. There is a sqrt call which couold be optimized away. Since we divide in effect by sqrt(length)*sqrt(length) which is just length ... "
2008-09-18 00:14:28 +08:00
matrix.preMultTranslate(_position);
matrix.preMultRotate(billboardRotation);
matrix.preMultRotate(_attitude);
2008-10-27 18:40:13 +08:00
matrix.preMultTranslate(-_pivotPoint);
return true;
}
void setAxis(const osg::Vec3& axis) { _axis = axis; }
void setNormal(const osg::Vec3& normal) { _normal = normal; }
protected:
virtual ~MyBillboardTransform() {}
osg::Vec3 _axis;
osg::Vec3 _normal;
};
osg::Geometry* createWing(const osg::Vec3& left, const osg::Vec3& nose, const osg::Vec3& right,float chordRatio,const osg::Vec4& color)
{
osg::Geometry* geom = new osg::Geometry;
osg::Vec3 normal = (nose-right)^(left-nose);
normal.normalize();
osg::Vec3 left_to_right = right-left;
osg::Vec3 mid = (right+left)*0.5f;
osg::Vec3 mid_to_nose = (nose-mid)*chordRatio*0.5f;
osg::Vec3Array* vertices = new osg::Vec3Array;
vertices->push_back(left);
//vertices->push_back(mid+mid_to_nose);
unsigned int noSteps = 40;
for(unsigned int i=1;i<noSteps;++i)
{
float ratio = (float)i/(float)noSteps;
vertices->push_back(left + left_to_right*ratio + mid_to_nose* (cosf((ratio-0.5f)*osg::PI*2.0f)+1.0f));
}
vertices->push_back(right);
vertices->push_back(nose);
geom->setVertexArray(vertices);
osg::Vec3Array* normals = new osg::Vec3Array;
normals->push_back(normal);
geom->setNormalArray(normals, osg::Array::BIND_OVERALL);
osg::Vec4Array* colors = new osg::Vec4Array;
colors->push_back(color);
geom->setColorArray(colors, osg::Array::BIND_OVERALL);
geom->addPrimitiveSet(new osg::DrawArrays(GL_POLYGON,0,vertices->getNumElements()));
osgUtil::Tessellator tessellator;
tessellator.retessellatePolygons(*geom);
return geom;
}
osg:: Node* createTextBelow(const osg::BoundingBox& bb, const std::string& label, const std::string&)
{
osg::Geode* geode = new osg::Geode();
std::string font("fonts/arial.ttf");
osgText::Text* text = new osgText::Text;
text->setFont(font);
text->setFontResolution(64,64);
2017-09-21 22:41:21 +08:00
if (s_useSDF)
{
text->getFont()->setGyphTextureFeatures(osgText::GlyphTexture::ALL_FEATURES);
text->setBackdropImplementation(osgText::Text::USE_SHADERS);
}
text->setAlignment(osgText::Text::CENTER_CENTER);
text->setAxisAlignment(osgText::Text::XZ_PLANE);
text->setPosition(bb.center()-osg::Vec3(0.0f,0.0f,(bb.zMax()-bb.zMin())));
text->setColor(osg::Vec4(0.37f,0.48f,0.67f,1.0f));
text->setText(label);
geode->addDrawable( text );
return geode;
}
osg:: Node* createTextLeft(const osg::BoundingBox& bb, const std::string& label, const std::string& subscript)
{
osg::Geode* geode = new osg::Geode();
osg::StateSet* stateset = geode->getOrCreateStateSet();
stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
//std::string font("fonts/times.ttf");
std::string font("fonts/arial.ttf");
osgText::Text* text = new osgText::Text;
text->setFont(font);
text->setFontResolution(110,120);
2017-09-21 22:41:21 +08:00
text->setAlignment(osgText::Text::RIGHT_CENTER);
text->setAxisAlignment(osgText::Text::XZ_PLANE);
text->setCharacterSize((bb.zMax()-bb.zMin())*1.0f);
2017-09-21 22:41:21 +08:00
text->setPosition(bb.center()-osg::Vec3((bb.xMax()-bb.xMin()),-(bb.yMax()-bb.yMin())*0.5f,(bb.zMax()-bb.zMin())*0.1f));
//text->setColor(osg::Vec4(0.37f,0.48f,0.67f,1.0f)); // Neil's original OSG colour
text->setColor(osg::Vec4(0.20f,0.45f,0.60f,1.0f)); // OGL logo colour
2017-09-21 22:41:21 +08:00
OSG_NOTICE<<std::endl<<"***** POS A ******"<<std::endl;
if (s_useSDF)
{
text->getFont()->setGyphTextureFeatures(osgText::GlyphTexture::ALL_FEATURES);
text->setBackdropImplementation(osgText::Text::USE_SHADERS);
}
OSG_NOTICE<<std::endl<<"***** POS B ******"<<std::endl;
text->setBackdropType(osgText::Text::OUTLINE);
text->setBackdropOffset(0.03f);
text->setBackdropColor(osg::Vec4(0.0f, 0.0f, 0.5f, 1.0f));
OSG_NOTICE<<std::endl<<"***** POS C ******"<<std::endl;
text->setColorGradientMode(osgText::Text::OVERALL);
osg::Vec4 lightblue(0.30f,0.6f,0.90f,1.0f);
osg::Vec4 blue(0.10f,0.30f,0.40f,1.0f);
text->setColorGradientCorners(lightblue, blue, blue, lightblue);
text->setText(label);
geode->addDrawable( text );
if (!subscript.empty())
{
osgText::Text* subscriptText = new osgText::Text;
subscriptText->setFont(font);
subscriptText->setText(subscript);
subscriptText->setAlignment(osgText::Text::RIGHT_CENTER);
subscriptText->setAxisAlignment(osgText::Text::XZ_PLANE);
subscriptText->setPosition(bb.center()-osg::Vec3((bb.xMax()-bb.xMin())*4.3f,-(bb.yMax()-bb.yMin())*0.5f,(bb.zMax()-bb.zMin())*0.6f));
subscriptText->setColor(osg::Vec4(0.0f,0.0f,0.0f,1.0f)); // black
geode->addDrawable( subscriptText );
}
return geode;
}
osg:: Node* createGlobe(const osg::BoundingBox& bb,float ratio, const std::string& filename)
{
osg::MatrixTransform* xform = new osg::MatrixTransform;
xform->setUpdateCallback(new osg::AnimationPathCallback(bb.center(),osg::Vec3(0.0f,0.0f,1.0f),osg::inDegrees(10.0f)));
Introduced CMake option OSG_PROVIDE_READFILE option that defaults to ON, but when switched to OFF disables the building of the osgDB::read*File() methods, forcing users to use osgDB::readRef*File() methods. The later is preferable as it closes a potential threading bug when using paging databases in conjunction with the osgDB::Registry Object Cache. This threading bug occurs when one thread gets an object from the Cache via an osgDB::read*File() call where only a pointer to the object is passed back, so taking a reference to the object is delayed till it gets reassigned to a ref_ptr<>, but at the same time another thread calls a flush of the Object Cache deleting this object as it's referenceCount is now zero. Using osgDB::readREf*File() makes sure the a ref_ptr<> is passed back and the referenceCount never goes to zero. To ensure the OSG builds when OSG_PROVIDE_READFILE is to OFF the many cases of osgDB::read*File() usage had to be replaced with a ref_ptr<> osgDB::readRef*File() usage. The avoid this change causing lots of other client code to be rewritten to handle the use of ref_ptr<> in place of C pointer I introduced a serious of templte methods in various class to adapt ref_ptr<> to the underly C pointer to be passed to old OSG API's, example of this is found in include/osg/Group: bool addChild(Node* child); // old method which can only be used with a Node* tempalte<class T> bool addChild(const osg::ref_ptr<T>& child) { return addChild(child.get()); } // adapter template method These changes together cover 149 modified files, so it's a large submission. This extent of changes are warrent to make use of the Object Cache and multi-threaded loaded more robust. git-svn-id: http://svn.openscenegraph.org/osg/OpenSceneGraph/trunk@15164 16af8721-9629-0410-8352-f15c8da7e697
2015-10-22 21:42:19 +08:00
osg::ref_ptr<osg::Node> bluemarble = filename.empty() ? 0 : osgDB::readRefNodeFile(filename.c_str());
if (bluemarble)
{
const osg::BoundingSphere& bs = bluemarble->getBound();
float s = 1.2*bb.radius()/bs.radius();
osg::MatrixTransform* positioner = new osg::MatrixTransform;
positioner->setMatrix(osg::Matrix::translate(-bs.center())*osg::Matrix::scale(s,s,s)*osg::Matrix::translate(bb.center()));
positioner->addChild(bluemarble);
xform->addChild(positioner);
}
else
{
osg::Geode* geode = new osg::Geode();
osg::StateSet* stateset = geode->getOrCreateStateSet();
Introduced CMake option OSG_PROVIDE_READFILE option that defaults to ON, but when switched to OFF disables the building of the osgDB::read*File() methods, forcing users to use osgDB::readRef*File() methods. The later is preferable as it closes a potential threading bug when using paging databases in conjunction with the osgDB::Registry Object Cache. This threading bug occurs when one thread gets an object from the Cache via an osgDB::read*File() call where only a pointer to the object is passed back, so taking a reference to the object is delayed till it gets reassigned to a ref_ptr<>, but at the same time another thread calls a flush of the Object Cache deleting this object as it's referenceCount is now zero. Using osgDB::readREf*File() makes sure the a ref_ptr<> is passed back and the referenceCount never goes to zero. To ensure the OSG builds when OSG_PROVIDE_READFILE is to OFF the many cases of osgDB::read*File() usage had to be replaced with a ref_ptr<> osgDB::readRef*File() usage. The avoid this change causing lots of other client code to be rewritten to handle the use of ref_ptr<> in place of C pointer I introduced a serious of templte methods in various class to adapt ref_ptr<> to the underly C pointer to be passed to old OSG API's, example of this is found in include/osg/Group: bool addChild(Node* child); // old method which can only be used with a Node* tempalte<class T> bool addChild(const osg::ref_ptr<T>& child) { return addChild(child.get()); } // adapter template method These changes together cover 149 modified files, so it's a large submission. This extent of changes are warrent to make use of the Object Cache and multi-threaded loaded more robust. git-svn-id: http://svn.openscenegraph.org/osg/OpenSceneGraph/trunk@15164 16af8721-9629-0410-8352-f15c8da7e697
2015-10-22 21:42:19 +08:00
osg::ref_ptr<osg::Image> image = osgDB::readRefImageFile("Images/land_shallow_topo_2048.jpg");
if (image)
{
2005-11-18 04:22:55 +08:00
osg::Texture2D* texture = new osg::Texture2D;
texture->setImage(image);
texture->setMaxAnisotropy(8);
stateset->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
}
osg::Material* material = new osg::Material;
stateset->setAttribute(material);
// the globe
geode->addDrawable(new osg::ShapeDrawable(new osg::Sphere(bb.center(),bb.radius()*ratio)));
xform->addChild(geode);
}
return xform;
}
osg:: Node* createBox(const osg::BoundingBox& bb,float chordRatio)
{
osg::Geode* geode = new osg::Geode();
osg::Vec4 white(1.0f,1.0f,1.0f,1.0f);
// front faces.
geode->addDrawable(createWing(bb.corner(4),bb.corner(6),bb.corner(7),chordRatio,white));
geode->addDrawable(createWing(bb.corner(7),bb.corner(5),bb.corner(4),chordRatio,white));
geode->addDrawable(createWing(bb.corner(4),bb.corner(5),bb.corner(1),chordRatio,white));
geode->addDrawable(createWing(bb.corner(1),bb.corner(0),bb.corner(4),chordRatio,white));
geode->addDrawable(createWing(bb.corner(1),bb.corner(5),bb.corner(7),chordRatio,white));
geode->addDrawable(createWing(bb.corner(7),bb.corner(3),bb.corner(1),chordRatio,white));
// back faces
geode->addDrawable(createWing(bb.corner(2),bb.corner(0),bb.corner(1),chordRatio,white));
geode->addDrawable(createWing(bb.corner(1),bb.corner(3),bb.corner(2),chordRatio,white));
geode->addDrawable(createWing(bb.corner(2),bb.corner(3),bb.corner(7),chordRatio,white));
geode->addDrawable(createWing(bb.corner(7),bb.corner(6),bb.corner(2),chordRatio,white));
geode->addDrawable(createWing(bb.corner(2),bb.corner(6),bb.corner(4),chordRatio,white));
geode->addDrawable(createWing(bb.corner(4),bb.corner(0),bb.corner(2),chordRatio,white));
return geode;
}
osg:: Node* createBoxNo5(const osg::BoundingBox& bb,float chordRatio)
{
osg::Geode* geode = new osg::Geode();
osg::Vec4 white(1.0f,1.0f,1.0f,1.0f);
// front faces.
geode->addDrawable(createWing(bb.corner(4),bb.corner(6),bb.corner(7),chordRatio,white));
geode->addDrawable(createWing(bb.corner(1),bb.corner(0),bb.corner(4),chordRatio,white));
geode->addDrawable(createWing(bb.corner(7),bb.corner(3),bb.corner(1),chordRatio,white));
// back faces
geode->addDrawable(createWing(bb.corner(2),bb.corner(0),bb.corner(1),chordRatio,white));
geode->addDrawable(createWing(bb.corner(1),bb.corner(3),bb.corner(2),chordRatio,white));
geode->addDrawable(createWing(bb.corner(2),bb.corner(3),bb.corner(7),chordRatio,white));
geode->addDrawable(createWing(bb.corner(7),bb.corner(6),bb.corner(2),chordRatio,white));
geode->addDrawable(createWing(bb.corner(2),bb.corner(6),bb.corner(4),chordRatio,white));
geode->addDrawable(createWing(bb.corner(4),bb.corner(0),bb.corner(2),chordRatio,white));
return geode;
}
osg:: Node* createBoxNo5No2(const osg::BoundingBox& bb,float chordRatio)
{
osg::Geode* geode = new osg::Geode();
// osg::Vec4 red(1.0f,0.0f,0.0f,1.0f);
// osg::Vec4 green(0.0f,1.0f,0.0f,1.0f);
// osg::Vec4 blue(0.0f,0.0f,1.0f,1.0f);
osg::Vec4 red(1.0f,0.12f,0.06f,1.0f);
osg::Vec4 green(0.21f,0.48f,0.03f,1.0f);
osg::Vec4 blue(0.20f,0.45f,0.60f,1.0f);
// front faces.
geode->addDrawable(createWing(bb.corner(4),bb.corner(6),bb.corner(7),chordRatio,red));
geode->addDrawable(createWing(bb.corner(1),bb.corner(0),bb.corner(4),chordRatio,green));
geode->addDrawable(createWing(bb.corner(7),bb.corner(3),bb.corner(1),chordRatio,blue));
return geode;
}
osg:: Node* createBackdrop(const osg::Vec3& corner,const osg::Vec3& top,const osg::Vec3& right)
{
osg::Geometry* geom = new osg::Geometry;
osg::Vec3 normal = (corner-top)^(right-corner);
normal.normalize();
osg::Vec3Array* vertices = new osg::Vec3Array;
vertices->push_back(top);
vertices->push_back(corner);
vertices->push_back(right);
vertices->push_back(right+(top-corner));
geom->setVertexArray(vertices);
osg::Vec3Array* normals = new osg::Vec3Array;
normals->push_back(normal);
geom->setNormalArray(normals, osg::Array::BIND_OVERALL);
osg::Vec4Array* colors = new osg::Vec4Array;
colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
geom->setColorArray(colors, osg::Array::BIND_OVERALL);
geom->addPrimitiveSet(new osg::DrawArrays(GL_QUADS,0,vertices->getNumElements()));
osg::Geode* geode = new osg::Geode();
geode->addDrawable(geom);
return geode;
}
osg::Node* createLogo(const std::string& filename, const std::string& label, const std::string& subscript)
{
osg::BoundingBox bb(osg::Vec3(0.0f,0.0f,0.0f),osg::Vec3(100.0f,100.0f,100.0f));
float chordRatio = 0.5f;
float sphereRatio = 0.6f;
// create a group to hold the whole model.
osg::Group* logo_group = new osg::Group;
osg::Quat r1,r2;
r1.makeRotate(-osg::inDegrees(45.0f),0.0f,0.0f,1.0f);
r2.makeRotate(osg::inDegrees(45.0f),1.0f,0.0f,0.0f);
MyBillboardTransform* xform = new MyBillboardTransform;
xform->setPivotPoint(bb.center());
xform->setPosition(bb.center());
xform->setAttitude(r1*r2);
// // create a transform to orientate the box and globe.
// osg::MatrixTransform* xform = new osg::MatrixTransform;
// xform->setDataVariance(osg::Object::STATIC);
// xform->setMatrix(osg::Matrix::translate(-bb.center())*
// osg::Matrix::rotate(-osg::inDegrees(45.0f),0.0f,0.0f,1.0f)*
// osg::Matrix::rotate(osg::inDegrees(45.0f),1.0f,0.0f,0.0f)*
// osg::Matrix::translate(bb.center()));
// add the box and globe to it.
//xform->addChild(createBox(bb,chordRatio));
//xform->addChild(createBoxNo5(bb,chordRatio));
xform->addChild(createBoxNo5No2(bb,chordRatio));
// add the transform to the group.
logo_group->addChild(xform);
logo_group->addChild(createGlobe(bb,sphereRatio,filename));
// add the text to the group.
//group->addChild(createTextBelow(bb));
logo_group->addChild(createTextLeft(bb, label, subscript));
// create the backdrop to render the shadow to.
osg::Vec3 corner(-900.0f,150.0f,-100.0f);
osg::Vec3 top(0.0f,0.0f,300.0f); top += corner;
osg::Vec3 right(1100.0f,0.0f,0.0f); right += corner;
// osg::Group* backdrop = new osg::Group;
// backdrop->addChild(createBackdrop(corner,top,right));
osg::ClearNode* backdrop = new osg::ClearNode;
backdrop->setClearColor(osg::Vec4(1.0f,1.0f,1.0f,0.0f));
//osg::Vec3 lightPosition(-500.0f,-2500.0f,500.0f);
//osg::Node* scene = createShadowedScene(logo_group,backdrop,lightPosition,0.0f,0);
osg::Group* scene = new osg::Group;
osg::StateSet* stateset = scene->getOrCreateStateSet();
stateset->setMode(GL_LIGHTING,osg::StateAttribute::OVERRIDE|osg::StateAttribute::OFF);
scene->addChild(logo_group);
scene->addChild(backdrop);
return scene;
}
int main( int argc, char **argv )
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
osg::DisplaySettings::instance()->setMinimumNumAlphaBits(8);
// construct the viewer.
osgViewer::Viewer viewer;
2017-02-27 18:47:14 +08:00
// add the state manipulator
viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) );
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
2017-09-21 22:41:21 +08:00
while(arguments.read("--sdf")) { s_useSDF = true; }
std::string label = "OpenSceneGraph";
std::string subscript = "";
bool showVersion = false;
while (arguments.read("--version")) { showVersion = true; }
if( showVersion )
{
label += " ";
label += osgGetVersion();
}
while (arguments.read("--label", label)) {}
while (arguments.read("--subscript", subscript)) {}
osg::ref_ptr<osg::Node> node;
if (arguments.argc()>1) node = createLogo(arguments[1], label, subscript);
else node = createLogo("", label, subscript);
// add model to viewer.
viewer.setSceneData( node.get() );
return viewer.run();
}