1 // Copyright (C) 2008  Tim Moore
2 // Copyright (C) 2011  Mathias Froehlich
3 //
4 // This program is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU General Public License as
6 // published by the Free Software Foundation; either version 2 of the
7 // License, or (at your option) any later version.
8 //
9 // This program is distributed in the hope that it will be useful, but
10 // WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 // General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with this program; if not, write to the Free Software
16 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17 
18 #ifdef HAVE_CONFIG_H
19 #  include <config.h>
20 #endif
21 
22 #include "CameraGroup.hxx"
23 
24 #include <Main/fg_props.hxx>
25 #include <Main/globals.hxx>
26 #include "renderer.hxx"
27 #include "FGEventHandler.hxx"
28 #include "WindowBuilder.hxx"
29 #include "WindowSystemAdapter.hxx"
30 
31 #include <simgear/math/SGRect.hxx>
32 #include <simgear/props/props.hxx>
33 #include <simgear/props/props_io.hxx> // for copyProperties
34 #include <simgear/structure/OSGUtils.hxx>
35 #include <simgear/structure/OSGVersion.hxx>
36 #include <simgear/scene/material/EffectCullVisitor.hxx>
37 #include <simgear/scene/util/RenderConstants.hxx>
38 
39 #include <algorithm>
40 #include <cstring>
41 #include <string>
42 
43 #include <osg/Camera>
44 #include <osg/Geometry>
45 #include <osg/GraphicsContext>
46 #include <osg/io_utils>
47 #include <osg/Math>
48 #include <osg/Matrix>
49 #include <osg/Notify>
50 #include <osg/Program>
51 #include <osg/Quat>
52 #include <osg/TexMat>
53 #include <osg/Vec3d>
54 #include <osg/Viewport>
55 
56 #include <osgUtil/IntersectionVisitor>
57 
58 #include <osgViewer/GraphicsWindow>
59 #include <osgViewer/Renderer>
60 
61 using namespace osg;
62 
63 namespace
64 {
65 
66     // Given a projection matrix, return a new one with the same frustum
67     // sides and new near / far values.
68 
makeNewProjMat(Matrixd & oldProj,double znear,double zfar,Matrixd & projection)69     void makeNewProjMat(Matrixd& oldProj, double znear,
70                         double zfar, Matrixd& projection)
71     {
72         projection = oldProj;
73         // Slightly inflate the near & far planes to avoid objects at the
74         // extremes being clipped out.
75         znear *= 0.999;
76         zfar *= 1.001;
77 
78         // Clamp the projection matrix z values to the range (near, far)
79         double epsilon = 1.0e-6;
80         if (fabs(projection(0,3)) < epsilon &&
81             fabs(projection(1,3)) < epsilon &&
82             fabs(projection(2,3)) < epsilon) {
83             // Projection is Orthographic
84             epsilon = -1.0/(zfar - znear); // Used as a temp variable
85             projection(2,2) = 2.0*epsilon;
86             projection(3,2) = (zfar + znear)*epsilon;
87         } else {
88             // Projection is Perspective
89             double trans_near = (-znear*projection(2,2) + projection(3,2)) /
90             (-znear*projection(2,3) + projection(3,3));
91             double trans_far = (-zfar*projection(2,2) + projection(3,2)) /
92             (-zfar*projection(2,3) + projection(3,3));
93             double ratio = fabs(2.0/(trans_near - trans_far));
94             double center = -0.5*(trans_near + trans_far);
95 
96             projection.postMult(osg::Matrixd(1.0, 0.0, 0.0, 0.0,
97                                              0.0, 1.0, 0.0, 0.0,
98                                              0.0, 0.0, ratio, 0.0,
99                                              0.0, 0.0, center*ratio, 1.0));
100         }
101     }
102 
103     osg::Matrix
invert(const osg::Matrix & matrix)104     invert(const osg::Matrix& matrix)
105     {
106         return osg::Matrix::inverse(matrix);
107     }
108 
109     /// Returns the zoom factor of the master camera.
110     /// The reference fov is the historic 55 deg
111     double
zoomFactor()112     zoomFactor()
113     {
114         double fov = fgGetDouble("/sim/current-view/field-of-view", 55);
115         if (fov < 1)
116             fov = 1;
117         return tan(55*0.5*SG_DEGREES_TO_RADIANS)/tan(fov*0.5*SG_DEGREES_TO_RADIANS);
118     }
119 
120     osg::Vec2d
preMult(const osg::Vec2d & v,const osg::Matrix & m)121     preMult(const osg::Vec2d& v, const osg::Matrix& m)
122     {
123         osg::Vec3d tmp = m.preMult(osg::Vec3(v, 0));
124         return osg::Vec2d(tmp[0], tmp[1]);
125     }
126 
127     osg::Matrix
relativeProjection(const osg::Matrix & P0,const osg::Matrix & R,const osg::Vec2d ref[2],const osg::Matrix & pP,const osg::Matrix & pR,const osg::Vec2d pRef[2])128     relativeProjection(const osg::Matrix& P0, const osg::Matrix& R, const osg::Vec2d ref[2],
129                        const osg::Matrix& pP, const osg::Matrix& pR, const osg::Vec2d pRef[2])
130     {
131         // Track the way from one projection space to the other:
132         // We want
133         //  P = T*S*P0
134         // where P0 is the projection template sensible for the given window size,
135         // T is a translation matrix and S a scale matrix.
136         // We need to determine T and S so that the reference points in the parents
137         // projection space match the two reference points in this cameras projection space.
138 
139         // Starting from the parents camera projection space, we get into this cameras
140         // projection space by the transform matrix:
141         //  P*R*inv(pP*pR) = T*S*P0*R*inv(pP*pR)
142         // So, at first compute that matrix without T*S and determine S and T from that
143 
144         // Ok, now osg uses the inverse matrix multiplication order, thus:
145         osg::Matrix PtoPwithoutTS = invert(pR*pP)*R*P0;
146         // Compute the parents reference points in the current projection space
147         // without the yet unknown T and S
148         osg::Vec2d pRefInThis[2] = {
149             preMult(pRef[0], PtoPwithoutTS),
150             preMult(pRef[1], PtoPwithoutTS)
151         };
152 
153         // To get the same zoom, rescale to match the parents size
154         double s = (ref[0] - ref[1]).length()/(pRefInThis[0] - pRefInThis[1]).length();
155         osg::Matrix S = osg::Matrix::scale(s, s, 1);
156 
157         // For the translation offset, incorporate the now known scale
158         // and recompute the position ot the first reference point in the
159         // currents projection space without the yet unknown T.
160         pRefInThis[0] = preMult(pRef[0], PtoPwithoutTS*S);
161         // The translation is then the difference of the reference points
162         osg::Matrix T = osg::Matrix::translate(osg::Vec3d(ref[0] - pRefInThis[0], 0));
163 
164         // Compose and return the desired final projection matrix
165         return P0*S*T;
166     }
167 
168 } // of anonymous namespace
169 
170 typedef std::vector<SGPropertyNode_ptr> SGPropertyNodeVec;
171 
172 namespace flightgear
173 {
174 using namespace osg;
175 
176 using std::strcmp;
177 using std::string;
178 
179     class CameraGroupListener : public SGPropertyChangeListener
180     {
181     public:
CameraGroupListener(CameraGroup * cg,SGPropertyNode * gnode)182         CameraGroupListener(CameraGroup* cg, SGPropertyNode* gnode) :
183         _groupNode(gnode),
184         _cameraGroup(cg)
185         {
186             listenToNode("znear", 0.1f);
187             listenToNode("zfar", 120000.0f);
188             listenToNode("near-field", 100.0f);
189         }
190 
~CameraGroupListener()191         virtual ~CameraGroupListener()
192         {
193             unlisten("znear");
194             unlisten("zfar");
195             unlisten("near-field");
196         }
197 
valueChanged(SGPropertyNode * prop)198         virtual void valueChanged(SGPropertyNode* prop)
199         {
200             if (!strcmp(prop->getName(), "znear")) {
201                 _cameraGroup->setZNear(prop->getFloatValue());
202             } else if (!strcmp(prop->getName(), "zfar")) {
203                 _cameraGroup->setZFar(prop->getFloatValue());
204             } else if (!strcmp(prop->getName(), "near-field")) {
205                 _cameraGroup->setNearField(prop->getFloatValue());
206             }
207         }
208     private:
listenToNode(const std::string & name,double val)209         void listenToNode(const std::string& name, double val)
210         {
211             SGPropertyNode* n = _groupNode->getChild(name);
212             if (!n) {
213                 n = _groupNode->getChild(name, 0 /* index */, true);
214                 n->setDoubleValue(val);
215             }
216             n->addChangeListener(this);
217             valueChanged(n); // propogate initial state through
218         }
219 
unlisten(const std::string & name)220         void unlisten(const std::string& name)
221         {
222             _groupNode->getChild(name)->removeChangeListener(this);
223         }
224 
225         SGPropertyNode_ptr _groupNode;
226         CameraGroup* _cameraGroup; // non-owning reference
227 
228     };
229 
230     class CameraViewportListener : public SGPropertyChangeListener
231     {
232     public:
CameraViewportListener(CameraInfo * info,SGPropertyNode * vnode,const osg::GraphicsContext::Traits * traits)233         CameraViewportListener(CameraInfo* info,
234                                SGPropertyNode* vnode,
235                                const osg::GraphicsContext::Traits *traits) :
236         _viewportNode(vnode),
237         _camera(info)
238         {
239             listenToNode("x", 0.0f);
240             listenToNode("y", 0.0f);
241             listenToNode("width", traits->width);
242             listenToNode("height", traits->height);
243         }
244 
~CameraViewportListener()245         virtual ~CameraViewportListener()
246         {
247             unlisten("x");
248             unlisten("y");
249             unlisten("width");
250             unlisten("height");
251         }
252 
valueChanged(SGPropertyNode * prop)253         virtual void valueChanged(SGPropertyNode* prop)
254         {
255             if (!strcmp(prop->getName(), "x")) {
256                 _camera->x = prop->getDoubleValue();
257             } else if (!strcmp(prop->getName(), "y")) {
258                 _camera->y = prop->getDoubleValue();
259             } else if (!strcmp(prop->getName(), "width")) {
260                 _camera->width = prop->getDoubleValue();
261             } else if (!strcmp(prop->getName(), "height")) {
262                 _camera->height = prop->getDoubleValue();
263             }
264         }
265     private:
listenToNode(const std::string & name,double val)266         void listenToNode(const std::string& name, double val)
267         {
268             SGPropertyNode* n = _viewportNode->getChild(name);
269             if (!n) {
270                 n = _viewportNode->getChild(name, 0 /* index */, true);
271                 n->setDoubleValue(val);
272             }
273             n->addChangeListener(this);
274             valueChanged(n); // propogate initial state through
275         }
276 
unlisten(const std::string & name)277         void unlisten(const std::string& name)
278         {
279             _viewportNode->getChild(name)->removeChangeListener(this);
280         }
281 
282         SGPropertyNode_ptr _viewportNode;
283         CameraInfo* _camera;
284 
285     };
286 
287     const char* MAIN_CAMERA = "main";
288     const char* FAR_CAMERA = "far";
289     const char* GEOMETRY_CAMERA = "geometry";
290     const char* SHADOW_CAMERA = "shadow";
291     const char* LIGHTING_CAMERA = "lighting";
292     const char* DISPLAY_CAMERA = "display";
293 
updateCameras()294 void CameraInfo::updateCameras()
295 {
296     bufferSize->set( osg::Vec2f( width, height ) );
297 
298     for (CameraMap::iterator ii = cameras.begin(); ii != cameras.end(); ++ii ) {
299         float f = ii->second.scaleFactor;
300         if ( f == 0.0f ) continue;
301 
302         if (ii->second.camera->getRenderTargetImplementation() == osg::Camera::FRAME_BUFFER_OBJECT)
303             ii->second.camera->getViewport()->setViewport(0, 0, width*f, height*f);
304         else
305             ii->second.camera->getViewport()->setViewport(x*f, y*f, width*f, height*f);
306     }
307 
308     for (RenderBufferMap::iterator ii = buffers.begin(); ii != buffers.end(); ++ii ) {
309         float f = ii->second.scaleFactor;
310         if ( f == 0.0f ) continue;
311         osg::Texture2D* texture = ii->second.texture.get();
312         if ( texture->getTextureHeight() != height*f || texture->getTextureWidth() != width*f ) {
313             texture->setTextureSize( width*f, height*f );
314             texture->dirtyTextureObject();
315         }
316     }
317 }
318 
resized(double w,double h)319 void CameraInfo::resized(double w, double h)
320 {
321     if (w == 1.0 && h == 1.0)
322         return;
323 
324     bufferSize->set( osg::Vec2f( w, h ) );
325 
326     for (RenderBufferMap::iterator ii = buffers.begin(); ii != buffers.end(); ++ii) {
327         float s = ii->second.scaleFactor;
328         if ( s == 0.0f ) continue;
329         ii->second.texture->setTextureSize( w * s, h * s );
330         ii->second.texture->dirtyTextureObject();
331     }
332 
333     for (CameraMap::iterator ii = cameras.begin(); ii != cameras.end(); ++ii) {
334         RenderStageInfo& rsi = ii->second;
335         if (!rsi.resizable ||
336                 rsi.camera->getRenderTargetImplementation() != osg::Camera::FRAME_BUFFER_OBJECT ||
337                 rsi.scaleFactor == 0.0f )
338             continue;
339 
340         Viewport* vp = rsi.camera->getViewport();
341         vp->width() = w * rsi.scaleFactor;
342         vp->height() = h * rsi.scaleFactor;
343 
344         osgViewer::Renderer* renderer
345             = static_cast<osgViewer::Renderer*>(rsi.camera->getRenderer());
346         for (int i = 0; i < 2; ++i) {
347             osgUtil::SceneView* sceneView = renderer->getSceneView(i);
348             sceneView->getRenderStage()->setFrameBufferObject(0);
349             sceneView->getRenderStage()->setCameraRequiresSetUp(true);
350             if (sceneView->getRenderStageLeft()) {
351                 sceneView->getRenderStageLeft()->setFrameBufferObject(0);
352                 sceneView->getRenderStageLeft()->setCameraRequiresSetUp(true);
353             }
354             if (sceneView->getRenderStageRight()) {
355                 sceneView->getRenderStageRight()->setFrameBufferObject(0);
356                 sceneView->getRenderStageRight()->setCameraRequiresSetUp(true);
357             }
358         }
359     }
360 }
361 
~CameraInfo()362 CameraInfo::~CameraInfo()
363 {
364     delete viewportListener;
365 }
366 
getCamera(const std::string & k) const367 osg::Camera* CameraInfo::getCamera(const std::string& k) const
368 {
369     CameraMap::const_iterator ii = cameras.find( k );
370     if (ii == cameras.end())
371         return 0;
372     return ii->second.camera.get();
373 }
374 
getBuffer(const std::string & k) const375 osg::Texture2D* CameraInfo::getBuffer(const std::string& k) const
376 {
377     RenderBufferMap::const_iterator ii = buffers.find(k);
378     if (ii == buffers.end())
379         return 0;
380     return ii->second.texture.get();
381 }
382 
getMainSlaveIndex() const383 int CameraInfo::getMainSlaveIndex() const
384 {
385     return cameras.find( MAIN_CAMERA )->second.slaveIndex;
386 }
387 
setMatrices(osg::Camera * c)388 void CameraInfo::setMatrices(osg::Camera* c)
389 {
390     view->set( c->getViewMatrix() );
391     osg::Matrixd vi = c->getInverseViewMatrix();
392     viewInverse->set( vi );
393     projInverse->set( osg::Matrix::inverse( c->getProjectionMatrix() ) );
394     osg::Vec4d pos = osg::Vec4d(0., 0., 0., 1.) * vi;
395     worldPosCart->set( osg::Vec3f( pos.x(), pos.y(), pos.z() ) );
396     SGGeod pos2 = SGGeod::fromCart( SGVec3d( pos.x(), pos.y(), pos.z() ) );
397     worldPosGeod->set( osg::Vec3f( pos2.getLongitudeRad(), pos2.getLatitudeRad(), pos2.getElevationM() ) );
398 }
399 
~CameraGroup()400 CameraGroup::~CameraGroup()
401 {
402 
403     for (CameraList::iterator i = _cameras.begin(); i != _cameras.end(); ++i) {
404         CameraInfo* info = *i;
405         for (CameraMap::iterator ii = info->cameras.begin(); ii != info->cameras.end(); ++ii) {
406             RenderStageInfo& rsi = ii->second;
407             unsigned int slaveIndex = _viewer->findSlaveIndexForCamera(rsi.camera);
408             _viewer->removeSlave(slaveIndex);
409         }
410     }
411 
412     _cameras.clear();
413 }
414 
update(const osg::Vec3d & position,const osg::Quat & orientation)415 void CameraGroup::update(const osg::Vec3d& position,
416                          const osg::Quat& orientation)
417 {
418     const Matrix masterView(osg::Matrix::translate(-position)
419                             * osg::Matrix::rotate(orientation.inverse()));
420     _viewer->getCamera()->setViewMatrix(masterView);
421     const Matrix& masterProj = _viewer->getCamera()->getProjectionMatrix();
422     double masterZoomFactor = zoomFactor();
423     for (CameraList::iterator i = _cameras.begin(); i != _cameras.end(); ++i) {
424         const CameraInfo* info = i->get();
425 
426         Camera* camera = info->getCamera(MAIN_CAMERA);
427         if ( camera ) {
428             const osg::View::Slave& slave = _viewer->getSlave(info->getMainSlaveIndex());
429 
430             Matrix viewMatrix;
431             if (info->flags & GUI) {
432                 viewMatrix = osg::Matrix(); // identifty transform on the GUI camera
433             } else if ((info->flags & VIEW_ABSOLUTE) != 0)
434                 viewMatrix = slave._viewOffset;
435             else
436                 viewMatrix = masterView * slave._viewOffset;
437             camera->setViewMatrix(viewMatrix);
438             Matrix projectionMatrix;
439             if (info->flags & GUI) {
440                 projectionMatrix = osg::Matrix::ortho2D(0, info->width, 0, info->height);
441             } else if ((info->flags & PROJECTION_ABSOLUTE) != 0) {
442                 if (info->flags & ENABLE_MASTER_ZOOM) {
443                     if (info->relativeCameraParent < _cameras.size()) {
444                         // template projection matrix and view matrix of the current camera
445                         osg::Matrix P0 = slave._projectionOffset;
446                         osg::Matrix R = viewMatrix;
447 
448                         // The already known projection and view matrix of the parent camera
449                         const CameraInfo* parentInfo = _cameras[info->relativeCameraParent].get();
450                         RenderStageInfo prsi = parentInfo->cameras.find(MAIN_CAMERA)->second;
451                         osg::Matrix pP = prsi.camera->getProjectionMatrix();
452                         osg::Matrix pR = prsi.camera->getViewMatrix();
453 
454                         // And the projection matrix derived from P0 so that the reference points match
455                         projectionMatrix = relativeProjection(P0, R, info->thisReference,
456                                                               pP, pR, info->parentReference);
457 
458                     } else {
459                         // We want to zoom, so take the original matrix and apply the zoom to it.
460                         projectionMatrix = slave._projectionOffset;
461                         projectionMatrix.postMultScale(osg::Vec3d(masterZoomFactor, masterZoomFactor, 1));
462                     }
463                 } else {
464                     projectionMatrix = slave._projectionOffset;
465                 }
466             } else {
467                 projectionMatrix = masterProj * slave._projectionOffset;
468             }
469 
470             CameraMap::const_iterator ii = info->cameras.find(FAR_CAMERA);
471             if (ii == info->cameras.end() || !ii->second.camera.valid()) {
472                 camera->setProjectionMatrix(projectionMatrix);
473             } else {
474                 Camera* farCamera = ii->second.camera;
475                 farCamera->setViewMatrix(viewMatrix);
476                 double left, right, bottom, top, parentNear, parentFar;
477                 projectionMatrix.getFrustum(left, right, bottom, top,
478                                             parentNear, parentFar);
479                 if ((info->flags & FIXED_NEAR_FAR) == 0) {
480                     parentNear = _zNear;
481                     parentFar = _zFar;
482                 }
483                 if (parentFar < _nearField || _nearField == 0.0f) {
484                     camera->setProjectionMatrix(projectionMatrix);
485                     camera->setCullMask(camera->getCullMask()
486                                         | simgear::BACKGROUND_BIT);
487                     camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
488                     farCamera->setNodeMask(0);
489                 } else {
490                     Matrix nearProj, farProj;
491                     makeNewProjMat(projectionMatrix, parentNear, _nearField,
492                                    nearProj);
493                     makeNewProjMat(projectionMatrix, _nearField, parentFar,
494                                    farProj);
495                     camera->setProjectionMatrix(nearProj);
496                     camera->setCullMask(camera->getCullMask()
497                                         & ~simgear::BACKGROUND_BIT);
498                     camera->setClearMask(GL_DEPTH_BUFFER_BIT);
499                     farCamera->setProjectionMatrix(farProj);
500                     farCamera->setNodeMask(camera->getNodeMask());
501                 }
502             }
503         } else {
504             bool viewDone = false;
505             Matrix viewMatrix;
506             bool projectionDone = false;
507             Matrix projectionMatrix;
508             for ( CameraMap::const_iterator ii = info->cameras.begin(); ii != info->cameras.end(); ++ii ) {
509                 if ( ii->first == SHADOW_CAMERA ) {
510                     globals->get_renderer()->updateShadowCamera(info, position);
511                     continue;
512                 }
513                 if ( ii->second.fullscreen )
514                     continue;
515 
516                 Camera* camera = ii->second.camera.get();
517                 int slaveIndex = ii->second.slaveIndex;
518                 const osg::View::Slave& slave = _viewer->getSlave(slaveIndex);
519 
520                 if ( !viewDone ) {
521                     if ((info->flags & VIEW_ABSOLUTE) != 0)
522                         viewMatrix = slave._viewOffset;
523                     else
524                         viewMatrix = masterView * slave._viewOffset;
525                     viewDone = true;
526                 }
527 
528                 camera->setViewMatrix( viewMatrix );
529 
530                 if ( !projectionDone ) {
531                     if ((info->flags & PROJECTION_ABSOLUTE) != 0) {
532                         if (info->flags & ENABLE_MASTER_ZOOM) {
533                             if (info->relativeCameraParent < _cameras.size()) {
534                                 // template projection matrix and view matrix of the current camera
535                                 osg::Matrix P0 = slave._projectionOffset;
536                                 osg::Matrix R = viewMatrix;
537 
538                                 // The already known projection and view matrix of the parent camera
539                                 const CameraInfo* parentInfo = _cameras[info->relativeCameraParent].get();
540                                 RenderStageInfo prsi = parentInfo->cameras.find(MAIN_CAMERA)->second;
541                                 osg::Matrix pP = prsi.camera->getProjectionMatrix();
542                                 osg::Matrix pR = prsi.camera->getViewMatrix();
543 
544                                 // And the projection matrix derived from P0 so that the reference points match
545                                 projectionMatrix = relativeProjection(P0, R, info->thisReference,
546                                                                       pP, pR, info->parentReference);
547 
548                             } else {
549                                 // We want to zoom, so take the original matrix and apply the zoom to it.
550                                 projectionMatrix = slave._projectionOffset;
551                                 projectionMatrix.postMultScale(osg::Vec3d(masterZoomFactor, masterZoomFactor, 1));
552                             }
553                         } else {
554                             projectionMatrix = slave._projectionOffset;
555                         }
556                     } else {
557                         projectionMatrix = masterProj * slave._projectionOffset;
558                     }
559                     projectionDone = true;
560                 }
561 
562                 camera->setProjectionMatrix(projectionMatrix);
563             }
564         }
565     }
566 
567     globals->get_renderer()->setPlanes( _zNear, _zFar );
568 }
569 
570 ref_ptr<CameraGroup> CameraGroup::_defaultGroup;
571 
CameraGroup(osgViewer::Viewer * viewer)572 CameraGroup::CameraGroup(osgViewer::Viewer* viewer) :
573 _viewer(viewer)
574 {
575 }
576 
setCameraParameters(float vfov,float aspectRatio)577 void CameraGroup::setCameraParameters(float vfov, float aspectRatio)
578 {
579     if (vfov != 0.0f && aspectRatio != 0.0f)
580         _viewer->getCamera()
581             ->setProjectionMatrixAsPerspective(vfov,
582                                                1.0f / aspectRatio,
583                                                _zNear, _zFar);
584 }
585 
getMasterAspectRatio() const586 double CameraGroup::getMasterAspectRatio() const
587 {
588     if (_cameras.empty())
589         return 0.0;
590 
591     const CameraInfo* info = _cameras.front();
592 
593     osg::Camera* camera = info->getCamera(MAIN_CAMERA);
594     if ( !camera )
595         camera = info->getCamera( GEOMETRY_CAMERA );
596     const osg::Viewport* viewport = camera->getViewport();
597     if (!viewport) {
598         return 0.0;
599     }
600 
601     return static_cast<double>(viewport->height()) / viewport->width();
602 }
603 
604 // Mostly copied from osg's osgViewer/View.cpp
605 
createPanoramicSphericalDisplayDistortionMesh(const Vec3 & origin,const Vec3 & widthVector,const Vec3 & heightVector,double sphere_radius,double collar_radius,Image * intensityMap=0,const Matrix & projectorMatrix=Matrix ())606 static osg::Geometry* createPanoramicSphericalDisplayDistortionMesh(
607     const Vec3& origin, const Vec3& widthVector, const Vec3& heightVector,
608     double sphere_radius, double collar_radius,
609     Image* intensityMap = 0, const Matrix& projectorMatrix = Matrix())
610 {
611     osg::Vec3d center(0.0,0.0,0.0);
612     osg::Vec3d eye(0.0,0.0,0.0);
613 
614     double distance = sqrt(sphere_radius*sphere_radius - collar_radius*collar_radius);
615     bool flip = false;
616     bool texcoord_flip = false;
617 
618 #if 0
619     osg::Vec3d projector = eye - osg::Vec3d(0.0,0.0, distance);
620 
621     OSG_INFO<<"createPanoramicSphericalDisplayDistortionMesh : Projector position = "<<projector<<std::endl;
622     OSG_INFO<<"createPanoramicSphericalDisplayDistortionMesh : distance = "<<distance<<std::endl;
623 #endif
624     // create the quad to visualize.
625     osg::Geometry* geometry = new osg::Geometry();
626 
627     geometry->setSupportsDisplayList(false);
628 
629     osg::Vec3 xAxis(widthVector);
630     float width = widthVector.length();
631     xAxis /= width;
632 
633     osg::Vec3 yAxis(heightVector);
634     float height = heightVector.length();
635     yAxis /= height;
636 
637     int noSteps = 160;
638 
639     osg::Vec3Array* vertices = new osg::Vec3Array;
640     osg::Vec2Array* texcoords0 = new osg::Vec2Array;
641     osg::Vec2Array* texcoords1 = intensityMap==0 ? new osg::Vec2Array : 0;
642     osg::Vec4Array* colors = new osg::Vec4Array;
643 
644 #if 0
645     osg::Vec3 bottom = origin;
646     osg::Vec3 dx = xAxis*(width/((float)(noSteps-2)));
647     osg::Vec3 dy = yAxis*(height/((float)(noSteps-1)));
648 #endif
649     osg::Vec3 top = origin + yAxis*height;
650 
651     osg::Vec3 screenCenter = origin + widthVector*0.5f + heightVector*0.5f;
652     float screenRadius = heightVector.length() * 0.5f;
653 
654     geometry->getOrCreateStateSet()->setMode(GL_CULL_FACE, osg::StateAttribute::OFF | osg::StateAttribute::PROTECTED);
655 
656     for(int i=0;i<noSteps;++i)
657     {
658         //osg::Vec3 cursor = bottom+dy*(float)i;
659         for(int j=0;j<noSteps;++j)
660         {
661             osg::Vec2 texcoord(double(i)/double(noSteps-1), double(j)/double(noSteps-1));
662             double theta = texcoord.x() * 2.0 * osg::PI;
663             double phi = (1.0-texcoord.y()) * osg::PI;
664 
665             if (texcoord_flip) texcoord.y() = 1.0f - texcoord.y();
666 
667             osg::Vec3 pos(sin(phi)*sin(theta), sin(phi)*cos(theta), cos(phi));
668             pos = pos*projectorMatrix;
669 
670             double alpha = atan2(pos.x(), pos.y());
671             if (alpha<0.0) alpha += 2.0*osg::PI;
672 
673             double beta = atan2(sqrt(pos.x()*pos.x() + pos.y()*pos.y()), pos.z());
674             if (beta<0.0) beta += 2.0*osg::PI;
675 
676             double gamma = atan2(sqrt(double(pos.x()*pos.x() + pos.y()*pos.y())), double(pos.z()+distance));
677             if (gamma<0.0) gamma += 2.0*osg::PI;
678 
679 
680             osg::Vec3 v = screenCenter + osg::Vec3(sin(alpha)*gamma*2.0/osg::PI, -cos(alpha)*gamma*2.0/osg::PI, 0.0f)*screenRadius;
681 
682             if (flip)
683                 vertices->push_back(osg::Vec3(v.x(), top.y()-(v.y()-origin.y()),v.z()));
684             else
685                 vertices->push_back(v);
686 
687             texcoords0->push_back( texcoord );
688 
689             osg::Vec2 texcoord1(alpha/(2.0*osg::PI), 1.0f - beta/osg::PI);
690             if (intensityMap)
691             {
692                 colors->push_back(intensityMap->getColor(texcoord1));
693             }
694             else
695             {
696                 colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
697                 if (texcoords1) texcoords1->push_back( texcoord1 );
698             }
699 
700 
701         }
702     }
703 
704 
705     // pass the created vertex array to the points geometry object.
706     geometry->setVertexArray(vertices);
707 
708     geometry->setColorArray(colors);
709     geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
710 
711     geometry->setTexCoordArray(0,texcoords0);
712     if (texcoords1) geometry->setTexCoordArray(1,texcoords1);
713 
714     osg::DrawElementsUShort* elements = new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLES);
715     geometry->addPrimitiveSet(elements);
716 
717     for(int i=0;i<noSteps-1;++i)
718     {
719         for(int j=0;j<noSteps-1;++j)
720         {
721             int i1 = j+(i+1)*noSteps;
722             int i2 = j+(i)*noSteps;
723             int i3 = j+1+(i)*noSteps;
724             int i4 = j+1+(i+1)*noSteps;
725 
726             osg::Vec3& v1 = (*vertices)[i1];
727             osg::Vec3& v2 = (*vertices)[i2];
728             osg::Vec3& v3 = (*vertices)[i3];
729             osg::Vec3& v4 = (*vertices)[i4];
730 
731             if ((v1-screenCenter).length()>screenRadius) continue;
732             if ((v2-screenCenter).length()>screenRadius) continue;
733             if ((v3-screenCenter).length()>screenRadius) continue;
734             if ((v4-screenCenter).length()>screenRadius) continue;
735 
736             elements->push_back(i1);
737             elements->push_back(i2);
738             elements->push_back(i3);
739 
740             elements->push_back(i1);
741             elements->push_back(i3);
742             elements->push_back(i4);
743         }
744     }
745 
746     return geometry;
747 }
748 
buildDistortionCamera(const SGPropertyNode * psNode,Camera * camera)749 void CameraGroup::buildDistortionCamera(const SGPropertyNode* psNode,
750                                         Camera* camera)
751 {
752     const SGPropertyNode* texNode = psNode->getNode("texture");
753     if (!texNode) {
754         // error
755         return;
756     }
757     string texName = texNode->getStringValue();
758     TextureMap::iterator itr = _textureTargets.find(texName);
759     if (itr == _textureTargets.end()) {
760         // error
761         return;
762     }
763     Viewport* viewport = camera->getViewport();
764     float width = viewport->width();
765     float height = viewport->height();
766     TextureRectangle* texRect = itr->second.get();
767     double radius = psNode->getDoubleValue("radius", 1.0);
768     double collar = psNode->getDoubleValue("collar", 0.45);
769     Geode* geode = new Geode();
770     geode->addDrawable(createPanoramicSphericalDisplayDistortionMesh(
771                            Vec3(0.0f,0.0f,0.0f), Vec3(width,0.0f,0.0f),
772                            Vec3(0.0f,height,0.0f), radius, collar));
773 
774     // new we need to add the texture to the mesh, we do so by creating a
775     // StateSet to contain the Texture StateAttribute.
776     StateSet* stateset = geode->getOrCreateStateSet();
777     stateset->setTextureAttributeAndModes(0, texRect, StateAttribute::ON);
778     stateset->setMode(GL_LIGHTING, StateAttribute::OFF);
779 
780     TexMat* texmat = new TexMat;
781     texmat->setScaleByTextureRectangleSize(true);
782     stateset->setTextureAttributeAndModes(0, texmat, osg::StateAttribute::ON);
783 #if 0
784     if (!applyIntensityMapAsColours && intensityMap)
785     {
786         stateset->setTextureAttributeAndModes(1, new osg::Texture2D(intensityMap), osg::StateAttribute::ON);
787     }
788 #endif
789     // add subgraph to render
790     camera->addChild(geode);
791     camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
792     camera->setClearColor(osg::Vec4(0.0, 0.0, 0.0, 1.0));
793     camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
794     camera->setCullingMode(osg::CullSettings::NO_CULLING);
795     camera->setName("DistortionCorrectionCamera");
796 }
797 
buildCamera(SGPropertyNode * cameraNode)798 CameraInfo* CameraGroup::buildCamera(SGPropertyNode* cameraNode)
799 {
800     WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
801     const SGPropertyNode* windowNode = cameraNode->getNode("window");
802     GraphicsWindow* window = 0;
803     int cameraFlags = DO_INTERSECTION_TEST;
804     if (windowNode) {
805         // New style window declaration / definition
806         window = wBuild->buildWindow(windowNode);
807     } else {
808         // Old style: suck window params out of camera block
809         window = wBuild->buildWindow(cameraNode);
810     }
811     if (!window) {
812         return 0;
813     }
814     Camera* camera = new Camera;
815     camera->setName("windowCamera");
816     camera->setAllowEventFocus(false);
817     camera->setGraphicsContext(window->gc.get());
818     camera->setViewport(new Viewport);
819     camera->setCullingMode(CullSettings::SMALL_FEATURE_CULLING
820                            | CullSettings::VIEW_FRUSTUM_CULLING);
821     camera->setInheritanceMask(CullSettings::ALL_VARIABLES
822                                & ~(CullSettings::CULL_MASK
823                                    | CullSettings::CULLING_MODE
824                                    | CullSettings::CLEAR_MASK
825                                    ));
826 
827     osg::Matrix vOff;
828     const SGPropertyNode* viewNode = cameraNode->getNode("view");
829     if (viewNode) {
830         double heading = viewNode->getDoubleValue("heading-deg", 0.0);
831         double pitch = viewNode->getDoubleValue("pitch-deg", 0.0);
832         double roll = viewNode->getDoubleValue("roll-deg", 0.0);
833         double x = viewNode->getDoubleValue("x", 0.0);
834         double y = viewNode->getDoubleValue("y", 0.0);
835         double z = viewNode->getDoubleValue("z", 0.0);
836         // Build a view matrix, which is the inverse of a model
837         // orientation matrix.
838         vOff = (Matrix::translate(-x, -y, -z)
839                 * Matrix::rotate(-DegreesToRadians(heading),
840                                  Vec3d(0.0, 1.0, 0.0),
841                                  -DegreesToRadians(pitch),
842                                  Vec3d(1.0, 0.0, 0.0),
843                                  -DegreesToRadians(roll),
844                                  Vec3d(0.0, 0.0, 1.0)));
845         if (viewNode->getBoolValue("absolute", false))
846             cameraFlags |= VIEW_ABSOLUTE;
847     } else {
848         // Old heading parameter, works in the opposite direction
849         double heading = cameraNode->getDoubleValue("heading-deg", 0.0);
850         vOff.makeRotate(DegreesToRadians(heading), osg::Vec3(0, 1, 0));
851     }
852     // Configuring the physical dimensions of a monitor
853     SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
854     double physicalWidth = viewportNode->getDoubleValue("width", 1024);
855     double physicalHeight = viewportNode->getDoubleValue("height", 768);
856     double bezelHeightTop = 0;
857     double bezelHeightBottom = 0;
858     double bezelWidthLeft = 0;
859     double bezelWidthRight = 0;
860     const SGPropertyNode* physicalDimensionsNode = 0;
861     if ((physicalDimensionsNode = cameraNode->getNode("physical-dimensions")) != 0) {
862         physicalWidth = physicalDimensionsNode->getDoubleValue("width", physicalWidth);
863         physicalHeight = physicalDimensionsNode->getDoubleValue("height", physicalHeight);
864         const SGPropertyNode* bezelNode = 0;
865         if ((bezelNode = physicalDimensionsNode->getNode("bezel")) != 0) {
866             bezelHeightTop = bezelNode->getDoubleValue("top", bezelHeightTop);
867             bezelHeightBottom = bezelNode->getDoubleValue("bottom", bezelHeightBottom);
868             bezelWidthLeft = bezelNode->getDoubleValue("left", bezelWidthLeft);
869             bezelWidthRight = bezelNode->getDoubleValue("right", bezelWidthRight);
870         }
871     }
872     osg::Matrix pOff;
873     unsigned parentCameraIndex = ~0u;
874     osg::Vec2d parentReference[2];
875     osg::Vec2d thisReference[2];
876     SGPropertyNode* projectionNode = 0;
877     if ((projectionNode = cameraNode->getNode("perspective")) != 0) {
878         double fovy = projectionNode->getDoubleValue("fovy-deg", 55.0);
879         double aspectRatio = projectionNode->getDoubleValue("aspect-ratio",
880                                                             1.0);
881         double zNear = projectionNode->getDoubleValue("near", 0.0);
882         double zFar = projectionNode->getDoubleValue("far", zNear + 20000);
883         double offsetX = projectionNode->getDoubleValue("offset-x", 0.0);
884         double offsetY = projectionNode->getDoubleValue("offset-y", 0.0);
885         double tan_fovy = tan(DegreesToRadians(fovy*0.5));
886         double right = tan_fovy * aspectRatio * zNear + offsetX;
887         double left = -tan_fovy * aspectRatio * zNear + offsetX;
888         double top = tan_fovy * zNear + offsetY;
889         double bottom = -tan_fovy * zNear + offsetY;
890         pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
891         cameraFlags |= PROJECTION_ABSOLUTE;
892         if (projectionNode->getBoolValue("fixed-near-far", true))
893             cameraFlags |= FIXED_NEAR_FAR;
894     } else if ((projectionNode = cameraNode->getNode("frustum")) != 0
895                || (projectionNode = cameraNode->getNode("ortho")) != 0) {
896         double top = projectionNode->getDoubleValue("top", 0.0);
897         double bottom = projectionNode->getDoubleValue("bottom", 0.0);
898         double left = projectionNode->getDoubleValue("left", 0.0);
899         double right = projectionNode->getDoubleValue("right", 0.0);
900         double zNear = projectionNode->getDoubleValue("near", 0.0);
901         double zFar = projectionNode->getDoubleValue("far", zNear + 20000);
902         if (cameraNode->getNode("frustum")) {
903             pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
904             cameraFlags |= PROJECTION_ABSOLUTE;
905         } else {
906             pOff.makeOrtho(left, right, bottom, top, zNear, zFar);
907             cameraFlags |= (PROJECTION_ABSOLUTE | ORTHO);
908         }
909         if (projectionNode->getBoolValue("fixed-near-far", true))
910             cameraFlags |= FIXED_NEAR_FAR;
911     } else if ((projectionNode = cameraNode->getNode("master-perspective")) != 0) {
912         double zNear = projectionNode->getDoubleValue("eye-distance", 0.4*physicalWidth);
913         double xoff = projectionNode->getDoubleValue("x-offset", 0);
914         double yoff = projectionNode->getDoubleValue("y-offset", 0);
915         double left = -0.5*physicalWidth - xoff;
916         double right = 0.5*physicalWidth - xoff;
917         double bottom = -0.5*physicalHeight - yoff;
918         double top = 0.5*physicalHeight - yoff;
919         pOff.makeFrustum(left, right, bottom, top, zNear, zNear*1000);
920         cameraFlags |= PROJECTION_ABSOLUTE | ENABLE_MASTER_ZOOM;
921     } else if ((projectionNode = cameraNode->getNode("right-of-perspective"))
922                || (projectionNode = cameraNode->getNode("left-of-perspective"))
923                || (projectionNode = cameraNode->getNode("above-perspective"))
924                || (projectionNode = cameraNode->getNode("below-perspective"))
925                || (projectionNode = cameraNode->getNode("reference-points-perspective"))) {
926         std::string name = projectionNode->getStringValue("parent-camera");
927         for (unsigned i = 0; i < _cameras.size(); ++i) {
928             if (_cameras[i]->name != name)
929                 continue;
930             parentCameraIndex = i;
931         }
932         if (_cameras.size() <= parentCameraIndex) {
933             SG_LOG(SG_VIEW, SG_ALERT, "CameraGroup::buildCamera: "
934                    "failed to find parent camera for relative camera!");
935             return 0;
936         }
937         const CameraInfo* parentInfo = _cameras[parentCameraIndex].get();
938         if (projectionNode->getNameString() == "right-of-perspective") {
939             double tmp = (parentInfo->physicalWidth + 2*parentInfo->bezelWidthRight)/parentInfo->physicalWidth;
940             parentReference[0] = osg::Vec2d(tmp, -1);
941             parentReference[1] = osg::Vec2d(tmp, 1);
942             tmp = (physicalWidth + 2*bezelWidthLeft)/physicalWidth;
943             thisReference[0] = osg::Vec2d(-tmp, -1);
944             thisReference[1] = osg::Vec2d(-tmp, 1);
945         } else if (projectionNode->getNameString() == "left-of-perspective") {
946             double tmp = (parentInfo->physicalWidth + 2*parentInfo->bezelWidthLeft)/parentInfo->physicalWidth;
947             parentReference[0] = osg::Vec2d(-tmp, -1);
948             parentReference[1] = osg::Vec2d(-tmp, 1);
949             tmp = (physicalWidth + 2*bezelWidthRight)/physicalWidth;
950             thisReference[0] = osg::Vec2d(tmp, -1);
951             thisReference[1] = osg::Vec2d(tmp, 1);
952         } else if (projectionNode->getNameString() == "above-perspective") {
953             double tmp = (parentInfo->physicalHeight + 2*parentInfo->bezelHeightTop)/parentInfo->physicalHeight;
954             parentReference[0] = osg::Vec2d(-1, tmp);
955             parentReference[1] = osg::Vec2d(1, tmp);
956             tmp = (physicalHeight + 2*bezelHeightBottom)/physicalHeight;
957             thisReference[0] = osg::Vec2d(-1, -tmp);
958             thisReference[1] = osg::Vec2d(1, -tmp);
959         } else if (projectionNode->getNameString() == "below-perspective") {
960             double tmp = (parentInfo->physicalHeight + 2*parentInfo->bezelHeightBottom)/parentInfo->physicalHeight;
961             parentReference[0] = osg::Vec2d(-1, -tmp);
962             parentReference[1] = osg::Vec2d(1, -tmp);
963             tmp = (physicalHeight + 2*bezelHeightTop)/physicalHeight;
964             thisReference[0] = osg::Vec2d(-1, tmp);
965             thisReference[1] = osg::Vec2d(1, tmp);
966         } else if (projectionNode->getNameString() == "reference-points-perspective") {
967             SGPropertyNode* parentNode = projectionNode->getNode("parent", true);
968             SGPropertyNode* thisNode = projectionNode->getNode("this", true);
969             SGPropertyNode* pointNode;
970 
971             pointNode = parentNode->getNode("point", 0, true);
972             parentReference[0][0] = pointNode->getDoubleValue("x", 0)*2/parentInfo->physicalWidth;
973             parentReference[0][1] = pointNode->getDoubleValue("y", 0)*2/parentInfo->physicalHeight;
974             pointNode = parentNode->getNode("point", 1, true);
975             parentReference[1][0] = pointNode->getDoubleValue("x", 0)*2/parentInfo->physicalWidth;
976             parentReference[1][1] = pointNode->getDoubleValue("y", 0)*2/parentInfo->physicalHeight;
977 
978             pointNode = thisNode->getNode("point", 0, true);
979             thisReference[0][0] = pointNode->getDoubleValue("x", 0)*2/physicalWidth;
980             thisReference[0][1] = pointNode->getDoubleValue("y", 0)*2/physicalHeight;
981             pointNode = thisNode->getNode("point", 1, true);
982             thisReference[1][0] = pointNode->getDoubleValue("x", 0)*2/physicalWidth;
983             thisReference[1][1] = pointNode->getDoubleValue("y", 0)*2/physicalHeight;
984         }
985 
986         pOff = osg::Matrix::perspective(45, physicalWidth/physicalHeight, 1, 20000);
987         cameraFlags |= PROJECTION_ABSOLUTE | ENABLE_MASTER_ZOOM;
988     } else {
989         // old style shear parameters
990         double shearx = cameraNode->getDoubleValue("shear-x", 0);
991         double sheary = cameraNode->getDoubleValue("shear-y", 0);
992         pOff.makeTranslate(-shearx, -sheary, 0);
993     }
994     const SGPropertyNode* textureNode = cameraNode->getNode("texture");
995     if (textureNode) {
996         string texName = textureNode->getStringValue("name");
997         int tex_width = textureNode->getIntValue("width");
998         int tex_height = textureNode->getIntValue("height");
999         TextureRectangle* texture = new TextureRectangle;
1000 
1001         texture->setTextureSize(tex_width, tex_height);
1002         texture->setInternalFormat(GL_RGB);
1003         texture->setFilter(Texture::MIN_FILTER, Texture::LINEAR);
1004         texture->setFilter(Texture::MAG_FILTER, Texture::LINEAR);
1005         texture->setWrap(Texture::WRAP_S, Texture::CLAMP_TO_EDGE);
1006         texture->setWrap(Texture::WRAP_T, Texture::CLAMP_TO_EDGE);
1007         camera->setDrawBuffer(GL_FRONT);
1008         camera->setReadBuffer(GL_FRONT);
1009         camera->setRenderTargetImplementation(Camera::FRAME_BUFFER_OBJECT);
1010         camera->attach(Camera::COLOR_BUFFER, texture);
1011         _textureTargets[texName] = texture;
1012     } else {
1013         camera->setDrawBuffer(GL_BACK);
1014         camera->setReadBuffer(GL_BACK);
1015     }
1016     const SGPropertyNode* psNode = cameraNode->getNode("panoramic-spherical");
1017     bool useMasterSceneGraph = !psNode;
1018     CameraInfo* info = globals->get_renderer()->buildRenderingPipeline(this, cameraFlags, camera, vOff, pOff,
1019                                                                         window->gc.get(), useMasterSceneGraph);
1020 
1021     info->name = cameraNode->getStringValue("name");
1022     info->physicalWidth = physicalWidth;
1023     info->physicalHeight = physicalHeight;
1024     info->bezelHeightTop = bezelHeightTop;
1025     info->bezelHeightBottom = bezelHeightBottom;
1026     info->bezelWidthLeft = bezelWidthLeft;
1027     info->bezelWidthRight = bezelWidthRight;
1028     info->relativeCameraParent = parentCameraIndex;
1029     info->parentReference[0] = parentReference[0];
1030     info->parentReference[1] = parentReference[1];
1031     info->thisReference[0] = thisReference[0];
1032     info->thisReference[1] = thisReference[1];
1033 
1034     // If a viewport isn't set on the camera, then it's hard to dig it
1035     // out of the SceneView objects in the viewer, and the coordinates
1036     // of mouse events are somewhat bizzare.
1037 
1038     info->viewportListener = new CameraViewportListener(info, viewportNode, window->gc->getTraits());
1039 
1040     info->updateCameras();
1041     // Distortion camera needs the viewport which is created by addCamera().
1042     if (psNode) {
1043         info->flags = info->flags | VIEW_ABSOLUTE;
1044         buildDistortionCamera(psNode, camera);
1045     }
1046     return info;
1047 }
1048 
buildGUICamera(SGPropertyNode * cameraNode,GraphicsWindow * window)1049 CameraInfo* CameraGroup::buildGUICamera(SGPropertyNode* cameraNode,
1050                                         GraphicsWindow* window)
1051 {
1052     WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
1053     const SGPropertyNode* windowNode = (cameraNode
1054                                         ? cameraNode->getNode("window")
1055                                         : 0);
1056     if (!window && windowNode) {
1057       // New style window declaration / definition
1058       window = wBuild->buildWindow(windowNode);
1059     }
1060 
1061     if (!window) { // buildWindow can fail
1062       SG_LOG(SG_VIEW, SG_WARN, "CameraGroup::buildGUICamera: failed to build a window");
1063       return NULL;
1064     }
1065 
1066     Camera* camera = new Camera;
1067     camera->setName( "GUICamera" );
1068     camera->setAllowEventFocus(false);
1069     camera->setGraphicsContext(window->gc.get());
1070     camera->setViewport(new Viewport);
1071     camera->setClearMask(0);
1072     camera->setInheritanceMask(CullSettings::ALL_VARIABLES
1073                                & ~(CullSettings::COMPUTE_NEAR_FAR_MODE
1074                                    | CullSettings::CULLING_MODE
1075                                    | CullSettings::CLEAR_MASK
1076                                    ));
1077     camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1078     camera->setCullingMode(osg::CullSettings::NO_CULLING);
1079     camera->setProjectionResizePolicy(Camera::FIXED);
1080     camera->setReferenceFrame(Transform::ABSOLUTE_RF);
1081     const int cameraFlags = GUI | DO_INTERSECTION_TEST;
1082 
1083     CameraInfo* result = new CameraInfo(cameraFlags);
1084     result->name = "GUI camera";
1085     // The camera group will always update the camera
1086     camera->setReferenceFrame(Transform::ABSOLUTE_RF);
1087 
1088     // Draw all nodes in the order they are added to the GUI camera
1089     camera->getOrCreateStateSet()
1090           ->setRenderBinDetails( 0,
1091                                  "PreOrderBin",
1092                                  osg::StateSet::OVERRIDE_RENDERBIN_DETAILS );
1093 
1094     getViewer()->addSlave(camera, Matrixd::identity(), Matrixd::identity(), false);
1095     //installCullVisitor(camera);
1096     int slaveIndex = getViewer()->getNumSlaves() - 1;
1097     result->addCamera( MAIN_CAMERA, camera, slaveIndex );
1098     camera->setRenderOrder(Camera::POST_RENDER, slaveIndex);
1099     addCamera(result);
1100 
1101     // XXX Camera needs to be drawn last; eventually the render order
1102     // should be assigned by a camera manager.
1103     camera->setRenderOrder(osg::Camera::POST_RENDER, 10000);
1104     SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
1105 
1106     result->viewportListener = new CameraViewportListener(result, viewportNode,
1107                                                               window->gc->getTraits());
1108 
1109     // Disable statistics for the GUI camera.
1110     camera->setStats(0);
1111     result->updateCameras();
1112     return result;
1113 }
1114 
buildCameraGroup(osgViewer::Viewer * viewer,SGPropertyNode * gnode)1115 CameraGroup* CameraGroup::buildCameraGroup(osgViewer::Viewer* viewer,
1116                                            SGPropertyNode* gnode)
1117 {
1118     CameraGroup* cgroup = new CameraGroup(viewer);
1119     cgroup->_listener.reset(new CameraGroupListener(cgroup, gnode));
1120 
1121     for (int i = 0; i < gnode->nChildren(); ++i) {
1122         SGPropertyNode* pNode = gnode->getChild(i);
1123         const char* name = pNode->getName();
1124         if (!strcmp(name, "camera")) {
1125             cgroup->buildCamera(pNode);
1126         } else if (!strcmp(name, "window")) {
1127             WindowBuilder::getWindowBuilder()->buildWindow(pNode);
1128         } else if (!strcmp(name, "gui")) {
1129             cgroup->buildGUICamera(pNode);
1130         }
1131     }
1132 
1133     return cgroup;
1134 }
1135 
setCameraCullMasks(Node::NodeMask nm)1136 void CameraGroup::setCameraCullMasks(Node::NodeMask nm)
1137 {
1138     for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
1139         CameraInfo* info = i->get();
1140         if (info->flags & GUI)
1141             continue;
1142         osg::ref_ptr<osg::Camera> farCamera = info->getCamera(FAR_CAMERA);
1143         osg::Camera* camera = info->getCamera( MAIN_CAMERA );
1144         if (camera) {
1145             if (farCamera.valid() && farCamera->getNodeMask() != 0) {
1146                 camera->setCullMask(nm & ~simgear::BACKGROUND_BIT);
1147                 camera->setCullMaskLeft(nm & ~simgear::BACKGROUND_BIT);
1148                 camera->setCullMaskRight(nm & ~simgear::BACKGROUND_BIT);
1149                 farCamera->setCullMask(nm);
1150                 farCamera->setCullMaskLeft(nm);
1151                 farCamera->setCullMaskRight(nm);
1152             } else {
1153                 camera->setCullMask(nm);
1154                 camera->setCullMaskLeft(nm);
1155                 camera->setCullMaskRight(nm);
1156             }
1157         } else {
1158             camera = info->getCamera( GEOMETRY_CAMERA );
1159             if (camera == 0) continue;
1160             camera->setCullMask( nm & ~simgear::MODELLIGHT_BIT );
1161 
1162             camera = info->getCamera( LIGHTING_CAMERA );
1163             if (camera == 0) continue;
1164             osg::Switch* sw = camera->getChild(0)->asSwitch();
1165             for (unsigned int i = 0; i < sw->getNumChildren(); ++i) {
1166                 osg::Camera* lc = dynamic_cast<osg::Camera*>(sw->getChild(i));
1167                 if (lc == 0) continue;
1168                 string name = lc->getName();
1169                 if (name == "LightCamera") {
1170                     lc->setCullMask( (nm & simgear::LIGHTS_BITS) | (lc->getCullMask() & ~simgear::LIGHTS_BITS) );
1171                 }
1172             }
1173         }
1174     }
1175 }
1176 
resized()1177 void CameraGroup::resized()
1178 {
1179     for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
1180         CameraInfo *info = i->get();
1181         Camera* camera = info->getCamera( MAIN_CAMERA );
1182         if ( camera == 0 )
1183             camera = info->getCamera( DISPLAY_CAMERA );
1184         const Viewport* viewport = camera->getViewport();
1185         info->x = viewport->x();
1186         info->y = viewport->y();
1187         info->width = viewport->width();
1188         info->height = viewport->height();
1189 
1190         info->resized( info->width, info->height );
1191     }
1192 }
1193 
getGUICamera() const1194 const CameraInfo* CameraGroup::getGUICamera() const
1195 {
1196     ConstCameraIterator result
1197         = std::find_if(camerasBegin(), camerasEnd(),
1198                    FlagTester<CameraInfo>(GUI));
1199     if (result == camerasEnd()) {
1200         return NULL;
1201     }
1202 
1203     return *result;
1204 }
1205 
getGUICamera(CameraGroup * cgroup)1206 Camera* getGUICamera(CameraGroup* cgroup)
1207 {
1208     if (!cgroup)
1209         return nullptr;
1210 
1211     const CameraInfo* info = cgroup->getGUICamera();
1212     if (!info) {
1213         return nullptr;
1214     }
1215 
1216     return info->getCamera(MAIN_CAMERA);
1217 }
1218 
1219 
computeCameraIntersection(const CameraInfo * cinfo,const osg::Vec2d & windowPos,osgUtil::LineSegmentIntersector::Intersections & intersections)1220 static bool computeCameraIntersection(const CameraInfo* cinfo, const osg::Vec2d& windowPos,
1221                                       osgUtil::LineSegmentIntersector::Intersections& intersections)
1222 {
1223   using osgUtil::Intersector;
1224   using osgUtil::LineSegmentIntersector;
1225 
1226   if (!(cinfo->flags & CameraGroup::DO_INTERSECTION_TEST))
1227     return false;
1228 
1229   const Camera* camera = cinfo->getCamera(MAIN_CAMERA);
1230   if ( !camera )
1231     camera = cinfo->getCamera( GEOMETRY_CAMERA );
1232 
1233   // if (camera->getGraphicsContext() != ea->getGraphicsContext())
1234  //   return false;
1235 
1236   const Viewport* viewport = camera->getViewport();
1237   SGRect<double> viewportRect(viewport->x(), viewport->y(),
1238                               viewport->x() + viewport->width() - 1.0,
1239                               viewport->y() + viewport->height()- 1.0);
1240 
1241   double epsilon = 0.5;
1242   if (!viewportRect.contains(windowPos.x(), windowPos.y(), epsilon))
1243     return false;
1244 
1245   Vec4d start(windowPos.x(), windowPos.y(), 0.0, 1.0);
1246   Vec4d end(windowPos.x(), windowPos.y(), 1.0, 1.0);
1247   Matrix windowMat = viewport->computeWindowMatrix();
1248   Matrix startPtMat = Matrix::inverse(camera->getProjectionMatrix()
1249                                       * windowMat);
1250   Matrix endPtMat;
1251   const Camera* farCamera = cinfo->getCamera( FAR_CAMERA );
1252   if (!farCamera || farCamera->getNodeMask() == 0)
1253     endPtMat = startPtMat;
1254   else
1255     endPtMat = Matrix::inverse(farCamera->getProjectionMatrix()
1256                                * windowMat);
1257   start = start * startPtMat;
1258   start /= start.w();
1259   end = end * endPtMat;
1260   end /= end.w();
1261   ref_ptr<LineSegmentIntersector> picker
1262   = new LineSegmentIntersector(Intersector::VIEW,
1263                                Vec3d(start.x(), start.y(), start.z()),
1264                                Vec3d(end.x(), end.y(), end.z()));
1265   osgUtil::IntersectionVisitor iv(picker.get());
1266   iv.setTraversalMask( simgear::PICK_BIT );
1267 
1268   const_cast<Camera*>(camera)->accept(iv);
1269   if (picker->containsIntersections()) {
1270     intersections = picker->getIntersections();
1271     return true;
1272   }
1273 
1274   return false;
1275 }
1276 
computeIntersections(const CameraGroup * cgroup,const osg::Vec2d & windowPos,osgUtil::LineSegmentIntersector::Intersections & intersections)1277 bool computeIntersections(const CameraGroup* cgroup,
1278                           const osg::Vec2d& windowPos,
1279                           osgUtil::LineSegmentIntersector::Intersections& intersections)
1280 {
1281     // test the GUI first
1282     const CameraInfo* guiCamera = cgroup->getGUICamera();
1283     if (guiCamera && computeCameraIntersection(guiCamera, windowPos, intersections))
1284         return true;
1285 
1286     // Find camera that contains event
1287     for (CameraGroup::ConstCameraIterator iter = cgroup->camerasBegin(),
1288              e = cgroup->camerasEnd();
1289          iter != e;
1290          ++iter) {
1291         const CameraInfo* cinfo = iter->get();
1292         if (cinfo == guiCamera)
1293             continue;
1294 
1295         if (computeCameraIntersection(cinfo, windowPos, intersections))
1296             return true;
1297     }
1298 
1299     intersections.clear();
1300     return false;
1301 }
1302 
warpGUIPointer(CameraGroup * cgroup,int x,int y)1303 void warpGUIPointer(CameraGroup* cgroup, int x, int y)
1304 {
1305     using osgViewer::GraphicsWindow;
1306     Camera* guiCamera = getGUICamera(cgroup);
1307     if (!guiCamera)
1308         return;
1309     Viewport* vport = guiCamera->getViewport();
1310     GraphicsWindow* gw
1311         = dynamic_cast<GraphicsWindow*>(guiCamera->getGraphicsContext());
1312     if (!gw)
1313         return;
1314     globals->get_renderer()->getEventHandler()->setMouseWarped();
1315     // Translate the warp request into the viewport of the GUI camera,
1316     // send the request to the window, then transform the coordinates
1317     // for the Viewer's event queue.
1318     double wx = x + vport->x();
1319     double wyUp = vport->height() + vport->y() - y;
1320     double wy;
1321     const GraphicsContext::Traits* traits = gw->getTraits();
1322     if (gw->getEventQueue()->getCurrentEventState()->getMouseYOrientation()
1323         == osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS) {
1324         wy = traits->height - wyUp;
1325     } else {
1326         wy = wyUp;
1327     }
1328     gw->getEventQueue()->mouseWarped(wx, wy);
1329     gw->requestWarpPointer(wx, wy);
1330     osgGA::GUIEventAdapter* eventState
1331         = cgroup->getViewer()->getEventQueue()->getCurrentEventState();
1332     double viewerX
1333         = (eventState->getXmin()
1334            + ((wx / double(traits->width))
1335               * (eventState->getXmax() - eventState->getXmin())));
1336     double viewerY
1337         = (eventState->getYmin()
1338            + ((wyUp / double(traits->height))
1339               * (eventState->getYmax() - eventState->getYmin())));
1340     cgroup->getViewer()->getEventQueue()->mouseWarped(viewerX, viewerY);
1341 }
1342 
buildDefaultGroup(osgViewer::Viewer * viewer)1343 void CameraGroup::buildDefaultGroup(osgViewer::Viewer* viewer)
1344 {
1345     // Look for windows, camera groups, and the old syntax of
1346     // top-level cameras
1347     SGPropertyNode* renderingNode = fgGetNode("/sim/rendering");
1348     SGPropertyNode* cgroupNode = renderingNode->getNode("camera-group", true);
1349     bool oldSyntax = !cgroupNode->hasChild("camera");
1350     if (oldSyntax) {
1351         for (int i = 0; i < renderingNode->nChildren(); ++i) {
1352             SGPropertyNode* propNode = renderingNode->getChild(i);
1353             const char* propName = propNode->getName();
1354             if (!strcmp(propName, "window") || !strcmp(propName, "camera")) {
1355                 SGPropertyNode* copiedNode
1356                     = cgroupNode->getNode(propName, propNode->getIndex(), true);
1357                 copyProperties(propNode, copiedNode);
1358             }
1359         }
1360 
1361         SGPropertyNodeVec cameras(cgroupNode->getChildren("camera"));
1362         SGPropertyNode* masterCamera = 0;
1363         SGPropertyNodeVec::const_iterator it;
1364         for (it = cameras.begin(); it != cameras.end(); ++it) {
1365             if ((*it)->getDoubleValue("shear-x", 0.0) == 0.0
1366                 && (*it)->getDoubleValue("shear-y", 0.0) == 0.0) {
1367                 masterCamera = it->ptr();
1368                 break;
1369             }
1370         }
1371         if (!masterCamera) {
1372             WindowBuilder *windowBuilder = WindowBuilder::getWindowBuilder();
1373             masterCamera = cgroupNode->getChild("camera", cameras.size(), true);
1374             setValue(masterCamera->getNode("window/name", true),
1375                      windowBuilder->getDefaultWindowName());
1376         }
1377         SGPropertyNode* nameNode = masterCamera->getNode("window/name");
1378         if (nameNode)
1379             setValue(cgroupNode->getNode("gui/window/name", true),
1380                      nameNode->getStringValue());
1381     }
1382 
1383     CameraGroup* cgroup = buildCameraGroup(viewer, cgroupNode);
1384     setDefault(cgroup);
1385 }
1386 
1387 } // of namespace flightgear
1388 
1389