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