root/OpenSceneGraph/trunk/examples/osgcamera/osgcamera.cpp @ 4805

Revision 4805, 13.5 kB (checked in by robert, 9 years ago)

Replaced tabs with spaces in examples.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1// C++ source file - (C) 2003 Robert Osfield, released under the OSGPL.
2//
3// Simple example of use of Producer::RenderSurface to create an OpenGL
4// graphics window, and OSG for rendering.
5
6#include <osg/Timer>
7#include <osg/GraphicsContext>
8#include <osg/GraphicsThread>
9
10#include <osgUtil/UpdateVisitor>
11#include <osgUtil/CullVisitor>
12#include <osgUtil/SceneView>
13#include <osgUtil/GLObjectsVisitor>
14
15#include <osgDB/ReadFile>
16#include <osgDB/DynamicLibrary>
17#include <osgDB/Registry>
18
19#include <map>
20#include <list>
21#include <iostream>
22
23
24
25////////////////////////////////////////////////////////////////////////////////
26//
27//
28//  **************** THIS IS AN EXPERIMENTAL IMPLEMENTATION ***************
29//  ************************** PLEASE DO NOT COPY  ************************
30//
31//
32///////////////////////////////////////////////////////////////////////////////
33
34
35// Compile operation, that compile OpenGL objects.
36struct CompileOperation : public osg::GraphicsThread::Operation
37{
38    CompileOperation(osg::Node* scene):
39        osg::GraphicsThread::Operation("Compile",false),
40        _scene(scene)
41    {
42    }
43   
44    virtual void operator () (osg::GraphicsContext* context)
45    {
46        std::cout<<"Compile"<<std::endl;
47   
48        osgUtil::GLObjectsVisitor compileVisitor;
49        compileVisitor.setState(context->getState());
50
51        // do the compile traversal
52        _scene->accept(compileVisitor);
53    }
54   
55    osg::ref_ptr<osg::Node> _scene;
56};
57
58// Cull operation, that does a cull on the scene graph.
59struct CullOperation : public osg::GraphicsThread::Operation
60{
61    CullOperation(osgUtil::SceneView* sceneView):
62        osg::GraphicsThread::Operation("Cull",true),
63        _sceneView(sceneView)
64    {
65    }
66   
67    virtual void operator () (osg::GraphicsContext* context)
68    {
69        _sceneView->setState(context->getState());
70        _sceneView->cull();
71    }
72   
73    osg::ref_ptr<osgUtil::SceneView> _sceneView;
74};
75
76// Draw operation, that does a draw on the scene graph.
77struct DrawOperation : public osg::GraphicsThread::Operation
78{
79    DrawOperation(osgUtil::SceneView* sceneView):
80        osg::GraphicsThread::Operation("Draw",true),
81        _sceneView(sceneView)
82    {
83    }
84   
85    virtual void operator () (osg::GraphicsContext*)
86    {
87        _sceneView->draw();
88    }
89   
90    osg::ref_ptr<osgUtil::SceneView> _sceneView;
91};
92
93struct CleanUpOperation : public osg::GraphicsThread::Operation
94{
95    CleanUpOperation(osgUtil::SceneView* sceneView):
96        osg::GraphicsThread::Operation("CleanUp",false),
97        _sceneView(sceneView)
98    {
99    }
100   
101    virtual void operator () (osg::GraphicsContext*)
102    {
103        _sceneView->releaseAllGLObjects();
104        _sceneView->flushAllDeletedGLObjects();
105    }
106   
107    osg::ref_ptr<osgUtil::SceneView> _sceneView;
108};
109
110// main does the following steps to create a multi-thread, multiple camera/graphics context view of a scene graph.
111//
112// 1) load the scene graph
113//
114// 2) create a list of camera, each with their own graphis context, with a graphics thread for each context.
115//
116// 3) set up the graphic threads so that the do an initial compile OpenGL objects operation, this is done once, and then this compile op is disgarded
117//
118// 4) set up the graphics thread so that it has all the graphics ops required for the main loop, these ops are:
119// 4.a) frame begin barrair, syncronizes all the waiting graphic threads so they don't run while update is occuring
120// 4.b) frame operation - the cull and draw for each camera
121// 4.c) frame end barrier, releases the update thread once all graphic threads have dispatched all their OpenGL commands
122// 4.d) pre swap barrier, barrier which ensures that all graphics threads have sent their data down to the gfx card.
123// 4.e) swap buffers, do the swap buffers on all the graphics contexts.
124//
125// 5. The main loop:
126// 5.a) update
127// 5.b) join the frame begin barrrier, releasing all the graphics threads to do their stuff
128// 5.c) block on the frame end barrier, waiting till all the graphics threads have done their cull/draws.
129// 5.d) check to see if any of the windows has been closed.
130//
131int main( int argc, char **argv )
132{
133    // use an ArgumentParser object to manage the program arguments.
134    osg::ArgumentParser arguments(&argc,argv);
135
136    std::string windowingLibrary("osgProducer");
137    while (arguments.read("--windowing",windowingLibrary)) {}
138
139    // load the osgProducer library manually.
140    osg::ref_ptr<osgDB::DynamicLibrary> windowingLib =
141        osgDB::DynamicLibrary::loadLibrary(osgDB::Registry::instance()->createLibraryNameForNodeKit(windowingLibrary));
142
143
144    if (!windowingLib)
145    {
146        std::cout<<"Error: failed to loading windowing library: "<<windowingLibrary<<std::endl;
147    }
148
149    unsigned int numberCameras = 3;
150    while (arguments.read("--cameras",numberCameras)) {}
151
152    unsigned int xpos = 0;
153    unsigned int ypos = 400;
154    unsigned int width = 400;
155    unsigned int height = 400;
156
157    while (arguments.read("--xpos",xpos)) {}
158    while (arguments.read("--ypos",ypos)) {}
159    while (arguments.read("--height",height)) {}
160    while (arguments.read("--width",width)) {}
161
162    unsigned int maxNumFrames = 1000;
163    while (arguments.read("--max-num-frames",maxNumFrames)) {}
164
165    // load the scene.
166    osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);
167    if (!loadedModel)
168    {
169        std::cout << argv[0] <<": No data loaded." << std::endl;
170        return 1;
171    }
172
173   
174    // set up the frame stamp for current frame to record the current time and frame number so that animtion code can advance correctly
175    osg::ref_ptr<osg::FrameStamp> frameStamp = new osg::FrameStamp;
176
177    unsigned int frameNum = 0;
178
179    osgUtil::UpdateVisitor updateVisitor;
180    updateVisitor.setFrameStamp(frameStamp.get());
181   
182    typedef std::list< osg::ref_ptr<osg::CameraNode> > CameraList;
183    typedef std::set< osg::GraphicsContext* > GraphicsContextSet;
184
185    CameraList cameraList;
186    GraphicsContextSet graphicsContextSet;
187
188    // create the cameras, graphic contexts and graphic threads.
189    bool shareContexts = false;
190    osg::GraphicsContext* previousContext = 0;
191    for(unsigned int i=0; i< numberCameras; ++i)
192    {
193        osg::ref_ptr<osg::CameraNode> camera = new osg::CameraNode;
194        camera->addChild(loadedModel.get());
195
196        osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
197        traits->_windowName = "osgcamera";
198        traits->_x = xpos;
199        traits->_y = ypos;
200        traits->_width = width;
201        traits->_height = height;
202        traits->_windowDecoration = true;
203        traits->_doubleBuffer = true;
204        traits->_sharedContext = shareContexts ? previousContext : 0;
205       
206        xpos += width;
207
208        osg::ref_ptr<osg::GraphicsContext> gfxc = osg::GraphicsContext::createGraphicsContext(traits.get());
209
210        if (!gfxc)
211        {
212            std::cout<<"Unable to create window."<<std::endl;
213            return 1;
214        }
215
216        camera->setGraphicsContext(gfxc.get());
217
218        // initialize the view to look at the center of the scene graph
219        const osg::BoundingSphere& bs = loadedModel->getBound();
220        osg::Matrix viewMatrix;
221        viewMatrix.makeLookAt(bs.center()-osg::Vec3(0.0,2.0f*bs.radius(),0.0),bs.center(),osg::Vec3(0.0f,0.0f,1.0f));
222
223        camera->setViewport(0,0,traits->_width,traits->_height);
224        camera->setProjectionMatrixAsPerspective(50.0f,1.4f,1.0f,10000.0f);
225        camera->setViewMatrix(viewMatrix);
226
227        // graphics thread will realize the window.
228        gfxc->createGraphicsThread();
229
230        cameraList.push_back(camera);
231
232        previousContext = gfxc.get();
233    }
234
235
236    // build the list of unique graphics contexts.
237    CameraList::iterator citr;
238    for(citr = cameraList.begin();
239        citr != cameraList.end();
240        ++citr)
241    {
242        graphicsContextSet.insert(const_cast<osg::GraphicsContext*>((*citr)->getGraphicsContext()));
243    }
244
245
246    std::cout<<"Number of cameras = "<<cameraList.size()<<std::endl;
247    std::cout<<"Number of graphics contexts = "<<graphicsContextSet.size()<<std::endl;
248
249
250    // first the compile of the GL Objects, do it syncronously.
251    GraphicsContextSet::iterator gitr;
252    osg::ref_ptr<CompileOperation> compileOp = new CompileOperation(loadedModel.get());
253    for(gitr = graphicsContextSet.begin();
254        gitr != graphicsContextSet.end();
255        ++gitr)
256    {
257        osg::GraphicsContext* context = *gitr;
258        context->getGraphicsThread()->add(compileOp.get(), false);
259    }
260
261
262    // second the begin frame barrier to all graphics threads
263    osg::ref_ptr<osg::BarrierOperation> frameBeginBarrierOp = new osg::BarrierOperation(graphicsContextSet.size()+1, osg::BarrierOperation::NO_OPERATION);
264    for(gitr = graphicsContextSet.begin();
265        gitr != graphicsContextSet.end();
266        ++gitr)
267    {
268        osg::GraphicsContext* context = *gitr;
269        context->getGraphicsThread()->add(frameBeginBarrierOp.get(), false);
270    }
271
272    osg::ref_ptr<osg::BarrierOperation> glFinishBarrierOp = new osg::BarrierOperation(graphicsContextSet.size(), osg::BarrierOperation::GL_FINISH);
273
274    // we can put a finish in to gate rendering throughput, so that each new frame starts with a clean sheet.
275    // you should only enable one of these, doFinishBeforeNewDraw will allow for the better parallism of the two finish approaches
276    // note, both are disabled right now, as glFinish is spin locking the CPU, not something that we want...
277    bool doFinishBeforeNewDraw = false;
278    bool doFinishAfterSwap = false;
279
280    // third add the frame for each camera.
281    for(citr = cameraList.begin();
282        citr != cameraList.end();
283        ++citr)
284    {
285        osg::CameraNode* camera = citr->get();
286        osg::GraphicsThread* graphicsThread = camera->getGraphicsContext()->getGraphicsThread();
287       
288        // create a scene view to do the cull and draw
289        osgUtil::SceneView* sceneView = new osgUtil::SceneView;
290        sceneView->setDefaults();
291        sceneView->setFrameStamp(frameStamp.get());
292        sceneView->setCamera(camera);   
293
294        // cull traversal operation
295        graphicsThread->add( new CullOperation(sceneView), false);
296
297        // optionally add glFinish barrier to ensure that all OpenGL commands are completed before we start dispatching a new frame
298        if (doFinishBeforeNewDraw) graphicsThread->add( glFinishBarrierOp.get(), false);
299
300        // draw traversal operation.
301        graphicsThread->add( new DrawOperation(sceneView), false);
302    }
303
304    // fourth add the frame end barrier, the pre swap barrier and finally the swap buffers to each graphics thread.
305    // The frame end barrier tells the main thead that the draw dispatch/read phase of the scene graph is complete.
306    // The pre swap barrier is an optional extra, which does a flush before joining the barrier, using this all graphics threads
307    // are held back until they have all dispatched their fifo to the graphics hardware. 
308    // The swapOp just issues a swap buffers for each of the graphics contexts.
309    osg::ref_ptr<osg::BarrierOperation> frameEndBarrierOp = new osg::BarrierOperation(graphicsContextSet.size()+1, osg::BarrierOperation::NO_OPERATION);
310    osg::ref_ptr<osg::BarrierOperation> preSwapBarrierOp = new osg::BarrierOperation(graphicsContextSet.size(), osg::BarrierOperation::GL_FLUSH);
311    osg::ref_ptr<osg::SwapBuffersOperation> swapOp = new osg::SwapBuffersOperation();
312    for(gitr = graphicsContextSet.begin();
313        gitr != graphicsContextSet.end();
314        ++gitr)
315    {
316        osg::GraphicsContext* context = *gitr;
317
318        context->getGraphicsThread()->add(frameEndBarrierOp.get(), false);
319        // context->getGraphicsThread()->add(preSwapBarrierOp.get(), false);
320        context->getGraphicsThread()->add(swapOp.get(), false);
321       
322        // optionally add finish barrier to ensure that we don't do any other graphics work till the current OpenGL commands are complete.
323        if (doFinishAfterSwap) context->getGraphicsThread()->add(glFinishBarrierOp.get(), false);
324    }
325
326
327    // record the timer tick at the start of rendering.   
328    osg::Timer_t start_tick = osg::Timer::instance()->tick();
329    osg::Timer_t previous_tick = start_tick;
330   
331    bool done = false;
332
333    // main loop -  update scene graph, dispatch frame, wait for frame done.
334    while( !done && frameNum<maxNumFrames)
335    {
336
337        osg::Timer_t current_tick = osg::Timer::instance()->tick();
338
339        frameStamp->setReferenceTime(osg::Timer::instance()->delta_s(start_tick,current_tick));
340        frameStamp->setFrameNumber(frameNum++);
341       
342        //std::cout<<"Frame rate "<<1.0/osg::Timer::instance()->delta_s(previous_tick,current_tick)<<std::endl;
343        previous_tick = current_tick;
344
345
346        // do the update traversal.
347        loadedModel->accept(updateVisitor);
348
349        // dispatch the frame.
350        frameBeginBarrierOp->block();
351       
352        // wait till the frame is done.
353        frameEndBarrierOp->block();
354
355        // check if any of the windows are closed
356        for(gitr = graphicsContextSet.begin();
357            gitr != graphicsContextSet.end();
358            ++gitr)
359        {
360            osg::GraphicsContext* context = *gitr;
361            if (!context->isRealized()) done = true;
362        }
363
364    }
365
366   
367    std::cout<<"Exiting application"<<std::endl;
368
369    // start clean up.
370    for(gitr = graphicsContextSet.begin();
371        gitr != graphicsContextSet.end();
372        ++gitr)
373    {
374        osg::GraphicsContext* context = *gitr;
375        osg::GraphicsThread* thread = context->getGraphicsThread();
376        if (thread)
377        {
378            thread->removeAllOperations();
379            thread->setDone(true);
380        }
381    }
382
383    std::cout<<"Removed all operations"<<std::endl;
384
385    return 0;
386}
Note: See TracBrowser for help on using the browser.