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