]> git.mxchange.org Git - flightgear.git/blob - src/Main/CameraGroup.cxx
bd1783b66d28380c75f854ef08d8c81a95b9fe14
[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 #include "CameraGroup.hxx"
18
19 #include "globals.hxx"
20 #include "renderer.hxx"
21 #include "FGEventHandler.hxx"
22 #include "WindowBuilder.hxx"
23 #include "WindowSystemAdapter.hxx"
24 #include <simgear/props/props.hxx>
25 #include <simgear/structure/OSGUtils.hxx>
26 #include <simgear/scene/util/RenderConstants.hxx>
27
28 #include <algorithm>
29 #include <cstring>
30 #include <string>
31
32 #include <osg/Camera>
33 #include <osg/GraphicsContext>
34 #include <osg/Math>
35 #include <osg/Matrix>
36 #include <osg/Quat>
37 #include <osg/Vec3d>
38 #include <osg/Viewport>
39
40 #include <osgUtil/IntersectionVisitor>
41
42 #include <osgViewer/GraphicsWindow>
43
44 namespace flightgear
45 {
46 using namespace osg;
47
48 using std::strcmp;
49 using std::string;
50
51 ref_ptr<CameraGroup> CameraGroup::_defaultGroup;
52
53 CameraGroup::CameraGroup(osgViewer::Viewer* viewer) :
54     _viewer(viewer)
55 {
56 }
57
58 }
59
60 namespace
61 {
62 using namespace osg;
63
64 // Given a projection matrix, return a new one with the same frustum
65 // sides and new near / far values.
66
67 void makeNewProjMat(Matrixd& oldProj, double znear,
68                                        double zfar, Matrixd& projection)
69 {
70     projection = oldProj;
71     // Slightly inflate the near & far planes to avoid objects at the
72     // extremes being clipped out.
73     znear *= 0.999;
74     zfar *= 1.001;
75
76     // Clamp the projection matrix z values to the range (near, far)
77     double epsilon = 1.0e-6;
78     if (fabs(projection(0,3)) < epsilon &&
79         fabs(projection(1,3)) < epsilon &&
80         fabs(projection(2,3)) < epsilon) {
81         // Projection is Orthographic
82         epsilon = -1.0/(zfar - znear); // Used as a temp variable
83         projection(2,2) = 2.0*epsilon;
84         projection(3,2) = (zfar + znear)*epsilon;
85     } else {
86         // Projection is Perspective
87         double trans_near = (-znear*projection(2,2) + projection(3,2)) /
88             (-znear*projection(2,3) + projection(3,3));
89         double trans_far = (-zfar*projection(2,2) + projection(3,2)) /
90             (-zfar*projection(2,3) + projection(3,3));
91         double ratio = fabs(2.0/(trans_near - trans_far));
92         double center = -0.5*(trans_near + trans_far);
93
94         projection.postMult(osg::Matrixd(1.0, 0.0, 0.0, 0.0,
95                                          0.0, 1.0, 0.0, 0.0,
96                                          0.0, 0.0, ratio, 0.0,
97                                          0.0, 0.0, center*ratio, 1.0));
98     }
99 }
100
101 void installCullVisitor(Camera* camera)
102 {
103 #if 0 // Not yet
104     osgViewer::Renderer* renderer
105         = static_cast<osgViewer::Renderer*>(camera->getRenderer());
106     for (int i = 0; i < 2; ++i) {
107         osgUtil::SceneView* sceneView = renderer->getSceneView(i);
108         sceneView->setCullVisitor(new simgear::EffectCullVisitor);
109     }
110 #endif
111 }
112 }
113
114 namespace flightgear
115 {
116 void updateCameras(const CameraInfo* info)
117 {
118     if (info->camera.valid())
119         info->camera->getViewport()->setViewport(info->x, info->y,
120                                                  info->width, info->height);
121     if (info->farCamera.valid())
122         info->farCamera->getViewport()->setViewport(info->x, info->y,
123                                                     info->width, info->height);
124 }
125
126 CameraInfo* CameraGroup::addCamera(unsigned flags, Camera* camera,
127                                    const Matrix& view,
128                                    const Matrix& projection,
129                                    bool useMasterSceneData)
130 {
131     CameraInfo* info = new CameraInfo(flags);
132     // The camera group will always update the camera
133     camera->setReferenceFrame(Transform::ABSOLUTE_RF);
134
135     Camera* farCamera = 0;
136     if ((flags & (GUI | ORTHO)) == 0) {
137         farCamera = simgear::clone(camera);
138         farCamera->setGraphicsContext(camera->getGraphicsContext());
139         // Each camera's viewport is written when the window is
140         // resized; if the the viewport isn't copied here, it gets updated
141         // twice and ends up with the wrong value.
142         farCamera->setViewport(simgear::clone(camera->getViewport()));
143         _viewer->addSlave(farCamera, view, projection, useMasterSceneData);
144         installCullVisitor(farCamera);
145         info->farCamera = farCamera;
146         info->farSlaveIndex = _viewer->getNumSlaves() - 1;
147         farCamera->setRenderOrder(Camera::NESTED_RENDER, info->farSlaveIndex);
148         camera->setCullMask(camera->getCullMask() & ~simgear::BACKGROUND_BIT);
149     }
150     camera->setClearMask(GL_DEPTH_BUFFER_BIT);
151     _viewer->addSlave(camera, view, projection, useMasterSceneData);
152     installCullVisitor(camera);
153     info->camera = camera;
154     info->slaveIndex = _viewer->getNumSlaves() - 1;
155     camera->setRenderOrder(Camera::NESTED_RENDER, info->slaveIndex);
156     _cameras.push_back(info);
157     return info;
158 }
159
160 void CameraGroup::update(const osg::Vec3d& position,
161                          const osg::Quat& orientation)
162 {
163     const Matrix masterView(osg::Matrix::translate(-position)
164                             * osg::Matrix::rotate(orientation.inverse()));
165     _viewer->getCamera()->setViewMatrix(masterView);
166     const Matrix& masterProj = _viewer->getCamera()->getProjectionMatrix();
167     for (CameraList::iterator i = _cameras.begin(); i != _cameras.end(); ++i) {
168         const CameraInfo* info = i->get();
169         const View::Slave& slave = _viewer->getSlave(info->slaveIndex);
170         // refreshes camera viewports (for now)
171         updateCameras(info);
172         Camera* camera = info->camera.get();
173         Matrix viewMatrix;
174         if ((info->flags & VIEW_ABSOLUTE) != 0)
175             viewMatrix = slave._viewOffset;
176         else
177             viewMatrix = masterView * slave._viewOffset;
178         camera->setViewMatrix(viewMatrix);
179         Matrix projectionMatrix;
180         if ((info->flags & PROJECTION_ABSOLUTE) != 0)
181             projectionMatrix = slave._projectionOffset;
182         else
183             projectionMatrix = masterProj * slave._projectionOffset;
184
185         if (!info->farCamera.valid()) {
186             camera->setProjectionMatrix(projectionMatrix);
187         } else {
188             Camera* farCamera = info->farCamera.get();
189             farCamera->setViewMatrix(viewMatrix);
190             double left, right, bottom, top, parentNear, parentFar;
191             projectionMatrix.getFrustum(left, right, bottom, top,
192                                         parentNear, parentFar);
193             if (parentFar < 100.0) {
194                 camera->setProjectionMatrix(projectionMatrix);
195                 camera->setCullMask(camera->getCullMask()
196                                     | simgear::BACKGROUND_BIT);
197                 farCamera->setNodeMask(0);
198             } else {
199                 Matrix nearProj, farProj;
200                 makeNewProjMat(projectionMatrix, parentNear, 100.0, nearProj);
201                 makeNewProjMat(projectionMatrix, 100.0, parentFar, farProj);
202                 camera->setProjectionMatrix(nearProj);
203                 camera->setCullMask(camera->getCullMask()
204                                     & ~simgear::BACKGROUND_BIT);
205                 farCamera->setProjectionMatrix(farProj);
206                 farCamera->setNodeMask(camera->getNodeMask());
207             }
208         }
209     }
210 }
211
212 void CameraGroup::setCameraParameters(float vfov, float aspectRatio)
213 {
214     const float zNear = .1f;
215     const float zFar = 120000.0f;
216     _viewer->getCamera()->setProjectionMatrixAsPerspective(vfov,
217                                                            1.0f / aspectRatio,
218                                                            zNear, zFar);
219 }
220 }
221
222 namespace
223 {
224 // A raw value for property nodes that references a class member via
225 // an osg::ref_ptr.
226 template<class C, class T>
227 class RefMember : public SGRawValue<T>
228 {
229 public:
230     RefMember (C *obj, T C::*ptr)
231         : _obj(obj), _ptr(ptr) {}
232     virtual ~RefMember () {}
233     virtual T getValue () const
234     {
235         return _obj.get()->*_ptr;
236     }
237     virtual bool setValue (T value)
238     {
239         _obj.get()->*_ptr = value;
240         return true;
241     }
242     virtual SGRawValue<T> * clone () const
243     {
244         return new RefMember(_obj.get(), _ptr);
245     }
246 private:
247     ref_ptr<C> _obj;
248     T C::* const _ptr;
249 };
250
251 template<typename C, typename T>
252 RefMember<C, T> makeRefMember(C *obj, T C::*ptr)
253 {
254     return RefMember<C, T>(obj, ptr);
255 }
256
257 template<typename C, typename T>
258 void bindMemberToNode(SGPropertyNode* parent, const char* childName,
259                       C* obj, T C::*ptr, T value)
260 {
261     SGPropertyNode* valNode = parent->getNode(childName);
262     RefMember<C, T> refMember = makeRefMember(obj, ptr);
263     if (!valNode) {
264         valNode = parent->getNode(childName, true);
265         valNode->tie(refMember, false);
266         setValue(valNode, value);
267     } else {
268         valNode->tie(refMember, true);
269     }
270 }
271
272 void buildViewport(flightgear::CameraInfo* info, SGPropertyNode* viewportNode,
273                    const osg::GraphicsContext::Traits *traits)
274 {
275     using namespace flightgear;
276     bindMemberToNode(viewportNode, "x", info, &CameraInfo::x, 0.0);
277     bindMemberToNode(viewportNode, "y", info, &CameraInfo::y, 0.0);
278     bindMemberToNode(viewportNode, "width", info, &CameraInfo::width,
279                      static_cast<double>(traits->width));
280     bindMemberToNode(viewportNode, "height", info, &CameraInfo::height,
281                      static_cast<double>(traits->height));
282 }
283 }
284
285 namespace flightgear
286 {
287
288 CameraInfo* CameraGroup::buildCamera(SGPropertyNode* cameraNode)
289 {
290     WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
291     const SGPropertyNode* windowNode = cameraNode->getNode("window");
292     GraphicsWindow* window = 0;
293     static int cameraNum = 0;
294     int cameraFlags = DO_INTERSECTION_TEST;
295     if (windowNode) {
296         // New style window declaration / definition
297         window = wBuild->buildWindow(windowNode);
298     } else {
299         // Old style: suck window params out of camera block
300         window = wBuild->buildWindow(cameraNode);
301     }
302     if (!window) {
303         return 0;
304     }
305     Camera* camera = new Camera;
306     camera->setAllowEventFocus(false);
307     camera->setGraphicsContext(window->gc.get());
308     camera->setViewport(new Viewport);
309     camera->setCullingMode(CullSettings::SMALL_FEATURE_CULLING
310                            | CullSettings::VIEW_FRUSTUM_CULLING);
311     camera->setInheritanceMask(CullSettings::ALL_VARIABLES
312                                & ~(CullSettings::CULL_MASK
313                                    | CullSettings::CULLING_MODE));
314
315     osg::Matrix pOff;
316     osg::Matrix vOff;
317     const SGPropertyNode* viewNode = cameraNode->getNode("view");
318     if (viewNode) {
319         double heading = viewNode->getDoubleValue("heading-deg", 0.0);
320         double pitch = viewNode->getDoubleValue("pitch-deg", 0.0);
321         double roll = viewNode->getDoubleValue("roll-deg", 0.0);
322         double x = viewNode->getDoubleValue("x", 0.0);
323         double y = viewNode->getDoubleValue("y", 0.0);
324         double z = viewNode->getDoubleValue("z", 0.0);
325         // Build a view matrix, which is the inverse of a model
326         // orientation matrix.
327         vOff = (Matrix::translate(-x, -y, -z)
328                 * Matrix::rotate(-DegreesToRadians(heading),
329                                  Vec3d(0.0, 1.0, 0.0),
330                                  -DegreesToRadians(pitch),
331                                  Vec3d(1.0, 0.0, 0.0),
332                                  -DegreesToRadians(roll),
333                                  Vec3d(0.0, 0.0, 1.0)));
334         if (viewNode->getBoolValue("absolute", false))
335             cameraFlags |= VIEW_ABSOLUTE;
336     } else {
337         // Old heading parameter, works in the opposite direction
338         double heading = cameraNode->getDoubleValue("heading-deg", 0.0);
339         vOff.makeRotate(DegreesToRadians(heading), osg::Vec3(0, 1, 0));
340     }
341     const SGPropertyNode* projectionNode = 0;
342     if ((projectionNode = cameraNode->getNode("perspective")) != 0) {
343         double fovy = projectionNode->getDoubleValue("fovy-deg", 55.0);
344         double aspectRatio = projectionNode->getDoubleValue("aspect-ratio",
345                                                             1.0);
346         double zNear = projectionNode->getDoubleValue("near", 0.0);
347         double zFar = projectionNode->getDoubleValue("far", 0.0);
348         double offsetX = projectionNode->getDoubleValue("offset-x", 0.0);
349         double offsetY = projectionNode->getDoubleValue("offset-y", 0.0);
350         double tan_fovy = tan(DegreesToRadians(fovy*0.5));
351         double right = tan_fovy * aspectRatio * zNear + offsetX;
352         double left = -tan_fovy * aspectRatio * zNear + offsetX;
353         double top = tan_fovy * zNear + offsetY;
354         double bottom = -tan_fovy * zNear + offsetY;
355         pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
356         cameraFlags |= PROJECTION_ABSOLUTE;
357     } else if ((projectionNode = cameraNode->getNode("frustum")) != 0
358                || (projectionNode = cameraNode->getNode("ortho")) != 0) {
359         double top = projectionNode->getDoubleValue("top", 0.0);
360         double bottom = projectionNode->getDoubleValue("bottom", 0.0);
361         double left = projectionNode->getDoubleValue("left", 0.0);
362         double right = projectionNode->getDoubleValue("right", 0.0);
363         double zNear = projectionNode->getDoubleValue("near", 0.0);
364         double zFar = projectionNode->getDoubleValue("far", 0.0);
365         if (cameraNode->getNode("frustum")) {
366             pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
367             cameraFlags |= PROJECTION_ABSOLUTE;
368         } else {
369             pOff.makeOrtho(left, right, bottom, top, zNear, zFar);
370             cameraFlags |= (PROJECTION_ABSOLUTE | ORTHO);
371         }
372     } else {
373         // old style shear parameters
374         double shearx = cameraNode->getDoubleValue("shear-x", 0);
375         double sheary = cameraNode->getDoubleValue("shear-y", 0);
376         pOff.makeTranslate(-shearx, -sheary, 0);
377     }
378     CameraInfo* info = addCamera(cameraFlags, camera, pOff, vOff);
379     // If a viewport isn't set on the camera, then it's hard to dig it
380     // out of the SceneView objects in the viewer, and the coordinates
381     // of mouse events are somewhat bizzare.
382     SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
383     buildViewport(info, viewportNode, window->gc->getTraits());
384     updateCameras(info);
385     return info;
386 }
387
388 CameraInfo* CameraGroup::buildGUICamera(SGPropertyNode* cameraNode,
389                                         GraphicsWindow* window)
390 {
391     WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
392     const SGPropertyNode* windowNode = (cameraNode
393                                         ? cameraNode->getNode("window")
394                                         : 0);
395     static int cameraNum = 0;
396     if (!window) {
397         if (windowNode) {
398             // New style window declaration / definition
399             window = wBuild->buildWindow(windowNode);
400             
401         } else {
402             return 0;
403         }
404     }
405     Camera* camera = new Camera;
406     camera->setAllowEventFocus(false);
407     camera->setGraphicsContext(window->gc.get());
408     camera->setViewport(new Viewport);
409     // XXX Camera needs to be drawn last; eventually the render order
410     // should be assigned by a camera manager.
411     camera->setRenderOrder(osg::Camera::POST_RENDER, 100);
412         camera->setClearMask(0);
413     camera->setInheritanceMask(CullSettings::ALL_VARIABLES
414                                & ~(CullSettings::COMPUTE_NEAR_FAR_MODE
415                                    | CullSettings::CULLING_MODE));
416     camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
417     camera->setCullingMode(osg::CullSettings::NO_CULLING);
418     camera->setProjectionResizePolicy(Camera::FIXED);
419     camera->setReferenceFrame(Transform::ABSOLUTE_RF);
420     const int cameraFlags = GUI;
421     CameraInfo* result = addCamera(cameraFlags, camera, Matrixd::identity(),
422                                    Matrixd::identity(), false);
423     SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
424     buildViewport(result, viewportNode, window->gc->getTraits());
425
426     // Disable statistics for the GUI camera.
427     result->camera->setStats(0);
428     updateCameras(result);
429     return result;
430 }
431
432 CameraGroup* CameraGroup::buildCameraGroup(osgViewer::Viewer* viewer,
433                                            SGPropertyNode* gnode)
434 {
435     CameraGroup* cgroup = new CameraGroup(viewer);
436     for (int i = 0; i < gnode->nChildren(); ++i) {
437         SGPropertyNode* pNode = gnode->getChild(i);
438         const char* name = pNode->getName();
439         if (!strcmp(name, "camera")) {
440             cgroup->buildCamera(pNode);
441         } else if (!strcmp(name, "window")) {
442             WindowBuilder::getWindowBuilder()->buildWindow(pNode);
443         } else if (!strcmp(name, "gui")) {
444             cgroup->buildGUICamera(pNode);
445         }
446     }
447     return cgroup;
448 }
449
450 void CameraGroup::setCameraCullMasks(Node::NodeMask nm)
451 {
452     for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
453         if ((*i)->flags & GUI)
454             continue;
455         (*i)->camera->setCullMask(nm & ~simgear::BACKGROUND_BIT);
456         (*i)->farCamera->setCullMask(nm);
457     }
458 }
459
460 void CameraGroup::resized()
461 {
462     for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
463         CameraInfo *info = i->get();
464         const Viewport* viewport = info->camera->getViewport();
465         info->x = viewport->x();
466         info->y = viewport->y();
467         info->width = viewport->width();
468         info->height = viewport->height();
469     }
470 }
471
472 Camera* getGUICamera(CameraGroup* cgroup)
473 {
474     CameraGroup::CameraIterator end = cgroup->camerasEnd();
475     CameraGroup::CameraIterator result
476         = std::find_if(cgroup->camerasBegin(), end,
477                        FlagTester<CameraInfo>(CameraGroup::GUI));
478     if (result != end)
479         return (*result)->camera.get();
480     else
481         return 0;
482 }
483
484 bool computeIntersections(const CameraGroup* cgroup,
485                           const osgGA::GUIEventAdapter* ea,
486                           osgUtil::LineSegmentIntersector::Intersections& intersections)
487 {
488     using osgUtil::Intersector;
489     using osgUtil::LineSegmentIntersector;
490     double x, y;
491     eventToWindowCoords(ea, x, y);
492     // Find camera that contains event
493     for (CameraGroup::ConstCameraIterator iter = cgroup->camerasBegin(),
494              e = cgroup->camerasEnd();
495          iter != e;
496          ++iter) {
497         const CameraInfo* cinfo = iter->get();
498         if ((cinfo->flags & CameraGroup::DO_INTERSECTION_TEST) == 0)
499             continue;
500         const Camera* camera = cinfo->camera.get();
501         if (camera->getGraphicsContext() != ea->getGraphicsContext())
502             continue;
503         const Viewport* viewport = camera->getViewport();
504         double epsilon = 0.5;
505         if (!(x >= viewport->x() - epsilon
506               && x < viewport->x() + viewport->width() -1.0 + epsilon
507               && y >= viewport->y() - epsilon
508               && y < viewport->y() + viewport->height() -1.0 + epsilon))
509             continue;
510         LineSegmentIntersector::CoordinateFrame cf = Intersector::WINDOW;
511         ref_ptr<LineSegmentIntersector> picker
512             = new LineSegmentIntersector(cf, x, y);
513         osgUtil::IntersectionVisitor iv(picker.get());
514         const_cast<Camera*>(camera)->accept(iv);
515         if (picker->containsIntersections()) {
516             intersections = picker->getIntersections();
517             return true;
518         } else {
519             break;
520         }
521     }
522     intersections.clear();
523     return false;
524 }
525
526 void warpGUIPointer(CameraGroup* cgroup, int x, int y)
527 {
528     using osgViewer::GraphicsWindow;
529     Camera* guiCamera = getGUICamera(cgroup);
530     if (!guiCamera)
531         return;
532     Viewport* vport = guiCamera->getViewport();
533     GraphicsWindow* gw
534         = dynamic_cast<GraphicsWindow*>(guiCamera->getGraphicsContext());
535     if (!gw)
536         return;
537     globals->get_renderer()->getEventHandler()->setMouseWarped();    
538     // Translate the warp request into the viewport of the GUI camera,
539     // send the request to the window, then transform the coordinates
540     // for the Viewer's event queue.
541     double wx = x + vport->x();
542     double wyUp = vport->height() + vport->y() - y;
543     double wy;
544     const GraphicsContext::Traits* traits = gw->getTraits();
545     if (gw->getEventQueue()->getCurrentEventState()->getMouseYOrientation()
546         == osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS) {
547         wy = traits->height - wyUp;
548     } else {
549         wy = wyUp;
550     }
551     gw->getEventQueue()->mouseWarped(wx, wy);
552     gw->requestWarpPointer(wx, wy);
553     osgGA::GUIEventAdapter* eventState
554         = cgroup->getViewer()->getEventQueue()->getCurrentEventState();
555     double viewerX
556         = (eventState->getXmin()
557            + ((wx / double(traits->width))
558               * (eventState->getXmax() - eventState->getXmin())));
559     double viewerY
560         = (eventState->getYmin()
561            + ((wyUp / double(traits->height))
562               * (eventState->getYmax() - eventState->getYmin())));
563     cgroup->getViewer()->getEventQueue()->mouseWarped(viewerX, viewerY);
564 }
565 }