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/material/EffectCullVisitor.hxx>
27 #include <simgear/scene/util/RenderConstants.hxx>
34 #include <osg/GraphicsContext>
39 #include <osg/Viewport>
41 #include <osgUtil/IntersectionVisitor>
43 #include <osgViewer/GraphicsWindow>
44 #include <osgViewer/Renderer>
53 ref_ptr<CameraGroup> CameraGroup::_defaultGroup;
55 CameraGroup::CameraGroup(osgViewer::Viewer* viewer) :
66 // Given a projection matrix, return a new one with the same frustum
67 // sides and new near / far values.
69 void makeNewProjMat(Matrixd& oldProj, double znear,
70 double zfar, Matrixd& projection)
73 // Slightly inflate the near & far planes to avoid objects at the
74 // extremes being clipped out.
78 // Clamp the projection matrix z values to the range (near, far)
79 double epsilon = 1.0e-6;
80 if (fabs(projection(0,3)) < epsilon &&
81 fabs(projection(1,3)) < epsilon &&
82 fabs(projection(2,3)) < epsilon) {
83 // Projection is Orthographic
84 epsilon = -1.0/(zfar - znear); // Used as a temp variable
85 projection(2,2) = 2.0*epsilon;
86 projection(3,2) = (zfar + znear)*epsilon;
88 // Projection is Perspective
89 double trans_near = (-znear*projection(2,2) + projection(3,2)) /
90 (-znear*projection(2,3) + projection(3,3));
91 double trans_far = (-zfar*projection(2,2) + projection(3,2)) /
92 (-zfar*projection(2,3) + projection(3,3));
93 double ratio = fabs(2.0/(trans_near - trans_far));
94 double center = -0.5*(trans_near + trans_far);
96 projection.postMult(osg::Matrixd(1.0, 0.0, 0.0, 0.0,
99 0.0, 0.0, center*ratio, 1.0));
103 void installCullVisitor(Camera* camera)
105 osgViewer::Renderer* renderer
106 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
107 for (int i = 0; i < 2; ++i) {
108 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
109 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 farCamera->setReferenceFrame(Transform::ABSOLUTE_RF);
143 // Each camera's viewport is written when the window is
144 // resized; if the the viewport isn't copied here, it gets updated
145 // twice and ends up with the wrong value.
146 farCamera->setViewport(simgear::clone(camera->getViewport()));
147 _viewer->addSlave(farCamera, view, projection, useMasterSceneData);
148 installCullVisitor(farCamera);
149 info->farCamera = farCamera;
150 info->farSlaveIndex = _viewer->getNumSlaves() - 1;
151 farCamera->setRenderOrder(Camera::POST_RENDER, info->farSlaveIndex);
152 camera->setCullMask(camera->getCullMask() & ~simgear::BACKGROUND_BIT);
153 camera->setClearMask(GL_DEPTH_BUFFER_BIT);
155 _viewer->addSlave(camera, view, projection, useMasterSceneData);
156 installCullVisitor(camera);
157 info->camera = camera;
158 info->slaveIndex = _viewer->getNumSlaves() - 1;
159 camera->setRenderOrder(Camera::POST_RENDER, info->slaveIndex);
160 _cameras.push_back(info);
164 void CameraGroup::update(const osg::Vec3d& position,
165 const osg::Quat& orientation)
167 const Matrix masterView(osg::Matrix::translate(-position)
168 * osg::Matrix::rotate(orientation.inverse()));
169 _viewer->getCamera()->setViewMatrix(masterView);
170 const Matrix& masterProj = _viewer->getCamera()->getProjectionMatrix();
171 for (CameraList::iterator i = _cameras.begin(); i != _cameras.end(); ++i) {
172 const CameraInfo* info = i->get();
173 const View::Slave& slave = _viewer->getSlave(info->slaveIndex);
174 // refreshes camera viewports (for now)
176 Camera* camera = info->camera.get();
178 if ((info->flags & VIEW_ABSOLUTE) != 0)
179 viewMatrix = slave._viewOffset;
181 viewMatrix = masterView * slave._viewOffset;
182 camera->setViewMatrix(viewMatrix);
183 Matrix projectionMatrix;
184 if ((info->flags & PROJECTION_ABSOLUTE) != 0)
185 projectionMatrix = slave._projectionOffset;
187 projectionMatrix = masterProj * slave._projectionOffset;
189 if (!info->farCamera.valid()) {
190 camera->setProjectionMatrix(projectionMatrix);
192 Camera* farCamera = info->farCamera.get();
193 farCamera->setViewMatrix(viewMatrix);
194 double left, right, bottom, top, parentNear, parentFar;
195 projectionMatrix.getFrustum(left, right, bottom, top,
196 parentNear, parentFar);
197 if (parentFar < _nearField || _nearField == 0.0f) {
198 camera->setProjectionMatrix(projectionMatrix);
199 camera->setCullMask(camera->getCullMask()
200 | simgear::BACKGROUND_BIT);
201 camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
202 farCamera->setNodeMask(0);
204 Matrix nearProj, farProj;
205 makeNewProjMat(projectionMatrix, parentNear, _nearField,
207 makeNewProjMat(projectionMatrix, _nearField, parentFar,
209 camera->setProjectionMatrix(nearProj);
210 camera->setCullMask(camera->getCullMask()
211 & ~simgear::BACKGROUND_BIT);
212 camera->setClearMask(GL_DEPTH_BUFFER_BIT);
213 farCamera->setProjectionMatrix(farProj);
214 farCamera->setNodeMask(camera->getNodeMask());
220 void CameraGroup::setCameraParameters(float vfov, float aspectRatio)
222 if (vfov != 0.0f && aspectRatio != 0.0f)
224 ->setProjectionMatrixAsPerspective(vfov,
232 // A raw value for property nodes that references a class member via
234 template<class C, class T>
235 class RefMember : public SGRawValue<T>
238 RefMember (C *obj, T C::*ptr)
239 : _obj(obj), _ptr(ptr) {}
240 virtual ~RefMember () {}
241 virtual T getValue () const
243 return _obj.get()->*_ptr;
245 virtual bool setValue (T value)
247 _obj.get()->*_ptr = value;
250 virtual SGRawValue<T> * clone () const
252 return new RefMember(_obj.get(), _ptr);
259 template<typename C, typename T>
260 RefMember<C, T> makeRefMember(C *obj, T C::*ptr)
262 return RefMember<C, T>(obj, ptr);
265 template<typename C, typename T>
266 void bindMemberToNode(SGPropertyNode* parent, const char* childName,
267 C* obj, T C::*ptr, T value)
269 SGPropertyNode* valNode = parent->getNode(childName);
270 RefMember<C, T> refMember = makeRefMember(obj, ptr);
272 valNode = parent->getNode(childName, true);
273 valNode->tie(refMember, false);
274 setValue(valNode, value);
276 valNode->tie(refMember, true);
280 void buildViewport(flightgear::CameraInfo* info, SGPropertyNode* viewportNode,
281 const osg::GraphicsContext::Traits *traits)
283 using namespace flightgear;
284 bindMemberToNode(viewportNode, "x", info, &CameraInfo::x, 0.0);
285 bindMemberToNode(viewportNode, "y", info, &CameraInfo::y, 0.0);
286 bindMemberToNode(viewportNode, "width", info, &CameraInfo::width,
287 static_cast<double>(traits->width));
288 bindMemberToNode(viewportNode, "height", info, &CameraInfo::height,
289 static_cast<double>(traits->height));
296 CameraInfo* CameraGroup::buildCamera(SGPropertyNode* cameraNode)
298 WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
299 const SGPropertyNode* windowNode = cameraNode->getNode("window");
300 GraphicsWindow* window = 0;
301 int cameraFlags = DO_INTERSECTION_TEST;
303 // New style window declaration / definition
304 window = wBuild->buildWindow(windowNode);
306 // Old style: suck window params out of camera block
307 window = wBuild->buildWindow(cameraNode);
312 Camera* camera = new Camera;
313 camera->setAllowEventFocus(false);
314 camera->setGraphicsContext(window->gc.get());
315 camera->setViewport(new Viewport);
316 camera->setCullingMode(CullSettings::SMALL_FEATURE_CULLING
317 | CullSettings::VIEW_FRUSTUM_CULLING);
318 camera->setInheritanceMask(CullSettings::ALL_VARIABLES
319 & ~(CullSettings::CULL_MASK
320 | CullSettings::CULLING_MODE));
324 const SGPropertyNode* viewNode = cameraNode->getNode("view");
326 double heading = viewNode->getDoubleValue("heading-deg", 0.0);
327 double pitch = viewNode->getDoubleValue("pitch-deg", 0.0);
328 double roll = viewNode->getDoubleValue("roll-deg", 0.0);
329 double x = viewNode->getDoubleValue("x", 0.0);
330 double y = viewNode->getDoubleValue("y", 0.0);
331 double z = viewNode->getDoubleValue("z", 0.0);
332 // Build a view matrix, which is the inverse of a model
333 // orientation matrix.
334 vOff = (Matrix::translate(-x, -y, -z)
335 * Matrix::rotate(-DegreesToRadians(heading),
336 Vec3d(0.0, 1.0, 0.0),
337 -DegreesToRadians(pitch),
338 Vec3d(1.0, 0.0, 0.0),
339 -DegreesToRadians(roll),
340 Vec3d(0.0, 0.0, 1.0)));
341 if (viewNode->getBoolValue("absolute", false))
342 cameraFlags |= VIEW_ABSOLUTE;
344 // Old heading parameter, works in the opposite direction
345 double heading = cameraNode->getDoubleValue("heading-deg", 0.0);
346 vOff.makeRotate(DegreesToRadians(heading), osg::Vec3(0, 1, 0));
348 const SGPropertyNode* projectionNode = 0;
349 if ((projectionNode = cameraNode->getNode("perspective")) != 0) {
350 double fovy = projectionNode->getDoubleValue("fovy-deg", 55.0);
351 double aspectRatio = projectionNode->getDoubleValue("aspect-ratio",
353 double zNear = projectionNode->getDoubleValue("near", 0.0);
354 double zFar = projectionNode->getDoubleValue("far", 0.0);
355 double offsetX = projectionNode->getDoubleValue("offset-x", 0.0);
356 double offsetY = projectionNode->getDoubleValue("offset-y", 0.0);
357 double tan_fovy = tan(DegreesToRadians(fovy*0.5));
358 double right = tan_fovy * aspectRatio * zNear + offsetX;
359 double left = -tan_fovy * aspectRatio * zNear + offsetX;
360 double top = tan_fovy * zNear + offsetY;
361 double bottom = -tan_fovy * zNear + offsetY;
362 pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
363 cameraFlags |= PROJECTION_ABSOLUTE;
364 } else if ((projectionNode = cameraNode->getNode("frustum")) != 0
365 || (projectionNode = cameraNode->getNode("ortho")) != 0) {
366 double top = projectionNode->getDoubleValue("top", 0.0);
367 double bottom = projectionNode->getDoubleValue("bottom", 0.0);
368 double left = projectionNode->getDoubleValue("left", 0.0);
369 double right = projectionNode->getDoubleValue("right", 0.0);
370 double zNear = projectionNode->getDoubleValue("near", 0.0);
371 double zFar = projectionNode->getDoubleValue("far", 0.0);
372 if (cameraNode->getNode("frustum")) {
373 pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
374 cameraFlags |= PROJECTION_ABSOLUTE;
376 pOff.makeOrtho(left, right, bottom, top, zNear, zFar);
377 cameraFlags |= (PROJECTION_ABSOLUTE | ORTHO);
380 // old style shear parameters
381 double shearx = cameraNode->getDoubleValue("shear-x", 0);
382 double sheary = cameraNode->getDoubleValue("shear-y", 0);
383 pOff.makeTranslate(-shearx, -sheary, 0);
385 CameraInfo* info = addCamera(cameraFlags, camera, pOff, vOff);
386 // If a viewport isn't set on the camera, then it's hard to dig it
387 // out of the SceneView objects in the viewer, and the coordinates
388 // of mouse events are somewhat bizzare.
389 SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
390 buildViewport(info, viewportNode, window->gc->getTraits());
395 CameraInfo* CameraGroup::buildGUICamera(SGPropertyNode* cameraNode,
396 GraphicsWindow* window)
398 WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
399 const SGPropertyNode* windowNode = (cameraNode
400 ? cameraNode->getNode("window")
404 // New style window declaration / definition
405 window = wBuild->buildWindow(windowNode);
411 Camera* camera = new Camera;
412 camera->setAllowEventFocus(false);
413 camera->setGraphicsContext(window->gc.get());
414 camera->setViewport(new Viewport);
415 // XXX Camera needs to be drawn last; eventually the render order
416 // should be assigned by a camera manager.
417 camera->setRenderOrder(osg::Camera::POST_RENDER, 100);
418 camera->setClearMask(0);
419 camera->setInheritanceMask(CullSettings::ALL_VARIABLES
420 & ~(CullSettings::COMPUTE_NEAR_FAR_MODE
421 | CullSettings::CULLING_MODE));
422 camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
423 camera->setCullingMode(osg::CullSettings::NO_CULLING);
424 camera->setProjectionResizePolicy(Camera::FIXED);
425 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
426 const int cameraFlags = GUI;
427 CameraInfo* result = addCamera(cameraFlags, camera, Matrixd::identity(),
428 Matrixd::identity(), false);
429 SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
430 buildViewport(result, viewportNode, window->gc->getTraits());
432 // Disable statistics for the GUI camera.
433 result->camera->setStats(0);
434 updateCameras(result);
438 CameraGroup* CameraGroup::buildCameraGroup(osgViewer::Viewer* viewer,
439 SGPropertyNode* gnode)
441 CameraGroup* cgroup = new CameraGroup(viewer);
442 for (int i = 0; i < gnode->nChildren(); ++i) {
443 SGPropertyNode* pNode = gnode->getChild(i);
444 const char* name = pNode->getName();
445 if (!strcmp(name, "camera")) {
446 cgroup->buildCamera(pNode);
447 } else if (!strcmp(name, "window")) {
448 WindowBuilder::getWindowBuilder()->buildWindow(pNode);
449 } else if (!strcmp(name, "gui")) {
450 cgroup->buildGUICamera(pNode);
453 bindMemberToNode(gnode, "znear", cgroup, &CameraGroup::_zNear, .1f);
454 bindMemberToNode(gnode, "zfar", cgroup, &CameraGroup::_zFar, 120000.0f);
455 bindMemberToNode(gnode, "near-field", cgroup, &CameraGroup::_nearField,
460 void CameraGroup::setCameraCullMasks(Node::NodeMask nm)
462 for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
463 CameraInfo* info = i->get();
464 if (info->flags & GUI)
466 if (info->farCamera.valid() && info->farCamera->getNodeMask() != 0) {
467 info->camera->setCullMask(nm & ~simgear::BACKGROUND_BIT);
468 info->farCamera->setCullMask(nm);
470 info->camera->setCullMask(nm);
475 void CameraGroup::resized()
477 for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
478 CameraInfo *info = i->get();
479 const Viewport* viewport = info->camera->getViewport();
480 info->x = viewport->x();
481 info->y = viewport->y();
482 info->width = viewport->width();
483 info->height = viewport->height();
487 Camera* getGUICamera(CameraGroup* cgroup)
489 CameraGroup::CameraIterator end = cgroup->camerasEnd();
490 CameraGroup::CameraIterator result
491 = std::find_if(cgroup->camerasBegin(), end,
492 FlagTester<CameraInfo>(CameraGroup::GUI));
494 return (*result)->camera.get();
499 bool computeIntersections(const CameraGroup* cgroup,
500 const osgGA::GUIEventAdapter* ea,
501 osgUtil::LineSegmentIntersector::Intersections& intersections)
503 using osgUtil::Intersector;
504 using osgUtil::LineSegmentIntersector;
506 eventToWindowCoords(ea, x, y);
507 // Find camera that contains event
508 for (CameraGroup::ConstCameraIterator iter = cgroup->camerasBegin(),
509 e = cgroup->camerasEnd();
512 const CameraInfo* cinfo = iter->get();
513 if ((cinfo->flags & CameraGroup::DO_INTERSECTION_TEST) == 0)
515 const Camera* camera = cinfo->camera.get();
516 if (camera->getGraphicsContext() != ea->getGraphicsContext())
518 const Viewport* viewport = camera->getViewport();
519 double epsilon = 0.5;
520 if (!(x >= viewport->x() - epsilon
521 && x < viewport->x() + viewport->width() -1.0 + epsilon
522 && y >= viewport->y() - epsilon
523 && y < viewport->y() + viewport->height() -1.0 + epsilon))
525 Vec4d start(x, y, 0.0, 1.0);
526 Vec4d end(x, y, 1.0, 1.0);
527 Matrix windowMat = viewport->computeWindowMatrix();
528 Matrix startPtMat = Matrix::inverse(camera->getProjectionMatrix()
531 if (!cinfo->farCamera.valid() || cinfo->farCamera->getNodeMask() == 0)
532 endPtMat = startPtMat;
534 endPtMat = Matrix::inverse(cinfo->farCamera->getProjectionMatrix()
536 start = start * startPtMat;
538 end = end * endPtMat;
540 ref_ptr<LineSegmentIntersector> picker
541 = new LineSegmentIntersector(Intersector::VIEW,
542 Vec3d(start.x(), start.y(), start.z()),
543 Vec3d(end.x(), end.y(), end.z()));
544 osgUtil::IntersectionVisitor iv(picker.get());
545 const_cast<Camera*>(camera)->accept(iv);
546 if (picker->containsIntersections()) {
547 intersections = picker->getIntersections();
553 intersections.clear();
557 void warpGUIPointer(CameraGroup* cgroup, int x, int y)
559 using osgViewer::GraphicsWindow;
560 Camera* guiCamera = getGUICamera(cgroup);
563 Viewport* vport = guiCamera->getViewport();
565 = dynamic_cast<GraphicsWindow*>(guiCamera->getGraphicsContext());
568 globals->get_renderer()->getEventHandler()->setMouseWarped();
569 // Translate the warp request into the viewport of the GUI camera,
570 // send the request to the window, then transform the coordinates
571 // for the Viewer's event queue.
572 double wx = x + vport->x();
573 double wyUp = vport->height() + vport->y() - y;
575 const GraphicsContext::Traits* traits = gw->getTraits();
576 if (gw->getEventQueue()->getCurrentEventState()->getMouseYOrientation()
577 == osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS) {
578 wy = traits->height - wyUp;
582 gw->getEventQueue()->mouseWarped(wx, wy);
583 gw->requestWarpPointer(wx, wy);
584 osgGA::GUIEventAdapter* eventState
585 = cgroup->getViewer()->getEventQueue()->getCurrentEventState();
587 = (eventState->getXmin()
588 + ((wx / double(traits->width))
589 * (eventState->getXmax() - eventState->getXmin())));
591 = (eventState->getYmin()
592 + ((wyUp / double(traits->height))
593 * (eventState->getYmax() - eventState->getYmin())));
594 cgroup->getViewer()->getEventQueue()->mouseWarped(viewerX, viewerY);