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

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

From Brad Colbert/Robert Osfield: added s/getSourceFormat and s/getSourceType to osg::Texture
along with support for this Texture1D, 2D, 3D, TextureCubeMap? and TextureRectangle?. The
new SourceFormat? and SourceType? parameters are only used when no osg::Image is assigned to
an osg::Texture, and main use is for render to texture effects.

Added support for --hdr option in osgprerender, which utilises the new Texture::setSourceFormat/Type() methods.

  • 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        else if (_image && _image->getPixelFormat()==GL_RGBA && _image->getDataType()==GL_FLOAT)
149        {
150            // we'll pick out the center 1/2 of the whole image,
151            int column_start = _image->s()/4;
152            int column_end = 3*column_start;
153           
154            int row_start = _image->t()/4;
155            int row_end = 3*row_start;
156           
157            // and then invert these pixels
158            for(int r=row_start; r<row_end; ++r)
159            {
160                float* data = (float*)_image->data(column_start, r);
161                for(int c=column_start; c<column_end; ++c)
162                {
163                    (*data) = 1.0f-(*data); ++data;
164                    (*data) = 1.0f-(*data); ++data;
165                    (*data) = 1.0f-(*data); ++data;
166                    (*data) = 1.0f; ++data;
167                }
168            }
169
170            // dirty the image (increments the modified count) so that any textures
171            // using the image can be informed that they need to update.
172            _image->dirty();
173        }
174       
175    }
176   
177    osg::Image* _image;
178};
179
180
181osg::Node* createPreRenderSubGraph(osg::Node* subgraph, unsigned tex_width, unsigned tex_height, osg::CameraNode::RenderTargetImplementation renderImplementation, bool useImage, bool useTextureRectangle, bool useHDR)
182{
183    if (!subgraph) return 0;
184
185    // create a group to contain the flag and the pre rendering camera.
186    osg::Group* parent = new osg::Group;
187
188    // texture to render to and to use for rendering of flag.
189    osg::Texture* texture = 0;
190    if (useTextureRectangle)
191    {
192        osg::TextureRectangle* textureRect = new osg::TextureRectangle;
193        textureRect->setTextureSize(tex_width, tex_height);
194        textureRect->setInternalFormat(GL_RGBA);
195        textureRect->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
196        textureRect->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
197       
198        texture = textureRect;
199    }
200    else
201    {
202        osg::Texture2D* texture2D = new osg::Texture2D;
203        texture2D->setTextureSize(tex_width, tex_height);
204        texture2D->setInternalFormat(GL_RGBA);
205        texture2D->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
206        texture2D->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
207       
208        texture = texture2D;
209    }
210
211    if (useHDR)
212    {
213        texture->setInternalFormat(GL_RGBA16F_ARB);
214        texture->setSourceFormat(GL_RGBA);
215        texture->setSourceType(GL_FLOAT);
216    }
217
218    // first create the geometry of the flag of which to view.
219    {
220        // create the to visualize.
221        osg::Geometry* polyGeom = new osg::Geometry();
222
223        polyGeom->setSupportsDisplayList(false);
224
225        osg::Vec3 origin(0.0f,0.0f,0.0f);
226        osg::Vec3 xAxis(1.0f,0.0f,0.0f);
227        osg::Vec3 yAxis(0.0f,0.0f,1.0f);
228        osg::Vec3 zAxis(0.0f,-1.0f,0.0f);
229        float height = 100.0f;
230        float width = 200.0f;
231        int noSteps = 20;
232
233        osg::Vec3Array* vertices = new osg::Vec3Array;
234        osg::Vec3 bottom = origin;
235        osg::Vec3 top = origin; top.z()+= height;
236        osg::Vec3 dv = xAxis*(width/((float)(noSteps-1)));
237
238        osg::Vec2Array* texcoords = new osg::Vec2Array;
239       
240        // note, when we use TextureRectangle we have to scale the tex coords up to compensate.
241        osg::Vec2 bottom_texcoord(0.0f,0.0f);
242        osg::Vec2 top_texcoord(0.0f, useTextureRectangle ? tex_height : 1.0f);
243        osg::Vec2 dv_texcoord((useTextureRectangle ? tex_width : 1.0f)/(float)(noSteps-1),0.0f);
244
245        for(int i=0;i<noSteps;++i)
246        {
247            vertices->push_back(top);
248            vertices->push_back(bottom);
249            top+=dv;
250            bottom+=dv;
251
252            texcoords->push_back(top_texcoord);
253            texcoords->push_back(bottom_texcoord);
254            top_texcoord+=dv_texcoord;
255            bottom_texcoord+=dv_texcoord;
256        }
257
258
259        // pass the created vertex array to the points geometry object.
260        polyGeom->setVertexArray(vertices);
261
262        polyGeom->setTexCoordArray(0,texcoords);
263
264
265        osg::Vec4Array* colors = new osg::Vec4Array;
266        colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
267        polyGeom->setColorArray(colors);
268        polyGeom->setColorBinding(osg::Geometry::BIND_OVERALL);
269
270        polyGeom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUAD_STRIP,0,vertices->size()));
271
272        // new we need to add the texture to the Drawable, we do so by creating a
273        // StateSet to contain the Texture StateAttribute.
274        osg::StateSet* stateset = new osg::StateSet;
275
276        stateset->setTextureAttributeAndModes(0, texture,osg::StateAttribute::ON);
277
278        polyGeom->setStateSet(stateset);
279
280        polyGeom->setUpdateCallback(new MyGeometryCallback(origin,xAxis,yAxis,zAxis,1.0,1.0/width,0.2f));
281
282        osg::Geode* geode = new osg::Geode();
283        geode->addDrawable(polyGeom);
284       
285        parent->addChild(geode);
286
287    }
288
289
290    // then create the camera node to do the render to texture
291    {   
292        osg::CameraNode* camera = new osg::CameraNode;
293
294        // set up the background color and clear mask.
295        camera->setClearColor(osg::Vec4(0.1f,0.1f,0.3f,1.0f));
296        camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
297
298        const osg::BoundingSphere& bs = subgraph->getBound();
299        if (!bs.valid())
300        {
301            return subgraph;
302        }
303
304        float znear = 1.0f*bs.radius();
305        float zfar  = 3.0f*bs.radius();
306
307        // 2:1 aspect ratio as per flag geomtry below.
308        float proj_top   = 0.25f*znear;
309        float proj_right = 0.5f*znear;
310
311        znear *= 0.9f;
312        zfar *= 1.1f;
313
314        // set up projection.
315        camera->setProjectionMatrixAsFrustum(-proj_right,proj_right,-proj_top,proj_top,znear,zfar);
316
317        // set view
318        camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
319        camera->setViewMatrixAsLookAt(bs.center()-osg::Vec3(0.0f,2.0f,0.0f)*bs.radius(),bs.center(),osg::Vec3(0.0f,0.0f,1.0f));
320
321        // set viewport
322        camera->setViewport(0,0,tex_width,tex_height);
323
324        // set the camera to render before the main camera.
325        camera->setRenderOrder(osg::CameraNode::PRE_RENDER);
326
327        // tell the camera to use OpenGL frame buffer object where supported.
328        camera->setRenderTargetImplementation(renderImplementation);
329
330       
331        if (useImage)
332        {
333            osg::Image* image = new osg::Image;
334            //image->allocateImage(tex_width, tex_height, 1, GL_RGBA, GL_UNSIGNED_BYTE);
335            image->allocateImage(tex_width, tex_height, 1, GL_RGBA, GL_FLOAT);
336
337            // attach the image so its copied on each frame.
338            camera->attach(osg::CameraNode::COLOR_BUFFER, image);
339           
340            camera->setPostDrawCallback(new MyCameraPostDrawCallback(image));
341           
342            // Rather than attach the texture directly to illustrate the texture's ability to
343            // detect an image update and to subload the image onto the texture.  You needn't
344            // do this when using an Image for copying to, as a seperate camera->attach(..)
345            // would suffice as well, but we'll do it the long way round here just for demonstation
346            // purposes (long way round meaning we'll need to copy image to main memory, then
347            // copy it back to the graphics card to the texture in one frame).
348            // The long way round allows us to mannually modify the copied image via the callback
349            // and then let this modified image by reloaded back.
350            texture->setImage(0, image);
351        }
352        else
353        {
354            // attach the texture and use it as the color buffer.
355            camera->attach(osg::CameraNode::COLOR_BUFFER, texture);
356        }
357
358
359        // add subgraph to render
360        camera->addChild(subgraph);
361
362        parent->addChild(camera);
363
364    }   
365
366    return parent;
367}
368
369int main( int argc, char **argv )
370{
371    // use an ArgumentParser object to manage the program arguments.
372    osg::ArgumentParser arguments(&argc,argv);
373
374    // set up the usage document, in case we need to print out how to use this program.
375    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates pre rendering of scene to a texture, and then apply this texture to geometry.");
376    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
377    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
378    arguments.getApplicationUsage()->addCommandLineOption("--fbo","Use Frame Buffer Object for render to texture, where supported.");
379    arguments.getApplicationUsage()->addCommandLineOption("--fb","Use FrameBuffer for render to texture.");
380    arguments.getApplicationUsage()->addCommandLineOption("--pbuffer","Use Pixel Buffer for render to texture, where supported.");
381    arguments.getApplicationUsage()->addCommandLineOption("--window","Use a seperate Window for render to texture.");
382    arguments.getApplicationUsage()->addCommandLineOption("--width","Set the width of the render to texture.");
383    arguments.getApplicationUsage()->addCommandLineOption("--height","Set the height of the render to texture.");
384    arguments.getApplicationUsage()->addCommandLineOption("--image","Render to an image, then apply a post draw callback to it, and use this image to update a texture.");
385    arguments.getApplicationUsage()->addCommandLineOption("--texture-rectangle","Use osg::TextureRectangle for doing the render to texure to.");
386   
387    // construct the viewer.
388    osgProducer::Viewer viewer(arguments);
389
390    // set up the value with sensible default event handlers.
391    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
392
393    // get details on keyboard and mouse bindings used by the viewer.
394    viewer.getUsage(*arguments.getApplicationUsage());
395
396    // if user request help write it out to cout.
397    if (arguments.read("-h") || arguments.read("--help"))
398    {
399        arguments.getApplicationUsage()->write(std::cout);
400        return 1;
401    }
402
403    unsigned tex_width = 1024;
404    unsigned tex_height = 512;
405    while (arguments.read("--width", tex_width)) {}
406    while (arguments.read("--height", tex_height)) {}
407
408    osg::CameraNode::RenderTargetImplementation renderImplementation = osg::CameraNode::FRAME_BUFFER_OBJECT;
409   
410    while (arguments.read("--fbo")) { renderImplementation = osg::CameraNode::FRAME_BUFFER_OBJECT; }
411    while (arguments.read("--pbuffer")) { renderImplementation = osg::CameraNode::PIXEL_BUFFER; }
412    while (arguments.read("--pbuffer-rtt")) { renderImplementation = osg::CameraNode::PIXEL_BUFFER_RTT; }
413    while (arguments.read("--fb")) { renderImplementation = osg::CameraNode::FRAME_BUFFER; }
414    while (arguments.read("--window")) { renderImplementation = osg::CameraNode::SEPERATE_WINDOW; }
415
416    bool useImage = false;
417    while (arguments.read("--image")) { useImage = true; }
418   
419    bool useTextureRectangle = false;
420    while (arguments.read("--texture-rectangle")) { useTextureRectangle = true; }
421   
422    bool useHDR = false;
423    while (arguments.read("--hdr")) { useHDR = true; }
424
425    // any option left unread are converted into errors to write out later.
426    arguments.reportRemainingOptionsAsUnrecognized();
427
428    // report any errors if they have occured when parsing the program aguments.
429    if (arguments.errors())
430    {
431        arguments.writeErrorMessages(std::cout);
432        return 1;
433    }
434   
435    if (arguments.argc()<=1)
436    {
437        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
438        return 1;
439    }
440
441   
442    // load the nodes from the commandline arguments.
443    osg::Node* loadedModel = osgDB::readNodeFiles(arguments);
444    if (!loadedModel)
445    {
446        return 1;
447    }
448   
449    // create a transform to spin the model.
450    osg::MatrixTransform* loadedModelTransform = new osg::MatrixTransform;
451    loadedModelTransform->addChild(loadedModel);
452
453    osg::NodeCallback* nc = new osgUtil::TransformCallback(loadedModelTransform->getBound().center(),osg::Vec3(0.0f,0.0f,1.0f),osg::inDegrees(45.0f));
454    loadedModelTransform->setUpdateCallback(nc);
455
456    osg::Group* rootNode = new osg::Group();
457    rootNode->addChild(createPreRenderSubGraph(loadedModelTransform,tex_width,tex_height, renderImplementation, useImage, useTextureRectangle, useHDR));
458
459
460    // add model to the viewer.
461    viewer.setSceneData( rootNode );
462
463
464    // create the windows and run the threads.
465    viewer.realize();
466
467    while( !viewer.done() )
468    {
469        // wait for all cull and draw threads to complete.
470        viewer.sync();
471
472        // update the scene by traversing it with the the update visitor which will
473        // call all node update callbacks and animations.
474        viewer.update();
475         
476        // fire off the cull and draw traversals of the scene.
477        viewer.frame();
478       
479    }
480   
481    // wait for all cull and draw threads to complete before exit.
482    viewer.sync();
483
484    return 0;
485}
Note: See TracBrowser for help on using the browser.