root/OpenSceneGraph/trunk/examples/osgprerender/osgprerender.cpp @ 4713

Revision 4713, 17.2 kB (checked in by robert, 8 years ago)

Added the support in AnimationPathCallback? for taking a pivot, axis and rotation rate
paramters in its constructor to allow it to be used to create rotations around a point.
This provides the same interface and functionality as osgUtil::TransformCallback? but
has the advantage and AnimationPathCallback? is fully supported by the .osg and .ive file formats.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1#include <osg/GLExtensions>
2#include <osg/Node>
3#include <osg/Geometry>
4#include <osg/Notify>
5#include <osg/MatrixTransform>
6#include <osg/Texture2D>
7#include <osg/TextureRectangle>
8#include <osg/Stencil>
9#include <osg/ColorMask>
10#include <osg/Depth>
11#include <osg/Billboard>
12#include <osg/Material>
13
14#include <osgGA/TrackballManipulator>
15#include <osgGA/FlightManipulator>
16#include <osgGA/DriveManipulator>
17
18#include <osgUtil/SmoothingVisitor>
19
20#include <osgDB/Registry>
21#include <osgDB/ReadFile>
22
23#include <osgProducer/Viewer>
24
25
26// call back which cretes a deformation field to oscilate the model.
27class MyGeometryCallback :
28    public osg::Drawable::UpdateCallback,
29    public osg::Drawable::AttributeFunctor
30{
31    public:
32   
33        MyGeometryCallback(const osg::Vec3& o,
34                           const osg::Vec3& x,const osg::Vec3& y,const osg::Vec3& z,
35                           double period,double xphase,double amplitude):
36            _firstCall(true),
37            _startTime(0.0),
38            _time(0.0),
39            _period(period),
40            _xphase(xphase),
41            _amplitude(amplitude),
42            _origin(o),
43            _xAxis(x),
44            _yAxis(y),
45            _zAxis(z) {}
46   
47        virtual void update(osg::NodeVisitor* nv,osg::Drawable* drawable)
48        {
49            const osg::FrameStamp* fs = nv->getFrameStamp();
50            double referenceTime = fs->getReferenceTime();
51            if (_firstCall)
52            {
53                _firstCall = false;
54                _startTime = referenceTime;
55            }
56           
57            _time = referenceTime-_startTime;
58           
59            drawable->accept(*this);
60            drawable->dirtyBound();
61           
62            osg::Geometry* geometry = dynamic_cast<osg::Geometry*>(drawable);
63            if (geometry)
64            {
65                osgUtil::SmoothingVisitor::smooth(*geometry);
66            }
67           
68        }
69       
70        virtual void apply(osg::Drawable::AttributeType type,unsigned int count,osg::Vec3* begin)
71        {
72            if (type == osg::Drawable::VERTICES)
73            {
74                const float TwoPI=2.0f*osg::PI;
75                const float phase = -_time/_period;
76               
77                osg::Vec3* end = begin+count;
78                for (osg::Vec3* itr=begin;itr<end;++itr)
79                {
80                    osg::Vec3 dv(*itr-_origin);
81                    osg::Vec3 local(dv*_xAxis,dv*_yAxis,dv*_zAxis);
82                   
83                    local.z() = local.x()*_amplitude*
84                                sinf(TwoPI*(phase+local.x()*_xphase));
85                   
86                    (*itr) = _origin +
87                             _xAxis*local.x()+
88                             _yAxis*local.y()+
89                             _zAxis*local.z();
90                }
91            }
92        }
93
94        bool    _firstCall;
95
96        double  _startTime;
97        double  _time;
98       
99        double  _period;
100        double  _xphase;
101        float   _amplitude;
102
103        osg::Vec3   _origin;
104        osg::Vec3   _xAxis;
105        osg::Vec3   _yAxis;
106        osg::Vec3   _zAxis;
107       
108};
109
110struct MyCameraPostDrawCallback : public osg::CameraNode::DrawCallback
111{
112    MyCameraPostDrawCallback(osg::Image* image):
113        _image(image)
114    {
115    }
116
117    virtual void operator () (const osg::CameraNode& /*camera*/) const
118    {
119        if (_image && _image->getPixelFormat()==GL_RGBA && _image->getDataType()==GL_UNSIGNED_BYTE)
120        {
121            // we'll pick out the center 1/2 of the whole image,
122            int column_start = _image->s()/4;
123            int column_end = 3*column_start;
124           
125            int row_start = _image->t()/4;
126            int row_end = 3*row_start;
127           
128
129            // and then invert these pixels
130            for(int r=row_start; r<row_end; ++r)
131            {
132                unsigned char* data = _image->data(column_start, r);
133                for(int c=column_start; c<column_end; ++c)
134                {
135                    (*data) = 255-(*data); ++data;
136                    (*data) = 255-(*data); ++data;
137                    (*data) = 255-(*data); ++data;
138                    (*data) = 255; ++data;
139                }
140            }
141
142
143            // dirty the image (increments the modified count) so that any textures
144            // using the image can be informed that they need to update.
145            _image->dirty();
146        }
147        else if (_image && _image->getPixelFormat()==GL_RGBA && _image->getDataType()==GL_FLOAT)
148        {
149            // we'll pick out the center 1/2 of the whole image,
150            int column_start = _image->s()/4;
151            int column_end = 3*column_start;
152           
153            int row_start = _image->t()/4;
154            int row_end = 3*row_start;
155           
156            // and then invert these pixels
157            for(int r=row_start; r<row_end; ++r)
158            {
159                float* data = (float*)_image->data(column_start, r);
160                for(int c=column_start; c<column_end; ++c)
161                {
162                    (*data) = 1.0f-(*data); ++data;
163                    (*data) = 1.0f-(*data); ++data;
164                    (*data) = 1.0f-(*data); ++data;
165                    (*data) = 1.0f; ++data;
166                }
167            }
168
169            // dirty the image (increments the modified count) so that any textures
170            // using the image can be informed that they need to update.
171            _image->dirty();
172        }
173       
174    }
175   
176    osg::Image* _image;
177};
178
179
180osg::Node* createPreRenderSubGraph(osg::Node* subgraph, unsigned tex_width, unsigned tex_height, osg::CameraNode::RenderTargetImplementation renderImplementation, bool useImage, bool useTextureRectangle, bool useHDR)
181{
182    if (!subgraph) return 0;
183
184    // create a group to contain the flag and the pre rendering camera.
185    osg::Group* parent = new osg::Group;
186
187    // texture to render to and to use for rendering of flag.
188    osg::Texture* texture = 0;
189    if (useTextureRectangle)
190    {
191        osg::TextureRectangle* textureRect = new osg::TextureRectangle;
192        textureRect->setTextureSize(tex_width, tex_height);
193        textureRect->setInternalFormat(GL_RGBA);
194        textureRect->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
195        textureRect->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
196       
197        texture = textureRect;
198    }
199    else
200    {
201        osg::Texture2D* texture2D = new osg::Texture2D;
202        texture2D->setTextureSize(tex_width, tex_height);
203        texture2D->setInternalFormat(GL_RGBA);
204        texture2D->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
205        texture2D->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
206       
207        texture = texture2D;
208    }
209
210    if (useHDR)
211    {
212        texture->setInternalFormat(GL_RGBA16F_ARB);
213        texture->setSourceFormat(GL_RGBA);
214        texture->setSourceType(GL_FLOAT);
215    }
216
217    // first create the geometry of the flag of which to view.
218    {
219        // create the to visualize.
220        osg::Geometry* polyGeom = new osg::Geometry();
221
222        polyGeom->setSupportsDisplayList(false);
223
224        osg::Vec3 origin(0.0f,0.0f,0.0f);
225        osg::Vec3 xAxis(1.0f,0.0f,0.0f);
226        osg::Vec3 yAxis(0.0f,0.0f,1.0f);
227        osg::Vec3 zAxis(0.0f,-1.0f,0.0f);
228        float height = 100.0f;
229        float width = 200.0f;
230        int noSteps = 20;
231
232        osg::Vec3Array* vertices = new osg::Vec3Array;
233        osg::Vec3 bottom = origin;
234        osg::Vec3 top = origin; top.z()+= height;
235        osg::Vec3 dv = xAxis*(width/((float)(noSteps-1)));
236
237        osg::Vec2Array* texcoords = new osg::Vec2Array;
238       
239        // note, when we use TextureRectangle we have to scale the tex coords up to compensate.
240        osg::Vec2 bottom_texcoord(0.0f,0.0f);
241        osg::Vec2 top_texcoord(0.0f, useTextureRectangle ? tex_height : 1.0f);
242        osg::Vec2 dv_texcoord((useTextureRectangle ? tex_width : 1.0f)/(float)(noSteps-1),0.0f);
243
244        for(int i=0;i<noSteps;++i)
245        {
246            vertices->push_back(top);
247            vertices->push_back(bottom);
248            top+=dv;
249            bottom+=dv;
250
251            texcoords->push_back(top_texcoord);
252            texcoords->push_back(bottom_texcoord);
253            top_texcoord+=dv_texcoord;
254            bottom_texcoord+=dv_texcoord;
255        }
256
257
258        // pass the created vertex array to the points geometry object.
259        polyGeom->setVertexArray(vertices);
260
261        polyGeom->setTexCoordArray(0,texcoords);
262
263
264        osg::Vec4Array* colors = new osg::Vec4Array;
265        colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
266        polyGeom->setColorArray(colors);
267        polyGeom->setColorBinding(osg::Geometry::BIND_OVERALL);
268
269        polyGeom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUAD_STRIP,0,vertices->size()));
270
271        // new we need to add the texture to the Drawable, we do so by creating a
272        // StateSet to contain the Texture StateAttribute.
273        osg::StateSet* stateset = new osg::StateSet;
274
275        stateset->setTextureAttributeAndModes(0, texture,osg::StateAttribute::ON);
276
277        polyGeom->setStateSet(stateset);
278
279        polyGeom->setUpdateCallback(new MyGeometryCallback(origin,xAxis,yAxis,zAxis,1.0,1.0/width,0.2f));
280
281        osg::Geode* geode = new osg::Geode();
282        geode->addDrawable(polyGeom);
283       
284        parent->addChild(geode);
285
286    }
287
288
289    // then create the camera node to do the render to texture
290    {   
291        osg::CameraNode* camera = new osg::CameraNode;
292
293        // set up the background color and clear mask.
294        camera->setClearColor(osg::Vec4(0.1f,0.1f,0.3f,1.0f));
295        camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
296
297        const osg::BoundingSphere& bs = subgraph->getBound();
298        if (!bs.valid())
299        {
300            return subgraph;
301        }
302
303        float znear = 1.0f*bs.radius();
304        float zfar  = 3.0f*bs.radius();
305
306        // 2:1 aspect ratio as per flag geomtry below.
307        float proj_top   = 0.25f*znear;
308        float proj_right = 0.5f*znear;
309
310        znear *= 0.9f;
311        zfar *= 1.1f;
312
313        // set up projection.
314        camera->setProjectionMatrixAsFrustum(-proj_right,proj_right,-proj_top,proj_top,znear,zfar);
315
316        // set view
317        camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
318        camera->setViewMatrixAsLookAt(bs.center()-osg::Vec3(0.0f,2.0f,0.0f)*bs.radius(),bs.center(),osg::Vec3(0.0f,0.0f,1.0f));
319
320        // set viewport
321        camera->setViewport(0,0,tex_width,tex_height);
322
323        // set the camera to render before the main camera.
324        camera->setRenderOrder(osg::CameraNode::PRE_RENDER);
325
326        // tell the camera to use OpenGL frame buffer object where supported.
327        camera->setRenderTargetImplementation(renderImplementation);
328
329       
330        if (useImage)
331        {
332            osg::Image* image = new osg::Image;
333            //image->allocateImage(tex_width, tex_height, 1, GL_RGBA, GL_UNSIGNED_BYTE);
334            image->allocateImage(tex_width, tex_height, 1, GL_RGBA, GL_FLOAT);
335
336            // attach the image so its copied on each frame.
337            camera->attach(osg::CameraNode::COLOR_BUFFER, image);
338           
339            camera->setPostDrawCallback(new MyCameraPostDrawCallback(image));
340           
341            // Rather than attach the texture directly to illustrate the texture's ability to
342            // detect an image update and to subload the image onto the texture.  You needn't
343            // do this when using an Image for copying to, as a seperate camera->attach(..)
344            // would suffice as well, but we'll do it the long way round here just for demonstation
345            // purposes (long way round meaning we'll need to copy image to main memory, then
346            // copy it back to the graphics card to the texture in one frame).
347            // The long way round allows us to mannually modify the copied image via the callback
348            // and then let this modified image by reloaded back.
349            texture->setImage(0, image);
350        }
351        else
352        {
353            // attach the texture and use it as the color buffer.
354            camera->attach(osg::CameraNode::COLOR_BUFFER, texture);
355        }
356
357
358        // add subgraph to render
359        camera->addChild(subgraph);
360
361        parent->addChild(camera);
362
363    }   
364
365    return parent;
366}
367
368int main( int argc, char **argv )
369{
370    // use an ArgumentParser object to manage the program arguments.
371    osg::ArgumentParser arguments(&argc,argv);
372
373    // set up the usage document, in case we need to print out how to use this program.
374    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates pre rendering of scene to a texture, and then apply this texture to geometry.");
375    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
376    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
377    arguments.getApplicationUsage()->addCommandLineOption("--fbo","Use Frame Buffer Object for render to texture, where supported.");
378    arguments.getApplicationUsage()->addCommandLineOption("--fb","Use FrameBuffer for render to texture.");
379    arguments.getApplicationUsage()->addCommandLineOption("--pbuffer","Use Pixel Buffer for render to texture, where supported.");
380    arguments.getApplicationUsage()->addCommandLineOption("--window","Use a seperate Window for render to texture.");
381    arguments.getApplicationUsage()->addCommandLineOption("--width","Set the width of the render to texture.");
382    arguments.getApplicationUsage()->addCommandLineOption("--height","Set the height of the render to texture.");
383    arguments.getApplicationUsage()->addCommandLineOption("--image","Render to an image, then apply a post draw callback to it, and use this image to update a texture.");
384    arguments.getApplicationUsage()->addCommandLineOption("--texture-rectangle","Use osg::TextureRectangle for doing the render to texure to.");
385   
386    // construct the viewer.
387    osgProducer::Viewer viewer(arguments);
388
389    // set up the value with sensible default event handlers.
390    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
391
392    // get details on keyboard and mouse bindings used by the viewer.
393    viewer.getUsage(*arguments.getApplicationUsage());
394
395    // if user request help write it out to cout.
396    if (arguments.read("-h") || arguments.read("--help"))
397    {
398        arguments.getApplicationUsage()->write(std::cout);
399        return 1;
400    }
401
402    unsigned tex_width = 1024;
403    unsigned tex_height = 512;
404    while (arguments.read("--width", tex_width)) {}
405    while (arguments.read("--height", tex_height)) {}
406
407    osg::CameraNode::RenderTargetImplementation renderImplementation = osg::CameraNode::FRAME_BUFFER_OBJECT;
408   
409    while (arguments.read("--fbo")) { renderImplementation = osg::CameraNode::FRAME_BUFFER_OBJECT; }
410    while (arguments.read("--pbuffer")) { renderImplementation = osg::CameraNode::PIXEL_BUFFER; }
411    while (arguments.read("--pbuffer-rtt")) { renderImplementation = osg::CameraNode::PIXEL_BUFFER_RTT; }
412    while (arguments.read("--fb")) { renderImplementation = osg::CameraNode::FRAME_BUFFER; }
413    while (arguments.read("--window")) { renderImplementation = osg::CameraNode::SEPERATE_WINDOW; }
414
415    bool useImage = false;
416    while (arguments.read("--image")) { useImage = true; }
417   
418    bool useTextureRectangle = false;
419    while (arguments.read("--texture-rectangle")) { useTextureRectangle = true; }
420   
421    bool useHDR = false;
422    while (arguments.read("--hdr")) { useHDR = true; }
423
424    // any option left unread are converted into errors to write out later.
425    arguments.reportRemainingOptionsAsUnrecognized();
426
427    // report any errors if they have occured when parsing the program aguments.
428    if (arguments.errors())
429    {
430        arguments.writeErrorMessages(std::cout);
431        return 1;
432    }
433   
434    if (arguments.argc()<=1)
435    {
436        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
437        return 1;
438    }
439
440   
441    // load the nodes from the commandline arguments.
442    osg::Node* loadedModel = osgDB::readNodeFiles(arguments);
443    if (!loadedModel)
444    {
445        return 1;
446    }
447   
448    // create a transform to spin the model.
449    osg::MatrixTransform* loadedModelTransform = new osg::MatrixTransform;
450    loadedModelTransform->addChild(loadedModel);
451
452    osg::NodeCallback* nc = new osg::AnimationPathCallback(loadedModelTransform->getBound().center(),osg::Vec3(0.0f,0.0f,1.0f),osg::inDegrees(45.0f));
453    loadedModelTransform->setUpdateCallback(nc);
454
455    osg::Group* rootNode = new osg::Group();
456    rootNode->addChild(createPreRenderSubGraph(loadedModelTransform,tex_width,tex_height, renderImplementation, useImage, useTextureRectangle, useHDR));
457
458
459    // add model to the viewer.
460    viewer.setSceneData( rootNode );
461
462
463    // create the windows and run the threads.
464    viewer.realize();
465
466    while( !viewer.done() )
467    {
468        // wait for all cull and draw threads to complete.
469        viewer.sync();
470
471        // update the scene by traversing it with the the update visitor which will
472        // call all node update callbacks and animations.
473        viewer.update();
474         
475        // fire off the cull and draw traversals of the scene.
476        viewer.frame();
477       
478    }
479   
480    // wait for all cull and draw threads to complete before exit.
481    viewer.sync();
482
483    return 0;
484}
Note: See TracBrowser for help on using the browser.