1 // Copyright (C) 2008 Tim Moore
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.
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.
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.
17 #include "CameraGroup.hxx"
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>
33 #include <osg/GraphicsContext>
38 #include <osg/Viewport>
40 #include <osgUtil/IntersectionVisitor>
42 #include <osgViewer/GraphicsWindow>
51 ref_ptr<CameraGroup> CameraGroup::_defaultGroup;
53 CameraGroup::CameraGroup(osgViewer::Viewer* viewer) :
64 // Given a projection matrix, return a new one with the same frustum
65 // sides and new near / far values.
67 void makeNewProjMat(Matrixd& oldProj, double znear,
68 double zfar, Matrixd& projection)
71 // Slightly inflate the near & far planes to avoid objects at the
72 // extremes being clipped out.
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;
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);
94 projection.postMult(osg::Matrixd(1.0, 0.0, 0.0, 0.0,
97 0.0, 0.0, center*ratio, 1.0));
101 void installCullVisitor(Camera* camera)
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);
116 void updateCameras(const CameraInfo* info)
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);
126 CameraInfo* CameraGroup::addCamera(unsigned flags, Camera* camera,
128 const Matrix& projection,
129 bool useMasterSceneData)
131 CameraInfo* info = new CameraInfo(flags);
132 // The camera group will always update the camera
133 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
135 Camera* farCamera = 0;
136 if ((flags & (GUI | ORTHO)) == 0) {
137 farCamera = new Camera;
138 farCamera->setAllowEventFocus(camera->getAllowEventFocus());
139 farCamera->setGraphicsContext(camera->getGraphicsContext());
140 farCamera->setCullingMode(camera->getCullingMode());
141 farCamera->setInheritanceMask(camera->getInheritanceMask());
142 // Each camera's viewport is written when the window is
143 // resized; if the the viewport isn't copied here, it gets updated
144 // twice and ends up with the wrong value.
145 farCamera->setViewport(simgear::clone(camera->getViewport()));
146 _viewer->addSlave(farCamera, view, projection, useMasterSceneData);
147 installCullVisitor(farCamera);
148 info->farCamera = farCamera;
149 info->farSlaveIndex = _viewer->getNumSlaves() - 1;
150 farCamera->setRenderOrder(Camera::NESTED_RENDER, info->farSlaveIndex);
151 camera->setCullMask(camera->getCullMask() & ~simgear::BACKGROUND_BIT);
152 camera->setClearMask(GL_DEPTH_BUFFER_BIT);
154 _viewer->addSlave(camera, view, projection, useMasterSceneData);
155 installCullVisitor(camera);
156 info->camera = camera;
157 info->slaveIndex = _viewer->getNumSlaves() - 1;
158 camera->setRenderOrder(Camera::NESTED_RENDER, info->slaveIndex);
159 _cameras.push_back(info);
163 void CameraGroup::update(const osg::Vec3d& position,
164 const osg::Quat& orientation)
166 const Matrix masterView(osg::Matrix::translate(-position)
167 * osg::Matrix::rotate(orientation.inverse()));
168 _viewer->getCamera()->setViewMatrix(masterView);
169 const Matrix& masterProj = _viewer->getCamera()->getProjectionMatrix();
170 for (CameraList::iterator i = _cameras.begin(); i != _cameras.end(); ++i) {
171 const CameraInfo* info = i->get();
172 const View::Slave& slave = _viewer->getSlave(info->slaveIndex);
173 // refreshes camera viewports (for now)
175 Camera* camera = info->camera.get();
177 if ((info->flags & VIEW_ABSOLUTE) != 0)
178 viewMatrix = slave._viewOffset;
180 viewMatrix = masterView * slave._viewOffset;
181 camera->setViewMatrix(viewMatrix);
182 Matrix projectionMatrix;
183 if ((info->flags & PROJECTION_ABSOLUTE) != 0)
184 projectionMatrix = slave._projectionOffset;
186 projectionMatrix = masterProj * slave._projectionOffset;
188 if (!info->farCamera.valid()) {
189 camera->setProjectionMatrix(projectionMatrix);
191 Camera* farCamera = info->farCamera.get();
192 farCamera->setViewMatrix(viewMatrix);
193 double left, right, bottom, top, parentNear, parentFar;
194 projectionMatrix.getFrustum(left, right, bottom, top,
195 parentNear, parentFar);
196 if (parentFar < _nearField || _nearField == 0.0f) {
197 camera->setProjectionMatrix(projectionMatrix);
198 camera->setCullMask(camera->getCullMask()
199 | simgear::BACKGROUND_BIT);
200 camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
201 farCamera->setNodeMask(0);
203 Matrix nearProj, farProj;
204 makeNewProjMat(projectionMatrix, parentNear, _nearField,
206 makeNewProjMat(projectionMatrix, _nearField, parentFar,
208 camera->setProjectionMatrix(nearProj);
209 camera->setCullMask(camera->getCullMask()
210 & ~simgear::BACKGROUND_BIT);
211 camera->setClearMask(GL_DEPTH_BUFFER_BIT);
212 farCamera->setProjectionMatrix(farProj);
213 farCamera->setNodeMask(camera->getNodeMask());
219 void CameraGroup::setCameraParameters(float vfov, float aspectRatio)
221 _viewer->getCamera()->setProjectionMatrixAsPerspective(vfov,
229 // A raw value for property nodes that references a class member via
231 template<class C, class T>
232 class RefMember : public SGRawValue<T>
235 RefMember (C *obj, T C::*ptr)
236 : _obj(obj), _ptr(ptr) {}
237 virtual ~RefMember () {}
238 virtual T getValue () const
240 return _obj.get()->*_ptr;
242 virtual bool setValue (T value)
244 _obj.get()->*_ptr = value;
247 virtual SGRawValue<T> * clone () const
249 return new RefMember(_obj.get(), _ptr);
256 template<typename C, typename T>
257 RefMember<C, T> makeRefMember(C *obj, T C::*ptr)
259 return RefMember<C, T>(obj, ptr);
262 template<typename C, typename T>
263 void bindMemberToNode(SGPropertyNode* parent, const char* childName,
264 C* obj, T C::*ptr, T value)
266 SGPropertyNode* valNode = parent->getNode(childName);
267 RefMember<C, T> refMember = makeRefMember(obj, ptr);
269 valNode = parent->getNode(childName, true);
270 valNode->tie(refMember, false);
271 setValue(valNode, value);
273 valNode->tie(refMember, true);
277 void buildViewport(flightgear::CameraInfo* info, SGPropertyNode* viewportNode,
278 const osg::GraphicsContext::Traits *traits)
280 using namespace flightgear;
281 bindMemberToNode(viewportNode, "x", info, &CameraInfo::x, 0.0);
282 bindMemberToNode(viewportNode, "y", info, &CameraInfo::y, 0.0);
283 bindMemberToNode(viewportNode, "width", info, &CameraInfo::width,
284 static_cast<double>(traits->width));
285 bindMemberToNode(viewportNode, "height", info, &CameraInfo::height,
286 static_cast<double>(traits->height));
293 CameraInfo* CameraGroup::buildCamera(SGPropertyNode* cameraNode)
295 WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
296 const SGPropertyNode* windowNode = cameraNode->getNode("window");
297 GraphicsWindow* window = 0;
298 static int cameraNum = 0;
299 int cameraFlags = DO_INTERSECTION_TEST;
301 // New style window declaration / definition
302 window = wBuild->buildWindow(windowNode);
304 // Old style: suck window params out of camera block
305 window = wBuild->buildWindow(cameraNode);
310 Camera* camera = new Camera;
311 camera->setAllowEventFocus(false);
312 camera->setGraphicsContext(window->gc.get());
313 camera->setViewport(new Viewport);
314 camera->setCullingMode(CullSettings::SMALL_FEATURE_CULLING
315 | CullSettings::VIEW_FRUSTUM_CULLING);
316 camera->setInheritanceMask(CullSettings::ALL_VARIABLES
317 & ~(CullSettings::CULL_MASK
318 | CullSettings::CULLING_MODE));
322 const SGPropertyNode* viewNode = cameraNode->getNode("view");
324 double heading = viewNode->getDoubleValue("heading-deg", 0.0);
325 double pitch = viewNode->getDoubleValue("pitch-deg", 0.0);
326 double roll = viewNode->getDoubleValue("roll-deg", 0.0);
327 double x = viewNode->getDoubleValue("x", 0.0);
328 double y = viewNode->getDoubleValue("y", 0.0);
329 double z = viewNode->getDoubleValue("z", 0.0);
330 // Build a view matrix, which is the inverse of a model
331 // orientation matrix.
332 vOff = (Matrix::translate(-x, -y, -z)
333 * Matrix::rotate(-DegreesToRadians(heading),
334 Vec3d(0.0, 1.0, 0.0),
335 -DegreesToRadians(pitch),
336 Vec3d(1.0, 0.0, 0.0),
337 -DegreesToRadians(roll),
338 Vec3d(0.0, 0.0, 1.0)));
339 if (viewNode->getBoolValue("absolute", false))
340 cameraFlags |= VIEW_ABSOLUTE;
342 // Old heading parameter, works in the opposite direction
343 double heading = cameraNode->getDoubleValue("heading-deg", 0.0);
344 vOff.makeRotate(DegreesToRadians(heading), osg::Vec3(0, 1, 0));
346 const SGPropertyNode* projectionNode = 0;
347 if ((projectionNode = cameraNode->getNode("perspective")) != 0) {
348 double fovy = projectionNode->getDoubleValue("fovy-deg", 55.0);
349 double aspectRatio = projectionNode->getDoubleValue("aspect-ratio",
351 double zNear = projectionNode->getDoubleValue("near", 0.0);
352 double zFar = projectionNode->getDoubleValue("far", 0.0);
353 double offsetX = projectionNode->getDoubleValue("offset-x", 0.0);
354 double offsetY = projectionNode->getDoubleValue("offset-y", 0.0);
355 double tan_fovy = tan(DegreesToRadians(fovy*0.5));
356 double right = tan_fovy * aspectRatio * zNear + offsetX;
357 double left = -tan_fovy * aspectRatio * zNear + offsetX;
358 double top = tan_fovy * zNear + offsetY;
359 double bottom = -tan_fovy * zNear + offsetY;
360 pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
361 cameraFlags |= PROJECTION_ABSOLUTE;
362 } else if ((projectionNode = cameraNode->getNode("frustum")) != 0
363 || (projectionNode = cameraNode->getNode("ortho")) != 0) {
364 double top = projectionNode->getDoubleValue("top", 0.0);
365 double bottom = projectionNode->getDoubleValue("bottom", 0.0);
366 double left = projectionNode->getDoubleValue("left", 0.0);
367 double right = projectionNode->getDoubleValue("right", 0.0);
368 double zNear = projectionNode->getDoubleValue("near", 0.0);
369 double zFar = projectionNode->getDoubleValue("far", 0.0);
370 if (cameraNode->getNode("frustum")) {
371 pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
372 cameraFlags |= PROJECTION_ABSOLUTE;
374 pOff.makeOrtho(left, right, bottom, top, zNear, zFar);
375 cameraFlags |= (PROJECTION_ABSOLUTE | ORTHO);
378 // old style shear parameters
379 double shearx = cameraNode->getDoubleValue("shear-x", 0);
380 double sheary = cameraNode->getDoubleValue("shear-y", 0);
381 pOff.makeTranslate(-shearx, -sheary, 0);
383 CameraInfo* info = addCamera(cameraFlags, camera, pOff, vOff);
384 // If a viewport isn't set on the camera, then it's hard to dig it
385 // out of the SceneView objects in the viewer, and the coordinates
386 // of mouse events are somewhat bizzare.
387 SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
388 buildViewport(info, viewportNode, window->gc->getTraits());
393 CameraInfo* CameraGroup::buildGUICamera(SGPropertyNode* cameraNode,
394 GraphicsWindow* window)
396 WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
397 const SGPropertyNode* windowNode = (cameraNode
398 ? cameraNode->getNode("window")
400 static int cameraNum = 0;
403 // New style window declaration / definition
404 window = wBuild->buildWindow(windowNode);
410 Camera* camera = new Camera;
411 camera->setAllowEventFocus(false);
412 camera->setGraphicsContext(window->gc.get());
413 camera->setViewport(new Viewport);
414 // XXX Camera needs to be drawn last; eventually the render order
415 // should be assigned by a camera manager.
416 camera->setRenderOrder(osg::Camera::POST_RENDER, 100);
417 camera->setClearMask(0);
418 camera->setInheritanceMask(CullSettings::ALL_VARIABLES
419 & ~(CullSettings::COMPUTE_NEAR_FAR_MODE
420 | CullSettings::CULLING_MODE));
421 camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
422 camera->setCullingMode(osg::CullSettings::NO_CULLING);
423 camera->setProjectionResizePolicy(Camera::FIXED);
424 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
425 const int cameraFlags = GUI;
426 CameraInfo* result = addCamera(cameraFlags, camera, Matrixd::identity(),
427 Matrixd::identity(), false);
428 SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
429 buildViewport(result, viewportNode, window->gc->getTraits());
431 // Disable statistics for the GUI camera.
432 result->camera->setStats(0);
433 updateCameras(result);
437 CameraGroup* CameraGroup::buildCameraGroup(osgViewer::Viewer* viewer,
438 SGPropertyNode* gnode)
440 CameraGroup* cgroup = new CameraGroup(viewer);
441 for (int i = 0; i < gnode->nChildren(); ++i) {
442 SGPropertyNode* pNode = gnode->getChild(i);
443 const char* name = pNode->getName();
444 if (!strcmp(name, "camera")) {
445 cgroup->buildCamera(pNode);
446 } else if (!strcmp(name, "window")) {
447 WindowBuilder::getWindowBuilder()->buildWindow(pNode);
448 } else if (!strcmp(name, "gui")) {
449 cgroup->buildGUICamera(pNode);
452 bindMemberToNode(gnode, "znear", cgroup, &CameraGroup::_zNear, .4f);
453 bindMemberToNode(gnode, "zfar", cgroup, &CameraGroup::_zFar, 120000.0f);
454 bindMemberToNode(gnode, "near-field", cgroup, &CameraGroup::_nearField,
459 void CameraGroup::setCameraCullMasks(Node::NodeMask nm)
461 for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
462 CameraInfo* info = i->get();
463 if (info->flags & GUI)
465 if (info->farCamera.valid() && info->farCamera->getNodeMask() != 0) {
466 info->camera->setCullMask(nm & ~simgear::BACKGROUND_BIT);
467 info->farCamera->setCullMask(nm);
469 info->camera->setCullMask(nm);
474 void CameraGroup::resized()
476 for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
477 CameraInfo *info = i->get();
478 const Viewport* viewport = info->camera->getViewport();
479 info->x = viewport->x();
480 info->y = viewport->y();
481 info->width = viewport->width();
482 info->height = viewport->height();
486 Camera* getGUICamera(CameraGroup* cgroup)
488 CameraGroup::CameraIterator end = cgroup->camerasEnd();
489 CameraGroup::CameraIterator result
490 = std::find_if(cgroup->camerasBegin(), end,
491 FlagTester<CameraInfo>(CameraGroup::GUI));
493 return (*result)->camera.get();
498 bool computeIntersections(const CameraGroup* cgroup,
499 const osgGA::GUIEventAdapter* ea,
500 osgUtil::LineSegmentIntersector::Intersections& intersections)
502 using osgUtil::Intersector;
503 using osgUtil::LineSegmentIntersector;
505 eventToWindowCoords(ea, x, y);
506 // Find camera that contains event
507 for (CameraGroup::ConstCameraIterator iter = cgroup->camerasBegin(),
508 e = cgroup->camerasEnd();
511 const CameraInfo* cinfo = iter->get();
512 if ((cinfo->flags & CameraGroup::DO_INTERSECTION_TEST) == 0)
514 const Camera* camera = cinfo->camera.get();
515 if (camera->getGraphicsContext() != ea->getGraphicsContext())
517 const Viewport* viewport = camera->getViewport();
518 double epsilon = 0.5;
519 if (!(x >= viewport->x() - epsilon
520 && x < viewport->x() + viewport->width() -1.0 + epsilon
521 && y >= viewport->y() - epsilon
522 && y < viewport->y() + viewport->height() -1.0 + epsilon))
524 Vec4d start(x, y, 0.0, 1.0);
525 Vec4d end(x, y, 1.0, 1.0);
526 Matrix windowMat = viewport->computeWindowMatrix();
527 Matrix startPtMat = Matrix::inverse(camera->getProjectionMatrix()
530 if (!cinfo->farCamera.valid() || cinfo->farCamera->getNodeMask() == 0)
531 endPtMat = startPtMat;
533 endPtMat = Matrix::inverse(cinfo->farCamera->getProjectionMatrix()
535 start = start * startPtMat;
537 end = end * endPtMat;
539 ref_ptr<LineSegmentIntersector> picker
540 = new LineSegmentIntersector(Intersector::VIEW,
541 Vec3d(start.x(), start.y(), start.z()),
542 Vec3d(end.x(), end.y(), end.z()));
543 osgUtil::IntersectionVisitor iv(picker.get());
544 const_cast<Camera*>(camera)->accept(iv);
545 if (picker->containsIntersections()) {
546 intersections = picker->getIntersections();
552 intersections.clear();
556 void warpGUIPointer(CameraGroup* cgroup, int x, int y)
558 using osgViewer::GraphicsWindow;
559 Camera* guiCamera = getGUICamera(cgroup);
562 Viewport* vport = guiCamera->getViewport();
564 = dynamic_cast<GraphicsWindow*>(guiCamera->getGraphicsContext());
567 globals->get_renderer()->getEventHandler()->setMouseWarped();
568 // Translate the warp request into the viewport of the GUI camera,
569 // send the request to the window, then transform the coordinates
570 // for the Viewer's event queue.
571 double wx = x + vport->x();
572 double wyUp = vport->height() + vport->y() - y;
574 const GraphicsContext::Traits* traits = gw->getTraits();
575 if (gw->getEventQueue()->getCurrentEventState()->getMouseYOrientation()
576 == osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS) {
577 wy = traits->height - wyUp;
581 gw->getEventQueue()->mouseWarped(wx, wy);
582 gw->requestWarpPointer(wx, wy);
583 osgGA::GUIEventAdapter* eventState
584 = cgroup->getViewer()->getEventQueue()->getCurrentEventState();
586 = (eventState->getXmin()
587 + ((wx / double(traits->width))
588 * (eventState->getXmax() - eventState->getXmin())));
590 = (eventState->getYmin()
591 + ((wyUp / double(traits->height))
592 * (eventState->getYmax() - eventState->getYmin())));
593 cgroup->getViewer()->getEventQueue()->mouseWarped(viewerX, viewerY);