From 15f88f35b2e651a43124a264f20e6549de41856c Mon Sep 17 00:00:00 2001 From: Don BURNS Date: Tue, 24 Jun 2003 15:40:09 +0000 Subject: [PATCH] *** empty log message *** --- Make/makedefs | 21 +- Make/makedirdefs | 5 +- Make/makepkg | 4 +- VisualStudio/VisualStudio.dsw | 27 + VisualStudio/osg/osg.dsp | 9 + examples/osgcameragroup/GNUmakefile | 8 + examples/osgcameragroup/osgcameragroup.cpp | 12 +- examples/osgconv/osgconv.cpp | 6 + examples/osghud/osghud.cpp | 11 +- examples/osglight/osglight.cpp | 2 +- examples/osgstereoimage/osgstereoimage.cpp | 2 +- .../osgtexturerectangle.cpp | 32 +- examples/osgviewer/osgviewer.cpp | 37 + include/osg/CollectOccludersVisitor | 2 +- include/osg/Drawable | 6 + include/osg/Geometry | 34 +- include/osg/Image | 3 + include/osg/Math | 6 + include/osg/Point | 14 +- include/osg/State | 7 + include/osg/TextureRectangle | 8 +- include/osg/TriangleFunctor | 24 +- include/osgGA/GUIEventHandler | 6 +- include/osgProducer/OsgCameraGroup | 2 +- include/osgProducer/OsgSceneHandler | 14 +- include/osgProducer/Viewer | 11 + include/osgSim/LightPointNode | 3 + include/osgText/Text | 66 +- include/osgUtil/CullVisitor | 4 +- include/osgUtil/SceneView | 6 +- include/osgUtil/UpdateVisitor | 4 +- src/osg/CullStack.cpp | 67 +- src/osg/Drawable.cpp | 14 + src/osg/GNUmakefile | 1 + src/osg/Geometry.cpp | 140 +++- src/osg/Image.cpp | 50 +- src/osg/Material.cpp | 26 +- src/osg/NodeVisitor.cpp | 6 +- src/osg/Point.cpp | 24 +- src/osg/State.cpp | 3 +- src/osg/TexEnvCombine.cpp | 6 +- src/osg/TextureRectangle.cpp | 24 +- src/osgDB/Registry.cpp | 17 +- src/osgGA/GUIEventHandlerVisitor.cpp | 2 +- src/osgPlugins/3dc/ReaderWriter3DC.cpp | 3 +- src/osgPlugins/dds/ReaderWriterDDS.cpp | 10 +- src/osgPlugins/flt/GeoSetBuilder.cpp | 2 +- src/osgPlugins/flt/flt2osg.cpp | 14 + src/osgPlugins/freetype/FreeTypeFont.cpp | 4 +- src/osgPlugins/ive/AnimationPathCallback.cpp | 12 +- src/osgPlugins/ive/DataInputStream.cpp | 695 ++++++++++++------ src/osgPlugins/ive/DataInputStream.h | 34 +- src/osgPlugins/ive/DataOutputStream.cpp | 511 +++++++++---- src/osgPlugins/ive/DataOutputStream.h | 30 +- src/osgPlugins/ive/Drawable.cpp | 25 +- src/osgPlugins/ive/GNUmakefile | 9 + src/osgPlugins/ive/Geode.cpp | 121 +-- src/osgPlugins/ive/Geometry.cpp | 35 +- src/osgPlugins/ive/Group.cpp | 174 ++--- src/osgPlugins/ive/Image.cpp | 193 ++--- src/osgPlugins/ive/LightSource.cpp | 2 +- src/osgPlugins/ive/Node.cpp | 6 +- src/osgPlugins/ive/ReadWrite.h | 89 ++- src/osgPlugins/ive/ReaderWriterIVE.cpp | 36 +- src/osgPlugins/ive/StateSet.cpp | 356 ++++----- src/osgPlugins/ive/Texture2D.cpp | 2 +- src/osgPlugins/ive/TextureCubeMap.cpp | 12 +- src/osgPlugins/obj/ReaderWriterOBJ.cpp | 14 +- src/osgPlugins/obj/glm.cpp | 660 ++++++++--------- src/osgPlugins/obj/glm.h | 144 ++-- src/osgPlugins/osg/Geometry.cpp | 2 +- src/osgPlugins/osgText/IO_Text.cpp | 50 +- src/osgPlugins/txp/TerrapageNode.cpp | 1 + src/osgPlugins/txp/trPagePageManager.cpp | 77 +- src/osgPlugins/txp/trPagePageManager.h | 2 + src/osgProducer/GNUmakefile | 7 + src/osgProducer/OsgCameraGroup.cpp | 33 +- src/osgProducer/OsgSceneHandler.cpp | 20 +- src/osgProducer/Viewer.cpp | 16 +- src/osgProducer/ViewerEventHandler.cpp | 27 +- src/osgSim/GNUmakefile | 2 + src/osgSim/LightPointDrawable.cpp | 1 - src/osgSim/LightPointDrawable.h | 1 - src/osgSim/LightPointNode.cpp | 31 +- src/osgText/Font.cpp | 92 ++- src/osgText/Text.cpp | 327 ++++---- src/osgUtil/IntersectVisitor.cpp | 2 +- src/osgUtil/Optimizer.cpp | 134 ++-- src/osgUtil/SceneView.cpp | 10 + src/osgUtil/SmoothingVisitor.cpp | 2 +- src/osgUtil/Tesselator.cpp | 2 +- 91 files changed, 2871 insertions(+), 1937 deletions(-) diff --git a/Make/makedefs b/Make/makedefs index 217011ea8..b963aaa4b 100644 --- a/Make/makedefs +++ b/Make/makedefs @@ -35,9 +35,9 @@ MAKEDEPEND = ignore ## ## Usage: ## Default - VERSION_REVISION is set to the value defined here -## Env variable PRODUCER_VERSION_REVISION overrides default +## Env variable OSG_VERSION_REVISION overrides default ## e.g.: -## % setenv PRODUCER_VERSION_REVISION 5 +## % setenv OSG_VERSION_REVISION 5 ## % make version ## Command line overrides env variable ## % make VERSION_REVISION= @@ -386,16 +386,17 @@ ifeq ($(OS),CYGWIN) LIB_EXT = dll PLUGIN_EXT = dll LINK = cp -f - INST_SYS_PREFIX = /usr/local/OpenSceneGraph - INST_LIBS = $(INST_SYS_PREFIX)/bin - INST_PLUGINS = $(INST_SYS_PREFIX)/bin - INST_INCLUDE = $(INST_SYS_PREFIX)/include + INST_LOCATION = /usr/local/OpenSceneGraph + INST_LIBS = $(INST_LOCATION)/bin + INST_PLUGINS = $(INST_LOCATION)/bin + INST_INCLUDE = $(INST_LOCATION)/include INST_SHARE_PREFIX = /usr/local/OpenSceneGraph INST_SRC = $(INST_SHARE_PREFIX)/src INST_EXAMPLES = $(INST_SHARE_PREFIX)/bin INST_EXAMPLE_SRC = $(INST_SHARE_PREFIX)/src/demos INST_DOC = $(INST_SHARE_PREFIX)/doc INST_DATA = $(INST_SHARE_PREFIX)/data + MAKEDIST = $(TOPDIR)/Make/makeinnosetup endif #### Cygwin/Mingw specific definitions @@ -432,10 +433,10 @@ ifeq ($(OS),MINGW) LIB_EXT = dll PLUGIN_EXT = dll LINK = cp -f - INST_SYS_PREFIX = /usr/local/OpenSceneGraph - INST_LIBS = $(INST_SYS_PREFIX)/bin - INST_PLUGINS = $(INST_SYS_PREFIX)/bin - INST_INCLUDE = $(INST_SYS_PREFIX)/include + INST_LOCATION = /usr/local/OpenSceneGraph + INST_LIBS = $(INST_LOCATION)/bin + INST_PLUGINS = $(INST_LOCATION)/bin + INST_INCLUDE = $(INST_LOCATION)/include INST_SHARE_PREFIX = /usr/local/OpenSceneGraph INST_SRC = $(INST_SHARE_PREFIX)/src INST_EXAMPLES = $(INST_SHARE_PREFIX)/bin diff --git a/Make/makedirdefs b/Make/makedirdefs index c7fdd810e..07020264a 100644 --- a/Make/makedirdefs +++ b/Make/makedirdefs @@ -128,6 +128,7 @@ EXAMPLE_DIRS = \ osgparticle\ osgpick\ osgprerender\ + osgpoints\ osgreflect\ osgscribe\ osgsequence\ @@ -146,8 +147,10 @@ EXAMPLE_DIRS = \ osgversion\ osgvertexprogram\ osgviewer\ + osgprerendercubemap\ -# osgprerendercubemap\ +# osgsimulation\ +# osgdemeter\ # osgjigsaw\ # comment in you want to compile the cluster demo. diff --git a/Make/makepkg b/Make/makepkg index 8aa1750e4..3f9f3ed39 100644 --- a/Make/makepkg +++ b/Make/makepkg @@ -23,7 +23,7 @@ print_pkginfo() PKG="$1" NAME="$2" `[ "$OS" = "SunOS" ] && echo ARCH=sparc` -VERSION=`$TOPDIR/bin/osgversion` +VERSION=`gmake -s version` CATEGORY="application,graphics,opengl" DESC="$3" BASEDIR="/opt/" @@ -67,7 +67,7 @@ make_installable() { PKGNAME=$1 PKGDIR=$PKGNAME.pkg - DISTNAME="$PKGNAME"-"`$TOPDIR/bin/osgversion`"-"$OS".shar + DISTNAME="$PKGNAME"-"`gmake -s version`"-"$OS".shar THISDIR=`pwd` cd $PKGSUBDIR diff --git a/VisualStudio/VisualStudio.dsw b/VisualStudio/VisualStudio.dsw index 7e1d9f2d2..5966e5855 100644 --- a/VisualStudio/VisualStudio.dsw +++ b/VisualStudio/VisualStudio.dsw @@ -753,6 +753,33 @@ Package=<4> ############################################################################### +Project: "Example osgprerendercubemap"=.\examples\osgprerendercubemap\osgprerendercubemap.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name Core osg + End Project Dependency + Begin Project Dependency + Project_Dep_Name Core osgDB + End Project Dependency + Begin Project Dependency + Project_Dep_Name Core osgGA + End Project Dependency + Begin Project Dependency + Project_Dep_Name Core osgProducer + End Project Dependency + Begin Project Dependency + Project_Dep_Name Core osgUtil + End Project Dependency +}}} + +############################################################################### + Project: "Example osgreflect"=.\examples\osgreflect\osgreflect.dsp - Package Owner=<4> Package=<5> diff --git a/VisualStudio/osg/osg.dsp b/VisualStudio/osg/osg.dsp index 7ffd27dd9..93adabb15 100755 --- a/VisualStudio/osg/osg.dsp +++ b/VisualStudio/osg/osg.dsp @@ -421,6 +421,10 @@ SOURCE=..\..\src\osg\Transform.cpp # End Source File # Begin Source File +SOURCE=..\..\src\osg\TransformAttributeFunctor.cpp +# End Source File +# Begin Source File + SOURCE=..\..\src\osg\BlendFunc.cpp # End Source File # Begin Source File @@ -837,6 +841,11 @@ SOURCE=..\..\Include\Osg\Transform # End Source File # Begin Source File +SOURCE=..\..\Include\Osg\TransformAttributeFunctor +# End Source File +# Begin Source File + + SOURCE=..\..\Include\Osg\TriangleFunctor # End Source File # Begin Source File diff --git a/examples/osgcameragroup/GNUmakefile b/examples/osgcameragroup/GNUmakefile index 37e12ff5a..399f1defd 100644 --- a/examples/osgcameragroup/GNUmakefile +++ b/examples/osgcameragroup/GNUmakefile @@ -15,5 +15,13 @@ EXEC = osgcameragroup INC += $(PRODUCER_INCLUDE_DIR) -I/usr/X11R6/include -I/usr/X11R6/include LDFLAGS += $(PRODUCER_LIB_DIR) -L/usr/X11R6/lib + +ifeq ($(USE_OPEN_THREAD),1) + DEF += -D_USE_OPEN_THREAD + INC += $(INC_OPEN_THREAD) + LDFLAGS += $(LIB_OPEN_THREAD) + LIBS += -lOpenThread +endif + include $(TOPDIR)/Make/makerules diff --git a/examples/osgcameragroup/osgcameragroup.cpp b/examples/osgcameragroup/osgcameragroup.cpp index 11d89a005..3a6037c67 100644 --- a/examples/osgcameragroup/osgcameragroup.cpp +++ b/examples/osgcameragroup/osgcameragroup.cpp @@ -149,10 +149,10 @@ int main( int argc, char **argv ) const osg::BoundingSphere& bs = loadedModel->getBound(); - Producer::Trackball tb; - tb.setOrientation( Producer::Trackball::Z_UP ); - tb.setDistance(bs.radius()*3.0f); - tb.translate(-bs.center().x(),-bs.center().y(),-bs.center().z()); + osg::ref_ptr tb = new Producer::Trackball; + tb->setOrientation( Producer::Trackball::Z_UP ); + tb->setDistance(bs.radius()*3.0f); + tb->translate(-bs.center().x(),-bs.center().y(),-bs.center().z()); // create the windows and run the threads. cg.realize(); @@ -168,10 +168,10 @@ int main( int argc, char **argv ) // call all node update callbacks and animations. cg.getSceneData()->accept(update); - tb.input( kbmcb.mx(), kbmcb.my(), kbmcb.mbutton() ); + tb->input( kbmcb.mx(), kbmcb.my(), kbmcb.mbutton() ); // update the main producer camera - cg.setViewByMatrix(tb.getMatrix()); + cg.setViewByMatrix(tb->getMatrix()); // fire off the cull and draw traversals of the scene. cg.frame(); diff --git a/examples/osgconv/osgconv.cpp b/examples/osgconv/osgconv.cpp index 752800861..4100a2fdf 100644 --- a/examples/osgconv/osgconv.cpp +++ b/examples/osgconv/osgconv.cpp @@ -9,6 +9,8 @@ #include #include +#include + #include "OrientationConverter.h" #include "GeoSet.h" @@ -273,6 +275,10 @@ int main( int argc, char **argv ) ConvertGeoSetsToGeometryVisitor cgtg; root->accept(cgtg); + // optimize the scene graph, remove rendundent nodes and state etc. + osgUtil::Optimizer optimizer; + optimizer.optimize(root.get()); + if( do_convert ) root = oc.convert( root.get() ); diff --git a/examples/osghud/osghud.cpp b/examples/osghud/osghud.cpp index c0c548fe6..9e3f8d985 100644 --- a/examples/osghud/osghud.cpp +++ b/examples/osghud/osghud.cpp @@ -35,8 +35,17 @@ osg::Node* createHUD() // turn lighting off for the text and disable depth test to ensure its always ontop. osg::StateSet* stateset = geode->getOrCreateStateSet(); stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF); - //stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF); + +#if 0 + // to ensure the hud appears on top we can either use osg::Depth to force the + // depth fragments to be placed at the front of the screen. stateset->setAttribute(new osg::Depth(osg::Depth::LESS,0.0,0.0001)); +#else + // or disable depth test, and make sure that the hud is drawn after everything + // else so that it always appears ontop. + stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF); + stateset->setRenderBinDetails(11,"RenderBin"); +#endif osg::Vec3 position(150.0f,800.0f,0.0f); osg::Vec3 delta(0.0f,-120.0f,0.0f); diff --git a/examples/osglight/osglight.cpp b/examples/osglight/osglight.cpp index a11473f03..7a5a8d268 100644 --- a/examples/osglight/osglight.cpp +++ b/examples/osglight/osglight.cpp @@ -356,7 +356,7 @@ int main( int argc, char **argv ) ++itr) { // switch off small feature culling to prevent the light points from being culled. - osgUtil::SceneView* sceneview = itr->get(); + osgUtil::SceneView* sceneview = (*itr)->getSceneView(); sceneview->setCullingMode( sceneview->getCullingMode() & ~osg::CullStack::SMALL_FEATURE_CULLING); } diff --git a/examples/osgstereoimage/osgstereoimage.cpp b/examples/osgstereoimage/osgstereoimage.cpp index ac682deda..13e99f7c2 100644 --- a/examples/osgstereoimage/osgstereoimage.cpp +++ b/examples/osgstereoimage/osgstereoimage.cpp @@ -508,7 +508,7 @@ int main( int argc, char **argv ) itr!=viewer.getSceneHandlerList().end(); ++itr) { - osgUtil::SceneView* sceneview = itr->get(); + osgUtil::SceneView* sceneview = (*itr)->getSceneView(); sceneview->setCullMask(0xffffffff); sceneview->setCullMaskLeft(0x00000001); sceneview->setCullMaskRight(0x00000002); diff --git a/examples/osgtexturerectangle/osgtexturerectangle.cpp b/examples/osgtexturerectangle/osgtexturerectangle.cpp index 5545ec629..2be0786d8 100644 --- a/examples/osgtexturerectangle/osgtexturerectangle.cpp +++ b/examples/osgtexturerectangle/osgtexturerectangle.cpp @@ -20,9 +20,9 @@ #include #include +#include #include #include - #include #include @@ -137,18 +137,14 @@ osg::Node* createRectangle(osg::BoundingBox& bb, // disable display list so our modified tex coordinates show up geom->setUseDisplayList(false); - osg::Geode* geode = new osg::Geode; - geode->addDrawable(geom); - // setup texture osg::TextureRectangle* texture = new osg::TextureRectangle; - texture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP); - texture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP); // load image osg::Image* img = osgDB::readImageFile(filename); texture->setImage(img); - + + // setup state osg::StateSet* state = geom->getOrCreateStateSet(); state->setTextureAttributeAndModes(0, texture, osg::StateAttribute::ON); @@ -156,6 +152,8 @@ osg::Node* createRectangle(osg::BoundingBox& bb, state->setMode(GL_LIGHTING, osg::StateAttribute::OFF); // install 'update' callback + osg::Geode* geode = new osg::Geode; + geode->addDrawable(geom); geode->setUpdateCallback(new TexturePanCallback(geom, img)); return geode; @@ -190,17 +188,17 @@ osg::Node* createHUD() state->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF); // add text - osg::Vec3 pos(150.0f, 800.0f, 0.0f); + osg::Vec3 pos(120.0f, 800.0f, 0.0f); const osg::Vec3 delta(0.0f, -80.0f, 0.0f); const char* text[] = { "TextureRectangle Mini-HOWTO", "- essentially behaves like Texture2D, *except* that:", - "- tex coords must be non-normalized (0..width) instead of (0..1)", - "- wrap mode must be CLAMP, CLAMP_TO_EDGE, or CLAMP_TO_BORDER", - "- repeating wrap modes are *not* supported", - "- texture border is *not* supported", - "- texture mipmaps are *not* supported", + "- tex coords must be non-normalized (0..pixel) instead of (0..1)", + "- wrap modes must be CLAMP, CLAMP_TO_EDGE, or CLAMP_TO_BORDER\n repeating wrap modes are not supported", + "- filter modes must be NEAREST or LINEAR since\n mipmaps are not supported", + "- texture borders are not supported", + "- defaults should be fine", NULL }; const char** t = text; @@ -226,9 +224,11 @@ osg::Node* createHUD() osg::Node* createModel(const std::string& filename) { osg::Group* root = new osg::Group; - - osg::BoundingBox bb(0.0f,0.0f,0.0f,1.0f,1.0f,1.0f); - root->addChild(createRectangle(bb, filename)); // XXX + + if (filename != "X") { + osg::BoundingBox bb(0.0f,0.0f,0.0f,1.0f,1.0f,1.0f); + root->addChild(createRectangle(bb, filename)); // XXX + } root->addChild(createHUD()); diff --git a/examples/osgviewer/osgviewer.cpp b/examples/osgviewer/osgviewer.cpp index 59ae93472..50fa96f46 100644 --- a/examples/osgviewer/osgviewer.cpp +++ b/examples/osgviewer/osgviewer.cpp @@ -13,6 +13,43 @@ #include #include + +#if 0 +enum Methods +{ + SET_1, + SET_2, + END +}; + + +typedef std::pair MethodPair; + +class Proxy +{ +public: + Proxy(MethodPair* methods) + { + std::cout<<"methods "< _vertexArray; - ref_ptr _vertexIndices; + ref_ptr _vertexArray; + ref_ptr _vertexIndices; mutable AttributeBinding _normalBinding; - ref_ptr _normalArray; - ref_ptr _normalIndices; + ref_ptr _normalArray; + ref_ptr _normalIndices; mutable AttributeBinding _colorBinding; - ref_ptr _colorArray; - ref_ptr _colorIndices; + ref_ptr _colorArray; + ref_ptr _colorIndices; mutable AttributeBinding _secondaryColorBinding; - ref_ptr _secondaryColorArray; - ref_ptr _secondaryColorIndices; + ref_ptr _secondaryColorArray; + ref_ptr _secondaryColorIndices; mutable AttributeBinding _fogCoordBinding; - ref_ptr _fogCoordArray; - ref_ptr _fogCoordIndices; + ref_ptr _fogCoordArray; + ref_ptr _fogCoordIndices; - TexCoordArrayList _texCoordList; + TexCoordArrayList _texCoordList; - VertexAttribArrayList _vertexAttribList; - mutable VertexAttribBindingList _vertexAttribBindingList; + VertexAttribArrayList _vertexAttribList; + mutable VertexAttribBindingList _vertexAttribBindingList; - mutable bool _fastPathComputed; + mutable bool _fastPathComputed; mutable bool _fastPath; }; diff --git a/include/osg/Image b/include/osg/Image index 183c5bf1a..eb3f37e12 100644 --- a/include/osg/Image +++ b/include/osg/Image @@ -155,6 +155,9 @@ class SG_EXPORT Image : public Object /** return the numbers of bytes the whole row/image/volume of pixels occupies.*/ inline unsigned int getTotalSizeInBytes() const { return getImageSizeInBytes()*_r; } + /** return the numbers of bytes the whole row/image/volume of pixels occupies, including all mip maps if included.*/ + unsigned int getTotalSizeInBytesIncludingMipmaps() const; + /** raw image data.*/ inline unsigned char *data() { return _data; } diff --git a/include/osg/Math b/include/osg/Math index 48f3abd36..aad8d0b73 100644 --- a/include/osg/Math +++ b/include/osg/Math @@ -113,6 +113,12 @@ const double PI_4 = 0.78539816339744830962; template inline T absolute(T v) { return v<(T)0?-v:v; } +/** return true if float lhs and rhs are equivalent, meaning that the difference between then is less than an epsilon value which default to 1e-6.*/ +inline float equivalent(float lhs,float rhs,float epsilon=1e-6) { float delta = rhs-lhs; return delta<0.0f?delta>=-epsilon:delta<=epsilon; } + +/** return true if double lhs and rhs are equivalent, meaning that the difference between then is less than an epsilon value which default to 1e-6.*/ +inline double equivalent(double lhs,double rhs,double epsilon=1e-6) { double delta = rhs-lhs; return delta<0.0?delta>=-epsilon:delta<=epsilon; } + /** return the minimum of two values, equivilant to std::min. * std::min not used because of STL implementation under IRIX contains no std::min.*/ template diff --git a/include/osg/Point b/include/osg/Point index dc149876d..e710c23f7 100644 --- a/include/osg/Point +++ b/include/osg/Point @@ -31,7 +31,9 @@ class SG_EXPORT Point : public StateAttribute StateAttribute(point,copyop), _size(point._size), _fadeThresholdSize(point._fadeThresholdSize), - _distanceAttenuation(point._distanceAttenuation) {} + _distanceAttenuation(point._distanceAttenuation), + _minSize(point._minSize), + _maxSize(point._maxSize) {} META_StateAttribute(osg, Point, POINT); @@ -46,6 +48,8 @@ class SG_EXPORT Point : public StateAttribute COMPARE_StateAttribute_Parameter(_size) COMPARE_StateAttribute_Parameter(_fadeThresholdSize) COMPARE_StateAttribute_Parameter(_distanceAttenuation) + COMPARE_StateAttribute_Parameter(_minSize) + COMPARE_StateAttribute_Parameter(_maxSize) return 0; // passed all the above comparison macro's, must be equal. } @@ -64,6 +68,12 @@ class SG_EXPORT Point : public StateAttribute void setDistanceAttenuation(const Vec3& distanceAttenuation); inline const Vec3& getDistanceAttenuation() const { return _distanceAttenuation; } + void setMinSize(float minSize); + inline float getMinSize() const {return _minSize;} + + void setMaxSize(float maxSize); + inline float getMaxSize() const {return _maxSize;} + virtual void apply(State& state) const; static void init_GL_EXT(); @@ -75,6 +85,8 @@ class SG_EXPORT Point : public StateAttribute float _size; float _fadeThresholdSize; Vec3 _distanceAttenuation; + float _minSize; + float _maxSize; }; diff --git a/include/osg/State b/include/osg/State index cbd42df1b..434b9442b 100644 --- a/include/osg/State +++ b/include/osg/State @@ -21,6 +21,7 @@ #include #include #include +#include #include #include @@ -79,6 +80,12 @@ class SG_EXPORT State : public Referenced /** reset the state object to an empty stack.*/ void reset(); + + inline const Viewport* getCurrentViewport() const + { + return static_cast(getLastAppliedAttribute(osg::StateAttribute::VIEWPORT)); + } + inline void applyProjectionMatrix(const osg::RefMatrix* matrix) { diff --git a/include/osg/TextureRectangle b/include/osg/TextureRectangle index c10ef76af..812743889 100644 --- a/include/osg/TextureRectangle +++ b/include/osg/TextureRectangle @@ -84,8 +84,8 @@ class SG_EXPORT TextureRectangle : public Texture SubloadCallback* getSubloadCallback() { return _subloadCallback.get(); } const SubloadCallback* getSubloadCallback() const { return _subloadCallback.get(); } - /** On first apply (unless already compiled), create the minmapped - * texture and bind it, subsequent apply will simple bind to texture.*/ + /** On first apply (unless already compiled), create and bind the + * texture, subsequent apply will simple bind to texture.*/ virtual void apply(State& state) const; protected : @@ -94,7 +94,9 @@ class SG_EXPORT TextureRectangle : public Texture virtual void computeInternalFormat() const; - void applyTexImageRectangle(GLenum target, Image* image, State& state, GLsizei& inwidth, GLsizei& inheight) const; + void applyTexParameters(GLenum target, State& state) const; + + void applyTexImage(GLenum target, Image* image, State& state, GLsizei& inwidth, GLsizei& inheight) const; // not ideal that _image is mutable, but its required since // Image::ensureDimensionsArePowerOfTwo() can only be called diff --git a/include/osg/TriangleFunctor b/include/osg/TriangleFunctor index 91b5394de..6cd619c2d 100644 --- a/include/osg/TriangleFunctor +++ b/include/osg/TriangleFunctor @@ -15,6 +15,7 @@ #define OSG_TRIANGLEFUNCTOR 1 #include +#include namespace osg { @@ -32,12 +33,23 @@ public: virtual ~TriangleFunctor() {} + virtual void setVertexArray(unsigned int count,const Vec2* vertices) + { + notify(WARN)<<"Triangle Functor does not support Vec2* vertex arrays"< > SceneHandlerList; + typedef std::vector < Producer::ref_ptr > SceneHandlerList; SceneHandlerList& getSceneHandlerList() { return _shvec;} diff --git a/include/osgProducer/OsgSceneHandler b/include/osgProducer/OsgSceneHandler index d0833721c..4d437462a 100644 --- a/include/osgProducer/OsgSceneHandler +++ b/include/osgProducer/OsgSceneHandler @@ -22,11 +22,20 @@ namespace osgProducer { -class OSGPRODUCER_EXPORT OsgSceneHandler : public Producer::Camera::SceneHandler, public osgUtil::SceneView +class OSGPRODUCER_EXPORT OsgSceneHandler : public Producer::Camera::SceneHandler { public : OsgSceneHandler(osg::DisplaySettings *ds = NULL); + + /// set the scene view to which will manage rendering of the OSG scene. + void setSceneView(osgUtil::SceneView* sceneView) { _sceneView = sceneView; } + + /// get the scene view. + osgUtil::SceneView* getSceneView() { return _sceneView.get(); } + + /// get the const scene view. + const osgUtil::SceneView* getSceneView() const { return _sceneView.get(); } /// override the init method to force it be run one at a time. virtual void init(); @@ -84,6 +93,9 @@ class OSGPRODUCER_EXPORT OsgSceneHandler : public Producer::Camera::SceneHandler protected: virtual ~OsgSceneHandler() {} + + + osg::ref_ptr _sceneView; osg::ref_ptr _clearCallback; osg::ref_ptr _cullCallback; diff --git a/include/osgProducer/Viewer b/include/osgProducer/Viewer index 408e490da..615c335ed 100644 --- a/include/osgProducer/Viewer +++ b/include/osgProducer/Viewer @@ -82,7 +82,18 @@ class OSGPRODUCER_EXPORT Viewer : public OsgCameraGroup, public osgGA::GUIAction virtual bool realize(); + /** Updated the scene. Handle any queued up events, do an update traversal and set the CameraGroup's setViewByMatrix if any camera manipulators are active.*/ virtual void update(); + + /** set the update visitor which does the update traversal of the scene graph. Automatically called by the update() method.*/ + void setUpdateVistor(osg::NodeVisitor* nv) { _updateVisitor = nv; } + + /** get the update visitor.*/ + osg::NodeVisitor* getUpdateVistor() { return _updateVisitor.get(); } + + /** get the const update visitor.*/ + const osg::NodeVisitor* getUpdateVistor() const { return _updateVisitor.get(); } + /** Dispatch the cull and draw for each of the Camera's for this frame.*/ virtual void frame(); diff --git a/include/osgSim/LightPointNode b/include/osgSim/LightPointNode index 7b110c330..0e3032507 100644 --- a/include/osgSim/LightPointNode +++ b/include/osgSim/LightPointNode @@ -45,6 +45,9 @@ class OSGSIM_EXPORT LightPointNode : public osg::Node virtual void traverse(osg::NodeVisitor& nv); + unsigned int getNumLightPoints() const { return _lightPointList.size(); } + + unsigned int addLightPoint(const LightPoint& lp); void removeLightPoint(unsigned int pos); diff --git a/include/osgText/Text b/include/osgText/Text index 0acc40159..9d7d9abdf 100644 --- a/include/osgText/Text +++ b/include/osgText/Text @@ -100,6 +100,18 @@ public: float getCharacterHeight() const { return _characterHeight; } float getCharacterAspectRatio() const { return _characterAspectRatio; } + enum CharacterSizeMode + { + OBJECT_COORDS, /// default + SCREEN_COORDS, /// internally scale the characters to be constant screen size. + OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT /// text that behavaves like OBJECT_COORDS sized text when a long distance way, but has its screen sized capped automatically when the viewer gets near. + }; + + /** Set how the CharacterSize value relates to the final rendered character.*/ + void setCharacterSizeMode(CharacterSizeMode mode) { _characterSizeMode = mode; } + + /** Get the CharacterSizeMode.*/ + CharacterSizeMode getCharacterSizeMode() const { return _characterSizeMode; } /** Set the maximum width of the text box. @@ -165,27 +177,11 @@ public: void setAxisAlignment(AxisAlignment axis); void setRotation(const osg::Quat& quat); - void setRotation(unsigned int contextID, const osg::Quat& quat); - const osg::Quat& getRotation(unsigned int contextID=0) const { return _rotation[contextID]; } + const osg::Quat& getRotation() const { return _rotation; } - void setScale(float scale); - void setScale(unsigned int contextID, float scale); - float getScale(unsigned int contextID=0) const { return _scale[contextID]; } - - void setScaleAndRotation(unsigned int contextID, float scale,const osg::Quat& quat); - - void setAutoUpdateEyeMovementTolerance(float tolerance) { _autoUpdateEyeMovementTolerance = tolerance; } - float getAutoUpdateEyeMovementTolerance() const { return _autoUpdateEyeMovementTolerance; } - void setAutoRotateToScreen(bool autoRotateToScreen); bool getAutoRotateToScreen() const { return _autoRotateToScreen; } - void setAutoScaleToLimitScreenSizeToFontResolution(bool autoScaleToScreen); - bool getAutoScaleToLimitScreenSizeToFontResolution() const { return _autoScaleToLimitScreenSizeToFontResolution; } - - - - enum Layout { LEFT_TO_RIGHT, /// default @@ -295,35 +291,49 @@ protected: unsigned int _fontHeight; float _characterHeight; float _characterAspectRatio; + CharacterSizeMode _characterSizeMode; float _maximumWidth; float _maximumHeight; String _text; osg::Vec3 _position; AlignmentType _alignment; - mutable osg::buffered_object _rotation; - mutable osg::buffered_value _scale; - float _autoUpdateEyeMovementTolerance; + osg::Quat _rotation; bool _autoRotateToScreen; - bool _autoScaleToLimitScreenSizeToFontResolution; Layout _layout; osg::Vec4 _color; unsigned int _drawMode; // iternal map used for rendering. Set up by the computeGlyphRepresentation() method. - TextureGlyphQuadMap _textureGlyphQuadMap; + mutable TextureGlyphQuadMap _textureGlyphQuadMap; void computeGlyphRepresentation(); // internal caches of the positioning of the text. - mutable osg::buffered_object _matrix; - osg::Vec3 _offset; - osg::Vec3 _normal; - mutable osg::BoundingBox _textBB; + + struct AutoTransformCache + { + AutoTransformCache(): + _traversalNumber(-1), + _width(0), + _height(0) {} + + int _traversalNumber; + int _width; + int _height; + osg::Vec3 _transformedPosition; + osg::Matrix _modelview; + osg::Matrix _projection; + osg::Matrix _matrix; + }; + + mutable osg::buffered_object _autoTransformCache; + mutable osg::Vec3 _offset; + mutable osg::Vec3 _normal; + mutable osg::BoundingBox _textBB; - void setUpAutoCallback(); void computePositions(); - void computePositions(unsigned int contextID); + void computePositions(unsigned int contextID) const; }; diff --git a/include/osgUtil/CullVisitor b/include/osgUtil/CullVisitor index 23fd52919..7d823676d 100644 --- a/include/osgUtil/CullVisitor +++ b/include/osgUtil/CullVisitor @@ -217,8 +217,8 @@ class OSGUTIL_EXPORT CullVisitor : public osg::NodeVisitor, public osg::CullStac protected: - /** prevent unwanted copy construction.*/ - CullVisitor(const CullVisitor&):osg::NodeVisitor(),osg::CullStack() {} +// /** prevent unwanted copy construction.*/ +// CullVisitor(const CullVisitor&): osg::NodeVisitor(), osg::CullStack() {} /** prevent unwanted copy operator.*/ CullVisitor& operator = (const CullVisitor&) { return *this; } diff --git a/include/osgUtil/SceneView b/include/osgUtil/SceneView index bfee44e2d..e93a76a5e 100644 --- a/include/osgUtil/SceneView +++ b/include/osgUtil/SceneView @@ -163,13 +163,13 @@ class OSGUTIL_EXPORT SceneView : public osg::Referenced void setCullMask(const osg::Node::NodeMask nm) { _cullMask = nm; } - const osg::Node::NodeMask getCullMask() const { return _cullMask; } + osg::Node::NodeMask getCullMask() const { return _cullMask; } void setCullMaskLeft(const osg::Node::NodeMask nm) { _cullMaskLeft = nm; } - const osg::Node::NodeMask getCullMaskLeft() const { return _cullMaskLeft; } + osg::Node::NodeMask getCullMaskLeft() const { return _cullMaskLeft; } void setCullMaskRight(const osg::Node::NodeMask nm) { _cullMaskRight = nm; } - const osg::Node::NodeMask getCullMaskRight() const { return _cullMaskRight; } + osg::Node::NodeMask getCullMaskRight() const { return _cullMaskRight; } /** Set the LOD bias for the CullVisitor to use.*/ void setLODScale(float bias) { _LODScale = bias; } diff --git a/include/osgUtil/UpdateVisitor b/include/osgUtil/UpdateVisitor index f00b1b6cc..fbbe3bf28 100644 --- a/include/osgUtil/UpdateVisitor +++ b/include/osgUtil/UpdateVisitor @@ -62,8 +62,8 @@ class OSGUTIL_EXPORT UpdateVisitor : public osg::NodeVisitor protected: - /** prevent unwanted copy construction.*/ - UpdateVisitor(const UpdateVisitor&):osg::NodeVisitor() {} +// /** prevent unwanted copy construction.*/ +// UpdateVisitor(const UpdateVisitor&):osg::NodeVisitor() {} /** prevent unwanted copy operator.*/ UpdateVisitor& operator = (const UpdateVisitor&) { return *this; } diff --git a/src/osg/CullStack.cpp b/src/osg/CullStack.cpp index 053e523d2..3b392d5e4 100644 --- a/src/osg/CullStack.cpp +++ b/src/osg/CullStack.cpp @@ -11,6 +11,7 @@ * OpenSceneGraph Public License for more details. */ #include +#include using namespace osg; @@ -199,27 +200,79 @@ void CullStack::pushModelViewMatrix(RefMatrix* matrix) _modelviewStack.push_back(matrix); pushCullingSet(); + + //osg::Timer timer; + + //osg::Timer_t tick_1 = timer.tick(); // fast method for computing the eye point in local coords which doesn't require the inverse matrix. const float x_0 = (*matrix)(0,0); const float x_1 = (*matrix)(1,0); const float x_2 = (*matrix)(2,0); - const float x_scale = (*matrix)(3,0) / -(x_0*x_0+x_1*x_1+x_2*x_2); + const float x_len2 = (x_0*x_0+x_1*x_1+x_2*x_2); const float y_0 = (*matrix)(0,1); const float y_1 = (*matrix)(1,1); const float y_2 = (*matrix)(2,1); - const float y_scale = (*matrix)(3,1) / -(y_0*y_0+y_1*y_1+y_2*y_2); + const float y_len2 = (y_0*y_0+y_1*y_1+y_2*y_2); + const float z_0 = (*matrix)(0,2); const float z_1 = (*matrix)(1,2); const float z_2 = (*matrix)(2,2); - const float z_scale = (*matrix)(3,2) / -(z_0*z_0+z_1*z_1+z_2*z_2); + const float z_len2 = (z_0*z_0+z_1*z_1+z_2*z_2); + + + bool useFastPath = (osg::equivalent(x_len2,y_len2) && + osg::equivalent(x_len2,z_len2) && + osg::equivalent(y_len2,z_len2)); + + // std::cout<<"x_len2 = "<index(pos)].ptr()); - else glVertex3fv((*_vertices)[pos].ptr()); + if (_indices) _vertices->accept(_indices->index(pos),*this); + else _vertices->accept(pos,*this); } - const Vec3Array* _vertices; - const IndexArray* _indices; + virtual void apply(const Vec2& v) { glVertex2fv(v.ptr()); } + virtual void apply(const Vec3& v) { glVertex3fv(v.ptr()); } + virtual void apply(const Vec4& v) { glVertex4fv(v.ptr()); } + + const Array* _vertices; + const IndexArray* _indices; }; class DrawNormal @@ -813,7 +817,7 @@ void Geometry::drawImplementation(State& state) const // if( _vertexArray.valid() ) - state.setVertexPointer(3,GL_FLOAT,0,_vertexArray->getDataPointer()); + state.setVertexPointer(_vertexArray->getDataSize(),_vertexArray->getDataType(),0,_vertexArray->getDataPointer()); else state.disableVertexPointer(); @@ -1547,13 +1551,26 @@ void Geometry::accept(ConstAttributeFunctor& af) const void Geometry::accept(PrimitiveFunctor& functor) const { - if (!_vertexArray.valid() || _vertexArray->empty()) return; - - + if (!_vertexArray.valid() || _vertexArray->getNumElements()==0) return; + if (!_vertexIndices.valid()) { - functor.setVertexArray(_vertexArray->size(),&(_vertexArray->front())); - + switch(_vertexArray->getType()) + { + case(Array::Vec2ArrayType): + functor.setVertexArray(_vertexArray->getNumElements(),static_cast(_vertexArray->getDataPointer())); + break; + case(Array::Vec3ArrayType): + functor.setVertexArray(_vertexArray->getNumElements(),static_cast(_vertexArray->getDataPointer())); + break; + case(Array::Vec4ArrayType): + functor.setVertexArray(_vertexArray->getNumElements(),static_cast(_vertexArray->getDataPointer())); + break; + default: + notify(WARN)<<"Warning: Geometry::accept(PrimtiveFunctor&) cannot handle Vertex Array type"<<_vertexArray->getType()<getType(); + switch(type) + { + case(Array::Vec2ArrayType): + vec2Array = static_cast(_vertexArray.get()); + break; + case(Array::Vec3ArrayType): + vec3Array = static_cast(_vertexArray.get()); + break; + case(Array::Vec4ArrayType): + vec4Array = static_cast(_vertexArray.get()); + break; + default: + notify(WARN)<<"Warning: Geometry::accept(PrimtiveFunctor&) cannot handle Vertex Array type"<<_vertexArray->getType()<index(vindex)]); + switch(type) + { + case(Array::Vec2ArrayType): + functor.vertex((*vec2Array)[_vertexIndices->index(vindex)]); + break; + case(Array::Vec3ArrayType): + functor.vertex((*vec3Array)[_vertexIndices->index(vindex)]); + break; + case(Array::Vec4ArrayType): + functor.vertex((*vec4Array)[_vertexIndices->index(vindex)]); + break; + default: + break; + } + } functor.end(); @@ -1601,7 +1653,20 @@ void Geometry::accept(PrimitiveFunctor& functor) const for(GLsizei primCount=0;primCount<*primItr;++primCount) { - functor.vertex((*_vertexArray)[_vertexIndices->index(vindex)]); + switch(type) + { + case(Array::Vec2ArrayType): + functor.vertex((*vec2Array)[_vertexIndices->index(vindex)]); + break; + case(Array::Vec3ArrayType): + functor.vertex((*vec3Array)[_vertexIndices->index(vindex)]); + break; + case(Array::Vec4ArrayType): + functor.vertex((*vec4Array)[_vertexIndices->index(vindex)]); + break; + default: + break; + } ++vindex; } @@ -1621,7 +1686,20 @@ void Geometry::accept(PrimitiveFunctor& functor) const ++primCount,++primItr) { unsigned int vindex=*primItr; - functor.vertex((*_vertexArray)[_vertexIndices->index(vindex)]); + switch(type) + { + case(Array::Vec2ArrayType): + functor.vertex((*vec2Array)[_vertexIndices->index(vindex)]); + break; + case(Array::Vec3ArrayType): + functor.vertex((*vec3Array)[_vertexIndices->index(vindex)]); + break; + case(Array::Vec4ArrayType): + functor.vertex((*vec4Array)[_vertexIndices->index(vindex)]); + break; + default: + break; + } } functor.end(); @@ -1637,7 +1715,20 @@ void Geometry::accept(PrimitiveFunctor& functor) const ++primItr) { unsigned int vindex=*primItr; - functor.vertex((*_vertexArray)[_vertexIndices->index(vindex)]); + switch(type) + { + case(Array::Vec2ArrayType): + functor.vertex((*vec2Array)[_vertexIndices->index(vindex)]); + break; + case(Array::Vec3ArrayType): + functor.vertex((*vec3Array)[_vertexIndices->index(vindex)]); + break; + case(Array::Vec4ArrayType): + functor.vertex((*vec4Array)[_vertexIndices->index(vindex)]); + break; + default: + break; + } } functor.end(); @@ -1653,7 +1744,20 @@ void Geometry::accept(PrimitiveFunctor& functor) const ++primItr) { unsigned int vindex=*primItr; - functor.vertex((*_vertexArray)[_vertexIndices->index(vindex)]); + switch(type) + { + case(Array::Vec2ArrayType): + functor.vertex((*vec2Array)[_vertexIndices->index(vindex)]); + break; + case(Array::Vec3ArrayType): + functor.vertex((*vec3Array)[_vertexIndices->index(vindex)]); + break; + case(Array::Vec4ArrayType): + functor.vertex((*vec4Array)[_vertexIndices->index(vindex)]); + break; + default: + break; + } } functor.end(); @@ -1742,7 +1846,7 @@ void Geometry::computeCorrectBindingsAndArraySizes() { if (verifyBindings()) return; - if (!_vertexArray.valid() || _vertexArray->empty()) + if (!_vertexArray.valid() || _vertexArray->getNumElements()==0) { // no vertex array so switch everything off. diff --git a/src/osg/Image.cpp b/src/osg/Image.cpp index b88095b87..765696bb5 100644 --- a/src/osg/Image.cpp +++ b/src/osg/Image.cpp @@ -142,6 +142,7 @@ unsigned int Image::computeNumComponents(GLenum format) switch(format) { case(GL_COMPRESSED_RGB_S3TC_DXT1_EXT): return 3; + case(GL_COMPRESSED_RGBA_S3TC_DXT1_EXT): return 4; case(GL_COMPRESSED_RGBA_S3TC_DXT3_EXT): return 4; case(GL_COMPRESSED_RGBA_S3TC_DXT5_EXT): return 4; case(GL_COLOR_INDEX): return 1; @@ -157,7 +158,11 @@ unsigned int Image::computeNumComponents(GLenum format) case(GL_BGRA): return 4; case(GL_LUMINANCE): return 1; case(GL_LUMINANCE_ALPHA): return 2; - default: return 0; + default: + { + std::cout<<"error format = "< +using namespace std; using namespace osg; State::State() @@ -726,7 +727,7 @@ bool State::checkGLErrors(StateAttribute::GLMode mode) const GLenum errorNo = glGetError(); if (errorNo!=GL_NO_ERROR) { - osg::notify(WARN)<<"Warning: detected OpenGL error '"<data()) diff --git a/src/osgDB/Registry.cpp b/src/osgDB/Registry.cpp index 43e7dd9a0..063113ae2 100644 --- a/src/osgDB/Registry.cpp +++ b/src/osgDB/Registry.cpp @@ -51,7 +51,8 @@ Registry* Registry::instance() // definition of the Registry Registry::Registry() { - notify(INFO) << "Constructing osg::Registry"<accept(*this); } } diff --git a/src/osgPlugins/3dc/ReaderWriter3DC.cpp b/src/osgPlugins/3dc/ReaderWriter3DC.cpp index bee225f25..53b6ab832 100644 --- a/src/osgPlugins/3dc/ReaderWriter3DC.cpp +++ b/src/osgPlugins/3dc/ReaderWriter3DC.cpp @@ -105,7 +105,8 @@ class ReaderWriter3DC : public osgDB::ReaderWriter //std::cout <setUseDisplayList(false); geometry->setVertexArray(vertices); geometry->setNormalArray(normals); geometry->setNormalBinding(osg::Geometry::BIND_PER_VERTEX); diff --git a/src/osgPlugins/dds/ReaderWriterDDS.cpp b/src/osgPlugins/dds/ReaderWriterDDS.cpp index ee6bdb76f..867b66f97 100644 --- a/src/osgPlugins/dds/ReaderWriterDDS.cpp +++ b/src/osgPlugins/dds/ReaderWriterDDS.cpp @@ -156,8 +156,11 @@ osg::Image* ReadDDSFile(const char *filename) fread(&ddsd, sizeof(ddsd), 1, fp); // Read image data. - unsigned int size = ddsd.dwMipMapCount > 1 ? ddsd.dwLinearSize * 2 : ddsd.dwLinearSize; - unsigned char* imageData = new unsigned char [size]; + unsigned int size = ddsd.dwMipMapCount > 1 ? ddsd.dwLinearSize * (ddsd.ddpfPixelFormat.dwFourCC==FOURCC_DXT1 ? 2: 4) : ddsd.dwLinearSize; + //###################unsigned int size = ddsd.dwMipMapCount > 1 ? ddsd.dwLinearSize * 2 : ddsd.dwLinearSize; + + + unsigned char* imageData = new unsigned char [size]; fread(imageData, 1, size, fp); // Close the file. fclose(fp); @@ -206,7 +209,8 @@ osg::Image* ReadDDSFile(const char *filename) else { internalFormat = GL_COMPRESSED_RGB_S3TC_DXT1_EXT; - pixelFormat = GL_COMPRESSED_RGB_S3TC_DXT1_EXT; + //#######################pixelFormat = GL_COMPRESSED_RGB_S3TC_DXT1_EXT; + pixelFormat = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; } break; case FOURCC_DXT3: diff --git a/src/osgPlugins/flt/GeoSetBuilder.cpp b/src/osgPlugins/flt/GeoSetBuilder.cpp index e26eca21e..eef0d269e 100644 --- a/src/osgPlugins/flt/GeoSetBuilder.cpp +++ b/src/osgPlugins/flt/GeoSetBuilder.cpp @@ -113,7 +113,7 @@ void DynGeoSet::addToGeometry(osg::Geometry* geom) { int indexBase = 0; - osg::Vec3Array* vertices = geom->getVertexArray(); + osg::Vec3Array* vertices = dynamic_cast(geom->getVertexArray()); if (vertices) { indexBase = vertices->size(); diff --git a/src/osgPlugins/flt/flt2osg.cpp b/src/osgPlugins/flt/flt2osg.cpp index 5108eca81..e336f5cbc 100644 --- a/src/osgPlugins/flt/flt2osg.cpp +++ b/src/osgPlugins/flt/flt2osg.cpp @@ -1838,11 +1838,25 @@ void ConvertFromFLT::visitLightPoint(GeoSetBuilder* pBuilder, LightPointRecord* osg::Point* point = new osg::Point; if (point) { + /* point->setSize(pSLightPoint->sfSize); stateSet->setAttributeAndModes( point, osg::StateAttribute::ON ); // point->setFadeThresholdSize(const float fadeThresholdSize); // point->setDistanceAttenuation(const Vec3& distanceAttenuation); // point->setStateSetModes(*stateSet, osg::StateAttribute::ON); // GL_POINT_SMOOTH + */ + //change to: + point->setSize(pSLightPoint->afActualPixelSize); + point->setFadeThresholdSize(pSLightPoint->sfTranspFalloff); + //numbers that are going to appear are "experimental" + point->setDistanceAttenuation(osg::Vec3(0.0001, 0.0005, 0.00000025)); + + point->setMinSize(pSLightPoint->sfMinPixelSize); + point->setMaxSize(pSLightPoint->sfMaxPixelSize); + + stateSet->setAttributeAndModes( point, osg::StateAttribute::ON ); + stateSet->setMode(GL_POINT_SMOOTH, osg::StateAttribute::ON); + stateSet->setAttributeAndModes(new osg::BlendFunc, osg::StateAttribute::ON); } diff --git a/src/osgPlugins/freetype/FreeTypeFont.cpp b/src/osgPlugins/freetype/FreeTypeFont.cpp index d869b6342..c38572976 100644 --- a/src/osgPlugins/freetype/FreeTypeFont.cpp +++ b/src/osgPlugins/freetype/FreeTypeFont.cpp @@ -12,7 +12,7 @@ */ #include "FreeTypeFont.h" -#include FT_GLYPH_H +//#include FT_GLYPH_H #include #include @@ -140,7 +140,7 @@ osg::Vec2 FreeTypeFont::getKerning(unsigned int leftcharcode,unsigned int rightc FT_Error error = FT_Get_Kerning( _face, // handle to face object left, // left glyph index right, // right glyph index - ft_kerning_default, // kerning mode + FT_KERNING_UNFITTED, // kerning mode &kerning ); // target vector if (error) diff --git a/src/osgPlugins/ive/AnimationPathCallback.cpp b/src/osgPlugins/ive/AnimationPathCallback.cpp index cac929188..ebf80fef5 100644 --- a/src/osgPlugins/ive/AnimationPathCallback.cpp +++ b/src/osgPlugins/ive/AnimationPathCallback.cpp @@ -36,10 +36,15 @@ void AnimationPathCallback::write(DataOutputStream* out){ out->writeDouble(_firstTime); out->writeDouble(_animationTime); // Write animationpath if any - out->writeInt((int)getAnimationPath()); - if(getAnimationPath()){ + if(getAnimationPath()) + { + out->writeInt(1); // true we have an animation path. ((ive::AnimationPath*)(getAnimationPath()))->write(out); } + else + { + out->writeInt(0); // false we don't have an animation path. + } } void AnimationPathCallback::read(DataInputStream* in){ @@ -61,7 +66,8 @@ void AnimationPathCallback::read(DataInputStream* in){ _firstTime = in->readDouble(); _animationTime = in->readDouble(); // Read animationpath if any - if(in->readInt()){ + if(in->readInt()) + { osg::AnimationPath* path = new osg::AnimationPath(); ((ive::AnimationPath*)(path))->read(in); setAnimationPath(path); diff --git a/src/osgPlugins/ive/DataInputStream.cpp b/src/osgPlugins/ive/DataInputStream.cpp index 848bedf95..6c03c9b68 100644 --- a/src/osgPlugins/ive/DataInputStream.cpp +++ b/src/osgPlugins/ive/DataInputStream.cpp @@ -1,77 +1,113 @@ /********************************************************************** * - * FILE: DataInputStream.cpp + * FILE: DataInputStream.cpp * - * DESCRIPTION: Implements methods to read simpel datatypes from an - * input stream. + * DESCRIPTION: Implements methods to read simpel datatypes from an + * input stream. * - * CREATED BY: Rune Schmidt Jensen + * CREATED BY: Rune Schmidt Jensen * - * HISTORY: Created 11.03.2003 + * HISTORY: Created 11.03.2003 * - * Copyright 2003 VR-C + * Copyright 2003 VR-C **********************************************************************/ #include "DataInputStream.h" #include "StateSet.h" +#include "BlendFunc.h" +#include "Material.h" +#include "CullFace.h" +#include "PolygonOffset.h" +#include "ShadeModel.h" +#include "Point.h" +#include "Texture2D.h" +#include "TextureCubeMap.h" +#include "TexEnv.h" +#include "TexEnvCombine.h" +#include "TexGen.h" + +#include "Group.h" +#include "MatrixTransform.h" +#include "Geode.h" +#include "LightSource.h" +#include "Billboard.h" +#include "Sequence.h" +#include "LOD.h" +//#include "ViewPoint.h" +#include "PositionAttitudeTransform.h" +#include "Transform.h" +#include "Switch.h" +#include "OccluderNode.h" +#include "Impostor.h" + +#include "Geometry.h" + #include using namespace ive; using namespace std; DataInputStream::DataInputStream(std::istream* istream){ - _istream = istream; - _peeking = false; - _peekValue = 0; + _istream = istream; + _peeking = false; + _peekValue = 0; - if(!istream){ - throw Exception("DataInputStream::DataInputStream(): null pointer exception in argument."); - } + if(!istream){ + throw Exception("DataInputStream::DataInputStream(): null pointer exception in argument."); + } - _version = readInt(); + _version = readInt(); - // Are we trying to open a binary .ive file which version are newer than this library. - if(_version>VERSION){ - throw Exception("DataInputStream::DataInputStream(): The version found in the file is newer than this library can handle."); - } + // Are we trying to open a binary .ive file which version are newer than this library. + if(_version>VERSION){ + throw Exception("DataInputStream::DataInputStream(): The version found in the file is newer than this library can handle."); + } } DataInputStream::~DataInputStream(){} bool DataInputStream::readBool(){ - bool b; - _istream->read((char*)&b, BOOLSIZE); - if (_istream->rdstate() & _istream->failbit) - throw Exception("DataInputStream::readBool(): Failed to read boolean value."); - return b; + bool b; + _istream->read((char*)&b, BOOLSIZE); + if (_istream->rdstate() & _istream->failbit) + throw Exception("DataInputStream::readBool(): Failed to read boolean value."); + return b; } char DataInputStream::readChar(){ - char c; - _istream->read(&c, CHARSIZE); - if (_istream->rdstate() & _istream->failbit) - throw Exception("DataInputStream::readChar(): Failed to read char value."); - return c; + char c; + _istream->read(&c, CHARSIZE); + if (_istream->rdstate() & _istream->failbit) + throw Exception("DataInputStream::readChar(): Failed to read char value."); + return c; } unsigned short DataInputStream::readUShort(){ - unsigned short s; - _istream->read((char*)&s, SHORTSIZE); - if (_istream->rdstate() & _istream->failbit) - throw Exception("DataInputStream::readUShort(): Failed to read unsigned short value."); - return s; + unsigned short s; + _istream->read((char*)&s, SHORTSIZE); + if (_istream->rdstate() & _istream->failbit) + throw Exception("DataInputStream::readUShort(): Failed to read unsigned short value."); + return s; +} + +unsigned int DataInputStream::readUInt(){ + unsigned int s; + _istream->read((char*)&s, INTSIZE); + if (_istream->rdstate() & _istream->failbit) + throw Exception("DataInputStream::readUInt(): Failed to read unsigned int value."); + return s; } int DataInputStream::readInt(){ - if(_peeking){ - _peeking = false; - return _peekValue; - } - int i; - _istream->read((char*)&i, INTSIZE); - if (_istream->rdstate() & _istream->failbit) - throw Exception("DataInputStream::readInt(): Failed to read int value."); - return i; + if(_peeking){ + _peeking = false; + return _peekValue; + } + int i; + _istream->read((char*)&i, INTSIZE); + if (_istream->rdstate() & _istream->failbit) + throw Exception("DataInputStream::readInt(): Failed to read int value."); + return i; } /** @@ -80,247 +116,476 @@ int DataInputStream::readInt(){ * return the same integer. */ int DataInputStream::peekInt(){ - if(_peeking){ - return _peekValue; - } - _peekValue = readInt(); - _peeking = true; - return _peekValue; + if(_peeking){ + return _peekValue; + } + _peekValue = readInt(); + _peeking = true; + return _peekValue; } float DataInputStream::readFloat(){ - float f; - _istream->read((char*)&f, FLOATSIZE); - if (_istream->rdstate() & _istream->failbit) - throw Exception("DataInputStream::readFloat(): Failed to read float value."); - return f; + float f; + _istream->read((char*)&f, FLOATSIZE); + if (_istream->rdstate() & _istream->failbit) + throw Exception("DataInputStream::readFloat(): Failed to read float value."); + return f; } long DataInputStream::readLong(){ - long l; - _istream->read((char*)&l, LONGSIZE); - if (_istream->rdstate() & _istream->failbit) - throw Exception("DataInputStream::readLong(): Failed to read long value."); - return l; + long l; + _istream->read((char*)&l, LONGSIZE); + if (_istream->rdstate() & _istream->failbit) + throw Exception("DataInputStream::readLong(): Failed to read long value."); + return l; } double DataInputStream::readDouble(){ - double d; - _istream->read((char*)&d, DOUBLESIZE); - if (_istream->rdstate() & _istream->failbit) - throw Exception("DataInputStream::readDouble(): Failed to read double value."); - return d; + double d; + _istream->read((char*)&d, DOUBLESIZE); + if (_istream->rdstate() & _istream->failbit) + throw Exception("DataInputStream::readDouble(): Failed to read double value."); + return d; } std::string DataInputStream::readString(){ - std::string s; - int size = readInt(); - s.resize(size); - _istream->read((char*)s.c_str(), size); - if (_istream->rdstate() & _istream->failbit) - throw Exception("DataInputStream::readString(): Failed to read string value."); - return s; + std::string s; + int size = readInt(); + s.resize(size); + _istream->read((char*)s.c_str(), size); + if (_istream->rdstate() & _istream->failbit) + throw Exception("DataInputStream::readString(): Failed to read string value."); + return s; } void DataInputStream::readCharArray(char* data, int size){ - _istream->read(data, size); - if (_istream->rdstate() & _istream->failbit) - throw Exception("DataInputStream::readCharArray(): Failed to read char value."); + _istream->read(data, size); + if (_istream->rdstate() & _istream->failbit) + throw Exception("DataInputStream::readCharArray(): Failed to read char value."); } osg::Vec2 DataInputStream::readVec2(){ - osg::Vec2 v; - v.set(readFloat(), readFloat()); - return v; + osg::Vec2 v; + v.x()=readFloat(); + v.y()=readFloat(); + return v; } osg::Vec3 DataInputStream::readVec3(){ - osg::Vec3 v; - v.set(readFloat(),readFloat(),readFloat()); - return v; + osg::Vec3 v; + v.x()=readFloat(); + v.y()=readFloat(); + v.z()=readFloat(); + return v; } osg::Vec4 DataInputStream::readVec4(){ - osg::Vec4 v; - v.set(readFloat(), readFloat(), readFloat(), readFloat()); - return v; + osg::Vec4 v; + v.x()=readFloat(); + v.y()=readFloat(); + v.z()=readFloat(); + v.w()=readFloat(); + return v; } osg::UByte4 DataInputStream::readUByte4(){ - osg::UByte4 v; - v.set(readChar(), readChar(), readChar(), readChar()); - return v; + osg::UByte4 v; + v.r()=readChar(); + v.g()=readChar(); + v.b()=readChar(); + v.a()=readChar(); + return v; } osg::Quat DataInputStream::readQuat(){ - osg::Quat q; - q.set(readFloat(), readFloat(), readFloat(), readFloat()); - return q; + osg::Quat q; + q.set(readFloat(), readFloat(), readFloat(), readFloat()); + return q; } -/** - * - */ -osg::Image* DataInputStream::readImage(std::string filename){ - // If image is already read and in list - // then just return pointer to this. - for(ImageList::iterator mitr=_imageList.begin(); - mitr!=_imageList.end(); ++mitr){ - if(mitr->first.compare(filename) == 0){ - return mitr->second.get(); - } - } - // Image is not in list. - // Read it from disk, - osg::Image* image = osgDB::readImageFile(filename.c_str()); - // add it to the imageList, - _imageList.push_back(ImagePair(filename, image)); - // and return image pointer. - return image; -} - -osg::StateSet* DataInputStream::readStateSet(){ - // Read statesets unique ID. - int id = readInt(); - // See if stateset is already in the list. - for(StateSetList::iterator itr=_statesetList.begin(); - itr!=_statesetList.end(); ++itr){ - if(itr->first == id){ - return itr->second.get(); - } - } - // StateSet is not in list. - // Create a new stateset, - osg::StateSet* stateset = new osg::StateSet(); - // read its properties from stream - ((ive::StateSet*)(stateset))->read(this); - // and add it to the stateset list, - _statesetList.push_back(StateSetPair(id, stateset)); - return stateset; -} osg::Geometry::AttributeBinding DataInputStream::readBinding(){ - char c = readChar(); - switch((int)c){ - case 0: return osg::Geometry::BIND_OFF; - case 1: return osg::Geometry::BIND_OVERALL; - case 2: return osg::Geometry::BIND_PER_PRIMITIVE; - case 3: return osg::Geometry::BIND_PER_PRIMITIVE_SET; - case 4: return osg::Geometry::BIND_PER_VERTEX; - default: throw Exception("Unknown binding type in DataInputStream::readBinding()"); - } + char c = readChar(); + switch((int)c){ + case 0: return osg::Geometry::BIND_OFF; + case 1: return osg::Geometry::BIND_OVERALL; + case 2: return osg::Geometry::BIND_PER_PRIMITIVE; + case 3: return osg::Geometry::BIND_PER_PRIMITIVE_SET; + case 4: return osg::Geometry::BIND_PER_VERTEX; + default: throw Exception("Unknown binding type in DataInputStream::readBinding()"); + } } osg::Array* DataInputStream::readArray(){ - char c = readChar(); - switch((int)c){ - case 0: return readIntArray(); - case 1: return readUByteArray(); - case 2: return readUShortArray(); - case 3: return readUIntArray(); - case 4: return readUByte4Array(); - case 5: return readFloatArray(); - case 6: return readVec2Array(); - case 7: return readVec3Array(); - case 8: return readVec4Array(); - default: throw Exception("Unknown array type in DataInputStream::readArray()"); - } + char c = readChar(); + switch((int)c){ + case 0: return readIntArray(); + case 1: return readUByteArray(); + case 2: return readUShortArray(); + case 3: return readUIntArray(); + case 4: return readUByte4Array(); + case 5: return readFloatArray(); + case 6: return readVec2Array(); + case 7: return readVec3Array(); + case 8: return readVec4Array(); + default: throw Exception("Unknown array type in DataInputStream::readArray()"); + } } osg::IntArray* DataInputStream::readIntArray(){ - int size = readInt(); - osg::IntArray* a = new osg::IntArray(); - a->reserve(size); - for(int i =0; ipush_back(readInt()); - } - return a; + int size = readInt(); + osg::IntArray* a = new osg::IntArray(size); + + _istream->read((char*)&((*a)[0]), INTSIZE*size); + if (_istream->rdstate() & _istream->failbit) + throw Exception("DataInputStream::readIntArray(): Failed to read Int array."); + +// a->reserve(size); +// for(int i =0; ipush_back(readInt()); +// } + return a; } osg::UByteArray* DataInputStream::readUByteArray(){ - int size = readInt(); - osg::UByteArray* a = new osg::UByteArray(); - a->reserve(size); - for(int i =0; ipush_back(readChar()); - } - return a; + int size = readInt(); + osg::UByteArray* a = new osg::UByteArray(size); + + _istream->read((char*)&((*a)[0]), CHARSIZE*size); + if (_istream->rdstate() & _istream->failbit) + throw Exception("DataInputStream::readUByteArray(): Failed to read UByte array."); + +// a->reserve(size); +// for(int i =0; ipush_back(readChar()); +// } + return a; } osg::UShortArray* DataInputStream::readUShortArray(){ - int size = readInt(); - osg::UShortArray* a = new osg::UShortArray(); - a->reserve(size); - for(int i =0; ipush_back(readUShort()); - } - return a; + int size = readInt(); + osg::UShortArray* a = new osg::UShortArray(size); + + _istream->read((char*)&((*a)[0]), SHORTSIZE*size); + if (_istream->rdstate() & _istream->failbit) + throw Exception("DataInputStream::readUShortArray(): Failed to read UShort array."); +// +// a->reserve(size); +// for(int i =0; ipush_back(readUShort()); +// } + return a; } osg::UIntArray* DataInputStream::readUIntArray(){ - int size = readInt(); - osg::UIntArray* a = new osg::UIntArray(); - a->reserve(size); - for(int i =0; ipush_back((unsigned int)readInt()); - } - return a; + int size = readInt(); + osg::UIntArray* a = new osg::UIntArray(size); + + _istream->read((char*)&((*a)[0]), INTSIZE*size); + if (_istream->rdstate() & _istream->failbit) + throw Exception("DataInputStream::readUIntArray(): Failed to read UInt array."); +// +// a->reserve(size); +// for(int i =0; ipush_back((unsigned int)readInt()); +// } + return a; } osg::UByte4Array* DataInputStream::readUByte4Array(){ - int size = readInt(); - osg::UByte4Array* a = new osg::UByte4Array(); - a->reserve(size); - for(int i =0; ipush_back(readUByte4()); - } - return a; + int size = readInt(); + osg::UByte4Array* a = new osg::UByte4Array(size); + + _istream->read((char*)&((*a)[0]), INTSIZE*size); + if (_istream->rdstate() & _istream->failbit) + throw Exception("DataInputStream::readUbyte4Array(): Failed to read UByte4 array."); + +// a->reserve(size); +// for(int i =0; ipush_back(readUByte4()); +// } + return a; } osg::FloatArray* DataInputStream::readFloatArray(){ - int size = readInt(); - osg::FloatArray* a = new osg::FloatArray(); - a->reserve(size); - for(int i =0; ipush_back(readFloat()); - } - return a; + int size = readInt(); + osg::FloatArray* a = new osg::FloatArray(size); + + _istream->read((char*)&((*a)[0]), FLOATSIZE*size); + if (_istream->rdstate() & _istream->failbit) + throw Exception("DataInputStream::readFloatArray(): Failed to read float array."); + +// a->reserve(size); +// for(int i =0; ipush_back(readFloat()); +// } + return a; } osg::Vec2Array* DataInputStream::readVec2Array(){ - int size = readInt(); - osg::Vec2Array* a = new osg::Vec2Array(size); - for(int i = 0; i < size; i++){ - (*a)[i] = (readVec2()); - } - return a; + int size = readInt(); + osg::Vec2Array* a = new osg::Vec2Array(size); + + _istream->read((char*)&((*a)[0]), FLOATSIZE*2*size); + if (_istream->rdstate() & _istream->failbit) + throw Exception("DataInputStream::readVec2Array(): Failed to read Vec2 array."); + +// for(int i = 0; i < size; i++){ +// (*a)[i] = (readVec2()); +// } + return a; } osg::Vec3Array* DataInputStream::readVec3Array(){ - int size = readInt(); - osg::Vec3Array* a = new osg::Vec3Array(size); - for(int i = 0; i < size; i++){ - (*a)[i] = readVec3(); - } - return a; + int size = readInt(); + osg::Vec3Array* a = new osg::Vec3Array(size); + + _istream->read((char*)&((*a)[0]), FLOATSIZE*3*size); + if (_istream->rdstate() & _istream->failbit) + throw Exception("DataInputStream::readVec3Array(): Failed to read Vec3 array."); + +// for(int i = 0; i < size; i++){ +// (*a)[i] = readVec3(); +// } + return a; } osg::Vec4Array* DataInputStream::readVec4Array(){ - int size = readInt(); - osg::Vec4Array* a = new osg::Vec4Array(size); - for(int i = 0; i < size; i++){ - (*a)[i] = (readVec4()); - } - return a; + int size = readInt(); + osg::Vec4Array* a = new osg::Vec4Array(size); + + _istream->read((char*)&((*a)[0]), FLOATSIZE*4*size); + if (_istream->rdstate() & _istream->failbit) + throw Exception("DataInputStream::readVec4Array(): Failed to read Vec4 array."); + + +// for(int i = 0; i < size; i++){ +// (*a)[i] = (readVec4()); +// } + + + return a; } osg::Matrix DataInputStream::readMatrix(){ - osg::Matrix mat; - float* p = mat.ptr(); - for(int i=0;i<16;i++){ - p[i] = readFloat(); - } - return mat; + osg::Matrix mat; + _istream->read((char*)(mat.ptr()), FLOATSIZE*16); + if (_istream->rdstate() & _istream->failbit) + throw Exception("DataInputStream::readMatrix(): Failed to read Matrix array."); +// float* p = mat.ptr(); +// for(int i=0;i<16;i++){ +// p[i] = readFloat(); +// } + return mat; +} + +osg::Image* DataInputStream::readImage(std::string filename) +{ + // If image is already read and in list + // then just return pointer to this. + ImageMap::iterator mitr=_imageMap.find(filename); + if (mitr!=_imageMap.end()) mitr->second.get(); + + // Image is not in list. + // Read it from disk, + osg::Image* image = osgDB::readImageFile(filename.c_str()); + + // add it to the imageList, + _imageMap[filename] = image; + // and return image pointer. + return image; +} + +osg::StateSet* DataInputStream::readStateSet() +{ + // Read statesets unique ID. + int id = readInt(); + // See if stateset is already in the list. + StateSetMap::iterator itr= _statesetMap.find(id); + if (itr!=_statesetMap.end()) return itr->second.get(); + + // StateSet is not in list. + // Create a new stateset, + osg::StateSet* stateset = new osg::StateSet(); + + // read its properties from stream + ((ive::StateSet*)(stateset))->read(this); + + // and add it to the stateset map, + _statesetMap[id] = stateset; + + return stateset; +} + +osg::StateAttribute* DataInputStream::readStateAttribute() +{ + // Read stateattributes unique ID. + int id = readInt(); + // See if stateattribute is already in the list. + StateAttributeMap::iterator itr= _stateAttributeMap.find(id); + if (itr!=_stateAttributeMap.end()) return itr->second.get(); + + // stateattribute is not in list. + // Create a new stateattribute, + + + osg::StateAttribute* attribute; + int attributeID = peekInt(); + if(attributeID == IVEBLENDFUNC){ + attribute = new osg::BlendFunc(); + ((ive::BlendFunc*)(attribute))->read(this); + } + else if(attributeID == IVEMATERIAL){ + attribute = new osg::Material(); + ((ive::Material*)(attribute))->read(this); + } + else if(attributeID == IVECULLFACE){ + attribute = new osg::CullFace(); + ((ive::CullFace*)(attribute))->read(this); + } + else if(attributeID == IVEPOLYGONOFFSET){ + attribute = new osg::PolygonOffset(); + ((ive::PolygonOffset*)(attribute))->read(this); + } + else if(attributeID == IVESHADEMODEL){ + attribute = new osg::ShadeModel(); + ((ive::ShadeModel*)(attribute))->read(this); + } + else if(attributeID == IVEPOINT){ + attribute = new osg::Point(); + ((ive::Point*)(attribute))->read(this); + } + else if(attributeID == IVETEXTURE2D){ + attribute = new osg::Texture2D(); + ((ive::Texture2D*)(attribute))->read(this); + } + else if(attributeID == IVETEXTURECUBEMAP){ + attribute = new osg::TextureCubeMap(); + ((ive::TextureCubeMap*)(attribute))->read(this); + } + else if(attributeID == IVETEXENV){ + attribute = new osg::TexEnv(); + ((ive::TexEnv*)(attribute))->read(this); + } + else if(attributeID == IVETEXENVCOMBINE){ + attribute = new osg::TexEnvCombine(); + ((ive::TexEnvCombine*)(attribute))->read(this); + } + else if(attributeID == IVETEXGEN){ + attribute = new osg::TexGen(); + ((ive::TexGen*)(attribute))->read(this); + } + else{ + throw Exception("Unkown StateAttribute in StateSet::read()"); + } + + // and add it to the stateattribute map, + _stateAttributeMap[id] = attribute; + + return attribute; +} + +osg::Drawable* DataInputStream::readDrawable() +{ + // Read stateattributes unique ID. + int id = readInt(); + // See if stateattribute is already in the list. + DrawableMap::iterator itr= _drawableMap.find(id); + if (itr!=_drawableMap.end()) return itr->second.get(); + + // stateattribute is not in list. + // Create a new stateattribute, + + int drawableTypeID = peekInt(); + osg::Drawable* drawable; + if(drawableTypeID == IVEGEOMETRY){ + drawable = new osg::Geometry(); + ((Geometry*)(drawable))->read(this); + } + else + throw Exception("Unknown drawable drawableTypeIDentification in Geode::read()"); + + + // and add it to the stateattribute map, + _drawableMap[id] = drawable; + + return drawable; +} + +osg::Node* DataInputStream::readNode() +{ + // Read node unique ID. + int id = readInt(); + // See if node is already in the list. + NodeMap::iterator itr= _nodeMap.find(id); + if (itr!=_nodeMap.end()) return itr->second.get(); + + // stateattribute is not in list. + // Create a new node, + + osg::Node* node; + int nodeTypeID= peekInt(); + + if(nodeTypeID== IVEMATRIXTRANSFORM){ + node = new osg::MatrixTransform(); + ((ive::MatrixTransform*)(node))->read(this); + } +// else if(nodeTypeID== IVEVIEWPOINT){ +// node = new osgfIVE::ViewPoint(); +// ((ive::ViewPoint*)(node))->read(this); +// } + else if(nodeTypeID== IVEPOSITIONATTITUDETRANSFORM){ + node = new osg::PositionAttitudeTransform(); + ((ive::PositionAttitudeTransform*)(node))->read(this); + } + else if(nodeTypeID== IVETRANSFORM){ + node = new osg::Transform(); + ((ive::Transform*)(node))->read(this); + } + else if(nodeTypeID== IVELIGHTSOURCE){ + node = new osg::LightSource(); + ((ive::LightSource*)(node))->read(this); + } + else if(nodeTypeID== IVESEQUENCE){ + node = new osg::Sequence(); + ((ive::Sequence*)(node))->read(this); + } + else if(nodeTypeID== IVELOD){ + node = new osg::LOD(); + ((ive::LOD*)(node))->read(this); + } + else if(nodeTypeID== IVESWITCH){ + node = new osg::Switch(); + ((ive::Switch*)(node))->read(this); + } + else if(nodeTypeID== IVEIMPOSTOR){ + node = new osg::Impostor(); + ((ive::Impostor*)(node))->read(this); + } + else if(nodeTypeID== IVEOCCLUDERNODE){ + node = new osg::OccluderNode(); + ((ive::OccluderNode*)(node))->read(this); + } + else if(nodeTypeID== IVEGROUP){ + node = new osg::Group(); + ((ive::Group*)(node))->read(this); + } + else if(nodeTypeID== IVEBILLBOARD){ + node = new osg::Billboard(); + ((ive::Billboard*)(node))->read(this); + } + else if(nodeTypeID== IVEGEODE){ + node = new osg::Geode(); + ((ive::Geode*)(node))->read(this); + } + else{ + throw Exception("Unknown node identification in DataInputStream::readNode()"); + } + + // and add it to the stateattribute map, + _nodeMap[id] = node; + + return node; } diff --git a/src/osgPlugins/ive/DataInputStream.h b/src/osgPlugins/ive/DataInputStream.h index a7ba42c5a..a0f57b2a4 100644 --- a/src/osgPlugins/ive/DataInputStream.h +++ b/src/osgPlugins/ive/DataInputStream.h @@ -32,6 +32,7 @@ public: bool readBool(); char readChar(); unsigned short readUShort(); + unsigned int readUInt(); int readInt(); int peekInt(); float readFloat(); @@ -46,8 +47,6 @@ public: osg::Quat readQuat(); osg::Matrix readMatrix(); osg::Geometry::AttributeBinding readBinding(); - osg::Image* readImage(std::string s); - osg::StateSet* readStateSet(); osg::Array* readArray(); osg::IntArray* readIntArray(); osg::UByteArray* readUByteArray(); @@ -59,22 +58,29 @@ public: osg::Vec3Array* readVec3Array(); osg::Vec4Array* readVec4Array(); - // Container to map image filenames to their respective images. - typedef std::pair > ImagePair; - typedef std::vector ImageList; + osg::Image* readImage(std::string s); + osg::StateSet* readStateSet(); + osg::StateAttribute* readStateAttribute(); + osg::Drawable* readDrawable(); + osg::Node* readNode(); - // Container to map stateset id to their respective stateset. - typedef std::pair > StateSetPair; - typedef std::vector StateSetList; + typedef std::map > ImageMap; + typedef std::map > StateSetMap; + typedef std::map > StateAttributeMap; + typedef std::map > DrawableMap; + typedef std::map > NodeMap; private: - std::istream* _istream; - int _version; - bool _peeking; - int _peekValue; - ImageList _imageList; - StateSetList _statesetList; + std::istream* _istream; + int _version; + bool _peeking; + int _peekValue; + ImageMap _imageMap; + StateSetMap _statesetMap; + StateAttributeMap _stateAttributeMap; + DrawableMap _drawableMap; + NodeMap _nodeMap; }; } diff --git a/src/osgPlugins/ive/DataOutputStream.cpp b/src/osgPlugins/ive/DataOutputStream.cpp index 69774a2e3..e0ff0b4fb 100644 --- a/src/osgPlugins/ive/DataOutputStream.cpp +++ b/src/osgPlugins/ive/DataOutputStream.cpp @@ -1,252 +1,449 @@ /********************************************************************** * - * FILE: DataOutputStream.cpp + * FILE: DataOutputStream.cpp * - * DESCRIPTION: Implements methods to write simpel datatypes to an - * output stream. + * DESCRIPTION: Implements methods to write simpel datatypes to an + * output stream. * - * CREATED BY: Rune Schmidt Jensen + * CREATED BY: Rune Schmidt Jensen * - * HISTORY: Created 11.03.2003 + * HISTORY: Created 11.03.2003 * - * Copyright 2003 VR-C + * Copyright 2003 VR-C **********************************************************************/ #include "DataOutputStream.h" #include "Exception.h" + #include "StateSet.h" +#include "BlendFunc.h" +#include "Material.h" +#include "CullFace.h" +#include "PolygonOffset.h" +#include "ShadeModel.h" +#include "Point.h" +#include "Texture2D.h" +#include "TextureCubeMap.h" +#include "TexEnv.h" +#include "TexEnvCombine.h" +#include "TexGen.h" + +#include "Group.h" +#include "MatrixTransform.h" +#include "Geode.h" +#include "LightSource.h" +#include "Billboard.h" +#include "Sequence.h" +#include "LOD.h" +//#include "ViewPoint.h" +#include "PositionAttitudeTransform.h" +#include "Transform.h" +#include "Switch.h" +#include "OccluderNode.h" +#include "Impostor.h" + +#include "Geometry.h" using namespace ive; DataOutputStream::DataOutputStream(std::ostream * ostream){ - _includeImageData= true; - _ostream = ostream; - if(!_ostream) - throw Exception("DataOutputStream::DataOutputStream(): null pointer exception in argument."); - writeInt(VERSION); + _includeImageData= true; + _ostream = ostream; + if(!_ostream) + throw Exception("DataOutputStream::DataOutputStream(): null pointer exception in argument."); + writeInt(VERSION); } DataOutputStream::~DataOutputStream(){} void DataOutputStream::writeBool(bool b){ - _ostream->write((char*)&b, BOOLSIZE); + _ostream->write((char*)&b, BOOLSIZE); } void DataOutputStream::writeChar(char c){ - _ostream->write(&c, CHARSIZE); + _ostream->write(&c, CHARSIZE); } void DataOutputStream::writeUShort(unsigned short s){ - _ostream->write((char*)&s, SHORTSIZE); + _ostream->write((char*)&s, SHORTSIZE); +} + +void DataOutputStream::writeUInt(unsigned int s){ + _ostream->write((char*)&s, INTSIZE); } void DataOutputStream::writeInt(int i){ - _ostream->write((char*)&i, INTSIZE); + _ostream->write((char*)&i, INTSIZE); } void DataOutputStream::writeFloat(float f){ - _ostream->write((char*)&f, FLOATSIZE); + _ostream->write((char*)&f, FLOATSIZE); } void DataOutputStream::writeLong(long l){ - _ostream->write((char*)&l, LONGSIZE); + _ostream->write((char*)&l, LONGSIZE); } void DataOutputStream::writeDouble(double d){ - _ostream->write((char*)&d, DOUBLESIZE); + _ostream->write((char*)&d, DOUBLESIZE); } void DataOutputStream::writeString(std::string s){ - writeInt(s.size()); - _ostream->write(s.c_str(), s.size()); + writeInt(s.size()); + _ostream->write(s.c_str(), s.size()); } void DataOutputStream::writeCharArray(char* data, int size){ - _ostream->write(data, size); + _ostream->write(data, size); } -void DataOutputStream::writeVec2(osg::Vec2 v){ - writeFloat(v.y()); - writeFloat(v.x()); +void DataOutputStream::writeVec2(const osg::Vec2& v){ + writeFloat(v.x()); + writeFloat(v.y()); } -void DataOutputStream::writeVec3(osg::Vec3 v){ - writeFloat(v.z()); - writeFloat(v.y()); - writeFloat(v.x()); +void DataOutputStream::writeVec3(const osg::Vec3& v){ + writeFloat(v.x()); + writeFloat(v.y()); + writeFloat(v.z()); } -void DataOutputStream::writeVec4(osg::Vec4 v){ - writeFloat(v.w()); - writeFloat(v.z()); - writeFloat(v.y()); - writeFloat(v.x()); +void DataOutputStream::writeVec4(const osg::Vec4& v){ + writeFloat(v.x()); + writeFloat(v.y()); + writeFloat(v.z()); + writeFloat(v.w()); } -void DataOutputStream::writeUByte4(osg::UByte4 v){ - writeChar(v.a()); - writeChar(v.b()); - writeChar(v.g()); - writeChar(v.r()); +void DataOutputStream::writeUByte4(const osg::UByte4& v){ + writeChar(v.r()); + writeChar(v.g()); + writeChar(v.b()); + writeChar(v.a()); } -void DataOutputStream::writeQuat(osg::Quat q){ - writeFloat(q.w()); - writeFloat(q.z()); - writeFloat(q.y()); - writeFloat(q.x()); -} - -void DataOutputStream::writeStateSet(osg::StateSet* stateset){ - // If stateset is already in list we do not write it again. - // We just writes its unique ID. - for(StateSetList::iterator itr=_statesetList.begin(); - itr!=_statesetList.end(); ++itr){ - if((*itr) == (int)stateset){ - writeInt((*itr)); - return; - } - } - // StateSet is not in list. - // We write its unique ID, - writeInt((int)stateset); - // add it to the stateset list, - _statesetList.push_back((int)stateset); - // and write it to stream. - ((ive::StateSet*)(stateset))->write(this); +void DataOutputStream::writeQuat(const osg::Quat& q){ + writeFloat(q.x()); + writeFloat(q.y()); + writeFloat(q.z()); + writeFloat(q.w()); } void DataOutputStream::writeBinding(osg::Geometry::AttributeBinding b){ - switch(b){ - case osg::Geometry::BIND_OFF: writeChar((char) 0); break; - case osg::Geometry::BIND_OVERALL: writeChar((char) 1); break; - case osg::Geometry::BIND_PER_PRIMITIVE: writeChar((char) 2); break; - case osg::Geometry::BIND_PER_PRIMITIVE_SET: writeChar((char) 3); break; - case osg::Geometry::BIND_PER_VERTEX: writeChar((char) 4); break; - default: throw Exception("Unknown binding in DataOutputStream::writeBinding()"); - } + switch(b){ + case osg::Geometry::BIND_OFF: writeChar((char) 0); break; + case osg::Geometry::BIND_OVERALL: writeChar((char) 1); break; + case osg::Geometry::BIND_PER_PRIMITIVE: writeChar((char) 2); break; + case osg::Geometry::BIND_PER_PRIMITIVE_SET: writeChar((char) 3); break; + case osg::Geometry::BIND_PER_VERTEX: writeChar((char) 4); break; + default: throw Exception("Unknown binding in DataOutputStream::writeBinding()"); + } } void DataOutputStream::writeArray(osg::Array* a){ - switch(a->getType()){ - case osg::Array::IntArrayType: - writeChar((char)0); - writeIntArray(static_cast(a)); - break; - case osg::Array::UByteArrayType: - writeChar((char)1); - writeUByteArray(static_cast(a)); - break; - case osg::Array::UShortArrayType: - writeChar((char)2); - writeUShortArray(static_cast(a)); - break; - case osg::Array::UIntArrayType: - writeChar((char)3); - writeUIntArray(static_cast(a)); - break; - case osg::Array::UByte4ArrayType: - writeChar((char)4); - writeUByte4Array(static_cast(a)); - break; - case osg::Array::FloatArrayType: - writeChar((char)5); - writeFloatArray(static_cast(a)); - break; - case osg::Array::Vec2ArrayType: - writeChar((char)6); - writeVec2Array(static_cast(a)); - break; - case osg::Array::Vec3ArrayType: - writeChar((char)7); - writeVec3Array(static_cast(a)); - break; - case osg::Array::Vec4ArrayType: - writeChar((char)8); - writeVec4Array(static_cast(a)); - break; - default: throw Exception("Unknown array type in DataOutputStream::writeArray()"); - } + switch(a->getType()){ + case osg::Array::IntArrayType: + writeChar((char)0); + writeIntArray(static_cast(a)); + break; + case osg::Array::UByteArrayType: + writeChar((char)1); + writeUByteArray(static_cast(a)); + break; + case osg::Array::UShortArrayType: + writeChar((char)2); + writeUShortArray(static_cast(a)); + break; + case osg::Array::UIntArrayType: + writeChar((char)3); + writeUIntArray(static_cast(a)); + break; + case osg::Array::UByte4ArrayType: + writeChar((char)4); + writeUByte4Array(static_cast(a)); + break; + case osg::Array::FloatArrayType: + writeChar((char)5); + writeFloatArray(static_cast(a)); + break; + case osg::Array::Vec2ArrayType: + writeChar((char)6); + writeVec2Array(static_cast(a)); + break; + case osg::Array::Vec3ArrayType: + writeChar((char)7); + writeVec3Array(static_cast(a)); + break; + case osg::Array::Vec4ArrayType: + writeChar((char)8); + writeVec4Array(static_cast(a)); + break; + default: throw Exception("Unknown array type in DataOutputStream::writeArray()"); + } } void DataOutputStream::writeIntArray(osg::IntArray* a){ - int size = a->getNumElements(); - writeInt(size); - for(int i =0; iindex(i)); - } + int size = a->getNumElements(); + writeInt(size); + for(int i =0; iindex(i)); + } } void DataOutputStream::writeUByteArray(osg::UByteArray* a){ - int size = a->getNumElements(); - writeInt(size); - for(int i =0; igetNumElements(); + writeInt(size); + for(int i =0; igetNumElements(); - writeInt(size); - for(int i =0; igetNumElements(); + writeInt(size); + for(int i =0; igetNumElements(); - writeInt(size); - for(int i =0; igetNumElements(); + writeInt(size); + for(int i =0; igetNumElements(); - writeInt(size); - for(int i =0; igetNumElements(); + writeInt(size); + for(int i =0; igetNumElements(); - writeInt(size); - for(int i =0; igetNumElements(); + writeInt(size); + for(int i =0; isize(); - writeInt(size); - for(int i=0;isize(); + writeInt(size); + for(int i=0;isize(); - writeInt(size); - for(int i = 0; i < size; i++){ + int size = a->size(); + writeInt(size); + for(int i = 0; i < size; i++){ writeVec3((*a)[i]); - } + } } void DataOutputStream::writeVec4Array(osg::Vec4Array* a){ - int size = a->size(); - writeInt(size); - for(int i=0;isize(); + writeInt(size); + for(int i=0;isecond); + } + else + { + // id doesn't exist so create a new ID and + // register the stateset. + + int id = _stateSetMap.size(); + _stateSetMap[stateset] = id; + + // write the id. + writeInt(id); + + // write the stateset. + ((ive::StateSet*)(stateset))->write(this); + } +} + +void DataOutputStream::writeStateAttribute(osg::StateAttribute* attribute) +{ + StateAttributeMap::iterator itr = _stateAttributeMap.find(attribute); + if (itr!=_stateAttributeMap.end()) + { + // Id already exists so just write ID. + writeInt(itr->second); + } + else + { + // id doesn't exist so create a new ID and + // register the stateset. + + int id = _stateAttributeMap.size(); + _stateAttributeMap[attribute] = id; + + // write the id. + writeInt(id); + + // write the stateset. + if(dynamic_cast(attribute)){ + ((ive::BlendFunc*)(attribute))->write(this); + } + // This is a Material + else if(dynamic_cast(attribute)){ + ((ive::Material*)(attribute))->write(this); + } + // This is a CullFace + else if(dynamic_cast(attribute)){ + ((ive::CullFace*)(attribute))->write(this); + } + // This is a PolygonOffset + else if(dynamic_cast(attribute)){ + ((ive::PolygonOffset*)(attribute))->write(this); + } + else if(dynamic_cast(attribute)){ + ((ive::ShadeModel*)(attribute))->write(this); + } + else if(dynamic_cast(attribute)){ + ((ive::Point*)(attribute))->write(this); + } + // This is a Texture2D + else if(dynamic_cast(attribute)){ + ((ive::Texture2D*)(attribute))->write(this); + } + // This is a TextureCubeMap + else if(dynamic_cast(attribute)){ + ((ive::TextureCubeMap*)(attribute))->write(this); + } + // This is a TexEnv + else if(dynamic_cast(attribute)){ + ((ive::TexEnv*)(attribute))->write(this); + } + // This is a TexEnvCombine + else if(dynamic_cast(attribute)){ + ((ive::TexEnvCombine*)(attribute))->write(this); + } + // This is a TexGen + else if(dynamic_cast(attribute)){ + ((ive::TexGen*)(attribute))->write(this); + } + else{ + std::string className = attribute->className(); + throw Exception(std::string("StateSet::write(): Unknown StateAttribute: ").append(className)); + } + } +} + +void DataOutputStream::writeDrawable(osg::Drawable* drawable) +{ + DrawableMap::iterator itr = _drawableMap.find(drawable); + if (itr!=_drawableMap.end()) + { + // Id already exists so just write ID. + writeInt(itr->second); + } + else + { + // id doesn't exist so create a new ID and + // register the stateset. + + int id = _drawableMap.size(); + _drawableMap[drawable] = id; + + // write the id. + writeInt(id); + + if(dynamic_cast(drawable)) + ((ive::Geometry*)(drawable))->write(this); + else{ + throw Exception("Unknown drawable in DataOutputStream::writeDrawable()"); + } + } +} + +void DataOutputStream::writeNode(osg::Node* node) +{ + NodeMap::iterator itr = _nodeMap.find(node); + if (itr!=_nodeMap.end()) + { + // Id already exists so just write ID. + writeInt(itr->second); + } + else + { + // id doesn't exist so create a new ID and + // register the stateset. + + int id = _nodeMap.size(); + _nodeMap[node] = id; + + // write the id. + writeInt(id); + + if(dynamic_cast(node)){ + ((ive::MatrixTransform*)(node))->write(this); + } +// else if(dynamic_cast(node)){ +// ((ive::ViewPoint*)(node))->write(this); +// } + else if(dynamic_cast(node)){ + ((ive::PositionAttitudeTransform*)(node))->write(this); + } + else if(dynamic_cast(node)){ + ((ive::LightSource*)(node))->write(this); + } + else if(dynamic_cast(node)){ + ((ive::Sequence*)(node))->write(this); + } + else if(dynamic_cast(node)){ + ((ive::Impostor*)(node))->write(this); + } + else if(dynamic_cast(node)){ + ((ive::LOD*)(node))->write(this); + } + else if(dynamic_cast(node)){ + ((ive::Switch*)(node))->write(this); + } + else if(dynamic_cast(node)){ + ((ive::OccluderNode*)(node))->write(this); + } + else if(dynamic_cast(node)){ + ((ive::Transform*)(node))->write(this); + } + else if(dynamic_cast(node)){ + ((ive::Group*)(node))->write(this); + } + else if(dynamic_cast(node)){ + ((ive::Billboard*)(node))->write(this); + } + else if(dynamic_cast(node)){ + ((ive::Geode*)(node))->write(this); + } + else + throw Exception("Unknown node in Group::write()"); + + } } diff --git a/src/osgPlugins/ive/DataOutputStream.h b/src/osgPlugins/ive/DataOutputStream.h index 386a08b08..3dffbf457 100644 --- a/src/osgPlugins/ive/DataOutputStream.h +++ b/src/osgPlugins/ive/DataOutputStream.h @@ -29,18 +29,18 @@ public: void writeBool(bool b); void writeChar(char c); void writeUShort(unsigned short s); + void writeUInt(unsigned int s); void writeInt(int i); void writeFloat(float f); void writeLong(long l); void writeDouble(double d); void writeString(std::string s); void writeCharArray(char* data, int size); - void writeVec2(osg::Vec2 v); - void writeVec3(osg::Vec3 v); - void writeVec4(osg::Vec4 v); - void writeUByte4(osg::UByte4 v); - void writeQuat(osg::Quat q); - void writeStateSet(osg::StateSet* stateset); + void writeVec2(const osg::Vec2& v); + void writeVec3(const osg::Vec3& v); + void writeVec4(const osg::Vec4& v); + void writeUByte4(const osg::UByte4& v); + void writeQuat(const osg::Quat& q); void writeBinding(osg::Geometry::AttributeBinding b); void writeArray(osg::Array* a); void writeIntArray(osg::IntArray* a); @@ -54,6 +54,11 @@ public: void writeVec4Array(osg::Vec4Array* a); void writeMatrix(osg::Matrix mat); + void writeStateSet(osg::StateSet* stateset); + void writeStateAttribute(osg::StateAttribute* sa); + void writeDrawable(osg::Drawable* sa); + void writeNode(osg::Node* sa); + // Set and get include image data in stream void setIncludeImageData(bool b) {_includeImageData=b;}; bool getIncludeImageData() {return _includeImageData;}; @@ -62,10 +67,17 @@ private: std::ostream* _ostream; // Container to map stateset uniques to their respective stateset. - typedef std::vector StateSetList; - StateSetList _statesetList; + typedef std::map StateSetMap; + typedef std::map StateAttributeMap; + typedef std::map DrawableMap; + typedef std::map NodeMap; + + StateSetMap _stateSetMap; + StateAttributeMap _stateAttributeMap; + DrawableMap _drawableMap; + NodeMap _nodeMap; - bool _includeImageData; + bool _includeImageData; }; diff --git a/src/osgPlugins/ive/Drawable.cpp b/src/osgPlugins/ive/Drawable.cpp index f59c80549..7f707debb 100644 --- a/src/osgPlugins/ive/Drawable.cpp +++ b/src/osgPlugins/ive/Drawable.cpp @@ -33,16 +33,23 @@ void Drawable::write(DataOutputStream* out){ // Write Drawable's properties. - // Write stateset. - out->writeInt((int)getStateSet()); - if(getStateSet()) - out->writeStateSet(getStateSet()); - + // Write stateset if any + if (getStateSet()) + { + out->writeInt(1); //true we have a stateset + out->writeStateSet(getStateSet()); + } + else + out->writeInt(0); //false we don't have a stateset + // Write shape - out->writeInt((int)getShape()); - if (getShape()){ - //static_cast(getShape())->write(out); - } + if (getShape()) + { + out->writeInt(1); //true we have a shape + //static_cast(getShape())->write(out); + } + else + out->writeInt(0); //false we don't have a shape // Write support display list. out->writeBool(getSupportsDisplayList()); diff --git a/src/osgPlugins/ive/GNUmakefile b/src/osgPlugins/ive/GNUmakefile index 9ea5f1ec6..f3ef0c329 100644 --- a/src/osgPlugins/ive/GNUmakefile +++ b/src/osgPlugins/ive/GNUmakefile @@ -6,18 +6,22 @@ CXXFILES =\ AnimationPathCallback.cpp\ Billboard.cpp\ BlendFunc.cpp\ + ConvexPlanarOccluder.cpp\ + ConvexPlanarPolygon.cpp\ CullFace.cpp\ DataInputStream.cpp\ DataOutputStream.cpp\ DrawArrayLengths.cpp\ DrawArrays.cpp\ DrawElementsUShort.cpp\ + DrawElementsUInt.cpp\ Drawable.cpp\ Exception.cpp\ Geode.cpp\ Geometry.cpp\ Group.cpp\ Image.cpp\ + Impostor.cpp\ LOD.cpp\ Light.cpp\ LightSource.cpp\ @@ -25,9 +29,14 @@ CXXFILES =\ MatrixTransform.cpp\ Node.cpp\ Object.cpp\ + OccluderNode.cpp\ PositionAttitudeTransform.cpp\ + PolygonOffset.cpp\ + Point.cpp\ PrimitiveSet.cpp\ Sequence.cpp\ + ShadeModel.cpp\ + Switch.cpp\ StateSet.cpp\ TexEnv.cpp\ TexEnvCombine.cpp\ diff --git a/src/osgPlugins/ive/Geode.cpp b/src/osgPlugins/ive/Geode.cpp index ceab97f5f..8767788a9 100644 --- a/src/osgPlugins/ive/Geode.cpp +++ b/src/osgPlugins/ive/Geode.cpp @@ -1,15 +1,15 @@ /********************************************************************** * - * FILE: Geode.cpp + * FILE: Geode.cpp * - * DESCRIPTION: Read/Write osg::Geode in binary format to disk. + * DESCRIPTION: Read/Write osg::Geode in binary format to disk. * - * CREATED BY: Auto generated by iveGenerated - * and later modified by Rune Schmidt Jensen. + * CREATED BY: Auto generated by iveGenerated + * and later modified by Rune Schmidt Jensen. * - * HISTORY: Created 18.3.2003 + * HISTORY: Created 18.3.2003 * - * Copyright 2003 VR-C + * Copyright 2003 VR-C **********************************************************************/ #include "Exception.h" @@ -23,64 +23,71 @@ using namespace ive; void Geode::write(DataOutputStream* out){ - // Write Geode's identification. - out->writeInt(IVEGEODE); - // If the osg class is inherited by any other class we should also write this to file. - osg::Node* node = dynamic_cast(this); - if(node){ - ((ive::Node*)(node))->write(out); - } - else - throw Exception("Geode::write(): Could not cast this osg::Geode to an osg::Node."); + // Write Geode's identification. + out->writeInt(IVEGEODE); + // If the osg class is inherited by any other class we should also write this to file. + osg::Node* node = dynamic_cast(this); + if(node){ + ((ive::Node*)(node))->write(out); + } + else + throw Exception("Geode::write(): Could not cast this osg::Geode to an osg::Node."); - // Write Geode's properties. + // Write Geode's properties. - // Write number of drawables. - out->writeInt(getNumDrawables()); - // Write out every drawable. - for(unsigned int i=0;i(drawable)) - ((ive::Geometry*)(drawable))->write(out); - else{ - throw Exception("Unknown drawable in Geode::write()"); - } + // Write number of drawables. + out->writeInt(getNumDrawables()); + // Write out every drawable. + for(unsigned int i=0;i(drawable)) + ((ive::Geometry*)(drawable))->write(out); + else{ + throw Exception("Unknown drawable in Geode::write()"); + } +#else + out->writeDrawable(drawable); +#endif } } void Geode::read(DataInputStream* in){ - // Read Geode's identification. - int id = in->peekInt(); - if(id == IVEGEODE){ - // Code to read Geode's properties. - id = in->readInt(); - // If the osg class is inherited by any other class we should also read this from file. - osg::Node* node = dynamic_cast(this); - if(node){ - ((ive::Node*)(node))->read(in); - } - else - throw Exception("Geode::read(): Could not cast this osg::Geode to an osg::Node."); + // Read Geode's identification. + int id = in->peekInt(); + if(id == IVEGEODE){ + // Code to read Geode's properties. + id = in->readInt(); + // If the osg class is inherited by any other class we should also read this from file. + osg::Node* node = dynamic_cast(this); + if(node){ + ((ive::Node*)(node))->read(in); + } + else + throw Exception("Geode::read(): Could not cast this osg::Geode to an osg::Node."); - // Read number of drawables. - int size = in->readInt(); - // Read the drawables. - for(int i = 0; ipeekInt(); - osg::Drawable* drawable; - if(id == IVEGEOMETRY){ - drawable = new osg::Geometry(); - ((Geometry*)(drawable))->read(in); - addDrawable(drawable); - } - else - throw Exception("Unknown drawable identification in Geode::read()"); - - } - } - else{ - throw Exception("Geode::read(): Expected Geode identification."); - } + // Read number of drawables. + int size = in->readInt(); + // Read the drawables. + for(int i = 0; ipeekInt(); + osg::Drawable* drawable; + if(id == IVEGEOMETRY){ + drawable = new osg::Geometry(); + ((Geometry*)(drawable))->read(in); + addDrawable(drawable); + } + else + throw Exception("Unknown drawable identification in Geode::read()"); +#else + addDrawable(in->readDrawable()); +#endif + } + } + else{ + throw Exception("Geode::read(): Expected Geode identification."); + } } diff --git a/src/osgPlugins/ive/Geometry.cpp b/src/osgPlugins/ive/Geometry.cpp index 6f8cc2669..f0d1a4d64 100644 --- a/src/osgPlugins/ive/Geometry.cpp +++ b/src/osgPlugins/ive/Geometry.cpp @@ -18,6 +18,7 @@ #include "DrawArrays.h" #include "DrawArrayLengths.h" #include "DrawElementsUShort.h" +#include "DrawElementsUInt.h" using namespace ive; @@ -46,61 +47,64 @@ void Geometry::write(DataOutputStream* out){ ((ive::DrawArrayLengths*)(getPrimitiveSet(i)))->write(out); else if(dynamic_cast(getPrimitiveSet(i))) ((ive::DrawElementsUShort*)(getPrimitiveSet(i)))->write(out); + else if(dynamic_cast(getPrimitiveSet(i))) + ((ive::DrawElementsUInt*)(getPrimitiveSet(i)))->write(out); else throw Exception("Unknown PrimitivSet in Geometry::write()"); } // Write vertex array if any - out->writeInt((int)getVertexArray()); - if (getVertexArray()){ - out->writeVec3Array(getVertexArray()); + out->writeLong((long)getVertexArray()); + if (getVertexArray()) + { + out->writeArray(getVertexArray()); } // Write vertex indices if any - out->writeInt((int)getVertexIndices()); + out->writeLong((long)getVertexIndices()); if (getVertexIndices()){ out->writeArray(getVertexIndices()); } // Write normal array if any - out->writeInt((int)getNormalArray()); + out->writeLong((long)getNormalArray()); if (getNormalArray()){ out->writeBinding(getNormalBinding()); out->writeVec3Array(getNormalArray()); } // Write normal indices if any - out->writeInt((int)getNormalIndices()); + out->writeLong((long)getNormalIndices()); if (getNormalIndices()){ out->writeArray(getNormalIndices()); } // Write color array if any. - out->writeInt((int)getColorArray()); + out->writeLong((long)getColorArray()); if (getColorArray()){ out->writeBinding(getColorBinding()); out->writeArray(getColorArray()); } // Write color indices if any - out->writeInt((int)getColorIndices()); + out->writeLong((long)getColorIndices()); if (getColorIndices()){ out->writeArray(getColorIndices()); } // Write secondary color array if any - out->writeInt((int)getSecondaryColorArray()); + out->writeLong((long)getSecondaryColorArray()); if (getSecondaryColorArray()){ out->writeBinding(getSecondaryColorBinding()); out->writeArray(getSecondaryColorArray()); } // Write second color indices if any - out->writeInt((int)getSecondaryColorIndices()); + out->writeLong((long)getSecondaryColorIndices()); if (getSecondaryColorIndices()){ out->writeArray(getSecondaryColorIndices()); } // Write fog coord array if any - out->writeInt((int)getFogCoordArray()); + out->writeLong((long)getFogCoordArray()); if (getFogCoordArray()){ out->writeBinding(getFogCoordBinding()); out->writeArray(getFogCoordArray()); } // Write fog coord indices if any - out->writeInt((int)getFogCoordIndices()); + out->writeLong((long)getFogCoordIndices()); if (getFogCoordIndices()){ out->writeArray(getFogCoordIndices()); } @@ -159,6 +163,11 @@ void Geometry::read(DataInputStream* in){ ((ive::DrawElementsUShort*)(prim))->read(in); addPrimitiveSet(prim); } + else if(primID==IVEDRAWELEMENTSUINT){ + prim = new osg::DrawElementsUInt(); + ((ive::DrawElementsUInt*)(prim))->read(in); + addPrimitiveSet(prim); + } else{ throw Exception("Unkown PrimitiveSet in Geometry::read()"); } @@ -167,7 +176,7 @@ void Geometry::read(DataInputStream* in){ // Read vertex array if any int va=in->readInt(); if (va){ - setVertexArray(in->readVec3Array()); + setVertexArray(in->readArray()); } // Read vertex indices if any int vi = in->readInt(); diff --git a/src/osgPlugins/ive/Group.cpp b/src/osgPlugins/ive/Group.cpp index 22bacb1be..171c45402 100644 --- a/src/osgPlugins/ive/Group.cpp +++ b/src/osgPlugins/ive/Group.cpp @@ -1,15 +1,15 @@ /********************************************************************** * - * FILE: Group.cpp + * FILE: Group.cpp * - * DESCRIPTION: Read/Write osg::Group in binary format to disk. + * DESCRIPTION: Read/Write osg::Group in binary format to disk. * - * CREATED BY: Auto generated by iveGenerated - * and later modified by Rune Schmidt Jensen. + * CREATED BY: Auto generated by iveGenerated + * and later modified by Rune Schmidt Jensen. * - * HISTORY: Created 17.3.2003 + * HISTORY: Created 17.3.2003 * - * Copyright 2003 VR-C + * Copyright 2003 VR-C **********************************************************************/ #include "Exception.h" @@ -28,138 +28,54 @@ using namespace ive; void Group::write(DataOutputStream* out){ - // Write Group's identification. - out->writeInt(IVEGROUP); - // If the osg class is inherited by any other class we should also write this to file. - osg::Node* node = dynamic_cast(this); - if(node){ - static_cast(node)->write(out); - } - else - throw Exception("Group::write(): Could not cast this osg::Group to an osg::Node."); + // Write Group's identification. + out->writeInt(IVEGROUP); + // If the osg class is inherited by any other class we should also write this to file. + osg::Node* node = dynamic_cast(this); + if(node){ + static_cast(node)->write(out); + } + else + throw Exception("Group::write(): Could not cast this osg::Group to an osg::Node."); - // Write Group's properties. + // Write Group's properties. - // Write number of children. - out->writeInt(getNumChildren()); - // Write children. + // Write number of children. + out->writeInt(getNumChildren()); + // Write children. for(unsigned int i=0; i(child)){ - ((ive::MatrixTransform*)(child))->write(out); - } -// else if(dynamic_cast(child)){ -// ((ive::ViewPoint*)(child))->write(out); -// } - else if(dynamic_cast(child)){ - ((ive::PositionAttitudeTransform*)(child))->write(out); - } - else if(dynamic_cast(child)){ - ((ive::LightSource*)(child))->write(out); - } - else if(dynamic_cast(child)){ - ((ive::Sequence*)(child))->write(out); - } - else if(dynamic_cast(child)){ - ((ive::LOD*)(child))->write(out); - } - else if(dynamic_cast(child)){ - ((ive::Transform*)(child))->write(out); - } - else if(dynamic_cast(child)){ - ((ive::Group*)(child))->write(out); - } - else if(dynamic_cast(child)){ - ((ive::Billboard*)(child))->write(out); - } - else if(dynamic_cast(child)){ - ((ive::Geode*)(child))->write(out); - } - else - throw Exception("Unknown child in Group::write()"); + osg::Node* child = getChild(i); + out->writeNode(child); } } void Group::read(DataInputStream* in){ - // Read Group's identification. - int id = in->peekInt(); - if(id == IVEGROUP){ - // Read Group's identification. - id = in->readInt(); + // Read Group's identification. + int id = in->peekInt(); + if(id == IVEGROUP){ + // Read Group's identification. + id = in->readInt(); - // If the osg class is inherited by any other class we should also read this from file. - osg::Node* node = dynamic_cast(this); - if(node){ - ((ive::Node*)(node))->read(in); - } - else - throw Exception("Group::read(): Could not cast this osg::Group to an osg::Node."); + // If the osg class is inherited by any other class we should also read this from file. + osg::Node* node = dynamic_cast(this); + if(node){ + ((ive::Node*)(node))->read(in); + } + else + throw Exception("Group::read(): Could not cast this osg::Group to an osg::Node."); - // Read groups properties. + // Read groups properties. - // Read number of children. - int size = in->readInt(); - // Read children. - for(int i=0; ipeekInt(); - osg::Node* child; - if(id == IVEMATRIXTRANSFORM){ - child = new osg::MatrixTransform(); - ((ive::MatrixTransform*)(child))->read(in); - addChild(child); - } -// else if(id == IVEVIEWPOINT){ -// child = new osgfIVE::ViewPoint(); -// ((ive::ViewPoint*)(child))->read(in); -// addChild(child); -// } - else if(id == IVEPOSITIONATTITUDETRANSFORM){ - child = new osg::PositionAttitudeTransform(); - ((ive::PositionAttitudeTransform*)(child))->read(in); - addChild(child); - } - else if(id == IVELIGHTSOURCE){ - child = new osg::LightSource(); - ((ive::LightSource*)(child))->read(in); - addChild(child); - } - else if(id == IVESEQUENCE){ - child = new osg::Sequence(); - ((ive::Sequence*)(child))->read(in); - addChild(child); - } - else if(id == IVELOD){ - child = new osg::LOD(); - ((ive::LOD*)(child))->read(in); - addChild(child); - } - else if(id == IVETRANSFORM){ - child = new osg::Transform(); - ((ive::Transform*)(child))->read(in); - addChild(child); - } - else if(id == IVEGROUP){ - child = new osg::Group(); - ((ive::Group*)(child))->read(in); - addChild(child); - } - else if(id == IVEBILLBOARD){ - child = new osg::Billboard(); - ((ive::Billboard*)(child))->read(in); - addChild(child); - } - else if(id == IVEGEODE){ - child = new osg::Geode(); - ((ive::Geode*)(child))->read(in); - addChild(child); - } - else{ - throw Exception("Unknown child identification in Group::read()"); - } - } - } - else{ - throw Exception("Group::read(): Expected Group identification"); - } + // Read number of children. + int size = in->readInt(); + // Read children. + for(int i=0; ireadNode()); + } + } + else{ + throw Exception("Group::read(): Expected Group identification"); + } } diff --git a/src/osgPlugins/ive/Image.cpp b/src/osgPlugins/ive/Image.cpp index 1713d3f64..73c2eb4a4 100644 --- a/src/osgPlugins/ive/Image.cpp +++ b/src/osgPlugins/ive/Image.cpp @@ -1,15 +1,15 @@ /********************************************************************** * - * FILE: Image.cpp + * FILE: Image.cpp * - * DESCRIPTION: Read/Write osg::Image in binary format to disk. + * DESCRIPTION: Read/Write osg::Image in binary format to disk. * - * CREATED BY: Auto generated by iveGenerated - * and later modified by Rune Schmidt Jensen. + * CREATED BY: Auto generated by iveGenerated + * and later modified by Rune Schmidt Jensen. * - * HISTORY: Created 20.3.2003 + * HISTORY: Created 20.3.2003 * - * Copyright 2003 VR-C + * Copyright 2003 VR-C **********************************************************************/ #include "Exception.h" @@ -18,104 +18,125 @@ using namespace ive; -void Image::write(DataOutputStream* out){ - // Write Image's identification. - out->writeInt(IVEIMAGE); - // If the osg class is inherited by any other class we should also write this to file. - osg::Object* obj = dynamic_cast(this); - if(obj){ - ((ive::Object*)(obj))->write(out); - } - else - throw Exception("Image::write(): Could not cast this osg::Image to an osg::Object."); - // Write Image's properties. +void Image::write(DataOutputStream* out) +{ + // Write Image's identification. + out->writeInt(IVEIMAGE); + // If the osg class is inherited by any other class we should also write this to file. + osg::Object* obj = dynamic_cast(this); + if(obj){ + ((ive::Object*)(obj))->write(out); + } + else + throw Exception("Image::write(): Could not cast this osg::Image to an osg::Object."); + // Write Image's properties. - // Write name - out->writeString(getFileName()); + // Write name + out->writeString(getFileName()); - // Write width, height, depth of image. - out->writeInt(s()); - out->writeInt(t()); - out->writeInt(r()); + // Write width, height, depth of image. + out->writeInt(s()); + out->writeInt(t()); + out->writeInt(r()); + + + std::cout << getFileName()<<"\t"<writeInt(getInternalTextureFormat()); - out->writeInt(getPixelFormat()); - out->writeInt(getDataType()); - out->writeInt(getPacking()); + out->writeInt(getPixelFormat()); + out->writeInt(getDataType()); + out->writeInt(getPacking()); - // Write modified tag. - out->writeInt(getModifiedTag()); + // Write modified tag. + out->writeInt(getModifiedTag()); - // Write mipmapdata vector - int size = _mipmapData.size(); - out->writeInt(size); - for(int i=0;iwriteInt(_mipmapData[i]); + // Write mipmapdata vector + int size = _mipmapData.size(); + out->writeInt(size); + for(int i=0;iwriteInt(_mipmapData[i]); - // Write image data if any - out->writeInt((int)data()); - if(data()){ - // Compute the size of image data and write this. - unsigned int size = computeRowWidthInBytes(s(),getPixelFormat(),getDataType(),getPacking())*t()*r(); - out->writeInt(size); - // Write the data - out->writeCharArray((char*)data(), size); - } + // Write image data if any + out->writeLong((long)data()); + if(data()){ + // Compute the size of image data and write this. + unsigned int size = getTotalSizeInBytesIncludingMipmaps(); + out->writeInt(size); + // Write the data + out->writeCharArray((char*)data(), size); + } } -void Image::read(DataInputStream* in){ - // Peek Image's identification. - int id = in->peekInt(); - if(id == IVEIMAGE){ - // Read Image's identification. - id = in->readInt(); - // If the osg class is inherited by any other class we should also read this from file. - osg::Object* obj = dynamic_cast(this); - if(obj){ - ((ive::Object*)(obj))->read(in); - } - else - throw Exception("Image::read(): Could not cast this osg::Image to an osg::Object."); - // Read Image's properties. +void Image::read(DataInputStream* in) +{ + // Peek Image's identification. + int id = in->peekInt(); + if(id == IVEIMAGE){ + // Read Image's identification. + id = in->readInt(); + // If the osg class is inherited by any other class we should also read this from file. + osg::Object* obj = dynamic_cast(this); + if(obj){ + ((ive::Object*)(obj))->read(in); + } + else + throw Exception("Image::read(): Could not cast this osg::Image to an osg::Object."); + // Read Image's properties. - // Read name - setFileName(in->readString()); + // Read name + setFileName(in->readString()); - // Read width, height, depth of image. - int s=in->readInt(); - int t=in->readInt(); - int r=in->readInt(); + // Read width, height, depth of image. + int is=in->readInt(); + int it=in->readInt(); + int ir=in->readInt(); - // Read formats, type and packing + // Read formats, type and packing GLint internalTextureFormat = (GLint) in->readInt(); - GLenum pixelFormat = (GLenum) in->readInt(); + GLenum pixelFormat = (GLenum) in->readInt(); GLenum dataType = (GLenum) in->readInt();; unsigned int packing = (unsigned int)in->readInt(); - // Read modified tag. + // Read modified tag. setModifiedTag((unsigned int)in->readInt()); - // Read mipmapdata vector - int size = in->readInt(); - _mipmapData.resize(size); - for(int i=0;ireadInt(); + // Read mipmapdata vector + int size = in->readInt(); + _mipmapData.resize(size); - // Read image data if any - if(in->readInt()){ - unsigned int dataSize = (unsigned int)in->readInt(); - //char* data = (char*)malloc (dataSize); - char* data = new char[dataSize]; - if(!data) - throw Exception("Image::read(): Unable to allocate memory for image data."); - in->readCharArray(data,dataSize); - setImage(s, t, r, internalTextureFormat, pixelFormat, - dataType, (unsigned char* ) data, osg::Image::USE_NEW_DELETE, packing); - } - } - else{ - throw Exception("Image::read(): Expected Image identification."); - } + //if (size) std::cout<<"is mip mapped "; + + for(int i=0;ireadInt(); + //std::cout<<_mipmapData[i]<<"\t"; + } + //std::cout<readInt()){ + unsigned int dataSize = (unsigned int)in->readInt(); + + //static int totalSize = 0; + + //totalSize += dataSize; + //std::cout<readCharArray(data,dataSize); + setImage(is, it, ir, internalTextureFormat, pixelFormat, + dataType, (unsigned char* ) data, osg::Image::USE_NEW_DELETE, packing); + } + } + else{ + throw Exception("Image::read(): Expected Image identification."); + } } diff --git a/src/osgPlugins/ive/LightSource.cpp b/src/osgPlugins/ive/LightSource.cpp index 9841a0c1e..6885d97ea 100644 --- a/src/osgPlugins/ive/LightSource.cpp +++ b/src/osgPlugins/ive/LightSource.cpp @@ -32,7 +32,7 @@ void LightSource::write(DataOutputStream* out){ // Write LightSource's properties. // Write out light - out->writeInt((int)getLight()); + out->writeLong((long)getLight()); if(getLight()){ ((ive::Light*)(getLight()))->write(out); } diff --git a/src/osgPlugins/ive/Node.cpp b/src/osgPlugins/ive/Node.cpp index 25c4c45e9..e1b9d96f6 100644 --- a/src/osgPlugins/ive/Node.cpp +++ b/src/osgPlugins/ive/Node.cpp @@ -51,7 +51,7 @@ void Node::write(DataOutputStream* out){ out->writeString(desc[i]); } // Write Stateset if any - out->writeInt((int) getStateSet()); + out->writeLong((long) getStateSet()); if(getStateSet()) out->writeStateSet(getStateSet()); @@ -59,7 +59,7 @@ void Node::write(DataOutputStream* out){ // Write UpdateCallback if any osg::NodeCallback* nc = getUpdateCallback(); if(nc && dynamic_cast(nc)){ - out->writeInt((int)nc); + out->writeLong((long)nc); ((ive::AnimationPathCallback*)(nc))->write(out); } else @@ -103,4 +103,4 @@ void Node::read(DataInputStream* in){ else{ throw Exception("Node::read(): Expected Node identification"); } -} \ No newline at end of file +} diff --git a/src/osgPlugins/ive/ReadWrite.h b/src/osgPlugins/ive/ReadWrite.h index 370e6819b..d9d4cac40 100644 --- a/src/osgPlugins/ive/ReadWrite.h +++ b/src/osgPlugins/ive/ReadWrite.h @@ -2,64 +2,73 @@ #define IVE_READWRITE 1 #include "DataInputStream.h" -#include "DataOutputStream.h" +#include "DataOutputStream.h" namespace ive { // Objects and Nodes -#define IVEOBJECT 0x00000001 -#define IVENODE 0x00000002 -#define IVEGROUP 0x00000003 -#define IVEMATRIXTRANSFORM 0x00000004 -#define IVESTATESET 0x00000005 -#define IVEGEODE 0x00000006 -#define IVEIMAGE 0x00000007 -#define IVELIGHTSOURCE 0x00000008 -#define IVELIGHT 0x00000009 -#define IVEBILLBOARD 0x00000010 -#define IVELOD 0x00000011 -#define IVESEQUENCE 0x00000012 -#define IVETRANSFORM 0x00000013 -#define IVEPOSITIONATTITUDETRANSFORM 0x00000014 -#define IVEANIMATIONPATH 0x00000015 +#define IVEOBJECT 0x00000001 +#define IVENODE 0x00000002 +#define IVEGROUP 0x00000003 +#define IVEMATRIXTRANSFORM 0x00000004 +#define IVESTATESET 0x00000005 +#define IVEGEODE 0x00000006 +#define IVEIMAGE 0x00000007 +#define IVELIGHTSOURCE 0x00000008 +#define IVELIGHT 0x00000009 +#define IVEBILLBOARD 0x00000010 +#define IVELOD 0x00000011 +#define IVESEQUENCE 0x00000012 +#define IVETRANSFORM 0x00000013 +#define IVEPOSITIONATTITUDETRANSFORM 0x00000014 +#define IVEANIMATIONPATH 0x00000015 +#define IVESWITCH 0x00000016 +#define IVEOCCLUDERNODE 0x00000017 +#define IVEIMPOSTOR 0x00000018 +#define IVECONVEXPLANAROCCLUDER 0x00000019 +#define IVECONVEXPLANARPOLYGON 0x00000020 // Node callbacks -#define IVENODECALLBACK 0x00000050 -#define IVEANIMATIONPATHCALLBACK 0x00000051 +#define IVENODECALLBACK 0x00000050 +#define IVEANIMATIONPATHCALLBACK 0x00000051 // State attributes. -#define IVESTATEATTRIBUTE 0x00000100 -#define IVEALPHAFUNC 0x00000101 -#define IVEBLENDFUNC 0x00000102 -#define IVEMATERIAL 0x00000110 -#define IVETEXTURE 0x00000120 -#define IVETEXTURE1D 0x00000121 -#define IVETEXTURE2D 0x00000122 -#define IVETEXTURE3D 0x00000123 -#define IVETEXTURECUBEMAP 0x00000124 -#define IVETEXENV 0x00000125 -#define IVETEXENVCOMBINE 0x00000126 -#define IVETEXGEN 0x00000127 -#define IVECULLFACE 0x00000128 +#define IVESTATEATTRIBUTE 0x00000100 +#define IVEALPHAFUNC 0x00000101 +#define IVEBLENDFUNC 0x00000102 +#define IVEMATERIAL 0x00000110 +#define IVETEXTURE 0x00000120 +#define IVETEXTURE1D 0x00000121 +#define IVETEXTURE2D 0x00000122 +#define IVETEXTURE3D 0x00000123 +#define IVETEXTURECUBEMAP 0x00000124 +#define IVETEXENV 0x00000125 +#define IVETEXENVCOMBINE 0x00000126 +#define IVETEXGEN 0x00000127 +#define IVECULLFACE 0x00000128 +#define IVEPOLYGONOFFSET 0x00000129 +#define IVESHADEMODEL 0x0000012A +#define IVEPOINT 0x0000012B // Drawables -#define IVEDRAWABLE 0x00001000 -#define IVEGEOMETRY 0x00001001 +#define IVEDRAWABLE 0x00001000 +#define IVEGEOMETRY 0x00001001 // Primitive set -#define IVEPRIMITIVESET 0x00010000 -#define IVEDRAWARRAYS 0x00010001 -#define IVEDRAWARRAYLENGTHS 0x00010002 -#define IVEDRAWELEMENTSUSHORT 0x00010003 +#define IVEPRIMITIVESET 0x00010000 +#define IVEDRAWARRAYS 0x00010001 +#define IVEDRAWARRAYLENGTHS 0x00010002 +#define IVEDRAWELEMENTSUSHORT 0x00010003 +#define IVEDRAWELEMENTSUINT 0x00010004 // Our own classes -#define IVEVIEWPOINT 0x00100001 +#define IVEVIEWPOINT 0x00100001 class ReadWrite{ public: - virtual void write(DataOutputStream* out) const = 0; - virtual void read(DataInputStream* out) const = 0; + virtual void write(DataOutputStream* out) const = 0; + virtual void read(DataInputStream* out) const = 0; }; } diff --git a/src/osgPlugins/ive/ReaderWriterIVE.cpp b/src/osgPlugins/ive/ReaderWriterIVE.cpp index 4cc66aff7..39e8a02b7 100644 --- a/src/osgPlugins/ive/ReaderWriterIVE.cpp +++ b/src/osgPlugins/ive/ReaderWriterIVE.cpp @@ -32,26 +32,9 @@ class IVEReaderWriter : public ReaderWriter { try{ // Create datainputstream. - ive::DataInputStream* in = new ive::DataInputStream(&fin); + ive::DataInputStream in(&fin); - // Which object is written first in the stream. - int id = in->peekInt(); - - if(id==IVEMATRIXTRANSFORM) - { - osg::MatrixTransform* rootNode = new osg::MatrixTransform; - ((ive::MatrixTransform*)(rootNode))->read(in); - return rootNode; - } - else if(id==IVEGROUP) - { - osg::Group* rootNode = new osg::Group; - ((ive::Group*)(rootNode))->read(in); - return rootNode; - } - else{ - std::cout <<"Unknown class identification in file "<< id << std::endl; - } + return in.readNode(); } catch(ive::Exception e) { @@ -63,6 +46,9 @@ class IVEReaderWriter : public ReaderWriter virtual WriteResult writeNode(const Node& node,const std::string& fileName, const osgDB::ReaderWriter::Options* options) { + std::string ext = getFileExtension(fileName); + if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED; + std::ofstream fout(fileName.c_str(), std::ios::out | std::ios::binary); WriteResult result = writeNode(node, fout, options); fout.close(); @@ -73,15 +59,9 @@ class IVEReaderWriter : public ReaderWriter { try { - ive::DataOutputStream* out = new ive::DataOutputStream(&fout); - // write ive file. - if(dynamic_cast(&node)) - const_cast(static_cast(&node))->write(out); - else if(dynamic_cast(&node)) - const_cast(static_cast(&node))->write(out); - else - std::cout<<"File must start with a MatrixTransform or Group "<(&node)); return WriteResult::FILE_SAVED; } catch(ive::Exception e) diff --git a/src/osgPlugins/ive/StateSet.cpp b/src/osgPlugins/ive/StateSet.cpp index 47aae1d50..8d8c7b965 100644 --- a/src/osgPlugins/ive/StateSet.cpp +++ b/src/osgPlugins/ive/StateSet.cpp @@ -1,15 +1,15 @@ /********************************************************************** * - * FILE: StateSet.cpp + * FILE: StateSet.cpp * - * DESCRIPTION: Read/Write osg::StateSet in binary format to disk. + * DESCRIPTION: Read/Write osg::StateSet in binary format to disk. * - * CREATED BY: Auto generated by iveGenerated - * and later modified by Rune Schmidt Jensen. + * CREATED BY: Auto generated by iveGenerated + * and later modified by Rune Schmidt Jensen. * - * HISTORY: Created 17.3.2003 + * HISTORY: Created 17.3.2003 * - * Copyright 2003 VR-C + * Copyright 2003 VR-C **********************************************************************/ #include "Exception.h" @@ -18,6 +18,8 @@ #include "BlendFunc.h" #include "Material.h" #include "CullFace.h" +#include "PolygonOffset.h" +#include "ShadeModel.h" #include "Texture2D.h" #include "TextureCubeMap.h" #include "TexEnv.h" @@ -29,238 +31,148 @@ using namespace ive; void StateSet::write(DataOutputStream* out){ - // Write StateSet's identification. - out->writeInt(IVESTATESET); - // If the osg class is inherited by any other class we should also write this to file. - osg::Object* obj = dynamic_cast(this); - if(obj){ - ((ive::Object*)(obj))->write(out); - } - else - throw Exception("StateSet::write(): Could not cast this osg::StateSet to an osg::Object."); + // Write StateSet's identification. + out->writeInt(IVESTATESET); + // If the osg class is inherited by any other class we should also write this to file. + osg::Object* obj = dynamic_cast(this); + if(obj){ + ((ive::Object*)(obj))->write(out); + } + else + throw Exception("StateSet::write(): Could not cast this osg::StateSet to an osg::Object."); - // Write render bin bin details. - switch(getRenderBinMode()){ - case osg::StateSet::INHERIT_RENDERBIN_DETAILS: out->writeChar((char)0);break; - case osg::StateSet::USE_RENDERBIN_DETAILS: out->writeChar((char)1);break; - case osg::StateSet::OVERRIDE_RENDERBIN_DETAILS: out->writeChar((char)2);break; - case osg::StateSet::ENCLOSE_RENDERBIN_DETAILS: out->writeChar((char)3);break; - default: throw Exception("Unknown RenderBinMode in StateSet::write()"); - } - out->writeInt(getBinNumber()); - out->writeString(getBinName()); + // Write render bin bin details. + switch(getRenderBinMode()){ + case osg::StateSet::INHERIT_RENDERBIN_DETAILS: out->writeChar((char)0);break; + case osg::StateSet::USE_RENDERBIN_DETAILS: out->writeChar((char)1);break; + case osg::StateSet::OVERRIDE_RENDERBIN_DETAILS: out->writeChar((char)2);break; + case osg::StateSet::ENCLOSE_RENDERBIN_DETAILS: out->writeChar((char)3);break; + default: throw Exception("Unknown RenderBinMode in StateSet::write()"); + } + out->writeInt(getBinNumber()); + out->writeString(getBinName()); - StateSet::ModeList ml = getModeList(); - StateSet::AttributeList al = getAttributeList(); + StateSet::ModeList ml = getModeList(); + StateSet::AttributeList al = getAttributeList(); - // Write stateset modes, this could for instance be GL_NORMALIZE, GL_LIGHT, etc. - out->writeInt(ml.size()); - for(StateSet::ModeList::const_iterator mitr=ml.begin(); mitr!=ml.end(); ++mitr){ - out->writeInt((unsigned int)mitr->first); - out->writeInt((unsigned int)mitr->second); - } + // Write stateset modes, this could for instance be GL_NORMALIZE, GL_LIGHT, etc. + out->writeInt(ml.size()); + for(StateSet::ModeList::const_iterator mitr=ml.begin(); mitr!=ml.end(); ++mitr){ + out->writeInt((unsigned int)mitr->first); + out->writeInt((unsigned int)mitr->second); + } - // Write stateset attributes, this could for instance be alphafunctions, materials, etc. - out->writeInt(al.size()); - for(StateSet::AttributeList::iterator aitr=al.begin(); aitr!=al.end(); ++aitr){ - // This is a BlendFunc. - if(dynamic_cast(aitr->second.first.get())){ - ((ive::BlendFunc*)(aitr->second.first.get()))->write(out); - out->writeInt(aitr->second.second); - } - // This is a Material - else if(dynamic_cast(aitr->second.first.get())){ - ((ive::Material*)(aitr->second.first.get()))->write(out); - out->writeInt(aitr->second.second); - } - // This is a CullFace - else if(dynamic_cast(aitr->second.first.get())){ - ((ive::CullFace*)(aitr->second.first.get()))->write(out); - out->writeInt(aitr->second.second); - } - else{ - std::string className = (aitr->second.first.get())->className(); - throw Exception(std::string("StateSet::write(): Unknown StateAttribute: ").append(className)); - } - } + // Write stateset attributes, this could for instance be alphafunctions, materials, etc. + out->writeInt(al.size()); + for(StateSet::AttributeList::iterator aitr=al.begin(); aitr!=al.end(); ++aitr){ + out->writeStateAttribute(aitr->second.first.get()); + out->writeInt(aitr->second.second); + } - StateSet::TextureModeList tml = getTextureModeList(); - StateSet::TextureAttributeList tal = getTextureAttributeList(); + StateSet::TextureModeList tml = getTextureModeList(); + StateSet::TextureAttributeList tal = getTextureAttributeList(); - // Write texture stateset modes, this could for instance be TEXGEN ON, TEXTURECUBEMAP ON, etc. - int nUnits = tml.size(); - out->writeInt(nUnits); + // Write texture stateset modes, this could for instance be TEXGEN ON, TEXTURECUBEMAP ON, etc. + int nUnits = tml.size(); + out->writeInt(nUnits); int unit; - for(unit=0;unitwriteInt(ml.size()); - for(StateSet::ModeList::const_iterator mitr=ml.begin(); mitr!=ml.end(); ++mitr){ - out->writeInt((unsigned int)mitr->first); - out->writeInt((unsigned int)mitr->second); - } - } + for(unit=0;unitwriteInt(ml.size()); + for(StateSet::ModeList::const_iterator mitr=ml.begin(); mitr!=ml.end(); ++mitr){ + out->writeInt((unsigned int)mitr->first); + out->writeInt((unsigned int)mitr->second); + } + } - // Write texture attributes, this could for instance texture2D, texturecubemap - nUnits = tal.size(); - out->writeInt(nUnits); - for(unit=0;unitwriteInt(al.size()); - for(StateSet::AttributeList::iterator aitr=al.begin(); aitr!=al.end(); ++aitr){ - // This is a Texture2D - if(dynamic_cast(aitr->second.first.get())){ - ((ive::Texture2D*)(aitr->second.first.get()))->write(out); - out->writeInt(aitr->second.second); - } - // This is a TextureCubeMap - else if(dynamic_cast(aitr->second.first.get())){ - ((ive::TextureCubeMap*)(aitr->second.first.get()))->write(out); - out->writeInt(aitr->second.second); - } - // This is a TexEnv - else if(dynamic_cast(aitr->second.first.get())){ - ((ive::TexEnv*)(aitr->second.first.get()))->write(out); - out->writeInt(aitr->second.second); - } - // This is a TexEnvCombine - else if(dynamic_cast(aitr->second.first.get())){ - ((ive::TexEnvCombine*)(aitr->second.first.get()))->write(out); - out->writeInt(aitr->second.second); - } - // This is a TexGen - else if(dynamic_cast(aitr->second.first.get())){ - ((ive::TexGen*)(aitr->second.first.get()))->write(out); - out->writeInt(aitr->second.second); - } - else{ - std::string className = (aitr->second.first.get())->className(); - throw Exception(std::string("StateSet::write(): Unknown Texture StateAttribute: ").append(className)); - } - } - } + // Write texture attributes, this could for instance texture2D, texturecubemap + nUnits = tal.size(); + out->writeInt(nUnits); + for(unit=0;unitwriteInt(al.size()); + for(StateSet::AttributeList::iterator aitr=al.begin(); aitr!=al.end(); ++aitr){ + out->writeStateAttribute(aitr->second.first.get()); + out->writeInt(aitr->second.second); + } + } } void StateSet::read(DataInputStream* in){ - // Read StateSet's identification. - int id = in->peekInt(); - if(id == IVESTATESET){ - // Code to read StateSet's properties. - id = in->readInt(); - - // If the osg class is inherited by any other class we should also read this from file. - osg::Object* obj = dynamic_cast(this); - if(obj){ - ((ive::Object*)(obj))->read(in);; - } - else - throw Exception("StateSet::read(): Could not cast this osg::StateSet to an osg::Object."); + // Read StateSet's identification. + int id = in->peekInt(); + if(id == IVESTATESET){ + // Code to read StateSet's properties. + id = in->readInt(); + + // If the osg class is inherited by any other class we should also read this from file. + osg::Object* obj = dynamic_cast(this); + if(obj){ + ((ive::Object*)(obj))->read(in);; + } + else + throw Exception("StateSet::read(): Could not cast this osg::StateSet to an osg::Object."); - // Read render bin details. - char c = in->readChar(); - int num = in->readInt(); - std::string name = in->readString(); - switch((int)c){ - case 0: - setRenderBinDetails(num, name, osg::StateSet::INHERIT_RENDERBIN_DETAILS); - break; - case 1: - setRenderBinDetails(num, name, osg::StateSet::USE_RENDERBIN_DETAILS); - break; - case 2: - setRenderBinDetails(num, name, osg::StateSet::OVERRIDE_RENDERBIN_DETAILS); - break; - case 3: - setRenderBinDetails(num, name, osg::StateSet::ENCLOSE_RENDERBIN_DETAILS); - break; - default: throw Exception("Unkown RenderBinMode in StateSet::read()"); - } + // Read render bin details. + char c = in->readChar(); + int num = in->readInt(); + std::string name = in->readString(); + switch((int)c){ + case 0: + setRenderBinDetails(num, name, osg::StateSet::INHERIT_RENDERBIN_DETAILS); + break; + case 1: + setRenderBinDetails(num, name, osg::StateSet::USE_RENDERBIN_DETAILS); + break; + case 2: + setRenderBinDetails(num, name, osg::StateSet::OVERRIDE_RENDERBIN_DETAILS); + break; + case 3: + setRenderBinDetails(num, name, osg::StateSet::ENCLOSE_RENDERBIN_DETAILS); + break; + default: throw Exception("Unkown RenderBinMode in StateSet::read()"); + } - // Read stateset modes. - int size = in->readInt(); + // Read stateset modes. + int size = in->readInt(); int i; - for(i=0;ireadInt(); - int value = in->readInt(); - setMode((osg::StateAttribute::GLMode)mode, (osg::StateAttribute::GLModeValue)value); - } + for(i=0;ireadInt(); + int value = in->readInt(); + setMode((osg::StateAttribute::GLMode)mode, (osg::StateAttribute::GLModeValue)value); + } - // Read state attributes - size = in->readInt(); - for(i=0;ipeekInt(); - if(attributeID == IVEBLENDFUNC){ - attribute = new osg::BlendFunc(); - ((ive::BlendFunc*)(attribute))->read(in); - setAttribute(attribute, (osg::StateAttribute::OverrideValue)in->readInt()); - } - else if(attributeID == IVEMATERIAL){ - attribute = new osg::Material(); - ((ive::Material*)(attribute))->read(in); - setAttribute(attribute, (osg::StateAttribute::OverrideValue)in->readInt()); - } - else if(attributeID == IVECULLFACE){ - attribute = new osg::CullFace(); - ((ive::CullFace*)(attribute))->read(in); - setAttribute(attribute, (osg::StateAttribute::OverrideValue)in->readInt()); - } - else{ - throw Exception("Unkown StateAttribute in StateSet::read()"); - } - } - - // Read texture stateset mode. - int nUnits = in->readInt(); + // Read state attributes + size = in->readInt(); + for(i=0;ireadStateAttribute(); + setAttribute(attribute, (osg::StateAttribute::OverrideValue)in->readInt()); + } + + // Read texture stateset mode. + int nUnits = in->readInt(); int unit; - for(unit=0;unitreadInt(); - for(i=0;ireadInt(); - int value = in->readInt(); - setTextureMode(unit,(osg::StateAttribute::GLMode)mode, (osg::StateAttribute::GLModeValue)value); - } - } + for(unit=0;unitreadInt(); + for(i=0;ireadInt(); + int value = in->readInt(); + setTextureMode(unit,(osg::StateAttribute::GLMode)mode, (osg::StateAttribute::GLModeValue)value); + } + } - // Read texture attributes. - nUnits = in->readInt(); - for(unit=0;unitreadInt(); - for(i=0;ipeekInt(); - if(attributeID == IVETEXTURE2D){ - attribute = new osg::Texture2D(); - ((ive::Texture2D*)(attribute))->read(in); - setTextureAttribute(unit, attribute, (osg::StateAttribute::OverrideValue)in->readInt()); - } - else if(attributeID == IVETEXTURECUBEMAP){ - attribute = new osg::TextureCubeMap(); - ((ive::TextureCubeMap*)(attribute))->read(in); - setTextureAttribute(unit, attribute, (osg::StateAttribute::OverrideValue)in->readInt()); - } - else if(attributeID == IVETEXENV){ - attribute = new osg::TexEnv(); - ((ive::TexEnv*)(attribute))->read(in); - setTextureAttribute(unit, attribute, (osg::StateAttribute::OverrideValue)in->readInt()); - } - else if(attributeID == IVETEXENVCOMBINE){ - attribute = new osg::TexEnvCombine(); - ((ive::TexEnvCombine*)(attribute))->read(in); - setTextureAttribute(unit, attribute, (osg::StateAttribute::OverrideValue)in->readInt()); - } - else if(attributeID == IVETEXGEN){ - attribute = new osg::TexGen(); - ((ive::TexGen*)(attribute))->read(in); - setTextureAttribute(unit, attribute, (osg::StateAttribute::OverrideValue)in->readInt()); - } - else{ - throw Exception("Unkown Texture StateAttribute in StateSet::read()"); - } - } - } - } - else{ - throw Exception("StateSet::read(): Expected StateSet identification"); - } + // Read texture attributes. + nUnits = in->readInt(); + for(unit=0;unitreadInt(); + for(i=0;ireadStateAttribute(); + setTextureAttribute(unit, attribute, (osg::StateAttribute::OverrideValue)in->readInt()); + } + } + } + else{ + throw Exception("StateSet::read(): Expected StateSet identification"); + } } diff --git a/src/osgPlugins/ive/Texture2D.cpp b/src/osgPlugins/ive/Texture2D.cpp index b451f38c0..7d3a2be35 100644 --- a/src/osgPlugins/ive/Texture2D.cpp +++ b/src/osgPlugins/ive/Texture2D.cpp @@ -38,7 +38,7 @@ void Texture2D::write(DataOutputStream* out){ // Include image data in stream if(includeImg){ - out->writeInt((int)getImage()); + out->writeLong((long)getImage()); if(getImage()) ((ive::Image*)getImage())->write(out); } diff --git a/src/osgPlugins/ive/TextureCubeMap.cpp b/src/osgPlugins/ive/TextureCubeMap.cpp index f397e679e..8e21589b4 100644 --- a/src/osgPlugins/ive/TextureCubeMap.cpp +++ b/src/osgPlugins/ive/TextureCubeMap.cpp @@ -41,27 +41,27 @@ void TextureCubeMap::write(DataOutputStream* out){ out->writeInt(getNumMipmapLevels()); // Write images if any - out->writeInt((int)getImage(osg::TextureCubeMap::POSITIVE_X)); + out->writeLong((long)getImage(osg::TextureCubeMap::POSITIVE_X)); if(getImage(osg::TextureCubeMap::POSITIVE_X)) ((ive::Image*)(getImage(osg::TextureCubeMap::POSITIVE_X)))->write(out); - out->writeInt((int)getImage(osg::TextureCubeMap::NEGATIVE_X)); + out->writeLong((long)getImage(osg::TextureCubeMap::NEGATIVE_X)); if(getImage(osg::TextureCubeMap::NEGATIVE_X)) ((ive::Image*)(getImage(osg::TextureCubeMap::NEGATIVE_X)))->write(out); - out->writeInt((int)getImage(osg::TextureCubeMap::POSITIVE_Y)); + out->writeLong((long)getImage(osg::TextureCubeMap::POSITIVE_Y)); if(getImage(osg::TextureCubeMap::POSITIVE_Y)) ((ive::Image*)(getImage(osg::TextureCubeMap::POSITIVE_Y)))->write(out); - out->writeInt((int)getImage(osg::TextureCubeMap::NEGATIVE_Y)); + out->writeLong((long)getImage(osg::TextureCubeMap::NEGATIVE_Y)); if(getImage(osg::TextureCubeMap::NEGATIVE_Y)) ((ive::Image*)(getImage(osg::TextureCubeMap::NEGATIVE_Y)))->write(out); - out->writeInt((int)getImage(osg::TextureCubeMap::POSITIVE_Z)); + out->writeLong((long)getImage(osg::TextureCubeMap::POSITIVE_Z)); if(getImage(osg::TextureCubeMap::POSITIVE_Z)) ((ive::Image*)(getImage(osg::TextureCubeMap::POSITIVE_Z)))->write(out); - out->writeInt((int)getImage(osg::TextureCubeMap::NEGATIVE_Z)); + out->writeLong((long)getImage(osg::TextureCubeMap::NEGATIVE_Z)); if(getImage(osg::TextureCubeMap::NEGATIVE_Z)) ((ive::Image*)(getImage(osg::TextureCubeMap::NEGATIVE_Z)))->write(out); diff --git a/src/osgPlugins/obj/ReaderWriterOBJ.cpp b/src/osgPlugins/obj/ReaderWriterOBJ.cpp index 17dac2681..44ebc8e14 100644 --- a/src/osgPlugins/obj/ReaderWriterOBJ.cpp +++ b/src/osgPlugins/obj/ReaderWriterOBJ.cpp @@ -14,7 +14,7 @@ */ #if defined(_MSC_VER) - #pragma warning( disable : 4786 ) + #pragma warning( disable : 4786 ) #endif #include @@ -118,8 +118,14 @@ osgDB::ReaderWriter::ReadResult ReaderWriterOBJ::readNode(const std::string& fil omtl->emmissive[2], omtl->emmissive[3])); // note, osg shininess scales between 0.0 and 1.0. mtl->setShininess(osg::Material::FRONT_AND_BACK, omtl->shininess); + mtl->setAlpha(osg::Material::FRONT_AND_BACK, omtl->alpha); stateset->setAttribute(mtl); + + if (omtl->alpha<1.0f) { + stateset->setMode(GL_BLEND,osg::StateAttribute::ON); + stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN); + } if (omtl->textureName) { @@ -158,9 +164,9 @@ osgDB::ReaderWriter::ReadResult ReaderWriterOBJ::readNode(const std::string& fil osg::Group* osg_top = NULL; if (obj->position[0] != 0.0f || obj->position[2] != 0.0f || obj->position[2] != 0.0f) { osg::MatrixTransform* xform = new osg::MatrixTransform; - // note obj_x -> osg_x, - // obj_y -> osg_z, - // obj_z -> osg_y, + // note obj_x -> osg_x, + // obj_y -> osg_z, + // obj_z -> osg_y, xform->setMatrix(osg::Matrix::translate(obj->position[0], obj->position[2], obj->position[1])); osg_top = xform; } diff --git a/src/osgPlugins/obj/glm.cpp b/src/osgPlugins/obj/glm.cpp index 9bd34bc46..f22dd1010 100644 --- a/src/osgPlugins/obj/glm.cpp +++ b/src/osgPlugins/obj/glm.cpp @@ -24,7 +24,7 @@ /* enums */ -enum { X, Y, Z, W }; /* elements of a vertex */ +enum { X, Y, Z, W }; /* elements of a vertex */ /* typedefs */ @@ -151,7 +151,7 @@ _glmWeldVectors(GLfloat* vectors, unsigned int* numvectors, GLfloat epsilon) for (i = 1; i <= *numvectors; i++) { for (j = 1; j <= copied; j++) { if (_glmEqual(&vectors[3 * i], &copies[3 * j], epsilon)) { - goto duplicate; + goto duplicate; } } @@ -159,7 +159,7 @@ _glmWeldVectors(GLfloat* vectors, unsigned int* numvectors, GLfloat epsilon) copies[3 * copied + 0] = vectors[3 * i + 0]; copies[3 * copied + 1] = vectors[3 * i + 1]; copies[3 * copied + 2] = vectors[3 * i + 2]; - j = copied; /* pass this along for below */ + j = copied; /* pass this along for below */ copied++; duplicate: @@ -338,6 +338,7 @@ _glmReadMTL(GLMmodel* model, char* name) model->materials[i].specular[2] = 0.0f; model->materials[i].textureName = NULL; model->materials[i].textureReflection = false; + model->materials[i].alpha = 1.0f; } model->materials[0].name = strdup("default"); @@ -361,30 +362,33 @@ _glmReadMTL(GLMmodel* model, char* name) model->materials[nummaterials].shininess /= 1000.0; model->materials[nummaterials].shininess *= 128.0; break; + case 'd': + fscanf(file, "%f", &model->materials[nummaterials].alpha); + break; case 'K': switch(buf[1]) { case 'd': - fscanf(file, "%f %f %f", - &model->materials[nummaterials].diffuse[0], - &model->materials[nummaterials].diffuse[1], - &model->materials[nummaterials].diffuse[2]); - break; + fscanf(file, "%f %f %f", + &model->materials[nummaterials].diffuse[0], + &model->materials[nummaterials].diffuse[1], + &model->materials[nummaterials].diffuse[2]); + break; case 's': - fscanf(file, "%f %f %f", - &model->materials[nummaterials].specular[0], - &model->materials[nummaterials].specular[1], - &model->materials[nummaterials].specular[2]); - break; + fscanf(file, "%f %f %f", + &model->materials[nummaterials].specular[0], + &model->materials[nummaterials].specular[1], + &model->materials[nummaterials].specular[2]); + break; case 'a': - fscanf(file, "%f %f %f", - &model->materials[nummaterials].ambient[0], - &model->materials[nummaterials].ambient[1], - &model->materials[nummaterials].ambient[2]); - break; + fscanf(file, "%f %f %f", + &model->materials[nummaterials].ambient[0], + &model->materials[nummaterials].ambient[1], + &model->materials[nummaterials].ambient[2]); + break; default: - /* eat up rest of line */ - fgets(buf, sizeof(buf), file); - break; + /* eat up rest of line */ + fgets(buf, sizeof(buf), file); + break; } break; @@ -455,11 +459,11 @@ _glmWriteMTL(GLMmodel* model, char* modelpath, char* mtllibname) material = &model->materials[i]; fprintf(file, "newmtl %s\n", material->name); fprintf(file, "Ka %f %f %f\n", - material->ambient[0], material->ambient[1], material->ambient[2]); + material->ambient[0], material->ambient[1], material->ambient[2]); fprintf(file, "Kd %f %f %f\n", - material->diffuse[0], material->diffuse[1], material->diffuse[2]); + material->diffuse[0], material->diffuse[1], material->diffuse[2]); fprintf(file, "Ks %f %f %f\n", - material->specular[0],material->specular[1],material->specular[2]); + material->specular[0],material->specular[1],material->specular[2]); fprintf(file, "Ns %f\n", material->shininess); fprintf(file, "\n"); } @@ -493,11 +497,11 @@ static void createCompositeName(char* buf,char* compositeName) static GLvoid _glmFirstPass(GLMmodel* model, FILE* file) { - unsigned int numvertices; /* number of vertices in model */ - unsigned int numnormals; /* number of normals in model */ - unsigned int numtexcoords; /* number of texcoords in model */ - unsigned int numtriangles; /* number of triangles in model */ - GLMgroup* group; /* current group */ + unsigned int numvertices; /* number of vertices in model */ + unsigned int numnormals; /* number of normals in model */ + unsigned int numtexcoords; /* number of texcoords in model */ + unsigned int numtriangles; /* number of triangles in model */ + GLMgroup* group; /* current group */ unsigned v, n, t; char buf[128]; @@ -507,32 +511,32 @@ _glmFirstPass(GLMmodel* model, FILE* file) numvertices = numnormals = numtexcoords = numtriangles = 0; while(fscanf(file, "%s", buf) != EOF) { switch(buf[0]) { - case '#': /* comment */ + case '#': /* comment */ /* eat up rest of line */ fgets(buf, sizeof(buf), file); break; - case 'v': /* v, vn, vt */ + case 'v': /* v, vn, vt */ switch(buf[1]) { - case '\0': /* vertex */ - /* eat up rest of line */ - fgets(buf, sizeof(buf), file); - numvertices++; - break; - case 'n': /* normal */ - /* eat up rest of line */ - fgets(buf, sizeof(buf), file); - numnormals++; - break; - case 't': /* texcoord */ - /* eat up rest of line */ - fgets(buf, sizeof(buf), file); - numtexcoords++; - break; + case '\0': /* vertex */ + /* eat up rest of line */ + fgets(buf, sizeof(buf), file); + numvertices++; + break; + case 'n': /* normal */ + /* eat up rest of line */ + fgets(buf, sizeof(buf), file); + numnormals++; + break; + case 't': /* texcoord */ + /* eat up rest of line */ + fgets(buf, sizeof(buf), file); + numtexcoords++; + break; default: - printf("_glmFirstPass(): Unknown token \"%s\".\n", buf); - //exit(1); - return; - break; + printf("_glmFirstPass(): Unknown token \"%s\".\n", buf); + //exit(1); + return; + break; } break; case 'm': @@ -545,7 +549,7 @@ _glmFirstPass(GLMmodel* model, FILE* file) /* eat up rest of line */ fgets(buf, sizeof(buf), file); break; - case 'g': /* group */ + case 'g': /* group */ { /* eat up rest of line */ fgets(buf, sizeof(buf), file); @@ -556,51 +560,51 @@ _glmFirstPass(GLMmodel* model, FILE* file) group = _glmAddGroup(model, compositeName); } break; - case 'f': /* face */ + case 'f': /* face */ v = n = t = 0; fscanf(file, "%s", buf); /* can be one of %d, %d//%d, %d/%d, %d/%d/%d %d//%d */ if (strstr(buf, "//")) { - /* v//n */ - sscanf(buf, "%d//%d", &v, &n); - fscanf(file, "%d//%d", &v, &n); - fscanf(file, "%d//%d", &v, &n); - numtriangles++; - group->numtriangles++; - while(fscanf(file, "%d//%d", &v, &n) > 0) { - numtriangles++; - group->numtriangles++; - } + /* v//n */ + sscanf(buf, "%d//%d", &v, &n); + fscanf(file, "%d//%d", &v, &n); + fscanf(file, "%d//%d", &v, &n); + numtriangles++; + group->numtriangles++; + while(fscanf(file, "%d//%d", &v, &n) > 0) { + numtriangles++; + group->numtriangles++; + } } else if (sscanf(buf, "%d/%d/%d", &v, &t, &n) == 3) { - /* v/t/n */ - fscanf(file, "%d/%d/%d", &v, &t, &n); - fscanf(file, "%d/%d/%d", &v, &t, &n); - numtriangles++; - group->numtriangles++; - while(fscanf(file, "%d/%d/%d", &v, &t, &n) > 0) { - numtriangles++; - group->numtriangles++; - } + /* v/t/n */ + fscanf(file, "%d/%d/%d", &v, &t, &n); + fscanf(file, "%d/%d/%d", &v, &t, &n); + numtriangles++; + group->numtriangles++; + while(fscanf(file, "%d/%d/%d", &v, &t, &n) > 0) { + numtriangles++; + group->numtriangles++; + } } else if (sscanf(buf, "%d/%d", &v, &t) == 2) { - /* v/t */ - fscanf(file, "%d/%d", &v, &t); - fscanf(file, "%d/%d", &v, &t); - numtriangles++; - group->numtriangles++; - while(fscanf(file, "%d/%d", &v, &t) > 0) { - numtriangles++; - group->numtriangles++; - } + /* v/t */ + fscanf(file, "%d/%d", &v, &t); + fscanf(file, "%d/%d", &v, &t); + numtriangles++; + group->numtriangles++; + while(fscanf(file, "%d/%d", &v, &t) > 0) { + numtriangles++; + group->numtriangles++; + } } else { - /* v */ - fscanf(file, "%d", &v); - fscanf(file, "%d", &v); - numtriangles++; - group->numtriangles++; - while(fscanf(file, "%d", &v) > 0) { - numtriangles++; - group->numtriangles++; - } + /* v */ + fscanf(file, "%d", &v); + fscanf(file, "%d", &v); + numtriangles++; + group->numtriangles++; + while(fscanf(file, "%d", &v) > 0) { + numtriangles++; + group->numtriangles++; + } } break; @@ -644,15 +648,15 @@ _glmFirstPass(GLMmodel* model, FILE* file) static GLvoid _glmSecondPass(GLMmodel* model, FILE* file) { - unsigned int numvertices; /* number of vertices in model */ - unsigned int numnormals; /* number of normals in model */ - unsigned int numtexcoords; /* number of texcoords in model */ - unsigned int numtriangles; /* number of triangles in model */ - GLfloat* vertices; /* array of vertices */ - GLfloat* normals; /* array of normals */ - GLfloat* texcoords; /* array of texture coordinates */ - GLMgroup* group; /* current group pointer */ - unsigned int material; /* current material */ + unsigned int numvertices; /* number of vertices in model */ + unsigned int numnormals; /* number of normals in model */ + unsigned int numtexcoords; /* number of texcoords in model */ + unsigned int numtriangles; /* number of triangles in model */ + GLfloat* vertices; /* array of vertices */ + GLfloat* normals; /* array of normals */ + GLfloat* texcoords; /* array of texture coordinates */ + GLMgroup* group; /* current group pointer */ + unsigned int material; /* current material */ unsigned int v, n, t; char buf[128]; @@ -674,32 +678,32 @@ _glmSecondPass(GLMmodel* model, FILE* file) while(fscanf(file, "%s", buf) != EOF) { char c = buf[0]; switch(c) { - case '#': /* comment */ + case '#': /* comment */ /* eat up rest of line */ fgets(buf, sizeof(buf), file); break; - case 'v': /* v, vn, vt */ + case 'v': /* v, vn, vt */ switch(buf[1]) { - case '\0': /* vertex */ - fscanf(file, "%f %f %f", - &vertices[3 * numvertices + X], - &vertices[3 * numvertices + Y], - &vertices[3 * numvertices + Z]); - numvertices++; - break; - case 'n': /* normal */ - fscanf(file, "%f %f %f", - &normals[3 * numnormals + X], - &normals[3 * numnormals + Y], - &normals[3 * numnormals + Z]); - numnormals++; - break; - case 't': /* texcoord */ - fscanf(file, "%f %f", - &texcoords[2 * numtexcoords + X], - &texcoords[2 * numtexcoords + Y]); - numtexcoords++; - break; + case '\0': /* vertex */ + fscanf(file, "%f %f %f", + &vertices[3 * numvertices + X], + &vertices[3 * numvertices + Y], + &vertices[3 * numvertices + Z]); + numvertices++; + break; + case 'n': /* normal */ + fscanf(file, "%f %f %f", + &normals[3 * numnormals + X], + &normals[3 * numnormals + Y], + &normals[3 * numnormals + Z]); + numnormals++; + break; + case 't': /* texcoord */ + fscanf(file, "%f %f", + &texcoords[2 * numtexcoords + X], + &texcoords[2 * numtexcoords + Y]); + numtexcoords++; + break; } break; case 'u': @@ -714,7 +718,7 @@ _glmSecondPass(GLMmodel* model, FILE* file) if (previousLineWas_g || firstGroup) group->material = material; break; - case 'g': /* group */ + case 'g': /* group */ /* eat up rest of line */ fgets(buf, sizeof(buf), file); char compositeName[128]; @@ -724,102 +728,102 @@ _glmSecondPass(GLMmodel* model, FILE* file) group->material = material; firstGroup = false; break; - case 'f': /* face */ + case 'f': /* face */ v = n = t = 0; fscanf(file, "%s", buf); /* can be one of %d, %d//%d, %d/%d, %d/%d/%d %d//%d */ if (strstr(buf, "//")) { - /* v//n */ - sscanf(buf, "%d//%d", &v, &n); - T(numtriangles).vindices[0] = v; - T(numtriangles).nindices[0] = n; - fscanf(file, "%d//%d", &v, &n); - T(numtriangles).vindices[1] = v; - T(numtriangles).nindices[1] = n; - fscanf(file, "%d//%d", &v, &n); - T(numtriangles).vindices[2] = v; - T(numtriangles).nindices[2] = n; - group->triangles[group->numtriangles++] = numtriangles; - numtriangles++; - while(fscanf(file, "%d//%d", &v, &n) > 0) { - T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0]; - T(numtriangles).nindices[0] = T(numtriangles-1).nindices[0]; - T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2]; - T(numtriangles).nindices[1] = T(numtriangles-1).nindices[2]; - T(numtriangles).vindices[2] = v; - T(numtriangles).nindices[2] = n; - group->triangles[group->numtriangles++] = numtriangles; - numtriangles++; - } + /* v//n */ + sscanf(buf, "%d//%d", &v, &n); + T(numtriangles).vindices[0] = v; + T(numtriangles).nindices[0] = n; + fscanf(file, "%d//%d", &v, &n); + T(numtriangles).vindices[1] = v; + T(numtriangles).nindices[1] = n; + fscanf(file, "%d//%d", &v, &n); + T(numtriangles).vindices[2] = v; + T(numtriangles).nindices[2] = n; + group->triangles[group->numtriangles++] = numtriangles; + numtriangles++; + while(fscanf(file, "%d//%d", &v, &n) > 0) { + T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0]; + T(numtriangles).nindices[0] = T(numtriangles-1).nindices[0]; + T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2]; + T(numtriangles).nindices[1] = T(numtriangles-1).nindices[2]; + T(numtriangles).vindices[2] = v; + T(numtriangles).nindices[2] = n; + group->triangles[group->numtriangles++] = numtriangles; + numtriangles++; + } } else if (sscanf(buf, "%d/%d/%d", &v, &t, &n) == 3) { - /* v/t/n */ - T(numtriangles).vindices[0] = v; - T(numtriangles).tindices[0] = t; - T(numtriangles).nindices[0] = n; - fscanf(file, "%d/%d/%d", &v, &t, &n); - T(numtriangles).vindices[1] = v; - T(numtriangles).tindices[1] = t; - T(numtriangles).nindices[1] = n; - fscanf(file, "%d/%d/%d", &v, &t, &n); - T(numtriangles).vindices[2] = v; - T(numtriangles).tindices[2] = t; - T(numtriangles).nindices[2] = n; - group->triangles[group->numtriangles++] = numtriangles; - group->hastexcoords = true; - numtriangles++; - while(fscanf(file, "%d/%d/%d", &v, &t, &n) > 0) { - T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0]; - T(numtriangles).tindices[0] = T(numtriangles-1).tindices[0]; - T(numtriangles).nindices[0] = T(numtriangles-1).nindices[0]; - T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2]; - T(numtriangles).tindices[1] = T(numtriangles-1).tindices[2]; - T(numtriangles).nindices[1] = T(numtriangles-1).nindices[2]; - T(numtriangles).vindices[2] = v; - T(numtriangles).tindices[2] = t; - T(numtriangles).nindices[2] = n; - group->triangles[group->numtriangles++] = numtriangles; - numtriangles++; - } + /* v/t/n */ + T(numtriangles).vindices[0] = v; + T(numtriangles).tindices[0] = t; + T(numtriangles).nindices[0] = n; + fscanf(file, "%d/%d/%d", &v, &t, &n); + T(numtriangles).vindices[1] = v; + T(numtriangles).tindices[1] = t; + T(numtriangles).nindices[1] = n; + fscanf(file, "%d/%d/%d", &v, &t, &n); + T(numtriangles).vindices[2] = v; + T(numtriangles).tindices[2] = t; + T(numtriangles).nindices[2] = n; + group->triangles[group->numtriangles++] = numtriangles; + group->hastexcoords = true; + numtriangles++; + while(fscanf(file, "%d/%d/%d", &v, &t, &n) > 0) { + T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0]; + T(numtriangles).tindices[0] = T(numtriangles-1).tindices[0]; + T(numtriangles).nindices[0] = T(numtriangles-1).nindices[0]; + T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2]; + T(numtriangles).tindices[1] = T(numtriangles-1).tindices[2]; + T(numtriangles).nindices[1] = T(numtriangles-1).nindices[2]; + T(numtriangles).vindices[2] = v; + T(numtriangles).tindices[2] = t; + T(numtriangles).nindices[2] = n; + group->triangles[group->numtriangles++] = numtriangles; + numtriangles++; + } } else if (sscanf(buf, "%d/%d", &v, &t) == 2) { - /* v/t */ - T(numtriangles).vindices[0] = v; - T(numtriangles).tindices[0] = t; - fscanf(file, "%d/%d", &v, &t); - T(numtriangles).vindices[1] = v; - T(numtriangles).tindices[1] = t; - fscanf(file, "%d/%d", &v, &t); - T(numtriangles).vindices[2] = v; - T(numtriangles).tindices[2] = t; - group->triangles[group->numtriangles++] = numtriangles; - group->hastexcoords = true; - numtriangles++; - while(fscanf(file, "%d/%d", &v, &t) > 0) { - T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0]; - T(numtriangles).tindices[0] = T(numtriangles-1).tindices[0]; - T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2]; - T(numtriangles).tindices[1] = T(numtriangles-1).tindices[2]; - T(numtriangles).vindices[2] = v; - T(numtriangles).tindices[2] = t; - group->triangles[group->numtriangles++] = numtriangles; - numtriangles++; - } + /* v/t */ + T(numtriangles).vindices[0] = v; + T(numtriangles).tindices[0] = t; + fscanf(file, "%d/%d", &v, &t); + T(numtriangles).vindices[1] = v; + T(numtriangles).tindices[1] = t; + fscanf(file, "%d/%d", &v, &t); + T(numtriangles).vindices[2] = v; + T(numtriangles).tindices[2] = t; + group->triangles[group->numtriangles++] = numtriangles; + group->hastexcoords = true; + numtriangles++; + while(fscanf(file, "%d/%d", &v, &t) > 0) { + T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0]; + T(numtriangles).tindices[0] = T(numtriangles-1).tindices[0]; + T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2]; + T(numtriangles).tindices[1] = T(numtriangles-1).tindices[2]; + T(numtriangles).vindices[2] = v; + T(numtriangles).tindices[2] = t; + group->triangles[group->numtriangles++] = numtriangles; + numtriangles++; + } } else { - /* v */ - sscanf(buf, "%d", &v); - T(numtriangles).vindices[0] = v; - fscanf(file, "%d", &v); - T(numtriangles).vindices[1] = v; - fscanf(file, "%d", &v); - T(numtriangles).vindices[2] = v; - group->triangles[group->numtriangles++] = numtriangles; - numtriangles++; - while(fscanf(file, "%d", &v) > 0) { - T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0]; - T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2]; - T(numtriangles).vindices[2] = v; - group->triangles[group->numtriangles++] = numtriangles; - numtriangles++; - } + /* v */ + sscanf(buf, "%d", &v); + T(numtriangles).vindices[0] = v; + fscanf(file, "%d", &v); + T(numtriangles).vindices[1] = v; + fscanf(file, "%d", &v); + T(numtriangles).vindices[2] = v; + group->triangles[group->numtriangles++] = numtriangles; + numtriangles++; + while(fscanf(file, "%d", &v) > 0) { + T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0]; + T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2]; + T(numtriangles).vindices[2] = v; + group->triangles[group->numtriangles++] = numtriangles; + numtriangles++; + } } break; @@ -837,10 +841,10 @@ _glmSecondPass(GLMmodel* model, FILE* file) #if 0 /* announce the memory requirements */ printf(" Memory: %d bytes\n", - numvertices * 3*sizeof(GLfloat) + - numnormals * 3*sizeof(GLfloat) * (numnormals ? 1 : 0) + - numtexcoords * 3*sizeof(GLfloat) * (numtexcoords ? 1 : 0) + - numtriangles * sizeof(GLMtriangle)); + numvertices * 3*sizeof(GLfloat) + + numnormals * 3*sizeof(GLfloat) * (numnormals ? 1 : 0) + + numtexcoords * 3*sizeof(GLfloat) * (numtexcoords ? 1 : 0) + + numtriangles * sizeof(GLMtriangle)); #endif } @@ -1042,7 +1046,7 @@ glmFacetNormals(GLMmodel* model) /* allocate memory for the new facet normals */ model->numfacetnorms = model->numtriangles; model->facetnorms = (GLfloat*)malloc(sizeof(GLfloat) * - 3 * (model->numfacetnorms + 1)); + 3 * (model->numfacetnorms + 1)); for (i = 0; i < model->numtriangles; i++) { model->triangles[i].findex = i+1; @@ -1148,15 +1152,15 @@ glmVertexNormals(GLMmodel* model, GLfloat angle) angle -- or, said another way, the angle between the two facet normals is less than (or equal to) the threshold angle */ dot = _glmDot(&model->facetnorms[3 * T(node->index).findex], - &model->facetnorms[3 * T(members[i]->index).findex]); + &model->facetnorms[3 * T(members[i]->index).findex]); if (dot > cos_angle) { - node->averaged = GL_TRUE; - average[0] += model->facetnorms[3 * T(node->index).findex + 0]; - average[1] += model->facetnorms[3 * T(node->index).findex + 1]; - average[2] += model->facetnorms[3 * T(node->index).findex + 2]; - avg = 1; /* we averaged at least one normal! */ + node->averaged = GL_TRUE; + average[0] += model->facetnorms[3 * T(node->index).findex + 0]; + average[1] += model->facetnorms[3 * T(node->index).findex + 1]; + average[2] += model->facetnorms[3 * T(node->index).findex + 2]; + avg = 1; /* we averaged at least one normal! */ } else { - node->averaged = GL_FALSE; + node->averaged = GL_FALSE; } node = node->next; } @@ -1177,28 +1181,28 @@ glmVertexNormals(GLMmodel* model, GLfloat angle) node = members[i]; while (node) { if (node->averaged) { - /* if this node was averaged, use the average normal */ - if (T(node->index).vindices[0] == i) - T(node->index).nindices[0] = avg; - else if (T(node->index).vindices[1] == i) - T(node->index).nindices[1] = avg; - else if (T(node->index).vindices[2] == i) - T(node->index).nindices[2] = avg; + /* if this node was averaged, use the average normal */ + if (T(node->index).vindices[0] == i) + T(node->index).nindices[0] = avg; + else if (T(node->index).vindices[1] == i) + T(node->index).nindices[1] = avg; + else if (T(node->index).vindices[2] == i) + T(node->index).nindices[2] = avg; } else { - /* if this node wasn't averaged, use the facet normal */ - model->normals[3 * numnormals + 0] = - model->facetnorms[3 * T(node->index).findex + 0]; - model->normals[3 * numnormals + 1] = - model->facetnorms[3 * T(node->index).findex + 1]; - model->normals[3 * numnormals + 2] = - model->facetnorms[3 * T(node->index).findex + 2]; - if (T(node->index).vindices[0] == i) - T(node->index).nindices[0] = numnormals; - else if (T(node->index).vindices[1] == i) - T(node->index).nindices[1] = numnormals; - else if (T(node->index).vindices[2] == i) - T(node->index).nindices[2] = numnormals; - numnormals++; + /* if this node wasn't averaged, use the facet normal */ + model->normals[3 * numnormals + 0] = + model->facetnorms[3 * T(node->index).findex + 0]; + model->normals[3 * numnormals + 1] = + model->facetnorms[3 * T(node->index).findex + 1]; + model->normals[3 * numnormals + 2] = + model->facetnorms[3 * T(node->index).findex + 2]; + if (T(node->index).vindices[0] == i) + T(node->index).nindices[0] = numnormals; + else if (T(node->index).vindices[1] == i) + T(node->index).nindices[1] = numnormals; + else if (T(node->index).vindices[2] == i) + T(node->index).nindices[2] = numnormals; + numnormals++; } node = node->next; } @@ -1280,7 +1284,7 @@ glmLinearTexture(GLMmodel* model) #if 0 printf("glmLinearTexture(): generated %d linear texture coordinates\n", - model->numtexcoords); + model->numtexcoords); #endif } @@ -1312,32 +1316,32 @@ glmSpheremapTexture(GLMmodel* model) /* do the calculations */ for (i = 1; i <= model->numnormals; i++) { - z = model->normals[3 * i + 0]; /* re-arrange for pole distortion */ + z = model->normals[3 * i + 0]; /* re-arrange for pole distortion */ y = model->normals[3 * i + 1]; x = model->normals[3 * i + 2]; r = sqrtf((x * x) + (y * y)); rho = sqrtf((r * r) + (z * z)); if(r == 0.0f) { - theta = 0.0f; - phi = 0.0f; + theta = 0.0f; + phi = 0.0f; } else { if(z == 0.0) - phi = 3.14159265f / 2.0f; + phi = 3.14159265f / 2.0f; else - phi = acosf(z / rho); + phi = acosf(z / rho); #if WE_DONT_NEED_THIS_CODE if(x == 0.0) - theta = 3.14159265f / 2.0f; /* asin(y / r); */ + theta = 3.14159265f / 2.0f; /* asin(y / r); */ else - theta = acos(x / r); + theta = acos(x / r); #endif if(y == 0.0) - theta = 3.141592365f / 2.0f; /* acos(x / r); */ + theta = 3.141592365f / 2.0f; /* acos(x / r); */ else - theta = asinf(y / r) + 3.14159265f / 2.0f; + theta = asinf(y / r) + 3.14159265f / 2.0f; } model->texcoords[2 * i + 0] = theta / 3.14159265f; @@ -1357,7 +1361,7 @@ glmSpheremapTexture(GLMmodel* model) #if 0 printf("glmSpheremapTexture(): generated %d spheremap texture coordinates\n", - model->numtexcoords); + model->numtexcoords); #endif } @@ -1415,9 +1419,9 @@ glmReadOBJ(char* filename) file = fopen(filename, "r"); if (!file) { fprintf(stderr, "glmReadOBJ() failed: can't open data file \"%s\".\n", - filename); + filename); //exit(1); - return NULL; + return NULL; } #if 0 @@ -1453,16 +1457,16 @@ glmReadOBJ(char* filename) /* allocate memory */ model->vertices = (GLfloat*)malloc(sizeof(GLfloat) * - 3 * (model->numvertices + 1)); + 3 * (model->numvertices + 1)); model->triangles = (GLMtriangle*)malloc(sizeof(GLMtriangle) * - model->numtriangles); + model->numtriangles); if (model->numnormals) { model->normals = (GLfloat*)malloc(sizeof(GLfloat) * - 3 * (model->numnormals + 1)); + 3 * (model->numnormals + 1)); } if (model->numtexcoords) { model->texcoords = (GLfloat*)malloc(sizeof(GLfloat) * - 2 * (model->numtexcoords + 1)); + 2 * (model->numtexcoords + 1)); } /* rewind to beginning of file and read in the data this pass */ @@ -1503,22 +1507,22 @@ glmWriteOBJ(GLMmodel* model, char* filename, unsigned int mode) /* do a bit of warning */ if (mode & GLM_FLAT && !model->facetnorms) { printf("glmWriteOBJ() warning: flat normal output requested " - "with no facet normals defined.\n"); + "with no facet normals defined.\n"); mode &= ~GLM_FLAT; } if (mode & GLM_SMOOTH && !model->normals) { printf("glmWriteOBJ() warning: smooth normal output requested " - "with no normals defined.\n"); + "with no normals defined.\n"); mode &= ~GLM_SMOOTH; } if (mode & GLM_TEXTURE && !model->texcoords) { printf("glmWriteOBJ() warning: texture coordinate output requested " - "with no texture coordinates defined.\n"); + "with no texture coordinates defined.\n"); mode &= ~GLM_TEXTURE; } if (mode & GLM_FLAT && mode & GLM_SMOOTH) { printf("glmWriteOBJ() warning: flat normal output requested " - "and smooth normal output requested (using smooth).\n"); + "and smooth normal output requested (using smooth).\n"); mode &= ~GLM_FLAT; } @@ -1526,9 +1530,9 @@ glmWriteOBJ(GLMmodel* model, char* filename, unsigned int mode) file = fopen(filename, "w"); if (!file) { fprintf(stderr, "glmWriteOBJ() failed: can't open file \"%s\" to write.\n", - filename); + filename); //exit(1); - return; + return; } /* spit out a header */ @@ -1550,9 +1554,9 @@ glmWriteOBJ(GLMmodel* model, char* filename, unsigned int mode) fprintf(file, "# %d vertices\n", model->numvertices); for (i = 1; i <= model->numvertices; i++) { fprintf(file, "v %f %f %f\n", - model->vertices[3 * i + 0], - model->vertices[3 * i + 1], - model->vertices[3 * i + 2]); + model->vertices[3 * i + 0], + model->vertices[3 * i + 1], + model->vertices[3 * i + 2]); } /* spit out the smooth/flat normals */ @@ -1561,18 +1565,18 @@ glmWriteOBJ(GLMmodel* model, char* filename, unsigned int mode) fprintf(file, "# %d normals\n", model->numnormals); for (i = 1; i <= model->numnormals; i++) { fprintf(file, "vn %f %f %f\n", - model->normals[3 * i + 0], - model->normals[3 * i + 1], - model->normals[3 * i + 2]); + model->normals[3 * i + 0], + model->normals[3 * i + 1], + model->normals[3 * i + 2]); } } else if (mode & GLM_FLAT) { fprintf(file, "\n"); fprintf(file, "# %d normals\n", model->numfacetnorms); for (i = 1; i <= model->numnormals; i++) { fprintf(file, "vn %f %f %f\n", - model->facetnorms[3 * i + 0], - model->facetnorms[3 * i + 1], - model->facetnorms[3 * i + 2]); + model->facetnorms[3 * i + 0], + model->facetnorms[3 * i + 1], + model->facetnorms[3 * i + 2]); } } @@ -1582,8 +1586,8 @@ glmWriteOBJ(GLMmodel* model, char* filename, unsigned int mode) fprintf(file, "# %d texcoords\n", model->numtexcoords); for (i = 1; i <= model->numtexcoords; i++) { fprintf(file, "vt %f %f\n", - model->texcoords[2 * i + 0], - model->texcoords[2 * i + 1]); + model->texcoords[2 * i + 0], + model->texcoords[2 * i + 1]); } } @@ -1599,53 +1603,53 @@ glmWriteOBJ(GLMmodel* model, char* filename, unsigned int mode) fprintf(file, "usemtl %s\n", model->materials[group->material].name); for (i = 0; i < group->numtriangles; i++) { if (mode & GLM_SMOOTH && mode & GLM_TEXTURE) { - fprintf(file, "f %d/%d/%d %d/%d/%d %d/%d/%d\n", - T(group->triangles[i]).vindices[0], - T(group->triangles[i]).nindices[0], - T(group->triangles[i]).tindices[0], - T(group->triangles[i]).vindices[1], - T(group->triangles[i]).nindices[1], - T(group->triangles[i]).tindices[1], - T(group->triangles[i]).vindices[2], - T(group->triangles[i]).nindices[2], - T(group->triangles[i]).tindices[2]); + fprintf(file, "f %d/%d/%d %d/%d/%d %d/%d/%d\n", + T(group->triangles[i]).vindices[0], + T(group->triangles[i]).nindices[0], + T(group->triangles[i]).tindices[0], + T(group->triangles[i]).vindices[1], + T(group->triangles[i]).nindices[1], + T(group->triangles[i]).tindices[1], + T(group->triangles[i]).vindices[2], + T(group->triangles[i]).nindices[2], + T(group->triangles[i]).tindices[2]); } else if (mode & GLM_FLAT && mode & GLM_TEXTURE) { - fprintf(file, "f %d/%d %d/%d %d/%d\n", - T(group->triangles[i]).vindices[0], - T(group->triangles[i]).findex, - T(group->triangles[i]).vindices[1], - T(group->triangles[i]).findex, - T(group->triangles[i]).vindices[2], - T(group->triangles[i]).findex); + fprintf(file, "f %d/%d %d/%d %d/%d\n", + T(group->triangles[i]).vindices[0], + T(group->triangles[i]).findex, + T(group->triangles[i]).vindices[1], + T(group->triangles[i]).findex, + T(group->triangles[i]).vindices[2], + T(group->triangles[i]).findex); } else if (mode & GLM_TEXTURE) { - fprintf(file, "f %d/%d %d/%d %d/%d\n", - T(group->triangles[i]).vindices[0], - T(group->triangles[i]).tindices[0], - T(group->triangles[i]).vindices[1], - T(group->triangles[i]).tindices[1], - T(group->triangles[i]).vindices[2], - T(group->triangles[i]).tindices[2]); + fprintf(file, "f %d/%d %d/%d %d/%d\n", + T(group->triangles[i]).vindices[0], + T(group->triangles[i]).tindices[0], + T(group->triangles[i]).vindices[1], + T(group->triangles[i]).tindices[1], + T(group->triangles[i]).vindices[2], + T(group->triangles[i]).tindices[2]); } else if (mode & GLM_SMOOTH) { - fprintf(file, "f %d//%d %d//%d %d//%d\n", - T(group->triangles[i]).vindices[0], - T(group->triangles[i]).nindices[0], - T(group->triangles[i]).vindices[1], - T(group->triangles[i]).nindices[1], - T(group->triangles[i]).vindices[2], - T(group->triangles[i]).nindices[2]); + fprintf(file, "f %d//%d %d//%d %d//%d\n", + T(group->triangles[i]).vindices[0], + T(group->triangles[i]).nindices[0], + T(group->triangles[i]).vindices[1], + T(group->triangles[i]).nindices[1], + T(group->triangles[i]).vindices[2], + T(group->triangles[i]).nindices[2]); } else if (mode & GLM_FLAT) { - fprintf(file, "f %d//%d %d//%d %d//%d\n", - T(group->triangles[i]).vindices[0], - T(group->triangles[i]).findex, - T(group->triangles[i]).vindices[1], - T(group->triangles[i]).findex, - T(group->triangles[i]).vindices[2], - T(group->triangles[i]).findex); + fprintf(file, "f %d//%d %d//%d %d//%d\n", + T(group->triangles[i]).vindices[0], + T(group->triangles[i]).findex, + T(group->triangles[i]).vindices[1], + T(group->triangles[i]).findex, + T(group->triangles[i]).vindices[2], + T(group->triangles[i]).findex); } else { - fprintf(file, "f %d %d %d\n", - T(group->triangles[i]).vindices[0], - T(group->triangles[i]).vindices[1], - T(group->triangles[i]).vindices[2]); + fprintf(file, "f %d %d %d\n", + T(group->triangles[i]).vindices[0], + T(group->triangles[i]).vindices[1], + T(group->triangles[i]).vindices[2]); } } fprintf(file, "\n"); @@ -1677,7 +1681,7 @@ glmWeld(GLMmodel* model, GLfloat epsilon) copies = _glmWeldVectors(vectors, &numvectors, epsilon); printf("glmWeld(): %d redundant vertices.\n", - model->numvertices - numvectors - 1); + model->numvertices - numvectors - 1); for (i = 0; i < model->numtriangles; i++) { T(i).vindices[0] = (unsigned int)vectors[3 * T(i).vindices[0] + 0]; @@ -1691,7 +1695,7 @@ glmWeld(GLMmodel* model, GLfloat epsilon) /* allocate space for the new vertices */ model->numvertices = numvectors; model->vertices = (GLfloat*)malloc(sizeof(GLfloat) * - 3 * (model->numvertices + 1)); + 3 * (model->numvertices + 1)); /* copy the optimized vertices into the actual vertex list */ for (i = 1; i <= model->numvertices; i++) { @@ -1712,7 +1716,7 @@ glmWeld(GLMmodel* model, GLfloat epsilon) copies = _glmOptimizeVectors(vectors, &numvectors); printf("glmOptimize(): %d redundant normals.\n", - model->numnormals - numvectors); + model->numnormals - numvectors); for (i = 0; i < model->numtriangles; i++) { T(i).nindices[0] = (unsigned int)vectors[3 * T(i).nindices[0] + 0]; @@ -1726,7 +1730,7 @@ glmWeld(GLMmodel* model, GLfloat epsilon) /* allocate space for the new normals */ model->numnormals = numvectors; model->normals = (GLfloat*)malloc(sizeof(GLfloat) * - 3 * (model->numnormals + 1)); + 3 * (model->numnormals + 1)); /* copy the optimized vertices into the actual vertex list */ for (i = 1; i <= model->numnormals; i++) { @@ -1745,7 +1749,7 @@ glmWeld(GLMmodel* model, GLfloat epsilon) copies = _glmOptimizeVectors(vectors, &numvectors); printf("glmOptimize(): %d redundant texcoords.\n", - model->numtexcoords - numvectors); + model->numtexcoords - numvectors); for (i = 0; i < model->numtriangles; i++) { for (j = 0; j < 3; j++) { @@ -1759,7 +1763,7 @@ glmWeld(GLMmodel* model, GLfloat epsilon) /* allocate space for the new texcoords */ model->numtexcoords = numvectors; model->texcoords = (GLfloat*)malloc(sizeof(GLfloat) * - 2 * (model->numtexcoords + 1)); + 2 * (model->numtexcoords + 1)); /* copy the optimized vertices into the actual vertex list */ for (i = 1; i <= model->numtexcoords; i++) { @@ -1778,9 +1782,9 @@ glmWeld(GLMmodel* model, GLfloat epsilon) for (i = 1; i <= model->numvertices; i++) { for (j = 0; j < model->numtriangles; i++) { if (T(j).vindices[0] == i || - T(j).vindices[1] == i || - T(j).vindices[1] == i) - break; + T(j).vindices[1] == i || + T(j).vindices[1] == i) + break; } } #endif diff --git a/src/osgPlugins/obj/glm.h b/src/osgPlugins/obj/glm.h index bd0088524..5861a0c81 100644 --- a/src/osgPlugins/obj/glm.h +++ b/src/osgPlugins/obj/glm.h @@ -24,12 +24,12 @@ /* defines */ -#define GLM_NONE (0) /* render with only vertices */ -#define GLM_FLAT (1 << 0) /* render with facet normals */ -#define GLM_SMOOTH (1 << 1) /* render with vertex normals */ -#define GLM_TEXTURE (1 << 2) /* render with texture coords */ -#define GLM_COLOR (1 << 3) /* render with colors */ -#define GLM_MATERIAL (1 << 4) /* render with materials */ +#define GLM_NONE (0) /* render with only vertices */ +#define GLM_FLAT (1 << 0) /* render with facet normals */ +#define GLM_SMOOTH (1 << 1) /* render with vertex normals */ +#define GLM_TEXTURE (1 << 2) /* render with texture coords */ +#define GLM_COLOR (1 << 3) /* render with colors */ +#define GLM_MATERIAL (1 << 4) /* render with materials */ /* structs */ @@ -38,25 +38,27 @@ */ struct GLMmaterial { - char* name; /* name of material */ - GLfloat diffuse[4]; /* diffuse component */ - GLfloat ambient[4]; /* ambient component */ - GLfloat specular[4]; /* specular component */ - GLfloat emmissive[4]; /* emmissive component */ - GLfloat shininess; /* specular exponent */ + char* name; /* name of material */ + GLfloat diffuse[4]; /* diffuse component */ + GLfloat ambient[4]; /* ambient component */ + GLfloat specular[4]; /* specular component */ + GLfloat emmissive[4]; /* emmissive component */ + GLfloat shininess; /* specular exponent */ char* textureName; /* name of any attached texture, add by RO */ bool textureReflection; /* true if texture is a reflection map */ + float alpha; /* alpha */ void init() { - name = NULL; - diffuse[0] = diffuse[1] = diffuse[2] = 0.8f; diffuse[3] = 1.0f; - ambient[0] = ambient[1] = ambient[2] = 0.2f; ambient[3] = 1.0f; - specular[0] = specular[1] = specular[2] = 0.0f; specular[3] = 1.0f; - emmissive[0] = emmissive[1] = emmissive[2] = 0.0f; emmissive[3] = 1.0f; - shininess = 0.0f; - textureName = NULL; - textureReflection = false; + name = NULL; + diffuse[0] = diffuse[1] = diffuse[2] = 0.8f; diffuse[3] = 1.0f; + ambient[0] = ambient[1] = ambient[2] = 0.2f; ambient[3] = 1.0f; + specular[0] = specular[1] = specular[2] = 0.0f; specular[3] = 1.0f; + emmissive[0] = emmissive[1] = emmissive[2] = 0.0f; emmissive[3] = 1.0f; + shininess = 0.0f; + textureName = NULL; + textureReflection = false; + alpha = 1.0f; } }; @@ -64,97 +66,97 @@ struct GLMmaterial /* GLMtriangle: Structure that defines a triangle in a model. */ struct GLMtriangle { - unsigned int vindices[3]; /* array of triangle vertex indices */ - unsigned int nindices[3]; /* array of triangle normal indices */ - unsigned int tindices[3]; /* array of triangle texcoord indices*/ - unsigned int findex; /* index of triangle facet normal */ + unsigned int vindices[3]; /* array of triangle vertex indices */ + unsigned int nindices[3]; /* array of triangle normal indices */ + unsigned int tindices[3]; /* array of triangle texcoord indices*/ + unsigned int findex; /* index of triangle facet normal */ void init() { - vindices[0] = vindices[2] = vindices[2] = 0 ; - nindices[0] = nindices[2] = nindices[2] = 0 ; - tindices[0] = tindices[2] = tindices[2] = 0 ; - findex=0; + vindices[0] = vindices[2] = vindices[2] = 0 ; + nindices[0] = nindices[2] = nindices[2] = 0 ; + tindices[0] = tindices[2] = tindices[2] = 0 ; + findex=0; } }; /* GLMgroup: Structure that defines a group in a model. */ struct GLMgroup { - char* name; /* name of this group */ - unsigned int numtriangles; /* number of triangles in this group */ - unsigned int* triangles; /* array of triangle indices */ + char* name; /* name of this group */ + unsigned int numtriangles; /* number of triangles in this group */ + unsigned int* triangles; /* array of triangle indices */ unsigned int material; /* index to material for group */ bool hastexcoords; /* set to true if triangles have texture coords */ - struct GLMgroup* next; /* pointer to next group in model */ + struct GLMgroup* next; /* pointer to next group in model */ void init() { - name = NULL; - numtriangles = 0; - triangles = NULL; - material = 0; + name = NULL; + numtriangles = 0; + triangles = NULL; + material = 0; hastexcoords = false; - next = NULL; + next = NULL; } }; /* GLMmodel: Structure that defines a model. */ struct GLMmodel { - char* pathname; /* path to this model */ - char* mtllibname; /* name of the material library */ + char* pathname; /* path to this model */ + char* mtllibname; /* name of the material library */ - unsigned int numvertices; /* number of vertices in model */ - GLfloat* vertices; /* array of vertices */ + unsigned int numvertices; /* number of vertices in model */ + GLfloat* vertices; /* array of vertices */ - unsigned int numnormals; /* number of normals in model */ - GLfloat* normals; /* array of normals */ + unsigned int numnormals; /* number of normals in model */ + GLfloat* normals; /* array of normals */ - unsigned int numtexcoords; /* number of texcoords in model */ - GLfloat* texcoords; /* array of texture coordinates */ + unsigned int numtexcoords; /* number of texcoords in model */ + GLfloat* texcoords; /* array of texture coordinates */ - unsigned int numfacetnorms; /* number of facetnorms in model */ - GLfloat* facetnorms; /* array of facetnorms */ + unsigned int numfacetnorms; /* number of facetnorms in model */ + GLfloat* facetnorms; /* array of facetnorms */ - unsigned int numtriangles; /* number of triangles in model */ - GLMtriangle* triangles; /* array of triangles */ + unsigned int numtriangles; /* number of triangles in model */ + GLMtriangle* triangles; /* array of triangles */ - unsigned int nummaterials; /* number of materials in model */ - GLMmaterial* materials; /* array of materials */ + unsigned int nummaterials; /* number of materials in model */ + GLMmaterial* materials; /* array of materials */ - unsigned int numgroups; /* number of groups in model */ - GLMgroup* groups; /* linked list of groups */ + unsigned int numgroups; /* number of groups in model */ + GLMgroup* groups; /* linked list of groups */ - GLfloat position[3]; /* position of the model */ + GLfloat position[3]; /* position of the model */ void init() { - pathname = NULL; - mtllibname = NULL; + pathname = NULL; + mtllibname = NULL; - numvertices = 0; - vertices = NULL; + numvertices = 0; + vertices = NULL; - numnormals = 0; - normals = NULL; + numnormals = 0; + normals = NULL; - numtexcoords = 0; - texcoords = NULL; + numtexcoords = 0; + texcoords = NULL; - numfacetnorms = 0; - facetnorms = NULL; + numfacetnorms = 0; + facetnorms = NULL; - numtriangles = 0; - triangles = NULL; + numtriangles = 0; + triangles = NULL; - nummaterials = 0; - materials = NULL; + nummaterials = 0; + materials = NULL; - numgroups = 0; - groups = NULL; + numgroups = 0; + groups = NULL; - position[0] = position[1] = position[2] = 0.0f; + position[0] = position[1] = position[2] = 0.0f; } diff --git a/src/osgPlugins/osg/Geometry.cpp b/src/osgPlugins/osg/Geometry.cpp index b9acbb1a8..06f962a9d 100644 --- a/src/osgPlugins/osg/Geometry.cpp +++ b/src/osgPlugins/osg/Geometry.cpp @@ -103,7 +103,7 @@ bool Geometry_readLocalData(Object& obj, Input& fr) { // post 0.9.3 releases. ++fr; - Vec3Array* vertices = dynamic_cast(Array_readLocalData(fr)); + Array* vertices = Array_readLocalData(fr); if (vertices) { geom.setVertexArray(vertices); diff --git a/src/osgPlugins/osgText/IO_Text.cpp b/src/osgPlugins/osgText/IO_Text.cpp index 145050481..ddd9154ab 100644 --- a/src/osgPlugins/osgText/IO_Text.cpp +++ b/src/osgPlugins/osgText/IO_Text.cpp @@ -62,6 +62,14 @@ bool Text_readLocalData(osg::Object &obj, osgDB::Input &fr) } } + if (fr.matchSequence("characterSizeMode %w")) + { + std::string str = fr[1].getStr(); + if (str=="OBJECT_COORDS") text.setCharacterSizeMode(osgText::Text::OBJECT_COORDS); + else if (str=="SCREEN_COORDS") text.setCharacterSizeMode(osgText::Text::SCREEN_COORDS); + else if (str=="OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT") text.setCharacterSizeMode(osgText::Text::OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT); + } + // maximum dimentsions of text box. if (fr[0].matchWord("maximumWidth")) { @@ -127,24 +135,6 @@ bool Text_readLocalData(osg::Object &obj, osgDB::Input &fr) } } - if (fr.matchSequence("scale %f")) - { - float scale; - fr[1].getFloat(scale); - text.setScale(scale); - fr += 2; - itAdvanced = true; - } - - if (fr.matchSequence("autoUpdateEyeMovementTolerance %f")) - { - float scale; - fr[1].getFloat(scale); - text.setAutoUpdateEyeMovementTolerance(scale); - fr += 2; - itAdvanced = true; - } - if (fr.matchSequence("autoRotateToScreen TRUE")) { text.setAutoRotateToScreen(true); @@ -154,7 +144,7 @@ bool Text_readLocalData(osg::Object &obj, osgDB::Input &fr) if (fr.matchSequence("autoScaleToLimitScreenSizeToFontResolution TRUE")) { - text.setAutoScaleToLimitScreenSizeToFontResolution(true); + text.setCharacterSizeMode(osgText::Text::SCREEN_COORDS); fr += 2; itAdvanced = true; } @@ -263,6 +253,14 @@ bool Text_writeLocalData(const osg::Object &obj, osgDB::Output &fw) // charater size. fw.indent() << "characterSize " << text.getCharacterHeight() << " " << text.getCharacterAspectRatio() << std::endl; + fw.indent() << "characterSizeMode "; + switch(text.getCharacterSizeMode()) + { + case osgText::Text::OBJECT_COORDS : fw<<"OBJECT_COORDS"<0.0f) { @@ -301,25 +299,11 @@ bool Text_writeLocalData(const osg::Object &obj, osgDB::Output &fw) fw.indent() << "rotation " << text.getRotation() << std::endl; } - if (text.getScale()!=1.0f) - { - fw.indent() << "scale " << text.getScale() << std::endl; - } - - if (text.getAutoUpdateEyeMovementTolerance()!=0.0f) - { - fw.indent() << "autoUpdateEyeMovementTolerance " << text.getAutoUpdateEyeMovementTolerance() << std::endl; - } - if (text.getAutoRotateToScreen()) { fw.indent() << "autoRotateToScreen TRUE"<< std::endl; } - if (text.getAutoScaleToLimitScreenSizeToFontResolution()) - { - fw.indent() << "autoScaleToLimitScreenSizeToFontResolution TRUE"<< std::endl; - } // layout fw.indent() << "layout "; diff --git a/src/osgPlugins/txp/TerrapageNode.cpp b/src/osgPlugins/txp/TerrapageNode.cpp index faa86212b..bbe8886b1 100644 --- a/src/osgPlugins/txp/TerrapageNode.cpp +++ b/src/osgPlugins/txp/TerrapageNode.cpp @@ -28,6 +28,7 @@ TerrapageNode::~TerrapageNode() { // will the page manger delete the archive? delete _pageManager; + _pageManager = 0L; } void TerrapageNode::traverse(osg::NodeVisitor& nv) diff --git a/src/osgPlugins/txp/trPagePageManager.cpp b/src/osgPlugins/txp/trPagePageManager.cpp index c57314be7..16688d6cc 100644 --- a/src/osgPlugins/txp/trPagePageManager.cpp +++ b/src/osgPlugins/txp/trPagePageManager.cpp @@ -199,7 +199,7 @@ bool OSGPageManager::StartThread(ThreadMode mode,ThreadID &newThread) DWORD dwThreadId=0; LPVOID dwThrdParam = (LPVOID) this; - newThread = CreateThread( + threadID = newThread = CreateThread( NULL, // default security attributes 0, // use default stack size ThreadFunc, // thread function @@ -223,6 +223,7 @@ bool OSGPageManager::StartThread(ThreadMode mode,ThreadID &newThread) threadMode = mode; if( pthread_create( &newThread, 0L, ThreadFunc, (void *)this ) != 0 ) threadMode = ThreadNone; + threadID = newThread; #endif return threadMode != ThreadNone; } @@ -232,10 +233,18 @@ bool OSGPageManager::StartThread(ThreadMode mode,ThreadID &newThread) */ bool OSGPageManager::EndThread() { + cancel = true; + // claer the path for thred loop to finish + osgSetEvent(locationChangeEvent); #ifdef _WIN32 + DWORD res = STILL_ACTIVE; + while(res==STILL_ACTIVE){ + GetExitCodeThread(threadID,&res); + Sleep(100); + } #else // Need a handle to the thread ID here. - //pthread_cancel( ?newThread? ); + pthread_join( threadID, 0 ); #endif return true; } @@ -251,9 +260,10 @@ bool OSGPageManager::ThreadLoop() if (threadMode != ThreadFree) throw 1; - bool done = false; bool pagingActive = false; - while (!done) { + cancel = false; + + while (!cancel) { /* Here's how we do it: Wait for position change Update manager w/ position @@ -308,36 +318,39 @@ bool OSGPageManager::ThreadLoop() #endif // Now do a single load - tile = pageManage->GetNextLoad(); - osg::Group *tileGroup=NULL; - pagingActive = false; - if (tile) { - osg::Group *parentNode = NULL; - tileGroup = archive->LoadTile(NULL,pageManage,tile,&parentNode); - pageManage->AckLoad(); - if (tileGroup) { + while( (tile = pageManage->GetNextLoad()) ) // Sasa's new code - more frame drops, but less missing tiles. + //if( (tile = pageManage->GetNextLoad()) ) // original code (0.9.4 and before) - less frame drops, more missing tiles. + { + osg::Group *tileGroup=NULL; + pagingActive = false; + osg::Group *parentNode = NULL; + tileGroup = archive->LoadTile(NULL,pageManage,tile,&parentNode); + pageManage->AckLoad(); + if (tileGroup) { #ifdef USE_THREADLOOP_DELETE - // Make an extra reference to it because we want it back for deletion - // RO, commenting out as we don't want to do delete here, we want it to happen in the merge thread. - tileGroup->ref(); + // Make an extra reference to it because we want it back for deletion + // RO, commenting out as we don't want to do delete here, we want it to happen in the merge thread. + tileGroup->ref(); #endif - } else { - int x,y,lod; - tile->GetTileLoc(x,y,lod); - fprintf(stderr,"Failed to load tile (%d,%d,%d)\n",x,y,lod); - } - - // Now add this tile to the merge list - if (tileGroup) { - osgLockMutex(changeListMutex); - toMerge.push_back(tileGroup); - toMergeParent.push_back(parentNode); - osgUnLockMutex(changeListMutex); - } - // We're not necessarily done paging, we're just handing control back - // It's likely we'll be back here - pagingActive = true; - } + } + else + { + int x,y,lod; + tile->GetTileLoc(x,y,lod); + fprintf(stderr,"Failed to load tile (%d,%d,%d)\n",x,y,lod); + } + + // Now add this tile to the merge list + if (tileGroup) { + osgLockMutex(changeListMutex); + toMerge.push_back(tileGroup); + toMergeParent.push_back(parentNode); + osgUnLockMutex(changeListMutex); + } + // We're not necessarily done paging, we're just handing control back + // It's likely we'll be back here + pagingActive = true; + } } } diff --git a/src/osgPlugins/txp/trPagePageManager.h b/src/osgPlugins/txp/trPagePageManager.h index 43f176a09..1890fe9ed 100644 --- a/src/osgPlugins/txp/trPagePageManager.h +++ b/src/osgPlugins/txp/trPagePageManager.h @@ -145,6 +145,8 @@ namespace txp std::vector toMergeParent; // Unhook list is filled in by the paging thread std::vector toUnhook; + + volatile bool cancel; #ifdef USE_THREADLOOP_DELETE // Main thread moves groups to the delete list as soon as they are unhooked diff --git a/src/osgProducer/GNUmakefile b/src/osgProducer/GNUmakefile index 066170fe0..d658414ac 100644 --- a/src/osgProducer/GNUmakefile +++ b/src/osgProducer/GNUmakefile @@ -17,5 +17,12 @@ LIB = $(LIB_PREFIX)$(TARGET_BASENAME).$(LIB_EXT) INC += $(PRODUCER_INCLUDE_DIR) -I/usr/X11R6/include LDFLAGS += $(PRODUCER_LIB_DIR) + +ifeq ($(USE_OPEN_THREAD),1) + DEF += -D_USE_OPEN_THREAD + INC += $(INC_OPEN_THREAD) + LDFLAGS += $(LIB_OPEN_THREAD) + LIBS += -lOpenThread +endif include $(TOPDIR)/Make/makerules diff --git a/src/osgProducer/OsgCameraGroup.cpp b/src/osgProducer/OsgCameraGroup.cpp index 931703923..fe697a4e7 100644 --- a/src/osgProducer/OsgCameraGroup.cpp +++ b/src/osgProducer/OsgCameraGroup.cpp @@ -187,24 +187,26 @@ void OsgCameraGroup::setUpSceneViewsWithData() { for(SceneHandlerList::iterator p = _shvec.begin(); p != _shvec.end(); p++ ) { + osgUtil::SceneView* sv = (*p)->getSceneView(); + if (_scene_decorator.valid()) { - (*p)->setSceneData( _scene_decorator.get() ); + sv->setSceneData( _scene_decorator.get() ); } else if (_scene_data.valid()) { - (*p)->setSceneData( _scene_data.get() ); + sv->setSceneData( _scene_data.get() ); } else { - (*p)->setSceneData( 0 ); + sv->setSceneData( 0 ); } - (*p)->setFrameStamp( _frameStamp.get() ); - (*p)->setGlobalStateSet( _global_stateset.get() ); - (*p)->setBackgroundColor( _background_color ); - (*p)->setLODScale( _LODScale ); - (*p)->setFusionDistance( _fusionDistanceMode, _fusionDistanceValue ); + sv->setFrameStamp( _frameStamp.get() ); + sv->setGlobalStateSet( _global_stateset.get() ); + sv->setBackgroundColor( _background_color ); + sv->setLODScale( _LODScale ); + sv->setFusionDistance( _fusionDistanceMode, _fusionDistanceValue ); } } @@ -317,14 +319,17 @@ bool OsgCameraGroup::realize() // create the scene handler. osgProducer::OsgSceneHandler *sh = new osgProducer::OsgSceneHandler(_ds.get()); - sh->setDefaults(); - sh->getState()->setContextID(i); + + osgUtil::SceneView* sv = sh->getSceneView(); + sv->setDefaults(); + + sh->setContextID(i); _shvec.push_back( sh ); cam->setSceneHandler( sh ); // set up the clear mask. - osgUtil::RenderStage *stage = sh->getRenderStage(); + osgUtil::RenderStage *stage = sv->getRenderStage(); if (stage) stage->setClearMask(clear_mask); // set the realize callback. @@ -363,7 +368,7 @@ bool OsgCameraGroup::realize() if( _global_stateset == NULL && _shvec.size() > 0 ) { SceneHandlerList::iterator p = _shvec.begin(); - _global_stateset = (*p)->getGlobalStateSet(); + _global_stateset = (*p)->getSceneView()->getGlobalStateSet(); } setUpSceneViewsWithData(); @@ -430,9 +435,9 @@ void OsgCameraGroup::setView(const osg::Matrix& matrix) const osg::Matrix OsgCameraGroup::getViewMatrix() const { osg::Matrix matrix; - if (_cfg && _cfg->getNumberOfCameras()>=1) + if (_cfg.valid() && _cfg->getNumberOfCameras()>=1) { - Producer::Camera *cam = _cfg->getCamera(0); + const Producer::Camera *cam = _cfg->getCamera(0); matrix.set(cam->getViewMatrix()); } return matrix; diff --git a/src/osgProducer/OsgSceneHandler.cpp b/src/osgProducer/OsgSceneHandler.cpp index c22bd1159..502a08f0b 100644 --- a/src/osgProducer/OsgSceneHandler.cpp +++ b/src/osgProducer/OsgSceneHandler.cpp @@ -18,10 +18,10 @@ using namespace osgUtil; using namespace osgProducer; OsgSceneHandler::OsgSceneHandler( osg::DisplaySettings *ds) : - osgUtil::SceneView(ds) + _sceneView(new osgUtil::SceneView(ds)) { - setProjectionMatrix( new osg::RefMatrix ); - setModelViewMatrix( new osg::RefMatrix ); + _sceneView->setProjectionMatrix( new osg::RefMatrix ); + _sceneView->setModelViewMatrix( new osg::RefMatrix ); } void OsgSceneHandler::init() @@ -31,7 +31,7 @@ void OsgSceneHandler::init() mutex.lock(); osg::notify(osg::INFO)<<" running "<SceneView::init(); osg::notify(osg::INFO)<<" done "<set(cam.getProjectionMatrix()); - getModelViewMatrix()->set(cam.getPositionAndAttitudeMatrix()); + _sceneView->getProjectionMatrix()->set(cam.getProjectionMatrix()); + _sceneView->getModelViewMatrix()->set(cam.getPositionAndAttitudeMatrix()); int x, y; unsigned int w, h; cam.getProjectionRectangle( x, y, w, h ); - setViewport( x, y, w, h ); + _sceneView->setViewport( x, y, w, h ); - SceneView::cull(); + _sceneView->cull(); } void OsgSceneHandler::drawImplementation(Producer::Camera &) { - SceneView::draw(); + _sceneView->SceneView::draw(); } void OsgSceneHandler::setContextID( int id ) { - getState()->setContextID( id ); + _sceneView->getState()->setContextID( id ); } diff --git a/src/osgProducer/Viewer.cpp b/src/osgProducer/Viewer.cpp index 049e48207..4aa9f6aeb 100644 --- a/src/osgProducer/Viewer.cpp +++ b/src/osgProducer/Viewer.cpp @@ -128,7 +128,7 @@ private: // osgProducer::Viewer implemention // Viewer::Viewer(): - _done(0), + _done(false), _kbmcb(0), _recordingAnimationPath(false) { @@ -231,8 +231,8 @@ void Viewer::setUpViewer(unsigned int options) } + if (!_updateVisitor) _updateVisitor = new osgUtil::UpdateVisitor; - _updateVisitor = new osgUtil::UpdateVisitor; _updateVisitor->setFrameStamp(_frameStamp.get()); if (options&TRACKBALL_MANIPULATOR) addCameraManipulator(new osgGA::TrackballManipulator); @@ -320,7 +320,7 @@ bool Viewer::realize() // draw traversal. for(SceneHandlerList::iterator p=_shvec.begin(); p!=_shvec.end(); p++ ) { - (*p)->getState()->setAbortRenderingPtr(&_done); + (*p)->getSceneView()->getState()->setAbortRenderingPtr(&_done); } return _realized; @@ -433,11 +433,12 @@ bool Viewer::computeNearFarPoints(float x,float y,unsigned int cameraNum,osg::Ve if (cameraNum>=getSceneHandlerList().size()) return false; OsgSceneHandler* scenehandler = getSceneHandlerList()[cameraNum].get(); + osgUtil::SceneView* sv = scenehandler->getSceneView(); float pixel_x,pixel_y; if (computePixelCoords(x,y,cameraNum,pixel_x,pixel_y)) { - return scenehandler->projectWindowXYIntoObject((int)(pixel_x+0.5f),(int)(pixel_y+0.5f),near_point,far_point); + return sv->projectWindowXYIntoObject((int)(pixel_x+0.5f),(int)(pixel_y+0.5f),near_point,far_point); } return false; @@ -462,11 +463,12 @@ bool Viewer::computeIntersections(float x,float y,unsigned int cameraNum,osgUtil //std::cout << " rx "<(camera->getSceneHandler()); + osgUtil::SceneView* sv = sh?sh->getSceneView():0; osg::Matrix vum; - if (sh!=0 && sh->getModelViewMatrix()!=0 && sh->getProjectionMatrix()!=0) + if (sv!=0 && sv->getModelViewMatrix()!=0 && sv->getProjectionMatrix()!=0) { - vum.set((*(sh->getModelViewMatrix())) * - (*(sh->getProjectionMatrix()))); + vum.set((*(sv->getModelViewMatrix())) * + (*(sv->getProjectionMatrix()))); } else { diff --git a/src/osgProducer/ViewerEventHandler.cpp b/src/osgProducer/ViewerEventHandler.cpp index 5fb84572c..8f1d240dc 100644 --- a/src/osgProducer/ViewerEventHandler.cpp +++ b/src/osgProducer/ViewerEventHandler.cpp @@ -138,17 +138,18 @@ void ViewerEventHandler::StatsAndHelpDrawCallback::operator()( const Producer::C _viewport->setViewport(x,y,width,height); OsgSceneHandler* osh = _veh->getOsgCameraGroup()->getSceneHandlerList()[_cameraNumber].get(); - osh->getState()->pushStateSet(_stateset.get()); + osgUtil::SceneView* sv = osh->getSceneView(); + sv->getState()->pushStateSet(_stateset.get()); if (_veh->getDisplayHelp()) displayHelp(); if (_veh->getFrameStatsMode()!=ViewerEventHandler::NO_STATS && camera.getInstrumentationMode()) { - osh->getState()->apply(); + sv->getState()->apply(); displayStats(); } - osh->getState()->popStateSet(); + sv->getState()->popStateSet(); } @@ -157,6 +158,7 @@ void ViewerEventHandler::StatsAndHelpDrawCallback::displayHelp() if (!_helpInitialized) createHelpText(); OsgSceneHandler* osh = _veh->getOsgCameraGroup()->getSceneHandlerList()[_cameraNumber].get(); + osgUtil::SceneView* sv = osh->getSceneView(); // should possibly update _viewport... @@ -180,21 +182,21 @@ void ViewerEventHandler::StatsAndHelpDrawCallback::displayHelp() ditr!=_descriptionList.end(); ++ditr) { - (*ditr)->draw(*(osh->getState())); + (*ditr)->draw(*(sv->getState())); } for(TextList::iterator oitr=_optionList.begin(); oitr!=_optionList.end(); ++oitr) { - (*oitr)->draw(*(osh->getState())); + (*oitr)->draw(*(sv->getState())); } for(TextList::iterator eitr=_explanationList.begin(); eitr!=_explanationList.end(); ++eitr) { - (*eitr)->draw(*(osh->getState())); + (*eitr)->draw(*(sv->getState())); } @@ -360,6 +362,7 @@ void ViewerEventHandler::StatsAndHelpDrawCallback::displayStats() if (!_statsInitialized) createStatsText(); OsgSceneHandler* osh = _veh->getOsgCameraGroup()->getSceneHandlerList()[_cameraNumber].get(); + osgUtil::SceneView* sv = osh->getSceneView(); // render the text if (_veh->getFrameStatsMode()>=ViewerEventHandler::FRAME_RATE) @@ -384,7 +387,7 @@ void ViewerEventHandler::StatsAndHelpDrawCallback::displayStats() char tmpText[128]; - _frameRateLabelText->draw(*(osh->getState())); + _frameRateLabelText->draw(*(sv->getState())); if (_fs.size()>1) { @@ -394,7 +397,7 @@ void ViewerEventHandler::StatsAndHelpDrawCallback::displayStats() sprintf(tmpText,"%4.2f",1.0/timePerFrame); _frameRateCounterText->setText(tmpText); } - _frameRateCounterText->draw(*(osh->getState())); + _frameRateCounterText->draw(*(sv->getState())); if (_veh->getFrameStatsMode()>=ViewerEventHandler::CAMERA_STATS) @@ -405,7 +408,7 @@ void ViewerEventHandler::StatsAndHelpDrawCallback::displayStats() itr!=_statsLabelList.end(); ++itr) { - (*itr)->draw(*(osh->getState())); + (*itr)->draw(*(sv->getState())); } double updateTime = 0.0; @@ -429,7 +432,7 @@ void ViewerEventHandler::StatsAndHelpDrawCallback::displayStats() sprintf(tmpText,"%4.2f",1000.0*updateTime/(double)_fs.size()); _updateTimeText->setText(tmpText); - _updateTimeText->draw(*(osh->getState())); + _updateTimeText->draw(*(sv->getState())); CameraTimes::iterator titr; for(itr=_cullTimeText.begin(),titr = _cullTimes.begin(); @@ -438,7 +441,7 @@ void ViewerEventHandler::StatsAndHelpDrawCallback::displayStats() { sprintf(tmpText,"%4.2f",1000.0*(*titr)/(double)_fs.size()); (*itr)->setText(tmpText); - (*itr)->draw(*(osh->getState())); + (*itr)->draw(*(sv->getState())); } for(itr=_drawTimeText.begin(),titr = _drawTimes.begin(); itr!=_drawTimeText.end() && titr!=_cullTimes.end(); @@ -446,7 +449,7 @@ void ViewerEventHandler::StatsAndHelpDrawCallback::displayStats() { sprintf(tmpText,"%4.2f",1000.0*(*titr)/(double)_fs.size()); (*itr)->setText(tmpText); - (*itr)->draw(*(osh->getState())); + (*itr)->draw(*(sv->getState())); } } diff --git a/src/osgSim/GNUmakefile b/src/osgSim/GNUmakefile index c088b97b0..7942c16c0 100644 --- a/src/osgSim/GNUmakefile +++ b/src/osgSim/GNUmakefile @@ -10,6 +10,8 @@ CXXFILES = \ Sector.cpp\ Version.cpp\ +# SphereSegment.cpp\ + DEF += -DOSGSIM_LIBRARY LIBS += -losg -losgUtil $(GL_LIBS) $(OTHER_LIBS) diff --git a/src/osgSim/LightPointDrawable.cpp b/src/osgSim/LightPointDrawable.cpp index c4ce3e696..05de331d7 100644 --- a/src/osgSim/LightPointDrawable.cpp +++ b/src/osgSim/LightPointDrawable.cpp @@ -41,7 +41,6 @@ LightPointDrawable::LightPointDrawable(): _colorMaskOff = new osg::ColorMask; _colorMaskOff->setMask(false,false,false,false); - _point = new osg::Point; } LightPointDrawable::LightPointDrawable(const LightPointDrawable& lpd,const osg::CopyOp& copyop): diff --git a/src/osgSim/LightPointDrawable.h b/src/osgSim/LightPointDrawable.h index 9a9d2b624..cc5d6462c 100644 --- a/src/osgSim/LightPointDrawable.h +++ b/src/osgSim/LightPointDrawable.h @@ -116,7 +116,6 @@ class OSGSIM_EXPORT LightPointDrawable : public osg::Drawable osg::ref_ptr _blendOne; osg::ref_ptr _blendOneMinusSrcAlpha; osg::ref_ptr _colorMaskOff; - osg::ref_ptr _point; }; diff --git a/src/osgSim/LightPointNode.cpp b/src/osgSim/LightPointNode.cpp index a82f766ce..d1f0bb174 100644 --- a/src/osgSim/LightPointNode.cpp +++ b/src/osgSim/LightPointNode.cpp @@ -24,13 +24,29 @@ #include -using namespace osgSim; +namespace osgSim +{ + +osg::StateSet* getSingletonLightPointStateSet() +{ + static osg::ref_ptr s_stateset = 0; + if (!s_stateset) + { + s_stateset = new osg::StateSet; + // force light point nodes to be drawn after everything else by picking a renderin bin number after + // the transparent bin. + s_stateset->setRenderBinDetails(20,"DepthSortedBin"); + } + return s_stateset.get(); +} + LightPointNode::LightPointNode(): _minPixelSize(0.0f), _maxPixelSize(30.0f), _maxVisableDistance2(FLT_MAX) { + setStateSet(getSingletonLightPointStateSet()); } /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ @@ -66,6 +82,12 @@ bool LightPointNode::computeBound() const _bsphere.init(); _bbox.init(); + if (_lightPointList.empty()) + { + _bsphere_computed=true; + return false; + } + LightPointList::const_iterator itr; for(itr=_lightPointList.begin(); @@ -96,6 +118,12 @@ bool LightPointNode::computeBound() const void LightPointNode::traverse(osg::NodeVisitor& nv) { + if (_lightPointList.empty()) + { + // no light points so no op. + return; + } + //#define USE_TIMER #ifdef USE_TIMER osg::Timer timer; @@ -363,3 +391,4 @@ void LightPointNode::traverse(osg::NodeVisitor& nv) } +} // end of namespace diff --git a/src/osgText/Font.cpp b/src/osgText/Font.cpp index 62d66137e..f8c4af284 100644 --- a/src/osgText/Font.cpp +++ b/src/osgText/Font.cpp @@ -1,3 +1,4 @@ + /* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield * * This library is open source and may be redistributed and/or modified under @@ -459,22 +460,95 @@ void Font::GlyphTexture::apply(osg::State& state) const } + static const GLubyte* s_renderer = 0; + static bool s_subloadAllGlyphsTogether = false; + if (!s_renderer) + { + s_renderer = glGetString(GL_RENDERER); + osg::notify(osg::INFO)<<"glGetString(GL_RENDERER)=="<subload(); + // default way of subloading as required. + + //std::cout<<"subloading"<subload(); + } + + // clear the list since we have now subloaded them. + glyphsWereSubloading.clear(); + + } + else + { + //std::cout<<"all loading"<subload(); + + // Rather than subloading to graphics, we'll write the values + // of the glyphs into some intermediate data and subload the + // whole thing at the end + for( int t = 0; t < (*itr)->t(); t++ ) + { + for( int s = 0; s < (*itr)->s(); s++ ) + { + int sindex = 2 * (t*(*itr)->s()+s); + int dindex = 2 * + ((((*itr)->getTexturePositionY()+t) * getTextureWidth()) + + ((*itr)->getTexturePositionX()+s)); + + const unsigned char *sptr = &(*itr)->data()[sindex]; + unsigned char *dptr = &local_data[dindex]; + + (*dptr++) = (*sptr++); + (*dptr) = (*sptr); + } + } + } + + // clear the list since we have now subloaded them. + glyphsWereSubloading.clear(); + + // Subload the image once + glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, + getTextureWidth(), + getTextureHeight(), + GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, local_data ); + + delete [] local_data; } - - // clear the list since we have now subloaded them. - glyphsWereSubloading.clear(); } else { @@ -556,7 +630,7 @@ void Font::Glyph::subload() const "\t "<(nv); - if (!cs) return false; - - unsigned int contextID = cs->getState() ? cs->getState()->getContextID() : 0; - - PositionData& positionData = _positions[contextID]; - - int width = positionData._previousWidth; - int height = positionData._previousHeight; - - osg::Viewport* viewport = cs->getViewport(); - if (viewport) - { - width = viewport->width(); - height = viewport->height(); - } - - osg::Vec3 eyePoint = cs->getEyeLocal(); - - bool doUpdate = positionData._traversalNumber==-1; - if (positionData._traversalNumber>=0) - { - osg::Vec3 dv = positionData._eyePosition-eyePoint; - if (dv.length2()>_text->getAutoUpdateEyeMovementTolerance()*(eyePoint-_text->getPosition()).length2()) - { - doUpdate = true; - } - else if (width!=positionData._previousWidth || height!=positionData._previousHeight) - { - doUpdate = true; - } - } - - positionData._traversalNumber = nv->getTraversalNumber(); - positionData._previousWidth = width; - positionData._previousHeight = height; - - if (doUpdate) - { - - float scale=_text->getScale(contextID); - - if (_text->getAutoScaleToLimitScreenSizeToFontResolution()) - { - float numPixels = cs->pixelSize(_text->getPosition(),_text->getCharacterHeight()); - if (numPixels>_text->getFontHeight()) - { - scale = _text->getFontHeight()/numPixels; - } - - //float size = 1.0f/cs->pixelSize(_text->getPosition(),1.0f); - //_text->setScale(size); - } - - osg::Quat rotation = _text->getRotation(contextID); - if (_text->getAutoRotateToScreen()) - { - rotation.set(cs->getModelViewMatrix()); - rotation = rotation.inverse(); - } - - _text->setScaleAndRotation(contextID,scale,rotation); - - } - - return false; - } - - typedef osg::buffered_object PositionList; - mutable PositionList _positions; - mutable osgText::Text* _text; - -}; - - Text::Text(): _fontWidth(32), _fontHeight(32), _characterHeight(32), _characterAspectRatio(1.0f), + _characterSizeMode(OBJECT_COORDS), _maximumWidth(0.0f), _maximumHeight(0.0f), _alignment(BASE_LINE), - _autoUpdateEyeMovementTolerance(0.0f), _autoRotateToScreen(false), - _autoScaleToLimitScreenSizeToFontResolution(false), _layout(LEFT_TO_RIGHT), _color(1.0f,1.0f,1.0f,1.0f), _drawMode(TEXT) { setUseDisplayList(false); - setScale(1.0f); } Text::Text(const Text& text,const osg::CopyOp& copyop): @@ -146,21 +47,18 @@ Text::Text(const Text& text,const osg::CopyOp& copyop): _fontHeight(text._fontHeight), _characterHeight(text._characterHeight), _characterAspectRatio(text._characterAspectRatio), + _characterSizeMode(text._characterSizeMode), _maximumWidth(text._maximumWidth), _maximumHeight(text._maximumHeight), _text(text._text), _position(text._position), _alignment(text._alignment), _rotation(text._rotation), - _scale(text._scale), - _autoUpdateEyeMovementTolerance(text._autoUpdateEyeMovementTolerance), _autoRotateToScreen(text._autoRotateToScreen), - _autoScaleToLimitScreenSizeToFontResolution(text._autoScaleToLimitScreenSizeToFontResolution), _layout(text._layout), _color(text._color), _drawMode(text._drawMode) { - setUpAutoCallback(); computeGlyphRepresentation(); } @@ -189,7 +87,6 @@ void Text::setFontResolution(unsigned int width, unsigned int height) computeGlyphRepresentation(); } - void Text::setCharacterSize(float height,float aspectRatio) { _characterHeight = height; @@ -278,75 +175,19 @@ void Text::setAxisAlignment(AxisAlignment axis) void Text::setRotation(const osg::Quat& quat) { - for(unsigned int i=0;i<_rotation.size();++i) - { - setRotation(i,quat); - } + _rotation = quat; + computePositions(); } -void Text::setRotation(unsigned int contextID, const osg::Quat& quat) -{ - if (_rotation[contextID]==quat) return; - - _rotation[contextID] = quat; - computePositions(contextID); -} - -void Text::setScale(float scale) -{ - for(unsigned int i=0;i<_scale.size();++i) - { - setScale(i,scale); - } -} - -void Text::setScale(unsigned int contextID, float scale) -{ - if (_scale[contextID]==scale) return; - - _scale[contextID] = scale; - computePositions(contextID); -} - -void Text::setScaleAndRotation(unsigned int contextID, float scale,const osg::Quat& quat) -{ - if (_scale[contextID]==scale && _rotation[contextID]==quat) return; - - _scale[contextID] = scale; - _rotation[contextID] = quat; - - computePositions(contextID); -} - -void Text::setAutoScaleToLimitScreenSizeToFontResolution(bool autoScaleToScreen) -{ - if (_autoScaleToLimitScreenSizeToFontResolution==autoScaleToScreen) return; - - _autoScaleToLimitScreenSizeToFontResolution = autoScaleToScreen; - setUpAutoCallback(); -} void Text::setAutoRotateToScreen(bool autoRotateToScreen) { if (_autoRotateToScreen==autoRotateToScreen) return; _autoRotateToScreen = autoRotateToScreen; - setUpAutoCallback(); } -void Text::setUpAutoCallback() -{ - if (_autoRotateToScreen || _autoScaleToLimitScreenSizeToFontResolution) - { - if (!getCullCallback()) - { - setCullCallback(new TextCullCallback(this)); - } - } - else setCullCallback(0); -} - void Text::setLayout(Layout layout) { if (_layout==layout) return; @@ -369,7 +210,7 @@ void Text::setDrawMode(unsigned int mode) _drawMode=mode; if (_drawMode&TEXT_PIXMAP) { - setAutoScaleToLimitScreenSizeToFontResolution(true); + setCharacterSizeMode(SCREEN_COORDS); setAutoRotateToScreen(true); } computeGlyphRepresentation(); @@ -388,9 +229,9 @@ bool Text::computeBound() const if (_textBB.valid()) { - for(unsigned int i=0;i<_matrix.size();++i) + for(unsigned int i=0;i<_autoTransformCache.size();++i) { - osg::Matrix& matrix = _matrix[i]; + osg::Matrix& matrix = _autoTransformCache[i]._matrix; _bbox.expandBy(osg::Vec3(_textBB.xMin(),_textBB.yMin(),_textBB.zMin())*matrix); _bbox.expandBy(osg::Vec3(_textBB.xMax(),_textBB.yMin(),_textBB.zMin())*matrix); _bbox.expandBy(osg::Vec3(_textBB.xMax(),_textBB.yMax(),_textBB.zMin())*matrix); @@ -605,13 +446,13 @@ void Text::computeGlyphRepresentation() void Text::computePositions() { - for(unsigned int i=0;i<_matrix.size();++i) + for(unsigned int i=0;i<_autoTransformCache.size();++i) { computePositions(i); } } -void Text::computePositions(unsigned int contextID) +void Text::computePositions(unsigned int contextID) const { switch(_alignment) @@ -632,18 +473,92 @@ void Text::computePositions(unsigned int contextID) case RIGHT_BASE_LINE: _offset.set((_textBB.xMax()+_textBB.xMin()),0.0f,0.0f); break; } - osg::Matrix& matrix = _matrix[contextID]; + + + AutoTransformCache& atc = _autoTransformCache[contextID]; + osg::Matrix& matrix = atc._matrix; - if (_scale[contextID]!=1.0f || !_rotation[contextID].zeroRotation()) + if (_characterSizeMode!=OBJECT_COORDS || _autoRotateToScreen) { + matrix.makeTranslate(-_offset); - if (_scale[contextID]!=1.0f) - matrix.postMult(osg::Matrix::scale(_scale[contextID],_scale[contextID],_scale[contextID])); - if (!_rotation[contextID].zeroRotation()) - matrix.postMult(osg::Matrix::rotate(_rotation[contextID])); + osg::Matrix rotate_matrix; + if (_autoRotateToScreen) + { + osg::Vec3 trans(atc._modelview.getTrans()); + atc._modelview.setTrans(0.0f,0.0f,0.0f); + rotate_matrix.invert(atc._modelview); + atc._modelview.setTrans(trans); + } + + if (_characterSizeMode!=OBJECT_COORDS) + { + + osg::Matrix M(rotate_matrix*osg::Matrix::translate(_position)*atc._modelview); + osg::Matrix& P = atc._projection; + + // compute the pixel size vector. + + // pre adjust P00,P20,P23,P33 by multiplying them by the viewport window matrix. + // here we do it in short hand with the knowledge of how the window matrix is formed + // note P23,P33 are multiplied by an implicit 1 which would come from the window matrix. + // Robert Osfield, June 2002. + + // scaling for horizontal pixels + float P00 = P(0,0)*atc._width*0.5f; + float P20_00 = P(2,0)*atc._width*0.5f + P(2,3)*atc._width*0.5f; + osg::Vec3 scale_00(M(0,0)*P00 + M(0,2)*P20_00, + M(1,0)*P00 + M(1,2)*P20_00, + M(2,0)*P00 + M(2,2)*P20_00); + + // scaling for vertical pixels + float P10 = P(1,1)*atc._height*0.5f; + float P20_10 = P(2,1)*atc._height*0.5f + P(2,3)*atc._height*0.5f; + osg::Vec3 scale_10(M(0,1)*P10 + M(0,2)*P20_10, + M(1,1)*P10 + M(1,2)*P20_10, + M(2,1)*P10 + M(2,2)*P20_10); + + float P23 = P(2,3); + float P33 = P(3,3); + + float pixelSizeVector_w = M(3,2)*P23 + M(3,3)*P33; + + float pixelSize = (_characterHeight*sqrtf(scale_00.length2()+scale_10.length2()))/(pixelSizeVector_w*0.701f); + + if (_characterSizeMode==SCREEN_COORDS) + { + float scale_font = _characterHeight/pixelSize; + matrix.postMult(osg::Matrix::scale(scale_font, scale_font,1.0f)); + } + else if (pixelSize>_fontHeight) + { + float scale_font = _fontHeight/pixelSize; + matrix.postMult(osg::Matrix::scale(scale_font, scale_font,1.0f)); + } + + } + + + if (_autoRotateToScreen) + { + matrix.postMult(rotate_matrix); + + } + + if (!_rotation.zeroRotation() ) + { + matrix.postMult(osg::Matrix::rotate(_rotation)); + } + + matrix.postMult(osg::Matrix::translate(_position)); + } + else if (!_rotation.zeroRotation()) + { + matrix.makeTranslate(-_offset); + matrix.postMult(osg::Matrix::rotate(_rotation)); matrix.postMult(osg::Matrix::translate(_position)); } else @@ -651,6 +566,7 @@ void Text::computePositions(unsigned int contextID) matrix.makeTranslate(_position-_offset); } + // now apply matrix to the glyphs. for(TextureGlyphQuadMap::iterator titr=_textureGlyphQuadMap.begin(); @@ -676,13 +592,60 @@ void Text::computePositions(unsigned int contextID) _normal = osg::Matrix::transform3x3(osg::Vec3(0.0f,0.0f,1.0f),matrix); _normal.normalize(); - dirtyBound(); + const_cast(this)->dirtyBound(); } void Text::drawImplementation(osg::State& state) const { unsigned int contextID = state.getContextID(); + if (_characterSizeMode!=OBJECT_COORDS || _autoRotateToScreen) + { + int frameNumber = state.getFrameStamp()?state.getFrameStamp()->getFrameNumber():0; + AutoTransformCache& atc = _autoTransformCache[contextID]; + const osg::Matrix& modelview = state.getModelViewMatrix(); + + osg::Vec3 newTransformedPosition = _position*modelview; + + int width = atc._width; + int height = atc._height; + + const osg::Viewport* viewport = state.getCurrentViewport(); + if (viewport) + { + width = viewport->width(); + height = viewport->height(); + } + + bool doUpdate = atc._traversalNumber==-1; + if (atc._traversalNumber>=0) + { + if (atc._modelview!=modelview) + { + doUpdate = true; + } + else if (width!=atc._width || height!=atc._height) + { + doUpdate = true; + } + } + + atc._traversalNumber = frameNumber; + atc._width = width; + atc._height = height; + + if (doUpdate) + { + atc._transformedPosition = newTransformedPosition; + atc._projection = state.getProjectionMatrix(); + atc._modelview = modelview; + + computePositions(contextID); + } + + } + + glNormal3fv(_normal.ptr()); glColor4fv(_color.ptr()); @@ -745,7 +708,7 @@ void Text::drawImplementation(osg::State& state) const { state.applyTextureMode(0,GL_TEXTURE_2D,osg::StateAttribute::OFF); - osg::Matrix& matrix = _matrix[contextID]; + const osg::Matrix& matrix = _autoTransformCache[contextID]._matrix; osg::Vec3 c00(osg::Vec3(_textBB.xMin(),_textBB.yMin(),_textBB.zMin())*matrix); osg::Vec3 c10(osg::Vec3(_textBB.xMax(),_textBB.yMin(),_textBB.zMin())*matrix); @@ -767,9 +730,9 @@ void Text::drawImplementation(osg::State& state) const { glColor4f(1.0f,0.0f,1.0f,1.0f); - float cursorsize = _characterHeight*0.5f*_scale[contextID]; + float cursorsize = _characterHeight*0.5f; - osg::Matrix& matrix = _matrix[contextID]; + const osg::Matrix& matrix = _autoTransformCache[contextID]._matrix; osg::Vec3 hl(osg::Vec3(_offset.x()-cursorsize,_offset.y(),_offset.z())*matrix); osg::Vec3 hr(osg::Vec3(_offset.x()+cursorsize,_offset.y(),_offset.z())*matrix); @@ -814,14 +777,6 @@ void Text::accept(osg::Drawable::PrimitiveFunctor& pf) const pf.setVertexArray(glyphquad._transformedCoords[0].size(),&(glyphquad._transformedCoords[0].front())); pf.drawArrays(GL_QUADS,0,glyphquad._transformedCoords[0].size()); -// pf.begin(GL_QUADS); -// for(GlyphQuads::Coords3::const_iterator itr = glyphquad._transformedCoords.begin(); -// itr!=glyphquad._transformedCoords.end(); -// ++itr) -// { -// pf.vertex(*itr); -// } -// pf.end(); } } diff --git a/src/osgUtil/IntersectVisitor.cpp b/src/osgUtil/IntersectVisitor.cpp index bfa40b81b..adff9102b 100644 --- a/src/osgUtil/IntersectVisitor.cpp +++ b/src/osgUtil/IntersectVisitor.cpp @@ -524,7 +524,7 @@ bool IntersectVisitor::intersect(Drawable& drawable) if (geometry) { - osg::Vec3Array* vertices = geometry->getVertexArray(); + osg::Vec3Array* vertices = dynamic_cast(geometry->getVertexArray()); if (vertices) { osg::Vec3* first = &(vertices->front()); diff --git a/src/osgUtil/Optimizer.cpp b/src/osgUtil/Optimizer.cpp index a546b491e..48df6660b 100644 --- a/src/osgUtil/Optimizer.cpp +++ b/src/osgUtil/Optimizer.cpp @@ -13,6 +13,7 @@ #include #include +#include #include #include #include @@ -106,45 +107,6 @@ void Optimizer::optimize(osg::Node* node, unsigned int options) } -class TransformFunctor : public osg::Drawable::AttributeFunctor -{ - public: - - osg::Matrix _m; - osg::Matrix _im; - - TransformFunctor(const osg::Matrix& m) - { - _m = m; - _im.invert(_m); - } - - virtual ~TransformFunctor() {} - - virtual void apply(osg::Drawable::AttributeType type,unsigned int count,osg::Vec3* begin) - { - if (type == osg::Drawable::VERTICES) - { - osg::Vec3* end = begin+count; - for (osg::Vec3* itr=begin;itr(obj); if (drawable) { - TransformFunctor tf(matrix); + osg::TransformAttributeFunctor tf(matrix); drawable->accept(tf); drawable->dirtyBound(); return; @@ -570,7 +532,7 @@ void CollectLowestTransformsVisitor::doTransform(osg::Object* obj,osg::Matrix& m osg::Matrix matrix_no_trans = matrix; matrix_no_trans.setTrans(0.0f,0.0f,0.0f); - TransformFunctor tf(matrix_no_trans); + osg::TransformAttributeFunctor tf(matrix_no_trans); osg::Vec3 axis = osg::Matrix::transform3x3(tf._im,billboard->getAxis()); axis.normalize(); @@ -1362,14 +1324,62 @@ bool Optimizer::MergeGeometryVisitor::geometryContainsSharedArrays(osg::Geometry return false; } + +class MergeArrayVisitor : public osg::ArrayVisitor +{ + public: + + osg::Array* _lhs; + + MergeArrayVisitor() : + _lhs(0) {} + + + void merge(osg::Array* lhs,osg::Array* rhs) + { + if (lhs==0 || rhs==0) return; + if (lhs->getType()!=rhs->getType()) return; + + _lhs = lhs; + + rhs->accept(*this); + } + + template + void _merge(T& rhs) + { + T* lhs = static_cast(_lhs); + lhs->insert(lhs->end(),rhs.begin(),rhs.end()); + } + + + virtual void apply(osg::Array&) { osg::notify(osg::WARN) << "Warning: Optimizer's MergeArrayVisitor cannot merge Array type." << std::endl; } + virtual void apply(osg::ByteArray& rhs) { _merge(rhs); } + virtual void apply(osg::ShortArray& rhs) { _merge(rhs); } + virtual void apply(osg::IntArray& rhs) { _merge(rhs); } + virtual void apply(osg::UByteArray& rhs) { _merge(rhs); } + virtual void apply(osg::UShortArray& rhs) { _merge(rhs); } + virtual void apply(osg::UIntArray& rhs) { _merge(rhs); } + virtual void apply(osg::UByte4Array& rhs) { _merge(rhs); } + virtual void apply(osg::FloatArray& rhs) { _merge(rhs); } + virtual void apply(osg::Vec2Array& rhs) { _merge(rhs); } + virtual void apply(osg::Vec3Array& rhs) { _merge(rhs); } + virtual void apply(osg::Vec4Array& rhs) { _merge(rhs); } +}; + bool Optimizer::MergeGeometryVisitor::mergeGeometry(osg::Geometry& lhs,osg::Geometry& rhs) { + + MergeArrayVisitor merger; unsigned int base = 0; if (lhs.getVertexArray() && rhs.getVertexArray()) { - base = lhs.getVertexArray()->size(); - lhs.getVertexArray()->insert(lhs.getVertexArray()->end(),rhs.getVertexArray()->begin(),rhs.getVertexArray()->end()); + + base = lhs.getVertexArray()->getNumElements(); + + merger.merge(lhs.getVertexArray(),rhs.getVertexArray()); + } else if (rhs.getVertexArray()) { @@ -1378,7 +1388,7 @@ bool Optimizer::MergeGeometryVisitor::mergeGeometry(osg::Geometry& lhs,osg::Geom if (lhs.getNormalArray() && rhs.getNormalArray() && lhs.getNormalBinding()!=osg::Geometry::BIND_OVERALL) { - lhs.getNormalArray()->insert(lhs.getNormalArray()->end(),rhs.getNormalArray()->begin(),rhs.getNormalArray()->end()); + merger.merge(lhs.getNormalArray(),rhs.getNormalArray()); } else if (rhs.getNormalArray()) { @@ -1387,34 +1397,34 @@ bool Optimizer::MergeGeometryVisitor::mergeGeometry(osg::Geometry& lhs,osg::Geom if (lhs.getColorArray() && rhs.getColorArray() && lhs.getColorBinding()!=osg::Geometry::BIND_OVERALL) { - // we need to add the handling of the other array types... - osg::Vec4Array* col_lhs = dynamic_cast(lhs.getColorArray()); - osg::Vec4Array* col_rhs = dynamic_cast(rhs.getColorArray()); - - if (col_lhs && col_rhs) - { - col_lhs->insert(col_lhs->end(),col_rhs->begin(),col_rhs->end()); - } + merger.merge(lhs.getColorArray(),rhs.getColorArray()); } else if (rhs.getColorArray()) { lhs.setColorArray(rhs.getColorArray()); } - // need to implement handle secondary color array. + if (lhs.getSecondaryColorArray() && rhs.getSecondaryColorArray() && lhs.getSecondaryColorBinding()!=osg::Geometry::BIND_OVERALL) + { + merger.merge(lhs.getSecondaryColorArray(),rhs.getSecondaryColorArray()); + } + else if (rhs.getColorArray()) + { + lhs.setSecondaryColorArray(rhs.getSecondaryColorArray()); + } - // need to implement handle fog coord array. + if (lhs.getFogCoordArray() && rhs.getFogCoordArray() && lhs.getFogCoordBinding()!=osg::Geometry::BIND_OVERALL) + { + merger.merge(lhs.getFogCoordArray(),rhs.getFogCoordArray()); + } + else if (rhs.getColorArray()) + { + lhs.setFogCoordArray(rhs.getFogCoordArray()); + } for(unsigned int unit=0;unit(lhs.getTexCoordArray(unit)); - osg::Vec2Array* tex_rhs = dynamic_cast(rhs.getTexCoordArray(unit)); - - if (tex_lhs && tex_rhs) - { - tex_lhs->insert(tex_lhs->end(),tex_rhs->begin(),tex_rhs->end()); - } + merger.merge(lhs.getTexCoordArray(unit),rhs.getTexCoordArray(unit)); } // shift the indices of the incomming primitives to account for the pre exisiting geometry. diff --git a/src/osgUtil/SceneView.cpp b/src/osgUtil/SceneView.cpp index f4c970454..b98b6afaf 100644 --- a/src/osgUtil/SceneView.cpp +++ b/src/osgUtil/SceneView.cpp @@ -65,6 +65,16 @@ SceneView::~SceneView() void SceneView::setDefaults() { + if (!_projectionMatrix) + { + _projectionMatrix = new RefMatrix(); + _projectionMatrix->makePerspective(50.0f,1.4f,1.0f,10000.0f); + } + if (!_modelviewMatrix) + { + _modelviewMatrix = new RefMatrix(); + } + _globalStateSet = new osg::StateSet; _lightingMode=HEADLIGHT; diff --git a/src/osgUtil/SmoothingVisitor.cpp b/src/osgUtil/SmoothingVisitor.cpp index ba0ab3bfe..1c82dcf04 100644 --- a/src/osgUtil/SmoothingVisitor.cpp +++ b/src/osgUtil/SmoothingVisitor.cpp @@ -109,7 +109,7 @@ void SmoothingVisitor::smooth(osg::Geometry& geom) if (!numSurfacePrimitives) return; - osg::Vec3Array *coords = geom.getVertexArray(); + osg::Vec3Array *coords = dynamic_cast(geom.getVertexArray()); if (!coords || !coords->size()) return; osg::Vec3Array *normals = new osg::Vec3Array(coords->size()); diff --git a/src/osgUtil/Tesselator.cpp b/src/osgUtil/Tesselator.cpp index cf6f3622f..1b4e6fe11 100644 --- a/src/osgUtil/Tesselator.cpp +++ b/src/osgUtil/Tesselator.cpp @@ -149,7 +149,7 @@ class InsertNewVertices : public osg::ArrayVisitor void Tesselator::retesselatePolygons(osg::Geometry& geom) { - Vec3Array* vertices = geom.getVertexArray(); + osg::Vec3Array* vertices = dynamic_cast(geom.getVertexArray()); if (!vertices || vertices->empty() || geom.getPrimitiveSetList().empty()) return;