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