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

Revision 4649, 15.9 kB (checked in by robert, 9 years ago)

Added an image negation callback to the render to image. Added commandline docs
for the new --image and --texture-rectangle options.

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