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

Revision 6941, 9.0 kB (checked in by robert, 8 years ago)

From Martin Lavery and Robert Osfield, Updated examples to use a variation of the MIT License

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1/* OpenSceneGraph example, osgtexture3D.
2*
3*  Permission is hereby granted, free of charge, to any person obtaining a copy
4*  of this software and associated documentation files (the "Software"), to deal
5*  in the Software without restriction, including without limitation the rights
6*  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7*  copies of the Software, and to permit persons to whom the Software is
8*  furnished to do so, subject to the following conditions:
9*
10*  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
11*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
13*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
14*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
15*  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
16*  THE SOFTWARE.
17*/
18
19#include <osg/Node>
20#include <osg/Geometry>
21#include <osg/Notify>
22#include <osg/Texture3D>
23#include <osg/TexGen>
24#include <osg/Geode>
25
26#include <osgDB/Registry>
27#include <osgDB/ReadFile>
28
29#include <osgViewer/Viewer>
30
31#include <iostream>
32
33//
34// A simple demo demonstrating different texturing modes,
35// including using of texture extensions.
36//
37
38
39typedef std::vector< osg::ref_ptr<osg::Image> > ImageList;
40
41
42class MyGraphicsContext {
43    public:
44        MyGraphicsContext()
45        {
46            osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
47            traits->x = 0;
48            traits->y = 0;
49            traits->width = 1;
50            traits->height = 1;
51            traits->windowDecoration = false;
52            traits->doubleBuffer = false;
53            traits->sharedContext = 0;
54            traits->pbuffer = true;
55
56            _gc = osg::GraphicsContext::createGraphicsContext(traits.get());
57
58            if (!_gc)
59            {
60                traits->pbuffer = false;
61                _gc = osg::GraphicsContext::createGraphicsContext(traits.get());
62            }
63
64            if (_gc.valid())
65            {
66                _gc->realize();
67                _gc->makeCurrent();
68            }
69        }
70       
71        bool valid() const { return _gc.valid() && _gc->isRealized(); }
72       
73    private:
74        osg::ref_ptr<osg::GraphicsContext> _gc;
75};
76
77
78osg::StateSet* createState()
79{
80    MyGraphicsContext gc;
81    if (!gc.valid())
82    {
83        osg::notify(osg::NOTICE)<<"Unable to create the graphics context required to build 3d image."<<std::endl;
84        return 0;
85    }
86
87    // read 4 2d images
88    osg::ref_ptr<osg::Image> image_0 = osgDB::readImageFile("Images/lz.rgb");
89    osg::ref_ptr<osg::Image> image_1 = osgDB::readImageFile("Images/reflect.rgb");
90    osg::ref_ptr<osg::Image> image_2 = osgDB::readImageFile("Images/tank.rgb");
91    osg::ref_ptr<osg::Image> image_3 = osgDB::readImageFile("Images/skymap.jpg");
92
93    if (!image_0 || !image_1 || !image_2 || !image_3)
94    {
95        std::cout << "Warning: could not open files."<<std::endl;
96        return new osg::StateSet;
97    }
98
99    if (image_0->getPixelFormat()!=image_1->getPixelFormat() || image_0->getPixelFormat()!=image_2->getPixelFormat() || image_0->getPixelFormat()!=image_3->getPixelFormat())
100    {
101        std::cout << "Warning: image pixel formats not compatible."<<std::endl;
102        return new osg::StateSet;
103    }
104
105    // get max 3D texture size
106    GLint textureSize = osg::Texture3D::getExtensions(0,true)->maxTexture3DSize();
107    if (textureSize > 256)
108        textureSize = 256;
109
110    // scale them all to the same size.
111    image_0->scaleImage(textureSize,textureSize,1);
112    image_1->scaleImage(textureSize,textureSize,1);
113    image_2->scaleImage(textureSize,textureSize,1);
114    image_3->scaleImage(textureSize,textureSize,1);
115
116
117    // then allocated a 3d image to use for texturing.
118    osg::Image* image_3d = new osg::Image;
119    image_3d->allocateImage(textureSize,textureSize,4,
120                            image_0->getPixelFormat(),image_0->getDataType());
121
122    // copy the 2d images into the 3d image.
123    image_3d->copySubImage(0,0,0,image_0.get());
124    image_3d->copySubImage(0,0,1,image_1.get());
125    image_3d->copySubImage(0,0,2,image_2.get());
126    image_3d->copySubImage(0,0,3,image_3.get());
127
128    image_3d->setInternalTextureFormat(image_0->getInternalTextureFormat());       
129
130    // set up the 3d texture itself,
131    // note, well set the filtering up so that mip mapping is disabled,
132    // gluBuild3DMipsmaps doesn't do a very good job of handled the
133    // inbalanced dimensions of the 256x256x4 texture.
134    osg::Texture3D* texture3D = new osg::Texture3D;
135    texture3D->setFilter(osg::Texture3D::MIN_FILTER,osg::Texture3D::LINEAR);
136    texture3D->setFilter(osg::Texture3D::MAG_FILTER,osg::Texture3D::LINEAR);
137    texture3D->setWrap(osg::Texture3D::WRAP_R,osg::Texture3D::REPEAT);
138    texture3D->setImage(image_3d);
139
140
141    // create a texgen to generate a R texture coordinate, the geometry
142    // itself will supply the S & T texture coordinates.
143    // in the animateStateSet callback well alter this R value to
144    // move the texture through the 3d texture, 3d texture filtering
145    // will do the blending for us.
146    osg::TexGen* texgen = new osg::TexGen;
147    texgen->setMode(osg::TexGen::OBJECT_LINEAR);
148    texgen->setPlane(osg::TexGen::R, osg::Plane(0.0f,0.0f,0.0f,0.2f));
149
150    // create the StateSet to store the texture data
151    osg::StateSet* stateset = new osg::StateSet;
152    stateset->setTextureMode(0,GL_TEXTURE_GEN_R,osg::StateAttribute::ON);
153    stateset->setTextureAttribute(0,texgen);
154    stateset->setTextureAttributeAndModes(0,texture3D,osg::StateAttribute::ON);
155
156    return stateset;
157}
158
159
160class UpdateStateCallback : public osg::NodeCallback
161{
162    public:
163        UpdateStateCallback() {}
164       
165        void animateState(osg::StateSet* stateset)
166        {
167            // here we simply get any existing texgen, and then increment its
168            // plane, pushing the R coordinate through the texture.
169            osg::StateAttribute* attribute = stateset->getTextureAttribute(0,osg::StateAttribute::TEXGEN);
170            osg::TexGen* texgen = dynamic_cast<osg::TexGen*>(attribute);
171            if (texgen)
172            {
173                texgen->getPlane(osg::TexGen::R)[3] += 0.001f;
174            }
175
176        }
177
178        virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
179        {
180
181            osg::StateSet* stateset = node->getStateSet();
182            if (stateset)
183            {
184                // we have an exisitng stateset, so lets animate it.
185                animateState(stateset);
186            }
187
188            // note, callback is repsonsible for scenegraph traversal so
189            // should always include call the traverse(node,nv) to ensure
190            // that the rest of cullbacks and the scene graph are traversed.
191            traverse(node,nv);
192        }     
193};
194
195/** create 2,2 square with center at 0,0,0 and aligned along the XZ plan */
196osg::Drawable* createSquare(float textureCoordMax=1.0f)
197{
198    // set up the Geometry.
199    osg::Geometry* geom = new osg::Geometry;
200
201    osg::Vec3Array* coords = new osg::Vec3Array(4);
202    (*coords)[0].set(-1.0f,0.0f,1.0f);
203    (*coords)[1].set(-1.0f,0.0f,-1.0f);
204    (*coords)[2].set(1.0f,0.0f,-1.0f);
205    (*coords)[3].set(1.0f,0.0f,1.0f);
206    geom->setVertexArray(coords);
207
208    osg::Vec3Array* norms = new osg::Vec3Array(1);
209    (*norms)[0].set(0.0f,-1.0f,0.0f);
210    geom->setNormalArray(norms);
211    geom->setNormalBinding(osg::Geometry::BIND_OVERALL);
212
213    osg::Vec2Array* tcoords = new osg::Vec2Array(4);
214    (*tcoords)[0].set(0.0f,textureCoordMax);
215    (*tcoords)[1].set(0.0f,0.0f);
216    (*tcoords)[2].set(textureCoordMax,0.0f);
217    (*tcoords)[3].set(textureCoordMax,textureCoordMax);
218    geom->setTexCoordArray(0,tcoords);
219   
220    geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4));
221
222    return geom;
223}
224
225osg::Node* createModel()
226{
227
228    // create the geometry of the model, just a simple 2d quad right now.   
229    osg::Geode* geode = new osg::Geode;
230    geode->addDrawable(createSquare());
231
232    // normally we'd create the stateset's to contain all the textures
233    // etc here, but, the above technique uses osg::Image::scaleImage and
234    // osg::Image::copySubImage() which are implemented with OpenGL utility
235    // library, which unfortunately can't be used until we have a valid
236    // OpenGL context, and at this point in initilialization we don't have
237    // a valid OpenGL context, so we have to delay creation of state until
238    // there is a valid OpenGL context.  I'll manage this by using an
239    // app callback which will create the state during the first traversal.
240    // A bit hacky, and my plan is to reimplement the osg::scaleImage and
241    // osg::Image::copySubImage() without using GLU which will get round
242    // this current limitation.
243    geode->setUpdateCallback(new UpdateStateCallback());
244    geode->setStateSet(createState());
245   
246    return geode;
247
248}
249
250
251int main(int , char **)
252{
253    // construct the viewer.
254    osgViewer::Viewer viewer;
255
256    // create a model from the images and pass it to the viewer.
257    viewer.setSceneData(createModel());
258
259    return viewer.run();
260}
Note: See TracBrowser for help on using the browser.