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