]> git.mxchange.org Git - flightgear.git/blob - src/Main/CameraGroup.cxx
Add fixed-near-far camera config parameter.
[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 "globals.hxx"
25 #include "renderer.hxx"
26 #include "FGEventHandler.hxx"
27 #include "WindowBuilder.hxx"
28 #include "WindowSystemAdapter.hxx"
29 #include <simgear/props/props.hxx>
30 #include <simgear/structure/OSGUtils.hxx>
31 #include <simgear/structure/OSGVersion.hxx>
32 #include <simgear/scene/material/EffectCullVisitor.hxx>
33 #include <simgear/scene/util/RenderConstants.hxx>
34
35 #include <algorithm>
36 #include <cstring>
37 #include <string>
38
39 #include <osg/Camera>
40 #include <osg/Geometry>
41 #include <osg/GraphicsContext>
42 #include <osg/io_utils>
43 #include <osg/Math>
44 #include <osg/Matrix>
45 #include <osg/Notify>
46 #include <osg/Program>
47 #include <osg/Quat>
48 #include <osg/TexMat>
49 #include <osg/Vec3d>
50 #include <osg/Viewport>
51
52 #include <osgUtil/IntersectionVisitor>
53
54 #include <osgViewer/GraphicsWindow>
55 #include <osgViewer/Renderer>
56
57 namespace flightgear
58 {
59 using namespace osg;
60
61 using std::strcmp;
62 using std::string;
63
64 ref_ptr<CameraGroup> CameraGroup::_defaultGroup;
65
66 CameraGroup::CameraGroup(osgViewer::Viewer* viewer) :
67     _viewer(viewer)
68 {
69 }
70
71 }
72
73 namespace
74 {
75 using namespace osg;
76
77 // Given a projection matrix, return a new one with the same frustum
78 // sides and new near / far values.
79
80 void makeNewProjMat(Matrixd& oldProj, double znear,
81                                        double zfar, Matrixd& projection)
82 {
83     projection = oldProj;
84     // Slightly inflate the near & far planes to avoid objects at the
85     // extremes being clipped out.
86     znear *= 0.999;
87     zfar *= 1.001;
88
89     // Clamp the projection matrix z values to the range (near, far)
90     double epsilon = 1.0e-6;
91     if (fabs(projection(0,3)) < epsilon &&
92         fabs(projection(1,3)) < epsilon &&
93         fabs(projection(2,3)) < epsilon) {
94         // Projection is Orthographic
95         epsilon = -1.0/(zfar - znear); // Used as a temp variable
96         projection(2,2) = 2.0*epsilon;
97         projection(3,2) = (zfar + znear)*epsilon;
98     } else {
99         // Projection is Perspective
100         double trans_near = (-znear*projection(2,2) + projection(3,2)) /
101             (-znear*projection(2,3) + projection(3,3));
102         double trans_far = (-zfar*projection(2,2) + projection(3,2)) /
103             (-zfar*projection(2,3) + projection(3,3));
104         double ratio = fabs(2.0/(trans_near - trans_far));
105         double center = -0.5*(trans_near + trans_far);
106
107         projection.postMult(osg::Matrixd(1.0, 0.0, 0.0, 0.0,
108                                          0.0, 1.0, 0.0, 0.0,
109                                          0.0, 0.0, ratio, 0.0,
110                                          0.0, 0.0, center*ratio, 1.0));
111     }
112 }
113
114 void installCullVisitor(Camera* camera)
115 {
116     osgViewer::Renderer* renderer
117         = static_cast<osgViewer::Renderer*>(camera->getRenderer());
118     for (int i = 0; i < 2; ++i) {
119         osgUtil::SceneView* sceneView = renderer->getSceneView(i);
120 #if SG_OSG_VERSION_LESS_THAN(3,0,0)
121         sceneView->setCullVisitor(new simgear::EffectCullVisitor);
122 #else
123         osg::ref_ptr<osgUtil::CullVisitor::Identifier> identifier;
124         identifier = sceneView->getCullVisitor()->getIdentifier();
125         sceneView->setCullVisitor(new simgear::EffectCullVisitor);
126         sceneView->getCullVisitor()->setIdentifier(identifier.get());
127
128         identifier = sceneView->getCullVisitorLeft()->getIdentifier();
129         sceneView->setCullVisitorLeft(sceneView->getCullVisitor()->clone());
130         sceneView->getCullVisitorLeft()->setIdentifier(identifier.get());
131
132         identifier = sceneView->getCullVisitorRight()->getIdentifier();
133         sceneView->setCullVisitorRight(sceneView->getCullVisitor()->clone());
134         sceneView->getCullVisitorRight()->setIdentifier(identifier.get());
135 #endif
136     }
137 }
138 }
139
140 namespace flightgear
141 {
142 void updateCameras(const CameraInfo* info)
143 {
144     if (info->camera.valid())
145         info->camera->getViewport()->setViewport(info->x, info->y,
146                                                  info->width, info->height);
147     if (info->farCamera.valid())
148         info->farCamera->getViewport()->setViewport(info->x, info->y,
149                                                     info->width, info->height);
150 }
151
152 CameraInfo* CameraGroup::addCamera(unsigned flags, Camera* camera,
153                                    const Matrix& view,
154                                    const Matrix& projection,
155                                    bool useMasterSceneData)
156 {
157     CameraInfo* info = new CameraInfo(flags);
158     // The camera group will always update the camera
159     camera->setReferenceFrame(Transform::ABSOLUTE_RF);
160
161     Camera* farCamera = 0;
162     if ((flags & (GUI | ORTHO)) == 0) {
163         farCamera = new Camera;
164         farCamera->setAllowEventFocus(camera->getAllowEventFocus());
165         farCamera->setGraphicsContext(camera->getGraphicsContext());
166         farCamera->setCullingMode(camera->getCullingMode());
167         farCamera->setInheritanceMask(camera->getInheritanceMask());
168         farCamera->setReferenceFrame(Transform::ABSOLUTE_RF);
169         // Each camera's viewport is written when the window is
170         // resized; if the the viewport isn't copied here, it gets updated
171         // twice and ends up with the wrong value.
172         farCamera->setViewport(simgear::clone(camera->getViewport()));
173         farCamera->setDrawBuffer(camera->getDrawBuffer());
174         farCamera->setReadBuffer(camera->getReadBuffer());
175         farCamera->setRenderTargetImplementation(
176             camera->getRenderTargetImplementation());
177         const Camera::BufferAttachmentMap& bufferMap
178             = camera->getBufferAttachmentMap();
179         if (bufferMap.count(Camera::COLOR_BUFFER) != 0) {
180             farCamera->attach(
181                 Camera::COLOR_BUFFER,
182                 bufferMap.find(Camera::COLOR_BUFFER)->second._texture.get());
183         }
184         _viewer->addSlave(farCamera, projection, view, useMasterSceneData);
185         installCullVisitor(farCamera);
186         info->farCamera = farCamera;
187         info->farSlaveIndex = _viewer->getNumSlaves() - 1;
188         farCamera->setRenderOrder(Camera::POST_RENDER, info->farSlaveIndex);
189         camera->setCullMask(camera->getCullMask() & ~simgear::BACKGROUND_BIT);
190         camera->setClearMask(GL_DEPTH_BUFFER_BIT);
191     }
192     _viewer->addSlave(camera, projection, view, useMasterSceneData);
193     installCullVisitor(camera);
194     info->camera = camera;
195     info->slaveIndex = _viewer->getNumSlaves() - 1;
196     camera->setRenderOrder(Camera::POST_RENDER, info->slaveIndex);
197     _cameras.push_back(info);
198     return info;
199 }
200
201 void CameraGroup::update(const osg::Vec3d& position,
202                          const osg::Quat& orientation)
203 {
204     const Matrix masterView(osg::Matrix::translate(-position)
205                             * osg::Matrix::rotate(orientation.inverse()));
206     _viewer->getCamera()->setViewMatrix(masterView);
207     const Matrix& masterProj = _viewer->getCamera()->getProjectionMatrix();
208     for (CameraList::iterator i = _cameras.begin(); i != _cameras.end(); ++i) {
209         const CameraInfo* info = i->get();
210         const View::Slave& slave = _viewer->getSlave(info->slaveIndex);
211 #if SG_OSG_VERSION_LESS_THAN(3,0,0)
212         // refreshes camera viewports (for now)
213         updateCameras(info);
214 #endif
215         Camera* camera = info->camera.get();
216         Matrix viewMatrix;
217         if ((info->flags & VIEW_ABSOLUTE) != 0)
218             viewMatrix = slave._viewOffset;
219         else
220             viewMatrix = masterView * slave._viewOffset;
221         camera->setViewMatrix(viewMatrix);
222         Matrix projectionMatrix;
223         if ((info->flags & PROJECTION_ABSOLUTE) != 0)
224             projectionMatrix = slave._projectionOffset;
225         else
226             projectionMatrix = masterProj * slave._projectionOffset;
227
228         if (!info->farCamera.valid()) {
229             camera->setProjectionMatrix(projectionMatrix);
230         } else {
231             Camera* farCamera = info->farCamera.get();
232             farCamera->setViewMatrix(viewMatrix);
233             double left, right, bottom, top, parentNear, parentFar;
234             projectionMatrix.getFrustum(left, right, bottom, top,
235                                         parentNear, parentFar);
236             if ((info->flags & FIXED_NEAR_FAR) == 0) {
237                 parentNear = _zNear;
238                 parentFar = _zFar;
239             }
240             if (parentFar < _nearField || _nearField == 0.0f) {
241                 camera->setProjectionMatrix(projectionMatrix);
242                 camera->setCullMask(camera->getCullMask()
243                                     | simgear::BACKGROUND_BIT);
244                 camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
245                 farCamera->setNodeMask(0);
246             } else {
247                 Matrix nearProj, farProj;
248                 makeNewProjMat(projectionMatrix, parentNear, _nearField,
249                                nearProj);
250                 makeNewProjMat(projectionMatrix, _nearField, parentFar,
251                                farProj);
252                 camera->setProjectionMatrix(nearProj);
253                 camera->setCullMask(camera->getCullMask()
254                                     & ~simgear::BACKGROUND_BIT);
255                 camera->setClearMask(GL_DEPTH_BUFFER_BIT);
256                 farCamera->setProjectionMatrix(farProj);
257                 farCamera->setNodeMask(camera->getNodeMask());
258             }
259         }
260     }
261 }
262
263 void CameraGroup::setCameraParameters(float vfov, float aspectRatio)
264 {
265     if (vfov != 0.0f && aspectRatio != 0.0f)
266         _viewer->getCamera()
267             ->setProjectionMatrixAsPerspective(vfov,
268                                                1.0f / aspectRatio,
269                                                _zNear, _zFar);
270 }
271     
272 double CameraGroup::getMasterAspectRatio() const
273 {
274     if (_cameras.empty())
275         return 0.0;
276     
277     const CameraInfo* info = _cameras.front();
278     
279     const osg::Viewport* viewport = info->camera->getViewport();
280     if (!viewport) {
281         return 0.0;
282     }
283     
284     return static_cast<double>(viewport->height()) / viewport->width();
285 }
286     
287 }
288
289 namespace
290 {
291 // A raw value for property nodes that references a class member via
292 // an osg::ref_ptr.
293 template<class C, class T>
294 class RefMember : public SGRawValue<T>
295 {
296 public:
297     RefMember (C *obj, T C::*ptr)
298         : _obj(obj), _ptr(ptr) {}
299     virtual ~RefMember () {}
300     virtual T getValue () const
301     {
302         return _obj.get()->*_ptr;
303     }
304     virtual bool setValue (T value)
305     {
306         _obj.get()->*_ptr = value;
307         return true;
308     }
309     virtual SGRawValue<T> * clone () const
310     {
311         return new RefMember(_obj.get(), _ptr);
312     }
313 private:
314     ref_ptr<C> _obj;
315     T C::* const _ptr;
316 };
317
318 template<typename C, typename T>
319 RefMember<C, T> makeRefMember(C *obj, T C::*ptr)
320 {
321     return RefMember<C, T>(obj, ptr);
322 }
323
324 template<typename C, typename T>
325 void bindMemberToNode(SGPropertyNode* parent, const char* childName,
326                       C* obj, T C::*ptr, T value)
327 {
328     SGPropertyNode* valNode = parent->getNode(childName);
329     RefMember<C, T> refMember = makeRefMember(obj, ptr);
330     if (!valNode) {
331         valNode = parent->getNode(childName, true);
332         valNode->tie(refMember, false);
333         setValue(valNode, value);
334     } else {
335         valNode->tie(refMember, true);
336     }
337 }
338
339 void buildViewport(flightgear::CameraInfo* info, SGPropertyNode* viewportNode,
340                    const osg::GraphicsContext::Traits *traits)
341 {
342     using namespace flightgear;
343     bindMemberToNode(viewportNode, "x", info, &CameraInfo::x, 0.0);
344     bindMemberToNode(viewportNode, "y", info, &CameraInfo::y, 0.0);
345     bindMemberToNode(viewportNode, "width", info, &CameraInfo::width,
346                      static_cast<double>(traits->width));
347     bindMemberToNode(viewportNode, "height", info, &CameraInfo::height,
348                      static_cast<double>(traits->height));
349 }
350 }
351
352 namespace flightgear
353 {
354
355 // Mostly copied from osg's osgViewer/View.cpp
356
357 static osg::Geometry* createParoramicSphericalDisplayDistortionMesh(
358     const Vec3& origin, const Vec3& widthVector, const Vec3& heightVector,
359     double sphere_radius, double collar_radius,
360     Image* intensityMap = 0, const Matrix& projectorMatrix = Matrix())
361 {
362     osg::Vec3d center(0.0,0.0,0.0);
363     osg::Vec3d eye(0.0,0.0,0.0);
364
365     double distance = sqrt(sphere_radius*sphere_radius - collar_radius*collar_radius);
366     bool flip = false;
367     bool texcoord_flip = false;
368
369     osg::Vec3d projector = eye - osg::Vec3d(0.0,0.0, distance);
370
371 #if 0
372     OSG_INFO<<"createParoramicSphericalDisplayDistortionMesh : Projector position = "<<projector<<std::endl;
373     OSG_INFO<<"createParoramicSphericalDisplayDistortionMesh : distance = "<<distance<<std::endl;
374 #endif
375     // create the quad to visualize.
376     osg::Geometry* geometry = new osg::Geometry();
377
378     geometry->setSupportsDisplayList(false);
379
380     osg::Vec3 xAxis(widthVector);
381     float width = widthVector.length();
382     xAxis /= width;
383
384     osg::Vec3 yAxis(heightVector);
385     float height = heightVector.length();
386     yAxis /= height;
387
388     int noSteps = 160;
389
390     osg::Vec3Array* vertices = new osg::Vec3Array;
391     osg::Vec2Array* texcoords0 = new osg::Vec2Array;
392     osg::Vec2Array* texcoords1 = intensityMap==0 ? new osg::Vec2Array : 0;
393     osg::Vec4Array* colors = new osg::Vec4Array;
394
395     osg::Vec3 bottom = origin;
396     osg::Vec3 dx = xAxis*(width/((float)(noSteps-2)));
397     osg::Vec3 dy = yAxis*(height/((float)(noSteps-1)));
398
399     osg::Vec3 top = origin + yAxis*height;
400
401     osg::Vec3 screenCenter = origin + widthVector*0.5f + heightVector*0.5f;
402     float screenRadius = heightVector.length() * 0.5f;
403
404     geometry->getOrCreateStateSet()->setMode(GL_CULL_FACE, osg::StateAttribute::OFF | osg::StateAttribute::PROTECTED);
405
406     for(int i=0;i<noSteps;++i)
407     {
408         osg::Vec3 cursor = bottom+dy*(float)i;
409         for(int j=0;j<noSteps;++j)
410         {
411             osg::Vec2 texcoord(double(i)/double(noSteps-1), double(j)/double(noSteps-1));
412             double theta = texcoord.x() * 2.0 * osg::PI;
413             double phi = (1.0-texcoord.y()) * osg::PI;
414
415             if (texcoord_flip) texcoord.y() = 1.0f - texcoord.y();
416
417             osg::Vec3 pos(sin(phi)*sin(theta), sin(phi)*cos(theta), cos(phi));
418             pos = pos*projectorMatrix;
419
420             double alpha = atan2(pos.x(), pos.y());
421             if (alpha<0.0) alpha += 2.0*osg::PI;
422
423             double beta = atan2(sqrt(pos.x()*pos.x() + pos.y()*pos.y()), pos.z());
424             if (beta<0.0) beta += 2.0*osg::PI;
425
426             double gamma = atan2(sqrt(double(pos.x()*pos.x() + pos.y()*pos.y())), double(pos.z()+distance));
427             if (gamma<0.0) gamma += 2.0*osg::PI;
428
429
430             osg::Vec3 v = screenCenter + osg::Vec3(sin(alpha)*gamma*2.0/osg::PI, -cos(alpha)*gamma*2.0/osg::PI, 0.0f)*screenRadius;
431
432             if (flip)
433                 vertices->push_back(osg::Vec3(v.x(), top.y()-(v.y()-origin.y()),v.z()));
434             else
435                 vertices->push_back(v);
436
437             texcoords0->push_back( texcoord );
438
439             osg::Vec2 texcoord1(alpha/(2.0*osg::PI), 1.0f - beta/osg::PI);
440             if (intensityMap)
441             {
442                 colors->push_back(intensityMap->getColor(texcoord1));
443             }
444             else
445             {
446                 colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
447                 if (texcoords1) texcoords1->push_back( texcoord1 );
448             }
449
450
451         }
452     }
453
454
455     // pass the created vertex array to the points geometry object.
456     geometry->setVertexArray(vertices);
457
458     geometry->setColorArray(colors);
459     geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
460
461     geometry->setTexCoordArray(0,texcoords0);
462     if (texcoords1) geometry->setTexCoordArray(1,texcoords1);
463
464     osg::DrawElementsUShort* elements = new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLES);
465     geometry->addPrimitiveSet(elements);
466
467     for(int i=0;i<noSteps-1;++i)
468     {
469         for(int j=0;j<noSteps-1;++j)
470         {
471             int i1 = j+(i+1)*noSteps;
472             int i2 = j+(i)*noSteps;
473             int i3 = j+1+(i)*noSteps;
474             int i4 = j+1+(i+1)*noSteps;
475
476             osg::Vec3& v1 = (*vertices)[i1];
477             osg::Vec3& v2 = (*vertices)[i2];
478             osg::Vec3& v3 = (*vertices)[i3];
479             osg::Vec3& v4 = (*vertices)[i4];
480
481             if ((v1-screenCenter).length()>screenRadius) continue;
482             if ((v2-screenCenter).length()>screenRadius) continue;
483             if ((v3-screenCenter).length()>screenRadius) continue;
484             if ((v4-screenCenter).length()>screenRadius) continue;
485
486             elements->push_back(i1);
487             elements->push_back(i2);
488             elements->push_back(i3);
489
490             elements->push_back(i1);
491             elements->push_back(i3);
492             elements->push_back(i4);
493         }
494     }
495
496     return geometry;
497 }
498
499 void CameraGroup::buildDistortionCamera(const SGPropertyNode* psNode,
500                                         Camera* camera)
501 {
502     const SGPropertyNode* texNode = psNode->getNode("texture");
503     if (!texNode) {
504         // error
505         return;
506     }
507     string texName = texNode->getStringValue();
508     TextureMap::iterator itr = _textureTargets.find(texName);
509     if (itr == _textureTargets.end()) {
510         // error
511         return;
512     }
513     Viewport* viewport = camera->getViewport();
514     float width = viewport->width();
515     float height = viewport->height();
516     TextureRectangle* texRect = itr->second.get();
517     double radius = psNode->getDoubleValue("radius", 1.0);
518     double collar = psNode->getDoubleValue("collar", 0.45);
519     Geode* geode = new Geode();
520     geode->addDrawable(createParoramicSphericalDisplayDistortionMesh(
521                            Vec3(0.0f,0.0f,0.0f), Vec3(width,0.0f,0.0f),
522                            Vec3(0.0f,height,0.0f), radius, collar));
523
524     // new we need to add the texture to the mesh, we do so by creating a
525     // StateSet to contain the Texture StateAttribute.
526     StateSet* stateset = geode->getOrCreateStateSet();
527     stateset->setTextureAttributeAndModes(0, texRect, StateAttribute::ON);
528     stateset->setMode(GL_LIGHTING, StateAttribute::OFF);
529
530     TexMat* texmat = new TexMat;
531     texmat->setScaleByTextureRectangleSize(true);
532     stateset->setTextureAttributeAndModes(0, texmat, osg::StateAttribute::ON);
533 #if 0
534     if (!applyIntensityMapAsColours && intensityMap)
535     {
536         stateset->setTextureAttributeAndModes(1, new osg::Texture2D(intensityMap), osg::StateAttribute::ON);
537     }
538 #endif
539     // add subgraph to render
540     camera->addChild(geode);
541     camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
542     camera->setClearColor(osg::Vec4(0.0, 0.0, 0.0, 1.0));
543     camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
544     camera->setCullingMode(osg::CullSettings::NO_CULLING);
545     camera->setName("DistortionCorrectionCamera");
546 }
547
548 CameraInfo* CameraGroup::buildCamera(SGPropertyNode* cameraNode)
549 {
550     WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
551     const SGPropertyNode* windowNode = cameraNode->getNode("window");
552     GraphicsWindow* window = 0;
553     int cameraFlags = DO_INTERSECTION_TEST;
554     if (windowNode) {
555         // New style window declaration / definition
556         window = wBuild->buildWindow(windowNode);
557     } else {
558         // Old style: suck window params out of camera block
559         window = wBuild->buildWindow(cameraNode);
560     }
561     if (!window) {
562         return 0;
563     }
564     Camera* camera = new Camera;
565     camera->setAllowEventFocus(false);
566     camera->setGraphicsContext(window->gc.get());
567     camera->setViewport(new Viewport);
568     camera->setCullingMode(CullSettings::SMALL_FEATURE_CULLING
569                            | CullSettings::VIEW_FRUSTUM_CULLING);
570     camera->setInheritanceMask(CullSettings::ALL_VARIABLES
571                                & ~(CullSettings::CULL_MASK
572                                    | CullSettings::CULLING_MODE
573 #if defined(HAVE_CULLSETTINGS_CLEAR_MASK)
574                                    | CullSettings::CLEAR_MASK
575 #endif
576                                    ));
577
578     osg::Matrix pOff;
579     osg::Matrix vOff;
580     const SGPropertyNode* viewNode = cameraNode->getNode("view");
581     if (viewNode) {
582         double heading = viewNode->getDoubleValue("heading-deg", 0.0);
583         double pitch = viewNode->getDoubleValue("pitch-deg", 0.0);
584         double roll = viewNode->getDoubleValue("roll-deg", 0.0);
585         double x = viewNode->getDoubleValue("x", 0.0);
586         double y = viewNode->getDoubleValue("y", 0.0);
587         double z = viewNode->getDoubleValue("z", 0.0);
588         // Build a view matrix, which is the inverse of a model
589         // orientation matrix.
590         vOff = (Matrix::translate(-x, -y, -z)
591                 * Matrix::rotate(-DegreesToRadians(heading),
592                                  Vec3d(0.0, 1.0, 0.0),
593                                  -DegreesToRadians(pitch),
594                                  Vec3d(1.0, 0.0, 0.0),
595                                  -DegreesToRadians(roll),
596                                  Vec3d(0.0, 0.0, 1.0)));
597         if (viewNode->getBoolValue("absolute", false))
598             cameraFlags |= VIEW_ABSOLUTE;
599     } else {
600         // Old heading parameter, works in the opposite direction
601         double heading = cameraNode->getDoubleValue("heading-deg", 0.0);
602         vOff.makeRotate(DegreesToRadians(heading), osg::Vec3(0, 1, 0));
603     }
604     const SGPropertyNode* projectionNode = 0;
605     if ((projectionNode = cameraNode->getNode("perspective")) != 0) {
606         double fovy = projectionNode->getDoubleValue("fovy-deg", 55.0);
607         double aspectRatio = projectionNode->getDoubleValue("aspect-ratio",
608                                                             1.0);
609         double zNear = projectionNode->getDoubleValue("near", 0.0);
610         double zFar = projectionNode->getDoubleValue("far", zNear + 20000);
611         double offsetX = projectionNode->getDoubleValue("offset-x", 0.0);
612         double offsetY = projectionNode->getDoubleValue("offset-y", 0.0);
613         double tan_fovy = tan(DegreesToRadians(fovy*0.5));
614         double right = tan_fovy * aspectRatio * zNear + offsetX;
615         double left = -tan_fovy * aspectRatio * zNear + offsetX;
616         double top = tan_fovy * zNear + offsetY;
617         double bottom = -tan_fovy * zNear + offsetY;
618         pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
619         cameraFlags |= PROJECTION_ABSOLUTE;
620         if (projectionNode->getBoolValue("fixed-near-far", true))
621             cameraFlags |= FIXED_NEAR_FAR;
622     } else if ((projectionNode = cameraNode->getNode("frustum")) != 0
623                || (projectionNode = cameraNode->getNode("ortho")) != 0) {
624         double top = projectionNode->getDoubleValue("top", 0.0);
625         double bottom = projectionNode->getDoubleValue("bottom", 0.0);
626         double left = projectionNode->getDoubleValue("left", 0.0);
627         double right = projectionNode->getDoubleValue("right", 0.0);
628         double zNear = projectionNode->getDoubleValue("near", 0.0);
629         double zFar = projectionNode->getDoubleValue("far", zNear + 20000);
630         if (cameraNode->getNode("frustum")) {
631             pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
632             cameraFlags |= PROJECTION_ABSOLUTE;
633         } else {
634             pOff.makeOrtho(left, right, bottom, top, zNear, zFar);
635             cameraFlags |= (PROJECTION_ABSOLUTE | ORTHO);
636         }
637         if (projectionNode->getBoolValue("fixed-near-far", true))
638             cameraFlags |= FIXED_NEAR_FAR;
639     } else {
640         // old style shear parameters
641         double shearx = cameraNode->getDoubleValue("shear-x", 0);
642         double sheary = cameraNode->getDoubleValue("shear-y", 0);
643         pOff.makeTranslate(-shearx, -sheary, 0);
644     }
645     const SGPropertyNode* textureNode = cameraNode->getNode("texture");
646     if (textureNode) {
647         string texName = textureNode->getStringValue("name");
648         int tex_width = textureNode->getIntValue("width");
649         int tex_height = textureNode->getIntValue("height");
650         TextureRectangle* texture = new TextureRectangle;
651
652         texture->setTextureSize(tex_width, tex_height);
653         texture->setInternalFormat(GL_RGB);
654         texture->setFilter(Texture::MIN_FILTER, Texture::LINEAR);
655         texture->setFilter(Texture::MAG_FILTER, Texture::LINEAR);
656         texture->setWrap(Texture::WRAP_S, Texture::CLAMP_TO_EDGE);
657         texture->setWrap(Texture::WRAP_T, Texture::CLAMP_TO_EDGE);
658         camera->setDrawBuffer(GL_FRONT);
659         camera->setReadBuffer(GL_FRONT);
660         camera->setRenderTargetImplementation(Camera::FRAME_BUFFER_OBJECT);
661         camera->attach(Camera::COLOR_BUFFER, texture);
662         _textureTargets[texName] = texture;
663     } else {
664         camera->setDrawBuffer(GL_BACK);
665         camera->setReadBuffer(GL_BACK);
666     }
667     const SGPropertyNode* psNode = cameraNode->getNode("panoramic-spherical");
668     bool useMasterSceneGraph = !psNode;
669     CameraInfo* info = addCamera(cameraFlags, camera, vOff, pOff,
670                                  useMasterSceneGraph);
671     // If a viewport isn't set on the camera, then it's hard to dig it
672     // out of the SceneView objects in the viewer, and the coordinates
673     // of mouse events are somewhat bizzare.
674     SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
675     buildViewport(info, viewportNode, window->gc->getTraits());
676     updateCameras(info);
677     // Distortion camera needs the viewport which is created by addCamera().
678     if (psNode) {
679         info->flags = info->flags | VIEW_ABSOLUTE;
680         buildDistortionCamera(psNode, camera);
681     }
682     return info;
683 }
684
685 CameraInfo* CameraGroup::buildGUICamera(SGPropertyNode* cameraNode,
686                                         GraphicsWindow* window)
687 {
688     WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
689     const SGPropertyNode* windowNode = (cameraNode
690                                         ? cameraNode->getNode("window")
691                                         : 0);
692     if (!window && windowNode) {
693       // New style window declaration / definition
694       window = wBuild->buildWindow(windowNode);
695     }
696
697     if (!window) { // buildWindow can fail
698       SG_LOG(SG_GENERAL, SG_WARN, "CameraGroup::buildGUICamera: failed to build a window");
699       return NULL;
700     }
701
702     Camera* camera = new Camera;
703     camera->setAllowEventFocus(false);
704     camera->setGraphicsContext(window->gc.get());
705     camera->setViewport(new Viewport);
706     // XXX Camera needs to be drawn last; eventually the render order
707     // should be assigned by a camera manager.
708     camera->setRenderOrder(osg::Camera::POST_RENDER, 100);
709         camera->setClearMask(0);
710     camera->setInheritanceMask(CullSettings::ALL_VARIABLES
711                                & ~(CullSettings::COMPUTE_NEAR_FAR_MODE
712                                    | CullSettings::CULLING_MODE
713 #if defined(HAVE_CULLSETTINGS_CLEAR_MASK)
714                                    | CullSettings::CLEAR_MASK
715 #endif
716                                    ));
717     camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
718     camera->setCullingMode(osg::CullSettings::NO_CULLING);
719     camera->setProjectionResizePolicy(Camera::FIXED);
720     camera->setReferenceFrame(Transform::ABSOLUTE_RF);
721     const int cameraFlags = GUI;
722     CameraInfo* result = addCamera(cameraFlags, camera, Matrixd::identity(),
723                                    Matrixd::identity(), false);
724     SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
725     buildViewport(result, viewportNode, window->gc->getTraits());
726
727     // Disable statistics for the GUI camera.
728     result->camera->setStats(0);
729     updateCameras(result);
730     return result;
731 }
732
733 CameraGroup* CameraGroup::buildCameraGroup(osgViewer::Viewer* viewer,
734                                            SGPropertyNode* gnode)
735 {
736     CameraGroup* cgroup = new CameraGroup(viewer);
737     for (int i = 0; i < gnode->nChildren(); ++i) {
738         SGPropertyNode* pNode = gnode->getChild(i);
739         const char* name = pNode->getName();
740         if (!strcmp(name, "camera")) {
741             cgroup->buildCamera(pNode);
742         } else if (!strcmp(name, "window")) {
743             WindowBuilder::getWindowBuilder()->buildWindow(pNode);
744         } else if (!strcmp(name, "gui")) {
745             cgroup->buildGUICamera(pNode);
746         }
747     }
748     bindMemberToNode(gnode, "znear", cgroup, &CameraGroup::_zNear, .1f);
749     bindMemberToNode(gnode, "zfar", cgroup, &CameraGroup::_zFar, 120000.0f);
750     bindMemberToNode(gnode, "near-field", cgroup, &CameraGroup::_nearField,
751                      100.0f);
752     return cgroup;
753 }
754
755 void CameraGroup::setCameraCullMasks(Node::NodeMask nm)
756 {
757     for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
758         CameraInfo* info = i->get();
759         if (info->flags & GUI)
760             continue;
761         if (info->farCamera.valid() && info->farCamera->getNodeMask() != 0) {
762             info->camera->setCullMask(nm & ~simgear::BACKGROUND_BIT);
763             info->camera->setCullMaskLeft(nm & ~simgear::BACKGROUND_BIT);
764             info->camera->setCullMaskRight(nm & ~simgear::BACKGROUND_BIT);
765             info->farCamera->setCullMask(nm);
766             info->farCamera->setCullMaskLeft(nm);
767             info->farCamera->setCullMaskRight(nm);
768         } else {
769             info->camera->setCullMask(nm);
770             info->camera->setCullMaskLeft(nm);
771             info->camera->setCullMaskRight(nm);
772         }
773     }
774 }
775
776 void CameraGroup::resized()
777 {
778     for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
779         CameraInfo *info = i->get();
780         const Viewport* viewport = info->camera->getViewport();
781         info->x = viewport->x();
782         info->y = viewport->y();
783         info->width = viewport->width();
784         info->height = viewport->height();
785     }
786 }
787
788 Camera* getGUICamera(CameraGroup* cgroup)
789 {
790     CameraGroup::CameraIterator end = cgroup->camerasEnd();
791     CameraGroup::CameraIterator result
792         = std::find_if(cgroup->camerasBegin(), end,
793                        FlagTester<CameraInfo>(CameraGroup::GUI));
794     if (result != end)
795         return (*result)->camera.get();
796     else
797         return 0;
798 }
799
800 bool computeIntersections(const CameraGroup* cgroup,
801                           const osgGA::GUIEventAdapter* ea,
802                           osgUtil::LineSegmentIntersector::Intersections& intersections)
803 {
804     using osgUtil::Intersector;
805     using osgUtil::LineSegmentIntersector;
806     double x, y;
807     eventToWindowCoords(ea, x, y);
808     // Find camera that contains event
809     for (CameraGroup::ConstCameraIterator iter = cgroup->camerasBegin(),
810              e = cgroup->camerasEnd();
811          iter != e;
812          ++iter) {
813         const CameraInfo* cinfo = iter->get();
814         if ((cinfo->flags & CameraGroup::DO_INTERSECTION_TEST) == 0)
815             continue;
816         const Camera* camera = cinfo->camera.get();
817         if (camera->getGraphicsContext() != ea->getGraphicsContext())
818             continue;
819         const Viewport* viewport = camera->getViewport();
820         double epsilon = 0.5;
821         if (!(x >= viewport->x() - epsilon
822               && x < viewport->x() + viewport->width() -1.0 + epsilon
823               && y >= viewport->y() - epsilon
824               && y < viewport->y() + viewport->height() -1.0 + epsilon))
825             continue;
826         Vec4d start(x, y, 0.0, 1.0);
827         Vec4d end(x, y, 1.0, 1.0);
828         Matrix windowMat = viewport->computeWindowMatrix();
829         Matrix startPtMat = Matrix::inverse(camera->getProjectionMatrix()
830                                             * windowMat);
831         Matrix endPtMat;
832         if (!cinfo->farCamera.valid() || cinfo->farCamera->getNodeMask() == 0)
833             endPtMat = startPtMat;
834         else
835             endPtMat = Matrix::inverse(cinfo->farCamera->getProjectionMatrix()
836                                        * windowMat);
837         start = start * startPtMat;
838         start /= start.w();
839         end = end * endPtMat;
840         end /= end.w();
841         ref_ptr<LineSegmentIntersector> picker
842             = new LineSegmentIntersector(Intersector::VIEW,
843                                          Vec3d(start.x(), start.y(), start.z()),
844                                          Vec3d(end.x(), end.y(), end.z()));
845         osgUtil::IntersectionVisitor iv(picker.get());
846         const_cast<Camera*>(camera)->accept(iv);
847         if (picker->containsIntersections()) {
848             intersections = picker->getIntersections();
849             return true;
850         } else {
851             break;
852         }
853     }
854     intersections.clear();
855     return false;
856 }
857
858 void warpGUIPointer(CameraGroup* cgroup, int x, int y)
859 {
860     using osgViewer::GraphicsWindow;
861     Camera* guiCamera = getGUICamera(cgroup);
862     if (!guiCamera)
863         return;
864     Viewport* vport = guiCamera->getViewport();
865     GraphicsWindow* gw
866         = dynamic_cast<GraphicsWindow*>(guiCamera->getGraphicsContext());
867     if (!gw)
868         return;
869     globals->get_renderer()->getEventHandler()->setMouseWarped();
870     // Translate the warp request into the viewport of the GUI camera,
871     // send the request to the window, then transform the coordinates
872     // for the Viewer's event queue.
873     double wx = x + vport->x();
874     double wyUp = vport->height() + vport->y() - y;
875     double wy;
876     const GraphicsContext::Traits* traits = gw->getTraits();
877     if (gw->getEventQueue()->getCurrentEventState()->getMouseYOrientation()
878         == osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS) {
879         wy = traits->height - wyUp;
880     } else {
881         wy = wyUp;
882     }
883     gw->getEventQueue()->mouseWarped(wx, wy);
884     gw->requestWarpPointer(wx, wy);
885     osgGA::GUIEventAdapter* eventState
886         = cgroup->getViewer()->getEventQueue()->getCurrentEventState();
887     double viewerX
888         = (eventState->getXmin()
889            + ((wx / double(traits->width))
890               * (eventState->getXmax() - eventState->getXmin())));
891     double viewerY
892         = (eventState->getYmin()
893            + ((wyUp / double(traits->height))
894               * (eventState->getYmax() - eventState->getYmin())));
895     cgroup->getViewer()->getEventQueue()->mouseWarped(viewerX, viewerY);
896 }
897 }