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