root/OpenSceneGraph/trunk/src/osgViewer/View.cpp @ 13172

Revision 13172, 81.5 kB (checked in by robert, 7 hours ago)

From Farshid Lashkari, "I've attached a small fix to the Collada loader which prevents a null pointer access in some cases."

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
2 *
3 * This library is open source and may be redistributed and/or modified under
4 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
5 * (at your option) any later version.  The full license is in LICENSE file
6 * included with this distribution, and on the openscenegraph.org website.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 * OpenSceneGraph Public License for more details.
12*/
13
14#include <osgViewer/Renderer>
15#include <osgViewer/View>
16#include <osgViewer/GraphicsWindow>
17
18#include <osg/io_utils>
19
20#include <osg/TextureCubeMap>
21#include <osg/TextureRectangle>
22#include <osg/Texture1D>
23#include <osg/TexMat>
24
25#include <osgUtil/Optimizer>
26#include <osgUtil/ShaderGen>
27#include <osgUtil/IntersectionVisitor>
28
29#include <iterator>
30
31using namespace osgViewer;
32
33class CollectedCoordinateSystemNodesVisitor : public osg::NodeVisitor
34{
35public:
36
37    CollectedCoordinateSystemNodesVisitor():
38        NodeVisitor(osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN) {}
39
40    META_NodeVisitor("osgViewer","CollectedCoordinateSystemNodesVisitor")
41
42    virtual void apply(osg::Node& node)
43    {
44        traverse(node);
45    }
46
47    virtual void apply(osg::CoordinateSystemNode& node)
48    {
49        if (_pathToCoordinateSystemNode.empty())
50        {
51            OSG_DEBUG<<"Found CoordinateSystemNode node"<<std::endl;
52            OSG_DEBUG<<"     CoordinateSystem = "<<node.getCoordinateSystem()<<std::endl;
53            _pathToCoordinateSystemNode = getNodePath();
54        }
55        else
56        {
57            OSG_DEBUG<<"Found additional CoordinateSystemNode node, but ignoring"<<std::endl;
58            OSG_DEBUG<<"     CoordinateSystem = "<<node.getCoordinateSystem()<<std::endl;
59        }
60        traverse(node);
61    }
62
63    osg::NodePath _pathToCoordinateSystemNode;
64};
65
66
67/** callback class to use to allow matrix manipulators to query the application for the local coordinate frame.*/
68class ViewerCoordinateFrameCallback : public osgGA::CameraManipulator::CoordinateFrameCallback
69{
70public:
71
72    ViewerCoordinateFrameCallback(osgViewer::View* view):
73        _view(view) {}
74
75    virtual osg::CoordinateFrame getCoordinateFrame(const osg::Vec3d& position) const
76    {
77        OSG_DEBUG<<"getCoordinateFrame("<<position<<")"<<std::endl;
78
79        osg::NodePath tmpPath = _view->getCoordinateSystemNodePath();
80
81        if (!tmpPath.empty())
82        {
83            osg::Matrixd coordinateFrame;
84
85            osg::CoordinateSystemNode* csn = dynamic_cast<osg::CoordinateSystemNode*>(tmpPath.back());
86            if (csn)
87            {
88                osg::Vec3 local_position = position*osg::computeWorldToLocal(tmpPath);
89
90                // get the coordinate frame in world coords.
91                coordinateFrame = csn->computeLocalCoordinateFrame(local_position)* osg::computeLocalToWorld(tmpPath);
92
93                // keep the position of the coordinate frame to reapply after rescale.
94                osg::Vec3d pos = coordinateFrame.getTrans();
95
96                // compensate for any scaling, so that the coordinate frame is a unit size
97                osg::Vec3d x(1.0,0.0,0.0);
98                osg::Vec3d y(0.0,1.0,0.0);
99                osg::Vec3d z(0.0,0.0,1.0);
100                x = osg::Matrixd::transform3x3(x,coordinateFrame);
101                y = osg::Matrixd::transform3x3(y,coordinateFrame);
102                z = osg::Matrixd::transform3x3(z,coordinateFrame);
103                coordinateFrame.preMultScale(osg::Vec3d(1.0/x.length(),1.0/y.length(),1.0/z.length()));
104
105                // reapply the position.
106                coordinateFrame.setTrans(pos);
107
108                OSG_DEBUG<<"csn->computeLocalCoordinateFrame(position)* osg::computeLocalToWorld(tmpPath)"<<coordinateFrame<<std::endl;
109
110            }
111            else
112            {
113                OSG_DEBUG<<"osg::computeLocalToWorld(tmpPath)"<<std::endl;
114                coordinateFrame =  osg::computeLocalToWorld(tmpPath);
115            }
116            return coordinateFrame;
117        }
118        else
119        {
120            OSG_DEBUG<<"   no coordinate system found, using default orientation"<<std::endl;
121            return osg::Matrixd::translate(position);
122        }
123    }
124
125protected:
126    virtual ~ViewerCoordinateFrameCallback() {}
127
128    osg::observer_ptr<osgViewer::View> _view;
129};
130
131
132View::View():
133    _fusionDistanceMode(osgUtil::SceneView::PROPORTIONAL_TO_SCREEN_DISTANCE),
134    _fusionDistanceValue(1.0f)
135{
136    // OSG_NOTICE<<"Constructing osgViewer::View"<<std::endl;
137
138    _startTick = 0;
139
140    _frameStamp = new osg::FrameStamp;
141    _frameStamp->setFrameNumber(0);
142    _frameStamp->setReferenceTime(0);
143    _frameStamp->setSimulationTime(0);
144
145    _scene = new Scene;
146
147    // make sure View is safe to reference multi-threaded.
148    setThreadSafeRefUnref(true);
149
150    // need to attach a Renderer to the master camera which has been default constructed
151    getCamera()->setRenderer(createRenderer(getCamera()));
152
153    setEventQueue(new osgGA::EventQueue);
154
155    setStats(new osg::Stats("View"));
156}
157
158
159View::View(const osgViewer::View& view, const osg::CopyOp& copyop):
160    osg::Object(true),
161    osg::View(view,copyop),
162    osgGA::GUIActionAdapter(),
163    _startTick(0),
164    _fusionDistanceMode(view._fusionDistanceMode),
165    _fusionDistanceValue(view._fusionDistanceValue)
166{
167    _scene = new Scene;
168
169    // need to attach a Renderer to the master camera which has been default constructed
170    getCamera()->setRenderer(createRenderer(getCamera()));
171
172    setEventQueue(new osgGA::EventQueue);
173
174    setStats(new osg::Stats("View"));
175}
176
177View::~View()
178{
179    OSG_INFO<<"Destructing osgViewer::View"<<std::endl;
180}
181
182void View::take(osg::View& rhs)
183{
184    osg::View::take(rhs);
185
186#if 1
187    osgViewer::View* rhs_osgViewer = dynamic_cast<osgViewer::View*>(&rhs);
188    if (rhs_osgViewer)
189    {
190
191        // copy across rhs
192        _startTick = rhs_osgViewer->_startTick;
193        _frameStamp = rhs_osgViewer->_frameStamp;
194
195        if (rhs_osgViewer->getSceneData())
196        {
197            _scene = rhs_osgViewer->_scene;
198        }
199
200        if (rhs_osgViewer->_cameraManipulator.valid())
201        {
202            _cameraManipulator = rhs_osgViewer->_cameraManipulator;
203        }
204
205        _eventHandlers.insert(_eventHandlers.end(), rhs_osgViewer->_eventHandlers.begin(), rhs_osgViewer->_eventHandlers.end());
206
207        _coordinateSystemNodePath = rhs_osgViewer->_coordinateSystemNodePath;
208
209        _displaySettings = rhs_osgViewer->_displaySettings;
210        _fusionDistanceMode = rhs_osgViewer->_fusionDistanceMode;
211        _fusionDistanceValue = rhs_osgViewer->_fusionDistanceValue;
212
213
214        // clear rhs
215        rhs_osgViewer->_frameStamp = 0;
216        rhs_osgViewer->_scene = 0;
217        rhs_osgViewer->_cameraManipulator = 0;
218        rhs_osgViewer->_eventHandlers.clear();
219
220        rhs_osgViewer->_coordinateSystemNodePath.clearNodePath();
221
222        rhs_osgViewer->_displaySettings = 0;
223    }
224#endif
225    computeActiveCoordinateSystemNodePath();
226    assignSceneDataToCameras();
227}
228
229osg::GraphicsOperation* View::createRenderer(osg::Camera* camera)
230{
231    Renderer* render = new Renderer(camera);
232    camera->setStats(new osg::Stats("Camera"));
233    return render;
234}
235
236
237void View::init()
238{
239    OSG_INFO<<"View::init()"<<std::endl;
240
241    osg::ref_ptr<osgGA::GUIEventAdapter> initEvent = _eventQueue->createEvent();
242    initEvent->setEventType(osgGA::GUIEventAdapter::FRAME);
243
244    if (_cameraManipulator.valid())
245    {
246        _cameraManipulator->init(*initEvent, *this);
247    }
248}
249
250void View::setStartTick(osg::Timer_t tick)
251{
252    _startTick = tick;
253}
254
255void View::setSceneData(osg::Node* node)
256{
257    if (node==_scene->getSceneData()) return;
258
259    osg::ref_ptr<Scene> scene = Scene::getScene(node);
260
261    if (scene)
262    {
263        OSG_INFO<<"View::setSceneData() Sharing scene "<<scene.get()<<std::endl;
264        _scene = scene;
265    }
266    else
267    {
268        if (_scene->referenceCount()!=1)
269        {
270            // we are not the only reference to the Scene so we cannot reuse it.
271            _scene = new Scene;
272            OSG_INFO<<"View::setSceneData() Allocating new scene"<<_scene.get()<<std::endl;
273        }
274        else
275        {
276            OSG_INFO<<"View::setSceneData() Reusing exisitng scene"<<_scene.get()<<std::endl;
277        }
278
279        _scene->setSceneData(node);
280    }
281
282    if (getSceneData())
283    {
284        #if defined(OSG_GLES2_AVAILABLE)
285            osgUtil::ShaderGenVisitor sgv;
286            getSceneData()->getOrCreateStateSet();
287            getSceneData()->accept(sgv);
288        #endif
289
290        // now make sure the scene graph is set up with the correct DataVariance to protect the dynamic elements of
291        // the scene graph from being run in parallel.
292        osgUtil::Optimizer::StaticObjectDetectionVisitor sodv;
293        getSceneData()->accept(sodv);
294
295        // make sure that existing scene graph objects are allocated with thread safe ref/unref
296        if (getViewerBase() &&
297            getViewerBase()->getThreadingModel()!=ViewerBase::SingleThreaded)
298        {
299            getSceneData()->setThreadSafeRefUnref(true);
300        }
301
302        // update the scene graph so that it has enough GL object buffer memory for the graphics contexts that will be using it.
303        getSceneData()->resizeGLObjectBuffers(osg::DisplaySettings::instance()->getMaxNumberOfGraphicsContexts());
304    }
305
306    computeActiveCoordinateSystemNodePath();
307
308    assignSceneDataToCameras();
309}
310
311void View::setDatabasePager(osgDB::DatabasePager* dp)
312{
313    _scene->setDatabasePager(dp);
314}
315
316osgDB::DatabasePager* View::getDatabasePager()
317{
318    return _scene->getDatabasePager();
319}
320
321const osgDB::DatabasePager* View::getDatabasePager() const
322{
323    return _scene->getDatabasePager();
324}
325
326
327void View::setImagePager(osgDB::ImagePager* dp)
328{
329    _scene->setImagePager(dp);
330}
331
332osgDB::ImagePager* View::getImagePager()
333{
334    return _scene->getImagePager();
335}
336
337const osgDB::ImagePager* View::getImagePager() const
338{
339    return _scene->getImagePager();
340}
341
342
343void View::setCameraManipulator(osgGA::CameraManipulator* manipulator, bool resetPosition)
344{
345    _cameraManipulator = manipulator;
346
347    if (_cameraManipulator.valid())
348    {
349        _cameraManipulator->setCoordinateFrameCallback(new ViewerCoordinateFrameCallback(this));
350
351        if (getSceneData()) _cameraManipulator->setNode(getSceneData());
352
353        if (resetPosition)
354        {
355            osg::ref_ptr<osgGA::GUIEventAdapter> dummyEvent = _eventQueue->createEvent();
356            _cameraManipulator->home(*dummyEvent, *this);
357        }
358    }
359}
360
361void View::home()
362{
363    if (_cameraManipulator.valid())
364    {
365        osg::ref_ptr<osgGA::GUIEventAdapter> dummyEvent = _eventQueue->createEvent();
366        _cameraManipulator->home(*dummyEvent, *this);
367    }
368}
369
370
371void View::addEventHandler(osgGA::GUIEventHandler* eventHandler)
372{
373    EventHandlers::iterator itr = std::find(_eventHandlers.begin(), _eventHandlers.end(), eventHandler);
374    if (itr == _eventHandlers.end())
375    {
376        _eventHandlers.push_back(eventHandler);
377    }
378}
379
380void View::removeEventHandler(osgGA::GUIEventHandler* eventHandler)
381{
382    EventHandlers::iterator itr = std::find(_eventHandlers.begin(), _eventHandlers.end(), eventHandler);
383    if (itr != _eventHandlers.end())
384    {
385        _eventHandlers.erase(itr);
386    }
387}
388
389void View::setCoordinateSystemNodePath(const osg::NodePath& nodePath)
390{
391    _coordinateSystemNodePath.setNodePath(nodePath);
392}
393
394osg::NodePath View::getCoordinateSystemNodePath() const
395{
396    osg::NodePath nodePath;
397    _coordinateSystemNodePath.getNodePath(nodePath);
398    return nodePath;
399}
400
401void View::computeActiveCoordinateSystemNodePath()
402{
403    // now search for CoordinateSystemNode's for which we want to track.
404    osg::Node* subgraph = getSceneData();
405
406    if (subgraph)
407    {
408
409        CollectedCoordinateSystemNodesVisitor ccsnv;
410        subgraph->accept(ccsnv);
411
412        if (!ccsnv._pathToCoordinateSystemNode.empty())
413        {
414           setCoordinateSystemNodePath(ccsnv._pathToCoordinateSystemNode);
415           return;
416        }
417    }
418
419    // otherwise no node path found so reset to empty.
420    setCoordinateSystemNodePath(osg::NodePath());
421}
422
423void View::setUpViewAcrossAllScreens()
424{
425    osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
426    if (!wsi)
427    {
428        OSG_NOTICE<<"View::setUpViewAcrossAllScreens() : Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
429        return;
430    }
431
432    osg::DisplaySettings* ds = _displaySettings.valid() ? _displaySettings.get() : osg::DisplaySettings::instance().get();
433
434    double fovy, aspectRatio, zNear, zFar;
435    _camera->getProjectionMatrixAsPerspective(fovy, aspectRatio, zNear, zFar);
436
437    osg::GraphicsContext::ScreenIdentifier si;
438    si.readDISPLAY();
439
440    // displayNum has not been set so reset it to 0.
441    if (si.displayNum<0) si.displayNum = 0;
442
443    unsigned int numScreens = wsi->getNumScreens(si);
444    if (numScreens==1)
445    {
446        if (si.screenNum<0) si.screenNum = 0;
447
448        unsigned int width, height;
449        wsi->getScreenResolution(si, width, height);
450
451        osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits(ds);
452        traits->hostName = si.hostName;
453        traits->displayNum = si.displayNum;
454        traits->screenNum = si.screenNum;
455        traits->x = 0;
456        traits->y = 0;
457        traits->width = width;
458        traits->height = height;
459        traits->windowDecoration = false;
460        traits->doubleBuffer = true;
461        traits->sharedContext = 0;
462
463        osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
464
465        _camera->setGraphicsContext(gc.get());
466
467        osgViewer::GraphicsWindow* gw = dynamic_cast<osgViewer::GraphicsWindow*>(gc.get());
468        if (gw)
469        {
470            OSG_INFO<<"  GraphicsWindow has been created successfully."<<std::endl;
471            gw->getEventQueue()->getCurrentEventState()->setWindowRectangle(0, 0, width, height );
472        }
473        else
474        {
475            OSG_NOTICE<<"  GraphicsWindow has not been created successfully."<<std::endl;
476        }
477
478        double newAspectRatio = double(traits->width) / double(traits->height);
479        double aspectRatioChange = newAspectRatio / aspectRatio;
480        if (aspectRatioChange != 1.0)
481        {
482            _camera->getProjectionMatrix() *= osg::Matrix::scale(1.0/aspectRatioChange,1.0,1.0);
483        }
484
485        _camera->setViewport(new osg::Viewport(0, 0, traits->width, traits->height));
486
487        GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
488
489        _camera->setDrawBuffer(buffer);
490        _camera->setReadBuffer(buffer);
491
492    }
493    else
494    {
495
496        double translate_x = 0.0;
497
498        for(unsigned int i=0; i<numScreens; ++i)
499        {
500            si.screenNum = i;
501
502            unsigned int width, height;
503            wsi->getScreenResolution(si, width, height);
504            translate_x += double(width) / (double(height) * aspectRatio);
505        }
506
507        bool stereoSplitScreens = numScreens==2 &&
508                                 ds->getStereoMode()==osg::DisplaySettings::HORIZONTAL_SPLIT &&
509                                 ds->getStereo();
510
511        for(unsigned int i=0; i<numScreens; ++i)
512        {
513            si.screenNum = i;
514
515            unsigned int width, height;
516            wsi->getScreenResolution(si, width, height);
517
518            osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits(ds);
519            traits->hostName = si.hostName;
520            traits->displayNum = si.displayNum;
521            traits->screenNum = si.screenNum;
522            traits->screenNum = i;
523            traits->x = 0;
524            traits->y = 0;
525            traits->width = width;
526            traits->height = height;
527            traits->windowDecoration = false;
528            traits->doubleBuffer = true;
529            traits->sharedContext = 0;
530
531            osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
532
533            osg::ref_ptr<osg::Camera> camera = new osg::Camera;
534            camera->setGraphicsContext(gc.get());
535
536            osgViewer::GraphicsWindow* gw = dynamic_cast<osgViewer::GraphicsWindow*>(gc.get());
537            if (gw)
538            {
539                OSG_INFO<<"  GraphicsWindow has been created successfully."<<gw<<std::endl;
540
541                gw->getEventQueue()->getCurrentEventState()->setWindowRectangle(traits->x, traits->y, traits->width, traits->height );
542            }
543            else
544            {
545                OSG_NOTICE<<"  GraphicsWindow has not been created successfully."<<std::endl;
546            }
547
548            camera->setViewport(new osg::Viewport(0, 0, traits->width, traits->height));
549
550            GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
551            camera->setDrawBuffer(buffer);
552            camera->setReadBuffer(buffer);
553
554            if (stereoSplitScreens)
555            {
556                unsigned int leftCameraNum = (ds->getSplitStereoHorizontalEyeMapping()==osg::DisplaySettings::LEFT_EYE_LEFT_VIEWPORT) ? 0 : 1;
557
558                osg::ref_ptr<osg::DisplaySettings> ds_local = new osg::DisplaySettings(*ds);
559                ds_local->setStereoMode(leftCameraNum==i ? osg::DisplaySettings::LEFT_EYE : osg::DisplaySettings::RIGHT_EYE);
560                camera->setDisplaySettings(ds_local.get());
561
562                addSlave(camera.get(), osg::Matrixd(), osg::Matrixd() );
563            }
564            else
565            {
566                double newAspectRatio = double(traits->width) / double(traits->height);
567                double aspectRatioChange = newAspectRatio / aspectRatio;
568
569                addSlave(camera.get(), osg::Matrixd::translate( translate_x - aspectRatioChange, 0.0, 0.0) * osg::Matrix::scale(1.0/aspectRatioChange,1.0,1.0), osg::Matrixd() );
570                translate_x -= aspectRatioChange * 2.0;
571            }
572        }
573    }
574
575    assignSceneDataToCameras();
576}
577
578void View::setUpViewInWindow(int x, int y, int width, int height, unsigned int screenNum)
579{
580    osg::DisplaySettings* ds = _displaySettings.valid() ? _displaySettings.get() : osg::DisplaySettings::instance().get();
581
582    osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits(ds);
583
584    traits->readDISPLAY();
585    if (traits->displayNum<0) traits->displayNum = 0;
586
587    traits->screenNum = screenNum;
588    traits->x = x;
589    traits->y = y;
590    traits->width = width;
591    traits->height = height;
592    traits->windowDecoration = true;
593    traits->doubleBuffer = true;
594    traits->sharedContext = 0;
595
596    osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
597
598    _camera->setGraphicsContext(gc.get());
599
600    osgViewer::GraphicsWindow* gw = dynamic_cast<osgViewer::GraphicsWindow*>(gc.get());
601    if (gw)
602    {
603        OSG_INFO<<"View::setUpViewOnSingleScreen - GraphicsWindow has been created successfully."<<std::endl;
604        gw->getEventQueue()->getCurrentEventState()->setWindowRectangle(x, y, width, height );
605    }
606    else
607    {
608        OSG_NOTICE<<"  GraphicsWindow has not been created successfully."<<std::endl;
609    }
610
611    double fovy, aspectRatio, zNear, zFar;
612    _camera->getProjectionMatrixAsPerspective(fovy, aspectRatio, zNear, zFar);
613
614    double newAspectRatio = double(traits->width) / double(traits->height);
615    double aspectRatioChange = newAspectRatio / aspectRatio;
616    if (aspectRatioChange != 1.0)
617    {
618        _camera->getProjectionMatrix() *= osg::Matrix::scale(1.0/aspectRatioChange,1.0,1.0);
619    }
620
621    _camera->setViewport(new osg::Viewport(0, 0, traits->width, traits->height));
622
623    GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
624
625    _camera->setDrawBuffer(buffer);
626    _camera->setReadBuffer(buffer);
627}
628
629void View::setUpViewOnSingleScreen(unsigned int screenNum)
630{
631    osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
632    if (!wsi)
633    {
634        OSG_NOTICE<<"View::setUpViewOnSingleScreen() : Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
635        return;
636    }
637
638    osg::DisplaySettings* ds = _displaySettings.valid() ? _displaySettings.get() : osg::DisplaySettings::instance().get();
639
640    osg::GraphicsContext::ScreenIdentifier si;
641    si.readDISPLAY();
642
643    // displayNum has not been set so reset it to 0.
644    if (si.displayNum<0) si.displayNum = 0;
645
646    si.screenNum = screenNum;
647
648    unsigned int width, height;
649    wsi->getScreenResolution(si, width, height);
650
651    osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits(ds);
652    traits->hostName = si.hostName;
653    traits->displayNum = si.displayNum;
654    traits->screenNum = si.screenNum;
655    traits->x = 0;
656    traits->y = 0;
657    traits->width = width;
658    traits->height = height;
659    traits->windowDecoration = false;
660    traits->doubleBuffer = true;
661    traits->sharedContext = 0;
662
663    osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
664
665    _camera->setGraphicsContext(gc.get());
666
667    osgViewer::GraphicsWindow* gw = dynamic_cast<osgViewer::GraphicsWindow*>(gc.get());
668    if (gw)
669    {
670        OSG_INFO<<"View::setUpViewOnSingleScreen - GraphicsWindow has been created successfully."<<std::endl;
671        gw->getEventQueue()->getCurrentEventState()->setWindowRectangle(0, 0, width, height );
672    }
673    else
674    {
675        OSG_NOTICE<<"  GraphicsWindow has not been created successfully."<<std::endl;
676    }
677
678    double fovy, aspectRatio, zNear, zFar;
679    _camera->getProjectionMatrixAsPerspective(fovy, aspectRatio, zNear, zFar);
680
681    double newAspectRatio = double(traits->width) / double(traits->height);
682    double aspectRatioChange = newAspectRatio / aspectRatio;
683    if (aspectRatioChange != 1.0)
684    {
685        _camera->getProjectionMatrix() *= osg::Matrix::scale(1.0/aspectRatioChange,1.0,1.0);
686    }
687
688    _camera->setViewport(new osg::Viewport(0, 0, traits->width, traits->height));
689
690    GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
691
692    _camera->setDrawBuffer(buffer);
693    _camera->setReadBuffer(buffer);
694}
695
696static osg::Geometry* create3DSphericalDisplayDistortionMesh(const osg::Vec3& origin, const osg::Vec3& widthVector, const osg::Vec3& heightVector, double sphere_radius, double collar_radius,osg::Image* intensityMap, const osg::Matrix& projectorMatrix)
697{
698    osg::Vec3d center(0.0,0.0,0.0);
699    osg::Vec3d eye(0.0,0.0,0.0);
700
701    double distance = sqrt(sphere_radius*sphere_radius - collar_radius*collar_radius);
702
703    bool centerProjection = false;
704
705    osg::Vec3d projector = eye - osg::Vec3d(0.0,0.0, distance);
706
707    OSG_INFO<<"create3DSphericalDisplayDistortionMesh : Projector position = "<<projector<<std::endl;
708    OSG_INFO<<"create3DSphericalDisplayDistortionMesh : distance = "<<distance<<std::endl;
709
710
711    // create the quad to visualize.
712    osg::Geometry* geometry = new osg::Geometry();
713
714    geometry->setSupportsDisplayList(false);
715
716    osg::Vec3 xAxis(widthVector);
717    float width = widthVector.length();
718    xAxis /= width;
719
720    osg::Vec3 yAxis(heightVector);
721    float height = heightVector.length();
722    yAxis /= height;
723
724    int noSteps = 50;
725
726    osg::Vec3Array* vertices = new osg::Vec3Array;
727    osg::Vec3Array* texcoords0 = new osg::Vec3Array;
728    osg::Vec2Array* texcoords1 = intensityMap==0 ? new osg::Vec2Array : 0;
729    osg::Vec4Array* colors = new osg::Vec4Array;
730
731    osg::Vec3 bottom = origin;
732    osg::Vec3 dx = xAxis*(width/((float)(noSteps-1)));
733    osg::Vec3 dy = yAxis*(height/((float)(noSteps-1)));
734
735    osg::Vec3d screenCenter = origin + widthVector*0.5f + heightVector*0.5f;
736    float screenRadius = heightVector.length() * 0.5f;
737
738    int i,j;
739
740    if (centerProjection)
741    {
742        for(i=0;i<noSteps;++i)
743        {
744            osg::Vec3 cursor = bottom+dy*(float)i;
745            for(j=0;j<noSteps;++j)
746            {
747                osg::Vec2 delta(cursor.x() - screenCenter.x(), cursor.y() - screenCenter.y());
748                double theta = atan2(-delta.y(), delta.x());
749                double phi = osg::PI_2 * delta.length() / screenRadius;
750                if (phi > osg::PI_2) phi = osg::PI_2;
751
752                phi *= 2.0;
753
754                if (theta<0.0) theta += 2.0*osg::PI;
755
756                // OSG_NOTICE<<"theta = "<<theta<< "phi="<<phi<<std::endl;
757
758                osg::Vec3 texcoord(sin(phi) * cos(theta),
759                                   sin(phi) * sin(theta),
760                                   cos(phi));
761
762                vertices->push_back(cursor);
763                texcoords0->push_back(texcoord * projectorMatrix);
764
765                osg::Vec2 texcoord1(theta/(2.0*osg::PI), 1.0f - phi/osg::PI_2);
766                if (intensityMap)
767                {
768                    colors->push_back(intensityMap->getColor(texcoord1));
769                }
770                else
771                {
772                    colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
773                    if (texcoords1) texcoords1->push_back( texcoord1 );
774                }
775
776                cursor += dx;
777            }
778            // OSG_NOTICE<<std::endl;
779        }
780    }
781    else
782    {
783        for(i=0;i<noSteps;++i)
784        {
785            osg::Vec3 cursor = bottom+dy*(float)i;
786            for(j=0;j<noSteps;++j)
787            {
788                osg::Vec2 delta(cursor.x() - screenCenter.x(), cursor.y() - screenCenter.y());
789                double theta = atan2(-delta.y(), delta.x());
790                double phi = osg::PI_2 * delta.length() / screenRadius;
791                if (phi > osg::PI_2) phi = osg::PI_2;
792                if (theta<0.0) theta += 2.0*osg::PI;
793
794                // OSG_NOTICE<<"theta = "<<theta<< "phi="<<phi<<std::endl;
795
796                double f = distance * sin(phi);
797                double e = distance * cos(phi) + sqrt( sphere_radius*sphere_radius - f*f);
798                double l = e * cos(phi);
799                double h = e * sin(phi);
800                double z = l - distance;
801
802                osg::Vec3 texcoord(h * cos(theta) / sphere_radius,
803                                   h * sin(theta) / sphere_radius,
804                                   z / sphere_radius);
805
806                vertices->push_back(cursor);
807                texcoords0->push_back(texcoord * projectorMatrix);
808
809                osg::Vec2 texcoord1(theta/(2.0*osg::PI), 1.0f - phi/osg::PI_2);
810                if (intensityMap)
811                {
812                    colors->push_back(intensityMap->getColor(texcoord1));
813                }
814                else
815                {
816                    colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
817                    if (texcoords1) texcoords1->push_back( texcoord1 );
818                }
819
820                cursor += dx;
821            }
822            // OSG_NOTICE<<std::endl;
823        }
824    }
825
826    // pass the created vertex array to the points geometry object.
827    geometry->setVertexArray(vertices);
828
829    geometry->setColorArray(colors);
830    geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
831
832    geometry->setTexCoordArray(0,texcoords0);
833    if (texcoords1) geometry->setTexCoordArray(1,texcoords1);
834
835    for(i=0;i<noSteps-1;++i)
836    {
837        osg::DrawElementsUShort* elements = new osg::DrawElementsUShort(osg::PrimitiveSet::QUAD_STRIP);
838        for(j=0;j<noSteps;++j)
839        {
840            elements->push_back(j+(i+1)*noSteps);
841            elements->push_back(j+(i)*noSteps);
842        }
843        geometry->addPrimitiveSet(elements);
844    }
845
846    return geometry;
847}
848
849void View::setUpViewFor3DSphericalDisplay(double radius, double collar, unsigned int screenNum, osg::Image* intensityMap, const osg::Matrixd& projectorMatrix)
850{
851    OSG_INFO<<"View::setUpViewFor3DSphericalDisplay(rad="<<radius<<", cllr="<<collar<<", sn="<<screenNum<<", im="<<intensityMap<<")"<<std::endl;
852    osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
853    if (!wsi)
854    {
855        OSG_NOTICE<<"Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
856        return;
857    }
858
859    osg::GraphicsContext::ScreenIdentifier si;
860    si.readDISPLAY();
861
862    // displayNum has not been set so reset it to 0.
863    if (si.displayNum<0) si.displayNum = 0;
864
865    si.screenNum = screenNum;
866
867    unsigned int width, height;
868    wsi->getScreenResolution(si, width, height);
869
870
871    osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
872    traits->hostName = si.hostName;
873    traits->displayNum = si.displayNum;
874    traits->screenNum = si.screenNum;
875    traits->x = 0;
876    traits->y = 0;
877    traits->width = width;
878    traits->height = height;
879    traits->windowDecoration = false;
880    traits->doubleBuffer = true;
881    traits->sharedContext = 0;
882
883
884    osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
885    if (!gc)
886    {
887        OSG_NOTICE<<"GraphicsWindow has not been created successfully."<<std::endl;
888        return;
889    }
890
891    bool applyIntensityMapAsColours = true;
892
893    int tex_width = 512;
894    int tex_height = 512;
895
896    int camera_width = tex_width;
897    int camera_height = tex_height;
898
899    osg::TextureCubeMap* texture = new osg::TextureCubeMap;
900
901    texture->setTextureSize(tex_width, tex_height);
902    texture->setInternalFormat(GL_RGB);
903    texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
904    texture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
905    texture->setWrap(osg::Texture::WRAP_S,osg::Texture::CLAMP_TO_EDGE);
906    texture->setWrap(osg::Texture::WRAP_T,osg::Texture::CLAMP_TO_EDGE);
907    texture->setWrap(osg::Texture::WRAP_R,osg::Texture::CLAMP_TO_EDGE);
908
909#if 0
910    osg::Camera::RenderTargetImplementation renderTargetImplementation = osg::Camera::SEPERATE_WINDOW;
911    GLenum buffer = GL_FRONT;
912#else
913    osg::Camera::RenderTargetImplementation renderTargetImplementation = osg::Camera::FRAME_BUFFER_OBJECT;
914    GLenum buffer = GL_FRONT;
915#endif
916
917    // front face
918    {
919        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
920        camera->setName("Front face camera");
921        camera->setGraphicsContext(gc.get());
922        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
923        camera->setDrawBuffer(buffer);
924        camera->setReadBuffer(buffer);
925        camera->setAllowEventFocus(false);
926        // tell the camera to use OpenGL frame buffer object where supported.
927        camera->setRenderTargetImplementation(renderTargetImplementation);
928
929        // attach the texture and use it as the color buffer.
930        camera->attach(osg::Camera::COLOR_BUFFER, texture, 0, osg::TextureCubeMap::POSITIVE_Y);
931
932        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd());
933    }
934
935
936    // top face
937    {
938        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
939        camera->setName("Top face camera");
940        camera->setGraphicsContext(gc.get());
941        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
942        camera->setDrawBuffer(buffer);
943        camera->setReadBuffer(buffer);
944        camera->setAllowEventFocus(false);
945
946        // tell the camera to use OpenGL frame buffer object where supported.
947        camera->setRenderTargetImplementation(renderTargetImplementation);
948
949        // attach the texture and use it as the color buffer.
950        camera->attach(osg::Camera::COLOR_BUFFER, texture, 0, osg::TextureCubeMap::POSITIVE_Z);
951
952        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd::rotate(osg::inDegrees(-90.0f), 1.0,0.0,0.0));
953    }
954
955    // left face
956    {
957        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
958        camera->setName("Left face camera");
959        camera->setGraphicsContext(gc.get());
960        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
961        camera->setDrawBuffer(buffer);
962        camera->setReadBuffer(buffer);
963        camera->setAllowEventFocus(false);
964
965        // tell the camera to use OpenGL frame buffer object where supported.
966        camera->setRenderTargetImplementation(renderTargetImplementation);
967
968        // attach the texture and use it as the color buffer.
969        camera->attach(osg::Camera::COLOR_BUFFER, texture, 0, osg::TextureCubeMap::NEGATIVE_X);
970
971        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd::rotate(osg::inDegrees(-90.0f), 0.0,1.0,0.0) * osg::Matrixd::rotate(osg::inDegrees(-90.0f), 0.0,0.0,1.0));
972    }
973
974    // right face
975    {
976        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
977        camera->setName("Right face camera");
978        camera->setGraphicsContext(gc.get());
979        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
980        camera->setDrawBuffer(buffer);
981        camera->setReadBuffer(buffer);
982        camera->setAllowEventFocus(false);
983
984        // tell the camera to use OpenGL frame buffer object where supported.
985        camera->setRenderTargetImplementation(renderTargetImplementation);
986
987        // attach the texture and use it as the color buffer.
988        camera->attach(osg::Camera::COLOR_BUFFER, texture, 0, osg::TextureCubeMap::POSITIVE_X);
989
990        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd::rotate(osg::inDegrees(90.0f), 0.0,1.0,0.0 ) * osg::Matrixd::rotate(osg::inDegrees(90.0f), 0.0,0.0,1.0));
991    }
992
993    // bottom face
994    {
995        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
996        camera->setGraphicsContext(gc.get());
997        camera->setName("Bottom face camera");
998        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
999        camera->setDrawBuffer(buffer);
1000        camera->setReadBuffer(buffer);
1001        camera->setAllowEventFocus(false);
1002
1003        // tell the camera to use OpenGL frame buffer object where supported.
1004        camera->setRenderTargetImplementation(renderTargetImplementation);
1005
1006        // attach the texture and use it as the color buffer.
1007        camera->attach(osg::Camera::COLOR_BUFFER, texture, 0, osg::TextureCubeMap::NEGATIVE_Z);
1008
1009        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd::rotate(osg::inDegrees(90.0f), 1.0,0.0,0.0) * osg::Matrixd::rotate(osg::inDegrees(180.0f), 0.0,0.0,1.0));
1010    }
1011
1012    // back face
1013    {
1014        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
1015        camera->setName("Back face camera");
1016        camera->setGraphicsContext(gc.get());
1017        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
1018        camera->setDrawBuffer(buffer);
1019        camera->setReadBuffer(buffer);
1020        camera->setAllowEventFocus(false);
1021
1022        // tell the camera to use OpenGL frame buffer object where supported.
1023        camera->setRenderTargetImplementation(renderTargetImplementation);
1024
1025        // attach the texture and use it as the color buffer.
1026        camera->attach(osg::Camera::COLOR_BUFFER, texture, 0, osg::TextureCubeMap::NEGATIVE_Y);
1027
1028        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd::rotate(osg::inDegrees(180.0f), 1.0,0.0,0.0));
1029    }
1030
1031    getCamera()->setProjectionMatrixAsPerspective(90.0f, 1.0, 1, 1000.0);
1032
1033    // distortion correction set up.
1034    {
1035        osg::Geode* geode = new osg::Geode();
1036        geode->addDrawable(create3DSphericalDisplayDistortionMesh(osg::Vec3(0.0f,0.0f,0.0f), osg::Vec3(width,0.0f,0.0f), osg::Vec3(0.0f,height,0.0f), radius, collar, applyIntensityMapAsColours ? intensityMap : 0, projectorMatrix));
1037
1038        // new we need to add the texture to the mesh, we do so by creating a
1039        // StateSet to contain the Texture StateAttribute.
1040        osg::StateSet* stateset = geode->getOrCreateStateSet();
1041        stateset->setTextureAttributeAndModes(0, texture,osg::StateAttribute::ON);
1042        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
1043
1044        if (!applyIntensityMapAsColours && intensityMap)
1045        {
1046            stateset->setTextureAttributeAndModes(1, new osg::Texture2D(intensityMap), osg::StateAttribute::ON);
1047        }
1048
1049        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
1050        camera->setGraphicsContext(gc.get());
1051        camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
1052        camera->setClearColor( osg::Vec4(0.0,0.0,0.0,1.0) );
1053        camera->setViewport(new osg::Viewport(0, 0, width, height));
1054        GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
1055        camera->setDrawBuffer(buffer);
1056        camera->setReadBuffer(buffer);
1057        camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF);
1058        camera->setAllowEventFocus(false);
1059        camera->setInheritanceMask(camera->getInheritanceMask() & ~osg::CullSettings::CLEAR_COLOR & ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE);
1060        //camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1061
1062        camera->setProjectionMatrixAsOrtho2D(0,width,0,height);
1063        camera->setViewMatrix(osg::Matrix::identity());
1064
1065        // add subgraph to render
1066        camera->addChild(geode);
1067
1068        camera->setName("DistortionCorrectionCamera");
1069
1070        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd(), false);
1071    }
1072
1073    getCamera()->setNearFarRatio(0.0001f);
1074
1075    if (getLightingMode()==osg::View::HEADLIGHT)
1076    {
1077        // set a local light source for headlight to ensure that lighting is consistent across sides of cube.
1078        getLight()->setPosition(osg::Vec4(0.0f,0.0f,0.0f,1.0f));
1079    }
1080}
1081
1082static osg::Geometry* createParoramicSphericalDisplayDistortionMesh(const osg::Vec3& origin, const osg::Vec3& widthVector, const osg::Vec3& heightVector, double sphere_radius, double collar_radius, osg::Image* intensityMap, const osg::Matrix& projectorMatrix)
1083{
1084    osg::Vec3d center(0.0,0.0,0.0);
1085    osg::Vec3d eye(0.0,0.0,0.0);
1086
1087    double distance = sqrt(sphere_radius*sphere_radius - collar_radius*collar_radius);
1088    bool flip = false;
1089    bool texcoord_flip = false;
1090
1091    osg::Vec3d projector = eye - osg::Vec3d(0.0,0.0, distance);
1092
1093
1094    OSG_INFO<<"createParoramicSphericalDisplayDistortionMesh : Projector position = "<<projector<<std::endl;
1095    OSG_INFO<<"createParoramicSphericalDisplayDistortionMesh : distance = "<<distance<<std::endl;
1096
1097    // create the quad to visualize.
1098    osg::Geometry* geometry = new osg::Geometry();
1099
1100    geometry->setSupportsDisplayList(false);
1101
1102    osg::Vec3 xAxis(widthVector);
1103    float width = widthVector.length();
1104    xAxis /= width;
1105
1106    osg::Vec3 yAxis(heightVector);
1107    float height = heightVector.length();
1108    yAxis /= height;
1109
1110    int noSteps = 160;
1111
1112    osg::Vec3Array* vertices = new osg::Vec3Array;
1113    osg::Vec2Array* texcoords0 = new osg::Vec2Array;
1114    osg::Vec2Array* texcoords1 = intensityMap==0 ? new osg::Vec2Array : 0;
1115    osg::Vec4Array* colors = new osg::Vec4Array;
1116
1117    osg::Vec3 top = origin + yAxis*height;
1118
1119    osg::Vec3 screenCenter = origin + widthVector*0.5f + heightVector*0.5f;
1120    float screenRadius = heightVector.length() * 0.5f;
1121
1122    geometry->getOrCreateStateSet()->setMode(GL_CULL_FACE, osg::StateAttribute::OFF | osg::StateAttribute::PROTECTED);
1123
1124    for(int i=0;i<noSteps;++i)
1125    {
1126        for(int j=0;j<noSteps;++j)
1127        {
1128            osg::Vec2 texcoord(double(i)/double(noSteps-1), double(j)/double(noSteps-1));
1129            double theta = texcoord.x() * 2.0 * osg::PI;
1130            double phi = (1.0-texcoord.y()) * osg::PI;
1131
1132            if (texcoord_flip) texcoord.y() = 1.0f - texcoord.y();
1133
1134            osg::Vec3 pos(sin(phi)*sin(theta), sin(phi)*cos(theta), cos(phi));
1135            pos = pos*projectorMatrix;
1136
1137            double alpha = atan2(pos.x(), pos.y());
1138            if (alpha<0.0) alpha += 2.0*osg::PI;
1139
1140            double beta = atan2(sqrt(pos.x()*pos.x() + pos.y()*pos.y()), pos.z());
1141            if (beta<0.0) beta += 2.0*osg::PI;
1142
1143            double gamma = atan2(sqrt(double(pos.x()*pos.x() + pos.y()*pos.y())), double(pos.z()+distance));
1144            if (gamma<0.0) gamma += 2.0*osg::PI;
1145
1146
1147            osg::Vec3 v = screenCenter + osg::Vec3(sin(alpha)*gamma*2.0/osg::PI, -cos(alpha)*gamma*2.0/osg::PI, 0.0f)*screenRadius;
1148
1149            if (flip)
1150                vertices->push_back(osg::Vec3(v.x(), top.y()-(v.y()-origin.y()),v.z()));
1151            else
1152                vertices->push_back(v);
1153
1154            texcoords0->push_back( texcoord );
1155
1156            osg::Vec2 texcoord1(alpha/(2.0*osg::PI), 1.0f - beta/osg::PI);
1157            if (intensityMap)
1158            {
1159                colors->push_back(intensityMap->getColor(texcoord1));
1160            }
1161            else
1162            {
1163                colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
1164                if (texcoords1) texcoords1->push_back( texcoord1 );
1165            }
1166
1167
1168        }
1169    }
1170
1171
1172    // pass the created vertex array to the points geometry object.
1173    geometry->setVertexArray(vertices);
1174
1175    geometry->setColorArray(colors);
1176    geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
1177
1178    geometry->setTexCoordArray(0,texcoords0);
1179    if (texcoords1) geometry->setTexCoordArray(1,texcoords1);
1180
1181    osg::DrawElementsUShort* elements = new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLES);
1182    geometry->addPrimitiveSet(elements);
1183
1184    for(int i=0;i<noSteps-1;++i)
1185    {
1186        for(int j=0;j<noSteps-1;++j)
1187        {
1188            int i1 = j+(i+1)*noSteps;
1189            int i2 = j+(i)*noSteps;
1190            int i3 = j+1+(i)*noSteps;
1191            int i4 = j+1+(i+1)*noSteps;
1192
1193            osg::Vec3& v1 = (*vertices)[i1];
1194            osg::Vec3& v2 = (*vertices)[i2];
1195            osg::Vec3& v3 = (*vertices)[i3];
1196            osg::Vec3& v4 = (*vertices)[i4];
1197
1198            if ((v1-screenCenter).length()>screenRadius) continue;
1199            if ((v2-screenCenter).length()>screenRadius) continue;
1200            if ((v3-screenCenter).length()>screenRadius) continue;
1201            if ((v4-screenCenter).length()>screenRadius) continue;
1202
1203            elements->push_back(i1);
1204            elements->push_back(i2);
1205            elements->push_back(i3);
1206
1207            elements->push_back(i1);
1208            elements->push_back(i3);
1209            elements->push_back(i4);
1210        }
1211    }
1212
1213    return geometry;
1214}
1215
1216void View::setUpViewForPanoramicSphericalDisplay(double radius, double collar, unsigned int screenNum, osg::Image* intensityMap, const osg::Matrixd& projectorMatrix)
1217{
1218    OSG_INFO<<"View::setUpViewForPanoramicSphericalDisplay(rad="<<radius<<", cllr="<<collar<<", sn="<<screenNum<<", im="<<intensityMap<<")"<<std::endl;
1219
1220    osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
1221    if (!wsi)
1222    {
1223        OSG_NOTICE<<"Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
1224        return;
1225    }
1226
1227    osg::GraphicsContext::ScreenIdentifier si;
1228    si.readDISPLAY();
1229
1230    // displayNum has not been set so reset it to 0.
1231    if (si.displayNum<0) si.displayNum = 0;
1232
1233    si.screenNum = screenNum;
1234
1235    unsigned int width, height;
1236    wsi->getScreenResolution(si, width, height);
1237
1238    osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
1239    traits->hostName = si.hostName;
1240    traits->displayNum = si.displayNum;
1241    traits->screenNum = si.screenNum;
1242    traits->x = 0;
1243    traits->y = 0;
1244    traits->width = width;
1245    traits->height = height;
1246    traits->windowDecoration = false;
1247    traits->doubleBuffer = true;
1248    traits->sharedContext = 0;
1249
1250
1251    bool applyIntensityMapAsColours = true;
1252
1253    osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
1254    if (!gc)
1255    {
1256        OSG_NOTICE<<"GraphicsWindow has not been created successfully."<<std::endl;
1257        return;
1258    }
1259
1260    int tex_width = width;
1261    int tex_height = height;
1262
1263    int camera_width = tex_width;
1264    int camera_height = tex_height;
1265
1266    osg::TextureRectangle* texture = new osg::TextureRectangle;
1267
1268    texture->setTextureSize(tex_width, tex_height);
1269    texture->setInternalFormat(GL_RGB);
1270    texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
1271    texture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
1272    texture->setWrap(osg::Texture::WRAP_S,osg::Texture::CLAMP_TO_EDGE);
1273    texture->setWrap(osg::Texture::WRAP_T,osg::Texture::CLAMP_TO_EDGE);
1274
1275#if 0
1276    osg::Camera::RenderTargetImplementation renderTargetImplementation = osg::Camera::SEPERATE_WINDOW;
1277    GLenum buffer = GL_FRONT;
1278#else
1279    osg::Camera::RenderTargetImplementation renderTargetImplementation = osg::Camera::FRAME_BUFFER_OBJECT;
1280    GLenum buffer = GL_FRONT;
1281#endif
1282
1283    // front face
1284    {
1285        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
1286        camera->setName("Front face camera");
1287        camera->setGraphicsContext(gc.get());
1288        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
1289        camera->setDrawBuffer(buffer);
1290        camera->setReadBuffer(buffer);
1291        camera->setAllowEventFocus(false);
1292        // tell the camera to use OpenGL frame buffer object where supported.
1293        camera->setRenderTargetImplementation(renderTargetImplementation);
1294
1295        // attach the texture and use it as the color buffer.
1296        camera->attach(osg::Camera::COLOR_BUFFER, texture);
1297
1298        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd());
1299    }
1300
1301    // distortion correction set up.
1302    {
1303        osg::Geode* geode = new osg::Geode();
1304        geode->addDrawable(createParoramicSphericalDisplayDistortionMesh(osg::Vec3(0.0f,0.0f,0.0f), osg::Vec3(width,0.0f,0.0f), osg::Vec3(0.0f,height,0.0f), radius, collar, applyIntensityMapAsColours ? intensityMap : 0, projectorMatrix));
1305
1306        // new we need to add the texture to the mesh, we do so by creating a
1307        // StateSet to contain the Texture StateAttribute.
1308        osg::StateSet* stateset = geode->getOrCreateStateSet();
1309        stateset->setTextureAttributeAndModes(0, texture,osg::StateAttribute::ON);
1310        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
1311
1312        osg::TexMat* texmat = new osg::TexMat;
1313        texmat->setScaleByTextureRectangleSize(true);
1314        stateset->setTextureAttributeAndModes(0, texmat, osg::StateAttribute::ON);
1315
1316        if (!applyIntensityMapAsColours && intensityMap)
1317        {
1318            stateset->setTextureAttributeAndModes(1, new osg::Texture2D(intensityMap), osg::StateAttribute::ON);
1319        }
1320
1321        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
1322        camera->setGraphicsContext(gc.get());
1323        camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
1324        camera->setClearColor( osg::Vec4(0.0,0.0,0.0,1.0) );
1325        camera->setViewport(new osg::Viewport(0, 0, width, height));
1326        GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
1327        camera->setDrawBuffer(buffer);
1328        camera->setReadBuffer(buffer);
1329        camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF);
1330        camera->setAllowEventFocus(false);
1331        camera->setInheritanceMask(camera->getInheritanceMask() & ~osg::CullSettings::CLEAR_COLOR & ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE);
1332        //camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1333
1334        camera->setProjectionMatrixAsOrtho2D(0,width,0,height);
1335        camera->setViewMatrix(osg::Matrix::identity());
1336
1337        // add subgraph to render
1338        camera->addChild(geode);
1339
1340        camera->setName("DistortionCorrectionCamera");
1341
1342        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd(), false);
1343    }
1344}
1345
1346void View::setUpViewForWoWVxDisplay(unsigned int screenNum, unsigned char wow_content, unsigned char wow_factor, unsigned char wow_offset, float wow_disparity_Zd, float wow_disparity_vz, float wow_disparity_M, float wow_disparity_C)
1347{
1348    OSG_INFO<<"View::setUpViewForWoWVxDisplay(...)"<<std::endl;
1349
1350    osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
1351    if (!wsi)
1352    {
1353        OSG_NOTICE<<"Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
1354        return;
1355    }
1356
1357    osg::GraphicsContext::ScreenIdentifier si;
1358    si.readDISPLAY();
1359
1360    // displayNum has not been set so reset it to 0.
1361    if (si.displayNum<0) si.displayNum = 0;
1362
1363    si.screenNum = screenNum;
1364
1365    unsigned int width, height;
1366    wsi->getScreenResolution(si, width, height);
1367
1368    osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
1369    traits->hostName = si.hostName;
1370    traits->displayNum = si.displayNum;
1371    traits->screenNum = si.screenNum;
1372    traits->x = 0;
1373    traits->y = 0;
1374    traits->width = width;
1375    traits->height = height;
1376    traits->windowDecoration = false;
1377    traits->doubleBuffer = true;
1378    traits->sharedContext = 0;
1379
1380
1381    osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
1382    if (!gc)
1383    {
1384        OSG_NOTICE<<"GraphicsWindow has not been created successfully."<<std::endl;
1385        return;
1386    }
1387
1388    int tex_width = width;
1389    int tex_height = height;
1390
1391    int camera_width = tex_width;
1392    int camera_height = tex_height;
1393
1394    osg::Texture2D* texture = new osg::Texture2D;
1395    texture->setTextureSize(tex_width, tex_height);
1396    texture->setInternalFormat(GL_RGB);
1397    texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
1398    texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
1399
1400    osg::Texture2D* textureD = new osg::Texture2D;
1401    textureD->setTextureSize(tex_width, tex_height);
1402    textureD->setInternalFormat(GL_DEPTH_COMPONENT);
1403    textureD->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
1404    textureD->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
1405
1406#if 0
1407    osg::Camera::RenderTargetImplementation renderTargetImplementation = osg::Camera::SEPERATE_WINDOW;
1408    GLenum buffer = GL_FRONT;
1409#else
1410    osg::Camera::RenderTargetImplementation renderTargetImplementation = osg::Camera::FRAME_BUFFER_OBJECT;
1411    GLenum buffer = GL_FRONT;
1412#endif
1413
1414    // front face
1415    {
1416        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
1417        camera->setName("Front face camera");
1418        camera->setGraphicsContext(gc.get());
1419        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
1420        camera->setDrawBuffer(buffer);
1421        camera->setReadBuffer(buffer);
1422        camera->setAllowEventFocus(false);
1423        // tell the camera to use OpenGL frame buffer object where supported.
1424        camera->setRenderTargetImplementation(renderTargetImplementation);
1425
1426        // attach the texture and use it as the color buffer.
1427        camera->attach(osg::Camera::COLOR_BUFFER, texture);
1428        camera->attach(osg::Camera::DEPTH_BUFFER, textureD);
1429
1430        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd());
1431    }
1432
1433    // WoW display set up.
1434    {
1435        osg::Texture1D *textureHeader = new osg::Texture1D();
1436        // Set up the header
1437        {
1438            unsigned char header[]= {0xF1,wow_content,wow_factor,wow_offset,0x00,0x00,0x00,0x00,0x00,0x00};
1439            // Calc the CRC32
1440            {
1441                unsigned long _register = 0;
1442                for(int i = 0; i < 10; ++i) {
1443                    unsigned char mask = 0x80;
1444                    unsigned char byte = header[i];
1445                    for (int j = 0; j < 8; ++j)
1446                    {
1447                        bool topBit = (_register & 0x80000000) != 0;
1448                        _register <<= 1;
1449                        _register ^= ((byte & mask) != 0? 0x1: 0x0);
1450                        if (topBit)
1451                        {
1452                            _register ^= 0x04c11db7;
1453                        }
1454                        mask >>= 1;
1455                    }
1456                }
1457                unsigned char *p = (unsigned char*) &_register;
1458                for(size_t i = 0; i < 4; ++i)
1459                {
1460                    header[i+6] = p[3-i];
1461                }
1462            }
1463
1464            osg::ref_ptr<osg::Image> imageheader = new osg::Image();
1465            imageheader->allocateImage(256,1,1,GL_LUMINANCE,GL_UNSIGNED_BYTE);
1466            {
1467                unsigned char *cheader = imageheader->data();
1468                for (int x=0; x<256; ++x){
1469                    cheader[x] = 0;
1470                }
1471                for (int x=0; x<=9; ++x){
1472                    for (int y=7; y>=0; --y){
1473                        int i = 2*(7-y)+16*x;
1474                        cheader[i] = (((1<<(y))&(header[x])) << (7-(y)));
1475                    }
1476                }
1477            }
1478            textureHeader->setImage(imageheader.get());
1479        }
1480
1481        // Create the Screen Aligned Quad
1482        osg::Geode* geode = new osg::Geode();
1483        {
1484            osg::Geometry* geom = new osg::Geometry;
1485
1486            osg::Vec3Array* vertices = new osg::Vec3Array;
1487            vertices->push_back(osg::Vec3(0,height,0));
1488            vertices->push_back(osg::Vec3(0,0,0));
1489            vertices->push_back(osg::Vec3(width,0,0));
1490            vertices->push_back(osg::Vec3(width,height,0));
1491            geom->setVertexArray(vertices);
1492
1493            osg::Vec2Array* tex = new osg::Vec2Array;
1494            tex->push_back(osg::Vec2(0,1));
1495            tex->push_back(osg::Vec2(0,0));
1496            tex->push_back(osg::Vec2(1,0));
1497            tex->push_back(osg::Vec2(1,1));
1498            geom->setTexCoordArray(0,tex);
1499
1500            geom->addPrimitiveSet(new osg::DrawArrays(GL_QUADS,0,4));
1501            geode->addDrawable(geom);
1502
1503            // new we need to add the textures to the quad, and setting up the shader.
1504            osg::StateSet* stateset = geode->getOrCreateStateSet();
1505            stateset->setTextureAttributeAndModes(0, textureHeader,osg::StateAttribute::ON);
1506            stateset->setTextureAttributeAndModes(1, texture,osg::StateAttribute::ON);
1507            stateset->setTextureAttributeAndModes(2, textureD,osg::StateAttribute::ON);
1508            stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
1509
1510            osg::ref_ptr<osg::Program> programShader = new osg::Program();
1511            stateset->setAttribute(programShader.get(), osg::StateAttribute::ON);
1512            stateset->addUniform( new osg::Uniform("wow_width", (int)width));
1513            stateset->addUniform( new osg::Uniform("wow_height", (int)height));
1514            stateset->addUniform( new osg::Uniform("wow_disparity_M", wow_disparity_M));
1515            stateset->addUniform( new osg::Uniform("wow_disparity_Zd", wow_disparity_Zd));
1516            stateset->addUniform( new osg::Uniform("wow_disparity_vz", wow_disparity_vz));
1517            stateset->addUniform( new osg::Uniform("wow_disparity_C", wow_disparity_C));
1518
1519            stateset->addUniform(new osg::Uniform("wow_header", 0));
1520            stateset->addUniform(new osg::Uniform("wow_tcolor", 1));
1521            stateset->addUniform(new osg::Uniform("wow_tdepth", 2));
1522
1523            osg::Shader *frag = new osg::Shader(osg::Shader::FRAGMENT);
1524            frag->setShaderSource(" "\
1525                    " uniform sampler1D wow_header;                                                                                   " \
1526                    " uniform sampler2D wow_tcolor;                                                                                   " \
1527                    " uniform sampler2D wow_tdepth;                                                                                   " \
1528                    "                                                                                                                 " \
1529                    " uniform int wow_width;                                                                                          " \
1530                    " uniform int wow_height;                                                                                         " \
1531                    " uniform float wow_disparity_M;                                                                                  " \
1532                    " uniform float wow_disparity_Zd;                                                                                 " \
1533                    " uniform float wow_disparity_vz;                                                                                 " \
1534                    " uniform float wow_disparity_C;                                                                                  " \
1535                    "                                                                                                                 " \
1536                    " float disparity(float Z)                                                                                        " \
1537                    " {                                                                                                               " \
1538                    "     return (wow_disparity_M*(1.0-(wow_disparity_vz/(Z-wow_disparity_Zd+wow_disparity_vz)))                        " \
1539                    "                   + wow_disparity_C) / 255.0;                                                                   " \
1540                    " }                                                                                                               " \
1541                    "                                                                                                                 " \
1542                    " void main()                                                                                                     " \
1543                    " {                                                                                                               " \
1544                    "       vec2 pos = (gl_FragCoord.xy / vec2(wow_width/2,wow_height) );                                             " \
1545                    "         if (gl_FragCoord.x > float(wow_width/2))                                                                  " \
1546                    "         {                                                                                                         " \
1547                    "             gl_FragColor = vec4(disparity(( texture2D(wow_tdepth, pos - vec2(1,0))).z));                          " \
1548                    "         }                                                                                                         " \
1549                    "         else{                                                                                                     " \
1550                    "             gl_FragColor = texture2D(wow_tcolor, pos);                                                            " \
1551                    "         }                                                                                                         " \
1552                    "     if ( (gl_FragCoord.y >= float(wow_height-1)) && (gl_FragCoord.x < 256.0) )                                    " \
1553                    "     {                                                                                                             " \
1554                    "         float pos = gl_FragCoord.x/256.0;                                                                         " \
1555                    "         float blue = texture1D(wow_header, pos).b;                                                                " \
1556                    "         if ( blue < 0.5)                                                                                          " \
1557                    "             gl_FragColor.b = 0.0;                                                                                 " \
1558                    "         else                                                                                                      " \
1559                    "             gl_FragColor.b = 1.0;                                                                                 " \
1560                    "     }                                                                                                             " \
1561                    " }                                                                                                               " );
1562
1563            programShader->addShader(frag);
1564        }
1565
1566        // Create the Camera
1567        {
1568            osg::ref_ptr<osg::Camera> camera = new osg::Camera;
1569            camera->setGraphicsContext(gc.get());
1570            camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
1571            camera->setClearColor( osg::Vec4(0.0,0.0,0.0,1.0) );
1572            camera->setViewport(new osg::Viewport(0, 0, width, height));
1573            GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
1574            camera->setDrawBuffer(buffer);
1575            camera->setReadBuffer(buffer);
1576            camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF);
1577            camera->setAllowEventFocus(false);
1578            camera->setInheritanceMask(camera->getInheritanceMask() & ~osg::CullSettings::CLEAR_COLOR & ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE);
1579            //camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1580
1581            camera->setProjectionMatrixAsOrtho2D(0,width,0,height);
1582            camera->setViewMatrix(osg::Matrix::identity());
1583
1584            // add subgraph to render
1585            camera->addChild(geode);
1586
1587            camera->setName("WoWCamera");
1588
1589            addSlave(camera.get(), osg::Matrixd(), osg::Matrixd(), false);
1590        }
1591    }
1592}
1593
1594DepthPartitionSettings::DepthPartitionSettings(DepthMode mode):
1595    _mode(mode),
1596    _zNear(1.0), _zMid(5.0), _zFar(1000.0)
1597{}
1598
1599bool DepthPartitionSettings::getDepthRange(osg::View& view, unsigned int partition, double& zNear, double& zFar)
1600{
1601    switch(_mode)
1602    {
1603        case(FIXED_RANGE):
1604        {
1605            if (partition==0)
1606            {
1607                zNear = _zNear;
1608                zFar = _zMid;
1609                return true;
1610            }
1611            else if (partition==1)
1612            {
1613                zNear = _zMid;
1614                zFar = _zFar;
1615                return true;
1616            }
1617            return false;
1618        }
1619        case(BOUNDING_VOLUME):
1620        {
1621            osgViewer::View* view_withSceneData = dynamic_cast<osgViewer::View*>(&view);
1622            const osg::Node* node = view_withSceneData ? view_withSceneData->getSceneData() : 0;
1623            if (!node) return false;
1624
1625            const osg::Camera* masterCamera = view.getCamera();
1626            if (!masterCamera) return false;
1627
1628            osg::BoundingSphere bs = node->getBound();
1629            const osg::Matrixd& viewMatrix = masterCamera->getViewMatrix();
1630            //osg::Matrixd& projectionMatrix = masterCamera->getProjectionMatrix();
1631
1632            osg::Vec3d lookVectorInWorldCoords = osg::Matrixd::transform3x3(viewMatrix,osg::Vec3d(0.0,0.0,-1.0));
1633            lookVectorInWorldCoords.normalize();
1634
1635            osg::Vec3d nearPointInWorldCoords = bs.center() - lookVectorInWorldCoords*bs.radius();
1636            osg::Vec3d farPointInWorldCoords = bs.center() + lookVectorInWorldCoords*bs.radius();
1637
1638            osg::Vec3d nearPointInEyeCoords = nearPointInWorldCoords * viewMatrix;
1639            osg::Vec3d farPointInEyeCoords = farPointInWorldCoords * viewMatrix;
1640
1641#if 0
1642            OSG_NOTICE<<std::endl;
1643            OSG_NOTICE<<"viewMatrix = "<<viewMatrix<<std::endl;
1644            OSG_NOTICE<<"lookVectorInWorldCoords = "<<lookVectorInWorldCoords<<std::endl;
1645            OSG_NOTICE<<"nearPointInWorldCoords = "<<nearPointInWorldCoords<<std::endl;
1646            OSG_NOTICE<<"farPointInWorldCoords = "<<farPointInWorldCoords<<std::endl;
1647            OSG_NOTICE<<"nearPointInEyeCoords = "<<nearPointInEyeCoords<<std::endl;
1648            OSG_NOTICE<<"farPointInEyeCoords = "<<farPointInEyeCoords<<std::endl;
1649#endif
1650            double minZNearRatio = 0.00001;
1651
1652
1653            if (masterCamera->getDisplaySettings())
1654            {
1655                OSG_NOTICE<<"Has display settings"<<std::endl;
1656            }
1657
1658            double scene_zNear = -nearPointInEyeCoords.z();
1659            double scene_zFar = -farPointInEyeCoords.z();
1660            if (scene_zNear<=0.0) scene_zNear = minZNearRatio * scene_zFar;
1661
1662            double scene_zMid = sqrt(scene_zFar*scene_zNear);
1663
1664#if 0
1665            OSG_NOTICE<<"scene_zNear = "<<scene_zNear<<std::endl;
1666            OSG_NOTICE<<"scene_zMid = "<<scene_zMid<<std::endl;
1667            OSG_NOTICE<<"scene_zFar = "<<scene_zFar<<std::endl;
1668#endif
1669            if (partition==0)
1670            {
1671                zNear = scene_zNear;
1672                zFar = scene_zMid;
1673                return true;
1674            }
1675            else if (partition==1)
1676            {
1677                zNear = scene_zMid;
1678                zFar = scene_zFar;
1679                return true;
1680            }
1681
1682            return false;
1683        }
1684        default: return false;
1685    }
1686}
1687
1688namespace osgDepthPartition {
1689
1690struct MyUpdateSlaveCallback : public osg::View::Slave::UpdateSlaveCallback
1691{
1692    MyUpdateSlaveCallback(DepthPartitionSettings* dps, unsigned int partition):_dps(dps), _partition(partition) {}
1693
1694    virtual void updateSlave(osg::View& view, osg::View::Slave& slave)
1695    {
1696        slave.updateSlaveImplementation(view);
1697
1698        if (!_dps) return;
1699
1700        osg::Camera* camera = slave._camera.get();
1701
1702        double computed_zNear;
1703        double computed_zFar;
1704        if (!_dps->getDepthRange(view, _partition, computed_zNear, computed_zFar))
1705        {
1706            OSG_NOTICE<<"Switching off Camera "<<camera<<std::endl;
1707            camera->setNodeMask(0x0);
1708            return;
1709        }
1710        else
1711        {
1712            camera->setNodeMask(0xffffff);
1713        }
1714
1715        if (camera->getProjectionMatrix()(0,3)==0.0 &&
1716            camera->getProjectionMatrix()(1,3)==0.0 &&
1717            camera->getProjectionMatrix()(2,3)==0.0)
1718        {
1719            double left, right, bottom, top, zNear, zFar;
1720            camera->getProjectionMatrixAsOrtho(left, right, bottom, top, zNear, zFar);
1721            camera->setProjectionMatrixAsOrtho(left, right, bottom, top, computed_zNear, computed_zFar);
1722        }
1723        else
1724        {
1725            double left, right, bottom, top, zNear, zFar;
1726            camera->getProjectionMatrixAsFrustum(left, right, bottom, top, zNear, zFar);
1727
1728            double nr = computed_zNear / zNear;
1729            camera->setProjectionMatrixAsFrustum(left * nr, right * nr, bottom * nr, top * nr, computed_zNear, computed_zFar);
1730        }
1731    }
1732
1733    osg::ref_ptr<DepthPartitionSettings> _dps;
1734    unsigned int _partition;
1735};
1736
1737
1738typedef std::list< osg::ref_ptr<osg::Camera> > Cameras;
1739
1740Cameras getActiveCameras(osg::View& view)
1741{
1742    Cameras activeCameras;
1743
1744    if (view.getCamera() && view.getCamera()->getGraphicsContext())
1745    {
1746        activeCameras.push_back(view.getCamera());
1747    }
1748
1749    for(unsigned int i=0; i<view.getNumSlaves(); ++i)
1750    {
1751        osg::View::Slave& slave = view.getSlave(i);
1752        if (slave._camera.valid() && slave._camera->getGraphicsContext())
1753        {
1754            activeCameras.push_back(slave._camera.get());
1755        }
1756    }
1757    return activeCameras;
1758}
1759
1760}
1761
1762bool View::setUpDepthPartitionForCamera(osg::Camera* cameraToPartition, DepthPartitionSettings* incomming_dps)
1763{
1764    osg::ref_ptr<osg::GraphicsContext> context = cameraToPartition->getGraphicsContext();
1765    if (!context) return false;
1766
1767    osg::ref_ptr<osg::Viewport> viewport = cameraToPartition->getViewport();
1768    if (!viewport) return false;
1769
1770    osg::ref_ptr<DepthPartitionSettings> dps = incomming_dps;
1771    if (!dps) dps = new DepthPartitionSettings;
1772
1773    bool useMastersSceneData = true;
1774    osg::Matrixd projectionOffset;
1775    osg::Matrixd viewOffset;
1776
1777    if (getCamera()==cameraToPartition)
1778    {
1779        // replace main camera with depth partition cameras
1780        OSG_INFO<<"View::setUpDepthPartitionForCamera(..) Replacing main Camera"<<std::endl;
1781    }
1782    else
1783    {
1784        unsigned int i = findSlaveIndexForCamera(cameraToPartition);
1785        if (i>=getNumSlaves()) return false;
1786
1787        osg::View::Slave& slave = getSlave(i);
1788
1789        useMastersSceneData = slave._useMastersSceneData;
1790        projectionOffset = slave._projectionOffset;
1791        viewOffset = slave._viewOffset;
1792
1793        OSG_NOTICE<<"View::setUpDepthPartitionForCamera(..) Replacing slave Camera"<<i<<std::endl;
1794        removeSlave(i);
1795    }
1796
1797    cameraToPartition->setGraphicsContext(0);
1798    cameraToPartition->setViewport(0);
1799
1800    // far camera
1801    {
1802        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
1803        camera->setGraphicsContext(context.get());
1804        camera->setViewport(viewport.get());
1805
1806        camera->setDrawBuffer(cameraToPartition->getDrawBuffer());
1807        camera->setReadBuffer(cameraToPartition->getReadBuffer());
1808
1809        camera->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
1810        camera->setCullingMode(osg::Camera::ENABLE_ALL_CULLING);
1811
1812        addSlave(camera.get());
1813
1814        osg::View::Slave& slave = getSlave(getNumSlaves()-1);
1815
1816        slave._useMastersSceneData = useMastersSceneData;
1817        slave._projectionOffset = projectionOffset;
1818        slave._viewOffset = viewOffset;
1819        slave._updateSlaveCallback =  new osgDepthPartition::MyUpdateSlaveCallback(dps.get(), 1);
1820    }
1821
1822    // near camera
1823    {
1824        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
1825        camera->setGraphicsContext(context.get());
1826        camera->setViewport(viewport.get());
1827
1828        camera->setDrawBuffer(cameraToPartition->getDrawBuffer());
1829        camera->setReadBuffer(cameraToPartition->getReadBuffer());
1830
1831        camera->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
1832        camera->setCullingMode(osg::Camera::ENABLE_ALL_CULLING);
1833        camera->setClearMask(GL_DEPTH_BUFFER_BIT);
1834
1835        addSlave(camera.get());
1836
1837        osg::View::Slave& slave = getSlave(getNumSlaves()-1);
1838        slave._useMastersSceneData = useMastersSceneData;
1839        slave._projectionOffset = projectionOffset;
1840        slave._viewOffset = viewOffset;
1841        slave._updateSlaveCallback =  new osgDepthPartition::MyUpdateSlaveCallback(dps.get(), 0);
1842    }
1843
1844    return true;
1845}
1846
1847
1848
1849bool View::setUpDepthPartition(DepthPartitionSettings* dsp)
1850{
1851    osgDepthPartition::Cameras originalCameras = osgDepthPartition::getActiveCameras(*this);
1852    if (originalCameras.empty())
1853    {
1854        OSG_INFO<<"osgView::View::setUpDepthPartition(,..), no windows assigned, doing view.setUpViewAcrossAllScreens()"<<std::endl;
1855        setUpViewAcrossAllScreens();
1856
1857        originalCameras = osgDepthPartition::getActiveCameras(*this);
1858        if (originalCameras.empty())
1859        {
1860            OSG_NOTICE<<"osgView::View::setUpDepthPartition(View,..) Unable to set up windows for viewer."<<std::endl;
1861            return false;
1862        }
1863    }
1864
1865    bool threadsWereRunning = getViewerBase()->areThreadsRunning();
1866    if (threadsWereRunning) getViewerBase()->stopThreading();
1867
1868    for(osgDepthPartition::Cameras::iterator itr = originalCameras.begin();
1869        itr != originalCameras.end();
1870        ++itr)
1871    {
1872        setUpDepthPartitionForCamera(itr->get(), dsp);
1873    }
1874
1875    if (threadsWereRunning) getViewerBase()->startThreading();
1876
1877    return true;
1878}
1879
1880
1881void View::assignSceneDataToCameras()
1882{
1883    // OSG_NOTICE<<"View::assignSceneDataToCameras()"<<std::endl;
1884
1885    if (_scene.valid() && _scene->getDatabasePager() && getViewerBase())
1886    {
1887        _scene->getDatabasePager()->setIncrementalCompileOperation(getViewerBase()->getIncrementalCompileOperation());
1888    }
1889
1890    osg::Node* sceneData = _scene.valid() ? _scene->getSceneData() : 0;
1891
1892    if (_cameraManipulator.valid())
1893    {
1894        _cameraManipulator->setNode(sceneData);
1895
1896        osg::ref_ptr<osgGA::GUIEventAdapter> dummyEvent = _eventQueue->createEvent();
1897
1898        _cameraManipulator->home(*dummyEvent, *this);
1899    }
1900
1901    if (_camera.valid())
1902    {
1903        _camera->removeChildren(0,_camera->getNumChildren());
1904        if (sceneData) _camera->addChild(sceneData);
1905
1906        Renderer* renderer = dynamic_cast<Renderer*>(_camera->getRenderer());
1907        if (renderer) renderer->setCompileOnNextDraw(true);
1908
1909    }
1910
1911    for(unsigned i=0; i<getNumSlaves(); ++i)
1912    {
1913        Slave& slave = getSlave(i);
1914        if (slave._camera.valid() && slave._useMastersSceneData)
1915        {
1916            slave._camera->removeChildren(0,slave._camera->getNumChildren());
1917            if (sceneData) slave._camera->addChild(sceneData);
1918
1919            Renderer* renderer = dynamic_cast<Renderer*>(slave._camera->getRenderer());
1920            if (renderer) renderer->setCompileOnNextDraw(true);
1921        }
1922    }
1923}
1924
1925void View::requestRedraw()
1926{
1927    if (getViewerBase())
1928    {
1929        getViewerBase()->_requestRedraw = true;
1930    }
1931    else
1932    {
1933        OSG_INFO<<"View::requestRedraw(), No viewer base has been assigned yet."<<std::endl;
1934    }
1935}
1936
1937void View::requestContinuousUpdate(bool flag)
1938{
1939    if (getViewerBase())
1940    {
1941        getViewerBase()->_requestContinousUpdate = flag;
1942    }
1943    else
1944    {
1945        OSG_INFO<<"View::requestContinuousUpdate(), No viewer base has been assigned yet."<<std::endl;
1946    }
1947}
1948
1949void View::requestWarpPointer(float x,float y)
1950{
1951    OSG_INFO<<"View::requestWarpPointer("<<x<<","<<y<<")"<<std::endl;
1952
1953    float local_x, local_y;
1954    const osg::Camera* camera = getCameraContainingPosition(x, y, local_x, local_y);
1955    if (camera)
1956    {
1957        const osgViewer::GraphicsWindow* gw = dynamic_cast<const osgViewer::GraphicsWindow*>(camera->getGraphicsContext());
1958        if (gw)
1959        {
1960            getEventQueue()->mouseWarped(x,y);
1961            if (gw->getEventQueue()->getCurrentEventState()->getMouseYOrientation()==osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS)
1962            {
1963                local_y = gw->getTraits()->height - local_y;
1964            }
1965            const_cast<osgViewer::GraphicsWindow*>(gw)->getEventQueue()->mouseWarped(local_x,local_y);
1966            const_cast<osgViewer::GraphicsWindow*>(gw)->requestWarpPointer(local_x, local_y);
1967        }
1968    }
1969    else
1970    {
1971        OSG_INFO<<"View::requestWarpPointer failed no camera containing pointer"<<std::endl;
1972    }
1973}
1974
1975bool View::containsCamera(const osg::Camera* camera) const
1976{
1977    if (_camera == camera) return true;
1978
1979    for(unsigned i=0; i<getNumSlaves(); ++i)
1980    {
1981        const Slave& slave = getSlave(i);
1982        if (slave._camera == camera) return true;
1983    }
1984    return false;
1985}
1986
1987const osg::Camera* View::getCameraContainingPosition(float x, float y, float& local_x, float& local_y) const
1988{
1989    const osgGA::GUIEventAdapter* eventState = getEventQueue()->getCurrentEventState();
1990    const osgViewer::GraphicsWindow* gw = dynamic_cast<const osgViewer::GraphicsWindow*>(eventState->getGraphicsContext());
1991
1992    bool view_invert_y = eventState->getMouseYOrientation()==osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS;
1993
1994    double epsilon = 0.5;
1995
1996    if (_camera->getGraphicsContext() &&
1997        (!gw || _camera->getGraphicsContext()==gw) &&
1998        _camera->getViewport())
1999    {
2000        const osg::Viewport* viewport = _camera->getViewport();
2001
2002        double new_x = x;
2003        double new_y = y;
2004
2005        if (!gw)
2006        {
2007            new_x = static_cast<double>(_camera->getGraphicsContext()->getTraits()->width) * (x - eventState->getXmin())/(eventState->getXmax()-eventState->getXmin());
2008            new_y = view_invert_y ?
2009                       static_cast<double>(_camera->getGraphicsContext()->getTraits()->height) * (1.0 - (y- eventState->getYmin())/(eventState->getYmax()-eventState->getYmin())) :
2010                       static_cast<double>(_camera->getGraphicsContext()->getTraits()->height) * (y - eventState->getYmin())/(eventState->getYmax()-eventState->getYmin());
2011        }
2012
2013        if (viewport &&
2014            new_x >= (viewport->x()-epsilon) && new_y >= (viewport->y()-epsilon) &&
2015            new_x < (viewport->x()+viewport->width()-1.0+epsilon) && new_y <= (viewport->y()+viewport->height()-1.0+epsilon) )
2016        {
2017            local_x = new_x;
2018            local_y = new_y;
2019
2020            OSG_INFO<<"Returning master camera"<<std::endl;
2021
2022            return _camera.get();
2023        }
2024    }
2025
2026    osg::Matrix masterCameraVPW = getCamera()->getViewMatrix() * getCamera()->getProjectionMatrix();
2027
2028    // convert to non dimensional
2029    x = (x - eventState->getXmin()) * 2.0 / (eventState->getXmax()-eventState->getXmin()) - 1.0;
2030    y = (y - eventState->getYmin())* 2.0 / (eventState->getYmax()-eventState->getYmin()) - 1.0;
2031
2032    if (view_invert_y) y = - y;
2033
2034    for(int i=getNumSlaves()-1; i>=0; --i)
2035    {
2036        const Slave& slave = getSlave(i);
2037        if (slave._camera.valid() &&
2038            slave._camera->getAllowEventFocus() &&
2039            slave._camera->getRenderTargetImplementation()==osg::Camera::FRAME_BUFFER)
2040        {
2041            OSG_INFO<<"Testing slave camera "<<slave._camera->getName()<<std::endl;
2042
2043            const osg::Camera* camera = slave._camera.get();
2044            const osg::Viewport* viewport = camera ? camera->getViewport() : 0;
2045
2046            osg::Matrix localCameraVPW = camera->getViewMatrix() * camera->getProjectionMatrix();
2047            if (viewport) localCameraVPW *= viewport->computeWindowMatrix();
2048
2049            osg::Matrix matrix( osg::Matrix::inverse(masterCameraVPW) * localCameraVPW );
2050
2051            osg::Vec3d new_coord = osg::Vec3d(x,y,0.0) * matrix;
2052
2053            //OSG_NOTICE<<"  x="<<x<<" y="<<y<<std::endl;;
2054            //OSG_NOTICE<<"  eventState->getXmin()="<<eventState->getXmin()<<" eventState->getXmax()="<<eventState->getXmax()<<std::endl;;
2055            //OSG_NOTICE<<"  new_coord "<<new_coord<<std::endl;;
2056
2057            if (viewport &&
2058                new_coord.x() >= (viewport->x()-epsilon) && new_coord.y() >= (viewport->y()-epsilon) &&
2059                new_coord.x() < (viewport->x()+viewport->width()-1.0+epsilon) && new_coord.y() <= (viewport->y()+viewport->height()-1.0+epsilon) )
2060            {
2061                // OSG_NOTICE<<"  in viewport "<<std::endl;;
2062
2063                local_x = new_coord.x();
2064                local_y = new_coord.y();
2065
2066                return camera;
2067            }
2068            else
2069            {
2070                // OSG_NOTICE<<"  not in viewport "<<viewport->x()<<" "<<(viewport->x()+viewport->width())<<std::endl;;
2071            }
2072
2073        }
2074    }
2075
2076    local_x = x;
2077    local_y = y;
2078
2079    return 0;
2080}
2081
2082bool View::computeIntersections(float x,float y, osgUtil::LineSegmentIntersector::Intersections& intersections, osg::Node::NodeMask traversalMask)
2083{
2084    if (!_camera.valid()) return false;
2085
2086    float local_x, local_y = 0.0;
2087    const osg::Camera* camera = getCameraContainingPosition(x, y, local_x, local_y);
2088    if (!camera) camera = _camera.get();
2089
2090
2091    osgUtil::LineSegmentIntersector::CoordinateFrame cf = camera->getViewport() ? osgUtil::Intersector::WINDOW : osgUtil::Intersector::PROJECTION;
2092    osg::ref_ptr< osgUtil::LineSegmentIntersector > picker = new osgUtil::LineSegmentIntersector(cf, local_x, local_y);
2093
2094#if 0
2095    OSG_NOTICE<<"View::computeIntersections(x="<<x<<", y="<<y<<", local_x="<<local_x<<", local_y="<<local_y<<") "<<cf<<std::endl;
2096    OSG_NOTICE<<"  viewport ("<<camera->getViewport()->x()<<","<<camera->getViewport()->y()<<","<<camera->getViewport()->width()<<","<<camera->getViewport()->height()<<")"<<std::endl;
2097
2098    const osg::GraphicsContext::Traits* traits = camera->getGraphicsContext() ? camera->getGraphicsContext()->getTraits() : 0;
2099    if (traits)
2100    {
2101        OSG_NOTICE<<"  window ("<<traits->x<<","<<traits->y<<","<<traits->width<<","<<traits->height<<")"<<std::endl;
2102    }
2103#endif
2104
2105    osgUtil::IntersectionVisitor iv(picker.get());
2106    iv.setTraversalMask(traversalMask);
2107
2108
2109#if 1
2110    const_cast<osg::Camera*>(camera)->accept(iv);
2111#else
2112
2113    // timing test code paths for comparing KdTree based intersections vs conventional intersections
2114
2115    iv.setUseKdTreeWhenAvailable(true);
2116    iv.setDoDummyTraversal(true);
2117
2118    const_cast<osg::Camera*>(camera)->accept(iv);
2119
2120
2121    osg::Timer_t before = osg::Timer::instance()->tick();
2122    const_cast<osg::Camera*>(camera)->accept(iv);
2123
2124    osg::Timer_t after_dummy = osg::Timer::instance()->tick();
2125
2126    int intersectsBeforeKdTree = picker->getIntersections().size();
2127
2128    iv.setDoDummyTraversal(false);
2129    const_cast<osg::Camera*>(camera)->accept(iv);
2130    osg::Timer_t after_kdTree_2 = osg::Timer::instance()->tick();
2131
2132    int intersectsBeforeConventional = picker->getIntersections().size();
2133
2134    iv.setUseKdTreeWhenAvailable(false);
2135    const_cast<osg::Camera*>(camera)->accept(iv);
2136    osg::Timer_t after = osg::Timer::instance()->tick();
2137
2138    int intersectsAfterConventional = picker->getIntersections().size();
2139
2140    double timeDummy = osg::Timer::instance()->delta_m(before, after_dummy);
2141    double timeKdTree = osg::Timer::instance()->delta_m(after_dummy, after_kdTree_2);
2142    double timeConventional = osg::Timer::instance()->delta_m(after_kdTree_2, after);
2143
2144    OSG_NOTICE<<"Using Dummy                    "<<timeDummy<<std::endl;
2145    OSG_NOTICE<<"      KdTrees                  "<<timeKdTree
2146                            <<"\tNum intersects = "<<intersectsBeforeConventional-intersectsBeforeKdTree<<std::endl;
2147    OSG_NOTICE<<"      KdTrees - Traversal      "<<timeKdTree-timeDummy<<std::endl;
2148    OSG_NOTICE<<"      Conventional             "<<timeConventional
2149                            <<"\tNum intersects = "<<intersectsAfterConventional-intersectsBeforeConventional<<std::endl;
2150    OSG_NOTICE<<"      Conventional - Traversal "<<timeConventional-timeDummy<<std::endl;
2151    OSG_NOTICE<<"      Delta                    "<<timeConventional/timeKdTree<<std::endl;
2152    OSG_NOTICE<<"      Delta sans Traversal     "<<(timeConventional-timeDummy)/(timeKdTree-timeDummy)<<std::endl;
2153    OSG_NOTICE<<std::endl;
2154#endif
2155
2156    if (picker->containsIntersections())
2157    {
2158        intersections = picker->getIntersections();
2159        return true;
2160    }
2161    else
2162    {
2163        intersections.clear();
2164        return false;
2165    }
2166}
2167
2168bool View::computeIntersections(float x,float y, const osg::NodePath& nodePath, osgUtil::LineSegmentIntersector::Intersections& intersections,osg::Node::NodeMask traversalMask)
2169{
2170    if (!_camera.valid() || nodePath.empty()) return false;
2171
2172    float local_x, local_y = 0.0;
2173    const osg::Camera* camera = getCameraContainingPosition(x, y, local_x, local_y);
2174    if (!camera) camera = _camera.get();
2175
2176    osg::Matrixd matrix;
2177    if (nodePath.size()>1)
2178    {
2179        osg::NodePath prunedNodePath(nodePath.begin(),nodePath.end()-1);
2180        matrix = osg::computeLocalToWorld(prunedNodePath);
2181    }
2182
2183    matrix.postMult(camera->getViewMatrix());
2184    matrix.postMult(camera->getProjectionMatrix());
2185
2186    double zNear = -1.0;
2187    double zFar = 1.0;
2188    if (camera->getViewport())
2189    {
2190        matrix.postMult(camera->getViewport()->computeWindowMatrix());
2191        zNear = 0.0;
2192        zFar = 1.0;
2193    }
2194
2195    osg::Matrixd inverse;
2196    inverse.invert(matrix);
2197
2198    osg::Vec3d startVertex = osg::Vec3d(local_x,local_y,zNear) * inverse;
2199    osg::Vec3d endVertex = osg::Vec3d(local_x,local_y,zFar) * inverse;
2200
2201    osg::ref_ptr< osgUtil::LineSegmentIntersector > picker = new osgUtil::LineSegmentIntersector(osgUtil::Intersector::MODEL, startVertex, endVertex);
2202
2203    osgUtil::IntersectionVisitor iv(picker.get());
2204    iv.setTraversalMask(traversalMask);
2205    nodePath.back()->accept(iv);
2206
2207    if (picker->containsIntersections())
2208    {
2209        intersections = picker->getIntersections();
2210        return true;
2211    }
2212    else
2213    {
2214        intersections.clear();
2215        return false;
2216    }
2217}
2218
2219
2220void View::addDevice(osgGA::Device* eventSource)
2221{
2222    Devices::iterator itr = std::find( _eventSources.begin(), _eventSources.end(), eventSource );
2223    if (itr==_eventSources.end())
2224    {
2225        _eventSources.push_back(eventSource);
2226    }
2227}
2228
2229void View::removeDevice(osgGA::Device* eventSource)
2230{
2231    Devices::iterator itr = std::find( _eventSources.begin(), _eventSources.end(), eventSource );
2232    if (itr!=_eventSources.end())
2233    {
2234        _eventSources.erase(itr);
2235    }
2236}
Note: See TracBrowser for help on using the browser.