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