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

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