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