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