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