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.
21 #include "CameraGroup.hxx"
23 #include "globals.hxx"
24 #include "renderer.hxx"
25 #include "FGEventHandler.hxx"
26 #include "WindowBuilder.hxx"
27 #include "WindowSystemAdapter.hxx"
28 #include <simgear/props/props.hxx>
29 #include <simgear/structure/OSGUtils.hxx>
30 #include <simgear/structure/OSGVersion.hxx>
31 #include <simgear/scene/material/EffectCullVisitor.hxx>
32 #include <simgear/scene/util/RenderConstants.hxx>
39 #include <osg/Geometry>
40 #include <osg/GraphicsContext>
41 #include <osg/io_utils>
45 #include <osg/Program>
49 #include <osg/Viewport>
51 #include <osgUtil/IntersectionVisitor>
53 #include <osgViewer/GraphicsWindow>
54 #include <osgViewer/Renderer>
63 ref_ptr<CameraGroup> CameraGroup::_defaultGroup;
65 CameraGroup::CameraGroup(osgViewer::Viewer* viewer) :
76 // Given a projection matrix, return a new one with the same frustum
77 // sides and new near / far values.
79 void makeNewProjMat(Matrixd& oldProj, double znear,
80 double zfar, Matrixd& projection)
83 // Slightly inflate the near & far planes to avoid objects at the
84 // extremes being clipped out.
88 // Clamp the projection matrix z values to the range (near, far)
89 double epsilon = 1.0e-6;
90 if (fabs(projection(0,3)) < epsilon &&
91 fabs(projection(1,3)) < epsilon &&
92 fabs(projection(2,3)) < epsilon) {
93 // Projection is Orthographic
94 epsilon = -1.0/(zfar - znear); // Used as a temp variable
95 projection(2,2) = 2.0*epsilon;
96 projection(3,2) = (zfar + znear)*epsilon;
98 // Projection is Perspective
99 double trans_near = (-znear*projection(2,2) + projection(3,2)) /
100 (-znear*projection(2,3) + projection(3,3));
101 double trans_far = (-zfar*projection(2,2) + projection(3,2)) /
102 (-zfar*projection(2,3) + projection(3,3));
103 double ratio = fabs(2.0/(trans_near - trans_far));
104 double center = -0.5*(trans_near + trans_far);
106 projection.postMult(osg::Matrixd(1.0, 0.0, 0.0, 0.0,
108 0.0, 0.0, ratio, 0.0,
109 0.0, 0.0, center*ratio, 1.0));
113 void installCullVisitor(Camera* camera)
115 osgViewer::Renderer* renderer
116 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
117 for (int i = 0; i < 2; ++i) {
118 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
119 #if SG_OSG_VERSION_LESS_THAN(3,0,0)
120 sceneView->setCullVisitor(new simgear::EffectCullVisitor);
122 osg::ref_ptr<osgUtil::CullVisitor::Identifier> identifier;
123 identifier = sceneView->getCullVisitor()->getIdentifier();
124 sceneView->setCullVisitor(new simgear::EffectCullVisitor);
125 sceneView->getCullVisitor()->setIdentifier(identifier.get());
127 identifier = sceneView->getCullVisitorLeft()->getIdentifier();
128 sceneView->setCullVisitorLeft(sceneView->getCullVisitor()->clone());
129 sceneView->getCullVisitorLeft()->setIdentifier(identifier.get());
131 identifier = sceneView->getCullVisitorRight()->getIdentifier();
132 sceneView->setCullVisitorRight(sceneView->getCullVisitor()->clone());
133 sceneView->getCullVisitorRight()->setIdentifier(identifier.get());
141 void updateCameras(const CameraInfo* info)
143 if (info->camera.valid())
144 info->camera->getViewport()->setViewport(info->x, info->y,
145 info->width, info->height);
146 if (info->farCamera.valid())
147 info->farCamera->getViewport()->setViewport(info->x, info->y,
148 info->width, info->height);
151 CameraInfo* CameraGroup::addCamera(unsigned flags, Camera* camera,
153 const Matrix& projection,
154 bool useMasterSceneData)
156 CameraInfo* info = new CameraInfo(flags);
157 // The camera group will always update the camera
158 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
160 Camera* farCamera = 0;
161 if ((flags & (GUI | ORTHO)) == 0) {
162 farCamera = new Camera;
163 farCamera->setAllowEventFocus(camera->getAllowEventFocus());
164 farCamera->setGraphicsContext(camera->getGraphicsContext());
165 farCamera->setCullingMode(camera->getCullingMode());
166 farCamera->setInheritanceMask(camera->getInheritanceMask());
167 farCamera->setReferenceFrame(Transform::ABSOLUTE_RF);
168 // Each camera's viewport is written when the window is
169 // resized; if the the viewport isn't copied here, it gets updated
170 // twice and ends up with the wrong value.
171 farCamera->setViewport(simgear::clone(camera->getViewport()));
172 farCamera->setDrawBuffer(camera->getDrawBuffer());
173 farCamera->setReadBuffer(camera->getReadBuffer());
174 farCamera->setRenderTargetImplementation(
175 camera->getRenderTargetImplementation());
176 const Camera::BufferAttachmentMap& bufferMap
177 = camera->getBufferAttachmentMap();
178 if (bufferMap.count(Camera::COLOR_BUFFER) != 0) {
180 Camera::COLOR_BUFFER,
181 bufferMap.find(Camera::COLOR_BUFFER)->second._texture.get());
183 _viewer->addSlave(farCamera, projection, view, useMasterSceneData);
184 installCullVisitor(farCamera);
185 info->farCamera = farCamera;
186 info->farSlaveIndex = _viewer->getNumSlaves() - 1;
187 farCamera->setRenderOrder(Camera::POST_RENDER, info->farSlaveIndex);
188 camera->setCullMask(camera->getCullMask() & ~simgear::BACKGROUND_BIT);
189 camera->setClearMask(GL_DEPTH_BUFFER_BIT);
191 _viewer->addSlave(camera, projection, view, useMasterSceneData);
192 installCullVisitor(camera);
193 info->camera = camera;
194 info->slaveIndex = _viewer->getNumSlaves() - 1;
195 camera->setRenderOrder(Camera::POST_RENDER, info->slaveIndex);
196 _cameras.push_back(info);
200 void CameraGroup::update(const osg::Vec3d& position,
201 const osg::Quat& orientation)
203 const Matrix masterView(osg::Matrix::translate(-position)
204 * osg::Matrix::rotate(orientation.inverse()));
205 _viewer->getCamera()->setViewMatrix(masterView);
206 const Matrix& masterProj = _viewer->getCamera()->getProjectionMatrix();
207 for (CameraList::iterator i = _cameras.begin(); i != _cameras.end(); ++i) {
208 const CameraInfo* info = i->get();
209 const View::Slave& slave = _viewer->getSlave(info->slaveIndex);
210 #if SG_OSG_VERSION_LESS_THAN(3,0,0)
211 // refreshes camera viewports (for now)
214 Camera* camera = info->camera.get();
216 if ((info->flags & VIEW_ABSOLUTE) != 0)
217 viewMatrix = slave._viewOffset;
219 viewMatrix = masterView * slave._viewOffset;
220 camera->setViewMatrix(viewMatrix);
221 Matrix projectionMatrix;
222 if ((info->flags & PROJECTION_ABSOLUTE) != 0)
223 projectionMatrix = slave._projectionOffset;
225 projectionMatrix = masterProj * slave._projectionOffset;
227 if (!info->farCamera.valid()) {
228 camera->setProjectionMatrix(projectionMatrix);
230 Camera* farCamera = info->farCamera.get();
231 farCamera->setViewMatrix(viewMatrix);
232 double left, right, bottom, top, parentNear, parentFar;
233 projectionMatrix.getFrustum(left, right, bottom, top,
234 parentNear, parentFar);
235 if (parentFar < _nearField || _nearField == 0.0f) {
236 camera->setProjectionMatrix(projectionMatrix);
237 camera->setCullMask(camera->getCullMask()
238 | simgear::BACKGROUND_BIT);
239 camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
240 farCamera->setNodeMask(0);
242 Matrix nearProj, farProj;
243 makeNewProjMat(projectionMatrix, parentNear, _nearField,
245 makeNewProjMat(projectionMatrix, _nearField, parentFar,
247 camera->setProjectionMatrix(nearProj);
248 camera->setCullMask(camera->getCullMask()
249 & ~simgear::BACKGROUND_BIT);
250 camera->setClearMask(GL_DEPTH_BUFFER_BIT);
251 farCamera->setProjectionMatrix(farProj);
252 farCamera->setNodeMask(camera->getNodeMask());
258 void CameraGroup::setCameraParameters(float vfov, float aspectRatio)
260 if (vfov != 0.0f && aspectRatio != 0.0f)
262 ->setProjectionMatrixAsPerspective(vfov,
270 // A raw value for property nodes that references a class member via
272 template<class C, class T>
273 class RefMember : public SGRawValue<T>
276 RefMember (C *obj, T C::*ptr)
277 : _obj(obj), _ptr(ptr) {}
278 virtual ~RefMember () {}
279 virtual T getValue () const
281 return _obj.get()->*_ptr;
283 virtual bool setValue (T value)
285 _obj.get()->*_ptr = value;
288 virtual SGRawValue<T> * clone () const
290 return new RefMember(_obj.get(), _ptr);
297 template<typename C, typename T>
298 RefMember<C, T> makeRefMember(C *obj, T C::*ptr)
300 return RefMember<C, T>(obj, ptr);
303 template<typename C, typename T>
304 void bindMemberToNode(SGPropertyNode* parent, const char* childName,
305 C* obj, T C::*ptr, T value)
307 SGPropertyNode* valNode = parent->getNode(childName);
308 RefMember<C, T> refMember = makeRefMember(obj, ptr);
310 valNode = parent->getNode(childName, true);
311 valNode->tie(refMember, false);
312 setValue(valNode, value);
314 valNode->tie(refMember, true);
318 void buildViewport(flightgear::CameraInfo* info, SGPropertyNode* viewportNode,
319 const osg::GraphicsContext::Traits *traits)
321 using namespace flightgear;
322 bindMemberToNode(viewportNode, "x", info, &CameraInfo::x, 0.0);
323 bindMemberToNode(viewportNode, "y", info, &CameraInfo::y, 0.0);
324 bindMemberToNode(viewportNode, "width", info, &CameraInfo::width,
325 static_cast<double>(traits->width));
326 bindMemberToNode(viewportNode, "height", info, &CameraInfo::height,
327 static_cast<double>(traits->height));
334 // Mostly copied from osg's osgViewer/View.cpp
336 static osg::Geometry* createParoramicSphericalDisplayDistortionMesh(
337 const Vec3& origin, const Vec3& widthVector, const Vec3& heightVector,
338 double sphere_radius, double collar_radius,
339 Image* intensityMap = 0, const Matrix& projectorMatrix = Matrix())
341 osg::Vec3d center(0.0,0.0,0.0);
342 osg::Vec3d eye(0.0,0.0,0.0);
344 double distance = sqrt(sphere_radius*sphere_radius - collar_radius*collar_radius);
346 bool texcoord_flip = false;
348 osg::Vec3d projector = eye - osg::Vec3d(0.0,0.0, distance);
351 OSG_INFO<<"createParoramicSphericalDisplayDistortionMesh : Projector position = "<<projector<<std::endl;
352 OSG_INFO<<"createParoramicSphericalDisplayDistortionMesh : distance = "<<distance<<std::endl;
354 // create the quad to visualize.
355 osg::Geometry* geometry = new osg::Geometry();
357 geometry->setSupportsDisplayList(false);
359 osg::Vec3 xAxis(widthVector);
360 float width = widthVector.length();
363 osg::Vec3 yAxis(heightVector);
364 float height = heightVector.length();
369 osg::Vec3Array* vertices = new osg::Vec3Array;
370 osg::Vec2Array* texcoords0 = new osg::Vec2Array;
371 osg::Vec2Array* texcoords1 = intensityMap==0 ? new osg::Vec2Array : 0;
372 osg::Vec4Array* colors = new osg::Vec4Array;
374 osg::Vec3 bottom = origin;
375 osg::Vec3 dx = xAxis*(width/((float)(noSteps-2)));
376 osg::Vec3 dy = yAxis*(height/((float)(noSteps-1)));
378 osg::Vec3 top = origin + yAxis*height;
380 osg::Vec3 screenCenter = origin + widthVector*0.5f + heightVector*0.5f;
381 float screenRadius = heightVector.length() * 0.5f;
383 geometry->getOrCreateStateSet()->setMode(GL_CULL_FACE, osg::StateAttribute::OFF | osg::StateAttribute::PROTECTED);
385 for(int i=0;i<noSteps;++i)
387 osg::Vec3 cursor = bottom+dy*(float)i;
388 for(int j=0;j<noSteps;++j)
390 osg::Vec2 texcoord(double(i)/double(noSteps-1), double(j)/double(noSteps-1));
391 double theta = texcoord.x() * 2.0 * osg::PI;
392 double phi = (1.0-texcoord.y()) * osg::PI;
394 if (texcoord_flip) texcoord.y() = 1.0f - texcoord.y();
396 osg::Vec3 pos(sin(phi)*sin(theta), sin(phi)*cos(theta), cos(phi));
397 pos = pos*projectorMatrix;
399 double alpha = atan2(pos.x(), pos.y());
400 if (alpha<0.0) alpha += 2.0*osg::PI;
402 double beta = atan2(sqrt(pos.x()*pos.x() + pos.y()*pos.y()), pos.z());
403 if (beta<0.0) beta += 2.0*osg::PI;
405 double gamma = atan2(sqrt(double(pos.x()*pos.x() + pos.y()*pos.y())), double(pos.z()+distance));
406 if (gamma<0.0) gamma += 2.0*osg::PI;
409 osg::Vec3 v = screenCenter + osg::Vec3(sin(alpha)*gamma*2.0/osg::PI, -cos(alpha)*gamma*2.0/osg::PI, 0.0f)*screenRadius;
412 vertices->push_back(osg::Vec3(v.x(), top.y()-(v.y()-origin.y()),v.z()));
414 vertices->push_back(v);
416 texcoords0->push_back( texcoord );
418 osg::Vec2 texcoord1(alpha/(2.0*osg::PI), 1.0f - beta/osg::PI);
421 colors->push_back(intensityMap->getColor(texcoord1));
425 colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
426 if (texcoords1) texcoords1->push_back( texcoord1 );
434 // pass the created vertex array to the points geometry object.
435 geometry->setVertexArray(vertices);
437 geometry->setColorArray(colors);
438 geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
440 geometry->setTexCoordArray(0,texcoords0);
441 if (texcoords1) geometry->setTexCoordArray(1,texcoords1);
443 osg::DrawElementsUShort* elements = new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLES);
444 geometry->addPrimitiveSet(elements);
446 for(int i=0;i<noSteps-1;++i)
448 for(int j=0;j<noSteps-1;++j)
450 int i1 = j+(i+1)*noSteps;
451 int i2 = j+(i)*noSteps;
452 int i3 = j+1+(i)*noSteps;
453 int i4 = j+1+(i+1)*noSteps;
455 osg::Vec3& v1 = (*vertices)[i1];
456 osg::Vec3& v2 = (*vertices)[i2];
457 osg::Vec3& v3 = (*vertices)[i3];
458 osg::Vec3& v4 = (*vertices)[i4];
460 if ((v1-screenCenter).length()>screenRadius) continue;
461 if ((v2-screenCenter).length()>screenRadius) continue;
462 if ((v3-screenCenter).length()>screenRadius) continue;
463 if ((v4-screenCenter).length()>screenRadius) continue;
465 elements->push_back(i1);
466 elements->push_back(i2);
467 elements->push_back(i3);
469 elements->push_back(i1);
470 elements->push_back(i3);
471 elements->push_back(i4);
478 void CameraGroup::buildDistortionCamera(const SGPropertyNode* psNode,
481 const SGPropertyNode* texNode = psNode->getNode("texture");
486 string texName = texNode->getStringValue();
487 TextureMap::iterator itr = _textureTargets.find(texName);
488 if (itr == _textureTargets.end()) {
492 Viewport* viewport = camera->getViewport();
493 float width = viewport->width();
494 float height = viewport->height();
495 TextureRectangle* texRect = itr->second.get();
496 double radius = psNode->getDoubleValue("radius", 1.0);
497 double collar = psNode->getDoubleValue("collar", 0.45);
498 Geode* geode = new Geode();
499 geode->addDrawable(createParoramicSphericalDisplayDistortionMesh(
500 Vec3(0.0f,0.0f,0.0f), Vec3(width,0.0f,0.0f),
501 Vec3(0.0f,height,0.0f), radius, collar));
503 // new we need to add the texture to the mesh, we do so by creating a
504 // StateSet to contain the Texture StateAttribute.
505 StateSet* stateset = geode->getOrCreateStateSet();
506 stateset->setTextureAttributeAndModes(0, texRect, StateAttribute::ON);
507 stateset->setMode(GL_LIGHTING, StateAttribute::OFF);
509 TexMat* texmat = new TexMat;
510 texmat->setScaleByTextureRectangleSize(true);
511 stateset->setTextureAttributeAndModes(0, texmat, osg::StateAttribute::ON);
513 if (!applyIntensityMapAsColours && intensityMap)
515 stateset->setTextureAttributeAndModes(1, new osg::Texture2D(intensityMap), osg::StateAttribute::ON);
518 // add subgraph to render
519 camera->addChild(geode);
520 camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
521 camera->setClearColor(osg::Vec4(0.0, 0.0, 0.0, 1.0));
522 camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
523 camera->setCullingMode(osg::CullSettings::NO_CULLING);
524 camera->setName("DistortionCorrectionCamera");
527 CameraInfo* CameraGroup::buildCamera(SGPropertyNode* cameraNode)
529 WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
530 const SGPropertyNode* windowNode = cameraNode->getNode("window");
531 GraphicsWindow* window = 0;
532 int cameraFlags = DO_INTERSECTION_TEST;
534 // New style window declaration / definition
535 window = wBuild->buildWindow(windowNode);
537 // Old style: suck window params out of camera block
538 window = wBuild->buildWindow(cameraNode);
543 Camera* camera = new Camera;
544 camera->setAllowEventFocus(false);
545 camera->setGraphicsContext(window->gc.get());
546 camera->setViewport(new Viewport);
547 camera->setCullingMode(CullSettings::SMALL_FEATURE_CULLING
548 | CullSettings::VIEW_FRUSTUM_CULLING);
549 camera->setInheritanceMask(CullSettings::ALL_VARIABLES
550 & ~(CullSettings::CULL_MASK
551 | CullSettings::CULLING_MODE
552 #if defined(HAVE_CULLSETTINGS_CLEAR_MASK)
553 | CullSettings::CLEAR_MASK
559 const SGPropertyNode* viewNode = cameraNode->getNode("view");
561 double heading = viewNode->getDoubleValue("heading-deg", 0.0);
562 double pitch = viewNode->getDoubleValue("pitch-deg", 0.0);
563 double roll = viewNode->getDoubleValue("roll-deg", 0.0);
564 double x = viewNode->getDoubleValue("x", 0.0);
565 double y = viewNode->getDoubleValue("y", 0.0);
566 double z = viewNode->getDoubleValue("z", 0.0);
567 // Build a view matrix, which is the inverse of a model
568 // orientation matrix.
569 vOff = (Matrix::translate(-x, -y, -z)
570 * Matrix::rotate(-DegreesToRadians(heading),
571 Vec3d(0.0, 1.0, 0.0),
572 -DegreesToRadians(pitch),
573 Vec3d(1.0, 0.0, 0.0),
574 -DegreesToRadians(roll),
575 Vec3d(0.0, 0.0, 1.0)));
576 if (viewNode->getBoolValue("absolute", false))
577 cameraFlags |= VIEW_ABSOLUTE;
579 // Old heading parameter, works in the opposite direction
580 double heading = cameraNode->getDoubleValue("heading-deg", 0.0);
581 vOff.makeRotate(DegreesToRadians(heading), osg::Vec3(0, 1, 0));
583 const SGPropertyNode* projectionNode = 0;
584 if ((projectionNode = cameraNode->getNode("perspective")) != 0) {
585 double fovy = projectionNode->getDoubleValue("fovy-deg", 55.0);
586 double aspectRatio = projectionNode->getDoubleValue("aspect-ratio",
588 double zNear = projectionNode->getDoubleValue("near", 0.0);
589 double zFar = projectionNode->getDoubleValue("far", 0.0);
590 double offsetX = projectionNode->getDoubleValue("offset-x", 0.0);
591 double offsetY = projectionNode->getDoubleValue("offset-y", 0.0);
592 double tan_fovy = tan(DegreesToRadians(fovy*0.5));
593 double right = tan_fovy * aspectRatio * zNear + offsetX;
594 double left = -tan_fovy * aspectRatio * zNear + offsetX;
595 double top = tan_fovy * zNear + offsetY;
596 double bottom = -tan_fovy * zNear + offsetY;
597 pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
598 cameraFlags |= PROJECTION_ABSOLUTE;
599 } else if ((projectionNode = cameraNode->getNode("frustum")) != 0
600 || (projectionNode = cameraNode->getNode("ortho")) != 0) {
601 double top = projectionNode->getDoubleValue("top", 0.0);
602 double bottom = projectionNode->getDoubleValue("bottom", 0.0);
603 double left = projectionNode->getDoubleValue("left", 0.0);
604 double right = projectionNode->getDoubleValue("right", 0.0);
605 double zNear = projectionNode->getDoubleValue("near", 0.0);
606 double zFar = projectionNode->getDoubleValue("far", 0.0);
607 if (cameraNode->getNode("frustum")) {
608 pOff.makeFrustum(left, right, bottom, top, zNear, zFar);
609 cameraFlags |= PROJECTION_ABSOLUTE;
611 pOff.makeOrtho(left, right, bottom, top, zNear, zFar);
612 cameraFlags |= (PROJECTION_ABSOLUTE | ORTHO);
615 // old style shear parameters
616 double shearx = cameraNode->getDoubleValue("shear-x", 0);
617 double sheary = cameraNode->getDoubleValue("shear-y", 0);
618 pOff.makeTranslate(-shearx, -sheary, 0);
620 const SGPropertyNode* textureNode = cameraNode->getNode("texture");
622 string texName = textureNode->getStringValue("name");
623 int tex_width = textureNode->getIntValue("width");
624 int tex_height = textureNode->getIntValue("height");
625 TextureRectangle* texture = new TextureRectangle;
627 texture->setTextureSize(tex_width, tex_height);
628 texture->setInternalFormat(GL_RGB);
629 texture->setFilter(Texture::MIN_FILTER, Texture::LINEAR);
630 texture->setFilter(Texture::MAG_FILTER, Texture::LINEAR);
631 texture->setWrap(Texture::WRAP_S, Texture::CLAMP_TO_EDGE);
632 texture->setWrap(Texture::WRAP_T, Texture::CLAMP_TO_EDGE);
633 camera->setDrawBuffer(GL_FRONT);
634 camera->setReadBuffer(GL_FRONT);
635 camera->setRenderTargetImplementation(Camera::FRAME_BUFFER_OBJECT);
636 camera->attach(Camera::COLOR_BUFFER, texture);
637 _textureTargets[texName] = texture;
639 camera->setDrawBuffer(GL_BACK);
640 camera->setReadBuffer(GL_BACK);
642 const SGPropertyNode* psNode = cameraNode->getNode("panoramic-spherical");
643 bool useMasterSceneGraph = !psNode;
644 CameraInfo* info = addCamera(cameraFlags, camera, vOff, pOff,
645 useMasterSceneGraph);
646 // If a viewport isn't set on the camera, then it's hard to dig it
647 // out of the SceneView objects in the viewer, and the coordinates
648 // of mouse events are somewhat bizzare.
649 SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
650 buildViewport(info, viewportNode, window->gc->getTraits());
652 // Distortion camera needs the viewport which is created by addCamera().
654 info->flags = info->flags | VIEW_ABSOLUTE;
655 buildDistortionCamera(psNode, camera);
660 CameraInfo* CameraGroup::buildGUICamera(SGPropertyNode* cameraNode,
661 GraphicsWindow* window)
663 WindowBuilder *wBuild = WindowBuilder::getWindowBuilder();
664 const SGPropertyNode* windowNode = (cameraNode
665 ? cameraNode->getNode("window")
667 if (!window && windowNode) {
668 // New style window declaration / definition
669 window = wBuild->buildWindow(windowNode);
672 if (!window) { // buildWindow can fail
673 SG_LOG(SG_GENERAL, SG_WARN, "CameraGroup::buildGUICamera: failed to build a window");
677 Camera* camera = new Camera;
678 camera->setAllowEventFocus(false);
679 camera->setGraphicsContext(window->gc.get());
680 camera->setViewport(new Viewport);
681 // XXX Camera needs to be drawn last; eventually the render order
682 // should be assigned by a camera manager.
683 camera->setRenderOrder(osg::Camera::POST_RENDER, 100);
684 camera->setClearMask(0);
685 camera->setInheritanceMask(CullSettings::ALL_VARIABLES
686 & ~(CullSettings::COMPUTE_NEAR_FAR_MODE
687 | CullSettings::CULLING_MODE
688 #if defined(HAVE_CULLSETTINGS_CLEAR_MASK)
689 | CullSettings::CLEAR_MASK
692 camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
693 camera->setCullingMode(osg::CullSettings::NO_CULLING);
694 camera->setProjectionResizePolicy(Camera::FIXED);
695 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
696 const int cameraFlags = GUI;
697 CameraInfo* result = addCamera(cameraFlags, camera, Matrixd::identity(),
698 Matrixd::identity(), false);
699 SGPropertyNode* viewportNode = cameraNode->getNode("viewport", true);
700 buildViewport(result, viewportNode, window->gc->getTraits());
702 // Disable statistics for the GUI camera.
703 result->camera->setStats(0);
704 updateCameras(result);
708 CameraGroup* CameraGroup::buildCameraGroup(osgViewer::Viewer* viewer,
709 SGPropertyNode* gnode)
711 CameraGroup* cgroup = new CameraGroup(viewer);
712 for (int i = 0; i < gnode->nChildren(); ++i) {
713 SGPropertyNode* pNode = gnode->getChild(i);
714 const char* name = pNode->getName();
715 if (!strcmp(name, "camera")) {
716 cgroup->buildCamera(pNode);
717 } else if (!strcmp(name, "window")) {
718 WindowBuilder::getWindowBuilder()->buildWindow(pNode);
719 } else if (!strcmp(name, "gui")) {
720 cgroup->buildGUICamera(pNode);
723 bindMemberToNode(gnode, "znear", cgroup, &CameraGroup::_zNear, .1f);
724 bindMemberToNode(gnode, "zfar", cgroup, &CameraGroup::_zFar, 120000.0f);
725 bindMemberToNode(gnode, "near-field", cgroup, &CameraGroup::_nearField,
730 void CameraGroup::setCameraCullMasks(Node::NodeMask nm)
732 for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
733 CameraInfo* info = i->get();
734 if (info->flags & GUI)
736 if (info->farCamera.valid() && info->farCamera->getNodeMask() != 0) {
737 info->camera->setCullMask(nm & ~simgear::BACKGROUND_BIT);
738 info->camera->setCullMaskLeft(nm & ~simgear::BACKGROUND_BIT);
739 info->camera->setCullMaskRight(nm & ~simgear::BACKGROUND_BIT);
740 info->farCamera->setCullMask(nm);
741 info->farCamera->setCullMaskLeft(nm);
742 info->farCamera->setCullMaskRight(nm);
744 info->camera->setCullMask(nm);
745 info->camera->setCullMaskLeft(nm);
746 info->camera->setCullMaskRight(nm);
751 void CameraGroup::resized()
753 for (CameraIterator i = camerasBegin(), e = camerasEnd(); i != e; ++i) {
754 CameraInfo *info = i->get();
755 const Viewport* viewport = info->camera->getViewport();
756 info->x = viewport->x();
757 info->y = viewport->y();
758 info->width = viewport->width();
759 info->height = viewport->height();
763 Camera* getGUICamera(CameraGroup* cgroup)
765 CameraGroup::CameraIterator end = cgroup->camerasEnd();
766 CameraGroup::CameraIterator result
767 = std::find_if(cgroup->camerasBegin(), end,
768 FlagTester<CameraInfo>(CameraGroup::GUI));
770 return (*result)->camera.get();
775 bool computeIntersections(const CameraGroup* cgroup,
776 const osgGA::GUIEventAdapter* ea,
777 osgUtil::LineSegmentIntersector::Intersections& intersections)
779 using osgUtil::Intersector;
780 using osgUtil::LineSegmentIntersector;
782 eventToWindowCoords(ea, x, y);
783 // Find camera that contains event
784 for (CameraGroup::ConstCameraIterator iter = cgroup->camerasBegin(),
785 e = cgroup->camerasEnd();
788 const CameraInfo* cinfo = iter->get();
789 if ((cinfo->flags & CameraGroup::DO_INTERSECTION_TEST) == 0)
791 const Camera* camera = cinfo->camera.get();
792 if (camera->getGraphicsContext() != ea->getGraphicsContext())
794 const Viewport* viewport = camera->getViewport();
795 double epsilon = 0.5;
796 if (!(x >= viewport->x() - epsilon
797 && x < viewport->x() + viewport->width() -1.0 + epsilon
798 && y >= viewport->y() - epsilon
799 && y < viewport->y() + viewport->height() -1.0 + epsilon))
801 Vec4d start(x, y, 0.0, 1.0);
802 Vec4d end(x, y, 1.0, 1.0);
803 Matrix windowMat = viewport->computeWindowMatrix();
804 Matrix startPtMat = Matrix::inverse(camera->getProjectionMatrix()
807 if (!cinfo->farCamera.valid() || cinfo->farCamera->getNodeMask() == 0)
808 endPtMat = startPtMat;
810 endPtMat = Matrix::inverse(cinfo->farCamera->getProjectionMatrix()
812 start = start * startPtMat;
814 end = end * endPtMat;
816 ref_ptr<LineSegmentIntersector> picker
817 = new LineSegmentIntersector(Intersector::VIEW,
818 Vec3d(start.x(), start.y(), start.z()),
819 Vec3d(end.x(), end.y(), end.z()));
820 osgUtil::IntersectionVisitor iv(picker.get());
821 const_cast<Camera*>(camera)->accept(iv);
822 if (picker->containsIntersections()) {
823 intersections = picker->getIntersections();
829 intersections.clear();
833 void warpGUIPointer(CameraGroup* cgroup, int x, int y)
835 using osgViewer::GraphicsWindow;
836 Camera* guiCamera = getGUICamera(cgroup);
839 Viewport* vport = guiCamera->getViewport();
841 = dynamic_cast<GraphicsWindow*>(guiCamera->getGraphicsContext());
844 globals->get_renderer()->getEventHandler()->setMouseWarped();
845 // Translate the warp request into the viewport of the GUI camera,
846 // send the request to the window, then transform the coordinates
847 // for the Viewer's event queue.
848 double wx = x + vport->x();
849 double wyUp = vport->height() + vport->y() - y;
851 const GraphicsContext::Traits* traits = gw->getTraits();
852 if (gw->getEventQueue()->getCurrentEventState()->getMouseYOrientation()
853 == osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS) {
854 wy = traits->height - wyUp;
858 gw->getEventQueue()->mouseWarped(wx, wy);
859 gw->requestWarpPointer(wx, wy);
860 osgGA::GUIEventAdapter* eventState
861 = cgroup->getViewer()->getEventQueue()->getCurrentEventState();
863 = (eventState->getXmin()
864 + ((wx / double(traits->width))
865 * (eventState->getXmax() - eventState->getXmin())));
867 = (eventState->getYmin()
868 + ((wyUp / double(traits->height))
869 * (eventState->getYmax() - eventState->getYmin())));
870 cgroup->getViewer()->getEventQueue()->mouseWarped(viewerX, viewerY);