root/OpenSceneGraph/trunk/src/osgViewer/View.cpp @ 12597

Revision 12597, 81.1 kB (checked in by robert, 3 years ago)

Resolved warnings reported by g++ 4.6's -Wunused-but-set-variable.

Warnings were:

/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osg/ShapeDrawable.cpp: In member function ‘void PrimitiveShapeVisitor::createHalfSphere(unsigned int, unsigned int, float, int, float, const Matrix&)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osg/ShapeDrawable.cpp:1409:11: warning: variable ‘nzBase’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osg/ShapeDrawable.cpp:1410:11: warning: variable ‘nRatioBase’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgUtil/DelaunayTriangulator.cpp: In function ‘osgUtil::Triangle_list osgUtil::fillHole(osg::Vec3Array*, std::vector<unsigned int, std::allocator<unsigned int> >)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgUtil/DelaunayTriangulator.cpp:569:27: warning: variable ‘ptest’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgUtil/DelaunayTriangulator.cpp: In member function ‘bool osgUtil::DelaunayTriangulator::triangulate()’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgUtil/DelaunayTriangulator.cpp:979:45: warning: variable ‘curp’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgUtil/RenderStage.cpp: In member function ‘void osgUtil::RenderStage::runCameraSetUp(osg::RenderInfo?&)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgUtil/RenderStage.cpp:631:18: warning: variable ‘stencilAttached’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgText/FadeText.cpp: In member function ‘void FadeTextPolytopeData::buildPolytope()’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgText/FadeText.cpp:74:20: warning: variable ‘edge23’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgText/FadeText.cpp:75:20: warning: variable ‘edge30’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgText/Text.cpp: In member function ‘void osgText::Text::computeBackdropPositions(unsigned int) const’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgText/Text.cpp:747:10: warning: variable ‘is_valid_size’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgGA/NodeTrackerManipulator.cpp: In member function ‘virtual bool osgGA::NodeTrackerManipulator::performMovementLeftMouseButton(double, double, double)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgGA/NodeTrackerManipulator.cpp:257:21: warning: variable ‘lookVector’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgGA/NodeTrackerManipulator.cpp:259:21: warning: variable ‘upVector’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgGA/TerrainManipulator.cpp: In member function ‘virtual bool osgGA::TerrainManipulator::performMovementMiddleMouseButton(double, double, double)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgGA/TerrainManipulator.cpp:217:11: warning: variable ‘lookVector’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgGA/TerrainManipulator.cpp:219:11: warning: variable ‘upVector’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgVolume/FixedFunctionTechnique.cpp: In member function ‘virtual void osgVolume::FixedFunctionTechnique::init()’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgVolume/FixedFunctionTechnique.cpp:124:30: warning: variable ‘tf’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgParticle/FluidProgram.cpp: In member function ‘virtual void osgParticle::FluidProgram::execute(double)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgParticle/FluidProgram.cpp:38:23: warning: variable ‘velBefore’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgShadow/ParallelSplitShadowMap.cpp: In member function ‘virtual void osgShadow::ParallelSplitShadowMap::cull(osgUtil::CullVisitor?&)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgShadow/ParallelSplitShadowMap.cpp:593:22: warning: variable ‘bb’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgTerrain/GeometryTechnique.cpp: In member function ‘virtual void osgTerrain::GeometryTechnique::generateGeometry(osgTerrain::GeometryTechnique::BufferData?&, osgTerrain::Locator*, const osg::Vec3d&)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgTerrain/GeometryTechnique.cpp:777:12: warning: variable ‘i_sampleFactor’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgTerrain/GeometryTechnique.cpp:778:12: warning: variable ‘j_sampleFactor’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/dds/ReaderWriterDDS.cpp: In function ‘osg::Image* ReadDDSFile(std::istream&)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/dds/ReaderWriterDDS.cpp:314:10: warning: variable ‘is3dImage’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/dds/ReaderWriterDDS.cpp: In function ‘bool WriteDDSFile(const osg::Image*, std::ostream&)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/dds/ReaderWriterDDS.cpp:721:10: warning: variable ‘is3dImage’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/hdr/hdrloader.cpp: In static member function ‘static bool HDRLoader::load(const char*, bool, HDRLoaderResult&)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/hdr/hdrloader.cpp:101:10: warning: variable ‘cmd’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/vtf/ReaderWriterVTF.cpp: In function ‘osg::Image* ReadVTFFile(std::istream&)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/vtf/ReaderWriterVTF.cpp:360:23: warning: variable ‘base’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/jp2/ReaderWriterJP2.cpp: In function ‘int putdata(jas_stream_t*, jas_image_t*, int)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/jp2/ReaderWriterJP2.cpp:41:13: warning: variable ‘linelen’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/Inventor/ConvertToInventor.cpp: In member function ‘void ConvertToInventor::processGeometry(const osg::Geometry*, ConvertToInventor::InventorState?*)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/Inventor/ConvertToInventor.cpp:1639:10: warning: variable ‘ok’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/Inventor/ConvertFromInventor.cpp: In member function ‘virtual SbBool? SoVRMLImageTextureOsg::readInstance(SoInput?*, short unsigned int)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/Inventor/ConvertFromInventor.cpp:1264:16: warning: variable ‘retval’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/OpenFlight/GeometryRecords.cpp: In member function ‘virtual void flt::Face::readRecord(flt::RecordInputStream?&, flt::Document&)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/OpenFlight/GeometryRecords.cpp:369:19: warning: variable ‘secondaryPackedColor’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/OpenFlight/GeometryRecords.cpp: In member function ‘virtual void flt::Mesh::readRecord(flt::RecordInputStream?&, flt::Document&)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/OpenFlight/GeometryRecords.cpp:942:19: warning: variable ‘secondaryPackedColor’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/OpenFlight/ReaderWriterFLT.cpp: In member function ‘virtual osgDB::ReaderWriter::ReadResult? FLTReaderWriter::readNode(std::istream&, const Options*) const’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/OpenFlight/ReaderWriterFLT.cpp:427:40: warning: variable ‘pos’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/ive/ShapeAttributeList.cpp: In member function ‘void ive::ShapeAttributeList::write(ive::DataOutputStream?*)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/ive/ShapeAttributeList.cpp:31:48: warning: variable ‘it’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/ac/Geode.cpp: In member function ‘void ac3d::Geode::ProcessGeometry?(std::ostream&, unsigned int)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/ac/Geode.cpp:806:35: warning: variable ‘fRep_s’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/ac/Geode.cpp:806:43: warning: variable ‘fRep_t’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/ac/Geode.cpp:807:35: warning: variable ‘fOffset_s’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/ac/Geode.cpp:807:46: warning: variable ‘fOffset_t’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/ac/Geode.cpp:932:38: warning: variable ‘primLength’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/txp/trpage_geom.cpp: In member function ‘virtual bool trpgGeometry::Write(trpgWriteBuffer&)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/txp/trpage_geom.cpp:615:19: warning: variable ‘u’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/txp/trpage_material.cpp: In member function ‘int trpgMatTable::AddMaterial?(const trpgMaterial&, bool)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/txp/trpage_material.cpp:103:10: warning: variable ‘spaceInTable’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/txp/trpage_rarchive.cpp: In member function ‘virtual bool trpgr_Archive::ReadHeader?(bool)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/txp/trpage_rarchive.cpp:261:14: warning: variable ‘headerHasTexTable’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/zip/unzip.cpp: In member function ‘ZRESULT TUnzip::Get(int, ZIPENTRY*)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/zip/unzip.cpp:4055:8: warning: variable ‘hidden’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/zip/unzip.cpp:4055:22: warning: variable ‘system’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/zip/unzip.cpp:4055:36: warning: variable ‘archive’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/zip/ZipArchive.cpp: In member function ‘virtual bool ZipArchive::getFileNames(osgDB::Archive::FileNameList?&) const’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/zip/ZipArchive.cpp:91:37: warning: variable ‘iterEnd’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/pvr/ReaderWriterPVR.cpp: In member function ‘osgDB::ReaderWriter::ReadResult? ReaderWriterPVR::readPVRStream(std::istream&) const’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/pvr/ReaderWriterPVR.cpp:155:14: warning: variable ‘hasAlpha’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgViewer/View.cpp: In function ‘osg::Geometry* create3DSphericalDisplayDistortionMesh(const Vec3&, const Vec3&, const Vec3&, double, double, osg::Image*, const Matrix&)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgViewer/View.cpp:737:15: warning: variable ‘cursor’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgViewer/View.cpp: In function ‘osg::Geometry* createParoramicSphericalDisplayDistortionMesh(const Vec3&, const Vec3&, const Vec3&, double, double, osg::Image*, const Matrix&)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgViewer/View.cpp:1130:19: warning: variable ‘cursor’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgViewer/View.cpp:1118:15: warning: variable ‘dx’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgViewer/GraphicsWindowX11.cpp: In member function ‘virtual void osgViewer::GraphicsWindowX11::checkEvents()’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgViewer/GraphicsWindowX11.cpp:1181:10: warning: variable ‘destroyWindowRequested’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/cfg/ConfigParser.cpp: In member function ‘bool osgProducer::CameraConfig::parseFile(const string&)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/cfg/ConfigParser.cpp:2247:13: warning: variable ‘result’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgQt/QGraphicsViewAdapter.cpp: In member function ‘bool osgQt::QGraphicsViewAdapter::handlePointerEvent(int, int, int)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgQt/QGraphicsViewAdapter.cpp:344:17: warning: variable ‘viewportGeometry’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/examples/osgdistortion/osgdistortion.cpp: In function ‘osg::Node* createDistortionSubgraph(osg::Node*, const Vec4&)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/examples/osgdistortion/osgdistortion.cpp:125:19: warning: variable ‘cursor’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/examples/osgdistortion/osgdistortion.cpp:126:19: warning: variable ‘texcoord’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/examples/osgdistortion/osgdistortion.cpp: In function ‘osg::Geometry* createDomeDistortionMesh(const Vec3&, const Vec3&, const Vec3&, osg::ArgumentParser?&)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/examples/osgdistortion/osgdistortion.cpp:358:15: warning: variable ‘cursor’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/examples/osgposter/osgposter.cpp: In function ‘int main(int, char**)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/examples/osgposter/osgposter.cpp:253:31: warning: variable ‘outputTiles’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/examples/osgthreadedterrain/osgthreadedterrain.cpp: In function ‘int main(int, char**)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/examples/osgthreadedterrain/osgthreadedterrain.cpp:669:10: warning: variable ‘readParameter’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/examples/osgtext3D/TextNode.cpp: In member function ‘virtual void osgText::Layout::layout(osgText::TextNode?&) const’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/examples/osgtext3D/TextNode.cpp:80:11: warning: variable ‘characterHeightScale’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/examples/osgvolume/osgvolume.cpp: In function ‘int main(int, char**)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/examples/osgvolume/osgvolume.cpp:678:38: warning: variable ‘internalFormatMode’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/examples/osgwidgetcanvas/osgwidgetcanvas.cpp: In function ‘bool windowMouseOver(osgWidget::Event&)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/examples/osgwidgetcanvas/osgwidgetcanvas.cpp:27:24: warning: variable ‘xy’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/examples/osgwidgetcanvas/osgwidgetcanvas.cpp: In function ‘bool widgetMouseOver(osgWidget::Event&)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/examples/osgwidgetcanvas/osgwidgetcanvas.cpp:35:24: warning: variable ‘xy’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/p3d/ReaderWriterP3D.cpp: In member function ‘osg::Node* ReaderWriterP3DXML::parseXmlGraph(osgDB::XmlNode?*, bool, osgDB::Options*) const’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/src/osgPlugins/p3d/ReaderWriterP3D.cpp:2121:10: warning: variable ‘readSlide’ set but not used [-Wunused-but-set-variable]
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/applications/present3D/present3D.cpp: In function ‘int main(int, char**)’:
/home/stephan/Dev/LibSources/OpenSceneGraph-3.0.0-rc2/applications/present3D/present3D.cpp:639:10: warning: variable ‘sizesSpecified’ set but not used [-Wunused-but-set-variable]

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
2 *
3 * This library is open source and may be redistributed and/or modified under
4 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
5 * (at your option) any later version.  The full license is in LICENSE file
6 * included with this distribution, and on the openscenegraph.org website.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 * OpenSceneGraph Public License for more details.
12*/
13
14#include <osgViewer/Renderer>
15#include <osgViewer/View>
16#include <osgViewer/GraphicsWindow>
17
18#include <osg/io_utils>
19
20#include <osg/TextureCubeMap>
21#include <osg/TextureRectangle>
22#include <osg/Texture1D>
23#include <osg/TexMat>
24
25#include <osgUtil/Optimizer>
26#include <osgUtil/ShaderGen>
27#include <osgUtil/IntersectionVisitor>
28
29#include <iterator>
30
31using namespace osgViewer;
32
33class CollectedCoordinateSystemNodesVisitor : public osg::NodeVisitor
34{
35public:
36
37    CollectedCoordinateSystemNodesVisitor():
38        NodeVisitor(osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN) {}
39
40    META_NodeVisitor("osgViewer","CollectedCoordinateSystemNodesVisitor")
41
42    virtual void apply(osg::Node& node)
43    {
44        traverse(node);
45    }
46
47    virtual void apply(osg::CoordinateSystemNode& node)
48    {
49        if (_pathToCoordinateSystemNode.empty())
50        {
51            OSG_DEBUG<<"Found CoordinateSystemNode node"<<std::endl;
52            OSG_DEBUG<<"     CoordinateSystem = "<<node.getCoordinateSystem()<<std::endl;
53            _pathToCoordinateSystemNode = getNodePath();
54        }
55        else
56        {
57            OSG_DEBUG<<"Found additional CoordinateSystemNode node, but ignoring"<<std::endl;
58            OSG_DEBUG<<"     CoordinateSystem = "<<node.getCoordinateSystem()<<std::endl;
59        }
60        traverse(node);
61    }
62
63    osg::NodePath _pathToCoordinateSystemNode;
64};
65
66
67/** callback class to use to allow matrix manipulators to query the application for the local coordinate frame.*/
68class ViewerCoordinateFrameCallback : public osgGA::CameraManipulator::CoordinateFrameCallback
69{
70public:
71
72    ViewerCoordinateFrameCallback(osgViewer::View* view):
73        _view(view) {}
74
75    virtual osg::CoordinateFrame getCoordinateFrame(const osg::Vec3d& position) const
76    {
77        OSG_DEBUG<<"getCoordinateFrame("<<position<<")"<<std::endl;
78
79        osg::NodePath tmpPath = _view->getCoordinateSystemNodePath();
80
81        if (!tmpPath.empty())
82        {
83            osg::Matrixd coordinateFrame;
84
85            osg::CoordinateSystemNode* csn = dynamic_cast<osg::CoordinateSystemNode*>(tmpPath.back());
86            if (csn)
87            {
88                osg::Vec3 local_position = position*osg::computeWorldToLocal(tmpPath);
89
90                // get the coordinate frame in world coords.
91                coordinateFrame = csn->computeLocalCoordinateFrame(local_position)* osg::computeLocalToWorld(tmpPath);
92
93                // keep the position of the coordinate frame to reapply after rescale.
94                osg::Vec3d pos = coordinateFrame.getTrans();
95
96                // compensate for any scaling, so that the coordinate frame is a unit size
97                osg::Vec3d x(1.0,0.0,0.0);
98                osg::Vec3d y(0.0,1.0,0.0);
99                osg::Vec3d z(0.0,0.0,1.0);
100                x = osg::Matrixd::transform3x3(x,coordinateFrame);
101                y = osg::Matrixd::transform3x3(y,coordinateFrame);
102                z = osg::Matrixd::transform3x3(z,coordinateFrame);
103                coordinateFrame.preMultScale(osg::Vec3d(1.0/x.length(),1.0/y.length(),1.0/z.length()));
104
105                // reapply the position.
106                coordinateFrame.setTrans(pos);
107
108                OSG_DEBUG<<"csn->computeLocalCoordinateFrame(position)* osg::computeLocalToWorld(tmpPath)"<<coordinateFrame<<std::endl;
109
110            }
111            else
112            {
113                OSG_DEBUG<<"osg::computeLocalToWorld(tmpPath)"<<std::endl;
114                coordinateFrame =  osg::computeLocalToWorld(tmpPath);
115            }
116            return coordinateFrame;
117        }
118        else
119        {
120            OSG_DEBUG<<"   no coordinate system found, using default orientation"<<std::endl;
121            return osg::Matrixd::translate(position);
122        }
123    }
124
125protected:
126    virtual ~ViewerCoordinateFrameCallback() {}
127
128    osg::observer_ptr<osgViewer::View> _view;
129};
130
131
132View::View():
133    _fusionDistanceMode(osgUtil::SceneView::PROPORTIONAL_TO_SCREEN_DISTANCE),
134    _fusionDistanceValue(1.0f)
135{
136    // OSG_NOTICE<<"Constructing osgViewer::View"<<std::endl;
137
138    _startTick = 0;
139
140    _frameStamp = new osg::FrameStamp;
141    _frameStamp->setFrameNumber(0);
142    _frameStamp->setReferenceTime(0);
143    _frameStamp->setSimulationTime(0);
144
145    _scene = new Scene;
146
147    // make sure View is safe to reference multi-threaded.
148    setThreadSafeRefUnref(true);
149
150    // need to attach a Renderer to the master camera which has been default constructed
151    getCamera()->setRenderer(createRenderer(getCamera()));
152
153    setEventQueue(new osgGA::EventQueue);
154
155    setStats(new osg::Stats("View"));
156}
157
158
159View::View(const osgViewer::View& view, const osg::CopyOp& copyop):
160    osg::View(view,copyop),
161    osgGA::GUIActionAdapter(),
162    _startTick(0),
163    _fusionDistanceMode(view._fusionDistanceMode),
164    _fusionDistanceValue(view._fusionDistanceValue)
165{
166    _scene = new Scene;
167
168    // need to attach a Renderer to the master camera which has been default constructed
169    getCamera()->setRenderer(createRenderer(getCamera()));
170
171    setEventQueue(new osgGA::EventQueue);
172
173    setStats(new osg::Stats("View"));
174}
175
176View::~View()
177{
178    OSG_INFO<<"Destructing osgViewer::View"<<std::endl;
179}
180
181void View::take(osg::View& rhs)
182{
183    osg::View::take(rhs);
184
185#if 1
186    osgViewer::View* rhs_osgViewer = dynamic_cast<osgViewer::View*>(&rhs);
187    if (rhs_osgViewer)
188    {
189
190        // copy across rhs
191        _startTick = rhs_osgViewer->_startTick;
192        _frameStamp = rhs_osgViewer->_frameStamp;
193
194        if (rhs_osgViewer->getSceneData())
195        {
196            _scene = rhs_osgViewer->_scene;
197        }
198
199        if (rhs_osgViewer->_cameraManipulator.valid())
200        {
201            _cameraManipulator = rhs_osgViewer->_cameraManipulator;
202        }
203
204        _eventHandlers.insert(_eventHandlers.end(), rhs_osgViewer->_eventHandlers.begin(), rhs_osgViewer->_eventHandlers.end());
205
206        _coordinateSystemNodePath = rhs_osgViewer->_coordinateSystemNodePath;
207
208        _displaySettings = rhs_osgViewer->_displaySettings;
209        _fusionDistanceMode = rhs_osgViewer->_fusionDistanceMode;
210        _fusionDistanceValue = rhs_osgViewer->_fusionDistanceValue;
211
212
213        // clear rhs
214        rhs_osgViewer->_frameStamp = 0;
215        rhs_osgViewer->_scene = 0;
216        rhs_osgViewer->_cameraManipulator = 0;
217        rhs_osgViewer->_eventHandlers.clear();
218
219        rhs_osgViewer->_coordinateSystemNodePath.clearNodePath();
220
221        rhs_osgViewer->_displaySettings = 0;
222    }
223#endif
224    computeActiveCoordinateSystemNodePath();
225    assignSceneDataToCameras();
226}
227
228osg::GraphicsOperation* View::createRenderer(osg::Camera* camera)
229{
230    Renderer* render = new Renderer(camera);
231    camera->setStats(new osg::Stats("Camera"));
232    return render;
233}
234
235
236void View::init()
237{
238    OSG_INFO<<"View::init()"<<std::endl;
239
240    osg::ref_ptr<osgGA::GUIEventAdapter> initEvent = _eventQueue->createEvent();
241    initEvent->setEventType(osgGA::GUIEventAdapter::FRAME);
242
243    if (_cameraManipulator.valid())
244    {
245        _cameraManipulator->init(*initEvent, *this);
246    }
247}
248
249void View::setStartTick(osg::Timer_t tick)
250{
251    _startTick = tick;
252}
253
254void View::setSceneData(osg::Node* node)
255{
256    if (node==_scene->getSceneData()) return;
257
258    osg::ref_ptr<Scene> scene = Scene::getScene(node);
259
260    if (scene)
261    {
262        OSG_INFO<<"View::setSceneData() Sharing scene "<<scene.get()<<std::endl;
263        _scene = scene;
264    }
265    else
266    {
267        if (_scene->referenceCount()!=1)
268        {
269            // we are not the only reference to the Scene so we cannot reuse it.
270            _scene = new Scene;
271            OSG_INFO<<"View::setSceneData() Allocating new scene"<<_scene.get()<<std::endl;
272        }
273        else
274        {
275            OSG_INFO<<"View::setSceneData() Reusing exisitng scene"<<_scene.get()<<std::endl;
276        }
277
278        _scene->setSceneData(node);
279    }
280
281    if (getSceneData())
282    {
283        #if defined(OSG_GLES2_AVAILABLE)
284            osgUtil::ShaderGenVisitor sgv;
285            getSceneData()->getOrCreateStateSet();
286            getSceneData()->accept(sgv);
287        #endif
288       
289        // now make sure the scene graph is set up with the correct DataVariance to protect the dynamic elements of
290        // the scene graph from being run in parallel.
291        osgUtil::Optimizer::StaticObjectDetectionVisitor sodv;
292        getSceneData()->accept(sodv);
293
294        // make sure that existing scene graph objects are allocated with thread safe ref/unref
295        if (getViewerBase() &&
296            getViewerBase()->getThreadingModel()!=ViewerBase::SingleThreaded)
297        {
298            getSceneData()->setThreadSafeRefUnref(true);
299        }
300
301        // update the scene graph so that it has enough GL object buffer memory for the graphics contexts that will be using it.
302        getSceneData()->resizeGLObjectBuffers(osg::DisplaySettings::instance()->getMaxNumberOfGraphicsContexts());
303    }
304
305    computeActiveCoordinateSystemNodePath();
306
307    assignSceneDataToCameras();
308}
309
310void View::setDatabasePager(osgDB::DatabasePager* dp)
311{
312    _scene->setDatabasePager(dp);
313}
314
315osgDB::DatabasePager* View::getDatabasePager()
316{
317    return _scene->getDatabasePager();
318}
319
320const osgDB::DatabasePager* View::getDatabasePager() const
321{
322    return _scene->getDatabasePager();
323}
324
325
326void View::setImagePager(osgDB::ImagePager* dp)
327{
328    _scene->setImagePager(dp);
329}
330
331osgDB::ImagePager* View::getImagePager()
332{
333    return _scene->getImagePager();
334}
335
336const osgDB::ImagePager* View::getImagePager() const
337{
338    return _scene->getImagePager();
339}
340
341
342void View::setCameraManipulator(osgGA::CameraManipulator* manipulator, bool resetPosition)
343{
344    _cameraManipulator = manipulator;
345
346    if (_cameraManipulator.valid())
347    {
348        _cameraManipulator->setCoordinateFrameCallback(new ViewerCoordinateFrameCallback(this));
349
350        if (getSceneData()) _cameraManipulator->setNode(getSceneData());
351
352        if (resetPosition)
353        {
354            osg::ref_ptr<osgGA::GUIEventAdapter> dummyEvent = _eventQueue->createEvent();
355            _cameraManipulator->home(*dummyEvent, *this);
356        }
357    }
358}
359
360void View::home()
361{
362    if (_cameraManipulator.valid())
363    {
364        osg::ref_ptr<osgGA::GUIEventAdapter> dummyEvent = _eventQueue->createEvent();
365        _cameraManipulator->home(*dummyEvent, *this);
366    }
367}
368
369
370void View::addEventHandler(osgGA::GUIEventHandler* eventHandler)
371{
372    EventHandlers::iterator itr = std::find(_eventHandlers.begin(), _eventHandlers.end(), eventHandler);
373    if (itr == _eventHandlers.end())
374    {
375        _eventHandlers.push_back(eventHandler);
376    }
377}
378
379void View::removeEventHandler(osgGA::GUIEventHandler* eventHandler)
380{
381    EventHandlers::iterator itr = std::find(_eventHandlers.begin(), _eventHandlers.end(), eventHandler);
382    if (itr != _eventHandlers.end())
383    {
384        _eventHandlers.erase(itr);
385    }
386}
387
388void View::setCoordinateSystemNodePath(const osg::NodePath& nodePath)
389{
390    _coordinateSystemNodePath.setNodePath(nodePath);
391}
392
393osg::NodePath View::getCoordinateSystemNodePath() const
394{
395    osg::NodePath nodePath;
396    _coordinateSystemNodePath.getNodePath(nodePath);
397    return nodePath;
398}
399
400void View::computeActiveCoordinateSystemNodePath()
401{
402    // now search for CoordinateSystemNode's for which we want to track.
403    osg::Node* subgraph = getSceneData();
404
405    if (subgraph)
406    {
407
408        CollectedCoordinateSystemNodesVisitor ccsnv;
409        subgraph->accept(ccsnv);
410
411        if (!ccsnv._pathToCoordinateSystemNode.empty())
412        {
413           setCoordinateSystemNodePath(ccsnv._pathToCoordinateSystemNode);
414           return;
415        }
416    }
417
418    // otherwise no node path found so reset to empty.
419    setCoordinateSystemNodePath(osg::NodePath());
420}
421
422void View::setUpViewAcrossAllScreens()
423{
424    osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
425    if (!wsi)
426    {
427        OSG_NOTICE<<"View::setUpViewAcrossAllScreens() : Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
428        return;
429    }
430
431    osg::DisplaySettings* ds = _displaySettings.valid() ? _displaySettings.get() : osg::DisplaySettings::instance().get();
432
433    double fovy, aspectRatio, zNear, zFar;
434    _camera->getProjectionMatrixAsPerspective(fovy, aspectRatio, zNear, zFar);
435
436    osg::GraphicsContext::ScreenIdentifier si;
437    si.readDISPLAY();
438
439    // displayNum has not been set so reset it to 0.
440    if (si.displayNum<0) si.displayNum = 0;
441
442    unsigned int numScreens = wsi->getNumScreens(si);
443    if (numScreens==1)
444    {
445        if (si.screenNum<0) si.screenNum = 0;
446
447        unsigned int width, height;
448        wsi->getScreenResolution(si, width, height);
449
450        osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits(ds);
451        traits->hostName = si.hostName;
452        traits->displayNum = si.displayNum;
453        traits->screenNum = si.screenNum;
454        traits->x = 0;
455        traits->y = 0;
456        traits->width = width;
457        traits->height = height;
458        traits->windowDecoration = false;
459        traits->doubleBuffer = true;
460        traits->sharedContext = 0;
461       
462        osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
463
464        _camera->setGraphicsContext(gc.get());
465
466        osgViewer::GraphicsWindow* gw = dynamic_cast<osgViewer::GraphicsWindow*>(gc.get());
467        if (gw)
468        {
469            OSG_INFO<<"  GraphicsWindow has been created successfully."<<std::endl;
470            gw->getEventQueue()->getCurrentEventState()->setWindowRectangle(0, 0, width, height );
471        }
472        else
473        {
474            OSG_NOTICE<<"  GraphicsWindow has not been created successfully."<<std::endl;
475        }
476
477        double newAspectRatio = double(traits->width) / double(traits->height);
478        double aspectRatioChange = newAspectRatio / aspectRatio;
479        if (aspectRatioChange != 1.0)
480        {
481            _camera->getProjectionMatrix() *= osg::Matrix::scale(1.0/aspectRatioChange,1.0,1.0);
482        }
483
484        _camera->setViewport(new osg::Viewport(0, 0, traits->width, traits->height));
485
486        GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
487
488        _camera->setDrawBuffer(buffer);
489        _camera->setReadBuffer(buffer);
490
491    }
492    else
493    {
494
495        double translate_x = 0.0;
496
497        for(unsigned int i=0; i<numScreens; ++i)
498        {
499            si.screenNum = i;
500
501            unsigned int width, height;
502            wsi->getScreenResolution(si, width, height);
503            translate_x += double(width) / (double(height) * aspectRatio);
504        }
505
506        bool stereoSlitScreens = numScreens==2 &&
507                                 ds->getStereoMode()==osg::DisplaySettings::HORIZONTAL_SPLIT &&
508                                 ds->getStereo();
509
510        for(unsigned int i=0; i<numScreens; ++i)
511        {
512            si.screenNum = i;
513
514            unsigned int width, height;
515            wsi->getScreenResolution(si, width, height);
516
517            osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits(ds);
518            traits->hostName = si.hostName;
519            traits->displayNum = si.displayNum;
520            traits->screenNum = si.screenNum;
521            traits->screenNum = i;
522            traits->x = 0;
523            traits->y = 0;
524            traits->width = width;
525            traits->height = height;
526            traits->windowDecoration = false;
527            traits->doubleBuffer = true;
528            traits->sharedContext = 0;
529
530            osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
531
532            osg::ref_ptr<osg::Camera> camera = new osg::Camera;
533            camera->setGraphicsContext(gc.get());
534
535            osgViewer::GraphicsWindow* gw = dynamic_cast<osgViewer::GraphicsWindow*>(gc.get());
536            if (gw)
537            {
538                OSG_INFO<<"  GraphicsWindow has been created successfully."<<gw<<std::endl;
539
540                gw->getEventQueue()->getCurrentEventState()->setWindowRectangle(traits->x, traits->y, traits->width, traits->height );
541            }
542            else
543            {
544                OSG_NOTICE<<"  GraphicsWindow has not been created successfully."<<std::endl;
545            }
546
547            camera->setViewport(new osg::Viewport(0, 0, traits->width, traits->height));
548
549            GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
550            camera->setDrawBuffer(buffer);
551            camera->setReadBuffer(buffer);
552
553            if (stereoSlitScreens)
554            {
555                unsigned int leftCameraNum = (ds->getSplitStereoHorizontalEyeMapping()==osg::DisplaySettings::LEFT_EYE_LEFT_VIEWPORT) ? 0 : 1;
556
557                osg::ref_ptr<osg::DisplaySettings> ds_local = new osg::DisplaySettings(*ds);
558                ds_local->setStereoMode(leftCameraNum==i ? osg::DisplaySettings::LEFT_EYE : osg::DisplaySettings::RIGHT_EYE);
559                camera->setDisplaySettings(ds_local.get());
560
561                addSlave(camera.get(), osg::Matrixd(), osg::Matrixd() );
562            }
563            else
564            {
565                double newAspectRatio = double(traits->width) / double(traits->height);
566                double aspectRatioChange = newAspectRatio / aspectRatio;
567
568                addSlave(camera.get(), osg::Matrixd::translate( translate_x - aspectRatioChange, 0.0, 0.0) * osg::Matrix::scale(1.0/aspectRatioChange,1.0,1.0), osg::Matrixd() );
569                translate_x -= aspectRatioChange * 2.0;
570            }
571        }
572    }
573
574    assignSceneDataToCameras();
575}
576
577void View::setUpViewInWindow(int x, int y, int width, int height, unsigned int screenNum)
578{
579    osg::DisplaySettings* ds = _displaySettings.valid() ? _displaySettings.get() : osg::DisplaySettings::instance().get();
580
581    osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits(ds);
582
583    traits->readDISPLAY();
584    if (traits->displayNum<0) traits->displayNum = 0;
585
586    traits->screenNum = screenNum;
587    traits->x = x;
588    traits->y = y;
589    traits->width = width;
590    traits->height = height;
591    traits->windowDecoration = true;
592    traits->doubleBuffer = true;
593    traits->sharedContext = 0;
594
595    osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
596
597    _camera->setGraphicsContext(gc.get());
598
599    osgViewer::GraphicsWindow* gw = dynamic_cast<osgViewer::GraphicsWindow*>(gc.get());
600    if (gw)
601    {
602        OSG_INFO<<"View::setUpViewOnSingleScreen - GraphicsWindow has been created successfully."<<std::endl;
603        gw->getEventQueue()->getCurrentEventState()->setWindowRectangle(x, y, width, height );
604    }
605    else
606    {
607        OSG_NOTICE<<"  GraphicsWindow has not been created successfully."<<std::endl;
608    }
609
610    double fovy, aspectRatio, zNear, zFar;
611    _camera->getProjectionMatrixAsPerspective(fovy, aspectRatio, zNear, zFar);
612
613    double newAspectRatio = double(traits->width) / double(traits->height);
614    double aspectRatioChange = newAspectRatio / aspectRatio;
615    if (aspectRatioChange != 1.0)
616    {
617        _camera->getProjectionMatrix() *= osg::Matrix::scale(1.0/aspectRatioChange,1.0,1.0);
618    }
619
620    _camera->setViewport(new osg::Viewport(0, 0, traits->width, traits->height));
621
622    GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
623
624    _camera->setDrawBuffer(buffer);
625    _camera->setReadBuffer(buffer);
626}
627
628void View::setUpViewOnSingleScreen(unsigned int screenNum)
629{
630    osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
631    if (!wsi)
632    {
633        OSG_NOTICE<<"View::setUpViewOnSingleScreen() : Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
634        return;
635    }
636
637    osg::DisplaySettings* ds = _displaySettings.valid() ? _displaySettings.get() : osg::DisplaySettings::instance().get();
638
639    osg::GraphicsContext::ScreenIdentifier si;
640    si.readDISPLAY();
641
642    // displayNum has not been set so reset it to 0.
643    if (si.displayNum<0) si.displayNum = 0;
644
645    si.screenNum = screenNum;
646
647    unsigned int width, height;
648    wsi->getScreenResolution(si, width, height);
649
650    osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits(ds);
651    traits->hostName = si.hostName;
652    traits->displayNum = si.displayNum;
653    traits->screenNum = si.screenNum;
654    traits->x = 0;
655    traits->y = 0;
656    traits->width = width;
657    traits->height = height;
658    traits->windowDecoration = false;
659    traits->doubleBuffer = true;
660    traits->sharedContext = 0;
661
662    osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
663
664    _camera->setGraphicsContext(gc.get());
665
666    osgViewer::GraphicsWindow* gw = dynamic_cast<osgViewer::GraphicsWindow*>(gc.get());
667    if (gw)
668    {
669        OSG_INFO<<"View::setUpViewOnSingleScreen - GraphicsWindow has been created successfully."<<std::endl;
670        gw->getEventQueue()->getCurrentEventState()->setWindowRectangle(0, 0, width, height );
671    }
672    else
673    {
674        OSG_NOTICE<<"  GraphicsWindow has not been created successfully."<<std::endl;
675    }
676
677    double fovy, aspectRatio, zNear, zFar;
678    _camera->getProjectionMatrixAsPerspective(fovy, aspectRatio, zNear, zFar);
679
680    double newAspectRatio = double(traits->width) / double(traits->height);
681    double aspectRatioChange = newAspectRatio / aspectRatio;
682    if (aspectRatioChange != 1.0)
683    {
684        _camera->getProjectionMatrix() *= osg::Matrix::scale(1.0/aspectRatioChange,1.0,1.0);
685    }
686
687    _camera->setViewport(new osg::Viewport(0, 0, traits->width, traits->height));
688
689    GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
690
691    _camera->setDrawBuffer(buffer);
692    _camera->setReadBuffer(buffer);
693}
694
695static osg::Geometry* create3DSphericalDisplayDistortionMesh(const osg::Vec3& origin, const osg::Vec3& widthVector, const osg::Vec3& heightVector, double sphere_radius, double collar_radius,osg::Image* intensityMap, const osg::Matrix& projectorMatrix)
696{
697    osg::Vec3d center(0.0,0.0,0.0);
698    osg::Vec3d eye(0.0,0.0,0.0);
699
700    double distance = sqrt(sphere_radius*sphere_radius - collar_radius*collar_radius);
701
702    bool centerProjection = false;
703
704    osg::Vec3d projector = eye - osg::Vec3d(0.0,0.0, distance);
705
706    OSG_INFO<<"create3DSphericalDisplayDistortionMesh : Projector position = "<<projector<<std::endl;
707    OSG_INFO<<"create3DSphericalDisplayDistortionMesh : distance = "<<distance<<std::endl;
708
709
710    // create the quad to visualize.
711    osg::Geometry* geometry = new osg::Geometry();
712
713    geometry->setSupportsDisplayList(false);
714
715    osg::Vec3 xAxis(widthVector);
716    float width = widthVector.length();
717    xAxis /= width;
718
719    osg::Vec3 yAxis(heightVector);
720    float height = heightVector.length();
721    yAxis /= height;
722
723    int noSteps = 50;
724
725    osg::Vec3Array* vertices = new osg::Vec3Array;
726    osg::Vec3Array* texcoords0 = new osg::Vec3Array;
727    osg::Vec2Array* texcoords1 = intensityMap==0 ? new osg::Vec2Array : 0;
728    osg::Vec4Array* colors = new osg::Vec4Array;
729
730    osg::Vec3 bottom = origin;
731    osg::Vec3 dx = xAxis*(width/((float)(noSteps-1)));
732    osg::Vec3 dy = yAxis*(height/((float)(noSteps-1)));
733
734    osg::Vec3d screenCenter = origin + widthVector*0.5f + heightVector*0.5f;
735    float screenRadius = heightVector.length() * 0.5f;
736
737    int i,j;
738
739    if (centerProjection)
740    {
741        for(i=0;i<noSteps;++i)
742        {
743            osg::Vec3 cursor = bottom+dy*(float)i;
744            for(j=0;j<noSteps;++j)
745            {
746                osg::Vec2 delta(cursor.x() - screenCenter.x(), cursor.y() - screenCenter.y());
747                double theta = atan2(-delta.y(), delta.x());
748                double phi = osg::PI_2 * delta.length() / screenRadius;
749                if (phi > osg::PI_2) phi = osg::PI_2;
750
751                phi *= 2.0;
752
753                if (theta<0.0) theta += 2.0*osg::PI;
754
755                // OSG_NOTICE<<"theta = "<<theta<< "phi="<<phi<<std::endl;
756
757                osg::Vec3 texcoord(sin(phi) * cos(theta),
758                                   sin(phi) * sin(theta),
759                                   cos(phi));
760
761                vertices->push_back(cursor);
762                texcoords0->push_back(texcoord * projectorMatrix);
763
764                osg::Vec2 texcoord1(theta/(2.0*osg::PI), 1.0f - phi/osg::PI_2);
765                if (intensityMap)
766                {
767                    colors->push_back(intensityMap->getColor(texcoord1));
768                }
769                else
770                {
771                    colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
772                    if (texcoords1) texcoords1->push_back( texcoord1 );
773                }
774
775                cursor += dx;
776            }
777            // OSG_NOTICE<<std::endl;
778        }
779    }
780    else
781    {
782        for(i=0;i<noSteps;++i)
783        {
784            osg::Vec3 cursor = bottom+dy*(float)i;
785            for(j=0;j<noSteps;++j)
786            {
787                osg::Vec2 delta(cursor.x() - screenCenter.x(), cursor.y() - screenCenter.y());
788                double theta = atan2(-delta.y(), delta.x());
789                double phi = osg::PI_2 * delta.length() / screenRadius;
790                if (phi > osg::PI_2) phi = osg::PI_2;
791                if (theta<0.0) theta += 2.0*osg::PI;
792
793                // OSG_NOTICE<<"theta = "<<theta<< "phi="<<phi<<std::endl;
794
795                double f = distance * sin(phi);
796                double e = distance * cos(phi) + sqrt( sphere_radius*sphere_radius - f*f);
797                double l = e * cos(phi);
798                double h = e * sin(phi);
799                double z = l - distance;
800
801                osg::Vec3 texcoord(h * cos(theta) / sphere_radius,
802                                   h * sin(theta) / sphere_radius,
803                                   z / sphere_radius);
804
805                vertices->push_back(cursor);
806                texcoords0->push_back(texcoord * projectorMatrix);
807
808                osg::Vec2 texcoord1(theta/(2.0*osg::PI), 1.0f - phi/osg::PI_2);
809                if (intensityMap)
810                {
811                    colors->push_back(intensityMap->getColor(texcoord1));
812                }
813                else
814                {
815                    colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
816                    if (texcoords1) texcoords1->push_back( texcoord1 );
817                }
818
819                cursor += dx;
820            }
821            // OSG_NOTICE<<std::endl;
822        }
823    }
824
825    // pass the created vertex array to the points geometry object.
826    geometry->setVertexArray(vertices);
827
828    geometry->setColorArray(colors);
829    geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
830
831    geometry->setTexCoordArray(0,texcoords0);
832    if (texcoords1) geometry->setTexCoordArray(1,texcoords1);
833
834    for(i=0;i<noSteps-1;++i)
835    {
836        osg::DrawElementsUShort* elements = new osg::DrawElementsUShort(osg::PrimitiveSet::QUAD_STRIP);
837        for(j=0;j<noSteps;++j)
838        {
839            elements->push_back(j+(i+1)*noSteps);
840            elements->push_back(j+(i)*noSteps);
841        }
842        geometry->addPrimitiveSet(elements);
843    }
844
845    return geometry;
846}
847
848void View::setUpViewFor3DSphericalDisplay(double radius, double collar, unsigned int screenNum, osg::Image* intensityMap, const osg::Matrixd& projectorMatrix)
849{
850    OSG_INFO<<"View::setUpViewFor3DSphericalDisplay(rad="<<radius<<", cllr="<<collar<<", sn="<<screenNum<<", im="<<intensityMap<<")"<<std::endl;
851    osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
852    if (!wsi)
853    {
854        OSG_NOTICE<<"Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
855        return;
856    }
857
858    osg::GraphicsContext::ScreenIdentifier si;
859    si.readDISPLAY();
860
861    // displayNum has not been set so reset it to 0.
862    if (si.displayNum<0) si.displayNum = 0;
863
864    si.screenNum = screenNum;
865
866    unsigned int width, height;
867    wsi->getScreenResolution(si, width, height);
868
869
870    osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
871    traits->hostName = si.hostName;
872    traits->displayNum = si.displayNum;
873    traits->screenNum = si.screenNum;
874    traits->x = 0;
875    traits->y = 0;
876    traits->width = width;
877    traits->height = height;
878    traits->windowDecoration = false;
879    traits->doubleBuffer = true;
880    traits->sharedContext = 0;
881
882
883    osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
884    if (!gc)
885    {
886        OSG_NOTICE<<"GraphicsWindow has not been created successfully."<<std::endl;
887        return;
888    }
889
890    bool applyIntensityMapAsColours = true;
891
892    int tex_width = 512;
893    int tex_height = 512;
894
895    int camera_width = tex_width;
896    int camera_height = tex_height;
897
898    osg::TextureCubeMap* texture = new osg::TextureCubeMap;
899
900    texture->setTextureSize(tex_width, tex_height);
901    texture->setInternalFormat(GL_RGB);
902    texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
903    texture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
904    texture->setWrap(osg::Texture::WRAP_S,osg::Texture::CLAMP_TO_EDGE);
905    texture->setWrap(osg::Texture::WRAP_T,osg::Texture::CLAMP_TO_EDGE);
906    texture->setWrap(osg::Texture::WRAP_R,osg::Texture::CLAMP_TO_EDGE);
907
908#if 0
909    osg::Camera::RenderTargetImplementation renderTargetImplementation = osg::Camera::SEPERATE_WINDOW;
910    GLenum buffer = GL_FRONT;
911#else
912    osg::Camera::RenderTargetImplementation renderTargetImplementation = osg::Camera::FRAME_BUFFER_OBJECT;
913    GLenum buffer = GL_FRONT;
914#endif
915
916    // front face
917    {
918        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
919        camera->setName("Front face camera");
920        camera->setGraphicsContext(gc.get());
921        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
922        camera->setDrawBuffer(buffer);
923        camera->setReadBuffer(buffer);
924        camera->setAllowEventFocus(false);
925        // tell the camera to use OpenGL frame buffer object where supported.
926        camera->setRenderTargetImplementation(renderTargetImplementation);
927
928        // attach the texture and use it as the color buffer.
929        camera->attach(osg::Camera::COLOR_BUFFER, texture, 0, osg::TextureCubeMap::POSITIVE_Y);
930
931        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd());
932    }
933
934
935    // top face
936    {
937        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
938        camera->setName("Top face camera");
939        camera->setGraphicsContext(gc.get());
940        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
941        camera->setDrawBuffer(buffer);
942        camera->setReadBuffer(buffer);
943        camera->setAllowEventFocus(false);
944
945        // tell the camera to use OpenGL frame buffer object where supported.
946        camera->setRenderTargetImplementation(renderTargetImplementation);
947
948        // attach the texture and use it as the color buffer.
949        camera->attach(osg::Camera::COLOR_BUFFER, texture, 0, osg::TextureCubeMap::POSITIVE_Z);
950
951        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd::rotate(osg::inDegrees(-90.0f), 1.0,0.0,0.0));
952    }
953
954    // left face
955    {
956        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
957        camera->setName("Left face camera");
958        camera->setGraphicsContext(gc.get());
959        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
960        camera->setDrawBuffer(buffer);
961        camera->setReadBuffer(buffer);
962        camera->setAllowEventFocus(false);
963
964        // tell the camera to use OpenGL frame buffer object where supported.
965        camera->setRenderTargetImplementation(renderTargetImplementation);
966
967        // attach the texture and use it as the color buffer.
968        camera->attach(osg::Camera::COLOR_BUFFER, texture, 0, osg::TextureCubeMap::NEGATIVE_X);
969
970        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd::rotate(osg::inDegrees(-90.0f), 0.0,1.0,0.0) * osg::Matrixd::rotate(osg::inDegrees(-90.0f), 0.0,0.0,1.0));
971    }
972
973    // right face
974    {
975        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
976        camera->setName("Right face camera");
977        camera->setGraphicsContext(gc.get());
978        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
979        camera->setDrawBuffer(buffer);
980        camera->setReadBuffer(buffer);
981        camera->setAllowEventFocus(false);
982
983        // tell the camera to use OpenGL frame buffer object where supported.
984        camera->setRenderTargetImplementation(renderTargetImplementation);
985
986        // attach the texture and use it as the color buffer.
987        camera->attach(osg::Camera::COLOR_BUFFER, texture, 0, osg::TextureCubeMap::POSITIVE_X);
988
989        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd::rotate(osg::inDegrees(90.0f), 0.0,1.0,0.0 ) * osg::Matrixd::rotate(osg::inDegrees(90.0f), 0.0,0.0,1.0));
990    }
991
992    // bottom face
993    {
994        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
995        camera->setGraphicsContext(gc.get());
996        camera->setName("Bottom face camera");
997        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
998        camera->setDrawBuffer(buffer);
999        camera->setReadBuffer(buffer);
1000        camera->setAllowEventFocus(false);
1001
1002        // tell the camera to use OpenGL frame buffer object where supported.
1003        camera->setRenderTargetImplementation(renderTargetImplementation);
1004
1005        // attach the texture and use it as the color buffer.
1006        camera->attach(osg::Camera::COLOR_BUFFER, texture, 0, osg::TextureCubeMap::NEGATIVE_Z);
1007
1008        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd::rotate(osg::inDegrees(90.0f), 1.0,0.0,0.0) * osg::Matrixd::rotate(osg::inDegrees(180.0f), 0.0,0.0,1.0));
1009    }
1010
1011    // back face
1012    {
1013        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
1014        camera->setName("Back face camera");
1015        camera->setGraphicsContext(gc.get());
1016        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
1017        camera->setDrawBuffer(buffer);
1018        camera->setReadBuffer(buffer);
1019        camera->setAllowEventFocus(false);
1020
1021        // tell the camera to use OpenGL frame buffer object where supported.
1022        camera->setRenderTargetImplementation(renderTargetImplementation);
1023
1024        // attach the texture and use it as the color buffer.
1025        camera->attach(osg::Camera::COLOR_BUFFER, texture, 0, osg::TextureCubeMap::NEGATIVE_Y);
1026
1027        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd::rotate(osg::inDegrees(180.0f), 1.0,0.0,0.0));
1028    }
1029
1030    getCamera()->setProjectionMatrixAsPerspective(90.0f, 1.0, 1, 1000.0);
1031
1032    // distortion correction set up.
1033    {
1034        osg::Geode* geode = new osg::Geode();
1035        geode->addDrawable(create3DSphericalDisplayDistortionMesh(osg::Vec3(0.0f,0.0f,0.0f), osg::Vec3(width,0.0f,0.0f), osg::Vec3(0.0f,height,0.0f), radius, collar, applyIntensityMapAsColours ? intensityMap : 0, projectorMatrix));
1036
1037        // new we need to add the texture to the mesh, we do so by creating a
1038        // StateSet to contain the Texture StateAttribute.
1039        osg::StateSet* stateset = geode->getOrCreateStateSet();
1040        stateset->setTextureAttributeAndModes(0, texture,osg::StateAttribute::ON);
1041        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
1042
1043        if (!applyIntensityMapAsColours && intensityMap)
1044        {
1045            stateset->setTextureAttributeAndModes(1, new osg::Texture2D(intensityMap), osg::StateAttribute::ON);
1046        }
1047
1048        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
1049        camera->setGraphicsContext(gc.get());
1050        camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
1051        camera->setClearColor( osg::Vec4(0.0,0.0,0.0,1.0) );
1052        camera->setViewport(new osg::Viewport(0, 0, width, height));
1053        GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
1054        camera->setDrawBuffer(buffer);
1055        camera->setReadBuffer(buffer);
1056        camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF);
1057        camera->setAllowEventFocus(false);
1058        camera->setInheritanceMask(camera->getInheritanceMask() & ~osg::CullSettings::CLEAR_COLOR & ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE);
1059        //camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1060
1061        camera->setProjectionMatrixAsOrtho2D(0,width,0,height);
1062        camera->setViewMatrix(osg::Matrix::identity());
1063
1064        // add subgraph to render
1065        camera->addChild(geode);
1066
1067        camera->setName("DistortionCorrectionCamera");
1068
1069        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd(), false);
1070    }
1071
1072    getCamera()->setNearFarRatio(0.0001f);
1073
1074    if (getLightingMode()==osg::View::HEADLIGHT)
1075    {
1076        // set a local light source for headlight to ensure that lighting is consistent across sides of cube.
1077        getLight()->setPosition(osg::Vec4(0.0f,0.0f,0.0f,1.0f));
1078    }
1079}
1080
1081static osg::Geometry* createParoramicSphericalDisplayDistortionMesh(const osg::Vec3& origin, const osg::Vec3& widthVector, const osg::Vec3& heightVector, double sphere_radius, double collar_radius, osg::Image* intensityMap, const osg::Matrix& projectorMatrix)
1082{
1083    osg::Vec3d center(0.0,0.0,0.0);
1084    osg::Vec3d eye(0.0,0.0,0.0);
1085
1086    double distance = sqrt(sphere_radius*sphere_radius - collar_radius*collar_radius);
1087    bool flip = false;
1088    bool texcoord_flip = false;
1089
1090    osg::Vec3d projector = eye - osg::Vec3d(0.0,0.0, distance);
1091
1092
1093    OSG_INFO<<"createParoramicSphericalDisplayDistortionMesh : Projector position = "<<projector<<std::endl;
1094    OSG_INFO<<"createParoramicSphericalDisplayDistortionMesh : distance = "<<distance<<std::endl;
1095
1096    // create the quad to visualize.
1097    osg::Geometry* geometry = new osg::Geometry();
1098
1099    geometry->setSupportsDisplayList(false);
1100
1101    osg::Vec3 xAxis(widthVector);
1102    float width = widthVector.length();
1103    xAxis /= width;
1104
1105    osg::Vec3 yAxis(heightVector);
1106    float height = heightVector.length();
1107    yAxis /= height;
1108
1109    int noSteps = 160;
1110
1111    osg::Vec3Array* vertices = new osg::Vec3Array;
1112    osg::Vec2Array* texcoords0 = new osg::Vec2Array;
1113    osg::Vec2Array* texcoords1 = intensityMap==0 ? new osg::Vec2Array : 0;
1114    osg::Vec4Array* colors = new osg::Vec4Array;
1115
1116    osg::Vec3 top = origin + yAxis*height;
1117
1118    osg::Vec3 screenCenter = origin + widthVector*0.5f + heightVector*0.5f;
1119    float screenRadius = heightVector.length() * 0.5f;
1120
1121    geometry->getOrCreateStateSet()->setMode(GL_CULL_FACE, osg::StateAttribute::OFF | osg::StateAttribute::PROTECTED);
1122
1123    for(int i=0;i<noSteps;++i)
1124    {
1125        for(int j=0;j<noSteps;++j)
1126        {
1127            osg::Vec2 texcoord(double(i)/double(noSteps-1), double(j)/double(noSteps-1));
1128            double theta = texcoord.x() * 2.0 * osg::PI;
1129            double phi = (1.0-texcoord.y()) * osg::PI;
1130
1131            if (texcoord_flip) texcoord.y() = 1.0f - texcoord.y();
1132
1133            osg::Vec3 pos(sin(phi)*sin(theta), sin(phi)*cos(theta), cos(phi));
1134            pos = pos*projectorMatrix;
1135
1136            double alpha = atan2(pos.x(), pos.y());
1137            if (alpha<0.0) alpha += 2.0*osg::PI;
1138
1139            double beta = atan2(sqrt(pos.x()*pos.x() + pos.y()*pos.y()), pos.z());
1140            if (beta<0.0) beta += 2.0*osg::PI;
1141
1142            double gamma = atan2(sqrt(double(pos.x()*pos.x() + pos.y()*pos.y())), double(pos.z()+distance));
1143            if (gamma<0.0) gamma += 2.0*osg::PI;
1144
1145
1146            osg::Vec3 v = screenCenter + osg::Vec3(sin(alpha)*gamma*2.0/osg::PI, -cos(alpha)*gamma*2.0/osg::PI, 0.0f)*screenRadius;
1147
1148            if (flip)
1149                vertices->push_back(osg::Vec3(v.x(), top.y()-(v.y()-origin.y()),v.z()));
1150            else
1151                vertices->push_back(v);
1152
1153            texcoords0->push_back( texcoord );
1154
1155            osg::Vec2 texcoord1(alpha/(2.0*osg::PI), 1.0f - beta/osg::PI);
1156            if (intensityMap)
1157            {
1158                colors->push_back(intensityMap->getColor(texcoord1));
1159            }
1160            else
1161            {
1162                colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
1163                if (texcoords1) texcoords1->push_back( texcoord1 );
1164            }
1165
1166
1167        }
1168    }
1169
1170
1171    // pass the created vertex array to the points geometry object.
1172    geometry->setVertexArray(vertices);
1173
1174    geometry->setColorArray(colors);
1175    geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
1176
1177    geometry->setTexCoordArray(0,texcoords0);
1178    if (texcoords1) geometry->setTexCoordArray(1,texcoords1);
1179
1180    osg::DrawElementsUShort* elements = new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLES);
1181    geometry->addPrimitiveSet(elements);
1182
1183    for(int i=0;i<noSteps-1;++i)
1184    {
1185        for(int j=0;j<noSteps-1;++j)
1186        {
1187            int i1 = j+(i+1)*noSteps;
1188            int i2 = j+(i)*noSteps;
1189            int i3 = j+1+(i)*noSteps;
1190            int i4 = j+1+(i+1)*noSteps;
1191
1192            osg::Vec3& v1 = (*vertices)[i1];
1193            osg::Vec3& v2 = (*vertices)[i2];
1194            osg::Vec3& v3 = (*vertices)[i3];
1195            osg::Vec3& v4 = (*vertices)[i4];
1196
1197            if ((v1-screenCenter).length()>screenRadius) continue;
1198            if ((v2-screenCenter).length()>screenRadius) continue;
1199            if ((v3-screenCenter).length()>screenRadius) continue;
1200            if ((v4-screenCenter).length()>screenRadius) continue;
1201
1202            elements->push_back(i1);
1203            elements->push_back(i2);
1204            elements->push_back(i3);
1205
1206            elements->push_back(i1);
1207            elements->push_back(i3);
1208            elements->push_back(i4);
1209        }
1210    }
1211
1212    return geometry;
1213}
1214
1215void View::setUpViewForPanoramicSphericalDisplay(double radius, double collar, unsigned int screenNum, osg::Image* intensityMap, const osg::Matrixd& projectorMatrix)
1216{
1217    OSG_INFO<<"View::setUpViewForPanoramicSphericalDisplay(rad="<<radius<<", cllr="<<collar<<", sn="<<screenNum<<", im="<<intensityMap<<")"<<std::endl;
1218
1219    osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
1220    if (!wsi)
1221    {
1222        OSG_NOTICE<<"Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
1223        return;
1224    }
1225
1226    osg::GraphicsContext::ScreenIdentifier si;
1227    si.readDISPLAY();
1228
1229    // displayNum has not been set so reset it to 0.
1230    if (si.displayNum<0) si.displayNum = 0;
1231
1232    si.screenNum = screenNum;
1233
1234    unsigned int width, height;
1235    wsi->getScreenResolution(si, width, height);
1236
1237    osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
1238    traits->hostName = si.hostName;
1239    traits->displayNum = si.displayNum;
1240    traits->screenNum = si.screenNum;
1241    traits->x = 0;
1242    traits->y = 0;
1243    traits->width = width;
1244    traits->height = height;
1245    traits->windowDecoration = false;
1246    traits->doubleBuffer = true;
1247    traits->sharedContext = 0;
1248
1249
1250    bool applyIntensityMapAsColours = true;
1251
1252    osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
1253    if (!gc)
1254    {
1255        OSG_NOTICE<<"GraphicsWindow has not been created successfully."<<std::endl;
1256        return;
1257    }
1258
1259    int tex_width = width;
1260    int tex_height = height;
1261
1262    int camera_width = tex_width;
1263    int camera_height = tex_height;
1264
1265    osg::TextureRectangle* texture = new osg::TextureRectangle;
1266
1267    texture->setTextureSize(tex_width, tex_height);
1268    texture->setInternalFormat(GL_RGB);
1269    texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
1270    texture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
1271    texture->setWrap(osg::Texture::WRAP_S,osg::Texture::CLAMP_TO_EDGE);
1272    texture->setWrap(osg::Texture::WRAP_T,osg::Texture::CLAMP_TO_EDGE);
1273
1274#if 0
1275    osg::Camera::RenderTargetImplementation renderTargetImplementation = osg::Camera::SEPERATE_WINDOW;
1276    GLenum buffer = GL_FRONT;
1277#else
1278    osg::Camera::RenderTargetImplementation renderTargetImplementation = osg::Camera::FRAME_BUFFER_OBJECT;
1279    GLenum buffer = GL_FRONT;
1280#endif
1281
1282    // front face
1283    {
1284        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
1285        camera->setName("Front face camera");
1286        camera->setGraphicsContext(gc.get());
1287        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
1288        camera->setDrawBuffer(buffer);
1289        camera->setReadBuffer(buffer);
1290        camera->setAllowEventFocus(false);
1291        // tell the camera to use OpenGL frame buffer object where supported.
1292        camera->setRenderTargetImplementation(renderTargetImplementation);
1293
1294        // attach the texture and use it as the color buffer.
1295        camera->attach(osg::Camera::COLOR_BUFFER, texture);
1296
1297        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd());
1298    }
1299
1300    // distortion correction set up.
1301    {
1302        osg::Geode* geode = new osg::Geode();
1303        geode->addDrawable(createParoramicSphericalDisplayDistortionMesh(osg::Vec3(0.0f,0.0f,0.0f), osg::Vec3(width,0.0f,0.0f), osg::Vec3(0.0f,height,0.0f), radius, collar, applyIntensityMapAsColours ? intensityMap : 0, projectorMatrix));
1304
1305        // new we need to add the texture to the mesh, we do so by creating a
1306        // StateSet to contain the Texture StateAttribute.
1307        osg::StateSet* stateset = geode->getOrCreateStateSet();
1308        stateset->setTextureAttributeAndModes(0, texture,osg::StateAttribute::ON);
1309        stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
1310
1311        osg::TexMat* texmat = new osg::TexMat;
1312        texmat->setScaleByTextureRectangleSize(true);
1313        stateset->setTextureAttributeAndModes(0, texmat, osg::StateAttribute::ON);
1314
1315        if (!applyIntensityMapAsColours && intensityMap)
1316        {
1317            stateset->setTextureAttributeAndModes(1, new osg::Texture2D(intensityMap), osg::StateAttribute::ON);
1318        }
1319
1320        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
1321        camera->setGraphicsContext(gc.get());
1322        camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
1323        camera->setClearColor( osg::Vec4(0.0,0.0,0.0,1.0) );
1324        camera->setViewport(new osg::Viewport(0, 0, width, height));
1325        GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
1326        camera->setDrawBuffer(buffer);
1327        camera->setReadBuffer(buffer);
1328        camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF);
1329        camera->setAllowEventFocus(false);
1330        camera->setInheritanceMask(camera->getInheritanceMask() & ~osg::CullSettings::CLEAR_COLOR & ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE);
1331        //camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1332
1333        camera->setProjectionMatrixAsOrtho2D(0,width,0,height);
1334        camera->setViewMatrix(osg::Matrix::identity());
1335
1336        // add subgraph to render
1337        camera->addChild(geode);
1338
1339        camera->setName("DistortionCorrectionCamera");
1340
1341        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd(), false);
1342    }
1343}
1344
1345void View::setUpViewForWoWVxDisplay(unsigned int screenNum, unsigned char wow_content, unsigned char wow_factor, unsigned char wow_offset, float wow_disparity_Zd, float wow_disparity_vz, float wow_disparity_M, float wow_disparity_C)
1346{
1347    OSG_INFO<<"View::setUpViewForWoWVxDisplay(...)"<<std::endl;
1348
1349    osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
1350    if (!wsi)
1351    {
1352        OSG_NOTICE<<"Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
1353        return;
1354    }
1355
1356    osg::GraphicsContext::ScreenIdentifier si;
1357    si.readDISPLAY();
1358
1359    // displayNum has not been set so reset it to 0.
1360    if (si.displayNum<0) si.displayNum = 0;
1361
1362    si.screenNum = screenNum;
1363
1364    unsigned int width, height;
1365    wsi->getScreenResolution(si, width, height);
1366
1367    osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
1368    traits->hostName = si.hostName;
1369    traits->displayNum = si.displayNum;
1370    traits->screenNum = si.screenNum;
1371    traits->x = 0;
1372    traits->y = 0;
1373    traits->width = width;
1374    traits->height = height;
1375    traits->windowDecoration = false;
1376    traits->doubleBuffer = true;
1377    traits->sharedContext = 0;
1378
1379
1380    osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
1381    if (!gc)
1382    {
1383        OSG_NOTICE<<"GraphicsWindow has not been created successfully."<<std::endl;
1384        return;
1385    }
1386
1387    int tex_width = width;
1388    int tex_height = height;
1389
1390    int camera_width = tex_width;
1391    int camera_height = tex_height;
1392
1393    osg::Texture2D* texture = new osg::Texture2D;
1394    texture->setTextureSize(tex_width, tex_height);
1395    texture->setInternalFormat(GL_RGB);
1396    texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
1397    texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
1398
1399    osg::Texture2D* textureD = new osg::Texture2D;
1400    textureD->setTextureSize(tex_width, tex_height);
1401    textureD->setInternalFormat(GL_DEPTH_COMPONENT);
1402    textureD->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
1403    textureD->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
1404
1405#if 0
1406    osg::Camera::RenderTargetImplementation renderTargetImplementation = osg::Camera::SEPERATE_WINDOW;
1407    GLenum buffer = GL_FRONT;
1408#else
1409    osg::Camera::RenderTargetImplementation renderTargetImplementation = osg::Camera::FRAME_BUFFER_OBJECT;
1410    GLenum buffer = GL_FRONT;
1411#endif
1412
1413    // front face
1414    {
1415        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
1416        camera->setName("Front face camera");
1417        camera->setGraphicsContext(gc.get());
1418        camera->setViewport(new osg::Viewport(0,0,camera_width, camera_height));
1419        camera->setDrawBuffer(buffer);
1420        camera->setReadBuffer(buffer);
1421        camera->setAllowEventFocus(false);
1422        // tell the camera to use OpenGL frame buffer object where supported.
1423        camera->setRenderTargetImplementation(renderTargetImplementation);
1424
1425        // attach the texture and use it as the color buffer.
1426        camera->attach(osg::Camera::COLOR_BUFFER, texture);
1427        camera->attach(osg::Camera::DEPTH_BUFFER, textureD);
1428
1429        addSlave(camera.get(), osg::Matrixd(), osg::Matrixd());
1430    }
1431
1432    // WoW display set up.
1433    {
1434        osg::Texture1D *textureHeader = new osg::Texture1D();
1435        // Set up the header
1436        {
1437            unsigned char header[]= {0xF1,wow_content,wow_factor,wow_offset,0x00,0x00,0x00,0x00,0x00,0x00};
1438            // Calc the CRC32
1439            {
1440                unsigned long _register = 0;
1441                for(int i = 0; i < 10; ++i) {
1442                    unsigned char mask = 0x80;
1443                    unsigned char byte = header[i];
1444                    for (int j = 0; j < 8; ++j)
1445                    {
1446                        bool topBit = (_register & 0x80000000) != 0;
1447                        _register <<= 1;
1448                        _register ^= ((byte & mask) != 0? 0x1: 0x0);
1449                        if (topBit)
1450                        {
1451                            _register ^= 0x04c11db7;
1452                        }
1453                        mask >>= 1;
1454                    }
1455                }
1456                unsigned char *p = (unsigned char*) &_register;
1457                for(size_t i = 0; i < 4; ++i)
1458                {
1459                    header[i+6] = p[3-i];
1460                }
1461            }
1462
1463            osg::ref_ptr<osg::Image> imageheader = new osg::Image();
1464            imageheader->allocateImage(256,1,1,GL_LUMINANCE,GL_UNSIGNED_BYTE);
1465            {
1466                unsigned char *cheader = imageheader->data();
1467                for (int x=0; x<256; ++x){
1468                    cheader[x] = 0;
1469                }
1470                for (int x=0; x<=9; ++x){
1471                    for (int y=7; y>=0; --y){
1472                        int i = 2*(7-y)+16*x;
1473                        cheader[i] = (((1<<(y))&(header[x])) << (7-(y)));
1474                    }
1475                }
1476            }
1477            textureHeader->setImage(imageheader.get());
1478        }
1479
1480        // Create the Screen Aligned Quad
1481        osg::Geode* geode = new osg::Geode();
1482        {
1483            osg::Geometry* geom = new osg::Geometry;
1484
1485            osg::Vec3Array* vertices = new osg::Vec3Array;
1486            vertices->push_back(osg::Vec3(0,height,0));
1487            vertices->push_back(osg::Vec3(0,0,0));
1488            vertices->push_back(osg::Vec3(width,0,0));
1489            vertices->push_back(osg::Vec3(width,height,0));
1490            geom->setVertexArray(vertices);
1491
1492            osg::Vec2Array* tex = new osg::Vec2Array;
1493            tex->push_back(osg::Vec2(0,1));
1494            tex->push_back(osg::Vec2(0,0));
1495            tex->push_back(osg::Vec2(1,0));
1496            tex->push_back(osg::Vec2(1,1));
1497            geom->setTexCoordArray(0,tex);
1498
1499            geom->addPrimitiveSet(new osg::DrawArrays(GL_QUADS,0,4));
1500            geode->addDrawable(geom);
1501
1502            // new we need to add the textures to the quad, and setting up the shader.
1503            osg::StateSet* stateset = geode->getOrCreateStateSet();
1504            stateset->setTextureAttributeAndModes(0, textureHeader,osg::StateAttribute::ON);
1505            stateset->setTextureAttributeAndModes(1, texture,osg::StateAttribute::ON);
1506            stateset->setTextureAttributeAndModes(2, textureD,osg::StateAttribute::ON);
1507            stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
1508
1509            osg::ref_ptr<osg::Program> programShader = new osg::Program();
1510            stateset->setAttribute(programShader.get(), osg::StateAttribute::ON);
1511            stateset->addUniform( new osg::Uniform("wow_width", (int)width));
1512            stateset->addUniform( new osg::Uniform("wow_height", (int)height));
1513            stateset->addUniform( new osg::Uniform("wow_disparity_M", wow_disparity_M));
1514            stateset->addUniform( new osg::Uniform("wow_disparity_Zd", wow_disparity_Zd));
1515            stateset->addUniform( new osg::Uniform("wow_disparity_vz", wow_disparity_vz));
1516            stateset->addUniform( new osg::Uniform("wow_disparity_C", wow_disparity_C));
1517
1518            stateset->addUniform(new osg::Uniform("wow_header", 0));
1519            stateset->addUniform(new osg::Uniform("wow_tcolor", 1));
1520            stateset->addUniform(new osg::Uniform("wow_tdepth", 2));
1521
1522            osg::Shader *frag = new osg::Shader(osg::Shader::FRAGMENT);
1523            frag->setShaderSource(" "\
1524                    " uniform sampler1D wow_header;                                                                                   " \
1525                    " uniform sampler2D wow_tcolor;                                                                                   " \
1526                    " uniform sampler2D wow_tdepth;                                                                                   " \
1527                    "                                                                                                                 " \
1528                    " uniform int wow_width;                                                                                          " \
1529                    " uniform int wow_height;                                                                                         " \
1530                    " uniform float wow_disparity_M;                                                                                  " \
1531                    " uniform float wow_disparity_Zd;                                                                                 " \
1532                    " uniform float wow_disparity_vz;                                                                                 " \
1533                    " uniform float wow_disparity_C;                                                                                  " \
1534                    "                                                                                                                 " \
1535                    " float disparity(float Z)                                                                                        " \
1536                    " {                                                                                                               " \
1537                    "     return (wow_disparity_M*(1.0-(wow_disparity_vz/(Z-wow_disparity_Zd+wow_disparity_vz)))                        " \
1538                    "                   + wow_disparity_C) / 255.0;                                                                   " \
1539                    " }                                                                                                               " \
1540                    "                                                                                                                 " \
1541                    " void main()                                                                                                     " \
1542                    " {                                                                                                               " \
1543                    "       vec2 pos = (gl_FragCoord.xy / vec2(wow_width/2,wow_height) );                                             " \
1544                    "         if (gl_FragCoord.x > float(wow_width/2))                                                                  " \
1545                    "         {                                                                                                         " \
1546                    "             gl_FragColor = vec4(disparity(( texture2D(wow_tdepth, pos - vec2(1,0))).z));                          " \
1547                    "         }                                                                                                         " \
1548                    "         else{                                                                                                     " \
1549                    "             gl_FragColor = texture2D(wow_tcolor, pos);                                                            " \
1550                    "         }                                                                                                         " \
1551                    "     if ( (gl_FragCoord.y >= float(wow_height-1)) && (gl_FragCoord.x < 256.0) )                                    " \
1552                    "     {                                                                                                             " \
1553                    "         float pos = gl_FragCoord.x/256.0;                                                                         " \
1554                    "         float blue = texture1D(wow_header, pos).b;                                                                " \
1555                    "         if ( blue < 0.5)                                                                                          " \
1556                    "             gl_FragColor.b = 0.0;                                                                                 " \
1557                    "         else                                                                                                      " \
1558                    "             gl_FragColor.b = 1.0;                                                                                 " \
1559                    "     }                                                                                                             " \
1560                    " }                                                                                                               " );
1561
1562            programShader->addShader(frag);
1563        }
1564
1565        // Create the Camera
1566        {
1567            osg::ref_ptr<osg::Camera> camera = new osg::Camera;
1568            camera->setGraphicsContext(gc.get());
1569            camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
1570            camera->setClearColor( osg::Vec4(0.0,0.0,0.0,1.0) );
1571            camera->setViewport(new osg::Viewport(0, 0, width, height));
1572            GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
1573            camera->setDrawBuffer(buffer);
1574            camera->setReadBuffer(buffer);
1575            camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF);
1576            camera->setAllowEventFocus(false);
1577            camera->setInheritanceMask(camera->getInheritanceMask() & ~osg::CullSettings::CLEAR_COLOR & ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE);
1578            //camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1579
1580            camera->setProjectionMatrixAsOrtho2D(0,width,0,height);
1581            camera->setViewMatrix(osg::Matrix::identity());
1582
1583            // add subgraph to render
1584            camera->addChild(geode);
1585
1586            camera->setName("WoWCamera");
1587
1588            addSlave(camera.get(), osg::Matrixd(), osg::Matrixd(), false);
1589        }
1590    }
1591}
1592
1593DepthPartitionSettings::DepthPartitionSettings(DepthMode mode):
1594    _mode(mode),
1595    _zNear(1.0), _zMid(5.0), _zFar(1000.0)
1596{}
1597
1598bool DepthPartitionSettings::getDepthRange(osg::View& view, unsigned int partition, double& zNear, double& zFar)
1599{
1600    switch(_mode)
1601    {
1602        case(FIXED_RANGE):
1603        {
1604            if (partition==0)
1605            {
1606                zNear = _zNear;
1607                zFar = _zMid;
1608                return true;
1609            }
1610            else if (partition==1)
1611            {
1612                zNear = _zMid;
1613                zFar = _zFar;
1614                return true;
1615            }
1616            return false;
1617        }
1618        case(BOUNDING_VOLUME):
1619        {
1620            osgViewer::View* view_withSceneData = dynamic_cast<osgViewer::View*>(&view);
1621            const osg::Node* node = view_withSceneData ? view_withSceneData->getSceneData() : 0;
1622            if (!node) return false;
1623
1624            const osg::Camera* masterCamera = view.getCamera();
1625            if (!masterCamera) return false;
1626
1627            osg::BoundingSphere bs = node->getBound();
1628            const osg::Matrixd& viewMatrix = masterCamera->getViewMatrix();
1629            //osg::Matrixd& projectionMatrix = masterCamera->getProjectionMatrix();
1630
1631            osg::Vec3d lookVectorInWorldCoords = osg::Matrixd::transform3x3(viewMatrix,osg::Vec3d(0.0,0.0,-1.0));
1632            lookVectorInWorldCoords.normalize();
1633
1634            osg::Vec3d nearPointInWorldCoords = bs.center() - lookVectorInWorldCoords*bs.radius();
1635            osg::Vec3d farPointInWorldCoords = bs.center() + lookVectorInWorldCoords*bs.radius();
1636
1637            osg::Vec3d nearPointInEyeCoords = nearPointInWorldCoords * viewMatrix;
1638            osg::Vec3d farPointInEyeCoords = farPointInWorldCoords * viewMatrix;
1639
1640#if 0
1641            OSG_NOTICE<<std::endl;
1642            OSG_NOTICE<<"viewMatrix = "<<viewMatrix<<std::endl;
1643            OSG_NOTICE<<"lookVectorInWorldCoords = "<<lookVectorInWorldCoords<<std::endl;
1644            OSG_NOTICE<<"nearPointInWorldCoords = "<<nearPointInWorldCoords<<std::endl;
1645            OSG_NOTICE<<"farPointInWorldCoords = "<<farPointInWorldCoords<<std::endl;
1646            OSG_NOTICE<<"nearPointInEyeCoords = "<<nearPointInEyeCoords<<std::endl;
1647            OSG_NOTICE<<"farPointInEyeCoords = "<<farPointInEyeCoords<<std::endl;
1648#endif
1649            double minZNearRatio = 0.00001;
1650
1651
1652            if (masterCamera->getDisplaySettings())
1653            {
1654                OSG_NOTICE<<"Has display settings"<<std::endl;
1655            }
1656
1657            double scene_zNear = -nearPointInEyeCoords.z();
1658            double scene_zFar = -farPointInEyeCoords.z();
1659            if (scene_zNear<=0.0) scene_zNear = minZNearRatio * scene_zFar;
1660
1661            double scene_zMid = sqrt(scene_zFar*scene_zNear);
1662
1663#if 0
1664            OSG_NOTICE<<"scene_zNear = "<<scene_zNear<<std::endl;
1665            OSG_NOTICE<<"scene_zMid = "<<scene_zMid<<std::endl;
1666            OSG_NOTICE<<"scene_zFar = "<<scene_zFar<<std::endl;
1667#endif
1668            if (partition==0)
1669            {
1670                zNear = scene_zNear;
1671                zFar = scene_zMid;
1672                return true;
1673            }
1674            else if (partition==1)
1675            {
1676                zNear = scene_zMid;
1677                zFar = scene_zFar;
1678                return true;
1679            }
1680
1681            return false;
1682        }
1683        default: return false;
1684    }
1685}
1686
1687namespace osgDepthPartition {
1688
1689struct MyUpdateSlaveCallback : public osg::View::Slave::UpdateSlaveCallback
1690{
1691    MyUpdateSlaveCallback(DepthPartitionSettings* dps, unsigned int partition):_dps(dps), _partition(partition) {}
1692
1693    virtual void updateSlave(osg::View& view, osg::View::Slave& slave)
1694    {
1695        slave.updateSlaveImplementation(view);
1696
1697        if (!_dps) return;
1698
1699        osg::Camera* camera = slave._camera.get();
1700
1701        double computed_zNear;
1702        double computed_zFar;
1703        if (!_dps->getDepthRange(view, _partition, computed_zNear, computed_zFar))
1704        {
1705            OSG_NOTICE<<"Switching off Camera "<<camera<<std::endl;
1706            camera->setNodeMask(0x0);
1707            return;
1708        }
1709        else
1710        {
1711            camera->setNodeMask(0xffffff);
1712        }
1713
1714        if (camera->getProjectionMatrix()(0,3)==0.0 &&
1715            camera->getProjectionMatrix()(1,3)==0.0 &&
1716            camera->getProjectionMatrix()(2,3)==0.0)
1717        {
1718            double left, right, bottom, top, zNear, zFar;
1719            camera->getProjectionMatrixAsOrtho(left, right, bottom, top, zNear, zFar);
1720            camera->setProjectionMatrixAsOrtho(left, right, bottom, top, computed_zNear, computed_zFar);
1721        }
1722        else
1723        {
1724            double left, right, bottom, top, zNear, zFar;
1725            camera->getProjectionMatrixAsFrustum(left, right, bottom, top, zNear, zFar);
1726
1727            double nr = computed_zNear / zNear;
1728            camera->setProjectionMatrixAsFrustum(left * nr, right * nr, bottom * nr, top * nr, computed_zNear, computed_zFar);
1729        }
1730    }
1731
1732    osg::ref_ptr<DepthPartitionSettings> _dps;
1733    unsigned int _partition;
1734};
1735
1736
1737typedef std::list< osg::ref_ptr<osg::Camera> > Cameras;
1738
1739Cameras getActiveCameras(osg::View& view)
1740{
1741    Cameras activeCameras;
1742
1743    if (view.getCamera() && view.getCamera()->getGraphicsContext())
1744    {
1745        activeCameras.push_back(view.getCamera());
1746    }
1747
1748    for(unsigned int i=0; i<view.getNumSlaves(); ++i)
1749    {
1750        osg::View::Slave& slave = view.getSlave(i);
1751        if (slave._camera.valid() && slave._camera->getGraphicsContext())
1752        {
1753            activeCameras.push_back(slave._camera.get());
1754        }
1755    }
1756    return activeCameras;
1757}
1758
1759}
1760
1761bool View::setUpDepthPartitionForCamera(osg::Camera* cameraToPartition, DepthPartitionSettings* incomming_dps)
1762{
1763    osg::ref_ptr<osg::GraphicsContext> context = cameraToPartition->getGraphicsContext();
1764    if (!context) return false;
1765
1766    osg::ref_ptr<osg::Viewport> viewport = cameraToPartition->getViewport();
1767    if (!viewport) return false;
1768
1769    osg::ref_ptr<DepthPartitionSettings> dps = incomming_dps;
1770    if (!dps) dps = new DepthPartitionSettings;
1771
1772    bool useMastersSceneData = true;
1773    osg::Matrixd projectionOffset;
1774    osg::Matrixd viewOffset;
1775
1776    if (getCamera()==cameraToPartition)
1777    {
1778        // replace main camera with depth partition cameras
1779        OSG_INFO<<"View::setUpDepthPartitionForCamera(..) Replacing main Camera"<<std::endl;
1780    }
1781    else
1782    {
1783        unsigned int i = findSlaveIndexForCamera(cameraToPartition);
1784        if (i>=getNumSlaves()) return false;
1785
1786        osg::View::Slave& slave = getSlave(i);
1787
1788        useMastersSceneData = slave._useMastersSceneData;
1789        projectionOffset = slave._projectionOffset;
1790        viewOffset = slave._viewOffset;
1791
1792        OSG_NOTICE<<"View::setUpDepthPartitionForCamera(..) Replacing slave Camera"<<i<<std::endl;
1793        removeSlave(i);
1794    }
1795
1796    cameraToPartition->setGraphicsContext(0);
1797    cameraToPartition->setViewport(0);
1798
1799    // far camera
1800    {
1801        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
1802        camera->setGraphicsContext(context.get());
1803        camera->setViewport(viewport.get());
1804
1805        camera->setDrawBuffer(cameraToPartition->getDrawBuffer());
1806        camera->setReadBuffer(cameraToPartition->getReadBuffer());
1807
1808        camera->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
1809        camera->setCullingMode(osg::Camera::ENABLE_ALL_CULLING);
1810
1811        addSlave(camera.get());
1812
1813        osg::View::Slave& slave = getSlave(getNumSlaves()-1);
1814
1815        slave._useMastersSceneData = useMastersSceneData;
1816        slave._projectionOffset = projectionOffset;
1817        slave._viewOffset = viewOffset;
1818        slave._updateSlaveCallback =  new osgDepthPartition::MyUpdateSlaveCallback(dps.get(), 1);
1819    }
1820
1821    // near camera
1822    {
1823        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
1824        camera->setGraphicsContext(context.get());
1825        camera->setViewport(viewport.get());
1826
1827        camera->setDrawBuffer(cameraToPartition->getDrawBuffer());
1828        camera->setReadBuffer(cameraToPartition->getReadBuffer());
1829
1830        camera->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
1831        camera->setCullingMode(osg::Camera::ENABLE_ALL_CULLING);
1832        camera->setClearMask(GL_DEPTH_BUFFER_BIT);
1833
1834        addSlave(camera.get());
1835
1836        osg::View::Slave& slave = getSlave(getNumSlaves()-1);
1837        slave._useMastersSceneData = useMastersSceneData;
1838        slave._projectionOffset = projectionOffset;
1839        slave._viewOffset = viewOffset;
1840        slave._updateSlaveCallback =  new osgDepthPartition::MyUpdateSlaveCallback(dps.get(), 0);
1841    }
1842
1843    return true;
1844}
1845
1846
1847
1848bool View::setUpDepthPartition(DepthPartitionSettings* dsp)
1849{
1850    osgDepthPartition::Cameras originalCameras = osgDepthPartition::getActiveCameras(*this);
1851    if (originalCameras.empty())
1852    {
1853        OSG_INFO<<"osgView::View::setUpDepthPartition(,..), no windows assigned, doing view.setUpViewAcrossAllScreens()"<<std::endl;
1854        setUpViewAcrossAllScreens();
1855
1856        originalCameras = osgDepthPartition::getActiveCameras(*this);
1857        if (originalCameras.empty())
1858        {
1859            OSG_NOTICE<<"osgView::View::setUpDepthPartition(View,..) Unable to set up windows for viewer."<<std::endl;
1860            return false;
1861        }
1862    }
1863
1864    bool threadsWereRunning = getViewerBase()->areThreadsRunning();
1865    if (threadsWereRunning) getViewerBase()->stopThreading();
1866
1867    for(osgDepthPartition::Cameras::iterator itr = originalCameras.begin();
1868        itr != originalCameras.end();
1869        ++itr)
1870    {
1871        setUpDepthPartitionForCamera(itr->get(), dsp);
1872    }
1873
1874    if (threadsWereRunning) getViewerBase()->startThreading();
1875
1876    return true;
1877}
1878
1879
1880void View::assignSceneDataToCameras()
1881{
1882    // OSG_NOTICE<<"View::assignSceneDataToCameras()"<<std::endl;
1883
1884    if (_scene.valid() && _scene->getDatabasePager() && getViewerBase())
1885    {
1886        _scene->getDatabasePager()->setIncrementalCompileOperation(getViewerBase()->getIncrementalCompileOperation());
1887    }
1888
1889    osg::Node* sceneData = _scene.valid() ? _scene->getSceneData() : 0;
1890
1891    if (_cameraManipulator.valid())
1892    {
1893        _cameraManipulator->setNode(sceneData);
1894
1895        osg::ref_ptr<osgGA::GUIEventAdapter> dummyEvent = _eventQueue->createEvent();
1896
1897        _cameraManipulator->home(*dummyEvent, *this);
1898    }
1899
1900    if (_camera.valid())
1901    {
1902        _camera->removeChildren(0,_camera->getNumChildren());
1903        if (sceneData) _camera->addChild(sceneData);
1904
1905        Renderer* renderer = dynamic_cast<Renderer*>(_camera->getRenderer());
1906        if (renderer) renderer->setCompileOnNextDraw(true);
1907
1908    }
1909
1910    for(unsigned i=0; i<getNumSlaves(); ++i)
1911    {
1912        Slave& slave = getSlave(i);
1913        if (slave._camera.valid() && slave._useMastersSceneData)
1914        {
1915            slave._camera->removeChildren(0,slave._camera->getNumChildren());
1916            if (sceneData) slave._camera->addChild(sceneData);
1917
1918            Renderer* renderer = dynamic_cast<Renderer*>(slave._camera->getRenderer());
1919            if (renderer) renderer->setCompileOnNextDraw(true);
1920        }
1921    }
1922}
1923
1924void View::requestRedraw()
1925{
1926    if (getViewerBase())
1927    {
1928        getViewerBase()->_requestRedraw = true;
1929    }
1930    else
1931    {
1932        OSG_INFO<<"View::requestRedraw(), No viewer base has been assigned yet."<<std::endl;
1933    }
1934}
1935
1936void View::requestContinuousUpdate(bool flag)
1937{
1938    if (getViewerBase())
1939    {
1940        getViewerBase()->_requestContinousUpdate = flag;
1941    }
1942    else
1943    {
1944        OSG_INFO<<"View::requestContinuousUpdate(), No viewer base has been assigned yet."<<std::endl;
1945    }
1946}
1947
1948void View::requestWarpPointer(float x,float y)
1949{
1950    OSG_INFO<<"View::requestWarpPointer("<<x<<","<<y<<")"<<std::endl;
1951
1952    float local_x, local_y;
1953    const osg::Camera* camera = getCameraContainingPosition(x, y, local_x, local_y);
1954    if (camera)
1955    {
1956        const osgViewer::GraphicsWindow* gw = dynamic_cast<const osgViewer::GraphicsWindow*>(camera->getGraphicsContext());
1957        if (gw)
1958        {
1959            getEventQueue()->mouseWarped(x,y);
1960            if (gw->getEventQueue()->getCurrentEventState()->getMouseYOrientation()==osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS)
1961            {
1962                local_y = gw->getTraits()->height - local_y;
1963            }
1964            const_cast<osgViewer::GraphicsWindow*>(gw)->getEventQueue()->mouseWarped(local_x,local_y);
1965            const_cast<osgViewer::GraphicsWindow*>(gw)->requestWarpPointer(local_x, local_y);
1966        }
1967    }
1968    else
1969    {
1970        OSG_INFO<<"View::requestWarpPointer failed no camera containing pointer"<<std::endl;
1971    }
1972}
1973
1974bool View::containsCamera(const osg::Camera* camera) const
1975{
1976    if (_camera == camera) return true;
1977
1978    for(unsigned i=0; i<getNumSlaves(); ++i)
1979    {
1980        const Slave& slave = getSlave(i);
1981        if (slave._camera == camera) return true;
1982    }
1983    return false;
1984}
1985
1986const osg::Camera* View::getCameraContainingPosition(float x, float y, float& local_x, float& local_y) const
1987{
1988    const osgGA::GUIEventAdapter* eventState = getEventQueue()->getCurrentEventState();
1989    const osgViewer::GraphicsWindow* gw = dynamic_cast<const osgViewer::GraphicsWindow*>(eventState->getGraphicsContext());
1990
1991    bool view_invert_y = eventState->getMouseYOrientation()==osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS;
1992
1993    double epsilon = 0.5;
1994
1995    if (_camera->getGraphicsContext() &&
1996        (!gw || _camera->getGraphicsContext()==gw) &&
1997        _camera->getViewport())
1998    {
1999        const osg::Viewport* viewport = _camera->getViewport();
2000
2001        double new_x = x;
2002        double new_y = y;
2003
2004        if (!gw)
2005        {
2006            new_x = static_cast<double>(_camera->getGraphicsContext()->getTraits()->width) * (x - eventState->getXmin())/(eventState->getXmax()-eventState->getXmin());
2007            new_y = view_invert_y ?
2008                       static_cast<double>(_camera->getGraphicsContext()->getTraits()->height) * (1.0 - (y- eventState->getYmin())/(eventState->getYmax()-eventState->getYmin())) :
2009                       static_cast<double>(_camera->getGraphicsContext()->getTraits()->height) * (y - eventState->getYmin())/(eventState->getYmax()-eventState->getXmin());
2010        }
2011
2012        if (viewport &&
2013            new_x >= (viewport->x()-epsilon) && new_y >= (viewport->y()-epsilon) &&
2014            new_x < (viewport->x()+viewport->width()-1.0+epsilon) && new_y <= (viewport->y()+viewport->height()-1.0+epsilon) )
2015        {
2016            local_x = new_x;
2017            local_y = new_y;
2018
2019            OSG_INFO<<"Returning master camera"<<std::endl;
2020
2021            return _camera.get();
2022        }
2023    }
2024
2025    osg::Matrix masterCameraVPW = getCamera()->getViewMatrix() * getCamera()->getProjectionMatrix();
2026
2027    // convert to non dimensional
2028    x = (x - eventState->getXmin()) * 2.0 / (eventState->getXmax()-eventState->getXmin()) - 1.0;
2029    y = (y - eventState->getYmin())* 2.0 / (eventState->getYmax()-eventState->getYmin()) - 1.0;
2030
2031    if (view_invert_y) y = - y;
2032
2033    for(int i=getNumSlaves()-1; i>=0; --i)
2034    {
2035        const Slave& slave = getSlave(i);
2036        if (slave._camera.valid() &&
2037            slave._camera->getAllowEventFocus() &&
2038            slave._camera->getRenderTargetImplementation()==osg::Camera::FRAME_BUFFER)
2039        {
2040            OSG_INFO<<"Testing slave camera "<<slave._camera->getName()<<std::endl;
2041
2042            const osg::Camera* camera = slave._camera.get();
2043            const osg::Viewport* viewport = camera ? camera->getViewport() : 0;
2044
2045            osg::Matrix localCameraVPW = camera->getViewMatrix() * camera->getProjectionMatrix();
2046            if (viewport) localCameraVPW *= viewport->computeWindowMatrix();
2047
2048            osg::Matrix matrix( osg::Matrix::inverse(masterCameraVPW) * localCameraVPW );
2049
2050            osg::Vec3d new_coord = osg::Vec3d(x,y,0.0) * matrix;
2051
2052            //OSG_NOTICE<<"  x="<<x<<" y="<<y<<std::endl;;
2053            //OSG_NOTICE<<"  eventState->getXmin()="<<eventState->getXmin()<<" eventState->getXmax()="<<eventState->getXmax()<<std::endl;;
2054            //OSG_NOTICE<<"  new_coord "<<new_coord<<std::endl;;
2055
2056            if (viewport &&
2057                new_coord.x() >= (viewport->x()-epsilon) && new_coord.y() >= (viewport->y()-epsilon) &&
2058                new_coord.x() < (viewport->x()+viewport->width()-1.0+epsilon) && new_coord.y() <= (viewport->y()+viewport->height()-1.0+epsilon) )
2059            {
2060                // OSG_NOTICE<<"  in viewport "<<std::endl;;
2061
2062                local_x = new_coord.x();
2063                local_y = new_coord.y();
2064
2065                return camera;
2066            }
2067            else
2068            {
2069                // OSG_NOTICE<<"  not in viewport "<<viewport->x()<<" "<<(viewport->x()+viewport->width())<<std::endl;;
2070            }
2071
2072        }
2073    }
2074
2075    local_x = x;
2076    local_y = y;
2077
2078    return 0;
2079}
2080
2081bool View::computeIntersections(float x,float y, osgUtil::LineSegmentIntersector::Intersections& intersections, osg::Node::NodeMask traversalMask)
2082{
2083    if (!_camera.valid()) return false;
2084
2085    float local_x, local_y = 0.0;
2086    const osg::Camera* camera = getCameraContainingPosition(x, y, local_x, local_y);
2087    if (!camera) camera = _camera.get();
2088
2089
2090    osgUtil::LineSegmentIntersector::CoordinateFrame cf = camera->getViewport() ? osgUtil::Intersector::WINDOW : osgUtil::Intersector::PROJECTION;
2091    osg::ref_ptr< osgUtil::LineSegmentIntersector > picker = new osgUtil::LineSegmentIntersector(cf, local_x, local_y);
2092
2093#if 0
2094    OSG_NOTICE<<"View::computeIntersections(x="<<x<<", y="<<y<<", local_x="<<local_x<<", local_y="<<local_y<<") "<<cf<<std::endl;
2095    OSG_NOTICE<<"  viewport ("<<camera->getViewport()->x()<<","<<camera->getViewport()->y()<<","<<camera->getViewport()->width()<<","<<camera->getViewport()->height()<<")"<<std::endl;
2096
2097    const osg::GraphicsContext::Traits* traits = camera->getGraphicsContext() ? camera->getGraphicsContext()->getTraits() : 0;
2098    if (traits)
2099    {
2100        OSG_NOTICE<<"  window ("<<traits->x<<","<<traits->y<<","<<traits->width<<","<<traits->height<<")"<<std::endl;
2101    }
2102#endif
2103
2104    osgUtil::IntersectionVisitor iv(picker.get());
2105    iv.setTraversalMask(traversalMask);
2106
2107
2108#if 1
2109    const_cast<osg::Camera*>(camera)->accept(iv);
2110#else
2111
2112    // timing test code paths for comparing KdTree based intersections vs conventional intersections
2113
2114    iv.setUseKdTreeWhenAvailable(true);
2115    iv.setDoDummyTraversal(true);
2116
2117    const_cast<osg::Camera*>(camera)->accept(iv);
2118
2119
2120    osg::Timer_t before = osg::Timer::instance()->tick();
2121    const_cast<osg::Camera*>(camera)->accept(iv);
2122
2123    osg::Timer_t after_dummy = osg::Timer::instance()->tick();
2124
2125    int intersectsBeforeKdTree = picker->getIntersections().size();
2126
2127    iv.setDoDummyTraversal(false);
2128    const_cast<osg::Camera*>(camera)->accept(iv);
2129    osg::Timer_t after_kdTree_2 = osg::Timer::instance()->tick();
2130
2131    int intersectsBeforeConventional = picker->getIntersections().size();
2132
2133    iv.setUseKdTreeWhenAvailable(false);
2134    const_cast<osg::Camera*>(camera)->accept(iv);
2135    osg::Timer_t after = osg::Timer::instance()->tick();
2136
2137    int intersectsAfterConventional = picker->getIntersections().size();
2138
2139    double timeDummy = osg::Timer::instance()->delta_m(before, after_dummy);
2140    double timeKdTree = osg::Timer::instance()->delta_m(after_dummy, after_kdTree_2);
2141    double timeConventional = osg::Timer::instance()->delta_m(after_kdTree_2, after);
2142
2143    OSG_NOTICE<<"Using Dummy                    "<<timeDummy<<std::endl;
2144    OSG_NOTICE<<"      KdTrees                  "<<timeKdTree
2145                            <<"\tNum intersects = "<<intersectsBeforeConventional-intersectsBeforeKdTree<<std::endl;
2146    OSG_NOTICE<<"      KdTrees - Traversal      "<<timeKdTree-timeDummy<<std::endl;
2147    OSG_NOTICE<<"      Conventional             "<<timeConventional
2148                            <<"\tNum intersects = "<<intersectsAfterConventional-intersectsBeforeConventional<<std::endl;
2149    OSG_NOTICE<<"      Conventional - Traversal "<<timeConventional-timeDummy<<std::endl;
2150    OSG_NOTICE<<"      Delta                    "<<timeConventional/timeKdTree<<std::endl;
2151    OSG_NOTICE<<"      Delta sans Traversal     "<<(timeConventional-timeDummy)/(timeKdTree-timeDummy)<<std::endl;
2152    OSG_NOTICE<<std::endl;
2153#endif
2154
2155    if (picker->containsIntersections())
2156    {
2157        intersections = picker->getIntersections();
2158        return true;
2159    }
2160    else
2161    {
2162        intersections.clear();
2163        return false;
2164    }
2165}
2166
2167bool View::computeIntersections(float x,float y, const osg::NodePath& nodePath, osgUtil::LineSegmentIntersector::Intersections& intersections,osg::Node::NodeMask traversalMask)
2168{
2169    if (!_camera.valid() || nodePath.empty()) return false;
2170
2171    float local_x, local_y = 0.0;
2172    const osg::Camera* camera = getCameraContainingPosition(x, y, local_x, local_y);
2173    if (!camera) camera = _camera.get();
2174
2175    osg::Matrixd matrix;
2176    if (nodePath.size()>1)
2177    {
2178        osg::NodePath prunedNodePath(nodePath.begin(),nodePath.end()-1);
2179        matrix = osg::computeLocalToWorld(prunedNodePath);
2180    }
2181
2182    matrix.postMult(camera->getViewMatrix());
2183    matrix.postMult(camera->getProjectionMatrix());
2184
2185    double zNear = -1.0;
2186    double zFar = 1.0;
2187    if (camera->getViewport())
2188    {
2189        matrix.postMult(camera->getViewport()->computeWindowMatrix());
2190        zNear = 0.0;
2191        zFar = 1.0;
2192    }
2193
2194    osg::Matrixd inverse;
2195    inverse.invert(matrix);
2196
2197    osg::Vec3d startVertex = osg::Vec3d(local_x,local_y,zNear) * inverse;
2198    osg::Vec3d endVertex = osg::Vec3d(local_x,local_y,zFar) * inverse;
2199
2200    osg::ref_ptr< osgUtil::LineSegmentIntersector > picker = new osgUtil::LineSegmentIntersector(osgUtil::Intersector::MODEL, startVertex, endVertex);
2201
2202    osgUtil::IntersectionVisitor iv(picker.get());
2203    iv.setTraversalMask(traversalMask);
2204    nodePath.back()->accept(iv);
2205
2206    if (picker->containsIntersections())
2207    {
2208        intersections = picker->getIntersections();
2209        return true;
2210    }
2211    else
2212    {
2213        intersections.clear();
2214        return false;
2215    }
2216}
2217
Note: See TracBrowser for help on using the browser.