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

Revision 11098, 72.5 kB (checked in by robert, 8 years ago)

Converted View across to use ObserverNodePath?.

  • 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_NOTIFY(osg::INFO)<<"Found CoordianteSystemNode node"<<std::endl;
52            OSG_NOTIFY(osg::INFO)<<"     CoordinateSystem = "<<node.getCoordinateSystem()<<std::endl;
53            _pathToCoordinateSystemNode = getNodePath();
54        }
55        else
56        {
57            OSG_NOTIFY(osg::INFO)<<"Found additional CoordianteSystemNode node, but ignoring"<<std::endl;
58            OSG_NOTIFY(osg::INFO)<<"     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::MatrixManipulator::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_NOTIFY(osg::INFO)<<"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_NOTIFY(osg::INFO)<<"csn->computeLocalCoordinateFrame(position)* osg::computeLocalToWorld(tmpPath)"<<coordinateFrame<<std::endl;
109
110            }
111            else
112            {
113                OSG_NOTIFY(osg::INFO)<<"osg::computeLocalToWorld(tmpPath)"<<std::endl;
114                coordinateFrame =  osg::computeLocalToWorld(tmpPath);
115            }
116            return coordinateFrame;
117        }
118        else
119        {
120            OSG_NOTIFY(osg::INFO)<<"   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_NOTIFY(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::View(view,copyop),
161    osgGA::GUIActionAdapter(),
162    _fusionDistanceMode(view._fusionDistanceMode),
163    _fusionDistanceValue(view._fusionDistanceValue)
164{
165    _scene = new Scene;
166
167    // need to attach a Renderer to the master camera which has been default constructed
168    getCamera()->setRenderer(createRenderer(getCamera()));
169
170    setEventQueue(new osgGA::EventQueue);
171
172    setStats(new osg::Stats("View"));
173}
174
175View::~View()
176{
177    OSG_NOTIFY(osg::INFO)<<"Destructing osgViewer::View"<<std::endl;
178}
179
180void View::take(osg::View& rhs)
181{
182    osg::View::take(rhs);
183
184#if 1
185    osgViewer::View* rhs_osgViewer = dynamic_cast<osgViewer::View*>(&rhs);
186    if (rhs_osgViewer)
187    {
188
189        // copy across rhs
190        _startTick = rhs_osgViewer->_startTick;
191        _frameStamp = rhs_osgViewer->_frameStamp;
192
193        if (rhs_osgViewer->getSceneData())
194        {
195            _scene = rhs_osgViewer->_scene;
196        }
197
198        if (rhs_osgViewer->_cameraManipulator.valid())
199        {
200            _cameraManipulator = rhs_osgViewer->_cameraManipulator;
201        }
202
203        _eventHandlers.insert(_eventHandlers.end(), rhs_osgViewer->_eventHandlers.begin(), rhs_osgViewer->_eventHandlers.end());
204
205        _coordinateSystemNodePath = rhs_osgViewer->_coordinateSystemNodePath;
206
207        _displaySettings = rhs_osgViewer->_displaySettings;
208        _fusionDistanceMode = rhs_osgViewer->_fusionDistanceMode;
209        _fusionDistanceValue = rhs_osgViewer->_fusionDistanceValue;
210
211
212        // clear rhs
213        rhs_osgViewer->_frameStamp = 0;
214        rhs_osgViewer->_scene = 0;
215        rhs_osgViewer->_cameraManipulator = 0;
216        rhs_osgViewer->_eventHandlers.clear();
217
218        rhs_osgViewer->_coordinateSystemNodePath.clearNodePath();
219
220        rhs_osgViewer->_displaySettings = 0;
221    }
222#endif
223    computeActiveCoordinateSystemNodePath();
224    assignSceneDataToCameras();
225}
226
227osg::GraphicsOperation* View::createRenderer(osg::Camera* camera)
228{
229    Renderer* render = new Renderer(camera);
230    camera->setStats(new osg::Stats("Camera"));
231    return render;
232}
233
234
235void View::init()
236{
237    OSG_NOTIFY(osg::INFO)<<"View::init()"<<std::endl;
238
239    osg::ref_ptr<osgGA::GUIEventAdapter> initEvent = _eventQueue->createEvent();
240    initEvent->setEventType(osgGA::GUIEventAdapter::FRAME);
241
242    if (_cameraManipulator.valid())
243    {
244        _cameraManipulator->init(*initEvent, *this);
245    }
246}
247
248void View::setStartTick(osg::Timer_t tick)
249{
250    _startTick = tick;
251}
252
253void View::setSceneData(osg::Node* node)
254{
255    if (node==_scene->getSceneData()) return;
256
257    osg::ref_ptr<Scene> scene = Scene::getScene(node);
258
259    if (scene)
260    {
261        OSG_NOTIFY(osg::INFO)<<"View::setSceneData() Sharing scene "<<scene.get()<<std::endl;
262        _scene = scene;
263    }
264    else
265    {
266        if (_scene->referenceCount()!=1)
267        {
268            // we are not the only reference to the Scene so we cannot reuse it.
269            _scene = new Scene;
270            OSG_NOTIFY(osg::INFO)<<"View::setSceneData() Allocating new scene"<<_scene.get()<<std::endl;
271        }
272        else
273        {
274            OSG_NOTIFY(osg::INFO)<<"View::setSceneData() Reusing exisitng scene"<<_scene.get()<<std::endl;
275        }
276
277        _scene->setSceneData(node);
278    }
279
280    if (getSceneData())
281    {
282        #if defined(OSG_GLES2_AVAILABLE)
283            osgUtil::ShaderGenVisitor sgv;
284            getSceneData()->getOrCreateStateSet();
285            getSceneData()->accept(sgv);
286        #endif
287       
288        // now make sure the scene graph is set up with the correct DataVariance to protect the dynamic elements of
289        // the scene graph from being run in parallel.
290        osgUtil::Optimizer::StaticObjectDetectionVisitor sodv;
291        getSceneData()->accept(sodv);
292
293        // make sure that existing scene graph objects are allocated with thread safe ref/unref
294        if (getViewerBase() &&
295            getViewerBase()->getThreadingModel()!=ViewerBase::SingleThreaded)
296        {
297            getSceneData()->setThreadSafeRefUnref(true);
298        }
299
300        // update the scene graph so that it has enough GL object buffer memory for the graphics contexts that will be using it.
301        getSceneData()->resizeGLObjectBuffers(osg::DisplaySettings::instance()->getMaxNumberOfGraphicsContexts());
302    }
303
304    computeActiveCoordinateSystemNodePath();
305
306    assignSceneDataToCameras();
307}
308
309void View::setDatabasePager(osgDB::DatabasePager* dp)
310{
311    _scene->setDatabasePager(dp);
312}
313
314osgDB::DatabasePager* View::getDatabasePager()
315{
316    return _scene->getDatabasePager();
317}
318
319const osgDB::DatabasePager* View::getDatabasePager() const
320{
321    return _scene->getDatabasePager();
322}
323
324
325void View::setImagePager(osgDB::ImagePager* dp)
326{
327    _scene->setImagePager(dp);
328}
329
330osgDB::ImagePager* View::getImagePager()
331{
332    return _scene->getImagePager();
333}
334
335const osgDB::ImagePager* View::getImagePager() const
336{
337    return _scene->getImagePager();
338}
339
340
341void View::setCameraManipulator(osgGA::MatrixManipulator* manipulator, bool resetPosition)
342{
343    _cameraManipulator = manipulator;
344
345    if (_cameraManipulator.valid())
346    {
347        _cameraManipulator->setCoordinateFrameCallback(new ViewerCoordinateFrameCallback(this));
348
349        if (getSceneData()) _cameraManipulator->setNode(getSceneData());
350
351        if (resetPosition)
352        {
353            osg::ref_ptr<osgGA::GUIEventAdapter> dummyEvent = _eventQueue->createEvent();
354            _cameraManipulator->home(*dummyEvent, *this);
355        }
356    }
357}
358
359void View::home()
360{
361    if (_cameraManipulator.valid())
362    {
363        osg::ref_ptr<osgGA::GUIEventAdapter> dummyEvent = _eventQueue->createEvent();
364        _cameraManipulator->home(*dummyEvent, *this);
365    }
366}
367
368
369void View::addEventHandler(osgGA::GUIEventHandler* eventHandler)
370{
371    EventHandlers::iterator itr = std::find(_eventHandlers.begin(), _eventHandlers.end(), eventHandler);
372    if (itr == _eventHandlers.end())
373    {
374        _eventHandlers.push_back(eventHandler);
375    }
376}
377
378void View::removeEventHandler(osgGA::GUIEventHandler* eventHandler)
379{
380    EventHandlers::iterator itr = std::find(_eventHandlers.begin(), _eventHandlers.end(), eventHandler);
381    if (itr != _eventHandlers.end())
382    {
383        _eventHandlers.erase(itr);
384    }
385}
386
387void View::setCoordinateSystemNodePath(const osg::NodePath& nodePath)
388{
389    _coordinateSystemNodePath.setNodePath(nodePath);
390}
391
392osg::NodePath View::getCoordinateSystemNodePath() const
393{
394    osg::NodePath nodePath;
395    _coordinateSystemNodePath.getNodePath(nodePath);
396    return nodePath;
397}
398
399void View::computeActiveCoordinateSystemNodePath()
400{
401    // now search for CoordinateSystemNode's for which we want to track.
402    osg::Node* subgraph = getSceneData();
403
404    if (subgraph)
405    {
406
407        CollectedCoordinateSystemNodesVisitor ccsnv;
408        subgraph->accept(ccsnv);
409
410        if (!ccsnv._pathToCoordinateSystemNode.empty())
411        {
412           setCoordinateSystemNodePath(ccsnv._pathToCoordinateSystemNode);
413           return;
414        }
415    }
416
417    // otherwise no node path found so reset to empty.
418    setCoordinateSystemNodePath(osg::NodePath());
419}
420
421void View::setUpViewAcrossAllScreens()
422{
423    osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
424    if (!wsi)
425    {
426        OSG_NOTIFY(osg::NOTICE)<<"View::setUpViewAcrossAllScreens() : Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
427        return;
428    }
429
430    osg::DisplaySettings* ds = _displaySettings.valid() ? _displaySettings.get() : osg::DisplaySettings::instance();
431
432    double fovy, aspectRatio, zNear, zFar;
433    _camera->getProjectionMatrixAsPerspective(fovy, aspectRatio, zNear, zFar);
434
435    osg::GraphicsContext::ScreenIdentifier si;
436    si.readDISPLAY();
437
438    // displayNum has not been set so reset it to 0.
439    if (si.displayNum<0) si.displayNum = 0;
440
441    unsigned int numScreens = wsi->getNumScreens(si);
442    if (numScreens==1)
443    {
444        if (si.screenNum<0) si.screenNum = 0;
445
446        unsigned int width, height;
447        wsi->getScreenResolution(si, width, height);
448
449        osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits(ds);
450        traits->hostName = si.hostName;
451        traits->displayNum = si.displayNum;
452        traits->screenNum = si.screenNum;
453        traits->x = 0;
454        traits->y = 0;
455        traits->width = width;
456        traits->height = height;
457        traits->windowDecoration = false;
458        traits->doubleBuffer = true;
459        traits->sharedContext = 0;
460       
461        osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
462
463        _camera->setGraphicsContext(gc.get());
464
465        osgViewer::GraphicsWindow* gw = dynamic_cast<osgViewer::GraphicsWindow*>(gc.get());
466        if (gw)
467        {
468            OSG_NOTIFY(osg::INFO)<<"  GraphicsWindow has been created successfully."<<std::endl;
469            gw->getEventQueue()->getCurrentEventState()->setWindowRectangle(0, 0, width, height );
470        }
471        else
472        {
473            OSG_NOTIFY(osg::NOTICE)<<"  GraphicsWindow has not been created successfully."<<std::endl;
474        }
475
476        double newAspectRatio = double(traits->width) / double(traits->height);
477        double aspectRatioChange = newAspectRatio / aspectRatio;
478        if (aspectRatioChange != 1.0)
479        {
480            _camera->getProjectionMatrix() *= osg::Matrix::scale(1.0/aspectRatioChange,1.0,1.0);
481        }
482
483        _camera->setViewport(new osg::Viewport(0, 0, traits->width, traits->height));
484
485        GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
486
487        _camera->setDrawBuffer(buffer);
488        _camera->setReadBuffer(buffer);
489
490    }
491    else
492    {
493
494        double translate_x = 0.0;
495
496        for(unsigned int i=0; i<numScreens; ++i)
497        {
498            si.screenNum = i;
499
500            unsigned int width, height;
501            wsi->getScreenResolution(si, width, height);
502            translate_x += double(width) / (double(height) * aspectRatio);
503        }
504
505        bool stereoSlitScreens = numScreens==2 &&
506                                 ds->getStereoMode()==osg::DisplaySettings::HORIZONTAL_SPLIT &&
507                                 ds->getStereo();
508
509        for(unsigned int i=0; i<numScreens; ++i)
510        {
511            si.screenNum = i;
512
513            unsigned int width, height;
514            wsi->getScreenResolution(si, width, height);
515
516            osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits(ds);
517            traits->hostName = si.hostName;
518            traits->displayNum = si.displayNum;
519            traits->screenNum = si.screenNum;
520            traits->screenNum = i;
521            traits->x = 0;
522            traits->y = 0;
523            traits->width = width;
524            traits->height = height;
525            traits->windowDecoration = false;
526            traits->doubleBuffer = true;
527            traits->sharedContext = 0;
528
529            osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
530
531            osg::ref_ptr<osg::Camera> camera = new osg::Camera;
532            camera->setGraphicsContext(gc.get());
533
534            osgViewer::GraphicsWindow* gw = dynamic_cast<osgViewer::GraphicsWindow*>(gc.get());
535            if (gw)
536            {
537                OSG_NOTIFY(osg::INFO)<<"  GraphicsWindow has been created successfully."<<gw<<std::endl;
538
539                gw->getEventQueue()->getCurrentEventState()->setWindowRectangle(traits->x, traits->y, traits->width, traits->height );
540            }
541            else
542            {
543                OSG_NOTIFY(osg::NOTICE)<<"  GraphicsWindow has not been created successfully."<<std::endl;
544            }
545
546            camera->setViewport(new osg::Viewport(0, 0, traits->width, traits->height));
547
548            GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
549            camera->setDrawBuffer(buffer);
550            camera->setReadBuffer(buffer);
551
552            if (stereoSlitScreens)
553            {
554                unsigned int leftCameraNum = (ds->getSplitStereoHorizontalEyeMapping()==osg::DisplaySettings::LEFT_EYE_LEFT_VIEWPORT) ? 0 : 1;
555
556                osg::ref_ptr<osg::DisplaySettings> ds_local = new osg::DisplaySettings(*ds);
557                ds_local->setStereoMode(leftCameraNum==i ? osg::DisplaySettings::LEFT_EYE : osg::DisplaySettings::RIGHT_EYE);
558                camera->setDisplaySettings(ds_local.get());
559
560                addSlave(camera.get(), osg::Matrixd(), osg::Matrixd() );
561            }
562            else
563            {
564                double newAspectRatio = double(traits->width) / double(traits->height);
565                double aspectRatioChange = newAspectRatio / aspectRatio;
566
567                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() );
568                translate_x -= aspectRatioChange * 2.0;
569            }
570        }
571    }
572
573    assignSceneDataToCameras();
574}
575
576void View::setUpViewInWindow(int x, int y, int width, int height, unsigned int screenNum)
577{
578    osg::DisplaySettings* ds = _displaySettings.valid() ? _displaySettings.get() : osg::DisplaySettings::instance();
579
580    osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits(ds);
581
582    traits->readDISPLAY();
583    if (traits->displayNum<0) traits->displayNum = 0;
584
585    traits->screenNum = screenNum;
586    traits->x = x;
587    traits->y = y;
588    traits->width = width;
589    traits->height = height;
590    traits->windowDecoration = true;
591    traits->doubleBuffer = true;
592    traits->sharedContext = 0;
593
594    osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
595
596    _camera->setGraphicsContext(gc.get());
597
598    osgViewer::GraphicsWindow* gw = dynamic_cast<osgViewer::GraphicsWindow*>(gc.get());
599    if (gw)
600    {
601        OSG_NOTIFY(osg::INFO)<<"View::setUpViewOnSingleScreen - GraphicsWindow has been created successfully."<<std::endl;
602        gw->getEventQueue()->getCurrentEventState()->setWindowRectangle(x, y, width, height );
603    }
604    else
605    {
606        OSG_NOTIFY(osg::NOTICE)<<"  GraphicsWindow has not been created successfully."<<std::endl;
607    }
608
609    double fovy, aspectRatio, zNear, zFar;
610    _camera->getProjectionMatrixAsPerspective(fovy, aspectRatio, zNear, zFar);
611
612    double newAspectRatio = double(traits->width) / double(traits->height);
613    double aspectRatioChange = newAspectRatio / aspectRatio;
614    if (aspectRatioChange != 1.0)
615    {
616        _camera->getProjectionMatrix() *= osg::Matrix::scale(1.0/aspectRatioChange,1.0,1.0);
617    }
618
619    _camera->setViewport(new osg::Viewport(0, 0, traits->width, traits->height));
620
621    GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
622
623    _camera->setDrawBuffer(buffer);
624    _camera->setReadBuffer(buffer);
625}
626
627void View::setUpViewOnSingleScreen(unsigned int screenNum)
628{
629    osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
630    if (!wsi)
631    {
632        OSG_NOTIFY(osg::NOTICE)<<"View::setUpViewOnSingleScreen() : Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
633        return;
634    }
635
636    osg::DisplaySettings* ds = _displaySettings.valid() ? _displaySettings.get() : osg::DisplaySettings::instance();
637
638    osg::GraphicsContext::ScreenIdentifier si;
639    si.readDISPLAY();
640
641    // displayNum has not been set so reset it to 0.
642    if (si.displayNum<0) si.displayNum = 0;
643
644    si.screenNum = screenNum;
645
646    unsigned int width, height;
647    wsi->getScreenResolution(si, width, height);
648
649    osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits(ds);
650    traits->hostName = si.hostName;
651    traits->displayNum = si.displayNum;
652    traits->screenNum = si.screenNum;
653    traits->x = 0;
654    traits->y = 0;
655    traits->width = width;
656    traits->height = height;
657    traits->windowDecoration = false;
658    traits->doubleBuffer = true;
659    traits->sharedContext = 0;
660
661    osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
662
663    _camera->setGraphicsContext(gc.get());
664
665    osgViewer::GraphicsWindow* gw = dynamic_cast<osgViewer::GraphicsWindow*>(gc.get());
666    if (gw)
667    {
668        OSG_NOTIFY(osg::INFO)<<"View::setUpViewOnSingleScreen - GraphicsWindow has been created successfully."<<std::endl;
669        gw->getEventQueue()->getCurrentEventState()->setWindowRectangle(0, 0, width, height );
670    }
671    else
672    {
673        OSG_NOTIFY(osg::NOTICE)<<"  GraphicsWindow has not been created successfully."<<std::endl;
674    }
675
676    double fovy, aspectRatio, zNear, zFar;
677    _camera->getProjectionMatrixAsPerspective(fovy, aspectRatio, zNear, zFar);
678
679    double newAspectRatio = double(traits->width) / double(traits->height);
680    double aspectRatioChange = newAspectRatio / aspectRatio;
681    if (aspectRatioChange != 1.0)
682    {
683        _camera->getProjectionMatrix() *= osg::Matrix::scale(1.0/aspectRatioChange,1.0,1.0);
684    }
685
686    _camera->setViewport(new osg::Viewport(0, 0, traits->width, traits->height));
687
688    GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
689
690    _camera->setDrawBuffer(buffer);
691    _camera->setReadBuffer(buffer);
692}
693
694static 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)
695{
696    osg::Vec3d center(0.0,0.0,0.0);
697    osg::Vec3d eye(0.0,0.0,0.0);
698
699    double distance = sqrt(sphere_radius*sphere_radius - collar_radius*collar_radius);
700
701    bool centerProjection = false;
702
703    osg::Vec3d projector = eye - osg::Vec3d(0.0,0.0, distance);
704
705    OSG_NOTIFY(osg::INFO)<<"create3DSphericalDisplayDistortionMesh : Projector position = "<<projector<<std::endl;
706    OSG_NOTIFY(osg::INFO)<<"create3DSphericalDisplayDistortionMesh : distance = "<<distance<<std::endl;
707
708
709    // create the quad to visualize.
710    osg::Geometry* geometry = new osg::Geometry();
711
712    geometry->setSupportsDisplayList(false);
713
714    osg::Vec3 xAxis(widthVector);
715    float width = widthVector.length();
716    xAxis /= width;
717
718    osg::Vec3 yAxis(heightVector);
719    float height = heightVector.length();
720    yAxis /= height;
721
722    int noSteps = 50;
723
724    osg::Vec3Array* vertices = new osg::Vec3Array;
725    osg::Vec3Array* texcoords0 = new osg::Vec3Array;
726    osg::Vec2Array* texcoords1 = intensityMap==0 ? new osg::Vec2Array : 0;
727    osg::Vec4Array* colors = new osg::Vec4Array;
728
729    osg::Vec3 bottom = origin;
730    osg::Vec3 dx = xAxis*(width/((float)(noSteps-1)));
731    osg::Vec3 dy = yAxis*(height/((float)(noSteps-1)));
732
733    osg::Vec3d screenCenter = origin + widthVector*0.5f + heightVector*0.5f;
734    float screenRadius = heightVector.length() * 0.5f;
735
736    osg::Vec3 cursor = bottom;
737    int i,j;
738
739    if (centerProjection)
740    {
741        for(i=0;i<noSteps;++i)
742        {
743            osg::Vec3 cursor = bottom+dy*(float)i;
744            for(j=0;j<noSteps;++j)
745            {
746                osg::Vec2 delta(cursor.x() - screenCenter.x(), cursor.y() - screenCenter.y());
747                double theta = atan2(-delta.y(), delta.x());
748                double phi = osg::PI_2 * delta.length() / screenRadius;
749                if (phi > osg::PI_2) phi = osg::PI_2;
750
751                phi *= 2.0;
752
753                if (theta<0.0) theta += 2.0*osg::PI;
754
755                // OSG_NOTIFY(osg::NOTICE)<<"theta = "<<theta<< "phi="<<phi<<std::endl;
756
757                osg::Vec3 texcoord(sin(phi) * cos(theta),
758                                   sin(phi) * sin(theta),
759                                   cos(phi));
760
761                vertices->push_back(cursor);
762                texcoords0->push_back(texcoord * projectorMatrix);
763
764                osg::Vec2 texcoord1(theta/(2.0*osg::PI), 1.0f - phi/osg::PI_2);
765                if (intensityMap)
766                {
767                    colors->push_back(intensityMap->getColor(texcoord1));
768                }
769                else
770                {
771                    colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
772                    if (texcoords1) texcoords1->push_back( texcoord1 );
773                }
774
775                cursor += dx;
776            }
777            // OSG_NOTIFY(osg::NOTICE)<<std::endl;
778        }
779    }
780    else
781    {
782        for(i=0;i<noSteps;++i)
783        {
784            osg::Vec3 cursor = bottom+dy*(float)i;
785            for(j=0;j<noSteps;++j)
786            {
787                osg::Vec2 delta(cursor.x() - screenCenter.x(), cursor.y() - screenCenter.y());
788                double theta = atan2(-delta.y(), delta.x());
789                double phi = osg::PI_2 * delta.length() / screenRadius;
790                if (phi > osg::PI_2) phi = osg::PI_2;
791                if (theta<0.0) theta += 2.0*osg::PI;
792
793                // OSG_NOTIFY(osg::NOTICE)<<"theta = "<<theta<< "phi="<<phi<<std::endl;
794
795                double f = distance * sin(phi);
796                double e = distance * cos(phi) + sqrt( sphere_radius*sphere_radius - f*f);
797                double l = e * cos(phi);
798                double h = e * sin(phi);
799                double z = l - distance;
800
801                osg::Vec3 texcoord(h * cos(theta) / sphere_radius,
802                                   h * sin(theta) / sphere_radius,
803                                   z / sphere_radius);
804
805                vertices->push_back(cursor);
806                texcoords0->push_back(texcoord * projectorMatrix);
807
808                osg::Vec2 texcoord1(theta/(2.0*osg::PI), 1.0f - phi/osg::PI_2);
809                if (intensityMap)
810                {
811                    colors->push_back(intensityMap->getColor(texcoord1));
812                }
813                else
814                {
815                    colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
816                    if (texcoords1) texcoords1->push_back( texcoord1 );
817                }
818
819                cursor += dx;
820            }
821            // OSG_NOTIFY(osg::NOTICE)<<std::endl;
822        }
823    }
824
825    // pass the created vertex array to the points geometry object.
826    geometry->setVertexArray(vertices);
827
828    geometry->setColorArray(colors);
829    geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
830
831    geometry->setTexCoordArray(0,texcoords0);
832    if (texcoords1) geometry->setTexCoordArray(1,texcoords1);
833
834    for(i=0;i<noSteps-1;++i)
835    {
836        osg::DrawElementsUShort* elements = new osg::DrawElementsUShort(osg::PrimitiveSet::QUAD_STRIP);
837        for(j=0;j<noSteps;++j)
838        {
839            elements->push_back(j+(i+1)*noSteps);
840            elements->push_back(j+(i)*noSteps);
841        }
842        geometry->addPrimitiveSet(elements);
843    }
844
845    return geometry;
846}
847
848void View::setUpViewFor3DSphericalDisplay(double radius, double collar, unsigned int screenNum, osg::Image* intensityMap, const osg::Matrixd& projectorMatrix)
849{
850    OSG_NOTIFY(osg::INFO)<<"View::setUpViewFor3DSphericalDisplay(rad="<<radius<<", cllr="<<collar<<", sn="<<screenNum<<", im="<<intensityMap<<")"<<std::endl;
851    osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
852    if (!wsi)
853    {
854        OSG_NOTIFY(osg::NOTICE)<<"Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
855        return;
856    }
857
858    osg::GraphicsContext::ScreenIdentifier si;
859    si.readDISPLAY();
860
861    // displayNum has not been set so reset it to 0.
862    if (si.displayNum<0) si.displayNum = 0;
863
864    si.screenNum = screenNum;
865
866    unsigned int width, height;
867    wsi->getScreenResolution(si, width, height);
868
869
870    osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
871    traits->hostName = si.hostName;
872    traits->displayNum = si.displayNum;
873    traits->screenNum = si.screenNum;
874    traits->x = 0;
875    traits->y = 0;
876    traits->width = width;
877    traits->height = height;
878    traits->windowDecoration = false;
879    traits->doubleBuffer = true;
880    traits->sharedContext = 0;
881
882
883    osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
884    if (!gc)
885    {
886        OSG_NOTIFY(osg::NOTICE)<<"GraphicsWindow has not been created successfully."<<std::endl;
887        return;
888    }
889
890    bool applyIntensityMapAsColours = true;
891
892    int tex_width = 512;
893    int tex_height = 512;
894
895    int camera_width = tex_width;
896    int camera_height = tex_height;
897
898    osg::TextureCubeMap* texture = new osg::TextureCubeMap;
899
900    texture->setTextureSize(tex_width, tex_height);
901    texture->setInternalFormat(GL_RGB);
902    texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
903    texture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
904    texture->setWrap(osg::Texture::WRAP_S,osg::Texture::CLAMP_TO_EDGE);
905    texture->setWrap(osg::Texture::WRAP_T,osg::Texture::CLAMP_TO_EDGE);
906    texture->setWrap(osg::Texture::WRAP_R,osg::Texture::CLAMP_TO_EDGE);
907
908#if 0
909    osg::Camera::RenderTargetImplementation renderTargetImplementation = osg::Camera::SEPERATE_WINDOW;
910    GLenum buffer = GL_FRONT;
911#else
912    osg::Camera::RenderTargetImplementation renderTargetImplementation = osg::Camera::FRAME_BUFFER_OBJECT;
913    GLenum buffer = GL_FRONT;
914#endif
915
916    // front face
917    {
918        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
919        camera->setName("Front face camera");
920        camera->setGraphicsContext(gc.get());
921        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
922        camera->setDrawBuffer(buffer);
923        camera->setReadBuffer(buffer);
924        camera->setAllowEventFocus(false);
925        // tell the camera to use OpenGL frame buffer object where supported.
926        camera->setRenderTargetImplementation(renderTargetImplementation);
927
928        // attach the texture and use it as the color buffer.
929        camera->attach(osg::Camera::COLOR_BUFFER, texture, 0, osg::TextureCubeMap::POSITIVE_Y);
930
931        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd());
932    }
933
934
935    // top face
936    {
937        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
938        camera->setName("Top face camera");
939        camera->setGraphicsContext(gc.get());
940        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
941        GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
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_NOTIFY(osg::INFO)<<"createParoramicSphericalDisplayDistortionMesh : Projector position = "<<projector<<std::endl;
1095    OSG_NOTIFY(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 bottom = origin;
1118    osg::Vec3 dx = xAxis*(width/((float)(noSteps-2)));
1119    osg::Vec3 dy = yAxis*(height/((float)(noSteps-1)));
1120
1121    osg::Vec3 top = origin + yAxis*height;
1122
1123    osg::Vec3 screenCenter = origin + widthVector*0.5f + heightVector*0.5f;
1124    float screenRadius = heightVector.length() * 0.5f;
1125
1126    geometry->getOrCreateStateSet()->setMode(GL_CULL_FACE, osg::StateAttribute::OFF | osg::StateAttribute::PROTECTED);
1127
1128    for(int i=0;i<noSteps;++i)
1129    {
1130        osg::Vec3 cursor = bottom+dy*(float)i;
1131        for(int j=0;j<noSteps;++j)
1132        {
1133            osg::Vec2 texcoord(double(i)/double(noSteps-1), double(j)/double(noSteps-1));
1134            double theta = texcoord.x() * 2.0 * osg::PI;
1135            double phi = (1.0-texcoord.y()) * osg::PI;
1136
1137            if (texcoord_flip) texcoord.y() = 1.0f - texcoord.y();
1138
1139            osg::Vec3 pos(sin(phi)*sin(theta), sin(phi)*cos(theta), cos(phi));
1140            pos = pos*projectorMatrix;
1141
1142            double alpha = atan2(pos.x(), pos.y());
1143            if (alpha<0.0) alpha += 2.0*osg::PI;
1144
1145            double beta = atan2(sqrt(pos.x()*pos.x() + pos.y()*pos.y()), pos.z());
1146            if (beta<0.0) beta += 2.0*osg::PI;
1147
1148            double gamma = atan2(sqrt(double(pos.x()*pos.x() + pos.y()*pos.y())), double(pos.z()+distance));
1149            if (gamma<0.0) gamma += 2.0*osg::PI;
1150
1151
1152            osg::Vec3 v = screenCenter + osg::Vec3(sin(alpha)*gamma*2.0/osg::PI, -cos(alpha)*gamma*2.0/osg::PI, 0.0f)*screenRadius;
1153
1154            if (flip)
1155                vertices->push_back(osg::Vec3(v.x(), top.y()-(v.y()-origin.y()),v.z()));
1156            else
1157                vertices->push_back(v);
1158
1159            texcoords0->push_back( texcoord );
1160
1161            osg::Vec2 texcoord1(alpha/(2.0*osg::PI), 1.0f - beta/osg::PI);
1162            if (intensityMap)
1163            {
1164                colors->push_back(intensityMap->getColor(texcoord1));
1165            }
1166            else
1167            {
1168                colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
1169                if (texcoords1) texcoords1->push_back( texcoord1 );
1170            }
1171
1172
1173        }
1174    }
1175
1176
1177    // pass the created vertex array to the points geometry object.
1178    geometry->setVertexArray(vertices);
1179
1180    geometry->setColorArray(colors);
1181    geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
1182
1183    geometry->setTexCoordArray(0,texcoords0);
1184    if (texcoords1) geometry->setTexCoordArray(1,texcoords1);
1185
1186    osg::DrawElementsUShort* elements = new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLES);
1187    geometry->addPrimitiveSet(elements);
1188
1189    for(int i=0;i<noSteps-1;++i)
1190    {
1191        for(int j=0;j<noSteps-1;++j)
1192        {
1193            int i1 = j+(i+1)*noSteps;
1194            int i2 = j+(i)*noSteps;
1195            int i3 = j+1+(i)*noSteps;
1196            int i4 = j+1+(i+1)*noSteps;
1197
1198            osg::Vec3& v1 = (*vertices)[i1];
1199            osg::Vec3& v2 = (*vertices)[i2];
1200            osg::Vec3& v3 = (*vertices)[i3];
1201            osg::Vec3& v4 = (*vertices)[i4];
1202
1203            if ((v1-screenCenter).length()>screenRadius) continue;
1204            if ((v2-screenCenter).length()>screenRadius) continue;
1205            if ((v3-screenCenter).length()>screenRadius) continue;
1206            if ((v4-screenCenter).length()>screenRadius) continue;
1207
1208            elements->push_back(i1);
1209            elements->push_back(i2);
1210            elements->push_back(i3);
1211
1212            elements->push_back(i1);
1213            elements->push_back(i3);
1214            elements->push_back(i4);
1215        }
1216    }
1217
1218    return geometry;
1219}
1220
1221void View::setUpViewForPanoramicSphericalDisplay(double radius, double collar, unsigned int screenNum, osg::Image* intensityMap, const osg::Matrixd& projectorMatrix)
1222{
1223    OSG_NOTIFY(osg::INFO)<<"View::setUpViewForPanoramicSphericalDisplay(rad="<<radius<<", cllr="<<collar<<", sn="<<screenNum<<", im="<<intensityMap<<")"<<std::endl;
1224
1225    osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
1226    if (!wsi)
1227    {
1228        OSG_NOTIFY(osg::NOTICE)<<"Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
1229        return;
1230    }
1231
1232    osg::GraphicsContext::ScreenIdentifier si;
1233    si.readDISPLAY();
1234
1235    // displayNum has not been set so reset it to 0.
1236    if (si.displayNum<0) si.displayNum = 0;
1237
1238    si.screenNum = screenNum;
1239
1240    unsigned int width, height;
1241    wsi->getScreenResolution(si, width, height);
1242
1243    osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
1244    traits->hostName = si.hostName;
1245    traits->displayNum = si.displayNum;
1246    traits->screenNum = si.screenNum;
1247    traits->x = 0;
1248    traits->y = 0;
1249    traits->width = width;
1250    traits->height = height;
1251    traits->windowDecoration = false;
1252    traits->doubleBuffer = true;
1253    traits->sharedContext = 0;
1254
1255
1256    bool applyIntensityMapAsColours = true;
1257
1258    osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
1259    if (!gc)
1260    {
1261        OSG_NOTIFY(osg::NOTICE)<<"GraphicsWindow has not been created successfully."<<std::endl;
1262        return;
1263    }
1264
1265    int tex_width = width;
1266    int tex_height = height;
1267
1268    int camera_width = tex_width;
1269    int camera_height = tex_height;
1270
1271    osg::TextureRectangle* texture = new osg::TextureRectangle;
1272
1273    texture->setTextureSize(tex_width, tex_height);
1274    texture->setInternalFormat(GL_RGB);
1275    texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
1276    texture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
1277    texture->setWrap(osg::Texture::WRAP_S,osg::Texture::CLAMP_TO_EDGE);
1278    texture->setWrap(osg::Texture::WRAP_T,osg::Texture::CLAMP_TO_EDGE);
1279
1280#if 0
1281    osg::Camera::RenderTargetImplementation renderTargetImplementation = osg::Camera::SEPERATE_WINDOW;
1282    GLenum buffer = GL_FRONT;
1283#else
1284    osg::Camera::RenderTargetImplementation renderTargetImplementation = osg::Camera::FRAME_BUFFER_OBJECT;
1285    GLenum buffer = GL_FRONT;
1286#endif
1287
1288    // front face
1289    {
1290        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
1291        camera->setName("Front face camera");
1292        camera->setGraphicsContext(gc.get());
1293        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
1294        camera->setDrawBuffer(buffer);
1295        camera->setReadBuffer(buffer);
1296        camera->setAllowEventFocus(false);
1297        // tell the camera to use OpenGL frame buffer object where supported.
1298        camera->setRenderTargetImplementation(renderTargetImplementation);
1299
1300        // attach the texture and use it as the color buffer.
1301        camera->attach(osg::Camera::COLOR_BUFFER, texture);
1302
1303        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd());
1304    }
1305
1306    // distortion correction set up.
1307    {
1308        osg::Geode* geode = new osg::Geode();
1309        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));
1310
1311        // new we need to add the texture to the mesh, we do so by creating a
1312        // StateSet to contain the Texture StateAttribute.
1313        osg::StateSet* stateset = geode->getOrCreateStateSet();
1314        stateset->setTextureAttributeAndModes(0, texture,osg::StateAttribute::ON);
1315        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
1316
1317        osg::TexMat* texmat = new osg::TexMat;
1318        texmat->setScaleByTextureRectangleSize(true);
1319        stateset->setTextureAttributeAndModes(0, texmat, osg::StateAttribute::ON);
1320
1321        if (!applyIntensityMapAsColours && intensityMap)
1322        {
1323            stateset->setTextureAttributeAndModes(1, new osg::Texture2D(intensityMap), osg::StateAttribute::ON);
1324        }
1325
1326        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
1327        camera->setGraphicsContext(gc.get());
1328        camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
1329        camera->setClearColor( osg::Vec4(0.0,0.0,0.0,1.0) );
1330        camera->setViewport(new osg::Viewport(0, 0, width, height));
1331        GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
1332        camera->setDrawBuffer(buffer);
1333        camera->setReadBuffer(buffer);
1334        camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF);
1335        camera->setAllowEventFocus(false);
1336        camera->setInheritanceMask(camera->getInheritanceMask() & ~osg::CullSettings::CLEAR_COLOR & ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE);
1337        //camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1338
1339        camera->setProjectionMatrixAsOrtho2D(0,width,0,height);
1340        camera->setViewMatrix(osg::Matrix::identity());
1341
1342        // add subgraph to render
1343        camera->addChild(geode);
1344
1345        camera->setName("DistortionCorrectionCamera");
1346
1347        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd(), false);
1348    }
1349}
1350
1351void 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)
1352{
1353    OSG_NOTIFY(osg::INFO)<<"View::setUpViewForWoWVxDisplay(...)"<<std::endl;
1354
1355    osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
1356    if (!wsi)
1357    {
1358        OSG_NOTIFY(osg::NOTICE)<<"Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
1359        return;
1360    }
1361
1362    osg::GraphicsContext::ScreenIdentifier si;
1363    si.readDISPLAY();
1364
1365    // displayNum has not been set so reset it to 0.
1366    if (si.displayNum<0) si.displayNum = 0;
1367
1368    si.screenNum = screenNum;
1369
1370    unsigned int width, height;
1371    wsi->getScreenResolution(si, width, height);
1372
1373    osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
1374    traits->hostName = si.hostName;
1375    traits->displayNum = si.displayNum;
1376    traits->screenNum = si.screenNum;
1377    traits->x = 0;
1378    traits->y = 0;
1379    traits->width = width;
1380    traits->height = height;
1381    traits->windowDecoration = false;
1382    traits->doubleBuffer = true;
1383    traits->sharedContext = 0;
1384
1385
1386    osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
1387    if (!gc)
1388    {
1389        OSG_NOTIFY(osg::NOTICE)<<"GraphicsWindow has not been created successfully."<<std::endl;
1390        return;
1391    }
1392
1393    int tex_width = width;
1394    int tex_height = height;
1395
1396    int camera_width = tex_width;
1397    int camera_height = tex_height;
1398
1399    osg::Texture2D* texture = new osg::Texture2D;
1400    texture->setTextureSize(tex_width, tex_height);
1401    texture->setInternalFormat(GL_RGB);
1402    texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
1403    texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
1404
1405    osg::Texture2D* textureD = new osg::Texture2D;
1406    textureD->setTextureSize(tex_width, tex_height);
1407    textureD->setInternalFormat(GL_DEPTH_COMPONENT);
1408    textureD->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
1409    textureD->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
1410
1411#if 0
1412    osg::Camera::RenderTargetImplementation renderTargetImplementation = osg::Camera::SEPERATE_WINDOW;
1413    GLenum buffer = GL_FRONT;
1414#else
1415    osg::Camera::RenderTargetImplementation renderTargetImplementation = osg::Camera::FRAME_BUFFER_OBJECT;
1416    GLenum buffer = GL_FRONT;
1417#endif
1418
1419    // front face
1420    {
1421        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
1422        camera->setName("Front face camera");
1423        camera->setGraphicsContext(gc.get());
1424        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
1425        camera->setDrawBuffer(buffer);
1426        camera->setReadBuffer(buffer);
1427        camera->setAllowEventFocus(false);
1428        // tell the camera to use OpenGL frame buffer object where supported.
1429        camera->setRenderTargetImplementation(renderTargetImplementation);
1430
1431        // attach the texture and use it as the color buffer.
1432        camera->attach(osg::Camera::COLOR_BUFFER, texture);
1433        camera->attach(osg::Camera::DEPTH_BUFFER, textureD);
1434
1435        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd());
1436    }
1437
1438    // WoW display set up.
1439    {
1440        osg::Texture1D *textureHeader = new osg::Texture1D();
1441        // Set up the header
1442        {
1443            unsigned char header[]= {0xF1,wow_content,wow_factor,wow_offset,0x00,0x00,0x00,0x00,0x00,0x00};
1444            // Calc the CRC32
1445            {
1446                unsigned long _register = 0;
1447                for(int i = 0; i < 10; ++i) {
1448                    unsigned char mask = 0x80;
1449                    unsigned char byte = header[i];
1450                    for (int j = 0; j < 8; ++j)
1451                    {
1452                        bool topBit = (_register & 0x80000000) != 0;
1453                        _register <<= 1;
1454                        _register ^= ((byte & mask) != 0? 0x1: 0x0);
1455                        if (topBit)
1456                        {
1457                            _register ^= 0x04c11db7;
1458                        }
1459                        mask >>= 1;
1460                    }
1461                }
1462                unsigned char *p = (unsigned char*) &_register;
1463                for(size_t i = 0; i < 4; ++i)
1464                {
1465                    header[i+6] = p[3-i];
1466                }
1467            }
1468
1469            osg::ref_ptr<osg::Image> imageheader = new osg::Image();
1470            imageheader->allocateImage(256,1,1,GL_LUMINANCE,GL_UNSIGNED_BYTE);
1471            {
1472                unsigned char *cheader = imageheader->data();
1473                for (int x=0; x<256; ++x){
1474                    cheader[x] = 0;
1475                }
1476                for (int x=0; x<=9; ++x){
1477                    for (int y=7; y>=0; --y){
1478                        int i = 2*(7-y)+16*x;
1479                        cheader[i] = (((1<<(y))&(header[x])) << (7-(y)));
1480                    }
1481                }
1482            }
1483            textureHeader->setImage(imageheader.get());
1484        }
1485
1486        // Create the Screen Aligned Quad
1487        osg::Geode* geode = new osg::Geode();
1488        {
1489            osg::Geometry* geom = new osg::Geometry;
1490
1491            osg::Vec3Array* vertices = new osg::Vec3Array;
1492            vertices->push_back(osg::Vec3(0,height,0));
1493            vertices->push_back(osg::Vec3(0,0,0));
1494            vertices->push_back(osg::Vec3(width,0,0));
1495            vertices->push_back(osg::Vec3(width,height,0));
1496            geom->setVertexArray(vertices);
1497
1498            osg::Vec2Array* tex = new osg::Vec2Array;
1499            tex->push_back(osg::Vec2(0,1));
1500            tex->push_back(osg::Vec2(0,0));
1501            tex->push_back(osg::Vec2(1,0));
1502            tex->push_back(osg::Vec2(1,1));
1503            geom->setTexCoordArray(0,tex);
1504
1505            geom->addPrimitiveSet(new osg::DrawArrays(GL_QUADS,0,4));
1506            geode->addDrawable(geom);
1507
1508            // new we need to add the textures to the quad, and setting up the shader.
1509            osg::StateSet* stateset = geode->getOrCreateStateSet();
1510            stateset->setTextureAttributeAndModes(0, textureHeader,osg::StateAttribute::ON);
1511            stateset->setTextureAttributeAndModes(1, texture,osg::StateAttribute::ON);
1512            stateset->setTextureAttributeAndModes(2, textureD,osg::StateAttribute::ON);
1513            stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
1514
1515            osg::ref_ptr<osg::Program> programShader = new osg::Program();
1516            stateset->setAttribute(programShader.get(), osg::StateAttribute::ON);
1517            stateset->addUniform( new osg::Uniform("wow_width", (int)width));
1518            stateset->addUniform( new osg::Uniform("wow_height", (int)height));
1519            stateset->addUniform( new osg::Uniform("wow_disparity_M", wow_disparity_M));
1520            stateset->addUniform( new osg::Uniform("wow_disparity_Zd", wow_disparity_Zd));
1521            stateset->addUniform( new osg::Uniform("wow_disparity_vz", wow_disparity_vz));
1522            stateset->addUniform( new osg::Uniform("wow_disparity_C", wow_disparity_C));
1523
1524            stateset->addUniform(new osg::Uniform("wow_header", 0));
1525            stateset->addUniform(new osg::Uniform("wow_tcolor", 1));
1526            stateset->addUniform(new osg::Uniform("wow_tdepth", 2));
1527
1528            osg::Shader *frag = new osg::Shader(osg::Shader::FRAGMENT);
1529            frag->setShaderSource(" "\
1530                    " uniform sampler1D wow_header;                                                                                   " \
1531                    " uniform sampler2D wow_tcolor;                                                                                   " \
1532                    " uniform sampler2D wow_tdepth;                                                                                   " \
1533                    "                                                                                                                 " \
1534                    " uniform int wow_width;                                                                                          " \
1535                    " uniform int wow_height;                                                                                         " \
1536                    " uniform float wow_disparity_M;                                                                                  " \
1537                    " uniform float wow_disparity_Zd;                                                                                 " \
1538                    " uniform float wow_disparity_vz;                                                                                 " \
1539                    " uniform float wow_disparity_C;                                                                                  " \
1540                    "                                                                                                                 " \
1541                    " float disparity(float Z)                                                                                        " \
1542                    " {                                                                                                               " \
1543                    "     return (wow_disparity_M*(1.0-(wow_disparity_vz/(Z-wow_disparity_Zd+wow_disparity_vz)))                        " \
1544                    "                   + wow_disparity_C) / 255.0;                                                                   " \
1545                    " }                                                                                                               " \
1546                    "                                                                                                                 " \
1547                    " void main()                                                                                                     " \
1548                    " {                                                                                                               " \
1549                    "       vec2 pos = (gl_FragCoord.xy / vec2(wow_width/2,wow_height) );                                             " \
1550                    "         if (gl_FragCoord.x > float(wow_width/2))                                                                  " \
1551                    "         {                                                                                                         " \
1552                    "             gl_FragColor = vec4(disparity(( texture2D(wow_tdepth, pos - vec2(1,0))).z));                          " \
1553                    "         }                                                                                                         " \
1554                    "         else{                                                                                                     " \
1555                    "             gl_FragColor = texture2D(wow_tcolor, pos);                                                            " \
1556                    "         }                                                                                                         " \
1557                    "     if ( (gl_FragCoord.y >= float(wow_height-1)) && (gl_FragCoord.x < 256.0) )                                    " \
1558                    "     {                                                                                                             " \
1559                    "         float pos = gl_FragCoord.x/256.0;                                                                         " \
1560                    "         float blue = texture1D(wow_header, pos).b;                                                                " \
1561                    "         if ( blue < 0.5)                                                                                          " \
1562                    "             gl_FragColor.b = 0.0;                                                                                 " \
1563                    "         else                                                                                                      " \
1564                    "             gl_FragColor.b = 1.0;                                                                                 " \
1565                    "     }                                                                                                             " \
1566                    " }                                                                                                               " );
1567
1568            programShader->addShader(frag);
1569        }
1570
1571        // Create the Camera
1572        {
1573            osg::ref_ptr<osg::Camera> camera = new osg::Camera;
1574            camera->setGraphicsContext(gc.get());
1575            camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
1576            camera->setClearColor( osg::Vec4(0.0,0.0,0.0,1.0) );
1577            camera->setViewport(new osg::Viewport(0, 0, width, height));
1578            GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
1579            camera->setDrawBuffer(buffer);
1580            camera->setReadBuffer(buffer);
1581            camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF);
1582            camera->setAllowEventFocus(false);
1583            camera->setInheritanceMask(camera->getInheritanceMask() & ~osg::CullSettings::CLEAR_COLOR & ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE);
1584            //camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1585
1586            camera->setProjectionMatrixAsOrtho2D(0,width,0,height);
1587            camera->setViewMatrix(osg::Matrix::identity());
1588
1589            // add subgraph to render
1590            camera->addChild(geode);
1591
1592            camera->setName("WoWCamera");
1593
1594            addSlave(camera.get(), osg::Matrixd(), osg::Matrixd(), false);
1595        }
1596    }
1597}
1598
1599
1600
1601void View::assignSceneDataToCameras()
1602{
1603    // OSG_NOTIFY(osg::NOTICE)<<"View::assignSceneDataToCameras()"<<std::endl;
1604
1605    osg::Node* sceneData = _scene.valid() ? _scene->getSceneData() : 0;
1606
1607    if (_cameraManipulator.valid())
1608    {
1609        _cameraManipulator->setNode(sceneData);
1610
1611        osg::ref_ptr<osgGA::GUIEventAdapter> dummyEvent = _eventQueue->createEvent();
1612
1613        _cameraManipulator->home(*dummyEvent, *this);
1614    }
1615
1616    if (_camera.valid())
1617    {
1618        _camera->removeChildren(0,_camera->getNumChildren());
1619        if (sceneData) _camera->addChild(sceneData);
1620
1621        Renderer* renderer = dynamic_cast<Renderer*>(_camera->getRenderer());
1622        if (renderer) renderer->setCompileOnNextDraw(true);
1623
1624    }
1625
1626    for(unsigned i=0; i<getNumSlaves(); ++i)
1627    {
1628        Slave& slave = getSlave(i);
1629        if (slave._camera.valid() && slave._useMastersSceneData)
1630        {
1631            slave._camera->removeChildren(0,slave._camera->getNumChildren());
1632            if (sceneData) slave._camera->addChild(sceneData);
1633
1634            Renderer* renderer = dynamic_cast<Renderer*>(slave._camera->getRenderer());
1635            if (renderer) renderer->setCompileOnNextDraw(true);
1636        }
1637    }
1638}
1639
1640void View::requestRedraw()
1641{
1642    if (getViewerBase())
1643    {
1644        getViewerBase()->_requestRedraw = true;
1645    }
1646    else
1647    {
1648        OSG_NOTIFY(osg::INFO)<<"View::requestRedraw(), No viewer base has been assigned yet."<<std::endl;
1649    }
1650}
1651
1652void View::requestContinuousUpdate(bool flag)
1653{
1654    if (getViewerBase())
1655    {
1656        getViewerBase()->_requestContinousUpdate = flag;
1657    }
1658    else
1659    {
1660        OSG_NOTIFY(osg::INFO)<<"View::requestContinuousUpdate(), No viewer base has been assigned yet."<<std::endl;
1661    }
1662}
1663
1664void View::requestWarpPointer(float x,float y)
1665{
1666    OSG_NOTIFY(osg::INFO)<<"View::requestWarpPointer("<<x<<","<<y<<")"<<std::endl;
1667
1668    float local_x, local_y;
1669    const osg::Camera* camera = getCameraContainingPosition(x, y, local_x, local_y);
1670    if (camera)
1671    {
1672        const osgViewer::GraphicsWindow* gw = dynamic_cast<const osgViewer::GraphicsWindow*>(camera->getGraphicsContext());
1673        if (gw)
1674        {
1675            getEventQueue()->mouseWarped(x,y);
1676            if (gw->getEventQueue()->getCurrentEventState()->getMouseYOrientation()==osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS)
1677            {
1678                local_y = gw->getTraits()->height - local_y;
1679            }
1680            const_cast<osgViewer::GraphicsWindow*>(gw)->getEventQueue()->mouseWarped(local_x,local_y);
1681            const_cast<osgViewer::GraphicsWindow*>(gw)->requestWarpPointer(local_x, local_y);
1682        }
1683    }
1684    else
1685    {
1686        OSG_NOTIFY(osg::INFO)<<"View::requestWarpPointer failed no camera containing pointer"<<std::endl;
1687    }
1688}
1689
1690bool View::containsCamera(const osg::Camera* camera) const
1691{
1692    if (_camera == camera) return true;
1693
1694    for(unsigned i=0; i<getNumSlaves(); ++i)
1695    {
1696        const Slave& slave = getSlave(i);
1697        if (slave._camera == camera) return true;
1698    }
1699    return false;
1700}
1701
1702const osg::Camera* View::getCameraContainingPosition(float x, float y, float& local_x, float& local_y) const
1703{
1704    const osgGA::GUIEventAdapter* eventState = getEventQueue()->getCurrentEventState();
1705    const osgViewer::GraphicsWindow* gw = dynamic_cast<const osgViewer::GraphicsWindow*>(eventState->getGraphicsContext());
1706
1707    bool view_invert_y = eventState->getMouseYOrientation()==osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS;
1708
1709    double epsilon = 0.5;
1710
1711    if (_camera->getGraphicsContext() &&
1712        (!gw || _camera->getGraphicsContext()==gw) &&
1713        _camera->getViewport())
1714    {
1715        const osg::Viewport* viewport = _camera->getViewport();
1716
1717        double new_x = x;
1718        double new_y = y;
1719
1720        if (!gw)
1721        {
1722            new_x = static_cast<double>(_camera->getGraphicsContext()->getTraits()->width) * (x - eventState->getXmin())/(eventState->getXmax()-eventState->getXmin());
1723            new_y = view_invert_y ?
1724                       static_cast<double>(_camera->getGraphicsContext()->getTraits()->height) * (1.0 - (y- eventState->getYmin())/(eventState->getYmax()-eventState->getYmin())) :
1725                       static_cast<double>(_camera->getGraphicsContext()->getTraits()->height) * (y - eventState->getYmin())/(eventState->getYmax()-eventState->getXmin());
1726        }
1727
1728        if (viewport &&
1729            new_x >= (viewport->x()-epsilon) && new_y >= (viewport->y()-epsilon) &&
1730            new_x < (viewport->x()+viewport->width()-1.0+epsilon) && new_y <= (viewport->y()+viewport->height()-1.0+epsilon) )
1731        {
1732            local_x = new_x;
1733            local_y = new_y;
1734
1735            OSG_NOTIFY(osg::INFO)<<"Returning master camera"<<std::endl;
1736
1737            return _camera.get();
1738        }
1739    }
1740
1741    osg::Matrix masterCameraVPW = getCamera()->getViewMatrix() * getCamera()->getProjectionMatrix();
1742
1743    // convert to non dimensional
1744    x = (x - eventState->getXmin()) * 2.0 / (eventState->getXmax()-eventState->getXmin()) - 1.0;
1745    y = (y - eventState->getYmin())* 2.0 / (eventState->getYmax()-eventState->getYmin()) - 1.0;
1746
1747    if (view_invert_y) y = - y;
1748
1749    for(int i=getNumSlaves()-1; i>=0; --i)
1750    {
1751        const Slave& slave = getSlave(i);
1752        if (slave._camera.valid() &&
1753            slave._camera->getAllowEventFocus() &&
1754            slave._camera->getRenderTargetImplementation()==osg::Camera::FRAME_BUFFER)
1755        {
1756            OSG_NOTIFY(osg::INFO)<<"Testing slave camera "<<slave._camera->getName()<<std::endl;
1757
1758            const osg::Camera* camera = slave._camera.get();
1759            const osg::Viewport* viewport = camera ? camera->getViewport() : 0;
1760
1761            osg::Matrix localCameraVPW = camera->getViewMatrix() * camera->getProjectionMatrix();
1762            if (viewport) localCameraVPW *= viewport->computeWindowMatrix();
1763
1764            osg::Matrix matrix( osg::Matrix::inverse(masterCameraVPW) * localCameraVPW );
1765
1766            osg::Vec3d new_coord = osg::Vec3d(x,y,0.0) * matrix;
1767
1768            //OSG_NOTIFY(osg::NOTICE)<<"  x="<<x<<" y="<<y<<std::endl;;
1769            //OSG_NOTIFY(osg::NOTICE)<<"  eventState->getXmin()="<<eventState->getXmin()<<" eventState->getXmax()="<<eventState->getXmax()<<std::endl;;
1770            //OSG_NOTIFY(osg::NOTICE)<<"  new_coord "<<new_coord<<std::endl;;
1771
1772            if (viewport &&
1773                new_coord.x() >= (viewport->x()-epsilon) && new_coord.y() >= (viewport->y()-epsilon) &&
1774                new_coord.x() < (viewport->x()+viewport->width()-1.0+epsilon) && new_coord.y() <= (viewport->y()+viewport->height()-1.0+epsilon) )
1775            {
1776                // OSG_NOTIFY(osg::NOTICE)<<"  in viewport "<<std::endl;;
1777
1778                local_x = new_coord.x();
1779                local_y = new_coord.y();
1780
1781                return camera;
1782            }
1783            else
1784            {
1785                // OSG_NOTIFY(osg::NOTICE)<<"  not in viewport "<<viewport->x()<<" "<<(viewport->x()+viewport->width())<<std::endl;;
1786            }
1787
1788        }
1789    }
1790
1791    local_x = x;
1792    local_y = y;
1793
1794    return 0;
1795}
1796
1797bool View::computeIntersections(float x,float y, osgUtil::LineSegmentIntersector::Intersections& intersections, osg::Node::NodeMask traversalMask)
1798{
1799    if (!_camera.valid()) return false;
1800
1801    float local_x, local_y = 0.0;
1802    const osg::Camera* camera = getCameraContainingPosition(x, y, local_x, local_y);
1803    if (!camera) camera = _camera.get();
1804
1805
1806    osgUtil::LineSegmentIntersector::CoordinateFrame cf = camera->getViewport() ? osgUtil::Intersector::WINDOW : osgUtil::Intersector::PROJECTION;
1807    osg::ref_ptr< osgUtil::LineSegmentIntersector > picker = new osgUtil::LineSegmentIntersector(cf, local_x, local_y);
1808
1809#if 0
1810    OSG_NOTIFY(osg::NOTICE)<<"View::computeIntersections(x="<<x<<", y="<<y<<", local_x="<<local_x<<", local_y="<<local_y<<") "<<cf<<std::endl;
1811    OSG_NOTIFY(osg::NOTICE)<<"  viewport ("<<camera->getViewport()->x()<<","<<camera->getViewport()->y()<<","<<camera->getViewport()->width()<<","<<camera->getViewport()->height()<<")"<<std::endl;
1812
1813    const osg::GraphicsContext::Traits* traits = camera->getGraphicsContext() ? camera->getGraphicsContext()->getTraits() : 0;
1814    if (traits)
1815    {
1816        OSG_NOTIFY(osg::NOTICE)<<"  window ("<<traits->x<<","<<traits->y<<","<<traits->width<<","<<traits->height<<")"<<std::endl;
1817    }
1818#endif
1819
1820    osgUtil::IntersectionVisitor iv(picker.get());
1821    iv.setTraversalMask(traversalMask);
1822
1823
1824#if 1
1825    const_cast<osg::Camera*>(camera)->accept(iv);
1826#else
1827
1828    // timing test code paths for comparing KdTree based intersections vs conventional intersections
1829
1830    iv.setUseKdTreeWhenAvailable(true);
1831    iv.setDoDummyTraversal(true);
1832
1833    const_cast<osg::Camera*>(camera)->accept(iv);
1834
1835
1836    osg::Timer_t before = osg::Timer::instance()->tick();
1837    const_cast<osg::Camera*>(camera)->accept(iv);
1838
1839    osg::Timer_t after_dummy = osg::Timer::instance()->tick();
1840
1841    int intersectsBeforeKdTree = picker->getIntersections().size();
1842
1843    iv.setDoDummyTraversal(false);
1844    const_cast<osg::Camera*>(camera)->accept(iv);
1845    osg::Timer_t after_kdTree_2 = osg::Timer::instance()->tick();
1846
1847    int intersectsBeforeConventional = picker->getIntersections().size();
1848
1849    iv.setUseKdTreeWhenAvailable(false);
1850    const_cast<osg::Camera*>(camera)->accept(iv);
1851    osg::Timer_t after = osg::Timer::instance()->tick();
1852
1853    int intersectsAfterConventional = picker->getIntersections().size();
1854
1855    double timeDummy = osg::Timer::instance()->delta_m(before, after_dummy);
1856    double timeKdTree = osg::Timer::instance()->delta_m(after_dummy, after_kdTree_2);
1857    double timeConventional = osg::Timer::instance()->delta_m(after_kdTree_2, after);
1858
1859    OSG_NOTIFY(osg::NOTICE)<<"Using Dummy                    "<<timeDummy<<std::endl;
1860    OSG_NOTIFY(osg::NOTICE)<<"      KdTrees                  "<<timeKdTree
1861                            <<"\tNum intersects = "<<intersectsBeforeConventional-intersectsBeforeKdTree<<std::endl;
1862    OSG_NOTIFY(osg::NOTICE)<<"      KdTrees - Traversal      "<<timeKdTree-timeDummy<<std::endl;
1863    OSG_NOTIFY(osg::NOTICE)<<"      Conventional             "<<timeConventional
1864                            <<"\tNum intersects = "<<intersectsAfterConventional-intersectsBeforeConventional<<std::endl;
1865    OSG_NOTIFY(osg::NOTICE)<<"      Conventional - Traversal "<<timeConventional-timeDummy<<std::endl;
1866    OSG_NOTIFY(osg::NOTICE)<<"      Delta                    "<<timeConventional/timeKdTree<<std::endl;
1867    OSG_NOTIFY(osg::NOTICE)<<"      Delta sans Traversal     "<<(timeConventional-timeDummy)/(timeKdTree-timeDummy)<<std::endl;
1868    OSG_NOTIFY(osg::NOTICE)<<std::endl;
1869#endif
1870
1871    if (picker->containsIntersections())
1872    {
1873        intersections = picker->getIntersections();
1874        return true;
1875    }
1876    else
1877    {
1878        intersections.clear();
1879        return false;
1880    }
1881}
1882
1883bool View::computeIntersections(float x,float y, const osg::NodePath& nodePath, osgUtil::LineSegmentIntersector::Intersections& intersections,osg::Node::NodeMask traversalMask)
1884{
1885    if (!_camera.valid() || nodePath.empty()) return false;
1886
1887    float local_x, local_y = 0.0;
1888    const osg::Camera* camera = getCameraContainingPosition(x, y, local_x, local_y);
1889    if (!camera) camera = _camera.get();
1890
1891    osg::Matrixd matrix;
1892    if (nodePath.size()>1)
1893    {
1894        osg::NodePath prunedNodePath(nodePath.begin(),nodePath.end()-1);
1895        matrix = osg::computeLocalToWorld(prunedNodePath);
1896    }
1897
1898    matrix.postMult(camera->getViewMatrix());
1899    matrix.postMult(camera->getProjectionMatrix());
1900
1901    double zNear = -1.0;
1902    double zFar = 1.0;
1903    if (camera->getViewport())
1904    {
1905        matrix.postMult(camera->getViewport()->computeWindowMatrix());
1906        zNear = 0.0;
1907        zFar = 1.0;
1908    }
1909
1910    osg::Matrixd inverse;
1911    inverse.invert(matrix);
1912
1913    osg::Vec3d startVertex = osg::Vec3d(local_x,local_y,zNear) * inverse;
1914    osg::Vec3d endVertex = osg::Vec3d(local_x,local_y,zFar) * inverse;
1915
1916    osg::ref_ptr< osgUtil::LineSegmentIntersector > picker = new osgUtil::LineSegmentIntersector(osgUtil::Intersector::MODEL, startVertex, endVertex);
1917
1918    osgUtil::IntersectionVisitor iv(picker.get());
1919    iv.setTraversalMask(traversalMask);
1920    nodePath.back()->accept(iv);
1921
1922    if (picker->containsIntersections())
1923    {
1924        intersections = picker->getIntersections();
1925        return true;
1926    }
1927    else
1928    {
1929        intersections.clear();
1930        return false;
1931    }
1932}
1933
Note: See TracBrowser for help on using the browser.