root/OpenSceneGraph/trunk/examples/osgtexture3D/osgtexture3D.cpp @ 1697

Revision 1697, 9.5 kB (checked in by robert, 11 years ago)

Ported osgGLUT based src/Demos across to being osgProducer based, and placed
them in the new examples/ directory.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1#include <osg/Node>
2#include <osg/Geometry>
3#include <osg/Notify>
4#include <osg/Texture3D>
5#include <osg/TexGen>
6#include <osg/Geode>
7
8#include <osgGA/TrackballManipulator>
9#include <osgGA/FlightManipulator>
10#include <osgGA/DriveManipulator>
11
12#include <osgDB/Registry>
13#include <osgDB/ReadFile>
14
15#include <osgProducer/Viewer>
16
17
18//
19// A simple demo demonstrating different texturing modes,
20// including using of texture extensions.
21//
22
23
24typedef std::vector< osg::ref_ptr<osg::Image> > ImageList;
25
26
27class ConstructStateCallback : public osg::NodeCallback
28{
29    public:
30        ConstructStateCallback() {}
31       
32        osg::StateSet* constructState()
33        {
34       
35            // read 4 2d images
36            osg::ref_ptr<osg::Image> image_0 = osgDB::readImageFile("Images/lz.rgb");
37            osg::ref_ptr<osg::Image> image_1 = osgDB::readImageFile("Images/reflect.rgb");
38            osg::ref_ptr<osg::Image> image_2 = osgDB::readImageFile("Images/tank.rgb");
39            osg::ref_ptr<osg::Image> image_3 = osgDB::readImageFile("Images/skymap.jpg");
40
41            if (!image_0 || !image_1 || !image_2 || !image_3)
42            {
43                std::cout << "Warning: could not open files."<<std::endl;
44                return new osg::StateSet;
45            }
46
47            if (image_0->getPixelFormat()!=image_1->getPixelFormat() || image_0->getPixelFormat()!=image_2->getPixelFormat() || image_0->getPixelFormat()!=image_3->getPixelFormat())
48            {
49                std::cout << "Warning: image pixel formats not compatible."<<std::endl;
50                return new osg::StateSet;
51            }
52
53            // get max 3D texture size
54            GLint textureSize = osg::Texture3D::getExtensions(0,true)->maxTexture3DSize();
55            if (textureSize > 256)
56                textureSize = 256;
57
58            // scale them all to the same size.
59            image_0->scaleImage(textureSize,textureSize,1);
60            image_1->scaleImage(textureSize,textureSize,1);
61            image_2->scaleImage(textureSize,textureSize,1);
62            image_3->scaleImage(textureSize,textureSize,1);
63
64
65            // then allocated a 3d image to use for texturing.
66            osg::Image* image_3d = new osg::Image;
67            image_3d->allocateImage(textureSize,textureSize,4,
68                                    image_0->getPixelFormat(),image_0->getDataType());
69
70            // copy the 2d images into the 3d image.
71            image_3d->copySubImage(0,0,0,image_0.get());
72            image_3d->copySubImage(0,0,1,image_1.get());
73            image_3d->copySubImage(0,0,2,image_2.get());
74            image_3d->copySubImage(0,0,3,image_3.get());
75
76            image_3d->setInternalTextureFormat(image_0->getInternalTextureFormat());       
77
78            // set up the 3d texture itself,
79            // note, well set the filtering up so that mip mapping is disabled,
80            // gluBuild3DMipsmaps doesn't do a very good job of handled the
81            // inbalanced dimensions of the 256x256x4 texture.
82            osg::Texture3D* texture3D = new osg::Texture3D;
83            texture3D->setFilter(osg::Texture3D::MIN_FILTER,osg::Texture3D::LINEAR);
84            texture3D->setFilter(osg::Texture3D::MAG_FILTER,osg::Texture3D::LINEAR);
85            texture3D->setImage(image_3d);
86
87
88            // create a texgen to generate a R texture coordinate, the geometry
89            // itself will supply the S & T texture coordinates.
90            // in the animateStateSet callback well alter this R value to
91            // move the texture through the 3d texture, 3d texture filtering
92            // will do the blending for us.
93            osg::TexGen* texgen = new osg::TexGen;
94            texgen->setMode(osg::TexGen::OBJECT_LINEAR);
95            texgen->setPlane(osg::TexGen::R, osg::Vec4(0.0f,0.0f,0.0f,0.2f));
96
97            // create the StateSet to store the texture data
98            osg::StateSet* stateset = new osg::StateSet;
99            stateset->setTextureMode(0,GL_TEXTURE_GEN_R,osg::StateAttribute::ON);
100            stateset->setTextureAttribute(0,texgen);
101            stateset->setTextureAttributeAndModes(0,texture3D,osg::StateAttribute::ON);
102
103            return stateset;
104        }
105
106        void animateState(osg::StateSet* stateset)
107        {
108            // here we simply get any existing texgen, and then increment its
109            // plane, pushing the R coordinate through the texture.
110            osg::StateAttribute* attribute = stateset->getTextureAttribute(0,osg::StateAttribute::TEXGEN);
111            osg::TexGen* texgen = dynamic_cast<osg::TexGen*>(attribute);
112            if (texgen)
113            {
114                texgen->getPlane(osg::TexGen::R)[3] += 0.001f;
115            }
116           
117        }
118
119        virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
120        {
121
122            osg::StateSet* stateset = node->getStateSet();
123            if (stateset)
124            {
125                // we have an exisitng stateset, so lets animate it.
126                animateState(stateset);
127            }
128            else
129            {
130                // no state exist yet, so we must be in the first
131                // pass, so lets create our stateset with all the
132                // textures in it.
133                stateset = constructState();
134                if (stateset) node->setStateSet(stateset);
135            }
136
137            // note, callback is repsonsible for scenegraph traversal so
138            // should always include call the traverse(node,nv) to ensure
139            // that the rest of cullbacks and the scene graph are traversed.
140            traverse(node,nv);
141        }     
142};
143
144/** create 2,2 square with center at 0,0,0 and aligned along the XZ plan */
145osg::Drawable* createSquare(float textureCoordMax=1.0f)
146{
147    // set up the Geometry.
148    osg::Geometry* geom = new osg::Geometry;
149
150    osg::Vec3Array* coords = new osg::Vec3Array(4);
151    (*coords)[0].set(-1.0f,0.0f,1.0f);
152    (*coords)[1].set(-1.0f,0.0f,-1.0f);
153    (*coords)[2].set(1.0f,0.0f,-1.0f);
154    (*coords)[3].set(1.0f,0.0f,1.0f);
155    geom->setVertexArray(coords);
156
157    osg::Vec3Array* norms = new osg::Vec3Array(1);
158    (*norms)[0].set(0.0f,-1.0f,0.0f);
159    geom->setNormalArray(norms);
160    geom->setNormalBinding(osg::Geometry::BIND_OVERALL);
161
162    osg::Vec2Array* tcoords = new osg::Vec2Array(4);
163    (*tcoords)[0].set(0.0f,textureCoordMax);
164    (*tcoords)[1].set(0.0f,0.0f);
165    (*tcoords)[2].set(textureCoordMax,0.0f);
166    (*tcoords)[3].set(textureCoordMax,textureCoordMax);
167    geom->setTexCoordArray(0,tcoords);
168   
169    geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4));
170
171    return geom;
172}
173
174osg::Node* createModel()
175{
176
177    // create the geometry of the model, just a simple 2d quad right now.   
178    osg::Geode* geode = new osg::Geode;
179    geode->addDrawable(createSquare());
180
181    // normally we'd create the stateset's to contain all the textures
182    // etc here, but, the above technique uses osg::Image::scaleImage and
183    // osg::Image::copySubImage() which are implemented with OpenGL utility
184    // library, which unfortunately can't be used until we have a valid
185    // OpenGL context, and at this point in initilialization we don't have
186    // a valid OpenGL context, so we have to delay creation of state until
187    // there is a valid OpenGL context.  I'll manage this by using an
188    // app callback which will create the state during the first traversal.
189    // A bit hacky, and my plan is to reimplement the osg::scaleImage and
190    // osg::Image::copySubImage() without using GLU which will get round
191    // this current limitation.
192    geode->setUpdateCallback(new ConstructStateCallback());
193   
194    return geode;
195
196}
197
198
199int main( int argc, char **argv )
200{
201
202    // use an ArgumentParser object to manage the program arguments.
203    osg::ArgumentParser arguments(&argc,argv);
204   
205    // set up the usage document, in case we need to print out how to use this program.
206    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getProgramName()+" [options] filename ...");
207    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
208   
209
210    // construct the viewer.
211    osgProducer::Viewer viewer(arguments);
212
213    // set up the value with sensible default event handlers.
214    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
215
216    // get details on keyboard and mouse bindings used by the viewer.
217    viewer.getUsage(*arguments.getApplicationUsage());
218
219    // if user request help write it out to cout.
220    if (arguments.read("-h") || arguments.read("--help"))
221    {
222        arguments.getApplicationUsage()->write(std::cout);
223        return 1;
224    }
225
226    // any option left unread are converted into errors to write out later.
227    arguments.reportRemainingOptionsAsUnrecognized();
228
229    // report any errors if they have occured when parsing the program aguments.
230    if (arguments.errors())
231    {
232        arguments.writeErrorMessages(std::cout);
233        return 1;
234    }
235
236    // create a model from the images.
237    osg::Node* rootNode = createModel();
238
239    if (rootNode)
240    {
241
242        // set the scene to render
243        viewer.setSceneData(rootNode);
244
245        // create the windows and run the threads.
246        viewer.realize(Producer::CameraGroup::ThreadPerCamera);
247
248        while( !viewer.done() )
249        {
250            // wait for all cull and draw threads to complete.
251            viewer.sync();
252
253            // update the scene by traversing it with the the update visitor which will
254            // call all node update callbacks and animations.
255            viewer.update();
256
257            // fire off the cull and draw traversals of the scene.
258            viewer.frame();
259
260        }
261       
262    }   
263   
264    return 0;
265}
Note: See TracBrowser for help on using the browser.