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

Revision 4386, 10.2 kB (checked in by robert, 9 years ago)

Cleaned up osghud and osgprerender examples

  • 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/Stencil>
8#include <osg/ColorMask>
9#include <osg/Depth>
10#include <osg/Billboard>
11#include <osg/Material>
12
13#include <osgGA/TrackballManipulator>
14#include <osgGA/FlightManipulator>
15#include <osgGA/DriveManipulator>
16
17#include <osgUtil/TransformCallback>
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
110osg::Node* createPreRenderSubGraph(osg::Node* subgraph)
111{
112    if (!subgraph) return 0;
113 
114    // create the quad to visualize.
115    osg::Geometry* polyGeom = new osg::Geometry();
116
117    polyGeom->setSupportsDisplayList(false);
118
119    osg::Vec3 origin(0.0f,0.0f,0.0f);
120    osg::Vec3 xAxis(1.0f,0.0f,0.0f);
121    osg::Vec3 yAxis(0.0f,0.0f,1.0f);
122    osg::Vec3 zAxis(0.0f,-1.0f,0.0f);
123    float height = 100.0f;
124    float width = 200.0f;
125    int noSteps = 20;
126   
127    osg::Vec3Array* vertices = new osg::Vec3Array;
128    osg::Vec3 bottom = origin;
129    osg::Vec3 top = origin; top.z()+= height;
130    osg::Vec3 dv = xAxis*(width/((float)(noSteps-1)));
131   
132    osg::Vec2Array* texcoords = new osg::Vec2Array;
133    osg::Vec2 bottom_texcoord(0.0f,0.0f);
134    osg::Vec2 top_texcoord(0.0f,1.0f);
135    osg::Vec2 dv_texcoord(1.0f/(float)(noSteps-1),0.0f);
136
137    for(int i=0;i<noSteps;++i)
138    {
139        vertices->push_back(top);
140        vertices->push_back(bottom);
141        top+=dv;
142        bottom+=dv;
143
144        texcoords->push_back(top_texcoord);
145        texcoords->push_back(bottom_texcoord);
146        top_texcoord+=dv_texcoord;
147        bottom_texcoord+=dv_texcoord;
148    }
149   
150
151    // pass the created vertex array to the points geometry object.
152    polyGeom->setVertexArray(vertices);
153   
154    polyGeom->setTexCoordArray(0,texcoords);
155   
156
157    osg::Vec4Array* colors = new osg::Vec4Array;
158    colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
159    polyGeom->setColorArray(colors);
160    polyGeom->setColorBinding(osg::Geometry::BIND_OVERALL);
161
162    polyGeom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUAD_STRIP,0,vertices->size()));
163
164
165
166    unsigned int tex_width = 2048;
167    unsigned int tex_height = 2048;
168
169
170    // new we need to add the texture to the Drawable, we do so by creating a
171    // StateSet to contain the Texture StateAttribute.
172    osg::StateSet* stateset = new osg::StateSet;
173
174    osg::Texture2D* texture = new osg::Texture2D;
175    texture->setTextureSize(tex_width, tex_height);
176    texture->setInternalFormat(GL_RGBA);
177    texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
178    texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
179    stateset->setTextureAttributeAndModes(0, texture,osg::StateAttribute::ON);
180
181    polyGeom->setStateSet(stateset);
182
183    polyGeom->setUpdateCallback(new MyGeometryCallback(origin,xAxis,yAxis,zAxis,1.0,1.0/width,0.2f));
184
185    osg::Geode* geode = new osg::Geode();
186    geode->addDrawable(polyGeom);
187
188
189    osg::CameraNode* camera = new osg::CameraNode;
190   
191    // set up the background color and clear mask.
192    camera->setClearColor(osg::Vec4(0.1f,0.1f,0.3f,1.0f));
193    camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
194
195    const osg::BoundingSphere& bs = subgraph->getBound();
196    if (!bs.valid())
197    {
198        return subgraph;
199    }
200
201    float znear = 1.0f*bs.radius();
202    float zfar  = 3.0f*bs.radius();
203
204    // 2:1 aspect ratio as per flag geomtry below.
205    float proj_top   = 0.25f*znear;
206    float proj_right = 0.5f*znear;
207
208    znear *= 0.9f;
209    zfar *= 1.1f;
210
211    // set up projection.
212    camera->setProjectionMatrixAsFrustum(-proj_right,proj_right,-proj_top,proj_top,znear,zfar);
213
214    // set view
215    camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
216    camera->setViewMatrixAsLookAt(bs.center()+osg::Vec3(0.0f,2.0f,0.0f)*bs.radius(),bs.center(),osg::Vec3(0.0f,0.0f,1.0f));
217
218    // set viewport
219    camera->setViewport(0,0,tex_width,tex_height);
220   
221    camera->getOrCreateStateSet()->setAttribute(camera->getViewport());
222   
223    // set the camera to render before the main camera.
224    camera->setRenderOrder(osg::CameraNode::PRE_RENDER);
225   
226    // tell the camera to use OpenGL frame buffer object where supported.
227    camera->setRenderTargetImplmentation(osg::CameraNode::FRAME_BUFFER_OBJECT);
228   
229    // attach the texture and use it as the color buffer.
230    camera->attach(osg::CameraNode::COLOR_BUFFER, texture);
231
232    // add subgraph to render
233    camera->addChild(subgraph);
234   
235   
236    // create a group to contain the flag and the pre rendering camera.
237    osg::Group* parent = new osg::Group;
238   
239    parent->addChild(camera);
240    parent->addChild(geode);
241
242
243    return parent;
244}
245
246int main( int argc, char **argv )
247{
248    // use an ArgumentParser object to manage the program arguments.
249    osg::ArgumentParser arguments(&argc,argv);
250
251    // set up the usage document, in case we need to print out how to use this program.
252    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates pre rendering of scene to a texture, and then apply this texture to geometry.");
253    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
254    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
255   
256    // construct the viewer.
257    osgProducer::Viewer viewer(arguments);
258
259    // set up the value with sensible default event handlers.
260    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
261
262    // get details on keyboard and mouse bindings used by the viewer.
263    viewer.getUsage(*arguments.getApplicationUsage());
264
265    // if user request help write it out to cout.
266    if (arguments.read("-h") || arguments.read("--help"))
267    {
268        arguments.getApplicationUsage()->write(std::cout);
269        return 1;
270    }
271
272    // any option left unread are converted into errors to write out later.
273    arguments.reportRemainingOptionsAsUnrecognized();
274
275    // report any errors if they have occured when parsing the program aguments.
276    if (arguments.errors())
277    {
278        arguments.writeErrorMessages(std::cout);
279        return 1;
280    }
281   
282    if (arguments.argc()<=1)
283    {
284        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
285        return 1;
286    }
287
288   
289    // load the nodes from the commandline arguments.
290    osg::Node* loadedModel = osgDB::readNodeFiles(arguments);
291    if (!loadedModel)
292    {
293//        write_usage(osg::notify(osg::NOTICE),argv[0]);
294        return 1;
295    }
296   
297    // create a transform to spin the model.
298    osg::MatrixTransform* loadedModelTransform = new osg::MatrixTransform;
299    loadedModelTransform->addChild(loadedModel);
300
301    osg::NodeCallback* nc = new osgUtil::TransformCallback(loadedModelTransform->getBound().center(),osg::Vec3(0.0f,0.0f,1.0f),osg::inDegrees(45.0f));
302    loadedModelTransform->setUpdateCallback(nc);
303
304    osg::Group* rootNode = new osg::Group();
305//    rootNode->addChild(loadedModelTransform);
306    rootNode->addChild(createPreRenderSubGraph(loadedModelTransform));
307
308
309    // add model to the viewer.
310    viewer.setSceneData( rootNode );
311
312
313    // create the windows and run the threads.
314    viewer.realize();
315
316    while( !viewer.done() )
317    {
318        // wait for all cull and draw threads to complete.
319        viewer.sync();
320
321        // update the scene by traversing it with the the update visitor which will
322        // call all node update callbacks and animations.
323        viewer.update();
324         
325        // fire off the cull and draw traversals of the scene.
326        viewer.frame();
327       
328    }
329   
330    // wait for all cull and draw threads to complete before exit.
331    viewer.sync();
332
333    return 0;
334}
Note: See TracBrowser for help on using the browser.