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