Compare commits

..

1 Commits

Author SHA1 Message Date
Paul MARTZ
43792651f0 Tagging 2.8.3. 2010-04-05 19:03:57 +00:00
96 changed files with 2509 additions and 4463 deletions

View File

@@ -30,8 +30,8 @@ PROJECT(OpenSceneGraph)
SET(OPENSCENEGRAPH_MAJOR_VERSION 2) SET(OPENSCENEGRAPH_MAJOR_VERSION 2)
SET(OPENSCENEGRAPH_MINOR_VERSION 8) SET(OPENSCENEGRAPH_MINOR_VERSION 8)
SET(OPENSCENEGRAPH_PATCH_VERSION 5) SET(OPENSCENEGRAPH_PATCH_VERSION 3)
SET(OPENSCENEGRAPH_SOVERSION 74) SET(OPENSCENEGRAPH_SOVERSION 65)
# set to 0 when not a release candidate, non zero means that any generated # set to 0 when not a release candidate, non zero means that any generated
# svn tags will be treated as release candidates of given number # svn tags will be treated as release candidates of given number
@@ -153,12 +153,6 @@ IF(UNIX)
FIND_PACKAGE(X11) FIND_PACKAGE(X11)
# Some Unicies need explicit linkage to the Math library or the build fails. # Some Unicies need explicit linkage to the Math library or the build fails.
FIND_LIBRARY(MATH_LIBRARY m) FIND_LIBRARY(MATH_LIBRARY m)
FIND_LIBRARY(DL_LIBRARY dl)
IF(NOT DL_LIBRARY)
SET(DL_LIBRARY "") # change from NOTFOUND to empty when passed to linker
ENDIF()
ENDIF(UNIX) ENDIF(UNIX)
# Make the headers visible to everything # Make the headers visible to everything
@@ -251,8 +245,6 @@ ENDIF(WIN32)
#luigi#ENDIF(UNIX) #luigi#ENDIF(UNIX)
######################################################################################################## ########################################################################################################
OPTION(OSG_NOTIFY_DISABLED "Set to ON to build OpenSceneGraph with the notify() disabled." OFF)
OPTION(OSG_USE_FLOAT_MATRIX "Set to ON to build OpenSceneGraph with float Matrix instead of double." OFF) OPTION(OSG_USE_FLOAT_MATRIX "Set to ON to build OpenSceneGraph with float Matrix instead of double." OFF)
MARK_AS_ADVANCED(OSG_USE_FLOAT_MATRIX) MARK_AS_ADVANCED(OSG_USE_FLOAT_MATRIX)
@@ -319,9 +311,6 @@ FIND_PACKAGE(OpenAL)
FIND_PACKAGE(XUL) FIND_PACKAGE(XUL)
FIND_PACKAGE(FFmpeg) FIND_PACKAGE(FFmpeg)
# Include macro utilities here
INCLUDE(OsgMacroUtils)
#use pkg-config to find various modues #use pkg-config to find various modues
INCLUDE(FindPkgConfig OPTIONAL) INCLUDE(FindPkgConfig OPTIONAL)
@@ -507,16 +496,8 @@ ENDIF(NOT MSVC)
# #
# On CMake 2.6.x use the newly minted CMAKE_LIBRARY_OUTPUT_DIRECTORY, # On CMake 2.6.x use the newly minted CMAKE_LIBRARY_OUTPUT_DIRECTORY,
# CMAKE_ARCHIVE_OUTPUT_DIRECTORY & CMAKE_RUNTIME_OUTPUT_DIRECTORY # CMAKE_ARCHIVE_OUTPUT_DIRECTORY & CMAKE_RUNTIME_OUTPUT_DIRECTORY
#
# CMake >= 2.8.1 changed the output directory algorithm (See doc). IF(CMAKE_MAJOR_VERSION EQUAL 2 AND CMAKE_MINOR_VERSION GREATER 4)
# Here we also set per-configuration directories (CMAKE_*_OUTPUT_DIRECTORY_<CONFIG>), or else binaries are generated in /bin/Debug and /bin/Release, etc. with MSVC and Xcode.
# (Doc reads "multi-configuration generators (VS, Xcode) do NOT append a per-configuration subdirectory to the specified directory").
# The workaround for 2.6.x (adding "../" as an output prefix for each target) seem to have no effect in >=2.8.1, so there is no need to change this.
IF(CMAKE_MAJOR_VERSION EQUAL 2 AND CMAKE_MINOR_VERSION LESS 5)
# If CMake < 2.6.0
SET(EXECUTABLE_OUTPUT_PATH ${OUTPUT_BINDIR})
SET(LIBRARY_OUTPUT_PATH ${OUTPUT_LIBDIR})
ELSE()
# If CMake >= 2.6.0 # If CMake >= 2.6.0
SET(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${OUTPUT_LIBDIR}) SET(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${OUTPUT_LIBDIR})
SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${OUTPUT_BINDIR}) SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${OUTPUT_BINDIR})
@@ -525,22 +506,10 @@ ELSE()
ELSE(WIN32) ELSE(WIN32)
SET(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${OUTPUT_LIBDIR}) SET(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${OUTPUT_LIBDIR})
ENDIF(WIN32) ENDIF(WIN32)
ELSE(CMAKE_MAJOR_VERSION EQUAL 2 AND CMAKE_MINOR_VERSION GREATER 4)
# Testing CMAKE_VERSION is possible in >= 2.6.4 only SET(EXECUTABLE_OUTPUT_PATH ${OUTPUT_BINDIR})
BUILDER_VERSION_GREATER(2 8 0) SET(LIBRARY_OUTPUT_PATH ${OUTPUT_LIBDIR})
IF(VALID_BUILDER_VERSION) # If CMake >= 2.8.1 ENDIF(CMAKE_MAJOR_VERSION EQUAL 2 AND CMAKE_MINOR_VERSION GREATER 4)
FOREACH(CONF ${CMAKE_CONFIGURATION_TYPES}) # For each configuration (Debug, Release, MinSizeRel... and/or anything the user chooses)
STRING(TOUPPER "${CONF}" CONF) # Go uppercase (DEBUG, RELEASE...)
SET("CMAKE_ARCHIVE_OUTPUT_DIRECTORY_${CONF}" "${OUTPUT_LIBDIR}")
SET("CMAKE_RUNTIME_OUTPUT_DIRECTORY_${CONF}" "${OUTPUT_BINDIR}")
IF(WIN32)
SET("CMAKE_LIBRARY_OUTPUT_DIRECTORY_${CONF}" "${OUTPUT_BINDIR}")
ELSE()
SET("CMAKE_LIBRARY_OUTPUT_DIRECTORY_${CONF}" "${OUTPUT_LIBDIR}")
ENDIF()
ENDFOREACH()
ENDIF(VALID_BUILDER_VERSION)
ENDIF()
#SET(INSTALL_BINDIR OpenSceneGraph/bin) #SET(INSTALL_BINDIR OpenSceneGraph/bin)
#SET(INSTALL_INCDIR OpenSceneGraph/include) #SET(INSTALL_INCDIR OpenSceneGraph/include)
@@ -642,7 +611,7 @@ ELSE (DYNAMIC_OPENSCENEGRAPH)
SET(OPENSCENEGRAPH_USER_DEFINED_DYNAMIC_OR_STATIC "STATIC") SET(OPENSCENEGRAPH_USER_DEFINED_DYNAMIC_OR_STATIC "STATIC")
ENDIF(DYNAMIC_OPENSCENEGRAPH) ENDIF(DYNAMIC_OPENSCENEGRAPH)
INCLUDE(OsgMacroUtils)
# OSG Core # OSG Core
ADD_SUBDIRECTORY(src) ADD_SUBDIRECTORY(src)

View File

@@ -9,36 +9,6 @@
# the content of this library for linking when in debugging # the content of this library for linking when in debugging
####################################################################################################### #######################################################################################################
# VALID_BUILDER_VERSION: used for replacing CMAKE_VERSION (available in v2.6.3 RC9) and VERSION_GREATER/VERSION_LESS (available in 2.6.2 RC4).
# This can be replaced by "IF(${CMAKE_VERSION} VERSION_LESS "x.y.z")" from 2.6.4.
SET(VALID_BUILDER_VERSION OFF)
MACRO(BUILDER_VERSION_GREATER MAJOR_VER MINOR_VER PATCH_VER)
SET(VALID_BUILDER_VERSION OFF)
IF(CMAKE_MAJOR_VERSION GREATER ${MAJOR_VER})
SET(VALID_BUILDER_VERSION ON)
ELSEIF(CMAKE_MAJOR_VERSION EQUAL ${MAJOR_VER})
IF(CMAKE_MINOR_VERSION GREATER ${MINOR_VER})
SET(VALID_BUILDER_VERSION ON)
ELSEIF(CMAKE_MINOR_VERSION EQUAL ${MINOR_VER})
IF(CMAKE_PATCH_VERSION GREATER ${PATCH_VER})
SET(VALID_BUILDER_VERSION ON)
ENDIF(CMAKE_PATCH_VERSION GREATER ${PATCH_VER})
ENDIF()
ENDIF()
ENDMACRO(BUILDER_VERSION_GREATER MAJOR_VER MINOR_VER PATCH_VER)
# CMAKE24: if CMake version is <2.6.0.
SET(CMAKE24 OFF)
IF(${CMAKE_MAJOR_VERSION} EQUAL 2 AND ${CMAKE_MINOR_VERSION} LESS 5)
SET(CMAKE24 ON)
ENDIF(${CMAKE_MAJOR_VERSION} EQUAL 2 AND ${CMAKE_MINOR_VERSION} LESS 5)
# CMAKE_VERSION_TEST: Define whether "IF(${CMAKE_VERSION} VERSION_LESS "x.y.z")" can be used or not.
BUILDER_VERSION_GREATER(2 6 3)
SET(CMAKE_VERSION_TEST ${VALID_BUILDER_VERSION}) # >= 2.6.4
SET(VALID_BUILDER_VERSION OFF)
MACRO(LINK_WITH_VARIABLES TRGTNAME) MACRO(LINK_WITH_VARIABLES TRGTNAME)
FOREACH(varname ${ARGN}) FOREACH(varname ${ARGN})
@@ -51,9 +21,9 @@ MACRO(LINK_WITH_VARIABLES TRGTNAME)
ENDMACRO(LINK_WITH_VARIABLES TRGTNAME) ENDMACRO(LINK_WITH_VARIABLES TRGTNAME)
MACRO(LINK_INTERNAL TRGTNAME) MACRO(LINK_INTERNAL TRGTNAME)
IF(NOT CMAKE24) IF(${CMAKE_MAJOR_VERSION} EQUAL 2 AND ${CMAKE_MINOR_VERSION} GREATER 4)
TARGET_LINK_LIBRARIES(${TRGTNAME} ${ARGN}) TARGET_LINK_LIBRARIES(${TRGTNAME} ${ARGN})
ELSE(NOT CMAKE24) ELSE(${CMAKE_MAJOR_VERSION} EQUAL 2 AND ${CMAKE_MINOR_VERSION} GREATER 4)
FOREACH(LINKLIB ${ARGN}) FOREACH(LINKLIB ${ARGN})
IF(MSVC AND OSG_MSVC_VERSIONED_DLL) IF(MSVC AND OSG_MSVC_VERSIONED_DLL)
#when using versioned names, the .dll name differ from .lib name, there is a problem with that: #when using versioned names, the .dll name differ from .lib name, there is a problem with that:
@@ -66,7 +36,7 @@ MACRO(LINK_INTERNAL TRGTNAME)
TARGET_LINK_LIBRARIES(${TRGTNAME} optimized "${LINKLIB}" debug "${LINKLIB}${CMAKE_DEBUG_POSTFIX}") TARGET_LINK_LIBRARIES(${TRGTNAME} optimized "${LINKLIB}" debug "${LINKLIB}${CMAKE_DEBUG_POSTFIX}")
ENDIF(MSVC AND OSG_MSVC_VERSIONED_DLL) ENDIF(MSVC AND OSG_MSVC_VERSIONED_DLL)
ENDFOREACH(LINKLIB) ENDFOREACH(LINKLIB)
ENDIF(NOT CMAKE24) ENDIF(${CMAKE_MAJOR_VERSION} EQUAL 2 AND ${CMAKE_MINOR_VERSION} GREATER 4)
ENDMACRO(LINK_INTERNAL TRGTNAME) ENDMACRO(LINK_INTERNAL TRGTNAME)
MACRO(LINK_EXTERNAL TRGTNAME) MACRO(LINK_EXTERNAL TRGTNAME)
@@ -146,44 +116,6 @@ ENDMACRO(SETUP_LINK_LIBRARIES)
# this is the common set of command for all the plugins # this is the common set of command for all the plugins
# #
# Sets the output directory property for CMake >= 2.6.0, giving an output path RELATIVE to default one
MACRO(SET_OUTPUT_DIR_PROPERTY_260 TARGET_TARGETNAME RELATIVE_OUTDIR)
BUILDER_VERSION_GREATER(2 8 0)
IF(NOT VALID_BUILDER_VERSION)
# If CMake <= 2.8.0 (Testing CMAKE_VERSION is possible in >= 2.6.4)
IF(MSVC_IDE)
# Using the "prefix" hack
SET_TARGET_PROPERTIES(${TARGET_TARGETNAME} PROPERTIES PREFIX "../${RELATIVE_OUTDIR}/")
ELSE(MSVC_IDE)
SET_TARGET_PROPERTIES(${TARGET_TARGETNAME} PROPERTIES PREFIX "${RELATIVE_OUTDIR}/")
ENDIF(MSVC_IDE)
ELSE(NOT VALID_BUILDER_VERSION)
# Using the output directory properties
# Global properties (All generators but VS & Xcode)
FILE(TO_CMAKE_PATH TMPVAR "CMAKE_ARCHIVE_OUTPUT_DIRECTORY/${RELATIVE_OUTDIR}")
SET_TARGET_PROPERTIES(${TARGET_TARGETNAME} PROPERTIES ARCHIVE_OUTPUT_DIRECTORY "${TMPVAR}")
FILE(TO_CMAKE_PATH TMPVAR "CMAKE_RUNTIME_OUTPUT_DIRECTORY/${RELATIVE_OUTDIR}")
SET_TARGET_PROPERTIES(${TARGET_TARGETNAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TMPVAR}")
FILE(TO_CMAKE_PATH TMPVAR "CMAKE_LIBRARY_OUTPUT_DIRECTORY/${RELATIVE_OUTDIR}")
SET_TARGET_PROPERTIES(${TARGET_TARGETNAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${TMPVAR}")
# Per-configuration property (VS, Xcode)
FOREACH(CONF ${CMAKE_CONFIGURATION_TYPES}) # For each configuration (Debug, Release, MinSizeRel... and/or anything the user chooses)
STRING(TOUPPER "${CONF}" CONF) # Go uppercase (DEBUG, RELEASE...)
# We use "FILE(TO_CMAKE_PATH", to create nice looking paths
FILE(TO_CMAKE_PATH "${CMAKE_ARCHIVE_OUTPUT_DIRECTORY_${CONF}}/${RELATIVE_OUTDIR}" TMPVAR)
SET_TARGET_PROPERTIES(${TARGET_TARGETNAME} PROPERTIES "ARCHIVE_OUTPUT_DIRECTORY_${CONF}" "${TMPVAR}")
FILE(TO_CMAKE_PATH "${CMAKE_RUNTIME_OUTPUT_DIRECTORY_${CONF}}/${RELATIVE_OUTDIR}" TMPVAR)
SET_TARGET_PROPERTIES(${TARGET_TARGETNAME} PROPERTIES "RUNTIME_OUTPUT_DIRECTORY_${CONF}" "${TMPVAR}")
FILE(TO_CMAKE_PATH "${CMAKE_LIBRARY_OUTPUT_DIRECTORY_${CONF}}/${RELATIVE_OUTDIR}" TMPVAR)
SET_TARGET_PROPERTIES(${TARGET_TARGETNAME} PROPERTIES "LIBRARY_OUTPUT_DIRECTORY_${CONF}" "${TMPVAR}")
ENDFOREACH(CONF ${CMAKE_CONFIGURATION_TYPES})
ENDIF(NOT VALID_BUILDER_VERSION)
ENDMACRO(SET_OUTPUT_DIR_PROPERTY_260 TARGET_TARGETNAME RELATIVE_OUTDIR)
MACRO(SETUP_PLUGIN PLUGIN_NAME) MACRO(SETUP_PLUGIN PLUGIN_NAME)
SET(TARGET_NAME ${PLUGIN_NAME} ) SET(TARGET_NAME ${PLUGIN_NAME} )
@@ -220,10 +152,13 @@ MACRO(SETUP_PLUGIN PLUGIN_NAME)
SET_TARGET_PROPERTIES(${TARGET_TARGETNAME} PROPERTIES DEBUG_POSTFIX "") SET_TARGET_PROPERTIES(${TARGET_TARGETNAME} PROPERTIES DEBUG_POSTFIX "")
ENDIF(NOT UNIX) ENDIF(NOT UNIX)
ELSE(NOT MSVC) ELSE(NOT MSVC)
IF(NOT CMAKE24) IF(${CMAKE_MAJOR_VERSION} EQUAL 2 AND ${CMAKE_MINOR_VERSION} GREATER 4)
SET_OUTPUT_DIR_PROPERTY_260(${TARGET_TARGETNAME} "${OSG_PLUGINS}") # Sets the ouput to be /osgPlugin-X.X.X ; also ensures the /Debug /Release are removed IF(NOT MSVC_IDE)
ELSE(NOT CMAKE24) SET_TARGET_PROPERTIES(${TARGET_TARGETNAME} PROPERTIES PREFIX "${OSG_PLUGINS}/")
ELSE(NOT MSVC_IDE)
SET_TARGET_PROPERTIES(${TARGET_TARGETNAME} PROPERTIES PREFIX "../${OSG_PLUGINS}/")
ENDIF(NOT MSVC_IDE)
ELSE(${CMAKE_MAJOR_VERSION} EQUAL 2 AND ${CMAKE_MINOR_VERSION} GREATER 4)
IF(OSG_MSVC_VERSIONED_DLL) IF(OSG_MSVC_VERSIONED_DLL)
#this is a hack... the build place is set to lib/<debug or release> by LIBARARY_OUTPUT_PATH equal to OUTPUT_LIBDIR #this is a hack... the build place is set to lib/<debug or release> by LIBARARY_OUTPUT_PATH equal to OUTPUT_LIBDIR
@@ -246,8 +181,7 @@ MACRO(SETUP_PLUGIN PLUGIN_NAME)
SET_TARGET_PROPERTIES(${TARGET_TARGETNAME} PROPERTIES PREFIX "${OSG_PLUGINS}/") SET_TARGET_PROPERTIES(${TARGET_TARGETNAME} PROPERTIES PREFIX "${OSG_PLUGINS}/")
ENDIF(OSG_MSVC_VERSIONED_DLL) ENDIF(OSG_MSVC_VERSIONED_DLL)
ENDIF(${CMAKE_MAJOR_VERSION} EQUAL 2 AND ${CMAKE_MINOR_VERSION} GREATER 4)
ENDIF(NOT CMAKE24)
ENDIF(NOT MSVC) ENDIF(NOT MSVC)
SET_TARGET_PROPERTIES(${TARGET_TARGETNAME} PROPERTIES PROJECT_LABEL "${TARGET_LABEL}") SET_TARGET_PROPERTIES(${TARGET_TARGETNAME} PROPERTIES PROJECT_LABEL "${TARGET_LABEL}")
@@ -323,7 +257,7 @@ MACRO(SETUP_EXE IS_COMMANDLINE_APP)
SET_TARGET_PROPERTIES(${TARGET_TARGETNAME} PROPERTIES OUTPUT_NAME ${TARGET_NAME}) SET_TARGET_PROPERTIES(${TARGET_TARGETNAME} PROPERTIES OUTPUT_NAME ${TARGET_NAME})
IF(MSVC_IDE AND OSG_MSVC_VERSIONED_DLL) IF(MSVC_IDE AND OSG_MSVC_VERSIONED_DLL)
SET_OUTPUT_DIR_PROPERTY_260(${TARGET_TARGETNAME} "") # Ensure the /Debug /Release are removed SET_TARGET_PROPERTIES(${TARGET_TARGETNAME} PROPERTIES PREFIX "../")
ENDIF(MSVC_IDE AND OSG_MSVC_VERSIONED_DLL) ENDIF(MSVC_IDE AND OSG_MSVC_VERSIONED_DLL)
SETUP_LINK_LIBRARIES() SETUP_LINK_LIBRARIES()
@@ -407,19 +341,10 @@ MACRO(HANDLE_MSVC_DLL)
ELSE(${ARGC} GREATER 1) ELSE(${ARGC} GREATER 1)
SET(LIB_SOVERSION ${OPENSCENEGRAPH_SOVERSION}) SET(LIB_SOVERSION ${OPENSCENEGRAPH_SOVERSION})
ENDIF(${ARGC} GREATER 1) ENDIF(${ARGC} GREATER 1)
SET_OUTPUT_DIR_PROPERTY_260(${LIB_NAME} "") # Ensure the /Debug /Release are removed
IF(NOT MSVC_IDE) IF(NOT MSVC_IDE)
IF (NOT CMAKE24) SET_TARGET_PROPERTIES(${LIB_NAME} PROPERTIES PREFIX "../bin/${LIB_PREFIX}${LIB_SOVERSION}-")
BUILDER_VERSION_GREATER(2 8 0) IF (${CMAKE_MAJOR_VERSION} EQUAL 2 AND ${CMAKE_MINOR_VERSION} EQUAL 4)
IF(NOT VALID_BUILDER_VERSION)
# If CMake < 2.8.1
SET_TARGET_PROPERTIES(${LIB_NAME} PROPERTIES PREFIX "../bin/${LIB_PREFIX}${LIB_SOVERSION}-" IMPORT_PREFIX "../")
ELSE(NOT VALID_BUILDER_VERSION)
SET_TARGET_PROPERTIES(${LIB_NAME} PROPERTIES PREFIX "${LIB_PREFIX}${LIB_SOVERSION}-")
ENDIF(NOT VALID_BUILDER_VERSION)
ELSE (NOT CMAKE24)
SET_TARGET_PROPERTIES(${LIB_NAME} PROPERTIES PREFIX "../bin/${LIB_PREFIX}${LIB_SOVERSION}-" IMPORT_PREFIX "../")
SET(NEW_LIB_NAME "${OUTPUT_BINDIR}/${LIB_PREFIX}${LIB_SOVERSION}-${LIB_NAME}") SET(NEW_LIB_NAME "${OUTPUT_BINDIR}/${LIB_PREFIX}${LIB_SOVERSION}-${LIB_NAME}")
ADD_CUSTOM_COMMAND( ADD_CUSTOM_COMMAND(
TARGET ${LIB_NAME} TARGET ${LIB_NAME}
@@ -429,19 +354,9 @@ MACRO(HANDLE_MSVC_DLL)
COMMAND ${CMAKE_COMMAND} -E remove "${NEW_LIB_NAME}.lib" COMMAND ${CMAKE_COMMAND} -E remove "${NEW_LIB_NAME}.lib"
COMMAND ${CMAKE_COMMAND} -E remove "${NEW_LIB_NAME}.exp" COMMAND ${CMAKE_COMMAND} -E remove "${NEW_LIB_NAME}.exp"
) )
ENDIF (NOT CMAKE24) ENDIF (${CMAKE_MAJOR_VERSION} EQUAL 2 AND ${CMAKE_MINOR_VERSION} EQUAL 4)
ELSE(NOT MSVC_IDE) ELSE(NOT MSVC_IDE)
IF (NOT CMAKE24) SET_TARGET_PROPERTIES(${LIB_NAME} PROPERTIES PREFIX "../../bin/${LIB_PREFIX}${LIB_SOVERSION}-" IMPORT_PREFIX "../")
BUILDER_VERSION_GREATER(2 8 0)
IF(NOT VALID_BUILDER_VERSION)
# If CMake < 2.8.1
SET_TARGET_PROPERTIES(${LIB_NAME} PROPERTIES PREFIX "../../bin/${LIB_PREFIX}${LIB_SOVERSION}-" IMPORT_PREFIX "../")
ELSE(NOT VALID_BUILDER_VERSION)
SET_TARGET_PROPERTIES(${LIB_NAME} PROPERTIES PREFIX "${LIB_PREFIX}${LIB_SOVERSION}-")
ENDIF(NOT VALID_BUILDER_VERSION)
ELSE (NOT CMAKE24)
SET_TARGET_PROPERTIES(${LIB_NAME} PROPERTIES PREFIX "../../bin/${LIB_PREFIX}${LIB_SOVERSION}-" IMPORT_PREFIX "../")
ENDIF (NOT CMAKE24)
ENDIF(NOT MSVC_IDE) ENDIF(NOT MSVC_IDE)
# SET_TARGET_PROPERTIES(${LIB_NAME} PROPERTIES PREFIX "../../bin/osg${OPENSCENEGRAPH_SOVERSION}-") # SET_TARGET_PROPERTIES(${LIB_NAME} PROPERTIES PREFIX "../../bin/osg${OPENSCENEGRAPH_SOVERSION}-")

View File

@@ -12,7 +12,6 @@ OrientationConverter::OrientationConverter( void )
R.makeIdentity(); R.makeIdentity();
T.makeIdentity(); T.makeIdentity();
_trans_set = false; _trans_set = false;
_use_world_frame = false;
S.makeIdentity(); S.makeIdentity();
} }
@@ -37,35 +36,21 @@ void OrientationConverter::setScale( const Vec3 &scale )
S = Matrix::scale(scale); S = Matrix::scale(scale);
} }
void OrientationConverter::useWorldFrame( bool worldFrame )
{
_use_world_frame = worldFrame;
}
Node* OrientationConverter::convert( Node *node ) Node* OrientationConverter::convert( Node *node )
{ {
// Order of operations here is : // Order of operations here is :
// 1. If world frame option not set, translate to world origin (0,0,0) // 1. Translate to world origin (0,0,0)
// 2. Rotate to new orientation // 2. Rotate to new orientation
// 3. Scale in new orientation coordinates // 3. Scale in new orientation coordinates
// 4. If an absolute translation was specified then // 4. If an absolute translation was specified then
// - translate to absolute translation in world coordinates // - translate to absolute translation in world coordinates
// else if world frame option not set, // else
// - translate back to model's original origin. // - translate back to model's original origin.
BoundingSphere bs = node->getBound(); BoundingSphere bs = node->getBound();
Matrix C; Matrix C = Matrix::translate( -bs.center() );
if( _trans_set == false )
if (_use_world_frame) T = Matrix::translate( bs.center() );
{
C.makeIdentity();
}
else
{
C = Matrix::translate( -bs.center() );
if( !_trans_set )
T = Matrix::translate( bs.center() );
}
osg::Group* root = new osg::Group; osg::Group* root = new osg::Group;
osg::MatrixTransform* transform = new osg::MatrixTransform; osg::MatrixTransform* transform = new osg::MatrixTransform;

View File

@@ -14,7 +14,6 @@ class OrientationConverter {
void setRotation( float degrees, const osg::Vec3 &axis ); void setRotation( float degrees, const osg::Vec3 &axis );
void setTranslation( const osg::Vec3 &trans); void setTranslation( const osg::Vec3 &trans);
void setScale( const osg::Vec3 &trans); void setScale( const osg::Vec3 &trans);
void useWorldFrame( bool worldFrame );
/** return the root of the updated subgraph as the subgraph /** return the root of the updated subgraph as the subgraph
* the node passed in my flatten during optimization.*/ * the node passed in my flatten during optimization.*/
@@ -26,7 +25,6 @@ class OrientationConverter {
osg::Matrix R, T, S; osg::Matrix R, T, S;
bool _trans_set; bool _trans_set;
bool _use_world_frame;
}; };
#endif #endif

View File

@@ -428,14 +428,12 @@ static void usage( const char *prog, const char *msg )
osg::notify(osg::NOTICE)<<" --compressed-dxt3 - Enable the usage of S3TC DXT3 compressed textures"<< std::endl; osg::notify(osg::NOTICE)<<" --compressed-dxt3 - Enable the usage of S3TC DXT3 compressed textures"<< std::endl;
osg::notify(osg::NOTICE)<<" --compressed-dxt5 - Enable the usage of S3TC DXT5 compressed textures"<< std::endl; osg::notify(osg::NOTICE)<<" --compressed-dxt5 - Enable the usage of S3TC DXT5 compressed textures"<< std::endl;
osg::notify(osg::NOTICE)<< std::endl; osg::notify(osg::NOTICE)<< std::endl;
osg::notify(osg::NOTICE)<<" --fix-transparency - fix statesets which are currently"<< std::endl; osg::notify(osg::NOTICE)<<" --fix-transparency - fix stateset which are curerntly declared as transprent,"<< std::endl;
osg::notify(osg::NOTICE)<<" declared as transparent, but should be opaque."<< std::endl; osg::notify(osg::NOTICE)<<" but should be opaque. Defaults to using the "<< std::endl;
osg::notify(osg::NOTICE)<<" Defaults to using the fixTranspancyMode"<< std::endl; osg::notify(osg::NOTICE)<<" fixTranspancyMode MAKE_OPAQUE_TEXTURE_STATESET_OPAQUE."<< std::endl;
osg::notify(osg::NOTICE)<<" MAKE_OPAQUE_TEXTURE_STATESET_OPAQUE."<< std::endl; osg::notify(osg::NOTICE)<<" --fix-transparency-mode <mode_string> - fix stateset which are curerntly declared as"<< std::endl;
osg::notify(osg::NOTICE)<<" --fix-transparency-mode <mode_string> - fix statesets which are currently"<< std::endl; osg::notify(osg::NOTICE)<<" transprent but should be opaque. The mode_string determines"<< std::endl;
osg::notify(osg::NOTICE)<<" declared as transparent but should be opaque."<< std::endl; osg::notify(osg::NOTICE)<<" algorithm is used to fix the transparency, options are: "<< std::endl;
osg::notify(osg::NOTICE)<<" The mode_string determines which algorithm is used"<< std::endl;
osg::notify(osg::NOTICE)<<" to fix the transparency, options are:"<< std::endl;
osg::notify(osg::NOTICE)<<" MAKE_OPAQUE_TEXTURE_STATESET_OPAQUE,"<<std::endl; osg::notify(osg::NOTICE)<<" MAKE_OPAQUE_TEXTURE_STATESET_OPAQUE,"<<std::endl;
osg::notify(osg::NOTICE)<<" MAKE_ALL_STATESET_OPAQUE."<<std::endl; osg::notify(osg::NOTICE)<<" MAKE_ALL_STATESET_OPAQUE."<<std::endl;
@@ -459,11 +457,10 @@ static void usage( const char *prog, const char *msg )
"\n" "\n"
" where X1,Y1,Z1 represent the UP vector in the input\n" " where X1,Y1,Z1 represent the UP vector in the input\n"
" files and X2,Y2,Z2 represent the UP vector of the\n" " files and X2,Y2,Z2 represent the UP vector of the\n"
" output file, or degrees is the rotation angle in\n" " output file, or degrees is the rotation angle in degrees\n"
" degrees around axis (A0,A1,A2). For example, to\n" " around axis (A0,A1,A2). For example, to convert a model\n"
" convert a model built in a Y-Up coordinate system to a\n" " built in a Y-Up coordinate system to a model with a Z-up\n"
" model with a Z-up coordinate system, the argument may\n" " coordinate system, the argument may look like\n"
" look like\n"
"\n" "\n"
" 0,1,0-0,0,1" " 0,1,0-0,0,1"
"\n" "\n"
@@ -478,14 +475,9 @@ static void usage( const char *prog, const char *msg )
" where X, Y, and Z represent the coordinates of the\n" " where X, Y, and Z represent the coordinates of the\n"
" absolute position in world space\n" " absolute position in world space\n"
<< std::endl; << std::endl;
osg::notify(osg::NOTICE)<<" --use-world-frame - Perform transformations in the world frame, rather\n" osg::notify(osg::NOTICE)<<" --simplify n - Run simplifier on prior to output. Argument must be a" << std::endl
" than relative to the center of the bounding sphere.\n" <<" normalized value for the resultant percentage reduction." << std::endl
<< std::endl; <<" Example: --simplify .5 will produce an 50 reduced model." << std::endl
osg::notify(osg::NOTICE)<<" --simplify n - Run simplifier prior to output. Argument must be a" << std::endl
<<" normalized value for the resultant percentage" << std::endl
<<" reduction." << std::endl
<<" Example: --simplify .5" << std::endl
<<" will produce a 50% reduced model." << std::endl
<< std::endl; << std::endl;
osg::notify(osg::NOTICE)<<" -s scale - Scale size of model. Scale argument must be the \n" osg::notify(osg::NOTICE)<<" -s scale - Scale size of model. Scale argument must be the \n"
" following :\n" " following :\n"
@@ -493,26 +485,25 @@ static void usage( const char *prog, const char *msg )
" SX,SY,SZ\n" " SX,SY,SZ\n"
"\n" "\n"
" where SX, SY, and SZ represent the scale factors\n" " where SX, SY, and SZ represent the scale factors\n"
" Caution: Scaling is done in destination orientation\n" " Caution: Scaling will be done in destination orientation\n"
<< std::endl; << std::endl;
osg::notify(osg::NOTICE)<<" --smooth - Smooth the surface by regenerating surface normals on\n" osg::notify(osg::NOTICE)<<" --smooth - Smooth the surface by regenerating surface normals on\n"
" all geometry nodes"<< std::endl; " all geometry"<< std::endl;
osg::notify(osg::NOTICE)<<" --addMissingColors - Add a white color value to all geometry nodes\n" osg::notify(osg::NOTICE)<<" --addMissingColors - Adding a white color value to all geometry that don't have\n"
" that don't have their own color values\n" " their own color values (--addMissingColours also accepted)."<< std::endl;
" (--addMissingColours also accepted)."<< std::endl;
osg::notify(osg::NOTICE)<<" --overallNormal - Replace normals with a single overall normal."<< std::endl; osg::notify(osg::NOTICE)<<" --overallNormal - Replace normals with a single overall normal."<< std::endl;
osg::notify( osg::NOTICE ) << std::endl; osg::notify( osg::NOTICE ) << std::endl;
osg::notify( osg::NOTICE ) << osg::notify( osg::NOTICE ) <<
" --formats - List all supported formats and their supported options." << std::endl; " --formats - Lists all supported formats and their supported options." << std::endl;
osg::notify( osg::NOTICE ) << osg::notify( osg::NOTICE ) <<
" --format <format> - Display information about the specified <format>,\n" " --format <format> - Displays information about the spefied <format>, where <format>\n"
" where <format> is the file extension, such as \"flt\"." << std::endl; " is the file extension, such as \"flt\"." << std::endl;
osg::notify( osg::NOTICE ) << osg::notify( osg::NOTICE ) <<
" --plugins - List all supported plugin files." << std::endl; " --plugins - Lists all supported plugin files." << std::endl;
osg::notify( osg::NOTICE ) << osg::notify( osg::NOTICE ) <<
" --plugin <plugin> - Display information about the specified <plugin>,\n" " --plugin >plugin> - Displays information about the spefied <plugin>, where <plugin>\n"
" where <plugin> is the plugin's full path and file name." << std::endl; " is the plugin's full path and file name." << std::endl;
} }
@@ -594,11 +585,6 @@ int main( int argc, char **argv )
OrientationConverter oc; OrientationConverter oc;
bool do_convert = false; bool do_convert = false;
if (arguments.read("--use-world-frame"))
{
oc.useWorldFrame(true);
}
std::string str; std::string str;
while (arguments.read("-O",str)) while (arguments.read("-O",str))
{ {
@@ -670,7 +656,7 @@ int main( int argc, char **argv )
if( sscanf( str.c_str(), "%f", if( sscanf( str.c_str(), "%f",
&nsimp ) != 1 ) &nsimp ) != 1 )
{ {
usage( argv[0], "Simplify argument format incorrect." ); usage( argv[0], "Scale argument format incorrect." );
return 1; return 1;
} }
std::cout << str << " " << nsimp << std::endl; std::cout << str << " " << nsimp << std::endl;

View File

@@ -489,7 +489,7 @@ void testThreadInitAndExit()
OpenThreads::Thread::microSleep(5000000); OpenThreads::Thread::microSleep(5000000);
} }
std::cout<<"pass notify thread test."<<std::endl<<std::endl; std::cout<<"pass noitfy thread test."<<std::endl<<std::endl;
} }
void testPolytope() void testPolytope()

View File

@@ -331,7 +331,6 @@ namespace osg
**************************************************************************/ **************************************************************************/
class Texture1D; class Texture1D;
class Texture2D; class Texture2D;
class Texture2DMultisample;
class Texture3D; class Texture3D;
class Texture2DArray; class Texture2DArray;
class TextureCubeMap; class TextureCubeMap;
@@ -346,7 +345,6 @@ namespace osg
explicit FrameBufferAttachment(RenderBuffer* target); explicit FrameBufferAttachment(RenderBuffer* target);
explicit FrameBufferAttachment(Texture1D* target, int level = 0); explicit FrameBufferAttachment(Texture1D* target, int level = 0);
explicit FrameBufferAttachment(Texture2D* target, int level = 0); explicit FrameBufferAttachment(Texture2D* target, int level = 0);
explicit FrameBufferAttachment(Texture2DMultisample* target, int level = 0);
explicit FrameBufferAttachment(Texture3D* target, int zoffset, int level = 0); explicit FrameBufferAttachment(Texture3D* target, int zoffset, int level = 0);
explicit FrameBufferAttachment(Texture2DArray* target, int layer, int level = 0); explicit FrameBufferAttachment(Texture2DArray* target, int layer, int level = 0);
explicit FrameBufferAttachment(TextureCubeMap* target, int face, int level = 0); explicit FrameBufferAttachment(TextureCubeMap* target, int face, int level = 0);

View File

@@ -18,8 +18,6 @@
#include <osg/NodeCallback> #include <osg/NodeCallback>
#include <osg/observer_ptr> #include <osg/observer_ptr>
#include <iterator>
namespace osg namespace osg
{ {

View File

@@ -11,11 +11,10 @@
* OpenSceneGraph Public License for more details. * OpenSceneGraph Public License for more details.
*/ */
#ifndef OSG_NOTIFY_H #ifndef OSG_NOTIFY
#define OSG_NOTIFY_H 1 #define OSG_NOTIFY 1
#include <osg/Export> #include <osg/Export>
#include <osg/Referenced> // for NotifyHandler
#include <ostream> #include <ostream>
@@ -24,8 +23,8 @@ namespace osg {
/** Range of notify levels from DEBUG_FP through to FATAL, ALWAYS /** Range of notify levels from DEBUG_FP through to FATAL, ALWAYS
* is reserved for forcing the absorption of all messages. The * is reserved for forcing the absorption of all messages. The
* keywords are also used verbatim when specified by the environmental * keywords are also used verbatim when specified by the environmental
* variable OSGNOTIFYLEVEL or OSG_NOTIFY_LEVEL. * variable OSGNOTIFYLEVEL. See documentation on osg::notify() for
* See documentation on osg::notify() for further details. * further details.
*/ */
enum NotifySeverity { enum NotifySeverity {
ALWAYS=0, ALWAYS=0,
@@ -38,108 +37,38 @@ enum NotifySeverity {
}; };
/** set the notify level, overriding the default or the value set by /** set the notify level, overriding the default or the value set by
* the environmental variable OSGNOTIFYLEVEL or OSG_NOTIFY_LEVEL. * the environmental variable OSGNOTIFYLEVEL.
*/ */
extern OSG_EXPORT void setNotifyLevel(NotifySeverity severity); extern OSG_EXPORT void setNotifyLevel(NotifySeverity severity);
/** get the notify level. */ /** get the notify level. */
extern OSG_EXPORT NotifySeverity getNotifyLevel(); extern OSG_EXPORT NotifySeverity getNotifyLevel();
/** is notification enabled, given the current setNotifyLevel() setting? */
extern OSG_EXPORT bool isNotifyEnabled(NotifySeverity severity);
/** initialize notify level. */ /** initialize notify level. */
extern OSG_EXPORT bool initNotifyLevel(); extern OSG_EXPORT bool initNotifyLevel();
#ifdef OSG_NOTIFY_DISABLED
inline bool isNotifyEnabled(NotifySeverity) { return false; }
#else
/** is notification enabled, given the current setNotifyLevel() setting? */
extern OSG_EXPORT bool isNotifyEnabled(NotifySeverity severity);
#endif
/** notify messaging function for providing fatal through to verbose /** notify messaging function for providing fatal through to verbose
* debugging messages. Level of messages sent to the console can * debugging messages. Level of messages sent to the console can
* be controlled by setting the NotifyLevel either within your * be controlled by setting the NotifyLevel either within your
* application or via the an environmental variable i.e. * application or via the an environmental variable. For instance
* - setenv OSGNOTIFYLEVEL DEBUG (for tsh) * setenv OSGNOTIFYLEVEL DEBUG (for tsh), export OSGNOTIFYLEVEL=DEBUG
* - export OSGNOTIFYLEVEL=DEBUG (for bourne shell) * (for bourne shell) or set OSGNOTIFYLEVEL=DEBUG (for Windows) all
* - set OSGNOTIFYLEVEL=DEBUG (for Windows) * tell the osg to redirect all debugging and more important messages
* * to the console (useful for debugging :-) setting ALWAYS will force
* All tell the osg to redirect all debugging and more important messages
* to the notification stream (useful for debugging) setting ALWAYS will force
* all messages to be absorbed, which might be appropriate for final * all messages to be absorbed, which might be appropriate for final
* applications. Default NotifyLevel is NOTICE. Check the enum * applications. Default NotifyLevel is NOTICE. Check the enum
* #NotifySeverity for full range of possibilities. To use the notify * NotifySeverity for full range of possibilities. To use the notify
* with your code simply use the notify function as a normal file * with your code simply use the notify function as a normal file
* stream (like std::cout) i.e * stream (like cout) i.e osg::notify(osg::DEBUG) << "Hello Bugs!"<<endl;
* @code
* osg::notify(osg::DEBUG) << "Hello Bugs!" << std::endl;
* @endcode
* @see setNotifyLevel, setNotifyHandler
*/ */
extern OSG_EXPORT std::ostream& notify(const NotifySeverity severity); extern OSG_EXPORT std::ostream& notify(const NotifySeverity severity);
inline std::ostream& notify(void) { return notify(osg::INFO); } inline std::ostream& notify(void) { return notify(osg::INFO); }
#define OSG_NOTIFY(level) if (osg::isNotifyEnabled(level)) osg::notify(level)
#define OSG_ALWAYS OSG_NOTIFY(osg::ALWAYS)
#define OSG_FATAL OSG_NOTIFY(osg::FATAL)
#define OSG_WARN OSG_NOTIFY(osg::WARN)
#define OSG_NOTICE OSG_NOTIFY(osg::NOTICE)
#define OSG_INFO OSG_NOTIFY(osg::INFO)
#define OSG_DEBUG OSG_NOTIFY(osg::DEBUG_INFO)
#define OSG_DEBUG_FP OSG_NOTIFY(osg::DEBUG_FP)
/** Handler processing output of notification stream. It acts as a sink to
* notification messages. It is called when notification stream needs to be
* synchronized (i.e. after osg::notify() << std::endl).
* StandardNotifyHandler is used by default, it writes notifications to stderr
* (severity <= WARN) or stdout (severity > WARN).
* Notifications can be redirected to other sinks such as GUI widgets or
* windows debugger (WinDebugNotifyHandler) with custom handlers.
* Use setNotifyHandler to set custom handler.
* Note that osg notification API is not thread safe although notification
* handler is called from many threads. When incorporating handlers into GUI
* widgets you must take care of thread safety on your own.
* @see setNotifyHandler
*/
class OSG_EXPORT NotifyHandler : public osg::Referenced
{
public:
virtual void notify(osg::NotifySeverity severity, const char *message) = 0;
};
/** Set notification handler, by default StandardNotifyHandler is used.
* @see NotifyHandler
*/
extern OSG_EXPORT void setNotifyHandler(NotifyHandler *handler);
/** Get currrent notification handler. */
extern OSG_EXPORT NotifyHandler *getNotifyHandler();
/** Redirects notification stream to stderr (severity <= WARN) or stdout (severity > WARN).
* The fputs() function is used to write messages to standard files. Note that
* std::out and std::cerr streams are not used.
* @see setNotifyHandler
*/
class OSG_EXPORT StandardNotifyHandler : public NotifyHandler
{
public:
void notify(osg::NotifySeverity severity, const char *message);
};
#if defined(WIN32) && !defined(__CYGWIN__)
/** Redirects notification stream to windows debugger with use of
* OuputDebugString functions.
* @see setNotifyHandler
*/
class OSG_EXPORT WinDebugNotifyHandler : public NotifyHandler
{
public:
void notify(osg::NotifySeverity severity, const char *message);
};
#endif
} }
#endif #endif

View File

@@ -96,14 +96,10 @@ class OSG_EXPORT Object : public Referenced
/** Set the name of object using C++ style string.*/ /** Set the name of object using C++ style string.*/
virtual void setName( const std::string& name ) { _name = name; } inline void setName( const std::string& name ) { _name = name; }
/** Set the name of object using a C style string.*/ /** Set the name of object using a C style string.*/
inline void setName( const char* name ) inline void setName( const char* name ) { _name = name; }
{
if (name) setName(std::string(name));
else setName(std::string());
}
/** Get the name of object.*/ /** Get the name of object.*/
inline const std::string& getName() const { return _name; } inline const std::string& getName() const { return _name; }

View File

@@ -18,75 +18,11 @@
#include <osg/Export> #include <osg/Export>
#include <osg/CopyOp> #include <osg/CopyOp>
#include <osg/Group> #include <osg/Group>
#include <osg/Geometry>
namespace osg { namespace osg {
// Create and return a StateSet appropriate for performing an occlusion
// query test (disable lighting, texture mapping, etc). Probably some
// room for improvement here. Could disable shaders, for example.
osg::StateSet* initOQState();
// Create and return a StateSet for rendering a debug representation of query geometry.
osg::StateSet* initOQDebugState();
// TestResult -- stores (per context) results of an occlusion query
// test performed by QueryGeometry. An OcclusionQueryNode has a
// Geode owning a single QueryGeometry that
// draws the occlusion query geometry. QueryGeometry keeps a
// TestResult per context to store the result/status of each query.
// Accessed during the cull and draw traversals.
class TestResult : public osg::Referenced
{
public:
TestResult() : _init( false ), _id( 0 ), _contextID( 0 ), _active( false ), _numPixels( 0 ) {}
~TestResult() {}
bool _init;
// Query ID for this context.
GLuint _id;
// Context ID owning this query ID.
unsigned int _contextID;
// Set to true when a query gets issued and set to
// false when the result is retrieved.
mutable bool _active;
// Result of last query.
GLint _numPixels;
};
// QueryGeometry -- A Drawable that performs an occlusion query,
// using its geometric data as the query geometry.
class QueryGeometry : public osg::Geometry
{
public:
QueryGeometry( const std::string& oqnName=std::string("") );
~QueryGeometry();
void reset();
// TBD implement copy constructor
virtual void drawImplementation( osg::RenderInfo& renderInfo ) const;
unsigned int getNumPixels();
void releaseGLObjects( osg::State* state = 0 );
static void deleteQueryObject( unsigned int contextID, GLuint handle );
static void flushDeletedQueryObjects( unsigned int contextID, double currentTime, double& availableTime );
static void discardDeletedQueryObjects( unsigned int contextID );
protected:
typedef osg::buffered_object< TestResult > ResultMap;
mutable ResultMap _results;
// Needed for debug only
std::string _oqnName;
};
// This Node performs occlusion query testing on its children. // This Node performs occlusion query testing on its children.
// You can use it directly to occlusion query test a portion // You can use it directly to occlusion query test a portion
@@ -152,7 +88,7 @@ public:
// These methods are public so that osgUtil::CullVisitor can access them. // These methods are public so that osgUtil::CullVisitor can access them.
// Not intended for application use. // Not intended for application use.
virtual bool getPassed( const osg::Camera* camera, osg::NodeVisitor& nv ); bool getPassed( const osg::Camera* camera, osg::NodeVisitor& nv );
void traverseQuery( const osg::Camera* camera, osg::NodeVisitor& nv ); void traverseQuery( const osg::Camera* camera, osg::NodeVisitor& nv );
void traverseDebug( osg::NodeVisitor& nv ); void traverseDebug( osg::NodeVisitor& nv );
@@ -169,7 +105,7 @@ public:
protected: protected:
virtual ~OcclusionQueryNode(); virtual ~OcclusionQueryNode();
virtual void createSupportNodes(); void createSupportNodes();
osg::ref_ptr< osg::Geode > _queryGeode; osg::ref_ptr< osg::Geode > _queryGeode;
osg::ref_ptr< osg::Geode > _debugGeode; osg::ref_ptr< osg::Geode > _debugGeode;

View File

@@ -142,9 +142,8 @@ class OSG_EXPORT Program : public osg::StateAttribute
GLenum _type; GLenum _type;
GLint _size; GLint _size;
}; };
typedef std::map< unsigned int, ActiveVarInfo > ActiveUniformMap;
typedef std::map< std::string, ActiveVarInfo > ActiveVarInfoMap; typedef std::map< std::string, ActiveVarInfo > ActiveVarInfoMap;
const ActiveUniformMap& getActiveUniforms(unsigned int contextID) const; const ActiveVarInfoMap& getActiveUniforms(unsigned int contextID) const;
const ActiveVarInfoMap& getActiveAttribs(unsigned int contextID) const; const ActiveVarInfoMap& getActiveAttribs(unsigned int contextID) const;
public: public:
@@ -185,7 +184,7 @@ class OSG_EXPORT Program : public osg::StateAttribute
inline void apply(const Uniform& uniform) const inline void apply(const Uniform& uniform) const
{ {
GLint location = getUniformLocation(uniform.getNameID()); GLint location = getUniformLocation(uniform.getName());
if (location>=0) if (location>=0)
{ {
if ((unsigned int)location>=_lastAppliedUniformList.size()) _lastAppliedUniformList.resize(location+1); if ((unsigned int)location>=_lastAppliedUniformList.size()) _lastAppliedUniformList.resize(location+1);
@@ -207,21 +206,10 @@ class OSG_EXPORT Program : public osg::StateAttribute
} }
} }
const ActiveUniformMap& getActiveUniforms() const {return _uniformInfoMap;} const ActiveVarInfoMap& getActiveUniforms() const {return _uniformInfoMap;}
const ActiveVarInfoMap& getActiveAttribs() const {return _attribInfoMap;} const ActiveVarInfoMap& getActiveAttribs() const {return _attribInfoMap;}
inline GLint getUniformLocation( unsigned int uniformNameID ) const { ActiveUniformMap::const_iterator itr = _uniformInfoMap.find(uniformNameID); return (itr!=_uniformInfoMap.end()) ? itr->second._location : -1; } inline GLint getUniformLocation( const std::string& name ) const { ActiveVarInfoMap::const_iterator itr = _uniformInfoMap.find(name); return (itr!=_uniformInfoMap.end()) ? itr->second._location : -1; }
/**
* Alternative version of getUniformLocation( unsigned int uniformNameID )
* retrofited into OSG for backward compatibility with osgCal,
* after uniform ids were refactored from std::strings to GLints in OSG version 2.9.10.
*
* Drawbacks: This method is not particularly fast. It has to access mutexed static
* map of uniform ids. So don't overuse it or your app performance will suffer.
*/
inline GLint getUniformLocation( const std::string & uniformName ) const { return getUniformLocation( Uniform::getNameID( uniformName ) ); }
inline GLint getAttribLocation( const std::string& name ) const { ActiveVarInfoMap::const_iterator itr = _attribInfoMap.find(name); return (itr!=_attribInfoMap.end()) ? itr->second._location : -1; } inline GLint getAttribLocation( const std::string& name ) const { ActiveVarInfoMap::const_iterator itr = _attribInfoMap.find(name); return (itr!=_attribInfoMap.end()) ? itr->second._location : -1; }
inline void addShaderToAttach(Shader *shader) inline void addShaderToAttach(Shader *shader)
@@ -250,7 +238,7 @@ class OSG_EXPORT Program : public osg::StateAttribute
bool _isLinked; bool _isLinked;
const unsigned int _contextID; const unsigned int _contextID;
ActiveUniformMap _uniformInfoMap; ActiveVarInfoMap _uniformInfoMap;
ActiveVarInfoMap _attribInfoMap; ActiveVarInfoMap _attribInfoMap;
typedef std::pair<osg::ref_ptr<const osg::Uniform>, unsigned int> UniformModifiedCountPair; typedef std::pair<osg::ref_ptr<const osg::Uniform>, unsigned int> UniformModifiedCountPair;

View File

@@ -975,16 +975,7 @@ class OSG_EXPORT State : public Referenced, public Observer
} }
inline const Program::PerContextProgram* getLastAppliedProgramObject() const { return _lastAppliedProgramObject; } inline const Program::PerContextProgram* getLastAppliedProgramObject() const { return _lastAppliedProgramObject; }
inline GLint getUniformLocation( unsigned int uniformNameID ) const { return _lastAppliedProgramObject ? _lastAppliedProgramObject->getUniformLocation(uniformNameID) : -1; } inline GLint getUniformLocation( const std::string& name ) const { return _lastAppliedProgramObject ? _lastAppliedProgramObject->getUniformLocation(name) : -1; }
/**
* Alternative version of getUniformLocation( unsigned int uniformNameID )
* retrofited into OSG for backward compatibility with osgCal,
* after uniform ids were refactored from std::strings to GLints in OSG version 2.9.10.
*
* Drawbacks: This method is not particularly fast. It has to access mutexed static
* map of uniform ids. So don't overuse it or your app performance will suffer.
*/
inline GLint getUniformLocation( const std::string & uniformName ) const { return _lastAppliedProgramObject ? _lastAppliedProgramObject->getUniformLocation(uniformName) : -1; }
inline GLint getAttribLocation( const std::string& name ) const { return _lastAppliedProgramObject ? _lastAppliedProgramObject->getAttribLocation(name) : -1; } inline GLint getAttribLocation( const std::string& name ) const { return _lastAppliedProgramObject ? _lastAppliedProgramObject->getAttribLocation(name) : -1; }

View File

@@ -199,10 +199,6 @@
#define GL_TEXTURE_DEPTH 0x8071 #define GL_TEXTURE_DEPTH 0x8071
#endif #endif
#ifndef GL_TEXTURE_2D_MULTISAMPLE
#define GL_TEXTURE_2D_MULTISAMPLE 0x9100
#endif
// Integer teture extension as in http://www.opengl.org/registry/specs/EXT/texture_integer.txt // Integer teture extension as in http://www.opengl.org/registry/specs/EXT/texture_integer.txt
#ifndef GL_EXT_texture_integer #ifndef GL_EXT_texture_integer
#define GL_RGBA32UI_EXT 0x8D70 #define GL_RGBA32UI_EXT 0x8D70
@@ -583,6 +579,12 @@ class OSG_EXPORT Texture : public osg::StateAttribute
public: public:
Extensions(unsigned int contextID); Extensions(unsigned int contextID);
Extensions(const Extensions& rhs);
void lowestCommonDenominator(const Extensions& rhs);
void setupGLExtensions(unsigned int contextID);
void setMultiTexturingSupported(bool flag) { _isMultiTexturingSupported=flag; } void setMultiTexturingSupported(bool flag) { _isMultiTexturingSupported=flag; }
bool isMultiTexturingSupported() const { return _isMultiTexturingSupported; } bool isMultiTexturingSupported() const { return _isMultiTexturingSupported; }
@@ -607,9 +609,6 @@ class OSG_EXPORT Texture : public osg::StateAttribute
void setGenerateMipMapSupported(bool flag) { _isGenerateMipMapSupported=flag; } void setGenerateMipMapSupported(bool flag) { _isGenerateMipMapSupported=flag; }
bool isGenerateMipMapSupported() const { return _isGenerateMipMapSupported; } bool isGenerateMipMapSupported() const { return _isGenerateMipMapSupported; }
void setTextureMultisampledSupported(bool flag) { _isTextureMultisampledSupported=flag; }
bool isTextureMultisampledSupported() const { return _isTextureMultisampledSupported; }
void setShadowSupported(bool flag) { _isShadowSupported = flag; } void setShadowSupported(bool flag) { _isShadowSupported = flag; }
bool isShadowSupported() const { return _isShadowSupported; } bool isShadowSupported() const { return _isShadowSupported; }
@@ -625,6 +624,10 @@ class OSG_EXPORT Texture : public osg::StateAttribute
bool isCompressedTexImage2DSupported() const { return _glCompressedTexImage2D!=0; } bool isCompressedTexImage2DSupported() const { return _glCompressedTexImage2D!=0; }
bool isCompressedTexSubImage2DSupported() const { return _glCompressedTexSubImage2D!=0; } bool isCompressedTexSubImage2DSupported() const { return _glCompressedTexSubImage2D!=0; }
void glCompressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data) const;
void glCompressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei type, const GLvoid *data) const;
void glGetCompressedTexImage(GLenum target, GLint level, GLvoid *data) const;
bool isClientStorageSupported() const { return _isClientStorageSupported; } bool isClientStorageSupported() const { return _isClientStorageSupported; }
bool isNonPowerOfTwoTextureSupported(GLenum filter) const bool isNonPowerOfTwoTextureSupported(GLenum filter) const
@@ -637,55 +640,13 @@ class OSG_EXPORT Texture : public osg::StateAttribute
void setTextureIntegerSupported(bool flag) { _isTextureIntegerEXTSupported=flag; } void setTextureIntegerSupported(bool flag) { _isTextureIntegerEXTSupported=flag; }
bool isTextureIntegerSupported() const { return _isTextureIntegerEXTSupported; } bool isTextureIntegerSupported() const { return _isTextureIntegerEXTSupported; }
void glCompressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data) const void glTexParameterIiv(GLenum target, GLenum pname, const GLint* data) const;
{ void glTexParameterIuiv(GLenum target, GLenum pname, const GLuint* data) const;
_glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data);
}
void glCompressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data) const
{
_glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data);
}
void glGetCompressedTexImage(GLenum target, GLint level, GLvoid *data) const
{
_glGetCompressedTexImage(target, level, data);
}
void glTexImage2DMultisample(GLenum target, GLsizei samples, GLint internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations) const
{
_glTexImage2DMultisample(target, samples, internalformat, width, height, fixedsamplelocations);
}
void glTexParameterIiv(GLenum target, GLenum pname, const GLint* data) const
{
_glTexParameterIiv(target, pname, data);
}
void glTexParameterIuiv(GLenum target, GLenum pname, const GLuint* data) const
{
_glTexParameterIuiv(target, pname, data);
}
protected: protected:
~Extensions() {} ~Extensions() {}
typedef void (APIENTRY * CompressedTexImage2DArbProc) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data);
typedef void (APIENTRY * CompressedTexSubImage2DArbProc) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data);
typedef void (APIENTRY * GetCompressedTexImageArbProc) (GLenum target, GLint level, GLvoid *data);
typedef void (APIENTRY * TexImage2DMultisample)(GLenum target, GLsizei samples, GLint internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations);
typedef void (APIENTRY * TexParameterIivProc)(GLenum target, GLenum pname, const GLint* data);
typedef void (APIENTRY * TexParameterIuivProc)(GLenum target, GLenum pname, const GLuint* data);
CompressedTexImage2DArbProc _glCompressedTexImage2D;
CompressedTexSubImage2DArbProc _glCompressedTexSubImage2D;
GetCompressedTexImageArbProc _glGetCompressedTexImage;
TexImage2DMultisample _glTexImage2DMultisample;
TexParameterIivProc _glTexParameterIiv;
TexParameterIuivProc _glTexParameterIuiv;
bool _isMultiTexturingSupported; bool _isMultiTexturingSupported;
bool _isTextureFilterAnisotropicSupported; bool _isTextureFilterAnisotropicSupported;
bool _isTextureCompressionARBSupported; bool _isTextureCompressionARBSupported;
@@ -694,7 +655,6 @@ class OSG_EXPORT Texture : public osg::StateAttribute
bool _isTextureEdgeClampSupported; bool _isTextureEdgeClampSupported;
bool _isTextureBorderClampSupported; bool _isTextureBorderClampSupported;
bool _isGenerateMipMapSupported; bool _isGenerateMipMapSupported;
bool _isTextureMultisampledSupported;
bool _isShadowSupported; bool _isShadowSupported;
bool _isShadowAmbientSupported; bool _isShadowAmbientSupported;
bool _isClientStorageSupported; bool _isClientStorageSupported;
@@ -704,6 +664,19 @@ class OSG_EXPORT Texture : public osg::StateAttribute
GLint _maxTextureSize; GLint _maxTextureSize;
GLint _numTextureUnits; GLint _numTextureUnits;
typedef void (APIENTRY * CompressedTexImage2DArbProc) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data);
typedef void (APIENTRY * CompressedTexSubImage2DArbProc) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data);
typedef void (APIENTRY * GetCompressedTexImageArbProc) (GLenum target, GLint level, GLvoid *data);
typedef void (APIENTRY * TexParameterIivProc)(GLenum target, GLenum pname, const GLint* data);
typedef void (APIENTRY * TexParameterIuivProc)(GLenum target, GLenum pname, const GLuint* data);
CompressedTexImage2DArbProc _glCompressedTexImage2D;
CompressedTexSubImage2DArbProc _glCompressedTexSubImage2D;
GetCompressedTexImageArbProc _glGetCompressedTexImage;
TexParameterIivProc _glTexParameterIiv;
TexParameterIuivProc _glTexParameterIuiv;
}; };
/** Gets the extension for the specified context. Creates the /** Gets the extension for the specified context. Creates the
@@ -737,7 +710,6 @@ class OSG_EXPORT Texture : public osg::StateAttribute
* unless you're implementing a subload callback. */ * unless you're implementing a subload callback. */
void applyTexImage2D_subload(State& state, GLenum target, const Image* image, GLsizei width, GLsizei height, GLint inInternalFormat, GLsizei numMipmapLevels) const; void applyTexImage2D_subload(State& state, GLenum target, const Image* image, GLsizei width, GLsizei height, GLint inInternalFormat, GLsizei numMipmapLevels) const;
/** Returned by mipmapBeforeTexImage() to indicate what /** Returned by mipmapBeforeTexImage() to indicate what
* mipmapAfterTexImage() should do */ * mipmapAfterTexImage() should do */
enum GenerateMipmapMode enum GenerateMipmapMode

View File

@@ -1,95 +0,0 @@
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*
* Texture2DMultisample codes Copyright (C) 2010 Marcin Hajder
* Thanks to to my company http://www.ai.com.pl for allowing me free this work.
*/
#ifndef OSG_TEXTURE2DMS
#define OSG_TEXTURE2DMS 1
#include <osg/Texture>
namespace osg {
/** Texture2DMultisample state class which encapsulates OpenGL 2D multisampled texture functionality.
* Multisampled texture were introduced with OpenGL 3.1 and extension GL_ARB_texture_multisample.
* See http://www.opengl.org/registry/specs/ARB/texture_multisample.txt for more info.
*/
class OSG_EXPORT Texture2DMultisample : public Texture
{
public :
Texture2DMultisample();
Texture2DMultisample(GLsizei numSamples, GLboolean fixedsamplelocations);
/** Copy constructor using CopyOp to manage deep vs shallow copy. */
Texture2DMultisample(const Texture2DMultisample& text,const CopyOp& copyop=CopyOp::SHALLOW_COPY);
META_StateAttribute(osg, Texture2DMultisample,TEXTURE);
/** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */
virtual int compare(const StateAttribute& rhs) const;
virtual GLenum getTextureTarget() const
{
return GL_TEXTURE_2D_MULTISAMPLE;
}
/** Sets the texture width and height. If width or height are zero,
* calculate the respective value from the source image size. */
inline void setTextureSize(int width, int height) const
{
_textureWidth = width;
_textureHeight = height;
}
inline void setNumSamples( int samples ) { _numSamples = samples; }
// unnecessary for Texture2DMultisample
virtual void setImage(unsigned int /*face*/, Image* /*image*/) {}
virtual Image* getImage(unsigned int /*face*/) { return NULL; }
virtual const Image* getImage(unsigned int /*face*/) const { return NULL; }
virtual unsigned int getNumImages() const {return 0; }
virtual void allocateMipmap(State& /*state*/) const {}
void setTextureWidth(int width) { _textureWidth=width; }
void setTextureHeight(int height) { _textureHeight=height; }
virtual int getTextureWidth() const { return _textureWidth; }
virtual int getTextureHeight() const { return _textureHeight; }
virtual int getTextureDepth() const { return 1; }
/** Bind the texture object. If the texture object hasn't already been
* compiled, create the texture mipmap levels. */
virtual void apply(State& state) const;
protected :
virtual ~Texture2DMultisample();
virtual void computeInternalFormat() const;
/** Subloaded images can have different texture and image sizes. */
mutable GLsizei _textureWidth, _textureHeight;
mutable GLsizei _numSamples;
mutable GLboolean _fixedsamplelocations;
};
}
#endif

View File

@@ -232,7 +232,7 @@ class OSG_EXPORT Uniform : public Object
Type getType() const { return _type; } Type getType() const { return _type; }
/** Set the name of the glUniform, ensuring it is only set once.*/ /** Set the name of the glUniform, ensuring it is only set once.*/
virtual void setName( const std::string& name ); void setName( const std::string& name );
/** Set the length of a uniform, ensuring it is only set once (1==scalar)*/ /** Set the length of a uniform, ensuring it is only set once (1==scalar)*/
void setNumElements( unsigned int numElements ); void setNumElements( unsigned int numElements );
@@ -259,9 +259,6 @@ class OSG_EXPORT Uniform : public Object
/** Return the internal data array type corresponding to a GLSL type */ /** Return the internal data array type corresponding to a GLSL type */
static GLenum getInternalArrayType( Type t ); static GLenum getInternalArrayType( Type t );
/** Return the number that the name maps to uniquely */
static unsigned int getNameID(const std::string& name);
/** convenient scalar (non-array) constructors w/ assignment */ /** convenient scalar (non-array) constructors w/ assignment */
explicit Uniform( const char* name, float f ); explicit Uniform( const char* name, float f );
explicit Uniform( const char* name, int i ); explicit Uniform( const char* name, int i );
@@ -466,8 +463,6 @@ class OSG_EXPORT Uniform : public Object
inline void setModifiedCount(unsigned int mc) { _modifiedCount = mc; } inline void setModifiedCount(unsigned int mc) { _modifiedCount = mc; }
inline unsigned int getModifiedCount() const { return _modifiedCount; } inline unsigned int getModifiedCount() const { return _modifiedCount; }
/** Get the number that the Uniform's name maps to uniquely */
unsigned int getNameID() const;
void apply(const GL2Extensions* ext, GLint location) const; void apply(const GL2Extensions* ext, GLint location) const;
@@ -489,8 +484,6 @@ class OSG_EXPORT Uniform : public Object
Type _type; Type _type;
unsigned int _numElements; unsigned int _numElements;
unsigned int _nameID;
// The internal data for osg::Uniforms are stored as an array of // The internal data for osg::Uniforms are stored as an array of
// getInternalArrayType() of length getInternalArrayNumElements(). // getInternalArrayType() of length getInternalArrayNumElements().

View File

@@ -21,8 +21,8 @@ extern "C" {
#define OPENSCENEGRAPH_MAJOR_VERSION 2 #define OPENSCENEGRAPH_MAJOR_VERSION 2
#define OPENSCENEGRAPH_MINOR_VERSION 8 #define OPENSCENEGRAPH_MINOR_VERSION 8
#define OPENSCENEGRAPH_PATCH_VERSION 5 #define OPENSCENEGRAPH_PATCH_VERSION 3
#define OPENSCENEGRAPH_SOVERSION 74 #define OPENSCENEGRAPH_SOVERSION 65
/** convinience macro that can be used to decide whether a feature is present or not i.e. /** convinience macro that can be used to decide whether a feature is present or not i.e.
* #if OSG_MIN_VERSION_REQUIRED(2,9,5) * #if OSG_MIN_VERSION_REQUIRED(2,9,5)

View File

@@ -91,9 +91,6 @@ class OSGDB_EXPORT Output : public osgDB::ofstream
virtual std::string getFileNameForOutput(const std::string& filename) const; virtual std::string getFileNameForOutput(const std::string& filename) const;
const std::string& getFileName() const { return _filename; } const std::string& getFileName() const { return _filename; }
void setOutputRelativeTextures(bool flag) { _outputRelativeTextures = flag; }
bool getOutputRelativeTextures() const { return _outputRelativeTextures; }
void setOutputTextureFiles(bool flag) { _outputTextureFiles = flag; } void setOutputTextureFiles(bool flag) { _outputTextureFiles = flag; }
bool getOutputTextureFiles() const { return _outputTextureFiles; } bool getOutputTextureFiles() const { return _outputTextureFiles; }
@@ -123,7 +120,6 @@ class OSGDB_EXPORT Output : public osgDB::ofstream
PathNameHint _pathNameHint; PathNameHint _pathNameHint;
bool _outputRelativeTextures;
bool _outputTextureFiles; bool _outputTextureFiles;
unsigned int _textureFileNameNumber; unsigned int _textureFileNameNumber;

View File

@@ -19,8 +19,6 @@
#include <osg/Quat> #include <osg/Quat>
#include <osg/observer_ptr> #include <osg/observer_ptr>
#include <iterator>
namespace osgGA{ namespace osgGA{
class OSGGA_EXPORT NodeTrackerManipulator : public MatrixManipulator class OSGGA_EXPORT NodeTrackerManipulator : public MatrixManipulator

View File

@@ -224,7 +224,7 @@ namespace osgIntrospection
// returns the actual pointed type if applicable // returns the actual pointed type if applicable
virtual const Type* ptype() const { return 0; } virtual const Type* ptype() const { return 0; }
// returns whether the data is a null pointer // returns whether the data is a null pointer
virtual bool isnullptr() const = 0; virtual bool nullptr() const = 0;
Instance_base *inst_; Instance_base *inst_;
Instance_base *_ref_inst; Instance_base *_ref_inst;
@@ -237,9 +237,9 @@ namespace osgIntrospection
{ {
Instance_box(): Instance_box_base(), nullptr_(false) {} Instance_box(): Instance_box_base(), nullptr_(false) {}
Instance_box(const T &d, bool isnullptr = false) Instance_box(const T &d, bool nullptr = false)
: Instance_box_base(), : Instance_box_base(),
nullptr_(isnullptr) nullptr_(nullptr)
{ {
Instance<T> *vl = new Instance<T>(d); Instance<T> *vl = new Instance<T>(d);
inst_ = vl; inst_ = vl;
@@ -267,7 +267,7 @@ namespace osgIntrospection
return &typeof(T); return &typeof(T);
} }
virtual bool isnullptr() const virtual bool nullptr() const
{ {
return nullptr_; return nullptr_;
} }
@@ -322,7 +322,7 @@ namespace osgIntrospection
return &typeofvalue(*static_cast<Instance<T> *>(inst_)->_data); return &typeofvalue(*static_cast<Instance<T> *>(inst_)->_data);
} }
virtual bool isnullptr() const virtual bool nullptr() const
{ {
return static_cast<Instance<T> *>(inst_)->_data == 0; return static_cast<Instance<T> *>(inst_)->_data == 0;
} }
@@ -428,7 +428,7 @@ namespace osgIntrospection
inline bool Value::isNullPointer() const inline bool Value::isNullPointer() const
{ {
return _inbox->isnullptr(); return _inbox->nullptr();
} }
} }

View File

@@ -69,9 +69,8 @@ class OSGSIM_EXPORT MultiSwitch : public osg::Group
/** Get which of the available switch set lists to use.*/ /** Get which of the available switch set lists to use.*/
unsigned int getActiveSwitchSet() const { return _activeSwitchSet; } unsigned int getActiveSwitchSet() const { return _activeSwitchSet; }
typedef std::vector<bool> ValueList; typedef std::vector<bool> ValueList;
typedef std::vector<ValueList> SwitchSetList; typedef std::vector<ValueList> SwitchSetList;
typedef std::vector<std::string> SwitchSetNameList;
/** Set the compile set of different values.*/ /** Set the compile set of different values.*/
void setSwitchSetList(const SwitchSetList& switchSetList); void setSwitchSetList(const SwitchSetList& switchSetList);
@@ -85,10 +84,6 @@ class OSGSIM_EXPORT MultiSwitch : public osg::Group
/** Get the a single set of different values for a particular switch set.*/ /** Get the a single set of different values for a particular switch set.*/
const ValueList& getValueList(unsigned int switchSet) const { return _values[switchSet]; } const ValueList& getValueList(unsigned int switchSet) const { return _values[switchSet]; }
void setValueName(unsigned int switchSet, const std::string& name);
const std::string& getValueName(unsigned int switchSet) const { return _valueNames[switchSet]; }
protected : protected :
virtual ~MultiSwitch() {} virtual ~MultiSwitch() {}
@@ -96,10 +91,9 @@ class OSGSIM_EXPORT MultiSwitch : public osg::Group
void expandToEncompassSwitchSet(unsigned int switchSet); void expandToEncompassSwitchSet(unsigned int switchSet);
// this is effectively a list of bit mask. // this is effectively a list of bit mask.
bool _newChildDefaultValue; bool _newChildDefaultValue;
unsigned int _activeSwitchSet; unsigned int _activeSwitchSet;
SwitchSetList _values; SwitchSetList _values;
SwitchSetNameList _valueNames;
}; };
} }

View File

@@ -62,16 +62,6 @@ public:
/**
* Turns off writing to the depth buffer when rendering text. This only affects text
* with no backdrop or text using the DELAYED_DEPTH_WRITES implementation, since
* the other backdrop implementations are really only useful for backwards
* compatibility and are not worth updating to utilize this flag.
*/
bool setEnableDepthWrites() { return _enableDepthWrites; }
void setEnableDepthWrites(bool enable) { _enableDepthWrites = enable; }
enum BackdropType enum BackdropType
{ {
DROP_SHADOW_BOTTOM_RIGHT = 0, // usually the type of shadow you see DROP_SHADOW_BOTTOM_RIGHT = 0, // usually the type of shadow you see
@@ -156,17 +146,7 @@ public:
* are significant on your particular hardware.) This mode is best for * are significant on your particular hardware.) This mode is best for
* when quality is important and stencil buffer hardware acceleration * when quality is important and stencil buffer hardware acceleration
* is available.*/ * is available.*/
STENCIL_BUFFER, STENCIL_BUFFER
/* DELAYED_DEPTH_WRITES
* This mode renders all text with depth writes turned off, then
* again with depth writes on, but with the color buffer disabled.
* This should render text accurately for all graphics cards. The
* only downside is the additional pass to render to the depth
* buffer. But if you don't need the depth buffer updated for
* your, this extra pass can be disabled by calling
* enableDepthWrites(false).*/
DELAYED_DEPTH_WRITES
}; };
/** /**
@@ -397,16 +377,12 @@ protected:
void drawImplementation(osg::State& state, const osg::Vec4& colorMultiplier) const; void drawImplementation(osg::State& state, const osg::Vec4& colorMultiplier) const;
void drawForegroundText(osg::State& state, const GlyphQuads& glyphquad, const osg::Vec4& colorMultiplier) const; void drawForegroundText(osg::State& state, const GlyphQuads& glyphquad, const osg::Vec4& colorMultiplier) const;
void drawTextWithBackdrop(osg::State& state, const osg::Vec4& colorMultiplier) const;
void renderOnlyForegroundText(osg::State& state, const osg::Vec4& colorMultiplier) const; void renderOnlyForegroundText(osg::State& state, const osg::Vec4& colorMultiplier) const;
void renderWithPolygonOffset(osg::State& state, const osg::Vec4& colorMultiplier) const; void renderWithPolygonOffset(osg::State& state, const osg::Vec4& colorMultiplier) const;
void renderWithNoDepthBuffer(osg::State& state, const osg::Vec4& colorMultiplier) const; void renderWithNoDepthBuffer(osg::State& state, const osg::Vec4& colorMultiplier) const;
void renderWithDepthRange(osg::State& state, const osg::Vec4& colorMultiplier) const; void renderWithDepthRange(osg::State& state, const osg::Vec4& colorMultiplier) const;
void renderWithStencilBuffer(osg::State& state, const osg::Vec4& colorMultiplier) const; void renderWithStencilBuffer(osg::State& state, const osg::Vec4& colorMultiplier) const;
void renderWithDelayedDepthWrites(osg::State& state, const osg::Vec4& colorMultiplier) const;
bool _enableDepthWrites;
BackdropType _backdropType; BackdropType _backdropType;
BackdropImplementation _backdropImplementation; BackdropImplementation _backdropImplementation;

View File

@@ -154,7 +154,6 @@ SET(LIB_PUBLIC_HEADERS
${HEADER_PATH}/Texture ${HEADER_PATH}/Texture
${HEADER_PATH}/Texture1D ${HEADER_PATH}/Texture1D
${HEADER_PATH}/Texture2D ${HEADER_PATH}/Texture2D
${HEADER_PATH}/Texture2DMultisample
${HEADER_PATH}/Texture2DArray ${HEADER_PATH}/Texture2DArray
${HEADER_PATH}/Texture3D ${HEADER_PATH}/Texture3D
${HEADER_PATH}/TextureCubeMap ${HEADER_PATH}/TextureCubeMap
@@ -310,7 +309,6 @@ ADD_LIBRARY(${LIB_NAME}
Texture1D.cpp Texture1D.cpp
Texture2DArray.cpp Texture2DArray.cpp
Texture2D.cpp Texture2D.cpp
Texture2DMultisample.cpp
Texture3D.cpp Texture3D.cpp
Texture.cpp Texture.cpp
TextureCubeMap.cpp TextureCubeMap.cpp
@@ -328,7 +326,7 @@ ADD_LIBRARY(${LIB_NAME}
LINK_INTERNAL(${LIB_NAME} LINK_INTERNAL(${LIB_NAME}
OpenThreads OpenThreads
) )
LINK_EXTERNAL(${LIB_NAME} ${CMAKE_THREAD_LIBS_INIT} ${MATH_LIBRARY} ${DL_LIBRARY}) LINK_EXTERNAL(${LIB_NAME} ${CMAKE_THREAD_LIBS_INIT} ${MATH_LIBRARY} )
LINK_CORELIB_DEFAULT(${LIB_NAME} ${CMAKE_THREAD_LIBS_INIT} ${MATH_LIBRARY} ) LINK_CORELIB_DEFAULT(${LIB_NAME} ${CMAKE_THREAD_LIBS_INIT} ${MATH_LIBRARY} )
INCLUDE(ModuleInstall OPTIONAL) INCLUDE(ModuleInstall OPTIONAL)

View File

@@ -23,7 +23,6 @@
#ifndef OSG_CONFIG #ifndef OSG_CONFIG
#define OSG_CONFIG 1 #define OSG_CONFIG 1
#cmakedefine OSG_NOTIFY_DISABLED
#cmakedefine OSG_USE_FLOAT_MATRIX #cmakedefine OSG_USE_FLOAT_MATRIX
#cmakedefine OSG_USE_FLOAT_PLANE #cmakedefine OSG_USE_FLOAT_PLANE
#cmakedefine OSG_USE_FLOAT_BOUNDINGSPHERE #cmakedefine OSG_USE_FLOAT_BOUNDINGSPHERE

View File

@@ -18,7 +18,6 @@
#include <osg/GLExtensions> #include <osg/GLExtensions>
#include <osg/Texture1D> #include <osg/Texture1D>
#include <osg/Texture2D> #include <osg/Texture2D>
#include <osg/Texture2DMultisample>
#include <osg/Texture3D> #include <osg/Texture3D>
#include <osg/Texture2DArray> #include <osg/Texture2DArray>
#include <osg/TextureCubeMap> #include <osg/TextureCubeMap>
@@ -302,8 +301,7 @@ struct FrameBufferAttachment::Pimpl
TEXTURE3D, TEXTURE3D,
TEXTURECUBE, TEXTURECUBE,
TEXTURERECT, TEXTURERECT,
TEXTURE2DARRAY, TEXTURE2DARRAY
TEXTURE2DMULTISAMPLE
}; };
TargetType targetType; TargetType targetType;
@@ -360,12 +358,6 @@ FrameBufferAttachment::FrameBufferAttachment(Texture2D* target, int level)
_ximpl->textureTarget = target; _ximpl->textureTarget = target;
} }
FrameBufferAttachment::FrameBufferAttachment(Texture2DMultisample* target, int level)
{
_ximpl = new Pimpl(Pimpl::TEXTURE2DMULTISAMPLE, level);
_ximpl->textureTarget = target;
}
FrameBufferAttachment::FrameBufferAttachment(Texture3D* target, int zoffset, int level) FrameBufferAttachment::FrameBufferAttachment(Texture3D* target, int zoffset, int level)
{ {
_ximpl = new Pimpl(Pimpl::TEXTURE3D, level); _ximpl = new Pimpl(Pimpl::TEXTURE3D, level);
@@ -415,14 +407,6 @@ FrameBufferAttachment::FrameBufferAttachment(Camera::Attachment& attachment)
return; return;
} }
osg::Texture2DMultisample* texture2DMS = dynamic_cast<osg::Texture2DMultisample*>(texture);
if (texture2DMS)
{
_ximpl = new Pimpl(Pimpl::TEXTURE2DMULTISAMPLE, attachment._level);
_ximpl->textureTarget = texture2DMS;
return;
}
osg::Texture3D* texture3D = dynamic_cast<osg::Texture3D*>(texture); osg::Texture3D* texture3D = dynamic_cast<osg::Texture3D*>(texture);
if (texture3D) if (texture3D)
{ {
@@ -564,9 +548,6 @@ void FrameBufferAttachment::attach(State &state, GLenum target, GLenum attachmen
case Pimpl::TEXTURE2D: case Pimpl::TEXTURE2D:
ext->glFramebufferTexture2DEXT(target, attachment_point, GL_TEXTURE_2D, tobj->_id, _ximpl->level); ext->glFramebufferTexture2DEXT(target, attachment_point, GL_TEXTURE_2D, tobj->_id, _ximpl->level);
break; break;
case Pimpl::TEXTURE2DMULTISAMPLE:
ext->glFramebufferTexture2DEXT(target, attachment_point, GL_TEXTURE_2D_MULTISAMPLE, tobj->_id, _ximpl->level);
break;
case Pimpl::TEXTURE3D: case Pimpl::TEXTURE3D:
ext->glFramebufferTexture3DEXT(target, attachment_point, GL_TEXTURE_3D, tobj->_id, _ximpl->level, _ximpl->zoffset); ext->glFramebufferTexture3DEXT(target, attachment_point, GL_TEXTURE_3D, tobj->_id, _ximpl->level, _ximpl->zoffset);
break; break;

View File

@@ -31,7 +31,6 @@
#include <map> #include <map>
#include <sstream> #include <sstream>
#include <algorithm> #include <algorithm>
#include <iterator>
using namespace osg; using namespace osg;

View File

@@ -11,148 +11,34 @@
* OpenSceneGraph Public License for more details. * OpenSceneGraph Public License for more details.
*/ */
#include <osg/Notify> #include <osg/Notify>
#include <osg/ApplicationUsage>
#include <osg/ref_ptr>
#include <string> #include <string>
#include <stdlib.h> #include <stdlib.h>
#include <stdio.h>
#include <sstream>
#include <iostream> #include <iostream>
#include <fstream>
#include <ctype.h> using namespace std;
namespace osg osg::NotifySeverity g_NotifyLevel = osg::NOTICE;
{
class NullStreamBuffer : public std::streambuf
{
private:
std::streamsize xsputn(const std::streambuf::char_type *str, std::streamsize n)
{
return n;
}
};
struct NullStream : public std::ostream
{
public:
NullStream():
std::ostream(new NullStreamBuffer)
{ _buffer = dynamic_cast<NullStreamBuffer *>(rdbuf()); }
~NullStream()
{
rdbuf(0);
delete _buffer;
}
protected:
NullStreamBuffer* _buffer;
};
/** Stream buffer calling notify handler when buffer is synchronized (usually on std::endl).
* Stream stores last notification severity to pass it to handler call.
*/
struct NotifyStreamBuffer : public std::stringbuf
{
NotifyStreamBuffer() : _severity(osg::NOTICE)
{
}
void setNotifyHandler(osg::NotifyHandler *handler) { _handler = handler; }
osg::NotifyHandler *getNotifyHandler() const { return _handler.get(); }
/** Sets severity for next call of notify handler */
void setCurrentSeverity(osg::NotifySeverity severity) { _severity = severity; }
osg::NotifySeverity getCurrentSeverity() const { return _severity; }
private:
int sync()
{
sputc(0); // string termination
if (_handler.valid())
_handler->notify(_severity, pbase());
pubseekpos(0, std::ios_base::out); // or str(std::string())
return 0;
}
osg::ref_ptr<osg::NotifyHandler> _handler;
osg::NotifySeverity _severity;
};
struct NotifyStream : public std::ostream
{
public:
NotifyStream():
std::ostream(new NotifyStreamBuffer)
{ _buffer = dynamic_cast<NotifyStreamBuffer *>(rdbuf()); }
void setCurrentSeverity(osg::NotifySeverity severity)
{
_buffer->setCurrentSeverity(severity);
}
osg::NotifySeverity getCurrentSeverity() const
{
return _buffer->getCurrentSeverity();
}
~NotifyStream()
{
rdbuf(0);
delete _buffer;
}
protected:
NotifyStreamBuffer* _buffer;
};
}
using namespace osg;
static osg::ApplicationUsageProxy Notify_e0(osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE, "OSG_NOTIFY_LEVEL <mode>", "FATAL | WARN | NOTICE | DEBUG_INFO | DEBUG_FP | DEBUG | INFO | ALWAYS");
static bool s_NeedNotifyInit = true;
static osg::NotifySeverity g_NotifyLevel = osg::NOTICE;
static osg::NullStream *g_NullStream;
static osg::NotifyStream *g_NotifyStream;
void osg::setNotifyLevel(osg::NotifySeverity severity) void osg::setNotifyLevel(osg::NotifySeverity severity)
{ {
if (s_NeedNotifyInit) osg::initNotifyLevel(); osg::initNotifyLevel();
g_NotifyLevel = severity; g_NotifyLevel = severity;
} }
osg::NotifySeverity osg::getNotifyLevel() osg::NotifySeverity osg::getNotifyLevel()
{ {
if (s_NeedNotifyInit) osg::initNotifyLevel(); osg::initNotifyLevel();
return g_NotifyLevel; return g_NotifyLevel;
} }
void osg::setNotifyHandler(osg::NotifyHandler *handler)
{
osg::NotifyStreamBuffer *buffer = static_cast<osg::NotifyStreamBuffer *>(g_NotifyStream->rdbuf());
if (buffer)
buffer->setNotifyHandler(handler);
}
osg::NotifyHandler* osg::getNotifyHandler()
{
if (s_NeedNotifyInit) osg::initNotifyLevel();
osg::NotifyStreamBuffer *buffer = static_cast<osg::NotifyStreamBuffer *>(g_NotifyStream->rdbuf());
return buffer ? buffer->getNotifyHandler() : 0;
}
bool osg::initNotifyLevel() bool osg::initNotifyLevel()
{ {
static osg::NullStream s_NullStream; static bool s_NotifyInit = false;
static osg::NotifyStream s_NotifyStream;
g_NullStream = &s_NullStream; if (s_NotifyInit) return true;
g_NotifyStream = &s_NotifyStream;
// g_NotifyLevel // g_NotifyLevel
// ============= // =============
@@ -186,59 +72,56 @@ bool osg::initNotifyLevel()
} }
// Setup standard notify handler s_NotifyInit = true;
osg::NotifyStreamBuffer *buffer = dynamic_cast<osg::NotifyStreamBuffer *>(g_NotifyStream->rdbuf());
if (buffer && !buffer->getNotifyHandler())
buffer->setNotifyHandler(new StandardNotifyHandler);
s_NeedNotifyInit = false;
return true; return true;
} }
#ifndef OSG_NOTIFY_DISABLED
bool osg::isNotifyEnabled( osg::NotifySeverity severity ) bool osg::isNotifyEnabled( osg::NotifySeverity severity )
{ {
if (s_NeedNotifyInit) osg::initNotifyLevel();
return severity<=g_NotifyLevel; return severity<=g_NotifyLevel;
} }
#endif
class NullStreamBuffer : public std::streambuf
{
private:
virtual streamsize xsputn (const char_type*, streamsize n)
{
return n;
}
};
struct NullStream : public std::ostream
{
NullStream():
std::ostream(new NullStreamBuffer) {}
virtual ~NullStream()
{
delete rdbuf();
rdbuf(0);
}
};
std::ostream& osg::notify(const osg::NotifySeverity severity) std::ostream& osg::notify(const osg::NotifySeverity severity)
{ {
if (s_NeedNotifyInit) osg::initNotifyLevel(); // set up global notify null stream for inline notify
static NullStream s_NotifyNulStream;
if (osg::isNotifyEnabled(severity)) static bool initialized = false;
if (!initialized)
{ {
g_NotifyStream->setCurrentSeverity(severity); std::cerr<<""; // dummy op to force construction of cerr, before a reference is passed back to calling code.
return *g_NotifyStream; std::cout<<""; // dummy op to force construction of cout, before a reference is passed back to calling code.
initialized = osg::initNotifyLevel();
} }
return *g_NullStream;
if (severity<=g_NotifyLevel)
{
if (severity<=osg::WARN) return std::cerr;
else return std::cout;
}
return s_NotifyNulStream;
} }
void osg::StandardNotifyHandler::notify(osg::NotifySeverity severity, const char *message)
{
#if 1
if (severity <= osg::WARN)
fputs(message, stderr);
else
fputs(message, stdout);
#else
fputs(message, stdout);
#endif
}
#if defined(WIN32) && !defined(__CYGWIN__)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
void osg::WinDebugNotifyHandler::notify(osg::NotifySeverity severity, const char *message)
{
OutputDebugStringA(message);
}
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -394,7 +394,7 @@ bool Program::getGlProgramInfoLog(unsigned int contextID, std::string& log) cons
return getPCP( contextID )->getInfoLog( log ); return getPCP( contextID )->getInfoLog( log );
} }
const Program::ActiveUniformMap& Program::getActiveUniforms(unsigned int contextID) const const Program::ActiveVarInfoMap& Program::getActiveUniforms(unsigned int contextID) const
{ {
return getPCP( contextID )->getActiveUniforms(); return getPCP( contextID )->getActiveUniforms();
} }
@@ -532,9 +532,10 @@ void Program::PerContextProgram::linkProgram()
if( loc != -1 ) if( loc != -1 )
{ {
_uniformInfoMap[Uniform::getNameID(reinterpret_cast<const char*>(name))] = ActiveVarInfo(loc,type,size); _uniformInfoMap[name] = ActiveVarInfo(loc,type,size);
OSG_INFO << "\tUniform \"" << name << "\"" osg::notify(osg::INFO)
<< "\tUniform \"" << name << "\""
<< " loc="<< loc << " loc="<< loc
<< " size="<< size << " size="<< size
<< " type=" << Uniform::getTypename((Uniform::Type)type) << " type=" << Uniform::getTypename((Uniform::Type)type)

View File

@@ -1562,6 +1562,70 @@ void Texture::setExtensions(unsigned int contextID,Extensions* extensions)
} }
Texture::Extensions::Extensions(unsigned int contextID) Texture::Extensions::Extensions(unsigned int contextID)
{
setupGLExtensions(contextID);
}
Texture::Extensions::Extensions(const Extensions& rhs):
Referenced()
{
_isMultiTexturingSupported = rhs._isMultiTexturingSupported;
_isTextureFilterAnisotropicSupported = rhs._isTextureFilterAnisotropicSupported;
_isTextureCompressionARBSupported = rhs._isTextureCompressionARBSupported;
_isTextureCompressionS3TCSupported = rhs._isTextureCompressionS3TCSupported;
_isTextureMirroredRepeatSupported = rhs._isTextureMirroredRepeatSupported;
_isTextureEdgeClampSupported = rhs._isTextureEdgeClampSupported;
_isTextureBorderClampSupported = rhs._isTextureBorderClampSupported;
_isGenerateMipMapSupported = rhs._isGenerateMipMapSupported;
_maxTextureSize = rhs._maxTextureSize;
_glCompressedTexImage2D = rhs._glCompressedTexImage2D;
_isShadowSupported = rhs._isShadowSupported;
_isShadowAmbientSupported = rhs._isShadowAmbientSupported;
_isClientStorageSupported = rhs._isClientStorageSupported;
_isNonPowerOfTwoTextureMipMappedSupported = rhs._isNonPowerOfTwoTextureMipMappedSupported;
_isNonPowerOfTwoTextureNonMipMappedSupported = rhs._isNonPowerOfTwoTextureNonMipMappedSupported;
_isTextureIntegerEXTSupported = rhs._isTextureIntegerEXTSupported;
}
void Texture::Extensions::lowestCommonDenominator(const Extensions& rhs)
{
if (!rhs._isMultiTexturingSupported) _isMultiTexturingSupported = false;
if (!rhs._isTextureFilterAnisotropicSupported) _isTextureFilterAnisotropicSupported = false;
if (!rhs._isTextureMirroredRepeatSupported) _isTextureMirroredRepeatSupported = false;
if (!rhs._isTextureEdgeClampSupported) _isTextureEdgeClampSupported = false;
if (!rhs._isTextureBorderClampSupported) _isTextureBorderClampSupported = false;
if (!rhs._isTextureCompressionARBSupported) _isTextureCompressionARBSupported = false;
if (!rhs._isTextureCompressionS3TCSupported) _isTextureCompressionS3TCSupported = false;
if (!rhs._isGenerateMipMapSupported) _isGenerateMipMapSupported = false;
if (rhs._maxTextureSize<_maxTextureSize) _maxTextureSize = rhs._maxTextureSize;
if (rhs._numTextureUnits<_numTextureUnits) _numTextureUnits = rhs._numTextureUnits;
if (!rhs._glCompressedTexImage2D) _glCompressedTexImage2D = 0;
if (!rhs._glCompressedTexSubImage2D) _glCompressedTexSubImage2D = 0;
if (!rhs._glGetCompressedTexImage) _glGetCompressedTexImage = 0;
if (!rhs._isShadowSupported) _isShadowSupported = false;
if (!rhs._isShadowAmbientSupported) _isShadowAmbientSupported = false;
if (!rhs._isClientStorageSupported) _isClientStorageSupported = false;
if (!rhs._isNonPowerOfTwoTextureMipMappedSupported) _isNonPowerOfTwoTextureMipMappedSupported = false;
if (!rhs._isNonPowerOfTwoTextureNonMipMappedSupported) _isNonPowerOfTwoTextureNonMipMappedSupported = false;
if (!rhs._isTextureIntegerEXTSupported) _isTextureIntegerEXTSupported = false;
}
void Texture::Extensions::setupGLExtensions(unsigned int contextID)
{ {
const char* version = (const char*) glGetString( GL_VERSION ); const char* version = (const char*) glGetString( GL_VERSION );
if (!version) if (!version)
@@ -1591,8 +1655,6 @@ Texture::Extensions::Extensions(unsigned int contextID)
_isTextureBorderClampSupported = isGLExtensionOrVersionSupported(contextID,"GL_ARB_texture_border_clamp", 1.3f); _isTextureBorderClampSupported = isGLExtensionOrVersionSupported(contextID,"GL_ARB_texture_border_clamp", 1.3f);
_isGenerateMipMapSupported = isGLExtensionOrVersionSupported(contextID,"GL_SGIS_generate_mipmap", 1.4f); _isGenerateMipMapSupported = isGLExtensionOrVersionSupported(contextID,"GL_SGIS_generate_mipmap", 1.4f);
_isTextureMultisampledSupported = isGLExtensionSupported(contextID,"GL_ARB_texture_multisample");
_isShadowSupported = isGLExtensionSupported(contextID,"GL_ARB_shadow"); _isShadowSupported = isGLExtensionSupported(contextID,"GL_ARB_shadow");
@@ -1644,12 +1706,73 @@ Texture::Extensions::Extensions(unsigned int contextID)
setGLExtensionFuncPtr(_glCompressedTexImage2D,"glCompressedTexImage2D","glCompressedTexImage2DARB"); setGLExtensionFuncPtr(_glCompressedTexImage2D,"glCompressedTexImage2D","glCompressedTexImage2DARB");
setGLExtensionFuncPtr(_glCompressedTexSubImage2D,"glCompressedTexSubImage2D","glCompressedTexSubImage2DARB"); setGLExtensionFuncPtr(_glCompressedTexSubImage2D,"glCompressedTexSubImage2D","glCompressedTexSubImage2DARB");
setGLExtensionFuncPtr(_glGetCompressedTexImage,"glGetCompressedTexImage","glGetCompressedTexImageARB");; setGLExtensionFuncPtr(_glGetCompressedTexImage,"glGetCompressedTexImage","glGetCompressedTexImageARB");;
setGLExtensionFuncPtr(_glTexImage2DMultisample, "glTexImage2DMultisample", "glTexImage2DMultisampleARB");
setGLExtensionFuncPtr(_glTexParameterIiv, "glTexParameterIiv", "glTexParameterIivARB"); setGLExtensionFuncPtr(_glTexParameterIiv, "glTexParameterIiv", "glTexParameterIivARB");
setGLExtensionFuncPtr(_glTexParameterIuiv, "glTexParameterIuiv", "glTexParameterIuivARB"); setGLExtensionFuncPtr(_glTexParameterIuiv, "glTexParameterIuiv", "glTexParameterIuivARB");
if (_glTexParameterIiv == NULL) setGLExtensionFuncPtr(_glTexParameterIiv, "glTexParameterIivEXT"); if (_glTexParameterIiv == NULL) setGLExtensionFuncPtr(_glTexParameterIiv, "glTexParameterIivEXT");
if (_glTexParameterIuiv == NULL) setGLExtensionFuncPtr(_glTexParameterIuiv, "glTexParameterIuivEXT"); if (_glTexParameterIuiv == NULL) setGLExtensionFuncPtr(_glTexParameterIuiv, "glTexParameterIuivEXT");
} }
void Texture::Extensions::glTexParameterIiv(GLenum target, GLenum pname, const GLint* data) const
{
if (_glTexParameterIiv)
{
_glTexParameterIiv(target, pname, data);
}
else
{
notify(WARN)<<"Error: glTexParameterIiv not supported by OpenGL driver"<<std::endl;
}
}
void Texture::Extensions::glTexParameterIuiv(GLenum target, GLenum pname, const GLuint* data) const
{
if (_glTexParameterIuiv)
{
_glTexParameterIuiv(target, pname, data);
}
else
{
notify(WARN)<<"Error: glTexParameterIuiv not supported by OpenGL driver"<<std::endl;
}
}
void Texture::Extensions::glCompressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data) const
{
if (_glCompressedTexImage2D)
{
_glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data);
}
else
{
notify(WARN)<<"Error: glCompressedTexImage2D not supported by OpenGL driver"<<std::endl;
}
}
void Texture::Extensions::glCompressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data) const
{
if (_glCompressedTexSubImage2D)
{
_glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data);
}
else
{
notify(WARN)<<"Error: glCompressedTexImage2D not supported by OpenGL driver"<<std::endl;
}
}
void Texture::Extensions::glGetCompressedTexImage(GLenum target, GLint level, GLvoid *data) const
{
if (_glGetCompressedTexImage)
{
_glGetCompressedTexImage(target, level, data);
}
else
{
notify(WARN)<<"Error: glGetCompressedTexImage not supported by OpenGL driver"<<std::endl;
}
}

View File

@@ -1,143 +0,0 @@
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*
* Texture2DMultisample codes Copyright (C) 2010 Marcin Hajder
* Thanks to to my company http://www.ai.com.pl for allowing me free this work.
*/
#include <osg/GLExtensions>
#include <osg/Texture2DMultisample>
#include <osg/State>
#include <osg/Notify>
using namespace osg;
Texture2DMultisample::Texture2DMultisample():
_textureWidth(0),
_textureHeight(0),
_numSamples(1),
_fixedsamplelocations(GL_FALSE)
{
}
Texture2DMultisample::Texture2DMultisample(GLsizei numSamples, GLboolean fixedsamplelocations):
_textureWidth(0),
_textureHeight(0),
_numSamples(numSamples),
_fixedsamplelocations(fixedsamplelocations)
{
}
Texture2DMultisample::Texture2DMultisample(const Texture2DMultisample& text,const CopyOp& copyop):
Texture(text,copyop),
_textureWidth(text._textureWidth),
_textureHeight(text._textureHeight),
_numSamples(text._numSamples),
_fixedsamplelocations(text._fixedsamplelocations)
{
}
Texture2DMultisample::~Texture2DMultisample()
{
}
int Texture2DMultisample::compare(const StateAttribute& sa) const
{
// check the types are equal and then create the rhs variable
// used by the COMPARE_StateAttribute_Parameter macro's below.
COMPARE_StateAttribute_Types(Texture2DMultisample,sa)
int result = compareTexture(rhs);
if (result!=0) return result;
// compare each parameter in turn against the rhs.
if (_textureWidth != 0 && rhs._textureWidth != 0)
{
COMPARE_StateAttribute_Parameter(_textureWidth)
}
if (_textureHeight != 0 && rhs._textureHeight != 0)
{
COMPARE_StateAttribute_Parameter(_textureHeight)
}
if (_numSamples != 0 && rhs._numSamples != 0)
{
COMPARE_StateAttribute_Parameter(_numSamples)
}
if (_fixedsamplelocations != 0 && rhs._fixedsamplelocations != 0)
{
COMPARE_StateAttribute_Parameter(_fixedsamplelocations)
}
return 0; // passed all the above comparison macro's, must be equal.
}
void Texture2DMultisample::apply(State& state) const
{
// current OpenGL context.
const unsigned int contextID = state.getContextID();
const Extensions* extensions = getExtensions(contextID,true);
if (!extensions->isTextureMultisampledSupported())
{
OSG_INFO<<"Texture2DMultisample not supoorted."<<std::endl;
return;
}
// No TextureObjectManager in 2.8.x, x <= 5
#if 0
Texture::TextureObjectManager* tom = Texture::getTextureObjectManager(contextID).get();
ElapsedTime elapsedTime(&(tom->getApplyTime()));
tom->getNumberApplied()++;
#endif
// get the texture object for the current contextID.
TextureObject* textureObject = getTextureObject(contextID);
if (textureObject)
{
textureObject->bind();
}
else if ( (_textureWidth!=0) && (_textureHeight!=0) && (_numSamples!=0) )
{
_textureObjectBuffer[contextID] = textureObject =
generateTextureObject( // this, // added to 2.9.x, not part of 2.8.x
contextID,
getTextureTarget(),
1,
_internalFormat,
_textureWidth,
_textureHeight,
1,
_borderWidth);
textureObject->bind();
extensions->glTexImage2DMultisample( getTextureTarget(),
_numSamples,
_internalFormat,
_textureWidth,
_textureHeight,
_fixedsamplelocations );
}
else
{
glBindTexture( getTextureTarget(), 0 );
}
}
void Texture2DMultisample::computeInternalFormat() const
{
computeInternalFormatType();
}

View File

@@ -21,7 +21,6 @@
#include <osg/Program> #include <osg/Program>
#include <osg/StateSet> #include <osg/StateSet>
#include <limits.h>
#include <algorithm> #include <algorithm>
using namespace osg; using namespace osg;
@@ -31,13 +30,13 @@ using namespace osg;
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
Uniform::Uniform() : Uniform::Uniform() :
_type(UNDEFINED), _numElements(0), _nameID(UINT_MAX), _modifiedCount(0) _type(UNDEFINED), _numElements(0), _modifiedCount(0)
{ {
} }
Uniform::Uniform( Type type, const std::string& name, int numElements ) : Uniform::Uniform( Type type, const std::string& name, int numElements ) :
_type(type), _numElements(0), _nameID(UINT_MAX), _modifiedCount(0) _type(type), _numElements(0), _modifiedCount(0)
{ {
setName(name); setName(name);
setNumElements(numElements); setNumElements(numElements);
@@ -88,8 +87,7 @@ void Uniform::setName( const std::string& name )
osg::notify(osg::WARN) << "cannot change Uniform name" << std::endl; osg::notify(osg::WARN) << "cannot change Uniform name" << std::endl;
return; return;
} }
Object::setName(name); _name = name;
_nameID = getNameID(_name);
} }
void Uniform::setNumElements( unsigned int numElements ) void Uniform::setNumElements( unsigned int numElements )
@@ -257,7 +255,6 @@ void Uniform::copyData(const Uniform& rhs)
{ {
// caller must ensure that _type==rhs._type // caller must ensure that _type==rhs._type
_numElements = rhs._numElements; _numElements = rhs._numElements;
_nameID = rhs._nameID;
if (rhs._floatArray.valid() || rhs._intArray.valid() || rhs._uintArray.valid()) allocateDataArray(); if (rhs._floatArray.valid() || rhs._intArray.valid() || rhs._uintArray.valid()) allocateDataArray();
if( _floatArray.valid() && rhs._floatArray.valid() ) *_floatArray = *rhs._floatArray; if( _floatArray.valid() && rhs._floatArray.valid() ) *_floatArray = *rhs._floatArray;
if( _intArray.valid() && rhs._intArray.valid() ) *_intArray = *rhs._intArray; if( _intArray.valid() && rhs._intArray.valid() ) *_intArray = *rhs._intArray;
@@ -605,24 +602,6 @@ GLenum Uniform::getInternalArrayType( Type t )
} }
unsigned int Uniform::getNameID(const std::string& name)
{
typedef std::map<std::string, unsigned int> UniformNameIDMap;
static OpenThreads::Mutex s_mutex_uniformNameIDMap;
static UniformNameIDMap s_uniformNameIDMap;
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(s_mutex_uniformNameIDMap);
UniformNameIDMap::iterator it = s_uniformNameIDMap.find(name);
if (it != s_uniformNameIDMap.end())
{
return it->second;
}
unsigned int id = s_uniformNameIDMap.size();
s_uniformNameIDMap.insert(UniformNameIDMap::value_type(name, id));
return id;
}
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
// value constructors for single-element (ie: non-array) uniforms // value constructors for single-element (ie: non-array) uniforms
@@ -1410,11 +1389,6 @@ bool Uniform::getElement( unsigned int index, bool& b0, bool& b1, bool& b2, bool
return true; return true;
} }
unsigned int Uniform::getNameID() const
{
return _nameID;
}
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
void Uniform::apply(const GL2Extensions* ext, GLint location) const void Uniform::apply(const GL2Extensions* ext, GLint location) const

View File

@@ -110,7 +110,7 @@ LINK_INTERNAL(${LIB_NAME}
osg osg
OpenThreads OpenThreads
) )
LINK_EXTERNAL(${LIB_NAME} ${OSGDB_PLATFORM_SPECIFIC_LIBRARIES} ${DL_LIBRARY}) LINK_EXTERNAL(${LIB_NAME} ${OSGDB_PLATFORM_SPECIFIC_LIBRARIES} )
LINK_CORELIB_DEFAULT(${LIB_NAME}) LINK_CORELIB_DEFAULT(${LIB_NAME})
INCLUDE(ModuleInstall OPTIONAL) INCLUDE(ModuleInstall OPTIONAL)

View File

@@ -29,7 +29,6 @@
#include <algorithm> #include <algorithm>
#include <functional> #include <functional>
#include <set> #include <set>
#include <iterator>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>

View File

@@ -48,7 +48,6 @@ void Output::init()
_numIndicesPerLine = 10; _numIndicesPerLine = 10;
_pathNameHint = AS_IS; _pathNameHint = AS_IS;
_outputRelativeTextures = false;
_outputTextureFiles = false; _outputTextureFiles = false;
_textureFileNameNumber = 0; _textureFileNameNumber = 0;

View File

@@ -8,8 +8,6 @@
#include <osg/TexEnv> #include <osg/TexEnv>
#include <osg/ref_ptr> #include <osg/ref_ptr>
#include <osg/MatrixTransform> #include <osg/MatrixTransform>
#include <osg/BlendFunc>
#include <osg/TexEnvCombine>
#include <osgDB/Registry> #include <osgDB/Registry>
#include <osgDB/FileUtils> #include <osgDB/FileUtils>
@@ -184,29 +182,18 @@ protected:
bool createFileObject(const osg::Node& node, Lib3dsFile * file3ds,const std::string& fileName, const osgDB::ReaderWriter::Options* options) const; bool createFileObject(const osg::Node& node, Lib3dsFile * file3ds,const std::string& fileName, const osgDB::ReaderWriter::Options* options) const;
/// An OSG state set with the original 3DS material attached (used to get info such as UV scaling & offset)
struct StateSetInfo
{
StateSetInfo(osg::StateSet * stateset=NULL, Lib3dsMaterial * lib3dsmat=NULL) : stateset(stateset), lib3dsmat(lib3dsmat) {}
StateSetInfo(const StateSetInfo & v) : stateset(v.stateset), lib3dsmat(v.lib3dsmat) {}
StateSetInfo & operator=(const StateSetInfo & v) { stateset=v.stateset; lib3dsmat=v.lib3dsmat; return *this; }
osg::StateSet * stateset;
Lib3dsMaterial * lib3dsmat;
};
class ReaderObject class ReaderObject
{ {
public: public:
ReaderObject(const osgDB::ReaderWriter::Options* options); ReaderObject(const osgDB::ReaderWriter::Options* options);
typedef std::vector<StateSetInfo> StateSetMap; typedef std::vector<osg::StateSet*> StateSetMap;
typedef std::vector<int> FaceList; typedef std::vector<int> FaceList;
typedef std::map<std::string,osg::StateSet*> GeoStateMap; typedef std::map<std::string,osg::StateSet*> GeoStateMap;
osg::Texture2D* createTexture(Lib3dsTextureMap *texture,const char* label,bool& transparancy); osg::Texture2D* createTexture(Lib3dsTextureMap *texture,const char* label,bool& transparancy);
StateSetInfo createStateSet(Lib3dsMaterial *materials); osg::StateSet* createStateSet(Lib3dsMaterial *materials);
osg::Drawable* createDrawable(Lib3dsMesh *meshes,FaceList& faceList, const osg::Matrix * matrix, StateSetInfo & ssi); osg::Drawable* createDrawable(Lib3dsMesh *meshes,FaceList& faceList, const osg::Matrix * matrix);
std::string _directory; std::string _directory;
bool _useSmoothingGroups; bool _useSmoothingGroups;
@@ -214,18 +201,15 @@ protected:
// MIKEC // MIKEC
osg::Node* processMesh(StateSetMap& drawStateMap,osg::Group* parent,Lib3dsMesh* mesh, const osg::Matrix * matrix); osg::Node* processMesh(StateSetMap& drawStateMap,osg::Group* parent,Lib3dsMesh* mesh, const osg::Matrix * matrix);
osg::Node* processNode(StateSetMap& drawStateMap,Lib3dsFile *f,Lib3dsNode *node); osg::Node* processNode(StateSetMap drawStateMap,Lib3dsFile *f,Lib3dsNode *node);
private: private:
const osgDB::ReaderWriter::Options* options; const osgDB::ReaderWriter::Options* options;
bool noMatrixTransforms; ///< Should the plugin apply matrices into the mesh vertices ("old behaviour"), instead of restoring matrices ("new behaviour")? bool noMatrixTransforms; ///< Should the plugin apply matrices into the mesh vertices ("old behaviour"), instead of restoring matrices ("new behaviour")?
bool checkForEspilonIdentityMatrices; bool checkForEspilonIdentityMatrices;
bool restoreMatrixTransformsNoMeshes; bool restoreMatrixTransformsNoMeshes;
typedef std::map<unsigned int,FaceList> SmoothingFaceMap; typedef std::map<unsigned int,FaceList> SmoothingFaceMap;
void addDrawableFromFace(osg::Geode * geode, FaceList & faceList, Lib3dsMesh * mesh, const osg::Matrix * matrix, StateSetInfo & ssi); void addDrawableFromFace(osg::Geode * geode, FaceList & faceList, Lib3dsMesh * mesh, const osg::Matrix * matrix, osg::StateSet * stateSet);
};
typedef std::map<std::string, osg::ref_ptr<osg::Texture2D> > TexturesMap; // Should be an unordered map (faster)
TexturesMap texturesMap;
};
}; };
// now register with Registry to instantiate the above // now register with Registry to instantiate the above
@@ -237,28 +221,29 @@ ReaderWriter3DS::ReaderWriter3DS()
supportsExtension("3ds","3D Studio model format"); supportsExtension("3ds","3D Studio model format");
//supportsOption("OutputTextureFiles","Write out the texture images to file"); //supportsOption("OutputTextureFiles","Write out the texture images to file");
//supportsOption("flipTexture", "flip texture upside-down"); //supportsOption("flipTexture", "flip texture upside-down");
supportsOption("extended3dsFilePaths", "(Write option) Keeps long texture filenames (not 8.3) when exporting 3DS, but can lead to compatibility problems."); supportsOption("extended3dsFilePaths", "Keeps long texture filenames (not 8.3) when exporting 3DS, but can lead to compatibility problems.");
supportsOption("noMatrixTransforms", "(Read option) Set the plugin to apply matrices into the mesh vertices (\"old behaviour\") instead of restoring them (\"new behaviour\"). You may use this option to avoid a few rounding errors."); supportsOption("noMatrixTransforms", "Set the plugin to apply matrices into the mesh vertices (\"old behaviour\") instead of restoring them (\"new behaviour\"). You may use this option to avoid a few rounding errors.");
supportsOption("checkForEspilonIdentityMatrices", "(Read option) If not set, then consider \"almost identity\" matrices to be identity ones (in case of rounding errors)."); supportsOption("checkForEspilonIdentityMatrices", "If not set, then consider \"almost identity\" matrices to be identity ones (in case of rounding errors).");
supportsOption("restoreMatrixTransformsNoMeshes", "(Read option) Makes an exception to the behaviour when 'noMatrixTransforms' is not set for mesh instances. When a mesh instance has a transform on it, the reader creates a MatrixTransform above the Geode. If you don't want the hierarchy to be modified, then you can use this option to merge the transform into vertices."); supportsOption("restoreMatrixTransformsNoMeshes", "Makes an exception to the behaviour when 'noMatrixTransforms' is not set for mesh instances. When a mesh instance has a transform on it, the reader creates a MatrixTransform above the Geode. If you don't want the hierarchy to be modified, then you can use this option to merge the transform into vertices.");
setByteOrder();
#if 0 #if 0
OSG_NOTICE<<"3DS reader sizes:"<<std::endl; osg::notify(osg::NOTICE)<<"3DS reader sizes:"<<std::endl;
OSG_NOTICE<<" sizeof(Lib3dsBool)="<<sizeof(Lib3dsBool)<<std::endl; osg::notify(osg::NOTICE)<<" sizeof(Lib3dsBool)="<<sizeof(Lib3dsBool)<<std::endl;
OSG_NOTICE<<" sizeof(Lib3dsByte)="<<sizeof(Lib3dsByte)<<std::endl; osg::notify(osg::NOTICE)<<" sizeof(Lib3dsByte)="<<sizeof(Lib3dsByte)<<std::endl;
OSG_NOTICE<<" sizeof(Lib3dsWord)="<<sizeof(Lib3dsWord)<<std::endl; osg::notify(osg::NOTICE)<<" sizeof(Lib3dsWord)="<<sizeof(Lib3dsWord)<<std::endl;
OSG_NOTICE<<" sizeof(Lib3dsDword)="<<sizeof(Lib3dsDword)<<std::endl; osg::notify(osg::NOTICE)<<" sizeof(Lib3dsDword)="<<sizeof(Lib3dsDword)<<std::endl;
OSG_NOTICE<<" sizeof(Lib3dsIntb)="<<sizeof(Lib3dsIntb)<<std::endl; osg::notify(osg::NOTICE)<<" sizeof(Lib3dsIntb)="<<sizeof(Lib3dsIntb)<<std::endl;
OSG_NOTICE<<" sizeof(Lib3dsIntw)="<<sizeof(Lib3dsIntw)<<std::endl; osg::notify(osg::NOTICE)<<" sizeof(Lib3dsIntw)="<<sizeof(Lib3dsIntw)<<std::endl;
OSG_NOTICE<<" sizeof(Lib3dsIntd)="<<sizeof(Lib3dsIntd)<<std::endl; osg::notify(osg::NOTICE)<<" sizeof(Lib3dsIntd)="<<sizeof(Lib3dsIntd)<<std::endl;
OSG_NOTICE<<" sizeof(Lib3dsFloat)="<<sizeof(Lib3dsFloat)<<std::endl; osg::notify(osg::NOTICE)<<" sizeof(Lib3dsFloat)="<<sizeof(Lib3dsFloat)<<std::endl;
OSG_NOTICE<<" sizeof(Lib3dsDouble)="<<sizeof(Lib3dsDouble)<<std::endl; osg::notify(osg::NOTICE)<<" sizeof(Lib3dsDouble)="<<sizeof(Lib3dsDouble)<<std::endl;
OSG_NOTICE<<" sizeof(Lib3dsVector)="<<sizeof(Lib3dsVector)<<std::endl; osg::notify(osg::NOTICE)<<" sizeof(Lib3dsVector)="<<sizeof(Lib3dsVector)<<std::endl;
OSG_NOTICE<<" sizeof(Lib3dsTexel)="<<sizeof(Lib3dsTexel)<<std::endl; osg::notify(osg::NOTICE)<<" sizeof(Lib3dsTexel)="<<sizeof(Lib3dsTexel)<<std::endl;
OSG_NOTICE<<" sizeof(Lib3dsQuat)="<<sizeof(Lib3dsQuat)<<std::endl; osg::notify(osg::NOTICE)<<" sizeof(Lib3dsQuat)="<<sizeof(Lib3dsQuat)<<std::endl;
OSG_NOTICE<<" sizeof(Lib3dsMatrix)="<<sizeof(Lib3dsMatrix)<<std::endl; osg::notify(osg::NOTICE)<<" sizeof(Lib3dsMatrix)="<<sizeof(Lib3dsMatrix)<<std::endl;
OSG_NOTICE<<" sizeof(Lib3dsRgb)="<<sizeof(Lib3dsRgb)<<std::endl; osg::notify(osg::NOTICE)<<" sizeof(Lib3dsRgb)="<<sizeof(Lib3dsRgb)<<std::endl;
OSG_NOTICE<<" sizeof(Lib3dsRgba)="<<sizeof(Lib3dsRgba)<<std::endl; osg::notify(osg::NOTICE)<<" sizeof(Lib3dsRgba)="<<sizeof(Lib3dsRgba)<<std::endl;
#endif #endif
} }
@@ -279,9 +264,9 @@ ReaderWriter3DS::ReaderObject::ReaderObject(const osgDB::ReaderWriter::Options*
{ {
if (opt == "noMatrixTransforms") if (opt == "noMatrixTransforms")
noMatrixTransforms = true; noMatrixTransforms = true;
else if (opt == "checkForEspilonIdentityMatrices") if (opt == "checkForEspilonIdentityMatrices")
checkForEspilonIdentityMatrices = true; checkForEspilonIdentityMatrices = true;
else if (opt == "restoreMatrixTransformsNoMeshes") if (opt == "restoreMatrixTransformsNoMeshes")
restoreMatrixTransformsNoMeshes = true; restoreMatrixTransformsNoMeshes = true;
} }
} }
@@ -379,7 +364,7 @@ void print(Lib3dsNode *node, int level)
void ReaderWriter3DS::ReaderObject::addDrawableFromFace(osg::Geode * geode, FaceList & faceList, void ReaderWriter3DS::ReaderObject::addDrawableFromFace(osg::Geode * geode, FaceList & faceList,
Lib3dsMesh * mesh, Lib3dsMesh * mesh,
const osg::Matrix * matrix, const osg::Matrix * matrix,
StateSetInfo & ssi) osg::StateSet * stateSet)
{ {
if (_useSmoothingGroups) if (_useSmoothingGroups)
{ {
@@ -399,22 +384,22 @@ void ReaderWriter3DS::ReaderObject::addDrawableFromFace(osg::Geode * geode, Face
// to ensure the vertices on adjacent groups // to ensure the vertices on adjacent groups
// don't get shared. // don't get shared.
FaceList& smoothFaceMap = sitr->second; FaceList& smoothFaceMap = sitr->second;
osg::ref_ptr<osg::Drawable> drawable = createDrawable(mesh,smoothFaceMap,matrix,ssi); osg::ref_ptr<osg::Drawable> drawable = createDrawable(mesh,smoothFaceMap,matrix);
if (drawable.valid()) if (drawable.valid())
{ {
if (ssi.stateset) if (stateSet)
drawable->setStateSet(ssi.stateset); drawable->setStateSet(stateSet);
geode->addDrawable(drawable.get()); geode->addDrawable(drawable.get());
} }
} }
} }
else // ignore smoothing groups. else // ignore smoothing groups.
{ {
osg::ref_ptr<osg::Drawable> drawable = createDrawable(mesh,faceList,matrix,ssi); osg::ref_ptr<osg::Drawable> drawable = createDrawable(mesh,faceList,matrix);
if (drawable.valid()) if (drawable.valid())
{ {
if (ssi.stateset) if (stateSet)
drawable->setStateSet(ssi.stateset); drawable->setStateSet(stateSet);
geode->addDrawable(drawable.get()); geode->addDrawable(drawable.get());
} }
} }
@@ -444,8 +429,8 @@ osg::Node* ReaderWriter3DS::ReaderObject::processMesh(StateSetMap& drawStateMap,
} }
if (materialFaceMap.empty() && defaultMaterialFaceList.empty()) if (materialFaceMap.empty() && defaultMaterialFaceList.empty())
{ {
OSG_NOTICE<<"Warning : no triangles assigned to mesh '"<<mesh->name<<"'"<< std::endl; osg::notify(osg::NOTICE)<<"Warning : no triangles assigned to mesh '"<<mesh->name<<"'"<< std::endl;
//OSG_INFO << "No material assigned to mesh '" << mesh->name << "'" << std::endl; //osg::notify(osg::INFO) << "No material assigned to mesh '" << mesh->name << "'" << std::endl;
return NULL; return NULL;
} }
else else
@@ -454,8 +439,7 @@ osg::Node* ReaderWriter3DS::ReaderObject::processMesh(StateSetMap& drawStateMap,
geode->setName(mesh->name); geode->setName(mesh->name);
if (!defaultMaterialFaceList.empty()) if (!defaultMaterialFaceList.empty())
{ {
StateSetInfo emptySSI; addDrawableFromFace(geode, defaultMaterialFaceList, mesh, matrix, NULL);
addDrawableFromFace(geode, defaultMaterialFaceList, mesh, matrix, emptySSI);
} }
for(unsigned int imat=0; imat<numMaterials; ++imat) for(unsigned int imat=0; imat<numMaterials; ++imat)
{ {
@@ -490,7 +474,7 @@ How to cope with pivot points in 3ds (short version)
Transform the node by the node matrix, which does the orientation about the pivot point, (and currently) transforms the object back by a translation to the PP. Transform the node by the node matrix, which does the orientation about the pivot point, (and currently) transforms the object back by a translation to the PP.
*/ */
osg::Node* ReaderWriter3DS::ReaderObject::processNode(StateSetMap& drawStateMap,Lib3dsFile *f,Lib3dsNode *node) osg::Node* ReaderWriter3DS::ReaderObject::processNode(StateSetMap drawStateMap,Lib3dsFile *f,Lib3dsNode *node)
{ {
// Get mesh // Get mesh
Lib3dsMeshInstanceNode * object = (node->type == LIB3DS_NODE_MESH_INSTANCE) ? reinterpret_cast<Lib3dsMeshInstanceNode *>(node) : NULL; Lib3dsMeshInstanceNode * object = (node->type == LIB3DS_NODE_MESH_INSTANCE) ? reinterpret_cast<Lib3dsMeshInstanceNode *>(node) : NULL;
@@ -499,14 +483,13 @@ osg::Node* ReaderWriter3DS::ReaderObject::processNode(StateSetMap& drawStateMap,
// Retreive LOCAL transform // Retreive LOCAL transform
static const osg::Matrix::value_type MATRIX_EPSILON = 1e-10; static const osg::Matrix::value_type MATRIX_EPSILON = 1e-10;
osg::Matrix osgWorldToNodeMatrix( copyLib3dsMatrixToOsgMatrix(node->matrix) ); osg::Matrix osgNodeMatrix( copyLib3dsMatrixToOsgMatrix(node->matrix) );
osg::Matrix osgWorldToParentNodeMatrix;
if (node->parent) if (node->parent)
{ {
// Matrices evaluated by lib3DS are multiplied by parents' ones // Matrices evaluated by lib3DS are multiplied by parents' ones
osgWorldToParentNodeMatrix = copyLib3dsMatrixToOsgMatrix(node->parent->matrix); osgNodeMatrix *= osg::Matrix::inverse( copyLib3dsMatrixToOsgMatrix(node->parent->matrix) );
} }
osg::Matrix osgNodeMatrix( osgWorldToNodeMatrix * osg::Matrix::inverse(osgWorldToParentNodeMatrix) );
// Test if we should create an intermediate Group (or MatrixTransform) and which matrix we should apply to the vertices // Test if we should create an intermediate Group (or MatrixTransform) and which matrix we should apply to the vertices
osg::Group* group = NULL; osg::Group* group = NULL;
@@ -518,20 +501,20 @@ osg::Node* ReaderWriter3DS::ReaderObject::processNode(StateSetMap& drawStateMap,
osg::Matrix meshMat; osg::Matrix meshMat;
if (mesh) if (mesh)
{ {
if (!noMatrixTransforms) if (!noMatrixTransforms)
{ {
// There can be a transform directly on a mesh instance (= as if a osg::MatrixTransform and a osg::Geode were merged together) in object->pos/rot/scl // There can be a transform directly on a mesh instance (= as if a osg::MatrixTransform and a osg::Geode were merged together) in object->pos/rot/scl
if (pivoted) { if (!pivoted) {
meshMat = osg::Matrix::inverse(copyLib3dsMatrixToOsgMatrix(mesh->matrix)) * osg::Matrix::translate(-pivot);
} else {
meshMat = osg::Matrix::inverse(copyLib3dsMatrixToOsgMatrix(mesh->matrix)); meshMat = osg::Matrix::inverse(copyLib3dsMatrixToOsgMatrix(mesh->matrix));
} else {
meshMat = osg::Matrix::inverse(copyLib3dsMatrixToOsgMatrix(mesh->matrix)) * osg::Matrix::translate(-pivot);
} }
} }
else { else {
if (pivoted) { if (pivoted) {
meshMat = osg::Matrix::inverse(copyLib3dsMatrixToOsgMatrix(mesh->matrix)) * osg::Matrix::translate(-pivot) * osgWorldToNodeMatrix; meshMat = osg::Matrix::inverse(copyLib3dsMatrixToOsgMatrix(mesh->matrix)) * osg::Matrix::translate(-pivot) * copyLib3dsMatrixToOsgMatrix(node->matrix);
} else { } else {
meshMat = osg::Matrix::inverse(copyLib3dsMatrixToOsgMatrix(mesh->matrix)) * osgWorldToNodeMatrix; // ==Identity when not pivoted? meshMat = osg::Matrix::inverse(copyLib3dsMatrixToOsgMatrix(mesh->matrix)) * copyLib3dsMatrixToOsgMatrix(node->matrix);
} }
osgNodeMatrix = osg::Matrix::identity(); // Not sure it's useful, but it's harmless ;) osgNodeMatrix = osg::Matrix::identity(); // Not sure it's useful, but it's harmless ;)
} }
@@ -564,8 +547,6 @@ osg::Node* ReaderWriter3DS::ReaderObject::processNode(StateSetMap& drawStateMap,
if (node->type == LIB3DS_NODE_MESH_INSTANCE) if (node->type == LIB3DS_NODE_MESH_INSTANCE)
group->setName(reinterpret_cast<Lib3dsMeshInstanceNode *>(node)->instance_name); group->setName(reinterpret_cast<Lib3dsMeshInstanceNode *>(node)->instance_name);
} }
else if (node->type == LIB3DS_NODE_MESH_INSTANCE && strlen(reinterpret_cast<Lib3dsMeshInstanceNode *>(node)->instance_name) != 0)
group->setName(reinterpret_cast<Lib3dsMeshInstanceNode *>(node)->instance_name);
else else
group->setName(node->name); group->setName(node->name);
@@ -670,7 +651,7 @@ static void fileio_log_func(void *self, Lib3dsLogLevel level, int indent, const
else if (level == LIB3DS_LOG_WARN) l = osg::NOTICE; else if (level == LIB3DS_LOG_WARN) l = osg::NOTICE;
else if (level == LIB3DS_LOG_INFO) l = osg::INFO; else if (level == LIB3DS_LOG_INFO) l = osg::INFO;
else if (level == LIB3DS_LOG_DEBUG) l = osg::DEBUG_INFO; else if (level == LIB3DS_LOG_DEBUG) l = osg::DEBUG_INFO;
OSG_NOTIFY(l) << msg << std::endl; osg::notify(l) << msg << std::endl;
} }
@@ -722,7 +703,7 @@ osgDB::ReaderWriter::ReadResult ReaderWriter3DS::readNode(const std::string& fil
// Do not use the lib3ds_file_open() as: // Do not use the lib3ds_file_open() as:
// 1. It relies on FILE* instead of iostreams (less safe) // 1. It relies on FILE* instead of iostreams (less safe)
// 2. It doesn't allow us to set a custom log output // 2. It doesn't allow us to set a custom log output
osgDB::ifstream fin(fileName.c_str(), std::ios_base::in | std::ios_base::binary); std::ifstream fin(fileName.c_str(), std::ios_base::in | std::ios_base::binary);
if (!fin.good()) return ReadResult::ERROR_IN_READING_FILE; if (!fin.good()) return ReadResult::ERROR_IN_READING_FILE;
return doReadNode(fin, options, fileName); return doReadNode(fin, options, fileName);
/* /*
@@ -758,7 +739,7 @@ osgDB::ReaderWriter::ReadResult ReaderWriter3DS::constructFrom3dsFile(Lib3dsFile
ReaderObject::StateSetMap drawStateMap; ReaderObject::StateSetMap drawStateMap;
unsigned int numMaterials = f->nmaterials; unsigned int numMaterials = f->nmaterials;
drawStateMap.insert(drawStateMap.begin(), numMaterials, StateSetInfo()); // Setup the map drawStateMap.insert(drawStateMap.begin(), numMaterials, NULL); // Setup the map
for (unsigned int imat=0; imat<numMaterials; ++imat) for (unsigned int imat=0; imat<numMaterials; ++imat)
{ {
Lib3dsMaterial * mat = f->materials[imat]; Lib3dsMaterial * mat = f->materials[imat];
@@ -788,7 +769,7 @@ osgDB::ReaderWriter::ReadResult ReaderWriter3DS::constructFrom3dsFile(Lib3dsFile
// Loading and re-exporting these files from 3DS produces a file with correct node structure, so perhaps these are not 100% conformant? // Loading and re-exporting these files from 3DS produces a file with correct node structure, so perhaps these are not 100% conformant?
if (f->nodes == NULL) if (f->nodes == NULL)
{ {
OSG_WARN<<"Warning: in 3ds loader: file has no nodes, traversing by meshes instead"<< std::endl; osg::notify(osg::WARN)<<"Warning: in 3ds loader: file has no nodes, traversing by meshes instead"<< std::endl;
traverse_nodes=true; traverse_nodes=true;
} }
@@ -822,8 +803,8 @@ osgDB::ReaderWriter::ReadResult ReaderWriter3DS::constructFrom3dsFile(Lib3dsFile
if (osg::getNotifyLevel()>=osg::INFO) if (osg::getNotifyLevel()>=osg::INFO)
{ {
OSG_INFO << "Final OSG node structure looks like this:"<< endl; osg::notify(osg::NOTICE) << "Final OSG node structure looks like this:"<< endl;
PrintVisitor pv(osg::notify(osg::INFO)); PrintVisitor pv(osg::notify(osg::NOTICE));
group->accept(pv); group->accept(pv);
} }
@@ -833,7 +814,7 @@ osgDB::ReaderWriter::ReadResult ReaderWriter3DS::constructFrom3dsFile(Lib3dsFile
/** /**
use matrix to pretransform geometry, or NULL to do nothing use matrix to pretransform geometry, or NULL to do nothing
*/ */
osg::Drawable* ReaderWriter3DS::ReaderObject::createDrawable(Lib3dsMesh *m,FaceList& faceList, const osg::Matrix * matrix, StateSetInfo & ssi) osg::Drawable* ReaderWriter3DS::ReaderObject::createDrawable(Lib3dsMesh *m,FaceList& faceList, const osg::Matrix * matrix)
{ {
osg::Geometry * geom = new osg::Geometry; osg::Geometry * geom = new osg::Geometry;
unsigned int i; unsigned int i;
@@ -888,24 +869,9 @@ osg::Drawable* ReaderWriter3DS::ReaderObject::createDrawable(Lib3dsMesh *m,FaceL
{ {
osg::ref_ptr<osg::Vec2Array> osg_tcoords = new osg::Vec2Array(noVertex); osg::ref_ptr<osg::Vec2Array> osg_tcoords = new osg::Vec2Array(noVertex);
geom->setTexCoordArray(0, osg_tcoords.get()); geom->setTexCoordArray(0, osg_tcoords.get());
// Texture 0 parameters (only one texture supported for now)
float scaleU(1.f), scaleV(1.f);
float offsetU(0.f), offsetV(0.f);
if (ssi.lib3dsmat && *(ssi.lib3dsmat->texture1_map.name)) // valid texture = name not empty
{
Lib3dsTextureMap & tex3ds = ssi.lib3dsmat->texture1_map;
scaleU = tex3ds.scale[0];
scaleV = tex3ds.scale[1];
offsetU = tex3ds.offset[0];
offsetV = tex3ds.offset[1];
if (tex3ds.rotation != 0) OSG_NOTICE << "3DS texture rotation not supported yet" << std::endl;
//TODO: tint_1, tint_2, tint_r, tint_g, tint_b
}
for (i=0; i<m->nvertices; ++i) for (i=0; i<m->nvertices; ++i)
{ {
if (orig2NewMapping[i]>=0) (*osg_tcoords)[orig2NewMapping[i]].set(m->texcos[i][0]*scaleU + offsetU, m->texcos[i][1]*scaleV + offsetV); if (orig2NewMapping[i]>=0) (*osg_tcoords)[orig2NewMapping[i]].set(m->texcos[i][0],m->texcos[i][1]);
} }
} }
@@ -992,26 +958,18 @@ osg::Drawable* ReaderWriter3DS::ReaderObject::createDrawable(Lib3dsMesh *m,FaceL
} }
osg::Texture2D* ReaderWriter3DS::ReaderObject::createTexture(Lib3dsTextureMap *texture,const char* label,bool& transparency) osg::Texture2D* ReaderWriter3DS::ReaderObject::createTexture(Lib3dsTextureMap *texture,const char* label,bool& transparancy)
{ {
if (texture && *(texture->name)) if (texture && *(texture->name))
{ {
OSG_INFO<<"texture->name="<<texture->name<<", _directory="<<_directory<<std::endl; osg::notify(osg::INFO)<<"texture->name="<<texture->name<<", _directory="<<_directory<<std::endl;
// First try already loaded textures.
TexturesMap::iterator itTex = texturesMap.find(texture->name);
if (itTex != texturesMap.end()) {
OSG_DEBUG << "Texture '" << texture->name << "' found in cache." << std::endl;
return itTex->second.get();
}
// Texture not in cache: locate and load.
std::string fileName = osgDB::findFileInDirectory(texture->name,_directory,osgDB::CASE_INSENSITIVE); std::string fileName = osgDB::findFileInDirectory(texture->name,_directory,osgDB::CASE_INSENSITIVE);
if (fileName.empty()) if (fileName.empty())
{ {
// file not found in .3ds file's directory, so we'll look in the datafile path list. // file not found in .3ds file's directory, so we'll look in the datafile path list.
fileName = osgDB::findDataFile(texture->name,options, osgDB::CASE_INSENSITIVE); fileName = osgDB::findDataFile(texture->name,options, osgDB::CASE_INSENSITIVE);
OSG_INFO<<"texture->name="<<texture->name<<", _directory="<<_directory<<std::endl; osg::notify(osg::INFO)<<"texture->name="<<texture->name<<", _directory="<<_directory<<std::endl;
} }
if (fileName.empty()) if (fileName.empty())
@@ -1023,30 +981,30 @@ osg::Texture2D* ReaderWriter3DS::ReaderObject::createTexture(Lib3dsTextureMap *
} }
else else
{ {
OSG_WARN << "texture '"<<texture->name<<"' not found"<< std::endl; osg::notify(osg::WARN) << "texture '"<<texture->name<<"' not found"<< std::endl;
return NULL; return NULL;
} }
} }
if (label) { OSG_DEBUG << label; } if (label) { osg::notify(osg::DEBUG_INFO) << label; }
else { OSG_DEBUG << "texture name"; } else { osg::notify(osg::DEBUG_INFO) << "texture name"; }
OSG_DEBUG << " '"<<texture->name<<"'"<< std::endl; osg::notify(osg::DEBUG_INFO) << " '"<<texture->name<<"'"<< std::endl;
OSG_DEBUG << " texture flag "<<texture->flags<< std::endl; osg::notify(osg::DEBUG_INFO) << " texture flag "<<texture->flags<< std::endl;
OSG_DEBUG << " LIB3DS_TEXTURE_DECALE "<<((texture->flags)&LIB3DS_TEXTURE_DECALE)<< std::endl; osg::notify(osg::DEBUG_INFO) << " LIB3DS_TEXTURE_DECALE "<<((texture->flags)&LIB3DS_TEXTURE_DECALE)<< std::endl;
OSG_DEBUG << " LIB3DS_TEXTURE_MIRROR "<<((texture->flags)&LIB3DS_TEXTURE_MIRROR)<< std::endl; osg::notify(osg::DEBUG_INFO) << " LIB3DS_TEXTURE_MIRROR "<<((texture->flags)&LIB3DS_TEXTURE_MIRROR)<< std::endl;
OSG_DEBUG << " LIB3DS_TEXTURE_NEGATE "<<((texture->flags)&LIB3DS_TEXTURE_NEGATE)<< std::endl; osg::notify(osg::DEBUG_INFO) << " LIB3DS_TEXTURE_NEGATE "<<((texture->flags)&LIB3DS_TEXTURE_NEGATE)<< std::endl;
OSG_DEBUG << " LIB3DS_TEXTURE_NO_TILE "<<((texture->flags)&LIB3DS_TEXTURE_NO_TILE)<< std::endl; osg::notify(osg::DEBUG_INFO) << " LIB3DS_TEXTURE_NO_TILE "<<((texture->flags)&LIB3DS_TEXTURE_NO_TILE)<< std::endl;
OSG_DEBUG << " LIB3DS_TEXTURE_SUMMED_AREA "<<((texture->flags)&LIB3DS_TEXTURE_SUMMED_AREA)<< std::endl; osg::notify(osg::DEBUG_INFO) << " LIB3DS_TEXTURE_SUMMED_AREA "<<((texture->flags)&LIB3DS_TEXTURE_SUMMED_AREA)<< std::endl;
OSG_DEBUG << " LIB3DS_TEXTURE_ALPHA_SOURCE "<<((texture->flags)&LIB3DS_TEXTURE_ALPHA_SOURCE)<< std::endl; osg::notify(osg::DEBUG_INFO) << " LIB3DS_TEXTURE_ALPHA_SOURCE "<<((texture->flags)&LIB3DS_TEXTURE_ALPHA_SOURCE)<< std::endl;
OSG_DEBUG << " LIB3DS_TEXTURE_TINT "<<((texture->flags)&LIB3DS_TEXTURE_TINT)<< std::endl; osg::notify(osg::DEBUG_INFO) << " LIB3DS_TEXTURE_TINT "<<((texture->flags)&LIB3DS_TEXTURE_TINT)<< std::endl;
OSG_DEBUG << " LIB3DS_TEXTURE_IGNORE_ALPHA "<<((texture->flags)&LIB3DS_TEXTURE_IGNORE_ALPHA)<< std::endl; osg::notify(osg::DEBUG_INFO) << " LIB3DS_TEXTURE_IGNORE_ALPHA "<<((texture->flags)&LIB3DS_TEXTURE_IGNORE_ALPHA)<< std::endl;
OSG_DEBUG << " LIB3DS_TEXTURE_RGB_TINT "<<((texture->flags)&LIB3DS_TEXTURE_RGB_TINT)<< std::endl; osg::notify(osg::DEBUG_INFO) << " LIB3DS_TEXTURE_RGB_TINT "<<((texture->flags)&LIB3DS_TEXTURE_RGB_TINT)<< std::endl;
osg::ref_ptr<osg::Image> osg_image = osgDB::readRefImageFile(fileName.c_str(), options); //Absolute Path osg::ref_ptr<osg::Image> osg_image = osgDB::readRefImageFile(fileName.c_str(), options); //Absolute Path
if (!osg_image.valid()) if (!osg_image.valid())
{ {
OSG_NOTICE << "Warning: Cannot create texture "<<texture->name<< std::endl; osg::notify(osg::NOTICE) << "Warning: Cannot create texture "<<texture->name<< std::endl;
return NULL; return NULL;
} }
if (osg_image->getFileName().empty()) // it should be done in OSG with osgDB::readRefImageFile(fileName.c_str()); if (osg_image->getFileName().empty()) // it should be done in OSG with osgDB::readRefImageFile(fileName.c_str());
@@ -1055,7 +1013,7 @@ osg::Texture2D* ReaderWriter3DS::ReaderObject::createTexture(Lib3dsTextureMap *
osg_texture->setImage(osg_image.get()); osg_texture->setImage(osg_image.get());
osg_texture->setName(texture->name); osg_texture->setName(texture->name);
// does the texture support transparancy? // does the texture support transparancy?
//transparency = ((texture->flags)&LIB3DS_TEXTURE_ALPHA_SOURCE)!=0; transparancy = ((texture->flags)&LIB3DS_TEXTURE_ALPHA_SOURCE)!=0;
// what is the wrap mode of the texture. // what is the wrap mode of the texture.
osg::Texture2D::WrapMode wm = ((texture->flags)&LIB3DS_TEXTURE_NO_TILE) ? osg::Texture2D::WrapMode wm = ((texture->flags)&LIB3DS_TEXTURE_NO_TILE) ?
@@ -1067,8 +1025,6 @@ osg::Texture2D* ReaderWriter3DS::ReaderObject::createTexture(Lib3dsTextureMap *
// bilinear. // bilinear.
osg_texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR_MIPMAP_NEAREST); osg_texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR_MIPMAP_NEAREST);
// Insert in cache map
texturesMap.insert(TexturesMap::value_type(texture->name, osg_texture));
return osg_texture; return osg_texture;
} }
else else
@@ -1076,42 +1032,38 @@ osg::Texture2D* ReaderWriter3DS::ReaderObject::createTexture(Lib3dsTextureMap *
} }
ReaderWriter3DS::StateSetInfo ReaderWriter3DS::ReaderObject::createStateSet(Lib3dsMaterial *mat) osg::StateSet* ReaderWriter3DS::ReaderObject::createStateSet(Lib3dsMaterial *mat)
{ {
if (mat==NULL) return StateSetInfo(); if (mat==NULL) return NULL;
bool textureTransparency=false;
bool transparency = false;
float alpha = 1.0f - mat->transparency;
int unit = 0;
osg::StateSet* stateset = new osg::StateSet; osg::StateSet* stateset = new osg::StateSet;
osg::Material* material = new osg::Material; osg::Material* material = new osg::Material;
osg::Vec3 ambient(mat->ambient[0],mat->ambient[1],mat->ambient[2]); float transparency = mat->transparency;
osg::Vec3 diffuse(mat->diffuse[0],mat->diffuse[1],mat->diffuse[2]); float alpha = 1.0f-transparency;
osg::Vec3 specular(mat->specular[0],mat->specular[1],mat->specular[2]);
specular *= mat->shin_strength;
float shininess = mat->shininess*128.0f;
// diffuse osg::Vec4 ambient(mat->ambient[0],mat->ambient[1],mat->ambient[2],alpha);
osg::Texture2D* texture1_map = createTexture(&(mat->texture1_map),"texture1_map",textureTransparency); osg::Vec4 diffuse(mat->diffuse[0],mat->diffuse[1],mat->diffuse[2],alpha);
osg::Vec4 specular(mat->specular[0],mat->specular[1],mat->specular[2],alpha);
specular *= mat->shin_strength;
float shininess = mat->shininess;
material->setName(mat->name);
material->setAmbient(osg::Material::FRONT_AND_BACK,ambient);
material->setDiffuse(osg::Material::FRONT_AND_BACK,diffuse);
material->setSpecular(osg::Material::FRONT_AND_BACK,specular);
material->setShininess(osg::Material::FRONT_AND_BACK,shininess*128.0f);
stateset->setAttribute(material);
bool textureTransparancy=false;
osg::Texture2D* texture1_map = createTexture(&(mat->texture1_map),"texture1_map",textureTransparancy);
if (texture1_map) if (texture1_map)
{ {
stateset->setTextureAttributeAndModes(unit, texture1_map, osg::StateAttribute::ON); stateset->setTextureAttributeAndModes(0,texture1_map,osg::StateAttribute::ON);
double factor = mat->texture1_map.percent; if (!textureTransparancy)
if(factor < 1.0)
{
osg::TexEnvCombine* texenv = new osg::TexEnvCombine();
texenv->setCombine_RGB(osg::TexEnvCombine::MODULATE);
texenv->setSource0_RGB(osg::TexEnvCombine::TEXTURE);
texenv->setSource1_RGB(osg::TexEnvCombine::PREVIOUS);
texenv->setSource2_RGB(osg::TexEnvCombine::CONSTANT);
texenv->setConstantColor(osg::Vec4(factor, factor, factor, factor));
stateset->setTextureAttributeAndModes(unit, texenv, osg::StateAttribute::ON);
}
else
{ {
// from an email from Eric Hamil, September 30, 2003. // from an email from Eric Hamil, September 30, 2003.
// According to the 3DS spec, and other // According to the 3DS spec, and other
@@ -1130,55 +1082,32 @@ ReaderWriter3DS::StateSetInfo ReaderWriter3DS::ReaderObject::createStateSet(Lib3
#else #else
// try alternative to avoid saturating with white // try alternative to avoid saturating with white
// setting white as per OpenGL defaults. // setting white as per OpenGL defaults.
ambient.set(0.2f,0.2f,0.2f); material->setAmbient(osg::Material::FRONT_AND_BACK,osg::Vec4(0.2f,0.2f,0.2f,alpha));
diffuse.set(0.8f,0.8f,0.8f); material->setDiffuse(osg::Material::FRONT_AND_BACK,osg::Vec4(0.8f,0.8f,0.8f,alpha));
specular.set(0.0f,0.0f,0.0f); material->setSpecular(osg::Material::FRONT_AND_BACK,osg::Vec4(0.0f,0.0f,0.0f,alpha));
#endif #endif
}
unit++;
}
// opacity
osg::Texture* opacity_map = createTexture(&(mat->opacity_map),"opacity_map", textureTransparency);
if (opacity_map)
{
if(texture1_map->getImage()->isImageTranslucent())
{
transparency = true;
stateset->setTextureAttributeAndModes(unit, opacity_map, osg::StateAttribute::ON);
double factor = mat->opacity_map.percent;
osg::TexEnvCombine* texenv = new osg::TexEnvCombine();
texenv->setCombine_Alpha(osg::TexEnvCombine::INTERPOLATE);
texenv->setSource0_Alpha(osg::TexEnvCombine::TEXTURE);
texenv->setSource1_Alpha(osg::TexEnvCombine::PREVIOUS);
texenv->setSource2_Alpha(osg::TexEnvCombine::CONSTANT);
texenv->setConstantColor(osg::Vec4(factor, factor, factor, 1.0 - factor));
stateset->setTextureAttributeAndModes(unit, texenv, osg::StateAttribute::ON);
unit++;
}
else
{
osg::notify(WARN)<<"The plugin does not support images without alpha channel for opacity"<<std::endl;
} }
// no longer required...
// bool decal = false;
//
// // not sure exactly how to interpret what is best for .3ds
// // but the default text env MODULATE doesn't work well, and
// // DECAL seems to work better.
// osg::TexEnv* texenv = new osg::TexEnv;
// if (decal)
// {
// texenv->setMode(osg::TexEnv::DECAL);
// }
// else
// {
// texenv->setMode(osg::TexEnv::MODULATE);
// }
// stateset->setTextureAttribute(0,texenv);
} }
// material if (transparency>0.0f || textureTransparancy)
material->setName(mat->name);
material->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4(ambient, alpha));
material->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4(diffuse, alpha));
material->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4(specular, alpha));
material->setShininess(osg::Material::FRONT_AND_BACK, shininess);
stateset->setAttribute(material);
if ((alpha < 1.0f) || transparency)
{ {
//stateset->setAttributeAndModes(new osg::BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
stateset->setMode(GL_BLEND,osg::StateAttribute::ON); stateset->setMode(GL_BLEND,osg::StateAttribute::ON);
stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN); stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
} }
@@ -1200,7 +1129,7 @@ ReaderWriter3DS::StateSetInfo ReaderWriter3DS::ReaderObject::createStateSet(Lib3
osg::ref_ptr<osg::Texture> reflection_map = createTexture(&(mat->reflection_map),"reflection_map",textureTransparancy); osg::ref_ptr<osg::Texture> reflection_map = createTexture(&(mat->reflection_map),"reflection_map",textureTransparancy);
osg::ref_ptr<osg::Texture> reflection_mask = createTexture(&(mat->reflection_mask),"reflection_mask",textureTransparancy); osg::ref_ptr<osg::Texture> reflection_mask = createTexture(&(mat->reflection_mask),"reflection_mask",textureTransparancy);
*/ */
return StateSetInfo(stateset, mat); return stateset;
} }
@@ -1210,7 +1139,7 @@ osgDB::ReaderWriter::WriteResult ReaderWriter3DS::writeNode(const osg::Node& nod
if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED; if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED;
osgDB::makeDirectoryForFile(fileName.c_str()); osgDB::makeDirectoryForFile(fileName.c_str());
osgDB::ofstream fout(fileName.c_str(), std::ios_base::out | std::ios_base::binary); std::ofstream fout(fileName.c_str(), std::ios_base::out | std::ios_base::binary);
if (!fout.good()) return WriteResult::ERROR_IN_WRITING_FILE; if (!fout.good()) return WriteResult::ERROR_IN_WRITING_FILE;
return doWriteNode(node, fout, options, fileName); return doWriteNode(node, fout, options, fileName);
/* /*
@@ -1231,7 +1160,7 @@ osgDB::ReaderWriter::WriteResult ReaderWriter3DS::writeNode(const osg::Node& nod
osgDB::ReaderWriter::WriteResult ReaderWriter3DS::writeNode(const osg::Node& node,std::ostream& fout,const Options* options) const osgDB::ReaderWriter::WriteResult ReaderWriter3DS::writeNode(const osg::Node& node,std::ostream& fout,const Options* options) const
{ {
//OSG_WARN << "!!WARNING!! 3DS write support is incomplete" << std::endl; //osg::notify(osg::WARN) << "!!WARNING!! 3DS write support is incomplete" << std::endl;
std::string optFileName; std::string optFileName;
if (options) if (options)
{ {

View File

@@ -1,138 +1,138 @@
#include "WriterCompareTriangle.h" #include "WriterCompareTriangle.h"
#include <assert.h> #include <assert.h>
WriterCompareTriangle::WriterCompareTriangle(const osg::Geode & geode, unsigned int nbVertices) : geode(geode) WriterCompareTriangle::WriterCompareTriangle(const osg::Geode & geode, unsigned int nbVertices) : geode(geode)
{ {
cutscene(nbVertices, geode.getBoundingBox()); cutscene(nbVertices, geode.getBoundingBox());
} }
bool bool
WriterCompareTriangle::operator()(const std::pair<Triangle, int> & t1, WriterCompareTriangle::operator()(const std::pair<Triangle, int> & t1,
const std::pair<Triangle, int> & t2) const const std::pair<Triangle, int> & t2) const
{ {
const osg::Geometry *g = geode.getDrawable( t1.second )->asGeometry(); const osg::Geometry *g = geode.getDrawable( t1.second )->asGeometry();
const osg::Vec3Array * vecs= static_cast<const osg::Vec3Array *>(g->getVertexArray()); const osg::Vec3Array * vecs= static_cast<const osg::Vec3Array *>(g->getVertexArray());
const osg::BoundingBox::vec_type v1( (*vecs)[t1.first.t1] ); const osg::BoundingBox::vec_type v1( (*vecs)[t1.first.t1] );
if (t1.second != t2.second) if (t1.second != t2.second)
{ {
const osg::Geometry *g = geode.getDrawable( t2.second )->asGeometry(); const osg::Geometry *g = geode.getDrawable( t2.second )->asGeometry();
vecs = static_cast<const osg::Vec3Array *>(g->getVertexArray()); vecs = static_cast<const osg::Vec3Array *>(g->getVertexArray());
}; };
const osg::BoundingBox::vec_type v2( (*vecs)[t2.first.t1] ); const osg::BoundingBox::vec_type v2( (*vecs)[t2.first.t1] );
int val1 = inWhichBox(v1); int val1 = inWhichBox(v1);
int val2 = inWhichBox(v2); int val2 = inWhichBox(v2);
return (val1 < val2); return (val1 < val2);
} }
void void
WriterCompareTriangle::setMaxMin(unsigned int & nbVerticesX, WriterCompareTriangle::setMaxMin(unsigned int & nbVerticesX,
unsigned int & nbVerticesY, unsigned int & nbVerticesY,
unsigned int & nbVerticesZ) const unsigned int & nbVerticesZ) const
{ {
static const unsigned int min = 1; static const unsigned int min = 1;
static const unsigned int max = 5; // Number of blocks used to divide the scene (arbitrary but seems ok) static const unsigned int max = 5; // Number of blocks used to divide the scene (arbitrary but seems ok)
nbVerticesX = osg::clampBetween<unsigned int>(nbVerticesX, min, max); nbVerticesX = osg::clampBetween<unsigned int>(nbVerticesX, min, max);
nbVerticesY = osg::clampBetween<unsigned int>(nbVerticesY, min, max); nbVerticesY = osg::clampBetween<unsigned int>(nbVerticesY, min, max);
nbVerticesZ = osg::clampBetween<unsigned int>(nbVerticesZ, min, max); nbVerticesZ = osg::clampBetween<unsigned int>(nbVerticesZ, min, max);
} }
void WriterCompareTriangle::cutscene(int nbVertices, const osg::BoundingBox & sceneBox) void WriterCompareTriangle::cutscene(int nbVertices, const osg::BoundingBox & sceneBox)
{ {
osg::BoundingBox::vec_type length = sceneBox._max - sceneBox._min; osg::BoundingBox::vec_type length = sceneBox._max - sceneBox._min;
static const float k = 1.3f; // Arbitrary constant multiplier for density computation ("simulates" non-uniform point distributions) static const float k = 1.3f; // Arbitrary constant multiplier for density computation ("simulates" non-uniform point distributions)
// Computes "density" of points, and thus the number of blocks to divide the mesh into // Computes "density" of points, and thus the number of blocks to divide the mesh into
unsigned int nbVerticesX = static_cast<unsigned int>( (nbVertices * k) / (length.z() * length.y()) ); unsigned int nbVerticesX = static_cast<unsigned int>( (nbVertices * k) / (length.z() * length.y()) );
unsigned int nbVerticesY = static_cast<unsigned int>( (nbVertices * k) / (length.z() * length.x()) ); unsigned int nbVerticesY = static_cast<unsigned int>( (nbVertices * k) / (length.z() * length.x()) );
unsigned int nbVerticesZ = static_cast<unsigned int>( (nbVertices * k) / (length.x() * length.y()) ); unsigned int nbVerticesZ = static_cast<unsigned int>( (nbVertices * k) / (length.x() * length.y()) );
setMaxMin (nbVerticesX, nbVerticesY, nbVerticesZ); // This function prevent from cutting the scene in too many blocs setMaxMin (nbVerticesX, nbVerticesY, nbVerticesZ); // This function prevent from cutting the scene in too many blocs
OSG_INFO osg::notify(osg::INFO)
<< "Cutting x by " << nbVerticesX << std::endl << "Cutting x by " << nbVerticesX << std::endl
<< "Cutting y by " << nbVerticesY << std::endl << "Cutting y by " << nbVerticesY << std::endl
<< "Cutting z by " << nbVerticesZ << std::endl; << "Cutting z by " << nbVerticesZ << std::endl;
osg::BoundingBox::value_type blocX = length.x() / nbVerticesX; // These 3 lines set the size of a bloc in x, y and z osg::BoundingBox::value_type blocX = length.x() / nbVerticesX; // These 3 lines set the size of a bloc in x, y and z
osg::BoundingBox::value_type blocY = length.y() / nbVerticesY; osg::BoundingBox::value_type blocY = length.y() / nbVerticesY;
osg::BoundingBox::value_type blocZ = length.z() / nbVerticesZ; osg::BoundingBox::value_type blocZ = length.z() / nbVerticesZ;
boxList.reserve(nbVerticesX * nbVerticesY * nbVerticesZ); boxList.reserve(nbVerticesX * nbVerticesY * nbVerticesZ);
short yinc = 1; short yinc = 1;
short xinc = 1; short xinc = 1;
unsigned int y = 0; unsigned int y = 0;
unsigned int x = 0; unsigned int x = 0;
for (unsigned int z = 0; z < nbVerticesZ; ++z) for (unsigned int z = 0; z < nbVerticesZ; ++z)
{ {
while (x < nbVerticesX && x >= 0) while (x < nbVerticesX && x >= 0)
{ {
while (y < nbVerticesY && y >= 0) while (y < nbVerticesY && y >= 0)
{ {
osg::BoundingBox::value_type xMin = sceneBox.xMin() + x * blocX; osg::BoundingBox::value_type xMin = sceneBox.xMin() + x * blocX;
if (x == 0) //to prevent from mesh with no case if (x == 0) //to prevent from mesh with no case
xMin -= 10; xMin -= 10;
osg::BoundingBox::value_type yMin = sceneBox.yMin() + y * blocY; osg::BoundingBox::value_type yMin = sceneBox.yMin() + y * blocY;
if (y == 0) //to prevent from mesh with no case if (y == 0) //to prevent from mesh with no case
yMin -= 10; yMin -= 10;
osg::BoundingBox::value_type zMin = sceneBox.zMin() + z * blocZ; osg::BoundingBox::value_type zMin = sceneBox.zMin() + z * blocZ;
if (z == 0) //to prevent from mesh with no case if (z == 0) //to prevent from mesh with no case
zMin -= 10; zMin -= 10;
osg::BoundingBox::value_type xMax = sceneBox.xMin() + (x + 1) * blocX; osg::BoundingBox::value_type xMax = sceneBox.xMin() + (x + 1) * blocX;
if (x == nbVerticesX - 1) //to prevent from mesh with no case if (x == nbVerticesX - 1) //to prevent from mesh with no case
xMax += 10; xMax += 10;
osg::BoundingBox::value_type yMax = sceneBox.yMin() + (y + 1) * blocY; osg::BoundingBox::value_type yMax = sceneBox.yMin() + (y + 1) * blocY;
if (y == nbVerticesY - 1) //to prevent from mesh with no case if (y == nbVerticesY - 1) //to prevent from mesh with no case
yMax += 10; yMax += 10;
osg::BoundingBox::value_type zMax = sceneBox.zMin() + (z + 1) * blocZ; osg::BoundingBox::value_type zMax = sceneBox.zMin() + (z + 1) * blocZ;
if (z == nbVerticesZ - 1) //to prevent from mesh with no case if (z == nbVerticesZ - 1) //to prevent from mesh with no case
zMax += 10; zMax += 10;
boxList.push_back(osg::BoundingBox(xMin, // Add a bloc to the list boxList.push_back(osg::BoundingBox(xMin, // Add a bloc to the list
yMin, yMin,
zMin, zMin,
xMax, xMax,
yMax, yMax,
zMax)); zMax));
y += yinc; y += yinc;
} }
yinc = -yinc; yinc = -yinc;
y += yinc; y += yinc;
x += xinc; x += xinc;
} }
xinc = -xinc; xinc = -xinc;
x += xinc; x += xinc;
} }
} }
int int
WriterCompareTriangle::inWhichBox(const osg::BoundingBox::value_type x, WriterCompareTriangle::inWhichBox(const osg::BoundingBox::value_type x,
const osg::BoundingBox::value_type y, const osg::BoundingBox::value_type y,
const osg::BoundingBox::value_type z) const const osg::BoundingBox::value_type z) const
{ {
for (unsigned int i = 0; i < boxList.size(); ++i) for (unsigned int i = 0; i < boxList.size(); ++i)
{ {
if (x >= boxList[i].xMin() && if (x >= boxList[i].xMin() &&
x < boxList[i].xMax() && x < boxList[i].xMax() &&
y >= boxList[i].yMin() && y >= boxList[i].yMin() &&
y < boxList[i].yMax() && y < boxList[i].yMax() &&
z >= boxList[i].zMin() && z >= boxList[i].zMin() &&
z < boxList[i].zMax()) z < boxList[i].zMax())
{ {
return i; return i;
} }
} }
assert(false && "Point is not in any blocs"); assert(false && "Point is not in any blocs");
return 0; return 0;
} }
int WriterCompareTriangle::inWhichBox(const osg::BoundingBox::vec_type & point) const { int WriterCompareTriangle::inWhichBox(const osg::BoundingBox::vec_type & point) const {
return inWhichBox(point.x(), point.y(), point.z()); return inWhichBox(point.x(), point.y(), point.z());
} }

View File

@@ -5,7 +5,7 @@
* *
* Copyright (C) ??? * Copyright (C) ???
* *
* Writing support added 2009 by Sukender (Benoit Neil), http://sukender.free.fr, * Writing support added 2007 by Sukender (Benoit Neil), http://sukender.free.fr,
* strongly inspired by the OBJ writer object by Stephan Huber * strongly inspired by the OBJ writer object by Stephan Huber
* *
* The Open Scene Graph (OSG) is a cross platform C++/OpenGL library for * The Open Scene Graph (OSG) is a cross platform C++/OpenGL library for
@@ -13,13 +13,6 @@
* The OSG homepage is http://www.openscenegraph.org/ * The OSG homepage is http://www.openscenegraph.org/
*/ */
/// [EXPERIMENTAL] Disables animation data (and matrix transforms) for compatibility with some 3rd party apps.
/// Animations are not read by all 3DS importers. Thus disabling them may allow some 3rd-party apps, such as Rhinoceros (tested with 4.0) to correctly import 3DS files.
/// However, having proper hierarchy with matrix transforms will become impossible.
///\warning This is still experimental, hence the compile flag. This should become a reader/writer option as soon as it works as intented (maybe "noMatrixTransforms" could become a read/write option?).
#define DISABLE_3DS_ANIMATION 0 // Default = 0
#include <osg/io_utils> #include <osg/io_utils>
#include <osg/CullFace> #include <osg/CullFace>
#include <osg/Billboard> #include <osg/Billboard>
@@ -28,7 +21,7 @@
#include "WriterNodeVisitor.h" #include "WriterNodeVisitor.h"
#include <assert.h> #include <assert.h>
#include <string.h> #include <string.h>
#include <limits.h>
void copyOsgMatrixToLib3dsMatrix(Lib3dsMatrix lib3ds_matrix, const osg::Matrix& osg_matrix) void copyOsgMatrixToLib3dsMatrix(Lib3dsMatrix lib3ds_matrix, const osg::Matrix& osg_matrix)
{ {
@@ -82,9 +75,15 @@ inline void copyOsgQuatToLib3dsQuat(float lib3ds_vector[4], const osg::Quat& osg
lib3ds_vector[3] = static_cast<float>(-angle); lib3ds_vector[3] = static_cast<float>(-angle);
} }
std::string getFileName(const std::string & path)
{
unsigned int slashPos = path.find_last_of("/\\");
if (slashPos == std::string::npos) return path;
return path.substr(slashPos+1);
}
/// Checks if a filename (\b not path) is 8.3 (an empty name is never 8.3, and a path is never 8.3). /// Checks if a filename (\b not path) is 8.3 (an empty name is never 8.3, and a path is never 8.3).
/// Please note the '8' and '3' limitations are in \b bytes, not in characters (which is different when using UTF8).
bool is83(const std::string & s) bool is83(const std::string & s)
{ {
// 012345678901 // 012345678901
@@ -92,7 +91,7 @@ bool is83(const std::string & s)
if (s.find_first_of("/\\") != std::string::npos) return false; // It should not be a path, but a filename if (s.find_first_of("/\\") != std::string::npos) return false; // It should not be a path, but a filename
unsigned int len = s.length(); unsigned int len = s.length();
if (len > 12 || len == 0) return false; if (len > 12 || len == 0) return false;
size_t pointPos = s.rfind('.'); unsigned int pointPos = s.rfind('.');
if (pointPos == std::string::npos) return len <= 8; // Without point if (pointPos == std::string::npos) return len <= 8; // Without point
// With point // With point
if (pointPos > 8) return false; if (pointPos > 8) return false;
@@ -100,138 +99,25 @@ bool is83(const std::string & s)
return true; return true;
} }
inline std::string::size_type maxNameLen(bool extendedFilePaths, bool isNodeName) { /// Tests if the given string is a path supported by 3DS format (8.3, 63 chars max).
if (extendedFilePaths) return 63; bool is3DSpath(const std::string & s, bool extendedFilePaths)
return isNodeName ? 8 : (8+1+3);
}
/// Tests if the given string is a path supported by 3DS format (8.3, 63 chars max, non empty).
inline bool is3DSName(const std::string & s, bool extendedFilePaths, bool isNodeName)
{ {
unsigned int len = s.length(); unsigned int len = s.length();
if (len > maxNameLen(extendedFilePaths, isNodeName) || len == 0) return false; if (len >= 64 || len == 0) return false;
// Extended paths are simply those that fits the 64 bytes buffer. if (extendedFilePaths) return true; // Extended paths are simply those that fits the 64 bytes buffer!
if (extendedFilePaths) return true;
// Short paths simply must have no subdirectory.
return is83(s);
}
// ************************************************************************** // For each subdirectory
// ************************************************************************** unsigned int tokenLen;
// The following block of code was taken from the osgDB 2.9.x trunk code for (unsigned int tokenBegin=0, tokenEnd=0; tokenEnd == std::string::npos; tokenBegin = tokenEnd+1)
// (FileNameUtils) so that the 3ds plugin will be completely self-contained
// in this release.
static const char * const PATH_SEPARATORS = "/\\";
static unsigned int PATH_SEPARATORS_LEN = 2;
/** Helper to iterate over elements of a path (including Windows' root, if any). **/
class PathIterator {
public:
PathIterator(const std::string & v);
bool valid() const { return start!=end; }
PathIterator & operator++();
std::string operator*();
protected:
std::string::const_iterator end; ///< End of path string
std::string::const_iterator start; ///< Points to the first char of an element, or ==end() if no more
std::string::const_iterator stop; ///< Points to the separator after 'start', or ==end()
/// Iterate until 'it' points to something different from a separator
std::string::const_iterator skipSeparators(std::string::const_iterator it);
std::string::const_iterator next(std::string::const_iterator it);
};
PathIterator::PathIterator(const std::string & v) : end(v.end()), start(v.begin()), stop(v.begin()) { operator++(); }
PathIterator & PathIterator::operator++()
{
if (!valid()) return *this;
start = skipSeparators(stop);
if (start != end) stop = next(start);
return *this;
}
std::string PathIterator::operator*()
{
if (!valid()) return std::string();
return std::string(start, stop);
}
std::string::const_iterator PathIterator::skipSeparators(std::string::const_iterator it)
{
for (; it!=end && std::find_first_of(it, it+1, PATH_SEPARATORS, PATH_SEPARATORS+PATH_SEPARATORS_LEN) != it+1; ++it) {}
return it;
}
std::string::const_iterator PathIterator::next(std::string::const_iterator it)
{
return std::find_first_of(it, end, PATH_SEPARATORS, PATH_SEPARATORS+PATH_SEPARATORS_LEN);
}
static std::string getPathRoot(const std::string& path) {
// Test for unix root
if (path.empty()) return "";
if (path[0] == '/') return "/";
// Now test for Windows root
if (path.length()<2) return "";
if (path[1] == ':') return path.substr(0, 2); // We should check that path[0] is a letter, but as ':' is invalid in paths in other cases, that's not a problem.
return "";
}
static std::string getPathRelative(const std::string& from, const std::string& to)
{
// This implementation is not 100% robust, and should be replaced with C++0x "std::path" as soon as possible.
// Definition: an "element" is a part between slashes. Ex: "/a/b" has two elements ("a" and "b").
// Algorithm:
// 1. If paths are neither both absolute nor both relative, then we cannot do anything (we need to make them absolute, but need additionnal info on how to make it). Return.
// 2. If both paths are absolute and root isn't the same (for Windows only, as roots are of the type "C:", "D:"), then the operation is impossible. Return.
// 3. Iterate over two paths elements until elements are equal
// 4. For each remaining element in "from", add ".." to result
// 5. For each remaining element in "to", add this element to result
// 1 & 2
const std::string root = getPathRoot(from);
if (root != getPathRoot(to)) {
OSG_INFO << "Cannot relativise paths. From=" << from << ", To=" << to << ". Returning 'to' unchanged." << std::endl;
//return to;
return osgDB::getSimpleFileName(to);
}
// 3
PathIterator itFrom(from), itTo(to);
// Iterators may point to Windows roots. As we tested they are equal, there is no need to ++itFrom and ++itTo.
// However, if we got an Unix root, we must add it to the result.
std::string res(root == "/" ? "/" : "");
for(; itFrom.valid() && itTo.valid() && *itFrom==*itTo; ++itFrom, ++itTo) {}
// 4
for(; itFrom.valid(); ++itFrom) res += "../";
// 5
for(; itTo.valid(); ++itTo) res += *itTo + "/";
// Remove trailing slash before returning
if (!res.empty() && std::find_first_of(res.rbegin(), res.rbegin()+1, PATH_SEPARATORS, PATH_SEPARATORS+PATH_SEPARATORS_LEN) != res.rbegin()+1)
{ {
return res.substr(0, res.length()-1); tokenEnd = s.find_first_of("/\\", tokenBegin);
if (tokenEnd != std::string::npos) tokenLen = tokenEnd-tokenBegin-1; // -1 to avoid reading the separator
else tokenLen = len-tokenBegin;
if ( tokenLen>0 && !is83(s.substr(tokenBegin, tokenLen)) ) return false;
} }
return res; return true;
} }
// strip all extensions from the filename.
static std::string getNameLessAllExtensions(const std::string& fileName)
{
// Finds start serach position: from last slash, or the begining of the string if none found
std::string::size_type startPos = fileName.find_last_of(PATH_SEPARATORS); // Finds forward slash *or* back slash
if (startPos == std::string::npos) startPos = 0;
std::string::size_type dot = fileName.find_first_of('.', startPos); // Finds *FIRST* dot from start pos
if (dot==std::string::npos) return fileName;
return std::string(fileName.begin(),fileName.begin()+dot);
}
// **************************************************************************
// **************************************************************************
// Use namespace qualification to avoid static-link symbol collitions // Use namespace qualification to avoid static-link symbol collitions
// from multiply defined symbols. // from multiply defined symbols.
@@ -280,7 +166,7 @@ public:
triangle.t2 = i2; triangle.t2 = i2;
triangle.t3 = i3; triangle.t3 = i3;
triangle.material = _material; triangle.material = _material;
_listTriangles.push_back(ListTriangle::value_type(triangle, _drawable_n)); _listTriangles.push_back(std::pair<Triangle, unsigned int>(triangle, _drawable_n));
} }
virtual void begin(GLenum mode) virtual void begin(GLenum mode)
{ {
@@ -469,13 +355,11 @@ void PrimitiveIndexWriter::drawArrays(GLenum mode,GLint first,GLsizei count)
case(GL_LINE_LOOP): case(GL_LINE_LOOP):
//break; //break;
default: default:
OSG_WARN << "3DS WriterNodeVisitor: can't handle mode " << mode << std::endl; osg::notify(osg::WARN) << "3DS WriterNodeVisitor: can't handle mode " << mode << std::endl;
break; break;
} }
} }
WriterNodeVisitor::Material::Material(WriterNodeVisitor & writerNodeVisitor, osg::StateSet * stateset, osg::Material* mat, osg::Texture* tex, int index) : WriterNodeVisitor::Material::Material(WriterNodeVisitor & writerNodeVisitor, osg::StateSet * stateset, osg::Material* mat, osg::Texture* tex, int index) :
index(index), index(index),
diffuse(1,1,1,1), diffuse(1,1,1,1),
@@ -486,7 +370,7 @@ WriterNodeVisitor::Material::Material(WriterNodeVisitor & writerNodeVisitor, osg
double_sided(false), double_sided(false),
image(NULL), image(NULL),
texture_transparency(false), texture_transparency(false),
texture_no_tile(true) // matches lib3ds_material.cpp initialize_texture_map(..) default flag setting texture_no_tile(false)
{ {
//static unsigned int s_objmaterial_id = 0; //static unsigned int s_objmaterial_id = 0;
//++s_objmaterial_id; //++s_objmaterial_id;
@@ -496,14 +380,9 @@ WriterNodeVisitor::Material::Material(WriterNodeVisitor & writerNodeVisitor, osg
diffuse = mat->getDiffuse(osg::Material::FRONT); diffuse = mat->getDiffuse(osg::Material::FRONT);
ambient = mat->getAmbient(osg::Material::FRONT); ambient = mat->getAmbient(osg::Material::FRONT);
specular = mat->getSpecular(osg::Material::FRONT); specular = mat->getSpecular(osg::Material::FRONT);
shininess = mat->getShininess(osg::Material::FRONT) / 128.f; shininess = mat->getShininess(osg::Material::FRONT);
// OpenGL shininess = pow(2, 10.0*mat->shininess); (As in lib3ds example)
// => mat->shininess = log.2( OpenGL shininess ) /10 (if values are >0)
// => mat->shininess = log( OpenGL shininess ) / log(2) /10
//shininess = mat->getShininess(osg::Material::FRONT) <= 0 ? 0 : log( mat->getShininess(osg::Material::FRONT) ) / log(2.f) / 10.f;
transparency = 1-diffuse.w(); transparency = 1-diffuse.w();
name = writerNodeVisitor.getUniqueName(mat->getName(),true,"mat"); name = writerNodeVisitor.getUniqueName(mat->getName(),"mat");
osg::StateAttribute * attribute = stateset->getAttribute(osg::StateAttribute::CULLFACE); osg::StateAttribute * attribute = stateset->getAttribute(osg::StateAttribute::CULLFACE);
if (!attribute) if (!attribute)
{ {
@@ -516,13 +395,13 @@ WriterNodeVisitor::Material::Material(WriterNodeVisitor & writerNodeVisitor, osg
if (mode == osg::CullFace::BACK) double_sided = false; if (mode == osg::CullFace::BACK) double_sided = false;
else if (mode == osg::CullFace::FRONT) else if (mode == osg::CullFace::FRONT)
{ {
OSG_WARN << "3DS Writer: Reversed face (culled FRONT) not supported yet." << std::endl; osg::notify(osg::WARN) << "3DS Writer: Reversed face (culled FRONT) not supported yet." << std::endl;
double_sided = false; double_sided = false;
} }
else else
{ {
assert(mode == osg::CullFace::FRONT_AND_BACK); assert(mode == osg::CullFace::FRONT_AND_BACK);
OSG_WARN << "3DS Writer: Invisible face (culled FRONT_AND_BACK) not supported yet." << std::endl; osg::notify(osg::WARN) << "3DS Writer: Invisible face (culled FRONT_AND_BACK) not supported yet." << std::endl;
double_sided = false; double_sided = false;
} }
} }
@@ -533,8 +412,7 @@ WriterNodeVisitor::Material::Material(WriterNodeVisitor & writerNodeVisitor, osg
if(img) if(img)
{ {
texture_transparency = (stateset->getMode(GL_BLEND) == osg::StateAttribute::ON); texture_transparency = (stateset->getMode(GL_BLEND) == osg::StateAttribute::ON);
osg::Texture::WrapMode wrapS = tex->getWrap(osg::Texture2D::WRAP_S); texture_no_tile = (tex->getWrap(osg::Texture2D::WRAP_S) == osg::Texture2D::CLAMP);
texture_no_tile = !(wrapS == osg::Texture2D::REPEAT || wrapS == osg::Texture2D::MIRROR);
image = img; image = img;
} }
} }
@@ -548,6 +426,49 @@ WriterNodeVisitor::Material::Material(WriterNodeVisitor & writerNodeVisitor, osg
} }
// If 'to' is in a subdirectory of 'from' then this function returns the
// subpath. Otherwise it just returns the file name.
// (Same as in FBX plugin)
std::string getPathRelative(const std::string& from/*directory*/,
const std::string& to/*file path*/)
{
std::string::size_type slash = to.find_last_of('/');
std::string::size_type backslash = to.find_last_of('\\');
if (slash == std::string::npos)
{
if (backslash == std::string::npos) return to;
slash = backslash;
}
else if (backslash != std::string::npos && backslash > slash)
{
slash = backslash;
}
if (from.empty() || from.length() > to.length())
return osgDB::getSimpleFileName(to);
std::string::const_iterator itTo = to.begin();
for (std::string::const_iterator itFrom = from.begin();
itFrom != from.end(); ++itFrom, ++itTo)
{
char a = tolower(*itFrom), b = tolower(*itTo);
if (a == '\\') a = '/';
if (b == '\\') b = '/';
if (a != b || itTo == to.begin() + slash + 1)
{
return osgDB::getSimpleFileName(to);
}
}
while (itTo != to.end() && (*itTo == '\\' || *itTo == '/'))
{
++itTo;
}
return std::string(itTo, to.end());
}
/// Converts an extension to a 3-letters long one equivalent. /// Converts an extension to a 3-letters long one equivalent.
std::string convertExt(const std::string & path, bool extendedFilePaths) std::string convertExt(const std::string & path, bool extendedFilePaths)
{ {
@@ -567,12 +488,12 @@ WriterNodeVisitor::WriterNodeVisitor(Lib3dsFile * file3ds, const std::string & f
osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN), osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
_succeeded(true), _succeeded(true),
_srcDirectory(srcDirectory), _srcDirectory(srcDirectory),
_file3ds(file3ds), file3ds(file3ds),
_currentStateSet(new osg::StateSet()), _currentStateSet(new osg::StateSet()),
_lastMaterialIndex(0), _lastMaterialIndex(0),
_lastMeshIndex(0), _lastMeshIndex(0),
_cur3dsNode(NULL), _cur3dsNode(NULL),
_options(options), options(options),
_imageCount(0), _imageCount(0),
_extendedFilePaths(false) _extendedFilePaths(false)
{ {
@@ -595,7 +516,7 @@ WriterNodeVisitor::WriterNodeVisitor(Lib3dsFile * file3ds, const std::string & f
void WriterNodeVisitor::writeMaterials() void WriterNodeVisitor::writeMaterials()
{ {
unsigned int nbMat = _materialMap.size(); unsigned int nbMat = _materialMap.size();
lib3ds_file_reserve_materials(_file3ds, nbMat, 1); lib3ds_file_reserve_materials(file3ds, nbMat, 1);
// Ugly thing: it seems lib3ds_file_insert_material() doesn't support insertion in a random order (else materials are not assigned the right way) // Ugly thing: it seems lib3ds_file_insert_material() doesn't support insertion in a random order (else materials are not assigned the right way)
for (unsigned int iMat=0; iMat<nbMat; ++iMat) for (unsigned int iMat=0; iMat<nbMat; ++iMat)
{ {
@@ -607,7 +528,7 @@ void WriterNodeVisitor::writeMaterials()
found = true; found = true;
assert(mat.index>=0 && mat.index < static_cast<int>(_materialMap.size())); assert(mat.index>=0 && mat.index < static_cast<int>(_materialMap.size()));
Lib3dsMaterial * mat3ds = lib3ds_material_new(osgDB::getSimpleFileName(mat.name).c_str()); Lib3dsMaterial * mat3ds = lib3ds_material_new(getFileName(mat.name).c_str());
copyOsgColorToLib3dsColor(mat3ds->ambient, mat.ambient); copyOsgColorToLib3dsColor(mat3ds->ambient, mat.ambient);
copyOsgColorToLib3dsColor(mat3ds->diffuse, mat.diffuse); copyOsgColorToLib3dsColor(mat3ds->diffuse, mat.diffuse);
copyOsgColorToLib3dsColor(mat3ds->specular, mat.specular); copyOsgColorToLib3dsColor(mat3ds->specular, mat.specular);
@@ -616,223 +537,137 @@ void WriterNodeVisitor::writeMaterials()
mat3ds->two_sided = mat.double_sided ? 1 : 0; mat3ds->two_sided = mat.double_sided ? 1 : 0;
if (mat.image) if (mat.image)
{ {
Lib3dsTextureMap & tex = mat3ds->texture1_map;
std::string path; std::string path;
ImageSet::const_iterator itImage( _imageSet.find(mat.image.get()) ); if(mat.image->getFileName().empty())
if (itImage != _imageSet.end())
{ {
// Image has been already used std::ostringstream oss;
path = itImage->second; oss << "Image_" << _imageCount++ << ".rgb";
path = oss.str();
} }
else else
{ {
// First time we 'see' this image path = getPathRelative(_srcDirectory, mat.image->getFileName());
if (mat.image->getFileName().empty()) }
{ path = convertExt(path, _extendedFilePaths);
std::ostringstream oss;
oss << "Image_" << _imageCount++ << ".rgb";
path = oss.str();
}
else
{
path = getPathRelative(_srcDirectory, mat.image->getFileName());
}
path = convertExt(path, _extendedFilePaths);
path = getUniqueName(path, false, "");
// Write if(!is3DSpath(path, _extendedFilePaths))
const std::string fullPath( osgDB::concatPaths(_directory, path) ); {
osgDB::makeDirectoryForFile(fullPath); path = getUniqueName(path, "", true);
osgDB::writeImageFile(*(mat.image), fullPath, _options); //path = osgDB::getSimpleFileName(path);
// Insert in map
_imageSet.insert(ImageSet::value_type(mat.image.get(), path));
} }
Lib3dsTextureMap & tex = mat3ds->texture1_map;
strcpy(tex.name, path.c_str()); strcpy(tex.name, path.c_str());
// Here we don't assume anything about initial flags state (actually it is set to LIB3DS_TEXTURE_NO_TILE by lib3DS, but this is subject to change) path = osgDB::concatPaths(_directory, path);
osgDB::makeDirectoryForFile(path);
//if (mat.image->valid()) osgDB::writeImageFile(*(mat.image), path);
if(_imageSet.find(mat.image.get()) == _imageSet.end())
{
_imageSet.insert(mat.image.get());
osgDB::writeImageFile(*(mat.image), path);
}
if (mat.texture_transparency) tex.flags |= LIB3DS_TEXTURE_ALPHA_SOURCE; if (mat.texture_transparency) tex.flags |= LIB3DS_TEXTURE_ALPHA_SOURCE;
else tex.flags &= ~LIB3DS_TEXTURE_ALPHA_SOURCE;
if (mat.texture_no_tile) tex.flags |= LIB3DS_TEXTURE_NO_TILE; if (mat.texture_no_tile) tex.flags |= LIB3DS_TEXTURE_NO_TILE;
else tex.flags &= ~LIB3DS_TEXTURE_NO_TILE;
} }
if (!succeeded()) if (!succeeded())
return; return;
lib3ds_file_insert_material(_file3ds, mat3ds, itr->second.index); lib3ds_file_insert_material(file3ds, mat3ds, itr->second.index);
break; // Ugly thing (3) break; // Ugly thing (3)
} }
assert(found); // Ugly thing (4) - Implementation error if !found assert(found); // Ugly thing (4) - Implementation error if !found
} }
} }
/// Truncates an UTF8 string so that it does not takes more than a given \b bytes amount (\b excluding the potential NULL end character).
/// The function assumes the UTF8 string is valid.
///\return A valid UTF8 string which size is less or equal to \c byteLimit.
// May be moved in osgDB/ConvertUTF?
std::string utf8TruncateBytes(const std::string & s, std::string::size_type byteLimit) {
// Untruncated strings
if (s.size() <= byteLimit) return s;
// Truncated strings std::string WriterNodeVisitor::getUniqueName(const std::string& _defaultValue, const std::string & _defaultPrefix, bool nameIsPath)
std::string::const_iterator it=s.begin(), itEnd=s.begin()+byteLimit;
std::string::const_iterator itStop=it;
// Note: itEnd is < s.end(), so that we can always write "it+1"
for(; it!=itEnd; ++it) {
unsigned char c = static_cast<unsigned char>(*it);
if ((c & 0x80) == 0) itStop=it+1; // 7 bits ANSI. itStop must then point after that character.
else if ((c & 0x40) != 0) itStop=it; // UTF8 sequence start: this is also past-the-end for the previous character (ANSI or UTF8)
}
return std::string(s.begin(), itStop);
}
#ifdef OSG_USE_UTF8_FILENAME
# define truncateFilenameBytes(str, size) utf8TruncateBytes(str, size)
#else
# define truncateFilenameBytes(str, size) std::string(str, 0, size)
#endif
std::string WriterNodeVisitor::getUniqueName(const std::string& _defaultValue, bool isNodeName, const std::string & _defaultPrefix, int currentPrefixLen)
{ {
//const unsigned int MAX_LENGTH = maxNameLen(_extendedFilePaths); static const unsigned int MAX_PREFIX_LEGNTH = 4; // Arbitrarily defined to 4 chars
const unsigned int MAX_PREFIX_LENGTH = _extendedFilePaths ? 52 : 6; // Arbitrarily defined for short names, kept enough room for displaying UINT_MAX (10 characters) for long names. assert(_defaultPrefix.length()<=MAX_PREFIX_LEGNTH); // Default prefix is too long (implementation error)
assert(_defaultPrefix.length()<=4); // Default prefix is too long (implementation error)
const std::string defaultPrefix(_defaultPrefix.empty() ? "_" : _defaultPrefix);
if (currentPrefixLen<0) currentPrefixLen = osg::maximum(_defaultPrefix.length(), _defaultValue.length());
currentPrefixLen = osg::clampBelow(currentPrefixLen, static_cast<int>(MAX_PREFIX_LENGTH));
// Tests if default name is valid and unique // Tests if default name is valid and unique
NameMap & nameMap = isNodeName ? _nodeNameMap : _imageNameMap; bool defaultIs83 = is83(_defaultValue);
PrefixMap & prefixMap = isNodeName ? _nodePrefixMap : _imagePrefixMap; bool defaultIsValid = nameIsPath ? is3DSpath(_defaultValue, _extendedFilePaths) : defaultIs83;
if (defaultIsValid && _nameMap.find(_defaultValue) == _nameMap.end())
// Handling of paths is simple. Algorithm:
// - For short names, subdirectories are simply forbidden. Use the simple file name.
// - Else, the whole (relative) path must simply be <64 chars.
// After this, begin enumeration.
std::string parentPath, filename, ext, namePrefix;
unsigned int max_val = 0;
// TODO Move the two parts of this giant if/else into two separate functions for better readability.
if (_extendedFilePaths)
{ {
// Tests if default name is valid and unique _nameMap.insert(_defaultValue);
if (is3DSName(_defaultValue, _extendedFilePaths, isNodeName)) return _defaultValue;
}
// Handling of paths is not well done yet. Defaulting to something very simple.
// We should actually ensure each component is 8 chars long, and final filename is 8.3, and total is <64 chars, or simply ensure total length for extended 3DS paths.
std::string defaultValue(nameIsPath ? osgDB::getSimpleFileName(_defaultValue) : _defaultValue);
std::string ext(nameIsPath ? osgDB::getFileExtensionIncludingDot(_defaultValue).substr(0, std::min<unsigned int>(_defaultValue.size(), 4)) : ""); // 4 chars = dot + 3 chars
if (ext == ".") ext = "";
std::string defaultPrefix(_defaultPrefix.empty() ? "_" : _defaultPrefix);
unsigned int max_val = 0;
std::string truncDefaultValue = "";
for (unsigned int i = 0; i < std::min<unsigned int>(defaultValue.size(), MAX_PREFIX_LEGNTH); ++i)
{
if (defaultValue[i] == '.')
{ {
std::pair<NameMap::iterator, bool> insertion( nameMap.insert(_defaultValue) ); truncDefaultValue = defaultValue.substr(0, i);
if (insertion.second) return _defaultValue; // Return if element is newly inserted in the map (else there is a naming collision) break;
} }
}
if (truncDefaultValue.empty())
truncDefaultValue = defaultValue.substr(0, std::min<unsigned int>(defaultValue.size(), MAX_PREFIX_LEGNTH));
assert(truncDefaultValue.size() <= MAX_PREFIX_LEGNTH);
std::map<std::string, unsigned int>::iterator pairPrefix;
// Simply separate name and last extension // TODO - Handle the case of extended 3DS paths and allow more than 8 chars
filename = osgDB::getNameLessExtension(osgDB::getSimpleFileName(_defaultValue)); defaultIs83 = is83(truncDefaultValue);
if (!isNodeName) if (defaultIs83)
{ {
ext = osgDB::getFileExtensionIncludingDot(_defaultValue); max_val = static_cast<unsigned int>(pow(10., 8. - truncDefaultValue.length())) -1;
if (ext == ".") ext = ""; pairPrefix = _mapPrefix.find(truncDefaultValue);
} }
// Compute parent path if (defaultIs83 && (pairPrefix == _mapPrefix.end() || pairPrefix->second <= max_val))
// Pre-condition: paths are supposed to be relative. {
// If full path is too long (>MAX_PREFIX_LENGTH), cut path to let enough space for simple file name. defaultPrefix = truncDefaultValue;
// Do not cut in the middle of a name, but at path separators.
parentPath = osgDB::getFilePath(_defaultValue);
if (_defaultValue.length() >MAX_PREFIX_LENGTH) // Not parentPath but _defaultValue!
{
// Nodes names: keep last directories (used only for the root name, generally named after the full file path)
// Images names: keep first directories (for images)
if (isNodeName) std::reverse(parentPath.begin(), parentPath.end());
unsigned lenToDelete(filename.length() + ext.length() + 1);
lenToDelete = osg::clampBelow(lenToDelete, MAX_PREFIX_LENGTH);
parentPath = truncateFilenameBytes(parentPath, MAX_PREFIX_LENGTH - lenToDelete); // +1 for the path separator
std::string::size_type separator = parentPath.find_last_of("/\\");
if (separator != std::string::npos) parentPath = parentPath.substr(0, separator);
if (isNodeName) std::reverse(parentPath.begin(), parentPath.end());
}
// Assert "MAX_PREFIX_LENGTH - parent path length - extension length -1" is >=0 and truncate name to this length to get our new prefix.
assert(parentPath.length() + ext.length() <= MAX_PREFIX_LENGTH);
const unsigned int len = MAX_PREFIX_LENGTH - (parentPath.length() + ext.length() +1);
namePrefix = truncateFilenameBytes(filename, len);
if (namePrefix.empty()) namePrefix = defaultPrefix;
// Truncate the filename to get our new prefix
namePrefix = truncateFilenameBytes(filename, currentPrefixLen);
// Enough space has been reserved for UINT_MAX values
max_val = UINT_MAX;
} }
else else
{ {
// Get last extension, and make filename have no extension max_val = static_cast<unsigned int>(pow(10., 8. - defaultPrefix.length())) -1;
filename = getNameLessAllExtensions(osgDB::getSimpleFileName(_defaultValue)); pairPrefix = _mapPrefix.find(defaultPrefix);
if (!isNodeName)
{
ext = truncateFilenameBytes(osgDB::getFileExtensionIncludingDot(_defaultValue), 4); // 4 chars = dot + 3 chars
if (ext == ".") ext = "";
}
// Tests if STRIPPED default name is valid and unique
const std::string strippedName( filename + ext );
if (is3DSName(strippedName, _extendedFilePaths, isNodeName))
{
std::pair<NameMap::iterator, bool> insertion( nameMap.insert(strippedName) );
if (insertion.second) return strippedName; // Return if element is newly inserted in the map (else there is a naming collision)
}
namePrefix = filename;
if (namePrefix.empty()) namePrefix = defaultPrefix;
// Truncate the filename to get our new prefix
namePrefix = truncateFilenameBytes(namePrefix, currentPrefixLen);
// Compute the maximum enumeration value
max_val = static_cast<unsigned int>(pow(10., 8. - namePrefix.length())) -1;
} }
assert(namePrefix.size() <= MAX_PREFIX_LENGTH);
// Find the current enumeration value (searchStart) unsigned int searchStart = 0;
unsigned int searchStart(0); if (pairPrefix != _mapPrefix.end())
PrefixMap::iterator pairPrefix( prefixMap.find(namePrefix) );
if (pairPrefix != prefixMap.end())
{ {
searchStart = pairPrefix->second; searchStart = pairPrefix->second;
} }
else
{
// Check if truncated name is ok
const std::string res( osgDB::concatPaths(parentPath, namePrefix + ext) );
if (nameMap.find(res) == nameMap.end()) {
prefixMap.insert(std::pair<std::string, unsigned int>(namePrefix, 0));
nameMap.insert(res);
return res;
}
}
// Search for a free value
for(unsigned int i = searchStart; i <= max_val; ++i) for(unsigned int i = searchStart; i <= max_val; ++i)
{ {
std::stringstream ss; std::stringstream ss;
ss << namePrefix << i; ss << defaultPrefix << i;
const std::string res( osgDB::concatPaths(parentPath, ss.str() + ext) ); const std::string & res = ss.str();
if (nameMap.find(res) == nameMap.end()) if (_nameMap.find(res) == _nameMap.end())
{ {
if (pairPrefix != prefixMap.end()) if (pairPrefix != _mapPrefix.end())
{ {
pairPrefix->second = i + 1; pairPrefix->second = i + 1;
} else } else
{ {
prefixMap.insert(std::pair<std::string, unsigned int>(namePrefix, i + 1)); _mapPrefix.insert(std::pair<std::string, unsigned int>(defaultPrefix, i + 1));
} }
nameMap.insert(res); _nameMap.insert(res);
return res; return res + ext;
} }
} }
// Failed finding a name // Failed finding a name
// Try with a shorter prefix if possible // Try with a shorter prefix if possible
if (currentPrefixLen>1) return getUniqueName(_defaultValue, isNodeName, defaultPrefix, currentPrefixLen-1); if (defaultPrefix.length()>1) return getUniqueName(_defaultValue, defaultPrefix.substr(0, defaultPrefix.length()-1), nameIsPath);
// Try with default prefix if not arleady done // Try with default prefix if not arleady done
if (defaultPrefix != std::string("_")) return getUniqueName(_defaultValue, isNodeName, "_", 1); if (defaultPrefix != std::string("_")) return getUniqueName(_defaultValue, "_", nameIsPath);
// No more names // No more names
OSG_NOTIFY(osg::FATAL) << "No more names available!" << std::endl; osg::notify(osg::FATAL) << "No more names available!" << std::endl;
_succeeded = false; _succeeded = false;
return "ERROR"; return "ERROR";
} }
@@ -889,7 +724,7 @@ WriterNodeVisitor::buildMesh(osg::Geode & geo,
bool texcoords, bool texcoords,
Lib3dsMesh * mesh) Lib3dsMesh * mesh)
{ {
OSG_DEBUG << "Building Mesh" << std::endl; osg::notify(osg::DEBUG_INFO) << "Building Mesh" << std::endl;
assert(mesh); assert(mesh);
// Write points // Write points
@@ -899,27 +734,16 @@ WriterNodeVisitor::buildMesh(osg::Geode & geo,
for(MapIndices::iterator it = index_vert.begin(); it != index_vert.end();++it) for(MapIndices::iterator it = index_vert.begin(); it != index_vert.end();++it)
{ {
osg::Geometry *g = geo.getDrawable( it->first.second )->asGeometry(); osg::Geometry *g = geo.getDrawable( it->first.second )->asGeometry();
const osg::Array * basevecs = g->getVertexArray(); assert(g->getVertexArray());
assert(basevecs); if (g->getVertexArray()->getType() != osg::Array::Vec3ArrayType)
if (!basevecs || basevecs->getNumElements()==0) continue;
if (basevecs->getType() == osg::Array::Vec3ArrayType)
{ {
const osg::Vec3Array & vecs= *static_cast<const osg::Vec3Array *>(basevecs); // TODO Handle double presision vertices by converting them to float with a warning
copyOsgVectorToLib3dsVector(mesh->vertices[it->second], vecs[it->first.first]*mat); osg::notify(osg::FATAL) << "Vertex array is not Vec3. Not implemented" << std::endl;
}
else if (basevecs->getType() == osg::Array::Vec3dArrayType)
{
// Handle double presision vertices by converting them to float with a warning
OSG_NOTICE << "3DS format only supports single precision vertices. Converting double precision to single." << std::endl;
const osg::Vec3dArray & vecs= *static_cast<const osg::Vec3dArray *>(basevecs);
copyOsgVectorToLib3dsVector(mesh->vertices[it->second], vecs[it->first.first]*mat);
}
else
{
OSG_NOTIFY(osg::FATAL) << "Vertex array is not Vec3 or Vec3d. Not implemented" << std::endl;
_succeeded = false; _succeeded = false;
return; return;
} }
const osg::Vec3Array & vecs= *static_cast<osg::Vec3Array *>(g->getVertexArray());
copyOsgVectorToLib3dsVector(mesh->vertices[it->second], vecs[it->first.first]*mat);
} }
// Write texture coords (Texture 0 only) // Write texture coords (Texture 0 only)
@@ -928,25 +752,26 @@ WriterNodeVisitor::buildMesh(osg::Geode & geo,
for(MapIndices::iterator it = index_vert.begin(); it != index_vert.end(); ++it) for(MapIndices::iterator it = index_vert.begin(); it != index_vert.end(); ++it)
{ {
osg::Geometry *g = geo.getDrawable( it->first.second )->asGeometry(); osg::Geometry *g = geo.getDrawable( it->first.second )->asGeometry();
const osg::Array * texarray = g->getNumTexCoordArrays()>=1 ? g->getTexCoordArray(0) : NULL; osg::Array * texarray = g->getTexCoordArray(0);
if (!texarray || texarray->getNumElements()==0) continue; if (texarray)
if (g->getTexCoordArray(0)->getType() != osg::Array::Vec2ArrayType)
{ {
OSG_NOTIFY(osg::FATAL) << "Texture coords array is not Vec2. Not implemented" << std::endl; if (g->getTexCoordArray(0)->getType() != osg::Array::Vec2ArrayType)
_succeeded = false; {
return; osg::notify(osg::FATAL) << "Texture coords array is not Vec2. Not implemented" << std::endl;
_succeeded = false;
return;
}
const osg::Vec2Array & vecs= *static_cast<osg::Vec2Array *>(texarray);
mesh->texcos[it->second][0] = vecs[it->first.first][0];
mesh->texcos[it->second][1] = vecs[it->first.first][1];
} }
const osg::Vec2Array & vecs= *static_cast<const osg::Vec2Array *>(texarray);
mesh->texcos[it->second][0] = vecs[it->first.first][0];
mesh->texcos[it->second][1] = vecs[it->first.first][1];
} }
} }
lib3ds_file_insert_mesh(_file3ds, mesh, _lastMeshIndex); lib3ds_file_insert_mesh(file3ds, mesh, _lastMeshIndex);
++_lastMeshIndex; ++_lastMeshIndex;
Lib3dsMeshInstanceNode * node3ds = lib3ds_node_new_mesh_instance(mesh, mesh->name, NULL, NULL, NULL); Lib3dsMeshInstanceNode * node3ds = lib3ds_node_new_mesh_instance(mesh, mesh->name, NULL, NULL, NULL);
lib3ds_file_append_node(_file3ds, reinterpret_cast<Lib3dsNode*>(node3ds), reinterpret_cast<Lib3dsNode*>(_cur3dsNode)); lib3ds_file_append_node(file3ds, reinterpret_cast<Lib3dsNode*>(node3ds), reinterpret_cast<Lib3dsNode*>(_cur3dsNode));
} }
unsigned int unsigned int
@@ -956,7 +781,16 @@ WriterNodeVisitor::calcVertices(osg::Geode & geo)
for (unsigned int i = 0; i < geo.getNumDrawables(); ++i) for (unsigned int i = 0; i < geo.getNumDrawables(); ++i)
{ {
osg::Geometry *g = geo.getDrawable( i )->asGeometry(); osg::Geometry *g = geo.getDrawable( i )->asGeometry();
if (g->getVertexArray()) numVertice += g->getVertexArray()->getNumElements(); assert(g->getVertexArray());
if (g->getVertexArray()->getType() != osg::Array::Vec3ArrayType)
{
// TODO Handle double presision vertices by converting them to float with a warning
osg::notify(osg::FATAL) << "Vertex array is not Vec3. Not implemented" << std::endl;
_succeeded = false;
return 0;
}
const osg::Vec3Array & vecs= *static_cast<osg::Vec3Array *>(g->getVertexArray());
numVertice += vecs.getNumElements();
} }
return numVertice; return numVertice;
} }
@@ -972,24 +806,23 @@ WriterNodeVisitor::buildFaces(osg::Geode & geo,
unsigned int nbVerticesRemaining = calcVertices(geo); // May set _succeded to false unsigned int nbVerticesRemaining = calcVertices(geo); // May set _succeded to false
if (!succeeded()) return; if (!succeeded()) return;
std::string name( getUniqueName(geo.getName().empty() ? geo.className() : geo.getName(), true, "geo") ); std::string name( getUniqueName(geo.getName().empty() ? geo.className() : geo.getName(), "geo") );
if (!succeeded()) return; if (!succeeded()) return;
Lib3dsMesh *mesh = lib3ds_mesh_new( name.c_str() ); Lib3dsMesh *mesh = lib3ds_mesh_new( name.c_str() );
if (!mesh) if (!mesh)
{ {
OSG_NOTIFY(osg::FATAL) << "Allocation error" << std::endl; osg::notify(osg::FATAL) << "Allocation error" << std::endl;
_succeeded = false; _succeeded = false;
return; return;
} }
//copyOsgMatrixToLib3dsMatrix(mesh->matrix, mat);
lib3ds_mesh_resize_faces (mesh, osg::minimum(nbTrianglesRemaining, MAX_FACES)); lib3ds_mesh_resize_faces (mesh, osg::minimum(nbTrianglesRemaining, MAX_FACES));
lib3ds_mesh_resize_vertices(mesh, osg::minimum(nbVerticesRemaining, MAX_VERTICES), texcoords ? 0 : 1, 0); // Not mandatory but will allocate once a big block lib3ds_mesh_resize_vertices(mesh, osg::minimum(nbVerticesRemaining, MAX_VERTICES), texcoords ? 0 : 1, 0); // Not mandatory but will allocate once a big block
// Test if the mesh will be split and needs sorting // Test if the mesh will be split and needs sorting
if (nbVerticesRemaining >= MAX_VERTICES || nbTrianglesRemaining >= MAX_FACES) if (nbVerticesRemaining >= MAX_VERTICES || nbTrianglesRemaining >= MAX_FACES)
{ {
OSG_INFO << "Sorting elements..." << std::endl; osg::notify(osg::INFO) << "Sorting elements..." << std::endl;
WriterCompareTriangle cmp(geo, nbVerticesRemaining); WriterCompareTriangle cmp(geo, nbVerticesRemaining);
std::sort(listTriangles.begin(), listTriangles.end(), cmp); std::sort(listTriangles.begin(), listTriangles.end(), cmp);
} }
@@ -1018,10 +851,10 @@ WriterNodeVisitor::buildFaces(osg::Geode & geo,
// We can't call a thing like "nbVerticesRemaining -= ...;" because points may be used multiple times. // We can't call a thing like "nbVerticesRemaining -= ...;" because points may be used multiple times.
// [Sukender: An optimisation here would take too much time I think.] // [Sukender: An optimisation here would take too much time I think.]
mesh = lib3ds_mesh_new( getUniqueName(geo.getName().empty() ? geo.className() : geo.getName(), true, "geo").c_str()); mesh = lib3ds_mesh_new( getUniqueName(geo.getName().empty() ? geo.className() : geo.getName(), "geo").c_str());
if (!mesh) if (!mesh)
{ {
OSG_NOTIFY(osg::FATAL) << "Allocation error" << std::endl; osg::notify(osg::FATAL) << "Allocation error" << std::endl;
_succeeded = false; _succeeded = false;
return; return;
} }
@@ -1044,28 +877,48 @@ WriterNodeVisitor::buildFaces(osg::Geode & geo,
} }
void void
WriterNodeVisitor::createListTriangle(osg::Geometry * geo, WriterNodeVisitor::createListTriangle(osg::Geometry * geo,
ListTriangle & listTriangles, ListTriangle & listTriangles,
bool & texcoords, bool & texcoords,
unsigned int & drawable_n) unsigned int & drawable_n)
{ {
const osg::Array * basevecs = geo->getVertexArray(); unsigned int nbVertices = 0;
if (!basevecs || basevecs->getNumElements()==0) return;
// Texture coords
const osg::Array * basetexvecs = geo->getNumTexCoordArrays()>=1 ? geo->getTexCoordArray(0) : NULL;
if (basetexvecs)
{ {
unsigned int nb = basetexvecs->getNumElements(); if (geo->getVertexArray() && geo->getVertexArray()->getType() != osg::Array::Vec3ArrayType)
if (nb != geo->getVertexArray()->getNumElements())
{ {
OSG_NOTIFY(osg::FATAL) << "There are more/less texture coords than vertices (corrupted geometry)" << std::endl; // TODO Handle double presision vertices by converting them to float with a warning
osg::notify(osg::FATAL) << "Vertex array is not Vec3. Not implemented" << std::endl;
_succeeded = false; _succeeded = false;
return; return;
} }
texcoords = true; const osg::Vec3Array * vecs = geo->getVertexArray() ? static_cast<osg::Vec3Array *>(geo->getVertexArray()) : NULL;
if (vecs)
{
nbVertices = geo->getVertexArray()->getNumElements();
// Texture coords
if (geo->getTexCoordArray(0) && geo->getTexCoordArray(0)->getType() != osg::Array::Vec2ArrayType)
{
osg::notify(osg::FATAL) << "Texture coords array is not Vec2. Not implemented" << std::endl;
_succeeded = false;
return;
}
const osg::Vec2Array * texvecs = geo->getTexCoordArray(0) ? static_cast<osg::Vec2Array *>(geo->getTexCoordArray(0)) : NULL;
if (texvecs)
{
unsigned int nb = geo->getTexCoordArray(0)->getNumElements();
if (nb != geo->getVertexArray()->getNumElements())
{
osg::notify(osg::FATAL) << "There are more/less texture coords than vertices (corrupted geometry)" << std::endl;
_succeeded = false;
return;
}
texcoords = true;
}
}
} }
if (nbVertices==0) return;
int material = processStateSet(_currentStateSet.get()); int material = processStateSet(_currentStateSet.get());
for(unsigned int i = 0; i < geo->getNumPrimitiveSets(); ++i) //Fill the Triangle List for(unsigned int i = 0; i < geo->getNumPrimitiveSets(); ++i) //Fill the Triangle List
@@ -1096,12 +949,8 @@ void WriterNodeVisitor::apply( osg::Geode &node )
} }
if (succeeded() && count > 0) if (succeeded() && count > 0)
{ {
#if DISABLE_3DS_ANIMATION
osg::Matrix mat( osg::computeLocalToWorld(getNodePath()) ); osg::Matrix mat( osg::computeLocalToWorld(getNodePath()) );
buildFaces(node, mat, listTriangles, texcoords); // May set _succeded to false buildFaces(node, mat, listTriangles, texcoords); // May set _succeded to false
#else
buildFaces(node, osg::Matrix(), listTriangles, texcoords); // May set _succeded to false
#endif
} }
popStateSet(node.getStateSet()); popStateSet(node.getStateSet());
//_nameStack.pop_back(); //_nameStack.pop_back();
@@ -1119,10 +968,8 @@ void WriterNodeVisitor::apply( osg::Billboard &node )
unsigned int count = node.getNumDrawables(); unsigned int count = node.getNumDrawables();
ListTriangle listTriangles; ListTriangle listTriangles;
bool texcoords = false; bool texcoords = false;
OSG_NOTICE << "Warning: 3DS writer is incomplete for Billboards (rotation not implemented)." << std::endl; osg::notify(osg::NOTICE) << "Warning: 3DS writer is incomplete for Billboards (rotation not implemented)." << std::endl;
#if DISABLE_3DS_ANIMATION
osg::Matrix m( osg::computeLocalToWorld(getNodePath()) ); osg::Matrix m( osg::computeLocalToWorld(getNodePath()) );
#endif
for ( unsigned int i = 0; i < count; i++ ) for ( unsigned int i = 0; i < count; i++ )
{ {
osg::Geometry *g = node.getDrawable( i )->asGeometry(); osg::Geometry *g = node.getDrawable( i )->asGeometry();
@@ -1136,15 +983,9 @@ void WriterNodeVisitor::apply( osg::Billboard &node )
popStateSet(g->getStateSet()); // May set _succeded to false popStateSet(g->getStateSet()); // May set _succeded to false
if (!succeeded()) break; if (!succeeded()) break;
osg::Matrix pointLocalMat(osg::Matrix::translate(node.getPosition(i))); // TODO handle rotation osg::Matrix currentBillBoardMat(osg::Matrix::translate(node.getPosition(i)) * m); // TODO handle rotation
#if DISABLE_3DS_ANIMATION apply3DSMatrixNode(node, currentBillBoardMat, "bil"); // Add a 3DS matrix node
osg::Matrix currentBillboardWorldMat(pointLocalMat * m); buildFaces(node, currentBillBoardMat, listTriangles, texcoords); // May set _succeded to false
apply3DSMatrixNode(node, &pointLocalMat, "bil"); // Add a 3DS matrix node (with local matrix)
buildFaces(node, currentBillboardWorldMat, listTriangles, texcoords); // May set _succeded to false
#else
apply3DSMatrixNode(node, &pointLocalMat, "bil"); // Add a 3DS matrix node (with local matrix)
buildFaces(node, osg::Matrix(), listTriangles, texcoords); // May set _succeded to false
#endif
if (!succeeded()) break; if (!succeeded()) break;
} }
} }
@@ -1161,12 +1002,7 @@ void WriterNodeVisitor::apply(osg::Group &node)
{ {
pushStateSet(node.getStateSet()); pushStateSet(node.getStateSet());
Lib3dsMeshInstanceNode * parent = _cur3dsNode; Lib3dsMeshInstanceNode * parent = _cur3dsNode;
#if DISABLE_3DS_ANIMATION apply3DSMatrixNode(node, osg::computeLocalToWorld(getNodePath()), "grp");
osg::Matrix mat( osg::computeLocalToWorld(getNodePath()) );
apply3DSMatrixNode(node, &mat, "grp");
#else
apply3DSMatrixNode(node, NULL, "grp");
#endif
if (succeeded()) if (succeeded())
traverse(node); traverse(node);
_cur3dsNode = parent; _cur3dsNode = parent;
@@ -1177,43 +1013,39 @@ void WriterNodeVisitor::apply(osg::MatrixTransform &node)
{ {
pushStateSet(node.getStateSet()); pushStateSet(node.getStateSet());
Lib3dsMeshInstanceNode * parent = _cur3dsNode; Lib3dsMeshInstanceNode * parent = _cur3dsNode;
#if DISABLE_3DS_ANIMATION apply3DSMatrixNode(node, osg::computeLocalToWorld(getNodePath()), "mtx");
osg::Matrix mat( osg::computeLocalToWorld(getNodePath()) );
#else
osg::Matrix mat( node.getMatrix() );
#endif
apply3DSMatrixNode(node, &mat, "mtx");
if (succeeded()) if (succeeded())
traverse(node); traverse(node);
_cur3dsNode = parent; _cur3dsNode = parent;
popStateSet(node.getStateSet()); popStateSet(node.getStateSet());
} }
void WriterNodeVisitor::apply3DSMatrixNode(osg::Node &node, const osg::Matrix * m, const char * const prefix) void WriterNodeVisitor::apply3DSMatrixNode(osg::Node &node, const osg::Matrix & m, const char * const prefix)
{ {
// Note: Creating a mesh instance with no transform and then copying the matrix doesn't work (matrix seems to be a temporary/computed value)
Lib3dsMeshInstanceNode * parent = _cur3dsNode; Lib3dsMeshInstanceNode * parent = _cur3dsNode;
Lib3dsMeshInstanceNode * node3ds = NULL;
if (m)
{
osg::Vec3 osgScl, osgPos;
osg::Quat osgRot, osgSo;
m->decompose(osgPos, osgRot, osgScl, osgSo);
float pos[3]; //const osg::Matrix & m = node.getMatrix();
float scl[3]; //const osg::Matrix m( osg::computeLocalToWorld(nodePath) ); // [NEEDS TESTING!] 3DS matrices always contain world to local transformation (not local transform; ie. from parent)
float rot[4];
copyOsgVectorToLib3dsVector(pos, osgPos);
copyOsgVectorToLib3dsVector(scl, osgScl);
copyOsgQuatToLib3dsQuat(rot, osgRot);
node3ds = lib3ds_node_new_mesh_instance(NULL, getUniqueName(node.getName().empty() ? node.className() : node.getName(), true, prefix).c_str(), pos, scl, rot);
}
else
{
node3ds = lib3ds_node_new_mesh_instance(NULL, getUniqueName(node.getName().empty() ? node.className() : node.getName(), true, prefix).c_str(), NULL, NULL, NULL);
}
lib3ds_file_append_node(_file3ds, reinterpret_cast<Lib3dsNode*>(node3ds), reinterpret_cast<Lib3dsNode*>(parent)); // Transform data used to be given to lib3ds_node_new_mesh_instance(), but it seems buggy (pivot problem? bug in conversion?).
float pos[3];
float scl[3];
float rot[4];
osg::Vec3 osgScl, osgPos;
osg::Quat osgRot, osgSo;
m.decompose(osgPos, osgRot, osgScl, osgSo);
copyOsgVectorToLib3dsVector(pos, osgPos);
copyOsgVectorToLib3dsVector(scl, osgScl);
copyOsgQuatToLib3dsQuat(rot, osgRot);
Lib3dsMeshInstanceNode * node3ds = lib3ds_node_new_mesh_instance
(NULL, getUniqueName(node.getName().empty() ? node.className() : node.getName(), prefix).c_str(), pos, scl, rot);
//// Create a mesh instance with no transform and then copy the matrix (doesn't work)
//Lib3dsMeshInstanceNode * node3ds = lib3ds_node_new_mesh_instance
// (NULL, getUniqueName(node.getName().empty() ? node.className() : node.getName(), "mtx").c_str(), NULL, NULL, NULL);
// copyOsgMatrixToLib3dsMatrix(node3ds->base.matrix, m);
lib3ds_file_append_node(file3ds, reinterpret_cast<Lib3dsNode*>(node3ds), reinterpret_cast<Lib3dsNode*>(parent));
_cur3dsNode = node3ds; _cur3dsNode = node3ds;
} }

View File

@@ -1,227 +1,222 @@
// -*-c++-*- // -*-c++-*-
/* /*
* 3DS reader/writer for Open Scene Graph * 3DS reader/writer for Open Scene Graph
* *
* Copyright (C) ??? * Copyright (C) ???
* *
* Writing support added 2009 by Sukender (Benoit Neil), http://sukender.free.fr, * Writing support added 2007 by Sukender (Benoit Neil), http://sukender.free.fr,
* strongly inspired by the OBJ writer object by Stephan Huber * strongly inspired by the OBJ writer object by Stephan Huber
* *
* The Open Scene Graph (OSG) is a cross platform C++/OpenGL library for * The Open Scene Graph (OSG) is a cross platform C++/OpenGL library for
* real-time rendering of large 3D photo-realistic models. * real-time rendering of large 3D photo-realistic models.
* The OSG homepage is http://www.openscenegraph.org/ * The OSG homepage is http://www.openscenegraph.org/
*/ */
#ifndef _3DS_WRITER_NODE_VISITOR_HEADER__ #ifndef _3DS_WRITER_NODE_VISITOR_HEADER__
#define _3DS_WRITER_NODE_VISITOR_HEADER__ #define _3DS_WRITER_NODE_VISITOR_HEADER__
#include <string> #include <string>
#include <stack> #include <stack>
#include <sstream> #include <sstream>
#include <osg/Notify> #include <osg/Notify>
#include <osg/Node> #include <osg/Node>
#include <osg/MatrixTransform> #include <osg/MatrixTransform>
#include <osg/Geode> #include <osg/Geode>
#include <osg/Geometry> #include <osg/Geometry>
#include <osg/StateSet> #include <osg/StateSet>
#include <osg/Material> #include <osg/Material>
#include <osg/Texture2D> #include <osg/Texture2D>
#include <osg/TexGen> #include <osg/TexGen>
#include <osg/TexMat> #include <osg/TexMat>
#include <osgDB/Registry> #include <osgDB/Registry>
#include <osgDB/ReadFile> #include <osgDB/ReadFile>
#include <osgDB/FileUtils> #include <osgDB/FileUtils>
#include <osgDB/FileNameUtils> #include <osgDB/FileNameUtils>
#include <map> #include <map>
#include "lib3ds/lib3ds.h" #include "lib3ds/lib3ds.h"
#include "WriterCompareTriangle.h" #include "WriterCompareTriangle.h"
#include <set> #include <set>
void copyOsgMatrixToLib3dsMatrix(Lib3dsMatrix lib3ds_matrix, const osg::Matrix& osg_matrix); void copyOsgMatrixToLib3dsMatrix(Lib3dsMatrix lib3ds_matrix, const osg::Matrix& osg_matrix);
typedef std::map<std::pair<unsigned int, unsigned int>, unsigned int> MapIndices; typedef std::map<std::pair<unsigned int, unsigned int>, unsigned int> MapIndices;
typedef std::vector<std::pair<Triangle, int> > ListTriangle; //the int is the drawable of the triangle typedef std::vector<std::pair<Triangle, int> > ListTriangle; //the int is the drawable of the triangle
namespace plugin3ds namespace plugin3ds
{ {
class WriterNodeVisitor: public osg::NodeVisitor class WriterNodeVisitor: public osg::NodeVisitor
{ {
public: public:
static const unsigned int MAX_VERTICES = 65000; static const unsigned int MAX_VERTICES = 65000;
static const unsigned int MAX_FACES = MAX_VERTICES; static const unsigned int MAX_FACES = MAX_VERTICES;
WriterNodeVisitor(Lib3dsFile * file3ds, const std::string & fileName, WriterNodeVisitor(Lib3dsFile * file3ds, const std::string & fileName,
const osgDB::ReaderWriter::Options* options, const osgDB::ReaderWriter::Options* options,
const std::string & srcDirectory); const std::string & srcDirectory);
bool succeeded() const { return _succeeded; } bool succeeded() const { return _succeeded; }
virtual void apply(osg::Geode &node); virtual void apply(osg::Geode &node);
virtual void apply(osg::Billboard &node); virtual void apply(osg::Billboard &node);
virtual void apply(osg::Group &node); virtual void apply(osg::Group &node);
virtual void apply(osg::MatrixTransform &node); virtual void apply(osg::MatrixTransform &node);
void traverse (osg::Node &node) void traverse (osg::Node &node)
{ {
pushStateSet(node.getStateSet()); pushStateSet(node.getStateSet());
osg::NodeVisitor::traverse( node ); osg::NodeVisitor::traverse( node );
popStateSet(node.getStateSet()); popStateSet(node.getStateSet());
} }
void pushStateSet(osg::StateSet* ss) void pushStateSet(osg::StateSet* ss)
{ {
if (NULL!=ss) { if (NULL!=ss) {
// Save our current stateset // Save our current stateset
_stateSetStack.push(_currentStateSet.get()); _stateSetStack.push(_currentStateSet.get());
// merge with node stateset // merge with node stateset
_currentStateSet = static_cast<osg::StateSet*>(_currentStateSet->clone(osg::CopyOp::SHALLOW_COPY)); _currentStateSet = static_cast<osg::StateSet*>(_currentStateSet->clone(osg::CopyOp::SHALLOW_COPY));
_currentStateSet->merge(*ss); _currentStateSet->merge(*ss);
} }
} }
void popStateSet(osg::StateSet* ss) void popStateSet(osg::StateSet* ss)
{ {
if (NULL!=ss) { if (NULL!=ss) {
// restore the previous stateset // restore the previous stateset
_currentStateSet = _stateSetStack.top(); _currentStateSet = _stateSetStack.top();
_stateSetStack.pop(); _stateSetStack.pop();
} }
} }
void writeMaterials(); void writeMaterials();
///\todo Add support for 2nd texture, opacity_map, bump_map, specular_map, shininess_map, self_illum_map, reflection_map. ///\todo Add support for 2nd texture, opacity_map, bump_map, specular_map, shininess_map, self_illum_map, reflection_map.
class Material { class Material {
public: public:
Material(WriterNodeVisitor & writerNodeVisitor, osg::StateSet * stateset, osg::Material* mat, osg::Texture* tex, int index=-1); Material(WriterNodeVisitor & writerNodeVisitor, osg::StateSet * stateset, osg::Material* mat, osg::Texture* tex, int index=-1);
int index; ///< Index in the 3DS file int index; ///< Index in the 3DS file
osg::Vec4 diffuse, ambient, specular; osg::Vec4 diffuse, ambient, specular;
float shininess; float shininess;
float transparency; float transparency;
bool double_sided; bool double_sided;
std::string name; std::string name;
osg::ref_ptr<osg::Image> image; osg::ref_ptr<osg::Image> image;
bool texture_transparency; bool texture_transparency;
bool texture_no_tile; bool texture_no_tile;
protected: protected:
Material() : index(-1) {} Material() : index(-1) {}
}; };
protected: protected:
struct CompareStateSet struct CompareStateSet
{ {
bool operator()(const osg::ref_ptr<osg::StateSet>& ss1, const osg::ref_ptr<osg::StateSet>& ss2) const bool operator()(const osg::ref_ptr<osg::StateSet>& ss1, const osg::ref_ptr<osg::StateSet>& ss2) const
{ {
return *ss1 < *ss2; return *ss1 < *ss2;
} }
}; };
private: private:
WriterNodeVisitor& operator = (const WriterNodeVisitor&) { return *this; } WriterNodeVisitor& operator = (const WriterNodeVisitor&) { return *this; }
/** /**
* Fill the faces field of the mesh and call buildMesh(). * Fill the faces field of the mesh and call buildMesh().
* \param geo is the geode who contain vertice and faces. * \param geo is the geode who contain vertice and faces.
* \param mat Local to world matrix applied to the geode * \param mat Local to world matrix applied to the geode
* \param listTriangles contain all the meshs faces. * \param listTriangles contain all the meshs faces.
* \param texcoords tell us if we have to treat texture coord. * \param texcoords tell us if we have to treat texture coord.
*/ */
void buildFaces(osg::Geode & geo, const osg::Matrix & mat, ListTriangle & listTriangles, bool texcoords); void buildFaces(osg::Geode & geo, const osg::Matrix & mat, ListTriangle & listTriangles, bool texcoords);
/** /**
* Calculate the number of vertices in the geode. * Calculate the number of vertices in the geode.
* \return the number of vertices in the geode. * \return the number of vertices in the geode.
*/ */
unsigned int calcVertices(osg::Geode & geo); unsigned int calcVertices(osg::Geode & geo);
/** /**
* Build a mesh * Build a mesh
* \param geo is the geode who contain vertice and faces * \param geo is the geode who contain vertice and faces
* \param mat Local to world matrix applied to the geode * \param mat Local to world matrix applied to the geode
* \param index_vert is the index used to build the new mesh * \param index_vert is the index used to build the new mesh
* \param texcoords tell us if we have to treat texture coord * \param texcoords tell us if we have to treat texture coord
* \param mesh is the mesh with faces filled * \param mesh is the mesh with faces filled
* \sa See cutScene() about the definition of the boxes for faces sorting. * \sa See cutScene() about the definition of the boxes for faces sorting.
*/ */
void void
buildMesh(osg::Geode & geo, buildMesh(osg::Geode & geo,
const osg::Matrix & mat, const osg::Matrix & mat,
MapIndices & index_vert, MapIndices & index_vert,
bool texcoords, bool texcoords,
Lib3dsMesh *mesh); Lib3dsMesh *mesh);
/** /**
* Add a vertice to the index and link him with the Triangle index and the drawable. * Add a vertice to the index and link him with the Triangle index and the drawable.
* \param index_vert is the map where the vertice are stored. * \param index_vert is the map where the vertice are stored.
* \param index is the indice of the vertice's position in the vec3. * \param index is the indice of the vertice's position in the vec3.
* \param drawable_n is the number of the drawable. * \param drawable_n is the number of the drawable.
* \return the position of the vertice in the final mesh. * \return the position of the vertice in the final mesh.
*/ */
unsigned int unsigned int
getMeshIndexForGeometryIndex(MapIndices & index_vert, getMeshIndexForGeometryIndex(MapIndices & index_vert,
unsigned int index, unsigned int index,
unsigned int drawable_n); unsigned int drawable_n);
/** /**
* Create the list of faces from the geode. * Create the list of faces from the geode.
* \param geo is the geode to study. * \param geo is the geode to study.
* \param listTriangles is the list to fill. * \param listTriangles is the list to fill.
* \param texcoords tell us if we have to treat texture coord. * \param texcoords tell us if we have to treat texture coord.
* \param drawable_n tell us which drawable we are building. * \param drawable_n tell us which drawable we are building.
*/ */
void createListTriangle(osg::Geometry * geo, void createListTriangle(osg::Geometry * geo,
ListTriangle & listTriangles, ListTriangle & listTriangles,
bool & texcoords, bool & texcoords,
unsigned int & drawable_n); unsigned int & drawable_n);
int processStateSet(osg::StateSet* stateset); int processStateSet(osg::StateSet* stateset);
std::string getUniqueName(const std::string& defaultvalue, bool isNodeName, const std::string & defaultPrefix = "", int currentPrefixLen = -1); std::string getUniqueName(const std::string& defaultvalue="", const std::string & defaultPrefix = "", bool nameIsPath = false);
std::string export3DSTexture(const osg::Image * image, const std::string & fileName); std::string export3DSTexture(const osg::Image * image, const std::string & fileName);
typedef std::stack<osg::ref_ptr<osg::StateSet> > StateSetStack; typedef std::stack<osg::ref_ptr<osg::StateSet> > StateSetStack;
typedef std::map< osg::ref_ptr<osg::StateSet>, Material, CompareStateSet> MaterialMap; typedef std::map< osg::ref_ptr<osg::StateSet>, Material, CompareStateSet> MaterialMap;
void apply3DSMatrixNode(osg::Node &node, const osg::Matrix * m, const char * const prefix); void apply3DSMatrixNode(osg::Node &node, const osg::Matrix & m, const char * const prefix);
bool _succeeded; bool _succeeded;
std::string _directory; std::string _directory;
std::string _srcDirectory; std::string _srcDirectory;
Lib3dsFile * _file3ds; Lib3dsFile * file3ds;
StateSetStack _stateSetStack; StateSetStack _stateSetStack;
osg::ref_ptr<osg::StateSet> _currentStateSet; osg::ref_ptr<osg::StateSet> _currentStateSet;
typedef std::map<std::string, unsigned int> PrefixMap; std::map<std::string, unsigned int> _mapPrefix; ///< List of next number to use in unique name generation, for each prefix
PrefixMap _nodePrefixMap; ///< List of next number to use in unique name generation, for each prefix std::set<std::string> _nameMap;
PrefixMap _imagePrefixMap; MaterialMap _materialMap;
typedef std::set<std::string> NameMap; unsigned int _lastMaterialIndex;
NameMap _nodeNameMap; unsigned int _lastMeshIndex;
NameMap _imageNameMap; Lib3dsMeshInstanceNode * _cur3dsNode;
MaterialMap _materialMap; const osgDB::ReaderWriter::Options* options;
unsigned int _lastMaterialIndex; unsigned int _imageCount;
unsigned int _lastMeshIndex; bool _extendedFilePaths;
Lib3dsMeshInstanceNode * _cur3dsNode; std::set<osg::Image *> _imageSet;
const osgDB::ReaderWriter::Options* _options; };
unsigned int _imageCount;
bool _extendedFilePaths; // end namespace plugin3ds
typedef std::map<osg::Image*, std::string> ImageSet; }
ImageSet _imageSet; ///< Map used to avoid renaming and writing twice an image
}; #endif
// end namespace plugin3ds
}
#endif

View File

@@ -788,6 +788,8 @@ extern LIB3DSAPI void lib3ds_matrix_rotate(float m[4][4], float angle, float ax,
extern LIB3DSAPI void lib3ds_matrix_camera(float m[4][4], float pos[3], float tgt[3], float roll); extern LIB3DSAPI void lib3ds_matrix_camera(float m[4][4], float pos[3], float tgt[3], float roll);
/* --- Code for OpenSceneGraph --- */ /* --- Code for OpenSceneGraph --- */
extern LIB3DSAPI void setByteOrder();
/* Definitions for compatibility with previous lib3DS used: */ /* Definitions for compatibility with previous lib3DS used: */
typedef float Lib3dsMatrix[4][4]; typedef float Lib3dsMatrix[4][4];
typedef float Lib3dsVector[3]; typedef float Lib3dsVector[3];

View File

@@ -446,14 +446,13 @@ mdata_read(Lib3dsFile *file, Lib3dsIo *io) {
static int static int
compare_node_id( const void *a, const void *b ) { compare_node_id( const void *a, const void *b ) {
return (int)((*((Lib3dsNode**)a))->node_id) - (int)((*((Lib3dsNode**)b))->node_id); return (*((Lib3dsNode**)a))->node_id - (*((Lib3dsNode**)b))->node_id;
} }
static int static int
compare_node_id2( const void *a, const void *b ) { compare_node_id2( const void *a, const void *b ) {
// not a is a pointer in the calling bsearch routine the user_id is an unsigned, while the node_id is an unsigned short?! return *((unsigned short*)a) - (*((Lib3dsNode**)b))->node_id;
return (int)(*((unsigned*)a)) - (int)((*((Lib3dsNode**)b))->node_id);
} }

View File

@@ -35,11 +35,7 @@
#endif #endif
#ifndef _MSC_VER #ifndef _MSC_VER
#if defined __sun || defined __hpux
#include <inttypes.h>
#else
#include <stdint.h> #include <stdint.h>
#endif
#else #else
typedef unsigned __int8 uint8_t; typedef unsigned __int8 uint8_t;
typedef unsigned __int16 uint16_t; typedef unsigned __int16 uint16_t;

View File

@@ -17,6 +17,16 @@
*/ */
#include "lib3ds_impl.h" #include "lib3ds_impl.h"
/* --- Code for OpenSceneGraph --- */
#include "lib3ds.h" // For setByteOrder()
#include <osg/Endian>
static bool s_requiresByteSwap = false;
extern LIB3DSAPI void setByteOrder()
{
s_requiresByteSwap = osg::getCpuByteOrder()==osg::BigEndian;
}
/* --- (end) Code for OpenSceneGraph --- */
typedef union { typedef union {
uint32_t dword_value; uint32_t dword_value;
@@ -161,6 +171,12 @@ lib3ds_io_read_word(Lib3dsIo *io) {
lib3ds_io_read(io, b, 2); lib3ds_io_read(io, b, 2);
w = ((uint16_t)b[1] << 8) | w = ((uint16_t)b[1] << 8) |
((uint16_t)b[0]); ((uint16_t)b[0]);
/* --- Code for OpenSceneGraph --- */
if (s_requiresByteSwap)
{
osg::swapBytes2((char*)&w);
}
/* --- (end) Code for OpenSceneGraph --- */
return(w); return(w);
} }
@@ -179,6 +195,12 @@ lib3ds_io_read_dword(Lib3dsIo *io) {
((uint32_t)b[2] << 16) | ((uint32_t)b[2] << 16) |
((uint32_t)b[1] << 8) | ((uint32_t)b[1] << 8) |
((uint32_t)b[0]); ((uint32_t)b[0]);
/* --- Code for OpenSceneGraph --- */
if (s_requiresByteSwap)
{
osg::swapBytes4((char*)&d);
}
/* --- (end) Code for OpenSceneGraph --- */
return(d); return(d);
} }
@@ -208,6 +230,12 @@ lib3ds_io_read_intw(Lib3dsIo *io) {
lib3ds_io_read(io, b, 2); lib3ds_io_read(io, b, 2);
w = ((uint16_t)b[1] << 8) | w = ((uint16_t)b[1] << 8) |
((uint16_t)b[0]); ((uint16_t)b[0]);
/* --- Code for OpenSceneGraph --- */
if (s_requiresByteSwap)
{
osg::swapBytes2((char*)&w);
}
/* --- (end) Code for OpenSceneGraph --- */
return((int16_t)w); return((int16_t)w);
} }
@@ -226,6 +254,12 @@ lib3ds_io_read_intd(Lib3dsIo *io) {
((uint32_t)b[2] << 16) | ((uint32_t)b[2] << 16) |
((uint32_t)b[1] << 8) | ((uint32_t)b[1] << 8) |
((uint32_t)b[0]); ((uint32_t)b[0]);
/* --- Code for OpenSceneGraph --- */
if (s_requiresByteSwap)
{
osg::swapBytes4((char*)&d);
}
/* --- (end) Code for OpenSceneGraph --- */
return((int32_t)d); return((int32_t)d);
} }
@@ -244,6 +278,12 @@ lib3ds_io_read_float(Lib3dsIo *io) {
((uint32_t)b[2] << 16) | ((uint32_t)b[2] << 16) |
((uint32_t)b[1] << 8) | ((uint32_t)b[1] << 8) |
((uint32_t)b[0]); ((uint32_t)b[0]);
/* --- Code for OpenSceneGraph --- */
if (s_requiresByteSwap)
{
osg::swapBytes4((char*)&(d.dword_value));
}
/* --- (end) Code for OpenSceneGraph --- */
return d.float_value; return d.float_value;
} }
@@ -320,11 +360,18 @@ lib3ds_io_write_byte(Lib3dsIo *io, uint8_t b) {
*/ */
void void
lib3ds_io_write_word(Lib3dsIo *io, uint16_t w) { lib3ds_io_write_word(Lib3dsIo *io, uint16_t w) {
/* --- Code for OpenSceneGraph --- */
if (s_requiresByteSwap)
{
osg::swapBytes2((char*)&w);
}
/* --- (end) Code for OpenSceneGraph --- */
uint8_t b[2]; uint8_t b[2];
assert(io); assert(io);
b[1] = uint8_t((w & 0xFF00) >> 8); b[1] = ((uint16_t)w & 0xFF00) >> 8;
b[0] = uint8_t(w & 0x00FF); b[0] = ((uint16_t)w & 0x00FF);
if (lib3ds_io_write(io, b, 2) != 2) { if (lib3ds_io_write(io, b, 2) != 2) {
lib3ds_io_write_error(io); lib3ds_io_write_error(io);
} }
@@ -336,6 +383,12 @@ lib3ds_io_write_word(Lib3dsIo *io, uint16_t w) {
*/ */
void void
lib3ds_io_write_dword(Lib3dsIo *io, uint32_t d) { lib3ds_io_write_dword(Lib3dsIo *io, uint32_t d) {
/* --- Code for OpenSceneGraph --- */
if (s_requiresByteSwap)
{
osg::swapBytes4((char*)&d);
}
/* --- (end) Code for OpenSceneGraph --- */
uint8_t b[4]; uint8_t b[4];
assert(io); assert(io);
@@ -366,11 +419,17 @@ lib3ds_io_write_intb(Lib3dsIo *io, int8_t b) {
*/ */
void void
lib3ds_io_write_intw(Lib3dsIo *io, int16_t w) { lib3ds_io_write_intw(Lib3dsIo *io, int16_t w) {
/* --- Code for OpenSceneGraph --- */
if (s_requiresByteSwap)
{
osg::swapBytes2((char*)&w);
}
/* --- (end) Code for OpenSceneGraph --- */
uint8_t b[2]; uint8_t b[2];
assert(io); assert(io);
b[1] = uint8_t((w & 0xFF00) >> 8); b[1] = ((uint16_t)w & 0xFF00) >> 8;
b[0] = uint8_t(w & 0x00FF); b[0] = ((uint16_t)w & 0x00FF);
if (lib3ds_io_write(io, b, 2) != 2) { if (lib3ds_io_write(io, b, 2) != 2) {
lib3ds_io_write_error(io); lib3ds_io_write_error(io);
} }
@@ -382,6 +441,12 @@ lib3ds_io_write_intw(Lib3dsIo *io, int16_t w) {
*/ */
void void
lib3ds_io_write_intd(Lib3dsIo *io, int32_t d) { lib3ds_io_write_intd(Lib3dsIo *io, int32_t d) {
/* --- Code for OpenSceneGraph --- */
if (s_requiresByteSwap)
{
osg::swapBytes4((char*)&d);
}
/* --- (end) Code for OpenSceneGraph --- */
uint8_t b[4]; uint8_t b[4];
assert(io); assert(io);
@@ -400,11 +465,17 @@ lib3ds_io_write_intd(Lib3dsIo *io, int32_t d) {
*/ */
void void
lib3ds_io_write_float(Lib3dsIo *io, float l) { lib3ds_io_write_float(Lib3dsIo *io, float l) {
uint8_t b[4]; uint8_t b[4];
Lib3dsDwordFloat d; Lib3dsDwordFloat d;
assert(io); assert(io);
d.float_value = l; d.float_value = l;
/* --- Code for OpenSceneGraph --- */
if (s_requiresByteSwap)
{
osg::swapBytes4((char*)&d.dword_value);
}
/* --- (end) Code for OpenSceneGraph --- */
b[3] = (uint8_t)(((uint32_t)d.dword_value & 0xFF000000) >> 24); b[3] = (uint8_t)(((uint32_t)d.dword_value & 0xFF000000) >> 24);
b[2] = (uint8_t)(((uint32_t)d.dword_value & 0x00FF0000) >> 16); b[2] = (uint8_t)(((uint32_t)d.dword_value & 0x00FF0000) >> 16);
b[1] = (uint8_t)(((uint32_t)d.dword_value & 0x0000FF00) >> 8); b[1] = (uint8_t)(((uint32_t)d.dword_value & 0x0000FF00) >> 8);

View File

@@ -166,7 +166,7 @@ lib3ds_node_new_mesh_instance(Lib3dsMesh *mesh, const char *instance_name, float
Lib3dsCameraNode* Lib3dsCameraNode*
lib3ds_node_new_camera(Lib3dsCamera *camera) { lib3ds_node_new_camera(Lib3dsCamera *camera) {
Lib3dsNode *node; Lib3dsNode *node = lib3ds_node_new(LIB3DS_NODE_CAMERA);
Lib3dsCameraNode *n; Lib3dsCameraNode *n;
assert(camera); assert(camera);

View File

@@ -235,7 +235,7 @@ setup_segment(Lib3dsTrack *track, int index, Lib3dsKey *pp, Lib3dsKey *p0, Lib3d
*pp = track->keys[track->nkeys - 2]; *pp = track->keys[track->nkeys - 2];
pp->frame = track->keys[track->nkeys - 2].frame - (track->keys[track->nkeys - 1].frame - track->keys[0].frame); pp->frame = track->keys[track->nkeys - 2].frame - (track->keys[track->nkeys - 1].frame - track->keys[0].frame);
} }
else ip = -1; // Avoids a compiler warning else ip = -1; // Avoids a compiler warning
} }
*p0 = track->keys[index - 1]; *p0 = track->keys[index - 1];
@@ -250,7 +250,6 @@ setup_segment(Lib3dsTrack *track, int index, Lib3dsKey *pp, Lib3dsKey *p0, Lib3d
*pn = track->keys[1]; *pn = track->keys[1];
pn->frame = track->keys[1].frame + (track->keys[track->nkeys-1].frame - track->keys[0].frame); pn->frame = track->keys[1].frame + (track->keys[track->nkeys-1].frame - track->keys[0].frame);
} }
else in = -1; // Avoids a compiler warning
} }
if (track->type == LIB3DS_TRACK_QUAT) { if (track->type == LIB3DS_TRACK_QUAT) {

View File

@@ -316,35 +316,6 @@ class Replicate : public Record
REGISTER_FLTRECORD(Replicate, REPLICATE_OP) REGISTER_FLTRECORD(Replicate, REPLICATE_OP)
/** IndexedString -
*/
class IndexedString : public Record
{
public:
IndexedString() {}
META_Record(IndexedString)
protected:
virtual ~IndexedString() {}
virtual void readRecord(RecordInputStream& in, Document& /*document*/)
{
std::streamsize size = in.getRecordSize();
uint32 index = in.readUInt32();
std::string name = in.readString(size-8);
if (_parent.valid())
_parent->setMultiSwitchValueName(index, name);
}
};
REGISTER_FLTRECORD(IndexedString, INDEXED_STRING_OP)
// Prevent "unknown record" message for the following ancillary records: // Prevent "unknown record" message for the following ancillary records:
REGISTER_FLTRECORD(DummyRecord, OLD_TRANSLATE2_OP) REGISTER_FLTRECORD(DummyRecord, OLD_TRANSLATE2_OP)
REGISTER_FLTRECORD(DummyRecord, OLD_ROTATE_ABOUT_POINT_OP) REGISTER_FLTRECORD(DummyRecord, OLD_ROTATE_ABOUT_POINT_OP)
@@ -356,6 +327,7 @@ REGISTER_FLTRECORD(DummyRecord, OLD_ROTATE_ABOUT_POINT2_OP)
REGISTER_FLTRECORD(DummyRecord, OLD_ROTATE_SCALE_TO_POINT_OP) REGISTER_FLTRECORD(DummyRecord, OLD_ROTATE_SCALE_TO_POINT_OP)
REGISTER_FLTRECORD(DummyRecord, OLD_PUT_TRANSFORM_OP) REGISTER_FLTRECORD(DummyRecord, OLD_PUT_TRANSFORM_OP)
REGISTER_FLTRECORD(DummyRecord, OLD_BOUNDING_BOX_OP) REGISTER_FLTRECORD(DummyRecord, OLD_BOUNDING_BOX_OP)
REGISTER_FLTRECORD(DummyRecord, INDEXED_STRING_OP)
REGISTER_FLTRECORD(DummyRecord, ROAD_ZONE_OP) REGISTER_FLTRECORD(DummyRecord, ROAD_ZONE_OP)
REGISTER_FLTRECORD(DummyRecord, ROTATE_ABOUT_EDGE_OP) REGISTER_FLTRECORD(DummyRecord, ROTATE_ABOUT_EDGE_OP)
REGISTER_FLTRECORD(DummyRecord, TRANSLATE_OP) REGISTER_FLTRECORD(DummyRecord, TRANSLATE_OP)

View File

@@ -1,3 +1,6 @@
#this file is automatically generated
SET(TARGET_SRC SET(TARGET_SRC
AncillaryRecords.cpp AncillaryRecords.cpp
AttrData.cpp AttrData.cpp

View File

@@ -26,7 +26,6 @@ Document::Document() :
_replaceClampWithClampToEdge(false), _replaceClampWithClampToEdge(false),
_preserveFace(false), _preserveFace(false),
_preserveObject(false), _preserveObject(false),
_replaceDoubleSidedPolys(false),
_defaultDOFAnimationState(false), _defaultDOFAnimationState(false),
_useTextureAlphaForTransparancyBinning(true), _useTextureAlphaForTransparancyBinning(true),
_useBillboardCenter(false), _useBillboardCenter(false),
@@ -84,7 +83,7 @@ void Document::pushExtension()
{ {
if (!_currentPrimaryRecord.valid()) if (!_currentPrimaryRecord.valid())
{ {
OSG_WARN << "No current primary in Document::pushExtension()." << std::endl; osg::notify(osg::WARN) << "No current primary in Document::pushExtension()." << std::endl;
return; return;
} }
@@ -96,7 +95,7 @@ void Document::popExtension()
_currentPrimaryRecord=_extensionStack.back().get(); _currentPrimaryRecord=_extensionStack.back().get();
if (!_currentPrimaryRecord.valid()) if (!_currentPrimaryRecord.valid())
{ {
OSG_WARN << "Can't decide primary in Document::popExtension()." << std::endl; osg::notify(osg::WARN) << "Can't decide primary in Document::popExtension()." << std::endl;
return; return;
} }
@@ -119,7 +118,7 @@ void Document::setSubSurfacePolygonOffset(int level, osg::PolygonOffset* po)
osg::PolygonOffset* Document::getSubSurfacePolygonOffset(int level) osg::PolygonOffset* Document::getSubSurfacePolygonOffset(int level)
{ {
OSG_DEBUG<<"Document::getSubSurfacePolygonOffset("<<level<<")"<<std::endl; osg::notify(osg::DEBUG_INFO)<<"Document::getSubSurfacePolygonOffset("<<level<<")"<<std::endl;
osg::ref_ptr<osg::PolygonOffset>& po = _subsurfacePolygonOffsets[level]; osg::ref_ptr<osg::PolygonOffset>& po = _subsurfacePolygonOffsets[level];
if (!po) if (!po)
{ {

View File

@@ -182,8 +182,6 @@ class Document
bool getPreserveFace() const { return _preserveFace; } bool getPreserveFace() const { return _preserveFace; }
void setPreserveObject(bool flag) { _preserveObject = flag; } void setPreserveObject(bool flag) { _preserveObject = flag; }
bool getPreserveObject() const { return _preserveObject; } bool getPreserveObject() const { return _preserveObject; }
void setReplaceDoubleSidedPolys(bool flag) { _replaceDoubleSidedPolys = flag; }
bool getReplaceDoubleSidedPolys() const { return _replaceDoubleSidedPolys; }
void setDefaultDOFAnimationState(bool state) { _defaultDOFAnimationState = state; } void setDefaultDOFAnimationState(bool state) { _defaultDOFAnimationState = state; }
bool getDefaultDOFAnimationState() const { return _defaultDOFAnimationState; } bool getDefaultDOFAnimationState() const { return _defaultDOFAnimationState; }
void setUseTextureAlphaForTransparancyBinning(bool flag) { _useTextureAlphaForTransparancyBinning=flag; } void setUseTextureAlphaForTransparancyBinning(bool flag) { _useTextureAlphaForTransparancyBinning=flag; }
@@ -208,7 +206,6 @@ class Document
bool _replaceClampWithClampToEdge; bool _replaceClampWithClampToEdge;
bool _preserveFace; bool _preserveFace;
bool _preserveObject; bool _preserveObject;
bool _replaceDoubleSidedPolys;
bool _defaultDOFAnimationState; bool _defaultDOFAnimationState;
bool _useTextureAlphaForTransparancyBinning; bool _useTextureAlphaForTransparancyBinning;
bool _useBillboardCenter; bool _useBillboardCenter;

View File

@@ -153,20 +153,20 @@ ExportOptions::parseOptionsString()
// See if it's a Boolen/toggle // See if it's a Boolen/toggle
if ( token == _validateOption ) if ( token == _validateOption )
{ {
OSG_INFO << "fltexp: Found: " << token << std::endl; osg::notify( osg::INFO ) << "fltexp: Found: " << token << std::endl;
setValidateOnly( true ); setValidateOnly( true );
continue; continue;
} }
if ( token == _stripTextureFilePathOption ) if ( token == _stripTextureFilePathOption )
{ {
OSG_INFO << "fltexp: Found: " << token << std::endl; osg::notify( osg::INFO ) << "fltexp: Found: " << token << std::endl;
setStripTextureFilePath( true ); setStripTextureFilePath( true );
continue; continue;
} }
// Protect against unrecognized options without values // Protect against unrecognized options without values
if ( pos == str.npos ) if ( pos == str.npos )
{ {
OSG_WARN << "fltexp: Bogus OptionString: " << token << std::endl; osg::notify( osg::WARN ) << "fltexp: Bogus OptionString: " << token << std::endl;
continue; continue;
} }
@@ -187,19 +187,19 @@ ExportOptions::parseOptionsString()
if (token == _versionOption) if (token == _versionOption)
{ {
OSG_INFO << "fltexp: Token: " << token << ", Value: " << value << std::endl; osg::notify( osg::INFO ) << "fltexp: Token: " << token << ", Value: " << value << std::endl;
int version( VERSION_16_1 ); int version( VERSION_16_1 );
if( value == std::string( "15.7" ) ) if( value == std::string( "15.7" ) )
version = VERSION_15_7; version = VERSION_15_7;
else if( value == std::string( "15.8" ) ) else if( value == std::string( "15.8" ) )
version = VERSION_15_8; version = VERSION_15_8;
else if( value != std::string( "16.1" ) ) else if( value != std::string( "16.1" ) )
OSG_WARN << "fltexp: Unsupported version: " << value << ". Defaulting to 16.1." << std::endl; osg::notify( osg::WARN ) << "fltexp: Unsupported version: " << value << ". Defaulting to 16.1." << std::endl;
setFlightFileVersionNumber( version ); setFlightFileVersionNumber( version );
} }
else if (token == _unitsOption) else if (token == _unitsOption)
{ {
OSG_INFO << "fltexp: Token: " << token << ", Value: " << value << std::endl; osg::notify( osg::INFO ) << "fltexp: Token: " << token << ", Value: " << value << std::endl;
FlightUnits units( METERS ); FlightUnits units( METERS );
if( value == std::string( "KILOMETERS" ) ) if( value == std::string( "KILOMETERS" ) )
units = KILOMETERS; units = KILOMETERS;
@@ -210,26 +210,26 @@ ExportOptions::parseOptionsString()
else if( value == std::string( "NAUTICAL_MILES" ) ) else if( value == std::string( "NAUTICAL_MILES" ) )
units = NAUTICAL_MILES; units = NAUTICAL_MILES;
else if( value != std::string( "METERS" ) ) else if( value != std::string( "METERS" ) )
OSG_WARN << "fltexp: Unsupported units: " << value << ". Defaulting to METERS." << std::endl; osg::notify( osg::WARN ) << "fltexp: Unsupported units: " << value << ". Defaulting to METERS." << std::endl;
setFlightUnits( units ); setFlightUnits( units );
} }
else if (token == _tempDirOption) else if (token == _tempDirOption)
{ {
OSG_INFO << "fltexp: Token: " << token << ", Value: " << value << std::endl; osg::notify( osg::INFO ) << "fltexp: Token: " << token << ", Value: " << value << std::endl;
setTempDir( value ); setTempDir( value );
} }
else if (token == _lightingOption) else if (token == _lightingOption)
{ {
OSG_INFO << "fltexp: Token: " << token << ", Value: " << value << std::endl; osg::notify( osg::INFO ) << "fltexp: Token: " << token << ", Value: " << value << std::endl;
bool lighting( true ); bool lighting( true );
if (value == std::string( "OFF" ) ) if (value == std::string( "OFF" ) )
lighting = false; lighting = false;
else if (value != std::string( "ON" ) ) else if (value != std::string( "ON" ) )
OSG_WARN << "fltexp: Unsupported lighting value: " << value << ". Defaulting to ON." << std::endl; osg::notify( osg::WARN ) << "fltexp: Unsupported lighting value: " << value << ". Defaulting to ON." << std::endl;
setLightingDefault( lighting ); setLightingDefault( lighting );
} }
else else
OSG_WARN << "fltexp: Bogus OptionString: " << token << std::endl; osg::notify( osg::WARN ) << "fltexp: Bogus OptionString: " << token << std::endl;
} }
} }

View File

@@ -21,6 +21,7 @@
#include <osg/Node> #include <osg/Node>
#include <osg/Notify> #include <osg/Notify>
#include <osgDB/ReaderWriter>
#include <osgDB/FileNameUtils> #include <osgDB/FileNameUtils>
#include <string> #include <string>

View File

@@ -117,12 +117,12 @@ FltExportVisitor::~FltExportVisitor()
// Delete our temp file. // Delete our temp file.
if (_recordsStr.is_open()) if (_recordsStr.is_open())
{ {
OSG_WARN << "fltexp: FltExportVisitor destructor has an open temp file." << std::endl; osg::notify( osg::WARN ) << "fltexp: FltExportVisitor destructor has an open temp file." << std::endl;
// This should not happen. FltExportVisitor::complete should close // This should not happen. FltExportVisitor::complete should close
// this file before we get to this destructor. // this file before we get to this destructor.
return; return;
} }
OSG_INFO << "fltexp: Deleting temp file " << _recordsTempName << std::endl; osg::notify( osg::INFO ) << "fltexp: Deleting temp file " << _recordsTempName << std::endl;
FLTEXP_DELETEFILE( _recordsTempName.c_str() ); FLTEXP_DELETEFILE( _recordsTempName.c_str() );
} }
@@ -356,7 +356,7 @@ FltExportVisitor::apply( osg::Geode& node )
if (!geom) if (!geom)
{ {
std::string warning( "fltexp: Non-Geometry Drawable encountered. Ignoring." ); std::string warning( "fltexp: Non-Geometry Drawable encountered. Ignoring." );
OSG_WARN << warning << std::endl; osg::notify( osg::WARN ) << warning << std::endl;
_fltOpt->getWriteResult().warn( warning ); _fltOpt->getWriteResult().warn( warning );
continue; continue;
} }
@@ -391,7 +391,7 @@ FltExportVisitor::apply( osg::Geode& node )
else else
{ {
std::string warning( "fltexp: Unknown PrimitiveSet type." ); std::string warning( "fltexp: Unknown PrimitiveSet type." );
OSG_WARN << warning << std::endl; osg::notify( osg::WARN ) << warning << std::endl;
_fltOpt->getWriteResult().warn( warning ); _fltOpt->getWriteResult().warn( warning );
return; return;
} }
@@ -429,7 +429,7 @@ FltExportVisitor::apply( osg::Geode& node )
else else
{ {
std::string warning( "fltexp: Unknown PrimitiveSet type." ); std::string warning( "fltexp: Unknown PrimitiveSet type." );
OSG_WARN << warning << std::endl; osg::notify( osg::WARN ) << warning << std::endl;
_fltOpt->getWriteResult().warn( warning ); _fltOpt->getWriteResult().warn( warning );
return; return;
} }
@@ -461,7 +461,7 @@ FltExportVisitor::apply( osg::Node& node )
// would export a Group record then continue traversal. Because we are // would export a Group record then continue traversal. Because we are
// a Node, there's no way to continue traversal, so just return.) // a Node, there's no way to continue traversal, so just return.)
std::string warning( "fltexp: Unknown Node in OpenFlight export." ); std::string warning( "fltexp: Unknown Node in OpenFlight export." );
OSG_WARN << warning << std::endl; osg::notify( osg::WARN ) << warning << std::endl;
_fltOpt->getWriteResult().warn( warning ); _fltOpt->getWriteResult().warn( warning );
return; return;
} }

View File

@@ -136,8 +136,7 @@ public:
void writeMeshPrimitive( const std::vector<unsigned int>& indices, GLenum mode ); void writeMeshPrimitive( const std::vector<unsigned int>& indices, GLenum mode );
void writeLocalVertexPool( const osg::Geometry& geom ); void writeLocalVertexPool( const osg::Geometry& geom );
void writeMultitexture( const osg::Geometry& geom ); void writeMultitexture( const osg::Geometry& geom );
void writeUVList( int numVerts, const osg::Geometry& geom, const std::vector<unsigned int>& indices ); void writeUVList( int numVerts, const osg::Geometry& geom );
void writeUVList( int numVerts, const osg::Geometry& geom, unsigned int first=0);
// Light Point records // Light Point records
void writeLightPoint(); void writeLightPoint();

View File

@@ -29,108 +29,8 @@
#include "Document.h" #include "Document.h"
#include "RecordInputStream.h" #include "RecordInputStream.h"
#include <algorithm>
namespace flt { namespace flt {
template<class ARRAY>
void reverseWindingOrder( ARRAY* data, GLenum mode, GLint first, GLint last )
{
switch( mode )
{
case osg::PrimitiveSet::TRIANGLES:
case osg::PrimitiveSet::QUADS:
case osg::PrimitiveSet::POLYGON:
// reverse all the vertices.
std::reverse(data->begin()+first, data->begin()+last);
break;
case osg::PrimitiveSet::TRIANGLE_STRIP:
case osg::PrimitiveSet::QUAD_STRIP:
// reverse only the shared edges.
for( GLint i = first; i < last-1; i+=2 )
{
std::swap( (*data)[i], (*data)[i+1] );
}
break;
case osg::PrimitiveSet::TRIANGLE_FAN:
// reverse all vertices except the first vertex.
std::reverse(data->begin()+first+1, data->begin()+last);
break;
}
}
void addDrawableAndReverseWindingOrder( osg::Geode* geode )
{
// Replace double sided polygons by duplicating the drawables and inverting the normals.
std::vector<osg::Geometry*> new_drawables;
for (size_t i=0; i<geode->getNumDrawables(); ++i)
{
const osg::Geometry* geometry = dynamic_cast<const osg::Geometry*>(geode->getDrawable(i));
if(geometry)
{
osg::Geometry* geom = new osg::Geometry(*geometry
, osg::CopyOp::DEEP_COPY_ARRAYS | osg::CopyOp::DEEP_COPY_PRIMITIVES);
new_drawables.push_back(geom);
for( size_t i = 0; i < geom->getNumPrimitiveSets( ); ++i )
{
osg::DrawArrays* drawarray = dynamic_cast<osg::DrawArrays*>( geom->getPrimitiveSet( i ) );
if( drawarray )
{
GLint first = drawarray->getFirst();
GLint last = drawarray->getFirst()+drawarray->getCount();
// Invert vertex order.
osg::Vec3Array* vertices = dynamic_cast<osg::Vec3Array*>(geom->getVertexArray());
if( vertices )
{
reverseWindingOrder( vertices, drawarray->getMode(), first, last );
}
if( geom->getNormalBinding( ) == osg::Geometry::BIND_PER_VERTEX )
{
osg::Vec3Array* normals = dynamic_cast<osg::Vec3Array*>(geom->getNormalArray());
if( normals )
{
// First, invert the direction of the normals.
for( GLint i = first; i < last; ++i )
{
(*normals)[i] = -(*normals)[i];
}
reverseWindingOrder( normals, drawarray->getMode(), first, last );
}
}
if( geom->getColorBinding( ) == osg::Geometry::BIND_PER_VERTEX )
{
osg::Vec4Array* colors = dynamic_cast<osg::Vec4Array*>(geom->getColorArray());
if( colors )
{
reverseWindingOrder( colors, drawarray->getMode(), first, last );
}
}
for( size_t i = 0; i < geom->getNumTexCoordArrays(); ++i )
{
osg::Vec2Array* UVs = dynamic_cast<osg::Vec2Array*>(geom->getTexCoordArray(i));
if( UVs )
{
reverseWindingOrder( UVs, drawarray->getMode(), first, last );
}
}
}
}
}
}
// Now add the new geometry drawable.
for( size_t i = 0; i < new_drawables.size( ); ++i )
{
geode->addDrawable( new_drawables[i] );
}
}
/* Face record /* Face record
*/ */
class Face : public PrimaryRecord class Face : public PrimaryRecord
@@ -474,15 +374,7 @@ protected:
break; break;
} }
case SOLID_NO_BACKFACE: // Disable backface culling case SOLID_NO_BACKFACE: // Disable backface culling
if( document.getReplaceDoubleSidedPolys( ) ) stateset->setMode(GL_CULL_FACE,osg::StateAttribute::OFF);
{
static osg::ref_ptr<osg::CullFace> cullFace = new osg::CullFace(osg::CullFace::BACK);
stateset->setAttributeAndModes(cullFace.get(), osg::StateAttribute::ON);
}
else
{
stateset->setMode(GL_CULL_FACE,osg::StateAttribute::OFF);
}
break; break;
} }
@@ -585,11 +477,6 @@ protected:
} }
} }
if( getDrawMode( ) == SOLID_NO_BACKFACE && document.getReplaceDoubleSidedPolys( ) )
{
addDrawableAndReverseWindingOrder( _geode.get() );
}
osg::StateSet* stateset = _geode->getOrCreateStateSet(); osg::StateSet* stateset = _geode->getOrCreateStateSet();
// Translucent image? // Translucent image?
@@ -1043,15 +930,7 @@ protected:
break; break;
} }
case SOLID_NO_BACKFACE: // Disable backface culling case SOLID_NO_BACKFACE: // Disable backface culling
if( document.getReplaceDoubleSidedPolys( ) ) stateset->setMode(GL_CULL_FACE,osg::StateAttribute::OFF);
{
static osg::ref_ptr<osg::CullFace> cullFace = new osg::CullFace(osg::CullFace::BACK);
stateset->setAttributeAndModes(cullFace.get(), osg::StateAttribute::ON);
}
else
{
stateset->setMode(GL_CULL_FACE,osg::StateAttribute::OFF);
}
break; break;
} }
@@ -1081,11 +960,6 @@ protected:
insertMatrixTransform(*_geode,*_matrix,_numberOfReplications); insertMatrixTransform(*_geode,*_matrix,_numberOfReplications);
} }
if( getDrawMode( ) == SOLID_NO_BACKFACE && document.getReplaceDoubleSidedPolys( ) )
{
addDrawableAndReverseWindingOrder( _geode.get() );
}
osg::StateSet* stateset = _geode->getOrCreateStateSet(); osg::StateSet* stateset = _geode->getOrCreateStateSet();
// Translucent image? // Translucent image?
@@ -1198,7 +1072,7 @@ protected:
if (!coord.valid()) if (!coord.valid())
{ {
OSG_NOTICE<<"Warning: data error detected in LocalVertexPool::readRecord coord="<<coord.x()<<" "<<coord.y()<<" "<<coord.z()<<std::endl; osg::notify(osg::NOTICE)<<"Warning: data error detected in LocalVertexPool::readRecord coord="<<coord.x()<<" "<<coord.y()<<" "<<coord.z()<<std::endl;
} }
} }
@@ -1213,7 +1087,7 @@ protected:
if (!color.valid()) if (!color.valid())
{ {
OSG_NOTICE<<"Warning: data error detected in LocalVertexPool::readRecord color="<<color.r()<<" "<<color.g()<<" "<<color.b()<<" "<<color.a()<<std::endl; osg::notify(osg::NOTICE)<<"Warning: data error detected in LocalVertexPool::readRecord color="<<color.r()<<" "<<color.g()<<" "<<color.b()<<" "<<color.a()<<std::endl;
} }
} }
@@ -1224,7 +1098,7 @@ protected:
if (!color.valid()) if (!color.valid())
{ {
OSG_NOTICE<<"Warning: data error detected in LocalVertexPool::readRecord color="<<color.r()<<" "<<color.g()<<" "<<color.b()<<" "<<color.a()<<std::endl; osg::notify(osg::NOTICE)<<"Warning: data error detected in LocalVertexPool::readRecord color="<<color.r()<<" "<<color.g()<<" "<<color.b()<<" "<<color.a()<<std::endl;
} }
} }
@@ -1235,7 +1109,7 @@ protected:
if (!normal.valid()) if (!normal.valid())
{ {
OSG_NOTICE<<"Warning: data error detected in LocalVertexPool::readRecord normal="<<normal.x()<<" "<<normal.y()<<" "<<normal.z()<<std::endl; osg::notify(osg::NOTICE)<<"Warning: data error detected in LocalVertexPool::readRecord normal="<<normal.x()<<" "<<normal.y()<<" "<<normal.z()<<std::endl;
} }
} }
@@ -1248,7 +1122,7 @@ protected:
if (!uv.valid()) if (!uv.valid())
{ {
OSG_NOTICE<<"Warning: data error detected in LocalVertexPool::readRecord uv="<<uv.x()<<" "<<uv.y()<<std::endl; osg::notify(osg::NOTICE)<<"Warning: data error detected in LocalVertexPool::readRecord uv="<<uv.x()<<" "<<uv.y()<<std::endl;
} }
} }

View File

@@ -103,7 +103,7 @@ MaterialPaletteManager::write( DataOutputStream& dos ) const
{ {
std::string warning( "fltexp: No support for different front and back material properties." ); std::string warning( "fltexp: No support for different front and back material properties." );
OSG_WARN << warning << std::endl; osg::notify( osg::WARN ) << warning << std::endl;
_fltOpt.getWriteResult().warn( warning ); _fltOpt.getWriteResult().warn( warning );
} }

View File

@@ -12,7 +12,7 @@
*/ */
// //
// OpenFlight (R) loader for OpenSceneGraph // OpenFlight<EFBFBD> loader for OpenSceneGraph
// //
// Copyright (C) 2005-2007 Brede Johansen // Copyright (C) 2005-2007 Brede Johansen
// //
@@ -30,23 +30,6 @@
#include "AttrData.h" #include "AttrData.h"
#include "RecordInputStream.h" #include "RecordInputStream.h"
#if defined(OSG_GLES1_AVAILABLE) || defined(OSG_GLES2_AVAILABLE)
#define GL_RGB5 0x8050
#define GL_RGBA4 0x8056
#define GL_RGBA8 0x8058
#define GL_RGBA12 0x805A
#define GL_RGB12 0x8053
#define GL_LUMINANCE12_ALPHA4 0x8046
#define GL_LUMINANCE12_ALPHA12 0x8047
#define GL_INTENSITY16 0x804D
#endif
#if defined(OSG_GL3_AVAILABLE)
#define GL_LUMINANCE12_ALPHA4 0x8046
#define GL_LUMINANCE12_ALPHA12 0x8047
#define GL_INTENSITY16 0x804D
#endif
namespace flt { namespace flt {
class VertexPalette : public Record class VertexPalette : public Record
@@ -466,7 +449,7 @@ protected:
std::string pathname = osgDB::findDataFile(filename,document.getOptions()); std::string pathname = osgDB::findDataFile(filename,document.getOptions());
if (pathname.empty()) if (pathname.empty())
{ {
OSG_WARN << "Can't find texture (" << index << ") " << filename << std::endl; osg::notify(osg::WARN) << "Can't find texture (" << index << ") " << filename << std::endl;
return; return;
} }

View File

@@ -69,16 +69,16 @@ protected:
virtual void readRecord(RecordInputStream& in, Document& document) virtual void readRecord(RecordInputStream& in, Document& document)
{ {
std::string id = in.readString(8); std::string id = in.readString(8);
OSG_DEBUG << "ID: " << id << std::endl; osg::notify(osg::DEBUG_INFO) << "ID: " << id << std::endl;
uint32 format = in.readUInt32(); uint32 format = in.readUInt32();
OSG_DEBUG << "Format: " << format << std::endl; osg::notify(osg::DEBUG_INFO) << "Format: " << format << std::endl;
document._version = format; document._version = format;
/*uint32 revision =*/ in.readUInt32(); /*uint32 revision =*/ in.readUInt32();
std::string revisionTime = in.readString(32); std::string revisionTime = in.readString(32);
OSG_INFO << "Last revision: " << revisionTime << std::endl; osg::notify(osg::INFO) << "Last revision: " << revisionTime << std::endl;
in.forward(4*2); in.forward(4*2);
@@ -131,7 +131,7 @@ protected:
osgSim::GeographicLocation* loc = new osgSim::GeographicLocation; osgSim::GeographicLocation* loc = new osgSim::GeographicLocation;
loc->set( originLat, originLong ); loc->set( originLat, originLong );
_header->setUserData( loc ); _header->setUserData( loc );
OSG_INFO << "DB lat=" << originLat << " lon=" << originLong << std::endl; osg::notify(osg::INFO) << "DB lat=" << originLat << " lon=" << originLong << std::endl;
document.setHeaderNode(_header.get()); document.setHeaderNode(_header.get());
} }
@@ -200,7 +200,7 @@ protected:
void readRecord(RecordInputStream& in, Document& document) void readRecord(RecordInputStream& in, Document& document)
{ {
std::string id = in.readString(8); std::string id = in.readString(8);
OSG_DEBUG << "ID: " << id << std::endl; osg::notify(osg::DEBUG_INFO) << "ID: " << id << std::endl;
/*int16 relativePriority =*/ in.readInt16(); /*int16 relativePriority =*/ in.readInt16();
in.forward(2); in.forward(2);
@@ -396,10 +396,10 @@ protected:
if ((length_x*length_y*length_z)==0.0f) if ((length_x*length_y*length_z)==0.0f)
{ {
OSG_NOTICE<<"Warning: OpenFlight DegreeOfFreedom::readRecord() found erroneous axis definition:"<<std::endl; osg::notify(osg::NOTICE)<<"Warning: OpenFlight DegreeOfFreedom::readRecord() found erroneous axis definition:"<<std::endl;
OSG_NOTICE<<" localOrigin="<<localOrigin<<std::endl; osg::notify(osg::NOTICE)<<" localOrigin="<<localOrigin<<std::endl;
OSG_NOTICE<<" pointOnXAxis="<<pointOnXAxis<<std::endl; osg::notify(osg::NOTICE)<<" pointOnXAxis="<<pointOnXAxis<<std::endl;
OSG_NOTICE<<" pointInXYPlane="<<pointInXYPlane<<std::endl; osg::notify(osg::NOTICE)<<" pointInXYPlane="<<pointInXYPlane<<std::endl;
xAxis.set(1.0f,0.0f,0.0f); xAxis.set(1.0f,0.0f,0.0f);
yAxis.set(0.0f,1.0f,0.0f); yAxis.set(0.0f,1.0f,0.0f);
@@ -615,14 +615,6 @@ public:
} }
} }
virtual void setMultiSwitchValueName(unsigned int switchSet, const std::string& name)
{
if (_multiSwitch.valid())
{
_multiSwitch->setValueName(switchSet, name);
}
}
protected: protected:
virtual ~Switch() {} virtual ~Switch() {}

View File

@@ -195,7 +195,7 @@ ReaderWriterATTR::writeObject(const osg::Object& object, const std::string& file
const AttrData* attr = dynamic_cast< const AttrData* >( &object ); const AttrData* attr = dynamic_cast< const AttrData* >( &object );
if (attr == NULL) if (attr == NULL)
{ {
OSG_FATAL << "AttrWriter: Invalid Object." << std::endl; osg::notify( osg::FATAL ) << "AttrWriter: Invalid Object." << std::endl;
return WriteResult::FILE_NOT_HANDLED; return WriteResult::FILE_NOT_HANDLED;
} }

View File

@@ -231,7 +231,6 @@ class FLTReaderWriter : public ReaderWriter
supportsOption("keepExternalReferences","Import option"); supportsOption("keepExternalReferences","Import option");
supportsOption("preserveFace","Import option"); supportsOption("preserveFace","Import option");
supportsOption("preserveObject","Import option"); supportsOption("preserveObject","Import option");
supportsOption("replaceDoubleSidedPolys","Import option");
supportsOption("dofAnimation","Import option"); supportsOption("dofAnimation","Import option");
supportsOption("billboardCenter","Import option"); supportsOption("billboardCenter","Import option");
supportsOption("noTextureAlphaForTransparancyBinning","Import option"); supportsOption("noTextureAlphaForTransparancyBinning","Import option");
@@ -244,7 +243,7 @@ class FLTReaderWriter : public ReaderWriter
supportsOption("convertToNauticalMiles","Import option"); supportsOption("convertToNauticalMiles","Import option");
supportsOption( "version=<ver>", "Export option: Specifies the version of the output OpenFlight file. Supported values include 15.7, 15.8, and 16.1. Default is 16.1. Example: \"version=15.8\"." ); supportsOption( "version=<ver>", "Export option: Specifies the version of the output OpenFlight file. Supported values include 15.7, 15.8, and 16.1. Default is 16.1. Example: \"version=15.8\"." );
supportsOption( "units=<units>", "Export option: Specifies the contents of the Units field of the OpenFlight header record. Valid values include INCHES, FEET, METERS, KILOMETERS, and NAUTICAL_MILES. Default is METERS. Example: \"units=METERS\"." ); supportsOption( "units=<units>", "Export option: Specifies the contents of the Units field of the OpenFliht header record. Valid values include INCHES, FEET, METERS, KILOMETERS, and NATICAL_MILES. Default is METERS. Example: \"units=METERS\"." );
supportsOption( "validate", "Export option: If present in the Options string, the plugin does not write an OpenFlight file. Instead, it returns an indication of the scene graph's suitability for OpenFlight export." ); supportsOption( "validate", "Export option: If present in the Options string, the plugin does not write an OpenFlight file. Instead, it returns an indication of the scene graph's suitability for OpenFlight export." );
supportsOption( "tempDir=<dir>", "Export option: Specifies the directory to use for creation of temporary files. If not specified, the directory is taken from the file name. If the file doesn't contain a path, the current working directory is used. Applications should set this to the name of their app-specific temp directory. If the path contains spaces, use double quotes to ensure correct parsing. Examples: \"tempDir=/tmp\", \"tempDir=\"C:\\My Temp Dir\"." ); supportsOption( "tempDir=<dir>", "Export option: Specifies the directory to use for creation of temporary files. If not specified, the directory is taken from the file name. If the file doesn't contain a path, the current working directory is used. Applications should set this to the name of their app-specific temp directory. If the path contains spaces, use double quotes to ensure correct parsing. Examples: \"tempDir=/tmp\", \"tempDir=\"C:\\My Temp Dir\"." );
supportsOption( "lighting=<ON|OFF>", "Export option: Specifies a default enable/disable state for lighting, for Nodes in the exported scene graph that don't set it explicitly. By default, the exporter assumes lighting is enabled (GL_LIGHTING ON). Set this to either ON or OFF. Example: \"lighting=OFF\"." ); supportsOption( "lighting=<ON|OFF>", "Export option: Specifies a default enable/disable state for lighting, for Nodes in the exported scene graph that don't set it explicitly. By default, the exporter assumes lighting is enabled (GL_LIGHTING ON). Set this to either ON or OFF. Example: \"lighting=OFF\"." );
@@ -311,7 +310,7 @@ class FLTReaderWriter : public ReaderWriter
if ( !keepExternalReferences ) if ( !keepExternalReferences )
{ {
OSG_DEBUG << "keepExternalReferences not found, so externals will be re-readed"<<std::endl; osg::notify(osg::DEBUG_INFO) << "keepExternalReferences not found, so externals will be re-readed"<<std::endl;
// read externals. // read externals.
if (rr.getNode()) if (rr.getNode())
{ {
@@ -323,7 +322,7 @@ class FLTReaderWriter : public ReaderWriter
} }
else else
{ {
OSG_DEBUG << "keepExternalReferences found, so externals will be left as ProxyNodes"<<std::endl; osg::notify(osg::DEBUG_INFO) << "keepExternalReferences found, so externals will be left as ProxyNodes"<<std::endl;
} }
} }
@@ -350,34 +349,31 @@ class FLTReaderWriter : public ReaderWriter
const char readerMsg[] = "flt reader option: "; const char readerMsg[] = "flt reader option: ";
document.setReplaceClampWithClampToEdge((options->getOptionString().find("clampToEdge")!=std::string::npos)); document.setReplaceClampWithClampToEdge((options->getOptionString().find("clampToEdge")!=std::string::npos));
OSG_DEBUG << readerMsg << "clampToEdge=" << document.getReplaceClampWithClampToEdge() << std::endl; osg::notify(osg::DEBUG_INFO) << readerMsg << "clampToEdge=" << document.getReplaceClampWithClampToEdge() << std::endl;
document.setKeepExternalReferences((options->getOptionString().find("keepExternalReferences")!=std::string::npos)); document.setKeepExternalReferences((options->getOptionString().find("keepExternalReferences")!=std::string::npos));
OSG_DEBUG << readerMsg << "keepExternalReferences=" << document.getKeepExternalReferences() << std::endl; osg::notify(osg::DEBUG_INFO) << readerMsg << "keepExternalReferences=" << document.getKeepExternalReferences() << std::endl;
document.setPreserveFace((options->getOptionString().find("preserveFace")!=std::string::npos)); document.setPreserveFace((options->getOptionString().find("preserveFace")!=std::string::npos));
OSG_DEBUG << readerMsg << "preserveFace=" << document.getPreserveFace() << std::endl; osg::notify(osg::DEBUG_INFO) << readerMsg << "preserveFace=" << document.getPreserveFace() << std::endl;
document.setPreserveObject((options->getOptionString().find("preserveObject")!=std::string::npos)); document.setPreserveObject((options->getOptionString().find("preserveObject")!=std::string::npos));
OSG_DEBUG << readerMsg << "preserveObject=" << document.getPreserveObject() << std::endl; osg::notify(osg::DEBUG_INFO) << readerMsg << "preserveObject=" << document.getPreserveObject() << std::endl;
document.setReplaceDoubleSidedPolys((options->getOptionString().find("replaceDoubleSidedPolys")!=std::string::npos));
OSG_DEBUG << readerMsg << "replaceDoubleSidedPolys=" << document.getReplaceDoubleSidedPolys() << std::endl;
document.setDefaultDOFAnimationState((options->getOptionString().find("dofAnimation")!=std::string::npos)); document.setDefaultDOFAnimationState((options->getOptionString().find("dofAnimation")!=std::string::npos));
OSG_DEBUG << readerMsg << "dofAnimation=" << document.getDefaultDOFAnimationState() << std::endl; osg::notify(osg::DEBUG_INFO) << readerMsg << "dofAnimation=" << document.getDefaultDOFAnimationState() << std::endl;
document.setUseBillboardCenter((options->getOptionString().find("billboardCenter")!=std::string::npos)); document.setUseBillboardCenter((options->getOptionString().find("billboardCenter")!=std::string::npos));
OSG_DEBUG << readerMsg << "billboardCenter=" << document.getUseBillboardCenter() << std::endl; osg::notify(osg::DEBUG_INFO) << readerMsg << "billboardCenter=" << document.getUseBillboardCenter() << std::endl;
document.setUseTextureAlphaForTransparancyBinning(options->getOptionString().find("noTextureAlphaForTransparancyBinning")==std::string::npos); document.setUseTextureAlphaForTransparancyBinning(options->getOptionString().find("noTextureAlphaForTransparancyBinning")==std::string::npos);
OSG_DEBUG << readerMsg << "noTextureAlphaForTransparancyBinning=" << !document.getUseTextureAlphaForTransparancyBinning() << std::endl; osg::notify(osg::DEBUG_INFO) << readerMsg << "noTextureAlphaForTransparancyBinning=" << !document.getUseTextureAlphaForTransparancyBinning() << std::endl;
document.setReadObjectRecordData(options->getOptionString().find("readObjectRecordData")==std::string::npos); document.setReadObjectRecordData(options->getOptionString().find("readObjectRecordData")==std::string::npos);
OSG_DEBUG << readerMsg << "readObjectRecordData=" << !document.getReadObjectRecordData() << std::endl; osg::notify(osg::DEBUG_INFO) << readerMsg << "readObjectRecordData=" << !document.getReadObjectRecordData() << std::endl;
document.setDoUnitsConversion((options->getOptionString().find("noUnitsConversion")==std::string::npos)); // default to true, unless noUnitsConversion is specified. document.setDoUnitsConversion((options->getOptionString().find("noUnitsConversion")==std::string::npos)); // default to true, unless noUnitsConversion is specified.
OSG_DEBUG << readerMsg << "noUnitsConversion=" << !document.getDoUnitsConversion() << std::endl; osg::notify(osg::DEBUG_INFO) << readerMsg << "noUnitsConversion=" << !document.getDoUnitsConversion() << std::endl;
if (document.getDoUnitsConversion()) if (document.getDoUnitsConversion())
{ {
@@ -537,9 +533,9 @@ class FLTReaderWriter : public ReaderWriter
{ {
if ( fileName.empty() ) if ( fileName.empty() )
{ {
osg::notify( osg::FATAL ) << "fltexp: writeNode: empty file name" << std::endl;
return WriteResult::FILE_NOT_HANDLED; return WriteResult::FILE_NOT_HANDLED;
} }
std::string ext = osgDB::getLowerCaseFileExtension( fileName ); std::string ext = osgDB::getLowerCaseFileExtension( fileName );
if ( !acceptsExtension(ext) ) if ( !acceptsExtension(ext) )
return WriteResult::FILE_NOT_HANDLED; return WriteResult::FILE_NOT_HANDLED;
@@ -553,7 +549,7 @@ class FLTReaderWriter : public ReaderWriter
fOut.open( fileName.c_str(), std::ios::out | std::ios::binary ); fOut.open( fileName.c_str(), std::ios::out | std::ios::binary );
if ( fOut.fail()) if ( fOut.fail())
{ {
OSG_FATAL << "fltexp: Failed to open output stream." << std::endl; osg::notify( osg::FATAL ) << "fltexp: Failed to open output stream." << std::endl;
return WriteResult::ERROR_IN_WRITING_FILE; return WriteResult::ERROR_IN_WRITING_FILE;
} }
@@ -587,7 +583,7 @@ class FLTReaderWriter : public ReaderWriter
// If the temp directory doesn't already exist, make it. // If the temp directory doesn't already exist, make it.
if ( !osgDB::makeDirectory( fltOpt->getTempDir() ) ) if ( !osgDB::makeDirectory( fltOpt->getTempDir() ) )
{ {
OSG_FATAL << "fltexp: Error creating temp dir: " << fltOpt->getTempDir() << std::endl; osg::notify( osg::FATAL ) << "fltexp: Error creating temp dir: " << fltOpt->getTempDir() << std::endl;
return WriteResult::ERROR_IN_WRITING_FILE; return WriteResult::ERROR_IN_WRITING_FILE;
} }
} }

View File

@@ -86,7 +86,6 @@ public:
virtual void addVertex(Vertex& /*vertex*/) {} virtual void addVertex(Vertex& /*vertex*/) {}
virtual void addVertexUV(int /*layer*/,const osg::Vec2& /*uv*/) {} virtual void addVertexUV(int /*layer*/,const osg::Vec2& /*uv*/) {}
virtual void addMorphVertex(Vertex& /*vertex0*/, Vertex& /*vertex100*/) {} virtual void addMorphVertex(Vertex& /*vertex0*/, Vertex& /*vertex100*/) {}
virtual void setMultiSwitchValueName(unsigned int /*switchSet*/, const std::string& /*name*/) {}
void setNumberOfReplications(int num) { _numberOfReplications = num; } void setNumberOfReplications(int num) { _numberOfReplications = num; }
void setMatrix(const osg::Matrix& matrix) { _matrix = new osg::RefMatrix(matrix); } void setMatrix(const osg::Matrix& matrix) { _matrix = new osg::RefMatrix(matrix); }

View File

@@ -47,7 +47,7 @@ bool RecordInputStream::readRecordBody(opcode_type opcode, size_type size, Docum
const uint16 LITTLE_ENDIAN_POP_LEVEL_OP = 0x0B00; const uint16 LITTLE_ENDIAN_POP_LEVEL_OP = 0x0B00;
if (opcode==LITTLE_ENDIAN_POP_LEVEL_OP) if (opcode==LITTLE_ENDIAN_POP_LEVEL_OP)
{ {
OSG_INFO << "Little endian pop-level record" << std::endl; osg::notify(osg::INFO) << "Little endian pop-level record" << std::endl;
opcode=POP_LEVEL_OP; opcode=POP_LEVEL_OP;
size=4; size=4;
} }
@@ -76,7 +76,7 @@ bool RecordInputStream::readRecordBody(opcode_type opcode, size_type size, Docum
} }
else // prototype not found else // prototype not found
{ {
OSG_WARN << "Unknown record, opcode=" << opcode << " size=" << size << std::endl; osg::notify(osg::WARN) << "Unknown record, opcode=" << opcode << " size=" << size << std::endl;
// Add to registry so we only have to see this error message once. // Add to registry so we only have to see this error message once.
Registry::instance()->addPrototype(opcode,new DummyRecord); Registry::instance()->addPrototype(opcode,new DummyRecord);

View File

@@ -40,12 +40,12 @@ void Registry::addPrototype(int opcode, Record* prototype)
{ {
if (prototype==0L) if (prototype==0L)
{ {
OSG_WARN << "Not a record." << std::endl; osg::notify(osg::WARN) << "Not a record." << std::endl;
return; return;
} }
if (_recordProtoMap.find(opcode) != _recordProtoMap.end()) if (_recordProtoMap.find(opcode) != _recordProtoMap.end())
OSG_WARN << "Registry already contains prototype for opcode " << opcode << "." << std::endl; osg::notify(osg::WARN) << "Registry already contains prototype for opcode " << opcode << "." << std::endl;
_recordProtoMap[opcode] = prototype; _recordProtoMap[opcode] = prototype;
} }

View File

@@ -42,12 +42,12 @@ VertexPaletteManager::~VertexPaletteManager()
// Delete our temp file. // Delete our temp file.
if (_verticesStr.is_open()) if (_verticesStr.is_open())
{ {
OSG_WARN << "fltexp: VertexPaletteManager destructor has an open temp file." << std::endl; osg::notify( osg::WARN ) << "fltexp: VertexPaletteManager destructor has an open temp file." << std::endl;
// This should not happen. FltExportVisitor::complete should close // This should not happen. FltExportVisitor::complete should close
// this file before we get to this destructor. // this file before we get to this destructor.
return; return;
} }
OSG_INFO << "fltexp: Deleting temp file " << _verticesTempName << std::endl; osg::notify( osg::INFO ) << "fltexp: Deleting temp file " << _verticesTempName << std::endl;
FLTEXP_DELETEFILE( _verticesTempName.c_str() ); FLTEXP_DELETEFILE( _verticesTempName.c_str() );
} }
} }
@@ -58,7 +58,7 @@ VertexPaletteManager::add( const osg::Geometry& geom )
const osg::Array* v = geom.getVertexArray(); const osg::Array* v = geom.getVertexArray();
if (!v) if (!v)
{ {
OSG_WARN << "fltexp: Attempting to add NULL vertex array in VertexPaletteManager." << std::endl; osg::notify( osg::WARN ) << "fltexp: Attempting to add NULL vertex array in VertexPaletteManager." << std::endl;
return; return;
} }
const osg::Array* c = geom.getColorArray(); const osg::Array* c = geom.getColorArray();
@@ -129,12 +129,12 @@ VertexPaletteManager::byteOffset( unsigned int idx ) const
{ {
if (!_current) if (!_current)
{ {
OSG_WARN << "fltexp: No current vertex array in VertexPaletteManager." << std::endl; osg::notify( osg::WARN ) << "fltexp: No current vertex array in VertexPaletteManager." << std::endl;
return 4; return 4;
} }
if (idx >= _current->_idxCount) if (idx >= _current->_idxCount)
{ {
OSG_WARN << "fltexp: Index out of range in VertexPaletteManager." << std::endl; osg::notify( osg::WARN ) << "fltexp: Index out of range in VertexPaletteManager." << std::endl;
return 4; return 4;
} }
@@ -232,19 +232,19 @@ VertexPaletteManager::writeRecords( const osg::Vec3dArray* v, const osg::Vec4Arr
case VERTEX_CN: case VERTEX_CN:
opcode = VERTEX_CN_OP; opcode = VERTEX_CN_OP;
if (!n) if (!n)
OSG_WARN << "fltexp: VPM::writeRecords: no normal array." << std::endl; osg::notify( osg::WARN ) << "fltexp: VPM::writeRecords: no normal array." << std::endl;
break; break;
case VERTEX_CNT: case VERTEX_CNT:
opcode = VERTEX_CNT_OP; opcode = VERTEX_CNT_OP;
if (!n) if (!n)
OSG_WARN << "fltexp: VPM::writeRecords: no normal array." << std::endl; osg::notify( osg::WARN ) << "fltexp: VPM::writeRecords: no normal array." << std::endl;
if (!t) if (!t)
OSG_WARN << "fltexp: VPM::writeRecords: no tex coord array." << std::endl; osg::notify( osg::WARN ) << "fltexp: VPM::writeRecords: no tex coord array." << std::endl;
break; break;
case VERTEX_CT: case VERTEX_CT:
opcode = VERTEX_CT_OP; opcode = VERTEX_CT_OP;
if (!t) if (!t)
OSG_WARN << "fltexp: VPM::writeRecords: no tex coord array." << std::endl; osg::notify( osg::WARN ) << "fltexp: VPM::writeRecords: no tex coord array." << std::endl;
break; break;
} }
@@ -368,7 +368,7 @@ VertexPaletteManager::asVec2Array( const osg::Array* in, const unsigned int n )
} }
default: default:
{ {
OSG_WARN << "fltexp: Unsupported array type in conversion to Vec2Array: " << arrayType << std::endl; osg::notify( osg::WARN ) << "fltexp: Unsupported array type in conversion to Vec2Array: " << arrayType << std::endl;
return NULL; return NULL;
} }
} }
@@ -416,7 +416,7 @@ VertexPaletteManager::asVec3Array( const osg::Array* in, const unsigned int n )
} }
default: default:
{ {
OSG_WARN << "fltexp: Unsupported array type in conversion to Vec3Array: " << arrayType << std::endl; osg::notify( osg::WARN ) << "fltexp: Unsupported array type in conversion to Vec3Array: " << arrayType << std::endl;
return NULL; return NULL;
} }
} }
@@ -464,7 +464,7 @@ VertexPaletteManager::asVec3dArray( const osg::Array* in, const unsigned int n )
} }
default: default:
{ {
OSG_WARN << "fltexp: Unsupported array type in conversion to Vec3dArray: " << arrayType << std::endl; osg::notify( osg::WARN ) << "fltexp: Unsupported array type in conversion to Vec3dArray: " << arrayType << std::endl;
return NULL; return NULL;
} }
} }
@@ -520,7 +520,7 @@ VertexPaletteManager::asVec4Array( const osg::Array* in, const unsigned int n )
} }
default: default:
{ {
OSG_WARN << "fltexp: Unsupported array type in conversion to Vec4Array: " << arrayType << std::endl; osg::notify( osg::WARN ) << "fltexp: Unsupported array type in conversion to Vec4Array: " << arrayType << std::endl;
return NULL; return NULL;
} }
} }

View File

@@ -190,17 +190,17 @@ class VertexCNT : public Record
if (!coord.valid()) if (!coord.valid())
{ {
OSG_NOTICE<<"Warning: data error detected in VertexCNT::readRecord coord="<<coord.x()<<" "<<coord.y()<<" "<<coord.z()<<std::endl; osg::notify(osg::NOTICE)<<"Warning: data error detected in VertexCNT::readRecord coord="<<coord.x()<<" "<<coord.y()<<" "<<coord.z()<<std::endl;
} }
if (!normal.valid()) if (!normal.valid())
{ {
OSG_NOTICE<<"Warning: data error detected in VertexCNT::readRecord normal="<<normal.x()<<" "<<normal.y()<<" "<<normal.z()<<std::endl; osg::notify(osg::NOTICE)<<"Warning: data error detected in VertexCNT::readRecord normal="<<normal.x()<<" "<<normal.y()<<" "<<normal.z()<<std::endl;
} }
if (!uv.valid()) if (!uv.valid())
{ {
OSG_NOTICE<<"Warning: data error detected in VertexCNT::readRecord uv="<<uv.x()<<" "<<uv.y()<<std::endl; osg::notify(osg::NOTICE)<<"Warning: data error detected in VertexCNT::readRecord uv="<<uv.x()<<" "<<uv.y()<<std::endl;
} }
// color // color

View File

@@ -46,7 +46,7 @@ FltExportVisitor::writeComment( const osg::Node& node, DataOutputStream* dos )
// short overrun // short overrun
std::string warning( "fltexp: writeComment: Descriptions too long, resorts in short overrun. Skipping." ); std::string warning( "fltexp: writeComment: Descriptions too long, resorts in short overrun. Skipping." );
_fltOpt->getWriteResult().warn( warning ); _fltOpt->getWriteResult().warn( warning );
OSG_WARN << warning << std::endl; osg::notify( osg::WARN ) << warning << std::endl;
continue; continue;
} }
uint16 length( (uint16)iLen ); uint16 length( (uint16)iLen );
@@ -100,7 +100,7 @@ FltExportVisitor::writeMatrix( const osg::Referenced* ref )
void void
FltExportVisitor::writeContinuationRecord( const unsigned short length ) FltExportVisitor::writeContinuationRecord( const unsigned short length )
{ {
OSG_DEBUG << "fltexp: Continuation record length: " << length+4 << std::endl; osg::notify( osg::DEBUG_INFO ) << "fltexp: Continuation record length: " << length+4 << std::endl;
_records->writeInt16( (int16) CONTINUATION_OP ); _records->writeInt16( (int16) CONTINUATION_OP );
_records->writeUInt16( length+4 ); _records->writeUInt16( length+4 );
} }

View File

@@ -185,7 +185,7 @@ FltExportVisitor::writeFace( const osg::Geode& geode, const osg::Geometry& geom,
case GL_POINTS: case GL_POINTS:
{ {
std::string warning( "fltexp: GL_POINTS not supported in FLT export." ); std::string warning( "fltexp: GL_POINTS not supported in FLT export." );
OSG_WARN << warning << std::endl; osg::notify( osg::WARN ) << warning << std::endl;
_fltOpt->getWriteResult().warn( warning ); _fltOpt->getWriteResult().warn( warning );
return; return;
break; break;
@@ -195,7 +195,7 @@ FltExportVisitor::writeFace( const osg::Geode& geode, const osg::Geometry& geom,
case GL_QUAD_STRIP: case GL_QUAD_STRIP:
{ {
std::string warning( "fltexp: Wrong mode in Face record." ); std::string warning( "fltexp: Wrong mode in Face record." );
OSG_WARN << warning << std::endl; osg::notify( osg::WARN ) << warning << std::endl;
_fltOpt->getWriteResult().warn( warning ); _fltOpt->getWriteResult().warn( warning );
return; return;
break; break;
@@ -248,7 +248,7 @@ FltExportVisitor::writeFace( const osg::Geode& geode, const osg::Geometry& geom,
else else
{ {
std::string warning( "fltexp: Face is textured, but Texture2D StateAttribute is NULL." ); std::string warning( "fltexp: Face is textured, but Texture2D StateAttribute is NULL." );
OSG_WARN << warning << std::endl; osg::notify( osg::WARN ) << warning << std::endl;
_fltOpt->getWriteResult().warn( warning ); _fltOpt->getWriteResult().warn( warning );
} }
} }
@@ -423,7 +423,7 @@ FltExportVisitor::writeMesh( const osg::Geode& geode, const osg::Geometry& geom
else else
{ {
std::string warning( "fltexp: Mesh is textured, but Texture2D StateAttribute is NULL." ); std::string warning( "fltexp: Mesh is textured, but Texture2D StateAttribute is NULL." );
OSG_WARN << warning << std::endl; osg::notify( osg::WARN ) << warning << std::endl;
_fltOpt->getWriteResult().warn( warning ); _fltOpt->getWriteResult().warn( warning );
} }
} }
@@ -579,7 +579,7 @@ FltExportVisitor::writeLocalVertexPool( const osg::Geometry& geom )
if (!v3) if (!v3)
{ {
std::string warning( "fltexp: writeLocalVertexPool: VertexArray is not Vec3Array." ); std::string warning( "fltexp: writeLocalVertexPool: VertexArray is not Vec3Array." );
OSG_WARN << warning << std::endl; osg::notify( osg::WARN ) << warning << std::endl;
_fltOpt->getWriteResult().warn( warning ); _fltOpt->getWriteResult().warn( warning );
return; return;
} }
@@ -755,7 +755,7 @@ FltExportVisitor::writeMultitexture( const osg::Geometry& geom )
{ {
std::ostringstream warning; std::ostringstream warning;
warning << "fltexp: No Texture2D for unit " << idx; warning << "fltexp: No Texture2D for unit " << idx;
OSG_WARN << warning.str() << std::endl; osg::notify( osg::WARN ) << warning.str() << std::endl;
_fltOpt->getWriteResult().warn( warning.str() ); _fltOpt->getWriteResult().warn( warning.str() );
} }
@@ -770,7 +770,7 @@ FltExportVisitor::writeMultitexture( const osg::Geometry& geom )
} }
void void
FltExportVisitor::writeUVList( int numVerts, const osg::Geometry& geom, const std::vector<unsigned int>& indices ) FltExportVisitor::writeUVList( int numVerts, const osg::Geometry& geom )
{ {
unsigned int numLayers( 0 ); unsigned int numLayers( 0 );
uint32 flags( 0 ); uint32 flags( 0 );
@@ -794,86 +794,32 @@ FltExportVisitor::writeUVList( int numVerts, const osg::Geometry& geom, const st
osg::Vec2 defaultCoord( 0., 0. ); osg::Vec2 defaultCoord( 0., 0. );
// const osg::StateSet* ss = getCurrentStateSet(); // const osg::StateSet* ss = getCurrentStateSet();
for( int vertexIdx=0; vertexIdx<numVerts; vertexIdx++)
{
for( idx=1; idx<8; idx++)
{
if( isTextured( idx, geom ) )
{
osg::Array* t = const_cast<osg::Array*>( geom.getTexCoordArray( idx ) );
osg::ref_ptr<osg::Vec2Array> t2 = dynamic_cast<osg::Vec2Array*>( t );
if (!t2.valid())
{
std::ostringstream warning;
warning << "fltexp: No Texture2D for unit " << idx;
OSG_WARN << warning.str() << std::endl;
_fltOpt->getWriteResult().warn( warning.str() );
t2 = new osg::Vec2Array;
}
const int size = t2->getNumElements();
int vIdx = indices[ vertexIdx ];
osg::Vec2& tc( defaultCoord );
if (vIdx < size)
tc = ( *t2 )[ vIdx ];
_records->writeFloat32( tc[ 0 ] );
_records->writeFloat32( tc[ 1 ] );
}
}
}
}
void
FltExportVisitor::writeUVList( int numVerts, const osg::Geometry& geom, unsigned int first )
{
unsigned int numLayers( 0 );
uint32 flags( 0 );
unsigned int idx;
for( idx=1; idx<8; idx++) for( idx=1; idx<8; idx++)
{ {
if( isTextured( idx, geom ) ) if( isTextured( idx, geom ) )
{ {
flags |= LAYER_1 >> (idx-1); osg::Array* t = const_cast<osg::Array*>( geom.getTexCoordArray( idx ) );
numLayers++; osg::ref_ptr<osg::Vec2Array> t2 = dynamic_cast<osg::Vec2Array*>( t );
} if (!t2.valid())
}
if( numLayers == 0 )
return;
uint16 length( 8 + (8*numLayers*numVerts) );
_records->writeInt16( (int16) UV_LIST_OP );
_records->writeUInt16( length );
_records->writeInt32( flags );
osg::Vec2 defaultCoord( 0., 0. );
for( int vertexIdx=0; vertexIdx<numVerts; vertexIdx++)
{
for( idx=1; idx<8; idx++)
{
if( isTextured( idx, geom ) )
{ {
osg::Array* t = const_cast<osg::Array*>( geom.getTexCoordArray( idx ) ); std::ostringstream warning;
osg::ref_ptr<osg::Vec2Array> t2 = dynamic_cast<osg::Vec2Array*>( t ); warning << "fltexp: No Texture2D for unit " << idx;
if (!t2.valid()) osg::notify( osg::WARN ) << warning.str() << std::endl;
{ _fltOpt->getWriteResult().warn( warning.str() );
std::ostringstream warning; t2 = new osg::Vec2Array;
warning << "fltexp: No Texture2D for unit " << idx; }
osg::notify( osg::WARN ) << warning.str() << std::endl; else if (static_cast<int>(t2->getNumElements()) != numVerts)
_fltOpt->getWriteResult().warn( warning.str() ); {
t2 = new osg::Vec2Array; std::ostringstream warning;
} warning << "fltexp: Invalid number of texture coordinates for unit " << idx;
else if (t2->getNumElements() < first + numVerts) osg::notify( osg::WARN ) << warning.str() << std::endl;
{ _fltOpt->getWriteResult().warn( warning.str() );
std::ostringstream warning; }
warning << "fltexp: Invalid number of texture coordinates for unit " << idx;
OSG_WARN << warning.str() << std::endl;
_fltOpt->getWriteResult().warn( warning.str() );
}
const int size = t2->getNumElements(); const int size = t2->getNumElements();
int vIdx = first + vertexIdx; int vIdx;
for( vIdx=0; vIdx<numVerts; vIdx++)
{
osg::Vec2& tc( defaultCoord ); osg::Vec2& tc( defaultCoord );
if (vIdx < size) if (vIdx < size)
tc = (*t2)[ vIdx ]; tc = (*t2)[ vIdx ];
@@ -1112,7 +1058,7 @@ FltExportVisitor::handleDrawElements( const osg::DrawElements* de, const osg::Ge
int numVerts = writeVertexList( indices, n ); int numVerts = writeVertexList( indices, n );
first += n; first += n;
writeUVList( numVerts, geom, indices ); writeUVList( numVerts, geom );
writePop(); writePop();
} }

View File

@@ -31,7 +31,6 @@
#include <osgSim/LightPointNode> #include <osgSim/LightPointNode>
#include <osgSim/ObjectRecordData> #include <osgSim/ObjectRecordData>
#include <stdlib.h>
// FIXME: This header was copied verbatim from the importer, with the only change // FIXME: This header was copied verbatim from the importer, with the only change
// being that the symbols it defines are placed in namespace 'fltexp' instead // being that the symbols it defines are placed in namespace 'fltexp' instead
@@ -283,7 +282,7 @@ FltExportVisitor::writeObject( const osg::Group& group, osgSim::ObjectRecordData
if (!ord) if (!ord)
{ {
std::string warning( "fltexp: writeObject has invalid ObjectRecordData." ); std::string warning( "fltexp: writeObject has invalid ObjectRecordData." );
OSG_WARN << warning << std::endl; osg::notify( osg::WARN ) << warning << std::endl;
_fltOpt->getWriteResult().warn( warning ); _fltOpt->getWriteResult().warn( warning );
return; return;
} }

View File

@@ -2,9 +2,8 @@
#ifndef HEADER_GUARD_OSGFFMPEG_FFMPEG_AUDIO_STREAM_H #ifndef HEADER_GUARD_OSGFFMPEG_FFMPEG_AUDIO_STREAM_H
#define HEADER_GUARD_OSGFFMPEG_FFMPEG_AUDIO_STREAM_H #define HEADER_GUARD_OSGFFMPEG_FFMPEG_AUDIO_STREAM_H
#include "FFmpegDecoder.hpp"
#include <osg/AudioStream> #include <osg/AudioStream>
#include "FFmpegDecoder.hpp"
namespace osgFFmpeg namespace osgFFmpeg
{ {

View File

@@ -6,7 +6,6 @@
extern "C" extern "C"
{ {
#define __STDC_CONSTANT_MACROS #define __STDC_CONSTANT_MACROS
#define FF_API_OLD_SAMPLE_FMT 0
#include <errno.h> // for error codes defined in avformat.h #include <errno.h> // for error codes defined in avformat.h
#include <stdint.h> #include <stdint.h>
#include <avcodec.h> #include <avcodec.h>

View File

@@ -2,14 +2,13 @@
#ifndef HEADER_GUARD_OSGFFMPEG_FFMPEG_IMAGE_STREAM_H #ifndef HEADER_GUARD_OSGFFMPEG_FFMPEG_IMAGE_STREAM_H
#define HEADER_GUARD_OSGFFMPEG_FFMPEG_IMAGE_STREAM_H #define HEADER_GUARD_OSGFFMPEG_FFMPEG_IMAGE_STREAM_H
#include "FFmpegDecoder.hpp"
#include "MessageQueue.hpp"
#include <osg/ImageStream> #include <osg/ImageStream>
#include <OpenThreads/Condition> #include <OpenThreads/Condition>
#include <OpenThreads/Thread> #include <OpenThreads/Thread>
#include "FFmpegDecoder.hpp"
#include "MessageQueue.hpp"
namespace osgFFmpeg namespace osgFFmpeg
{ {

View File

@@ -11,12 +11,14 @@
* OpenSceneGraph Public License for more details. * OpenSceneGraph Public License for more details.
*/ */
#include "FFmpegImageStream.hpp"
#include <osgDB/Registry> #include <osgDB/Registry>
#include <osgDB/FileNameUtils> #include <osgDB/FileNameUtils>
#include <osgDB/FileUtils> #include <osgDB/FileUtils>
#include "FFmpegHeaders.hpp"
#include "FFmpegImageStream.hpp"
/** Implementation heavily inspired by http://www.dranger.com/ffmpeg/ */ /** Implementation heavily inspired by http://www.dranger.com/ffmpeg/ */

View File

@@ -110,7 +110,6 @@ class OSGReaderWriter : public ReaderWriter
supportsExtension("osgs","Psuedo OpenSceneGraph file loaded, with file encoded in filename string"); supportsExtension("osgs","Psuedo OpenSceneGraph file loaded, with file encoded in filename string");
supportsOption("precision","Set the floating point precision when writing out files"); supportsOption("precision","Set the floating point precision when writing out files");
supportsOption("OutputTextureFiles","Write out the texture images to file"); supportsOption("OutputTextureFiles","Write out the texture images to file");
supportsOption("OutputRelativeTextures","Write texture images to a subfolder and reference them with relative file names");
} }
virtual const char* className() const { return "OSG Reader/Writer"; } virtual const char* className() const { return "OSG Reader/Writer"; }
@@ -261,10 +260,6 @@ class OSGReaderWriter : public ReaderWriter
iss >> prec; iss >> prec;
fout.precision(prec); fout.precision(prec);
} }
if (opt=="OutputRelativeTextures")
{
fout.setOutputRelativeTextures(true);
}
if (opt=="OutputTextureFiles") if (opt=="OutputTextureFiles")
{ {
fout.setOutputTextureFiles(true); fout.setOutputTextureFiles(true);
@@ -282,7 +277,6 @@ class OSGReaderWriter : public ReaderWriter
std::string ext = osgDB::getLowerCaseFileExtension(fileName); std::string ext = osgDB::getLowerCaseFileExtension(fileName);
if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED; if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED;
Output fout(fileName.c_str()); Output fout(fileName.c_str());
if (fout) if (fout)
{ {
@@ -302,7 +296,6 @@ class OSGReaderWriter : public ReaderWriter
virtual WriteResult writeObject(const Object& obj,std::ostream& fout, const osgDB::ReaderWriter::Options* options) const virtual WriteResult writeObject(const Object& obj,std::ostream& fout, const osgDB::ReaderWriter::Options* options) const
{ {
if (fout) if (fout)
{ {
Output foutput; Output foutput;
@@ -368,7 +361,6 @@ class OSGReaderWriter : public ReaderWriter
}; };
// now register with Registry to instantiate the above // now register with Registry to instantiate the above
// reader/writer. // reader/writer.
REGISTER_OSGPLUGIN(osg, OSGReaderWriter) REGISTER_OSGPLUGIN(osg, OSGReaderWriter)

View File

@@ -5,8 +5,6 @@
#include "osgDB/Input" #include "osgDB/Input"
#include "osgDB/Output" #include "osgDB/Output"
#include "osgDB/WriteFile" #include "osgDB/WriteFile"
#include "osgDB/FileNameUtils"
#include "osgDB/FileUtils"
using namespace osg; using namespace osg;
using namespace osgDB; using namespace osgDB;
@@ -89,18 +87,7 @@ bool Texture2D_writeLocalData(const Object& obj, Output& fw)
else else
{ {
std::string fileName = texture.getImage()->getFileName(); std::string fileName = texture.getImage()->getFileName();
if (fw.getOutputRelativeTextures()) if (fw.getOutputTextureFiles())
{
std::string generatedFileName = osgDB::getSimpleFileName(osgDB::getNameLessExtension(fw.getTextureFileNameForOutput()));
std::string textureDir = osgDB::getNameLessExtension(fw.getFileName()) + "_textures";
std::string relativeDir = osgDB::getSimpleFileName(textureDir);
std::string texFnWithOriginalFormat = generatedFileName + osgDB::getFileExtensionIncludingDot(fileName);
std::string fullFileName = osgDB::concatPaths(textureDir, texFnWithOriginalFormat);
fileName = relativeDir + "/" + texFnWithOriginalFormat;
osgDB::makeDirectory(textureDir);
osgDB::writeImageFile(*texture.getImage(), fullFileName);
}
else if (fw.getOutputTextureFiles())
{ {
if (fileName.empty()) if (fileName.empty())
{ {

View File

@@ -47,10 +47,6 @@ public:
iss >> prec; iss >> prec;
fout.precision(prec); fout.precision(prec);
} }
if (opt=="OutputRelativeTextures")
{
fout.setOutputRelativeTextures(true);
}
if (opt=="OutputTextureFiles") if (opt=="OutputTextureFiles")
{ {
fout.setOutputTextureFiles(true); fout.setOutputTextureFiles(true);

View File

@@ -14,129 +14,173 @@
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <sstream>
using namespace osg; using namespace osg;
template <class T> template <class T>
unsigned char* read_bitmap_ascii(std::istream& fin, int width, int height) unsigned char* read_bitmap_ascii(FILE* fp, int width, int height)
{ {
T* data = new T[width*height]; T* data = new T[width*height];
T* dst = data;
T* end = data + width*height; T* end = data + width*height;
int x = 0; while(dst < end)
T* dst = end - width;
int value = 0;
while(dst >= data)
{ {
fin >> value; T value = 0;
if (!fin.good())
// read in characters looking for '0's and '1's, these
// values map to 255 and 0. Any other characters
// are silently ignored.
while(1)
{ {
delete [] data; int ch = fgetc(fp);
return NULL; if (feof(fp) || ferror(fp))
} {
delete [] data;
return NULL;
}
// place value in the image. 0 is white and anything else is black. if (ch == '0')
*(dst++) = value ? 0 : 255; {
value = 255;
// At end of each row, jump back two rows break;
++x; }
if (x == width) else if (ch == '1')
{ {
x = 0; value = 0;
dst -= 2*width; break;
} }
}
return reinterpret_cast<unsigned char*>(data);
}
template <class T>
unsigned char* read_grayscale_ascii(std::istream& fin, int width, int height, int max_value)
{
T* data = new T[width*height];
T* end = data + width*height;
int x = 0;
T* dst = end - width;
int value = 0;
float max = (sizeof(T) == 1) ? 255.0 : 65535.0;
while(dst >= data)
{
fin >> value;
if (!fin.good())
{
delete [] data;
return NULL;
} }
// place value in the image // place value in the image
*(dst++) = T(float(value)/float(max_value)*max); *(dst++) = value;
// At end of each row, jump back two rows
++x;
if (x == width)
{
x = 0;
dst -= 2*width;
}
} }
return reinterpret_cast<unsigned char*>(data); return reinterpret_cast<unsigned char*>(data);
} }
template <class T> template <class T>
unsigned char* read_color_ascii(std::istream& fin, int width, int height, int max_value) unsigned char* read_grayscale_ascii(FILE* fp, int width, int height)
{
T* data = new T[width*height];
T* dst = data;
T* end = data + width*height;
while(dst < end)
{
int ch;
T value = 0;
// read and discard any whitespace
// until a digit is reached
do
{
ch = fgetc(fp);
if (feof(fp) || ferror(fp))
{
delete [] data;
return NULL;
}
}
while(!isdigit(ch));
// continue reading digits and incrementally
// construct the integer value
do
{
value = 10*value + (ch - '0');
ch = fgetc(fp);
if (feof(fp) || ferror(fp))
{
delete [] data;
return NULL;
}
}
while(isdigit(ch));
// place value in the image
*(dst++) = value;
}
return reinterpret_cast<unsigned char*>(data);
}
template <class T>
unsigned char* read_color_ascii(FILE* fp, int width, int height)
{ {
T* data = new T[3*width*height]; T* data = new T[3*width*height];
T* dst = data;
T* end = data + 3*width*height; T* end = data + 3*width*height;
int x = 0; osg::notify(osg::NOTICE)<<"Width = "<<width<<std::endl;
T* dst = end - 3*width; osg::notify(osg::NOTICE)<<"Height = "<<height<<std::endl;
int value = 0;
float max = (sizeof(T) == 1) ? 255.0 : 65535.0; unsigned int numRead = 0;
while(dst >= data) while(dst < end)
{ {
fin >> value; int ch;
if (!fin.good()) T value = 0;
// read and discard any whitespace
// until a digit is reached
do
{ {
delete [] data; ch = fgetc(fp);
return NULL; if (feof(fp) || ferror(fp))
{
osg::notify(osg::NOTICE)<<"Error 1 "<<numRead<<std::endl;
delete [] data;
return NULL;
}
} }
while(!isdigit(ch));
// continue reading digits and incrementally
// construct the integer value
do
{
value = 10*value + (ch - '0');
ch = fgetc(fp);
if (feof(fp) || ferror(fp))
{
osg::notify(osg::NOTICE)<<"Error 2"<<std::endl;
delete [] data;
return NULL;
}
}
while(isdigit(ch));
++numRead;
// place value in the image // place value in the image
*(dst++) = T(float(value)/float(max_value)*max); *(dst++) = value;
// At end of the row, jump back two rows
++x;
if (x == width*3)
{
x = 0;
dst -= 6*width;
}
} }
osg::notify(osg::NOTICE)<<"Completed"<<std::endl;
return reinterpret_cast<unsigned char*>(data); return reinterpret_cast<unsigned char*>(data);
} }
template <class T> template <class T>
unsigned char* read_bitmap_binary(std::istream& fin, int width, int height) unsigned char* read_bitmap_binary(FILE* fp, int width, int height)
{ {
T* data = new T[width*height]; T* data = new T[width*height];
for(int y = height-1; y >= 0; --y) for(int y = 0; y < height; y++)
{ {
T* dst = data + (y+0)*width; T* dst = data + (y+0)*width;
T* end = data + (y+1)*width; T* end = data + (y+1)*width;
while(dst < end) while(dst < end)
{ {
unsigned char b = (unsigned char) fin.get(); unsigned char b = fgetc(fp);
if (!fin.good()) if (feof(fp) || ferror(fp))
{ {
fclose(fp);
delete [] data; delete [] data;
return NULL; return NULL;
} }
@@ -154,58 +198,48 @@ template <class T>
} }
template <class T> template <class T>
unsigned char* read_grayscale_binary(std::istream& fin, int width, int height) unsigned char* read_grayscale_binary(FILE* fp, int width, int height)
{ {
T* data = new T[width*height]; T* data = new T[width*height];
for(int y = height-1; y >= 0; --y) if (fread(data, sizeof(T)*width*height, 1, fp) != 1)
{ {
T* dst = data + y*width; fclose(fp);
fin.read((char*)dst, sizeof(T)*width); delete [] data;
if (!fin.good()) return NULL;
{
delete [] data;
return NULL;
}
} }
// if the machine is little endian swap the bytes around // if the machine is little endian swap the bytes around
if (sizeof(T) == 2 && getCpuByteOrder() == osg::LittleEndian) if (sizeof(T) > 1 && getCpuByteOrder() == osg::LittleEndian)
{ {
unsigned char *bs = reinterpret_cast<unsigned char *>(data); for(int i = 0; i < width*height; i++)
unsigned char *end = bs + sizeof(T)*width*height;
for (; bs < end; bs += 2)
{ {
unsigned char* bs = (unsigned char*)(&data[i]);
std::swap(bs[0], bs[1]); std::swap(bs[0], bs[1]);
} }
} }
return reinterpret_cast<unsigned char *>(data); return reinterpret_cast<unsigned char*>(data);
} }
template <class T> template <class T>
unsigned char* read_color_binary(std::istream& fin, int width, int height) unsigned char* read_color_binary(FILE* fp, int width, int height)
{ {
T* data = new T[3*width*height]; T* data = new T[3*width*height];
for(int y = height-1; y >= 0; --y) if (fread(data, 3*sizeof(T)*width*height, 1, fp) != 1)
{ {
T* dst = data + y*3*width; fclose(fp);
fin.read((char*)dst, sizeof(T)*3*width); delete [] data;
if (!fin.good()) return NULL;
{
delete [] data;
return NULL;
}
} }
// if the machine is little endian swap the bytes around // if the machine is little endian swap the bytes around
if (sizeof(T) == 2 && getCpuByteOrder() == osg::LittleEndian) if (sizeof(T) > 1 && getCpuByteOrder() == osg::LittleEndian)
{ {
unsigned char *bs = reinterpret_cast<unsigned char *>(data); for(int i = 0; i < 3*width*height; i++)
unsigned char *end = bs + sizeof(T)*3*width*height;
for (; bs < end; bs+=2)
{ {
unsigned char* bs = (unsigned char*)(&data[i]);
std::swap(bs[0], bs[1]); std::swap(bs[0], bs[1]);
} }
} }
@@ -226,23 +260,32 @@ class ReaderWriterPNM : public osgDB::ReaderWriter
virtual const char* className() const { return "PNM Image Reader/Writer"; } virtual const char* className() const { return "PNM Image Reader/Writer"; }
virtual ReadResult readImage(std::istream& fin, const osgDB::ReaderWriter::Options* options=NULL) const virtual ReadResult readImage(const std::string& file, const osgDB::ReaderWriter::Options* options) const
{ {
std::string ext = osgDB::getLowerCaseFileExtension(file);
if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;
std::string fileName = osgDB::findDataFile( file, options );
if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;
FILE *fp = NULL;
char line[300];
int ppmtype = 0; /* P1, P2, etc. */ int ppmtype = 0; /* P1, P2, etc. */
int width = 0; int width = 0;
int height = 0; int height = 0;
int max_value = 0; int max_value = 0;
// Open file.
fp = osgDB::fopen(fileName.c_str(), "rb");
// Read header items. // Read header items.
std::string line;
int row; int row;
for (row = 1; row <= 3; row++) for (row = 1; row <= 3; row++)
{ {
getline(fin, line); if ( fgets(line, 300, fp) == NULL)
if (!fin.good()) break;
return ReadResult::ERROR_IN_READING_FILE;
const char *cp = line.c_str(); char *cp = line;
while (*cp && isspace(*cp)) while (*cp && isspace(*cp))
cp++; cp++;
if (! *cp || *cp == '#') if (! *cp || *cp == '#')
@@ -260,10 +303,12 @@ class ReaderWriterPNM : public osgDB::ReaderWriter
} }
else if (row == 2) else if (row == 2)
{ {
std::istringstream istr(line); // Get the image size.
width = atoi(line);
istr >> width; char *cp = line + strspn(line, "\t \n\r");
istr >> height; cp += strspn(cp, "0123456789");
cp += strspn(line, "\t \n\r");
height = atoi(cp);
// pbm files don't have row 3 // pbm files don't have row 3
if (ppmtype == 1 || ppmtype == 4) if (ppmtype == 1 || ppmtype == 4)
@@ -275,8 +320,7 @@ class ReaderWriterPNM : public osgDB::ReaderWriter
else if (row == 3) else if (row == 3)
{ {
// Get the maximum value // Get the maximum value
std::istringstream istr(line); max_value = atoi(line);
istr >> max_value;
} }
} }
@@ -285,6 +329,7 @@ class ReaderWriterPNM : public osgDB::ReaderWriter
max_value <= 0 || max_value > 65535 || max_value <= 0 || max_value > 65535 ||
ppmtype < 1 || ppmtype > 6) ppmtype < 1 || ppmtype > 6)
{ {
fclose(fp);
return ReadResult::ERROR_IN_READING_FILE; return ReadResult::ERROR_IN_READING_FILE;
} }
@@ -297,24 +342,29 @@ class ReaderWriterPNM : public osgDB::ReaderWriter
dataType = GL_UNSIGNED_SHORT; dataType = GL_UNSIGNED_SHORT;
switch(ppmtype) switch(ppmtype)
{ {
case 1: // bitmap ascii
pixelFormat = GL_LUMINANCE;
data = read_bitmap_ascii<unsigned short>(fp, width, height);
break;
case 2: // grayscale ascii case 2: // grayscale ascii
pixelFormat = GL_LUMINANCE; pixelFormat = GL_LUMINANCE;
data = read_grayscale_ascii<unsigned short>(fin, width, height, max_value); data = read_grayscale_ascii<unsigned short>(fp, width, height);
break; break;
case 3: // color ascii case 3: // color ascii
pixelFormat = GL_RGB; pixelFormat = GL_RGB;
data = read_color_ascii<unsigned short>(fin, width, height, max_value); data = read_color_ascii<unsigned short>(fp, width, height);
break;
case 4: // bitmap binary
pixelFormat = GL_LUMINANCE;
data = read_bitmap_binary<unsigned short>(fp, width, height);
break; break;
case 5: // grayscale binary case 5: // grayscale binary
pixelFormat = GL_LUMINANCE; pixelFormat = GL_LUMINANCE;
data = read_grayscale_binary<unsigned short>(fin, width, height); data = read_grayscale_binary<unsigned short>(fp, width, height);
break; break;
case 6: // color binary case 6: // color binary
pixelFormat = GL_RGB; pixelFormat = GL_RGB;
data = read_color_binary<unsigned short>(fin, width, height); data = read_color_binary<unsigned short>(fp, width, height);
break;
default:
return ReadResult::ERROR_IN_READING_FILE;
break; break;
} }
} }
@@ -325,41 +375,44 @@ class ReaderWriterPNM : public osgDB::ReaderWriter
{ {
case 1: // bitmap ascii case 1: // bitmap ascii
pixelFormat = GL_LUMINANCE; pixelFormat = GL_LUMINANCE;
data = read_bitmap_ascii<unsigned char>(fin, width, height); data = read_bitmap_ascii<unsigned char>(fp, width, height);
break; break;
case 2: // grayscale ascii case 2: // grayscale ascii
pixelFormat = GL_LUMINANCE; pixelFormat = GL_LUMINANCE;
data = read_grayscale_ascii<unsigned char>(fin, width, height, max_value); data = read_grayscale_ascii<unsigned char>(fp, width, height);
break; break;
case 3: // color ascii case 3: // color ascii
pixelFormat = GL_RGB; pixelFormat = GL_RGB;
data = read_color_ascii<unsigned char>(fin, width, height, max_value); data = read_color_ascii<unsigned char>(fp, width, height);
break; break;
case 4: // bitmap binary case 4: // bitmap binary
pixelFormat = GL_LUMINANCE; pixelFormat = GL_LUMINANCE;
data = read_bitmap_binary<unsigned char>(fin, width, height); data = read_bitmap_binary<unsigned char>(fp, width, height);
break; break;
case 5: // grayscale binary case 5: // grayscale binary
pixelFormat = GL_LUMINANCE; pixelFormat = GL_LUMINANCE;
data = read_grayscale_binary<unsigned char>(fin, width, height); data = read_grayscale_binary<unsigned char>(fp, width, height);
break; break;
case 6: // color binary case 6: // color binary
pixelFormat = GL_RGB; pixelFormat = GL_RGB;
data = read_color_binary<unsigned char>(fin, width, height); data = read_color_binary<unsigned char>(fp, width, height);
break;
default:
return ReadResult::ERROR_IN_READING_FILE;
break; break;
} }
} }
if (data == NULL) if (data == NULL)
{ {
if (fp)
fclose(fp);
return ReadResult::FILE_NOT_HANDLED; return ReadResult::FILE_NOT_HANDLED;
} }
if (fp)
fclose(fp);
osg::Image* pOsgImage = new osg::Image(); osg::Image* pOsgImage = new osg::Image();
pOsgImage->setFileName(fileName.c_str());
pOsgImage->setImage(width, height, 1, pOsgImage->setImage(width, height, 1,
pixelFormat, pixelFormat,
pixelFormat, pixelFormat,
@@ -375,24 +428,6 @@ class ReaderWriterPNM : public osgDB::ReaderWriter
return pOsgImage; return pOsgImage;
} }
virtual ReadResult readImage(const std::string& file, const osgDB::ReaderWriter::Options* options) const
{
std::string ext = osgDB::getLowerCaseFileExtension(file);
if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;
std::string fileName = osgDB::findDataFile( file, options );
if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;
std::ifstream fin(fileName.c_str());
if (!fin.good())
return ReadResult::ERROR_IN_READING_FILE;
ReadResult rr = readImage(fin, options);
fin.close();
if (rr.validImage()) rr.getImage()->setFileName(file);
return rr;
}
virtual WriteResult writeImage(const osg::Image& image,std::ostream& fout,const osgDB::ReaderWriter::Options* options) const virtual WriteResult writeImage(const osg::Image& image,std::ostream& fout,const osgDB::ReaderWriter::Options* options) const
{ {
bool ascii = (options && options->getOptionString().find("ascii")!=std::string::npos); bool ascii = (options && options->getOptionString().find("ascii")!=std::string::npos);

View File

@@ -22,7 +22,6 @@
#include<cassert> #include<cassert>
#include<deque> #include<deque>
#include<algorithm> #include<algorithm>
#include <iterator>
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>

View File

@@ -163,7 +163,6 @@ void MultiSwitch::expandToEncompassSwitchSet(unsigned int switchSet)
// need to expand arrays. // need to expand arrays.
unsigned int originalSize = _values.size(); unsigned int originalSize = _values.size();
_values.resize(switchSet+1); _values.resize(switchSet+1);
_valueNames.resize(switchSet+1);
for(unsigned int i=originalSize;i<=switchSet;++i) for(unsigned int i=originalSize;i<=switchSet;++i)
{ {
ValueList& values = _values[i]; ValueList& values = _values[i];
@@ -233,10 +232,3 @@ void MultiSwitch::setValueList(unsigned int switchSet, const ValueList& values)
_values[switchSet] = values; _values[switchSet] = values;
} }
void MultiSwitch::setValueName(unsigned int switchSet, const std::string& name)
{
expandToEncompassSwitchSet(switchSet);
_valueNames[switchSet] = name;
}

View File

@@ -3,8 +3,6 @@
#include <osg/Notify> #include <osg/Notify>
#include <osg/Math> #include <osg/Math>
#include <iterator>
using namespace osgText; using namespace osgText;
//////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////

View File

@@ -26,9 +26,6 @@
#include "DefaultFont.h" #include "DefaultFont.h"
#include <osg/GLExtensions>
#include <osg/GL>
using namespace osg; using namespace osg;
using namespace osgText; using namespace osgText;
@@ -36,9 +33,8 @@ using namespace osgText;
Text::Text(): Text::Text():
_color(1.0f,1.0f,1.0f,1.0f), _color(1.0f,1.0f,1.0f,1.0f),
_enableDepthWrites(true),
_backdropType(NONE), _backdropType(NONE),
_backdropImplementation(DELAYED_DEPTH_WRITES), _backdropImplementation(DEPTH_RANGE),
_backdropHorizontalOffset(0.07f), _backdropHorizontalOffset(0.07f),
_backdropVerticalOffset(0.07f), _backdropVerticalOffset(0.07f),
_backdropColor(0.0f, 0.0f, 0.0f, 1.0f), _backdropColor(0.0f, 0.0f, 0.0f, 1.0f),
@@ -46,14 +42,13 @@ Text::Text():
_colorGradientTopLeft(1.0f, 0.0f, 0.0f, 1.0f), _colorGradientTopLeft(1.0f, 0.0f, 0.0f, 1.0f),
_colorGradientBottomLeft(0.0f, 1.0f, 0.0f, 1.0f), _colorGradientBottomLeft(0.0f, 1.0f, 0.0f, 1.0f),
_colorGradientBottomRight(0.0f, 0.0f, 1.0f, 1.0f), _colorGradientBottomRight(0.0f, 0.0f, 1.0f, 1.0f),
_colorGradientTopRight(1.0f, 1.0f, 1.0f, 1.0f) _colorGradientTopRight(1.0f, 1.0f, 1.0f, 1.0f)
{} {}
Text::Text(const Text& text,const osg::CopyOp& copyop): Text::Text(const Text& text,const osg::CopyOp& copyop):
osgText::TextBase(text,copyop), osgText::TextBase(text,copyop),
_font(text._font), _font(text._font),
_color(text._color), _color(text._color),
_enableDepthWrites(text._enableDepthWrites),
_backdropType(text._backdropType), _backdropType(text._backdropType),
_backdropImplementation(text._backdropImplementation), _backdropImplementation(text._backdropImplementation),
_backdropHorizontalOffset(text._backdropHorizontalOffset), _backdropHorizontalOffset(text._backdropHorizontalOffset),
@@ -457,31 +452,16 @@ void Text::computeGlyphRepresentation()
glyphquad._glyphs.push_back(glyph); glyphquad._glyphs.push_back(glyph);
glyphquad._lineNumbers.push_back(lineNumber); glyphquad._lineNumbers.push_back(lineNumber);
// Adjust coordinates and texture coordinates to avoid
// clipping the edges of antialiased characters.
osg::Vec2 mintc = glyph->getMinTexCoord();
osg::Vec2 maxtc = glyph->getMaxTexCoord();
osg::Vec2 vDiff = maxtc - mintc;
float fHorizTCMargin = 1.0f / glyph->getTexture()->getTextureWidth();
float fVertTCMargin = 1.0f / glyph->getTexture()->getTextureHeight();
float fHorizQuadMargin = vDiff.x() == 0.0f ? 0.0f : width * fHorizTCMargin / vDiff.x();
float fVertQuadMargin = vDiff.y() == 0.0f ? 0.0f : height * fVertTCMargin / vDiff.y();
mintc.x() -= fHorizTCMargin;
mintc.y() -= fVertTCMargin;
maxtc.x() += fHorizTCMargin;
maxtc.y() += fVertTCMargin;
// set up the coords of the quad // set up the coords of the quad
osg::Vec2 upLeft = local+osg::Vec2(0.0f-fHorizQuadMargin,height+fVertQuadMargin); glyphquad._coords.push_back(local+osg::Vec2(0.0f,height));
osg::Vec2 lowLeft = local+osg::Vec2(0.0f-fHorizQuadMargin,0.0f-fVertQuadMargin); glyphquad._coords.push_back(local+osg::Vec2(0.0f,0.0f));
osg::Vec2 lowRight = local+osg::Vec2(width+fHorizQuadMargin,0.0f-fVertQuadMargin); glyphquad._coords.push_back(local+osg::Vec2(width,0.0f));
osg::Vec2 upRight = local+osg::Vec2(width+fHorizQuadMargin,height+fVertQuadMargin); glyphquad._coords.push_back(local+osg::Vec2(width,height));
glyphquad._coords.push_back(upLeft);
glyphquad._coords.push_back(lowLeft);
glyphquad._coords.push_back(lowRight);
glyphquad._coords.push_back(upRight);
// set up the tex coords of the quad // set up the tex coords of the quad
const osg::Vec2& mintc = glyph->getMinTexCoord();
const osg::Vec2& maxtc = glyph->getMaxTexCoord();
glyphquad._texcoords.push_back(osg::Vec2(mintc.x(),maxtc.y())); glyphquad._texcoords.push_back(osg::Vec2(mintc.x(),maxtc.y()));
glyphquad._texcoords.push_back(osg::Vec2(mintc.x(),mintc.y())); glyphquad._texcoords.push_back(osg::Vec2(mintc.x(),mintc.y()));
glyphquad._texcoords.push_back(osg::Vec2(maxtc.x(),mintc.y())); glyphquad._texcoords.push_back(osg::Vec2(maxtc.x(),mintc.y()));
@@ -493,19 +473,20 @@ void Text::computeGlyphRepresentation()
{ {
case LEFT_TO_RIGHT: case LEFT_TO_RIGHT:
cursor.x() += glyph->getHorizontalAdvance() * wr; cursor.x() += glyph->getHorizontalAdvance() * wr;
_textBB.expandBy(osg::Vec3(lowLeft.x(), lowLeft.y(), 0.0f)); //lower left corner _textBB.expandBy(osg::Vec3(local.x(),local.y(),0.0f)); //lower left corner
_textBB.expandBy(osg::Vec3(upRight.x(), upRight.y(), 0.0f)); //upper right corner _textBB.expandBy(osg::Vec3(cursor.x(),local.y()+height,0.0f)); //upper right corner
break; break;
case VERTICAL: case VERTICAL:
cursor.y() -= glyph->getVerticalAdvance() * hr; cursor.y() -= glyph->getVerticalAdvance() *hr;
_textBB.expandBy(osg::Vec3(upLeft.x(),upLeft.y(),0.0f)); //upper left corner _textBB.expandBy(osg::Vec3(local.x(),local.y()+height,0.0f)); //upper left corner
_textBB.expandBy(osg::Vec3(lowRight.x(),lowRight.y(),0.0f)); //lower right corner _textBB.expandBy(osg::Vec3(local.x()+width,cursor.y(),0.0f)); //lower right corner
break; break;
case RIGHT_TO_LEFT: case RIGHT_TO_LEFT:
_textBB.expandBy(osg::Vec3(lowRight.x(),lowRight.y(),0.0f)); //lower right corner _textBB.expandBy(osg::Vec3(local.x()+width,local.y(),0.0f)); //lower right corner
_textBB.expandBy(osg::Vec3(upLeft.x(),upLeft.y(),0.0f)); //upper left corner _textBB.expandBy(osg::Vec3(cursor.x(),local.y()+height,0.0f)); //upper left corner
break; break;
} }
previous_charcode = charcode; previous_charcode = charcode;
} }
@@ -1360,7 +1341,7 @@ void Text::drawImplementation(osg::State& state, const osg::Vec4& colorMultiplie
// So this is a pick your poison approach. Each alternative // So this is a pick your poison approach. Each alternative
// backend has trade-offs associated with it, but with luck, // backend has trade-offs associated with it, but with luck,
// the user may find that works for them. // the user may find that works for them.
if(_backdropType != NONE && _backdropImplementation != DELAYED_DEPTH_WRITES) if(_backdropType != NONE)
{ {
switch(_backdropImplementation) switch(_backdropImplementation)
{ {
@@ -1382,7 +1363,7 @@ void Text::drawImplementation(osg::State& state, const osg::Vec4& colorMultiplie
} }
else else
{ {
renderWithDelayedDepthWrites(state,colorMultiplier); renderOnlyForegroundText(state,colorMultiplier);
} }
} }
@@ -1773,137 +1754,7 @@ void Text::renderOnlyForegroundText(osg::State& state, const osg::Vec4& colorMul
drawForegroundText(state, glyphquad, colorMultiplier); drawForegroundText(state, glyphquad, colorMultiplier);
} }
}
void Text::renderWithDelayedDepthWrites(osg::State& state, const osg::Vec4& colorMultiplier) const
{
glPushAttrib( _enableDepthWrites ? (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) : GL_DEPTH_BUFFER_BIT);
// Render to color buffer without writing to depth buffer.
glDepthMask(GL_FALSE);
drawTextWithBackdrop(state,colorMultiplier);
// Render to depth buffer if depth writes requested.
if( _enableDepthWrites )
{
glDepthMask(GL_TRUE);
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
drawTextWithBackdrop(state,colorMultiplier);
}
glPopAttrib();
}
//
// NOTE: This section was taken from osg svn trunk, and was in the State
// class. It is only included here to implement the osgText clipping patch
// r11768. [2011-05-24 Eric Sokolowsky]
//
typedef std::vector<GLushort> Indices;
Indices _quadIndices[6];
// This function originally called glDrawElementsInstanced if available.
// Since this is a function only available in OpenGL 3.1 and later, I
// removed its call for this patch. [2011-05-24 Eric Sokolowsky]
inline void glDrawElementsInstanced(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount )
{
glDrawElements(mode, count, type, indices);
}
void drawQuads(GLint first, GLsizei count, GLsizei primCount = 0)
{
// OSG_NOTICE<<"State::drawQuads("<<first<<", "<<count<<")"<<std::endl;
unsigned int array = first % 4;
unsigned int offsetFirst = ((first-array) / 4) * 6;
unsigned int numQuads = (count/4);
unsigned int numIndices = numQuads * 6;
unsigned int endOfIndices = offsetFirst+numIndices;
Indices& indices = _quadIndices[array];
if (endOfIndices>65536)
{
OSG_NOTICE<<"Warning: State::drawQuads("<<first<<", "<<count<<") too large handle in remapping to ushort glDrawElements."<<std::endl;
endOfIndices = 65536;
}
if (endOfIndices >= indices.size())
{
// we need to expand the _indexArray to be big enough to cope with all the quads required.
unsigned int numExistingQuads = indices.size()/6;
unsigned int numRequiredQuads = endOfIndices/6;
indices.reserve(endOfIndices);
for(unsigned int i=numExistingQuads; i<numRequiredQuads; ++i)
{
unsigned int base = i*4 + array;
indices.push_back(base);
indices.push_back(base+1);
indices.push_back(base+3);
indices.push_back(base+1);
indices.push_back(base+2);
indices.push_back(base+3);
// OSG_NOTICE<<" adding quad indices ("<<base<<")"<<std::endl;
}
}
// if (array!=0) return;
// OSG_NOTICE<<" glDrawElements(GL_TRIANGLES, "<<numIndices<<", GL_UNSIGNED_SHORT, "<<&(indices[base])<<")"<<std::endl;
glDrawElementsInstanced(GL_TRIANGLES, numIndices, GL_UNSIGNED_SHORT, &(indices[offsetFirst]), primCount);
}
//
// End of section taken from State.cpp.
//
void Text::drawTextWithBackdrop(osg::State& state, const osg::Vec4& colorMultiplier) const
{
unsigned int contextID = state.getContextID();
for(TextureGlyphQuadMap::iterator titr=_textureGlyphQuadMap.begin();
titr!=_textureGlyphQuadMap.end();
++titr)
{
// need to set the texture here...
state.applyTextureAttribute(0,titr->first.get());
const GlyphQuads& glyphquad = titr->second;
if(_backdropType != NONE)
{
unsigned int backdrop_index;
unsigned int max_backdrop_index;
if(_backdropType == OUTLINE)
{
backdrop_index = 0;
max_backdrop_index = 8;
}
else
{
backdrop_index = _backdropType;
max_backdrop_index = _backdropType+1;
}
state.setTexCoordPointer( 0, 2, GL_FLOAT, 0, &(glyphquad._texcoords.front()));
state.disableColorPointer();
// Original r11768 patch changed here [2011-05-24 Eric Sokolowsky]
//state.Color(_backdropColor.r(),_backdropColor.g(),_backdropColor.b(),_backdropColor.a());
glColor4f(_backdropColor.r(),_backdropColor.g(),_backdropColor.b(),_backdropColor.a());
for( ; backdrop_index < max_backdrop_index; backdrop_index++)
{
const GlyphQuads::Coords3& transformedBackdropCoords = glyphquad._transformedBackdropCoords[backdrop_index][contextID];
if (!transformedBackdropCoords.empty())
{
state.setVertexPointer( 3, GL_FLOAT, 0, &(transformedBackdropCoords.front()));
// Original r11768 patch changed here [2011-05-24 Eric Sokolowsky]
//state.drawQuads(0,transformedBackdropCoords.size());
drawQuads(0,transformedBackdropCoords.size());
}
}
}
drawForegroundText(state, glyphquad, colorMultiplier);
}
} }

View File

@@ -23,7 +23,6 @@
#include <algorithm> #include <algorithm>
#include <set> #include <set>
#include <map> //GWM July 2005 map is used in constraints. #include <map> //GWM July 2005 map is used in constraints.
#include <iterator>
#include <osgUtil/Tessellator> // tessellator triangulates the constrained triangles #include <osgUtil/Tessellator> // tessellator triangulates the constrained triangles
namespace osgUtil namespace osgUtil

View File

@@ -43,7 +43,6 @@
#include <algorithm> #include <algorithm>
#include <numeric> #include <numeric>
#include <sstream> #include <sstream>
#include <iterator>
using namespace osgUtil; using namespace osgUtil;

View File

@@ -15,7 +15,6 @@
#include <osg/Notify> #include <osg/Notify>
#include <osg/Texture1D> #include <osg/Texture1D>
#include <osg/Texture2D> #include <osg/Texture2D>
#include <osg/Texture2DMultisample>
#include <osg/Texture3D> #include <osg/Texture3D>
#include <osg/TextureRectangle> #include <osg/TextureRectangle>
#include <osg/TextureCubeMap> #include <osg/TextureCubeMap>
@@ -276,7 +275,6 @@ void RenderStage::runCameraSetUp(osg::RenderInfo& renderInfo)
osg::Texture* texture = itr->second._texture.get(); osg::Texture* texture = itr->second._texture.get();
osg::Texture1D* texture1D = 0; osg::Texture1D* texture1D = 0;
osg::Texture2D* texture2D = 0; osg::Texture2D* texture2D = 0;
osg::Texture2DMultisample* texture2DMS = 0;
osg::Texture3D* texture3D = 0; osg::Texture3D* texture3D = 0;
osg::TextureCubeMap* textureCubeMap = 0; osg::TextureCubeMap* textureCubeMap = 0;
osg::TextureRectangle* textureRectangle = 0; osg::TextureRectangle* textureRectangle = 0;
@@ -294,13 +292,6 @@ void RenderStage::runCameraSetUp(osg::RenderInfo& renderInfo)
texture2D->setTextureSize(width,height); texture2D->setTextureSize(width,height);
} }
} }
else if (0 != (texture2DMS = dynamic_cast<osg::Texture2DMultisample*>(texture)))
{
if (texture2DMS->getTextureWidth()==0 || texture2DMS->getTextureHeight()==0)
{
texture2DMS->setTextureSize(width,height);
}
}
else if (0 != (texture3D = dynamic_cast<osg::Texture3D*>(texture))) else if (0 != (texture3D = dynamic_cast<osg::Texture3D*>(texture)))
{ {
if (texture3D->getTextureWidth()==0 || texture3D->getTextureHeight()==0 || texture3D->getTextureDepth()==0 ) if (texture3D->getTextureWidth()==0 || texture3D->getTextureHeight()==0 || texture3D->getTextureDepth()==0 )

View File

@@ -27,8 +27,6 @@
#include <osg/GLU> #include <osg/GLU>
#include <iterator>
using namespace osg; using namespace osg;
using namespace osgUtil; using namespace osgUtil;

View File

@@ -21,7 +21,6 @@
#include <set> #include <set>
#include <list> #include <list>
#include <algorithm> #include <algorithm>
#include <iterator>
using namespace osgUtil; using namespace osgUtil;

View File

@@ -20,7 +20,6 @@
#include <stdio.h> #include <stdio.h>
#include <algorithm> #include <algorithm>
#include <map> #include <map>
#include <iterator>
#include "TriStrip_tri_stripper.h" #include "TriStrip_tri_stripper.h"

View File

@@ -25,8 +25,6 @@
#include <osgUtil/Optimizer> #include <osgUtil/Optimizer>
#include <osgUtil/IntersectionVisitor> #include <osgUtil/IntersectionVisitor>
#include <iterator>
using namespace osgViewer; using namespace osgViewer;
class CollectedCoordinateSystemNodesVisitor : public osg::NodeVisitor class CollectedCoordinateSystemNodesVisitor : public osg::NodeVisitor

View File

@@ -179,11 +179,11 @@ suppress reflector "osg::MixinVector< GLuint >"
suppress reflector "OpenThreads::Atomic" suppress reflector "OpenThreads::Atomic"
suppress reflector "OpenThreads::AtomicPtr" suppress reflector "OpenThreads::AtomicPtr"
#suppress reflector "osg::BoundingBoxImpl< osg::Vec3f >" suppress reflector "osg::BoundingBoxImpl< osg::Vec3f >"
#suppress reflector "osg::BoundingBoxImpl< osg::Vec3d >" suppress reflector "osg::BoundingBoxImpl< osg::Vec3d >"
#suppress reflector "osg::BoundingSphereImpl< osg::Vec3f >" suppress reflector "osg::BoundingSphereImpl< osg::Vec3f >"
#suppress reflector "osg::BoundingSphereImpl< osg::Vec3d >" suppress reflector "osg::BoundingSphereImpl< osg::Vec3d >"
############################################################################# #############################################################################
@@ -237,12 +237,11 @@ end
############################################################################# #############################################################################
# Doxygen fails to detect that # Doxygen fails to detect that /osg::Texture(1D|2D|3D|Rectangle)/ and
# /osg::Texture(1D|2D|2DMultisample|3D|Rectangle)/ and # osgText::Font::GlyphTexture are not-abstract class, so we need
# osgText::Font::GlyphTexture are not-abstract class, so we need to # to specify that manually
# specify that manually
configure reflector /osg::Texture(1D|2D|2DMultisample|3D|Rectangle)/ configure reflector /osg::Texture(1D|2D|3D|Rectangle)/
object-type object-type
end end
@@ -436,56 +435,3 @@ configure reflector "osgManipulator::MotionCommand"
replace with "" replace with ""
end end
end end
#############################################################################
# Fix bounding box/sphere - member templates aren't supported
configure reflector "osg::BoundingBoxImpl< osg::Vec3d >"
configure method /.*_BoundingBoxImpl.*_VT_.*/
replace with ""
end
configure method /.*_BoundingSphereImpl.*_VT_.*/
replace with ""
end
end
configure reflector "osg::BoundingBoxImpl< osg::Vec3f >"
configure method /.*_BoundingBoxImpl.*_VT_.*/
replace with ""
end
configure method /.*_BoundingSphereImpl.*_VT_.*/
replace with ""
end
end
configure reflector "osg::BoundingSphereImpl< osg::Vec3d >"
configure method /.*_BoundingBoxImpl.*_VT_.*/
replace with ""
end
configure method /.*_BoundingSphereImpl.*_VT_.*/
replace with ""
end
end
configure reflector "osg::BoundingSphereImpl< osg::Vec3f >"
configure method /.*_BoundingBoxImpl.*_VT_.*/
replace with ""
end
configure method /.*_BoundingSphereImpl.*_VT_.*/
replace with ""
end
end
#############################################################################
# Fix osgShadow wrapper crashing on load
# Might not be needed when BoundingSphere/Box is fixed.
configure reflector "osgShadow::ConvexPolyhedron"
configure method /.*_computeBoundingBox_.*/
replace with ""
end
end

View File

@@ -30,299 +30,3 @@ TYPE_NAME_ALIAS(osg::BoundingBoxImpl< osg::Vec3d >, osg::BoundingBoxd)
TYPE_NAME_ALIAS(osg::BoundingBoxd, osg::BoundingBox) TYPE_NAME_ALIAS(osg::BoundingBoxd, osg::BoundingBox)
BEGIN_VALUE_REFLECTOR(osg::BoundingBoxImpl< osg::Vec3d >)
I_DeclaringFile("osg/BoundingBox");
I_Constructor0(____BoundingBoxImpl,
"Creates an uninitialized bounding box. ",
"");
I_Constructor6(IN, osg::BoundingBoxImpl< osg::Vec3d >::value_type, xmin, IN, osg::BoundingBoxImpl< osg::Vec3d >::value_type, ymin, IN, osg::BoundingBoxImpl< osg::Vec3d >::value_type, zmin, IN, osg::BoundingBoxImpl< osg::Vec3d >::value_type, xmax, IN, osg::BoundingBoxImpl< osg::Vec3d >::value_type, ymax, IN, osg::BoundingBoxImpl< osg::Vec3d >::value_type, zmax,
____BoundingBoxImpl__value_type__value_type__value_type__value_type__value_type__value_type,
"Creates a bounding box initialized to the given extents. ",
"");
I_Constructor2(IN, const osg::BoundingBoxImpl< osg::Vec3d >::vec_type &, min, IN, const osg::BoundingBoxImpl< osg::Vec3d >::vec_type &, max,
____BoundingBoxImpl__C5_vec_type_R1__C5_vec_type_R1,
"Creates a bounding box initialized to the given extents. ",
"");
I_Method0(void, init,
Properties::NON_VIRTUAL,
__void__init,
"Clear the bounding box. ",
"Erases existing minimum and maximum extents. ");
I_Method0(bool, valid,
Properties::NON_VIRTUAL,
__bool__valid,
"Returns true if the bounding box extents are valid, false otherwise. ",
"");
I_Method6(void, set, IN, osg::BoundingBoxImpl< osg::Vec3d >::value_type, xmin, IN, osg::BoundingBoxImpl< osg::Vec3d >::value_type, ymin, IN, osg::BoundingBoxImpl< osg::Vec3d >::value_type, zmin, IN, osg::BoundingBoxImpl< osg::Vec3d >::value_type, xmax, IN, osg::BoundingBoxImpl< osg::Vec3d >::value_type, ymax, IN, osg::BoundingBoxImpl< osg::Vec3d >::value_type, zmax,
Properties::NON_VIRTUAL,
__void__set__value_type__value_type__value_type__value_type__value_type__value_type,
"Sets the bounding box extents. ",
"");
I_Method2(void, set, IN, const osg::BoundingBoxImpl< osg::Vec3d >::vec_type &, min, IN, const osg::BoundingBoxImpl< osg::Vec3d >::vec_type &, max,
Properties::NON_VIRTUAL,
__void__set__C5_vec_type_R1__C5_vec_type_R1,
"Sets the bounding box extents. ",
"");
I_Method0(osg::BoundingBoxImpl< osg::Vec3d >::value_type &, xMin,
Properties::NON_VIRTUAL,
__value_type_R1__xMin,
"",
"");
I_Method0(osg::BoundingBoxImpl< osg::Vec3d >::value_type, xMin,
Properties::NON_VIRTUAL,
__value_type__xMin,
"",
"");
I_Method0(osg::BoundingBoxImpl< osg::Vec3d >::value_type &, yMin,
Properties::NON_VIRTUAL,
__value_type_R1__yMin,
"",
"");
I_Method0(osg::BoundingBoxImpl< osg::Vec3d >::value_type, yMin,
Properties::NON_VIRTUAL,
__value_type__yMin,
"",
"");
I_Method0(osg::BoundingBoxImpl< osg::Vec3d >::value_type &, zMin,
Properties::NON_VIRTUAL,
__value_type_R1__zMin,
"",
"");
I_Method0(osg::BoundingBoxImpl< osg::Vec3d >::value_type, zMin,
Properties::NON_VIRTUAL,
__value_type__zMin,
"",
"");
I_Method0(osg::BoundingBoxImpl< osg::Vec3d >::value_type &, xMax,
Properties::NON_VIRTUAL,
__value_type_R1__xMax,
"",
"");
I_Method0(osg::BoundingBoxImpl< osg::Vec3d >::value_type, xMax,
Properties::NON_VIRTUAL,
__value_type__xMax,
"",
"");
I_Method0(osg::BoundingBoxImpl< osg::Vec3d >::value_type &, yMax,
Properties::NON_VIRTUAL,
__value_type_R1__yMax,
"",
"");
I_Method0(osg::BoundingBoxImpl< osg::Vec3d >::value_type, yMax,
Properties::NON_VIRTUAL,
__value_type__yMax,
"",
"");
I_Method0(osg::BoundingBoxImpl< osg::Vec3d >::value_type &, zMax,
Properties::NON_VIRTUAL,
__value_type_R1__zMax,
"",
"");
I_Method0(osg::BoundingBoxImpl< osg::Vec3d >::value_type, zMax,
Properties::NON_VIRTUAL,
__value_type__zMax,
"",
"");
I_Method0(const osg::BoundingBoxImpl< osg::Vec3d >::vec_type, center,
Properties::NON_VIRTUAL,
__C5_vec_type__center,
"Calculates and returns the bounding box center. ",
"");
I_Method0(osg::BoundingBoxImpl< osg::Vec3d >::value_type, radius,
Properties::NON_VIRTUAL,
__value_type__radius,
"Calculates and returns the bounding box radius. ",
"");
I_Method0(osg::BoundingBoxImpl< osg::Vec3d >::value_type, radius2,
Properties::NON_VIRTUAL,
__value_type__radius2,
"Calculates and returns the squared length of the bounding box radius. ",
"Note, radius2() is faster to calculate than radius(). ");
I_Method1(const osg::BoundingBoxImpl< osg::Vec3d >::vec_type, corner, IN, unsigned int, pos,
Properties::NON_VIRTUAL,
__C5_vec_type__corner__unsigned_int,
"Returns a specific corner of the bounding box. ",
"pos specifies the corner as a number between 0 and 7. Each bit selects an axis, X, Y, or Z from least- to most-significant. Unset bits select the minimum value for that axis, and set bits select the maximum. ");
I_Method1(void, expandBy, IN, const osg::BoundingBoxImpl< osg::Vec3d >::vec_type &, v,
Properties::NON_VIRTUAL,
__void__expandBy__C5_vec_type_R1,
"Expands the bounding box to include the given coordinate. ",
"If the box is uninitialized, set its min and max extents to v. ");
I_Method3(void, expandBy, IN, osg::BoundingBoxImpl< osg::Vec3d >::value_type, x, IN, osg::BoundingBoxImpl< osg::Vec3d >::value_type, y, IN, osg::BoundingBoxImpl< osg::Vec3d >::value_type, z,
Properties::NON_VIRTUAL,
__void__expandBy__value_type__value_type__value_type,
"Expands the bounding box to include the given coordinate. ",
"If the box is uninitialized, set its min and max extents to Vec3(x,y,z). ");
I_Method1(void, expandBy, IN, const osg::BoundingBoxImpl< osg::Vec3d > &, bb,
Properties::NON_VIRTUAL,
__void__expandBy__C5_BoundingBoxImpl_R1,
"Expands this bounding box to include the given bounding box. ",
"If this box is uninitialized, set it equal to bb. ");
I_Method1(osg::BoundingBoxImpl< osg::Vec3d >, intersect, IN, const osg::BoundingBoxImpl< osg::Vec3d > &, bb,
Properties::NON_VIRTUAL,
__BoundingBoxImpl__intersect__C5_BoundingBoxImpl_R1,
"Returns the intersection of this bounding box and the specified bounding box. ",
"");
I_Method1(bool, intersects, IN, const osg::BoundingBoxImpl< osg::Vec3d > &, bb,
Properties::NON_VIRTUAL,
__bool__intersects__C5_BoundingBoxImpl_R1,
"Return true if this bounding box intersects the specified bounding box. ",
"");
I_Method1(bool, contains, IN, const osg::BoundingBoxImpl< osg::Vec3d >::vec_type &, v,
Properties::NON_VIRTUAL,
__bool__contains__C5_vec_type_R1,
"Returns true if this bounding box contains the specified coordinate. ",
"");
I_PublicMemberProperty(osg::BoundingBoxImpl< osg::Vec3d >::vec_type, _min);
I_PublicMemberProperty(osg::BoundingBoxImpl< osg::Vec3d >::vec_type, _max);
END_REFLECTOR
BEGIN_VALUE_REFLECTOR(osg::BoundingBoxImpl< osg::Vec3f >)
I_DeclaringFile("osg/BoundingBox");
I_Constructor0(____BoundingBoxImpl,
"Creates an uninitialized bounding box. ",
"");
I_Constructor6(IN, osg::BoundingBoxImpl< osg::Vec3f >::value_type, xmin, IN, osg::BoundingBoxImpl< osg::Vec3f >::value_type, ymin, IN, osg::BoundingBoxImpl< osg::Vec3f >::value_type, zmin, IN, osg::BoundingBoxImpl< osg::Vec3f >::value_type, xmax, IN, osg::BoundingBoxImpl< osg::Vec3f >::value_type, ymax, IN, osg::BoundingBoxImpl< osg::Vec3f >::value_type, zmax,
____BoundingBoxImpl__value_type__value_type__value_type__value_type__value_type__value_type,
"Creates a bounding box initialized to the given extents. ",
"");
I_Constructor2(IN, const osg::BoundingBoxImpl< osg::Vec3f >::vec_type &, min, IN, const osg::BoundingBoxImpl< osg::Vec3f >::vec_type &, max,
____BoundingBoxImpl__C5_vec_type_R1__C5_vec_type_R1,
"Creates a bounding box initialized to the given extents. ",
"");
I_Method0(void, init,
Properties::NON_VIRTUAL,
__void__init,
"Clear the bounding box. ",
"Erases existing minimum and maximum extents. ");
I_Method0(bool, valid,
Properties::NON_VIRTUAL,
__bool__valid,
"Returns true if the bounding box extents are valid, false otherwise. ",
"");
I_Method6(void, set, IN, osg::BoundingBoxImpl< osg::Vec3f >::value_type, xmin, IN, osg::BoundingBoxImpl< osg::Vec3f >::value_type, ymin, IN, osg::BoundingBoxImpl< osg::Vec3f >::value_type, zmin, IN, osg::BoundingBoxImpl< osg::Vec3f >::value_type, xmax, IN, osg::BoundingBoxImpl< osg::Vec3f >::value_type, ymax, IN, osg::BoundingBoxImpl< osg::Vec3f >::value_type, zmax,
Properties::NON_VIRTUAL,
__void__set__value_type__value_type__value_type__value_type__value_type__value_type,
"Sets the bounding box extents. ",
"");
I_Method2(void, set, IN, const osg::BoundingBoxImpl< osg::Vec3f >::vec_type &, min, IN, const osg::BoundingBoxImpl< osg::Vec3f >::vec_type &, max,
Properties::NON_VIRTUAL,
__void__set__C5_vec_type_R1__C5_vec_type_R1,
"Sets the bounding box extents. ",
"");
I_Method0(osg::BoundingBoxImpl< osg::Vec3f >::value_type &, xMin,
Properties::NON_VIRTUAL,
__value_type_R1__xMin,
"",
"");
I_Method0(osg::BoundingBoxImpl< osg::Vec3f >::value_type, xMin,
Properties::NON_VIRTUAL,
__value_type__xMin,
"",
"");
I_Method0(osg::BoundingBoxImpl< osg::Vec3f >::value_type &, yMin,
Properties::NON_VIRTUAL,
__value_type_R1__yMin,
"",
"");
I_Method0(osg::BoundingBoxImpl< osg::Vec3f >::value_type, yMin,
Properties::NON_VIRTUAL,
__value_type__yMin,
"",
"");
I_Method0(osg::BoundingBoxImpl< osg::Vec3f >::value_type &, zMin,
Properties::NON_VIRTUAL,
__value_type_R1__zMin,
"",
"");
I_Method0(osg::BoundingBoxImpl< osg::Vec3f >::value_type, zMin,
Properties::NON_VIRTUAL,
__value_type__zMin,
"",
"");
I_Method0(osg::BoundingBoxImpl< osg::Vec3f >::value_type &, xMax,
Properties::NON_VIRTUAL,
__value_type_R1__xMax,
"",
"");
I_Method0(osg::BoundingBoxImpl< osg::Vec3f >::value_type, xMax,
Properties::NON_VIRTUAL,
__value_type__xMax,
"",
"");
I_Method0(osg::BoundingBoxImpl< osg::Vec3f >::value_type &, yMax,
Properties::NON_VIRTUAL,
__value_type_R1__yMax,
"",
"");
I_Method0(osg::BoundingBoxImpl< osg::Vec3f >::value_type, yMax,
Properties::NON_VIRTUAL,
__value_type__yMax,
"",
"");
I_Method0(osg::BoundingBoxImpl< osg::Vec3f >::value_type &, zMax,
Properties::NON_VIRTUAL,
__value_type_R1__zMax,
"",
"");
I_Method0(osg::BoundingBoxImpl< osg::Vec3f >::value_type, zMax,
Properties::NON_VIRTUAL,
__value_type__zMax,
"",
"");
I_Method0(const osg::BoundingBoxImpl< osg::Vec3f >::vec_type, center,
Properties::NON_VIRTUAL,
__C5_vec_type__center,
"Calculates and returns the bounding box center. ",
"");
I_Method0(osg::BoundingBoxImpl< osg::Vec3f >::value_type, radius,
Properties::NON_VIRTUAL,
__value_type__radius,
"Calculates and returns the bounding box radius. ",
"");
I_Method0(osg::BoundingBoxImpl< osg::Vec3f >::value_type, radius2,
Properties::NON_VIRTUAL,
__value_type__radius2,
"Calculates and returns the squared length of the bounding box radius. ",
"Note, radius2() is faster to calculate than radius(). ");
I_Method1(const osg::BoundingBoxImpl< osg::Vec3f >::vec_type, corner, IN, unsigned int, pos,
Properties::NON_VIRTUAL,
__C5_vec_type__corner__unsigned_int,
"Returns a specific corner of the bounding box. ",
"pos specifies the corner as a number between 0 and 7. Each bit selects an axis, X, Y, or Z from least- to most-significant. Unset bits select the minimum value for that axis, and set bits select the maximum. ");
I_Method1(void, expandBy, IN, const osg::BoundingBoxImpl< osg::Vec3f >::vec_type &, v,
Properties::NON_VIRTUAL,
__void__expandBy__C5_vec_type_R1,
"Expands the bounding box to include the given coordinate. ",
"If the box is uninitialized, set its min and max extents to v. ");
I_Method3(void, expandBy, IN, osg::BoundingBoxImpl< osg::Vec3f >::value_type, x, IN, osg::BoundingBoxImpl< osg::Vec3f >::value_type, y, IN, osg::BoundingBoxImpl< osg::Vec3f >::value_type, z,
Properties::NON_VIRTUAL,
__void__expandBy__value_type__value_type__value_type,
"Expands the bounding box to include the given coordinate. ",
"If the box is uninitialized, set its min and max extents to Vec3(x,y,z). ");
I_Method1(void, expandBy, IN, const osg::BoundingBoxImpl< osg::Vec3f > &, bb,
Properties::NON_VIRTUAL,
__void__expandBy__C5_BoundingBoxImpl_R1,
"Expands this bounding box to include the given bounding box. ",
"If this box is uninitialized, set it equal to bb. ");
I_Method1(osg::BoundingBoxImpl< osg::Vec3f >, intersect, IN, const osg::BoundingBoxImpl< osg::Vec3f > &, bb,
Properties::NON_VIRTUAL,
__BoundingBoxImpl__intersect__C5_BoundingBoxImpl_R1,
"Returns the intersection of this bounding box and the specified bounding box. ",
"");
I_Method1(bool, intersects, IN, const osg::BoundingBoxImpl< osg::Vec3f > &, bb,
Properties::NON_VIRTUAL,
__bool__intersects__C5_BoundingBoxImpl_R1,
"Return true if this bounding box intersects the specified bounding box. ",
"");
I_Method1(bool, contains, IN, const osg::BoundingBoxImpl< osg::Vec3f >::vec_type &, v,
Properties::NON_VIRTUAL,
__bool__contains__C5_vec_type_R1,
"Returns true if this bounding box contains the specified coordinate. ",
"");
I_PublicMemberProperty(osg::BoundingBoxImpl< osg::Vec3f >::vec_type, _min);
I_PublicMemberProperty(osg::BoundingBoxImpl< osg::Vec3f >::vec_type, _max);
END_REFLECTOR

View File

@@ -30,165 +30,3 @@ TYPE_NAME_ALIAS(osg::BoundingSphereImpl< osg::Vec3d >, osg::BoundingSphered)
TYPE_NAME_ALIAS(osg::BoundingSphered, osg::BoundingSphere) TYPE_NAME_ALIAS(osg::BoundingSphered, osg::BoundingSphere)
BEGIN_VALUE_REFLECTOR(osg::BoundingSphereImpl< osg::Vec3d >)
I_DeclaringFile("osg/BoundingSphere");
I_Constructor0(____BoundingSphereImpl,
"Construct a default bounding sphere with radius to -1.0f, representing an invalid/unset bounding sphere. ",
"");
I_Constructor2(IN, const osg::BoundingSphereImpl< osg::Vec3d >::vec_type &, center, IN, osg::BoundingSphereImpl< osg::Vec3d >::value_type, radius,
____BoundingSphereImpl__C5_vec_type_R1__value_type,
"Creates a bounding sphere initialized to the given extents. ",
"");
I_Constructor1(IN, const osg::BoundingSphereImpl< osg::Vec3d > &, bs,
Properties::NON_EXPLICIT,
____BoundingSphereImpl__C5_BoundingSphereImpl_R1,
"Creates a bounding sphere initialized to the given extents. ",
"");
I_Method0(void, init,
Properties::NON_VIRTUAL,
__void__init,
"Clear the bounding sphere. ",
"Reset to default values. ");
I_Method0(bool, valid,
Properties::NON_VIRTUAL,
__bool__valid,
"Returns true of the bounding sphere extents are valid, false otherwise. ",
"");
I_Method2(void, set, IN, const osg::BoundingSphereImpl< osg::Vec3d >::vec_type &, center, IN, osg::BoundingSphereImpl< osg::Vec3d >::value_type, radius,
Properties::NON_VIRTUAL,
__void__set__C5_vec_type_R1__value_type,
"Set the bounding sphere to the given center/radius using floats. ",
"");
I_Method0(osg::BoundingSphereImpl< osg::Vec3d >::vec_type &, center,
Properties::NON_VIRTUAL,
__vec_type_R1__center,
"Returns the center of the bounding sphere. ",
"");
I_Method0(const osg::BoundingSphereImpl< osg::Vec3d >::vec_type &, center,
Properties::NON_VIRTUAL,
__C5_vec_type_R1__center,
"Returns the const center of the bounding sphere. ",
"");
I_Method0(osg::BoundingSphereImpl< osg::Vec3d >::value_type &, radius,
Properties::NON_VIRTUAL,
__value_type_R1__radius,
"Returns the radius of the bounding sphere. ",
"");
I_Method0(osg::BoundingSphereImpl< osg::Vec3d >::value_type, radius,
Properties::NON_VIRTUAL,
__value_type__radius,
"Returns the const radius of the bounding sphere. ",
"");
I_Method0(osg::BoundingSphereImpl< osg::Vec3d >::value_type, radius2,
Properties::NON_VIRTUAL,
__value_type__radius2,
"Returns the squared length of the radius. ",
"Note, For performance reasons, the calling method is responsible for checking to make sure the sphere is valid. ");
I_Method1(void, expandBy, IN, const osg::BoundingSphereImpl< osg::Vec3d > &, sh,
Properties::NON_VIRTUAL,
__void__expandBy__C5_BoundingSphereImpl_R1,
"Expands the sphere to encompass the given sphere. ",
"Repositions the sphere center to minimize the radius increase. If the sphere is uninitialized, set its center and radius to match sh. ");
I_Method1(void, expandRadiusBy, IN, const osg::BoundingSphereImpl< osg::Vec3d > &, sh,
Properties::NON_VIRTUAL,
__void__expandRadiusBy__C5_BoundingSphereImpl_R1,
"Expands the sphere to encompass the given sphere. ",
"Does not repositions the sphere center. If the sphere is uninitialized, set its center and radius to match sh. ");
I_Method1(bool, contains, IN, const osg::BoundingSphereImpl< osg::Vec3d >::vec_type &, v,
Properties::NON_VIRTUAL,
__bool__contains__C5_vec_type_R1,
"Returns true if v is within the sphere. ",
"");
I_Method1(bool, intersects, IN, const osg::BoundingSphereImpl< osg::Vec3d > &, bs,
Properties::NON_VIRTUAL,
__bool__intersects__C5_BoundingSphereImpl_R1,
"Returns true if there is a non-empty intersection with the given bounding sphere. ",
"");
I_PublicMemberProperty(osg::BoundingSphereImpl< osg::Vec3d >::vec_type, _center);
I_PublicMemberProperty(osg::BoundingSphereImpl< osg::Vec3d >::value_type, _radius);
END_REFLECTOR
BEGIN_VALUE_REFLECTOR(osg::BoundingSphereImpl< osg::Vec3f >)
I_DeclaringFile("osg/BoundingSphere");
I_Constructor0(____BoundingSphereImpl,
"Construct a default bounding sphere with radius to -1.0f, representing an invalid/unset bounding sphere. ",
"");
I_Constructor2(IN, const osg::BoundingSphereImpl< osg::Vec3f >::vec_type &, center, IN, osg::BoundingSphereImpl< osg::Vec3f >::value_type, radius,
____BoundingSphereImpl__C5_vec_type_R1__value_type,
"Creates a bounding sphere initialized to the given extents. ",
"");
I_Constructor1(IN, const osg::BoundingSphereImpl< osg::Vec3f > &, bs,
Properties::NON_EXPLICIT,
____BoundingSphereImpl__C5_BoundingSphereImpl_R1,
"Creates a bounding sphere initialized to the given extents. ",
"");
I_Method0(void, init,
Properties::NON_VIRTUAL,
__void__init,
"Clear the bounding sphere. ",
"Reset to default values. ");
I_Method0(bool, valid,
Properties::NON_VIRTUAL,
__bool__valid,
"Returns true of the bounding sphere extents are valid, false otherwise. ",
"");
I_Method2(void, set, IN, const osg::BoundingSphereImpl< osg::Vec3f >::vec_type &, center, IN, osg::BoundingSphereImpl< osg::Vec3f >::value_type, radius,
Properties::NON_VIRTUAL,
__void__set__C5_vec_type_R1__value_type,
"Set the bounding sphere to the given center/radius using floats. ",
"");
I_Method0(osg::BoundingSphereImpl< osg::Vec3f >::vec_type &, center,
Properties::NON_VIRTUAL,
__vec_type_R1__center,
"Returns the center of the bounding sphere. ",
"");
I_Method0(const osg::BoundingSphereImpl< osg::Vec3f >::vec_type &, center,
Properties::NON_VIRTUAL,
__C5_vec_type_R1__center,
"Returns the const center of the bounding sphere. ",
"");
I_Method0(osg::BoundingSphereImpl< osg::Vec3f >::value_type &, radius,
Properties::NON_VIRTUAL,
__value_type_R1__radius,
"Returns the radius of the bounding sphere. ",
"");
I_Method0(osg::BoundingSphereImpl< osg::Vec3f >::value_type, radius,
Properties::NON_VIRTUAL,
__value_type__radius,
"Returns the const radius of the bounding sphere. ",
"");
I_Method0(osg::BoundingSphereImpl< osg::Vec3f >::value_type, radius2,
Properties::NON_VIRTUAL,
__value_type__radius2,
"Returns the squared length of the radius. ",
"Note, For performance reasons, the calling method is responsible for checking to make sure the sphere is valid. ");
I_Method1(void, expandBy, IN, const osg::BoundingSphereImpl< osg::Vec3f > &, sh,
Properties::NON_VIRTUAL,
__void__expandBy__C5_BoundingSphereImpl_R1,
"Expands the sphere to encompass the given sphere. ",
"Repositions the sphere center to minimize the radius increase. If the sphere is uninitialized, set its center and radius to match sh. ");
I_Method1(void, expandRadiusBy, IN, const osg::BoundingSphereImpl< osg::Vec3f > &, sh,
Properties::NON_VIRTUAL,
__void__expandRadiusBy__C5_BoundingSphereImpl_R1,
"Expands the sphere to encompass the given sphere. ",
"Does not repositions the sphere center. If the sphere is uninitialized, set its center and radius to match sh. ");
I_Method1(bool, contains, IN, const osg::BoundingSphereImpl< osg::Vec3f >::vec_type &, v,
Properties::NON_VIRTUAL,
__bool__contains__C5_vec_type_R1,
"Returns true if v is within the sphere. ",
"");
I_Method1(bool, intersects, IN, const osg::BoundingSphereImpl< osg::Vec3f > &, bs,
Properties::NON_VIRTUAL,
__bool__intersects__C5_BoundingSphereImpl_R1,
"Returns true if there is a non-empty intersection with the given bounding sphere. ",
"");
I_PublicMemberProperty(osg::BoundingSphereImpl< osg::Vec3f >::vec_type, _center);
I_PublicMemberProperty(osg::BoundingSphereImpl< osg::Vec3f >::value_type, _radius);
END_REFLECTOR

View File

@@ -20,7 +20,6 @@
#include <osg/Texture1D> #include <osg/Texture1D>
#include <osg/Texture2D> #include <osg/Texture2D>
#include <osg/Texture2DArray> #include <osg/Texture2DArray>
#include <osg/Texture2DMultisample>
#include <osg/Texture3D> #include <osg/Texture3D>
#include <osg/TextureCubeMap> #include <osg/TextureCubeMap>
#include <osg/TextureRectangle> #include <osg/TextureRectangle>
@@ -90,10 +89,6 @@ BEGIN_VALUE_REFLECTOR(osg::FrameBufferAttachment)
____FrameBufferAttachment__Texture2D_P1__int, ____FrameBufferAttachment__Texture2D_P1__int,
"", "",
""); "");
I_ConstructorWithDefaults2(IN, osg::Texture2DMultisample *, target, , IN, int, level, 0,
____FrameBufferAttachment__Texture2DMultisample_P1__int,
"",
"");
I_ConstructorWithDefaults3(IN, osg::Texture3D *, target, , IN, int, zoffset, , IN, int, level, 0, I_ConstructorWithDefaults3(IN, osg::Texture3D *, target, , IN, int, zoffset, , IN, int, level, 0,
____FrameBufferAttachment__Texture3D_P1__int__int, ____FrameBufferAttachment__Texture3D_P1__int__int,
"", "",

View File

@@ -71,7 +71,7 @@ BEGIN_ABSTRACT_OBJECT_REFLECTOR(osg::Object)
"return the name of the object's class type. ", "return the name of the object's class type. ",
"Must be defined by derived classes. "); "Must be defined by derived classes. ");
I_Method1(void, setName, IN, const std::string &, name, I_Method1(void, setName, IN, const std::string &, name,
Properties::VIRTUAL, Properties::NON_VIRTUAL,
__void__setName__C5_std_string_R1, __void__setName__C5_std_string_R1,
"Set the name of object using C++ style string. ", "Set the name of object using C++ style string. ",
""); "");

View File

@@ -26,129 +26,10 @@
#undef OUT #undef OUT
#endif #endif
BEGIN_VALUE_REFLECTOR(osg::Program::ActiveVarInfo)
I_DeclaringFile("osg/Program");
I_Constructor0(____ActiveVarInfo,
"",
"");
I_Constructor3(IN, GLint, loc, IN, GLenum, type, IN, GLint, size,
____ActiveVarInfo__GLint__GLenum__GLint,
"",
"");
I_PublicMemberProperty(GLint, _location);
I_PublicMemberProperty(GLenum, _type);
I_PublicMemberProperty(GLint, _size);
END_REFLECTOR
BEGIN_OBJECT_REFLECTOR(osg::Program::PerContextProgram)
I_DeclaringFile("osg/Program");
I_BaseType(osg::Referenced);
I_Constructor2(IN, const osg::Program *, program, IN, unsigned int, contextID,
____PerContextProgram__C5_Program_P1__unsigned_int,
"",
"");
I_Method0(GLuint, getHandle,
Properties::NON_VIRTUAL,
__GLuint__getHandle,
"",
"");
I_Method0(void, requestLink,
Properties::NON_VIRTUAL,
__void__requestLink,
"",
"");
I_Method0(void, linkProgram,
Properties::NON_VIRTUAL,
__void__linkProgram,
"",
"");
I_Method0(bool, validateProgram,
Properties::NON_VIRTUAL,
__bool__validateProgram,
"",
"");
I_Method0(bool, needsLink,
Properties::NON_VIRTUAL,
__bool__needsLink,
"",
"");
I_Method0(bool, isLinked,
Properties::NON_VIRTUAL,
__bool__isLinked,
"",
"");
I_Method1(bool, getInfoLog, IN, std::string &, infoLog,
Properties::NON_VIRTUAL,
__bool__getInfoLog__std_string_R1,
"",
"");
I_Method0(void, useProgram,
Properties::NON_VIRTUAL,
__void__useProgram,
"",
"");
I_Method0(void, resetAppliedUniforms,
Properties::NON_VIRTUAL,
__void__resetAppliedUniforms,
"",
"");
I_Method1(void, apply, IN, const osg::Uniform &, uniform,
Properties::NON_VIRTUAL,
__void__apply__C5_Uniform_R1,
"",
"");
I_Method0(const osg::Program::ActiveUniformMap &, getActiveUniforms,
Properties::NON_VIRTUAL,
__C5_ActiveUniformMap_R1__getActiveUniforms,
"",
"");
I_Method0(const osg::Program::ActiveVarInfoMap &, getActiveAttribs,
Properties::NON_VIRTUAL,
__C5_ActiveVarInfoMap_R1__getActiveAttribs,
"",
"");
I_Method1(GLint, getUniformLocation, IN, unsigned int, uniformNameID,
Properties::NON_VIRTUAL,
__GLint__getUniformLocation__unsigned_int,
"",
"");
I_Method1(GLint, getUniformLocation, IN, const std::string &, uniformName,
Properties::NON_VIRTUAL,
__GLint__getUniformLocation__C5_std_string_R1,
"Alternative version of getUniformLocation( unsigned int uniformNameID ) retrofited into OSG for backward compatibility with osgCal, after uniform ids were refactored from std::strings to GLints in OSG version 2.9.10. ",
"Drawbacks: This method is not particularly fast. It has to access mutexed static map of uniform ids. So don't overuse it or your app performance will suffer. ");
I_Method1(GLint, getAttribLocation, IN, const std::string &, name,
Properties::NON_VIRTUAL,
__GLint__getAttribLocation__C5_std_string_R1,
"",
"");
I_Method1(void, addShaderToAttach, IN, osg::Shader *, shader,
Properties::NON_VIRTUAL,
__void__addShaderToAttach__Shader_P1,
"",
"");
I_Method1(void, addShaderToDetach, IN, osg::Shader *, shader,
Properties::NON_VIRTUAL,
__void__addShaderToDetach__Shader_P1,
"",
"");
I_SimpleProperty(const osg::Program::ActiveVarInfoMap &, ActiveAttribs,
__C5_ActiveVarInfoMap_R1__getActiveAttribs,
0);
I_SimpleProperty(const osg::Program::ActiveUniformMap &, ActiveUniforms,
__C5_ActiveUniformMap_R1__getActiveUniforms,
0);
I_SimpleProperty(GLuint, Handle,
__GLuint__getHandle,
0);
END_REFLECTOR
TYPE_NAME_ALIAS(std::map< std::string COMMA GLuint >, osg::Program::AttribBindingList) TYPE_NAME_ALIAS(std::map< std::string COMMA GLuint >, osg::Program::AttribBindingList)
TYPE_NAME_ALIAS(std::map< std::string COMMA GLuint >, osg::Program::FragDataBindingList) TYPE_NAME_ALIAS(std::map< std::string COMMA GLuint >, osg::Program::FragDataBindingList)
TYPE_NAME_ALIAS(std::map< unsigned int COMMA osg::Program::ActiveVarInfo >, osg::Program::ActiveUniformMap)
TYPE_NAME_ALIAS(std::map< std::string COMMA osg::Program::ActiveVarInfo >, osg::Program::ActiveVarInfoMap) TYPE_NAME_ALIAS(std::map< std::string COMMA osg::Program::ActiveVarInfo >, osg::Program::ActiveVarInfoMap)
BEGIN_OBJECT_REFLECTOR(osg::Program) BEGIN_OBJECT_REFLECTOR(osg::Program)
@@ -301,9 +182,9 @@ BEGIN_OBJECT_REFLECTOR(osg::Program)
__bool__getGlProgramInfoLog__unsigned_int__std_string_R1, __bool__getGlProgramInfoLog__unsigned_int__std_string_R1,
"Query InfoLog from a glProgram. ", "Query InfoLog from a glProgram. ",
""); "");
I_Method1(const osg::Program::ActiveUniformMap &, getActiveUniforms, IN, unsigned int, contextID, I_Method1(const osg::Program::ActiveVarInfoMap &, getActiveUniforms, IN, unsigned int, contextID,
Properties::NON_VIRTUAL, Properties::NON_VIRTUAL,
__C5_ActiveUniformMap_R1__getActiveUniforms__unsigned_int, __C5_ActiveVarInfoMap_R1__getActiveUniforms__unsigned_int,
"", "",
""); "");
I_Method1(const osg::Program::ActiveVarInfoMap &, getActiveAttribs, IN, unsigned int, contextID, I_Method1(const osg::Program::ActiveVarInfoMap &, getActiveAttribs, IN, unsigned int, contextID,
@@ -353,9 +234,119 @@ BEGIN_OBJECT_REFLECTOR(osg::Program)
0); 0);
END_REFLECTOR END_REFLECTOR
BEGIN_VALUE_REFLECTOR(osg::Program::ActiveVarInfo)
I_DeclaringFile("osg/Program");
I_Constructor0(____ActiveVarInfo,
"",
"");
I_Constructor3(IN, GLint, loc, IN, GLenum, type, IN, GLint, size,
____ActiveVarInfo__GLint__GLenum__GLint,
"",
"");
I_PublicMemberProperty(GLint, _location);
I_PublicMemberProperty(GLenum, _type);
I_PublicMemberProperty(GLint, _size);
END_REFLECTOR
BEGIN_OBJECT_REFLECTOR(osg::Program::PerContextProgram)
I_DeclaringFile("osg/Program");
I_BaseType(osg::Referenced);
I_Constructor2(IN, const osg::Program *, program, IN, unsigned int, contextID,
____PerContextProgram__C5_Program_P1__unsigned_int,
"",
"");
I_Method0(GLuint, getHandle,
Properties::NON_VIRTUAL,
__GLuint__getHandle,
"",
"");
I_Method0(void, requestLink,
Properties::NON_VIRTUAL,
__void__requestLink,
"",
"");
I_Method0(void, linkProgram,
Properties::NON_VIRTUAL,
__void__linkProgram,
"",
"");
I_Method0(bool, validateProgram,
Properties::NON_VIRTUAL,
__bool__validateProgram,
"",
"");
I_Method0(bool, needsLink,
Properties::NON_VIRTUAL,
__bool__needsLink,
"",
"");
I_Method0(bool, isLinked,
Properties::NON_VIRTUAL,
__bool__isLinked,
"",
"");
I_Method1(bool, getInfoLog, IN, std::string &, infoLog,
Properties::NON_VIRTUAL,
__bool__getInfoLog__std_string_R1,
"",
"");
I_Method0(void, useProgram,
Properties::NON_VIRTUAL,
__void__useProgram,
"",
"");
I_Method0(void, resetAppliedUniforms,
Properties::NON_VIRTUAL,
__void__resetAppliedUniforms,
"",
"");
I_Method1(void, apply, IN, const osg::Uniform &, uniform,
Properties::NON_VIRTUAL,
__void__apply__C5_Uniform_R1,
"",
"");
I_Method0(const osg::Program::ActiveVarInfoMap &, getActiveUniforms,
Properties::NON_VIRTUAL,
__C5_ActiveVarInfoMap_R1__getActiveUniforms,
"",
"");
I_Method0(const osg::Program::ActiveVarInfoMap &, getActiveAttribs,
Properties::NON_VIRTUAL,
__C5_ActiveVarInfoMap_R1__getActiveAttribs,
"",
"");
I_Method1(GLint, getUniformLocation, IN, const std::string &, name,
Properties::NON_VIRTUAL,
__GLint__getUniformLocation__C5_std_string_R1,
"",
"");
I_Method1(GLint, getAttribLocation, IN, const std::string &, name,
Properties::NON_VIRTUAL,
__GLint__getAttribLocation__C5_std_string_R1,
"",
"");
I_Method1(void, addShaderToAttach, IN, osg::Shader *, shader,
Properties::NON_VIRTUAL,
__void__addShaderToAttach__Shader_P1,
"",
"");
I_Method1(void, addShaderToDetach, IN, osg::Shader *, shader,
Properties::NON_VIRTUAL,
__void__addShaderToDetach__Shader_P1,
"",
"");
I_SimpleProperty(const osg::Program::ActiveVarInfoMap &, ActiveAttribs,
__C5_ActiveVarInfoMap_R1__getActiveAttribs,
0);
I_SimpleProperty(const osg::Program::ActiveVarInfoMap &, ActiveUniforms,
__C5_ActiveVarInfoMap_R1__getActiveUniforms,
0);
I_SimpleProperty(GLuint, Handle,
__GLuint__getHandle,
0);
END_REFLECTOR
STD_MAP_REFLECTOR(std::map< std::string COMMA GLuint >) STD_MAP_REFLECTOR(std::map< std::string COMMA GLuint >)
STD_MAP_REFLECTOR(std::map< std::string COMMA osg::Program::ActiveVarInfo >) STD_MAP_REFLECTOR(std::map< std::string COMMA osg::Program::ActiveVarInfo >)
STD_MAP_REFLECTOR(std::map< unsigned int COMMA osg::Program::ActiveVarInfo >)

View File

@@ -1,179 +0,0 @@
// ***************************************************************************
//
// Generated automatically by genwrapper.
// Please DO NOT EDIT this file!
//
// ***************************************************************************
#include <osgIntrospection/ReflectionMacros>
#include <osgIntrospection/TypedMethodInfo>
#include <osgIntrospection/StaticMethodInfo>
#include <osgIntrospection/Attributes>
#include <osg/CopyOp>
#include <osg/Image>
#include <osg/Object>
#include <osg/State>
#include <osg/StateAttribute>
#include <osg/Texture2DMultisample>
// Must undefine IN and OUT macros defined in Windows headers
#ifdef IN
#undef IN
#endif
#ifdef OUT
#undef OUT
#endif
BEGIN_OBJECT_REFLECTOR(osg::Texture2DMultisample)
I_DeclaringFile("osg/Texture2DMultisample");
I_BaseType(osg::Texture);
I_Constructor0(____Texture2DMultisample,
"",
"");
I_Constructor2(IN, GLsizei, numSamples, IN, GLboolean, fixedsamplelocations,
____Texture2DMultisample__GLsizei__GLboolean,
"",
"");
I_ConstructorWithDefaults2(IN, const osg::Texture2DMultisample &, text, , IN, const osg::CopyOp &, copyop, osg::CopyOp::SHALLOW_COPY,
____Texture2DMultisample__C5_Texture2DMultisample_R1__C5_CopyOp_R1,
"Copy constructor using CopyOp to manage deep vs shallow copy. ",
"");
I_Method0(osg::Object *, cloneType,
Properties::VIRTUAL,
__osg_Object_P1__cloneType,
"Clone the type of an attribute, with Object* return type. ",
"Must be defined by derived classes. ");
I_Method1(osg::Object *, clone, IN, const osg::CopyOp &, x,
Properties::VIRTUAL,
__osg_Object_P1__clone__C5_osg_CopyOp_R1,
"Clone an attribute, with Object* return type. ",
"Must be defined by derived classes. ");
I_Method1(bool, isSameKindAs, IN, const osg::Object *, obj,
Properties::VIRTUAL,
__bool__isSameKindAs__C5_osg_Object_P1,
"Return true if this and obj are of the same kind of object. ",
"");
I_Method0(const char *, libraryName,
Properties::VIRTUAL,
__C5_char_P1__libraryName,
"Return the name of the attribute's library. ",
"");
I_Method0(const char *, className,
Properties::VIRTUAL,
__C5_char_P1__className,
"Return the name of the attribute's class type. ",
"");
I_Method0(osg::StateAttribute::Type, getType,
Properties::VIRTUAL,
__Type__getType,
"Return the Type identifier of the attribute's class type. ",
"");
I_Method1(int, compare, IN, const osg::StateAttribute &, rhs,
Properties::VIRTUAL,
__int__compare__C5_StateAttribute_R1,
"Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. ",
"");
I_Method0(GLenum, getTextureTarget,
Properties::VIRTUAL,
__GLenum__getTextureTarget,
"",
"");
I_Method2(void, setTextureSize, IN, int, width, IN, int, height,
Properties::NON_VIRTUAL,
__void__setTextureSize__int__int,
"Sets the texture width and height. ",
"If width or height are zero, calculate the respective value from the source image size. ");
I_Method1(void, setNumSamples, IN, int, samples,
Properties::NON_VIRTUAL,
__void__setNumSamples__int,
"",
"");
I_Method2(void, setImage, IN, unsigned, face, IN, osg::Image *, image,
Properties::VIRTUAL,
__void__setImage__unsigned__Image_P1,
"Sets the texture image for the specified face. ",
"");
I_Method1(osg::Image *, getImage, IN, unsigned, face,
Properties::VIRTUAL,
__Image_P1__getImage__unsigned,
"Gets the texture image for the specified face. ",
"");
I_Method1(const osg::Image *, getImage, IN, unsigned, face,
Properties::VIRTUAL,
__C5_Image_P1__getImage__unsigned,
"Gets the const texture image for specified face. ",
"");
I_Method0(unsigned int, getNumImages,
Properties::VIRTUAL,
__unsigned_int__getNumImages,
"Gets the number of images that can be assigned to this Texture. ",
"");
I_Method1(void, allocateMipmap, IN, osg::State &, state,
Properties::VIRTUAL,
__void__allocateMipmap__State_R1,
"Allocate mipmap levels of the texture by subsequent calling of glTexImage* function. ",
"");
I_Method1(void, setTextureWidth, IN, int, width,
Properties::NON_VIRTUAL,
__void__setTextureWidth__int,
"",
"");
I_Method1(void, setTextureHeight, IN, int, height,
Properties::NON_VIRTUAL,
__void__setTextureHeight__int,
"",
"");
I_Method0(int, getTextureWidth,
Properties::VIRTUAL,
__int__getTextureWidth,
"",
"");
I_Method0(int, getTextureHeight,
Properties::VIRTUAL,
__int__getTextureHeight,
"",
"");
I_Method0(int, getTextureDepth,
Properties::VIRTUAL,
__int__getTextureDepth,
"",
"");
I_Method1(void, apply, IN, osg::State &, state,
Properties::VIRTUAL,
__void__apply__State_R1,
"Bind the texture object. ",
"If the texture object hasn't already been compiled, create the texture mipmap levels. ");
I_ProtectedMethod0(void, computeInternalFormat,
Properties::VIRTUAL,
Properties::CONST,
__void__computeInternalFormat,
"",
"");
I_ArrayProperty(osg::Image *, Image,
__Image_P1__getImage__unsigned,
__void__setImage__unsigned__Image_P1,
__unsigned_int__getNumImages,
0,
0,
0);
I_SimpleProperty(int, NumSamples,
0,
__void__setNumSamples__int);
I_SimpleProperty(int, TextureDepth,
__int__getTextureDepth,
0);
I_SimpleProperty(int, TextureHeight,
__int__getTextureHeight,
__void__setTextureHeight__int);
I_SimpleProperty(GLenum, TextureTarget,
__GLenum__getTextureTarget,
0);
I_SimpleProperty(int, TextureWidth,
__int__getTextureWidth,
__void__setTextureWidth__int);
I_SimpleProperty(osg::StateAttribute::Type, Type,
__Type__getType,
0);
END_REFLECTOR

View File

@@ -233,7 +233,7 @@ BEGIN_OBJECT_REFLECTOR(osg::Uniform)
"Get the type of glUniform as enum. ", "Get the type of glUniform as enum. ",
""); "");
I_Method1(void, setName, IN, const std::string &, name, I_Method1(void, setName, IN, const std::string &, name,
Properties::VIRTUAL, Properties::NON_VIRTUAL,
__void__setName__C5_std_string_R1, __void__setName__C5_std_string_R1,
"Set the name of the glUniform, ensuring it is only set once. ", "Set the name of the glUniform, ensuring it is only set once. ",
""); "");
@@ -862,11 +862,6 @@ BEGIN_OBJECT_REFLECTOR(osg::Uniform)
__unsigned_int__getModifiedCount, __unsigned_int__getModifiedCount,
"", "",
""); "");
I_Method0(unsigned int, getNameID,
Properties::NON_VIRTUAL,
__unsigned_int__getNameID,
"Get the number that the Uniform's name maps to uniquely. ",
"");
I_Method2(void, apply, IN, const osg::GL2Extensions *, ext, IN, GLint, location, I_Method2(void, apply, IN, const osg::GL2Extensions *, ext, IN, GLint, location,
Properties::NON_VIRTUAL, Properties::NON_VIRTUAL,
__void__apply__C5_GL2Extensions_P1__GLint, __void__apply__C5_GL2Extensions_P1__GLint,
@@ -892,10 +887,6 @@ BEGIN_OBJECT_REFLECTOR(osg::Uniform)
__GLenum__getInternalArrayType__Type_S, __GLenum__getInternalArrayType__Type_S,
"Return the internal data array type corresponding to a GLSL type. ", "Return the internal data array type corresponding to a GLSL type. ",
""); "");
I_StaticMethod1(unsigned int, getNameID, IN, const std::string &, name,
__unsigned_int__getNameID__C5_std_string_R1_S,
"Return the number that the name maps to uniquely. ",
"");
I_ProtectedMethod1(bool, isCompatibleType, IN, osg::Uniform::Type, t, I_ProtectedMethod1(bool, isCompatibleType, IN, osg::Uniform::Type, t,
Properties::NON_VIRTUAL, Properties::NON_VIRTUAL,
Properties::CONST, Properties::CONST,
@@ -954,9 +945,6 @@ BEGIN_OBJECT_REFLECTOR(osg::Uniform)
I_SimpleProperty(const std::string &, Name, I_SimpleProperty(const std::string &, Name,
0, 0,
__void__setName__C5_std_string_R1); __void__setName__C5_std_string_R1);
I_SimpleProperty(unsigned int, NameID,
__unsigned_int__getNameID,
0);
I_SimpleProperty(unsigned int, NumElements, I_SimpleProperty(unsigned int, NumElements,
0, 0,
__void__setNumElements__unsigned_int); __void__setNumElements__unsigned_int);

View File

@@ -125,7 +125,11 @@ BEGIN_VALUE_REFLECTOR(osgShadow::ConvexPolyhedron)
__void__getPoints__Vertices_R1, __void__getPoints__Vertices_R1,
"", "",
""); "");
I_MethodWithDefaults1(osg::BoundingBox, computeBoundingBox, IN, const osg::Matrix &, m, osgShadow::ConvexPolyhedron::defaultMatrix,
Properties::NON_VIRTUAL,
__osg_BoundingBox__computeBoundingBox__C5_osg_Matrix_R1,
"",
"");
I_MethodWithDefaults3(osg::Geometry *, buildGeometry, IN, const osg::Vec4d &, colorOutline, , IN, const osg::Vec4d &, colorInside, , IN, osg::Geometry *, useGeometry, NULL, I_MethodWithDefaults3(osg::Geometry *, buildGeometry, IN, const osg::Vec4d &, colorOutline, , IN, const osg::Vec4d &, colorInside, , IN, osg::Geometry *, useGeometry, NULL,
Properties::NON_VIRTUAL, Properties::NON_VIRTUAL,
__osg_Geometry_P1__buildGeometry__C5_osg_Vec4d_R1__C5_osg_Vec4d_R1__osg_Geometry_P1, __osg_Geometry_P1__buildGeometry__C5_osg_Vec4d_R1__C5_osg_Vec4d_R1__osg_Geometry_P1,

View File

@@ -28,92 +28,7 @@
#undef OUT #undef OUT
#endif #endif
TYPE_NAME_ALIAS(std::vector< osgText::Font::Glyph * >, osgText::Text::GlyphQuads::Glyphs) TYPE_NAME_ALIAS(std::map< osg::ref_ptr< osgText::Font::GlyphTexture > COMMA osgText::Text::GlyphQuads >, osgText::Text::TextureGlyphQuadMap)
TYPE_NAME_ALIAS(std::vector< unsigned int >, osgText::Text::GlyphQuads::LineNumbers)
TYPE_NAME_ALIAS(std::vector< osg::Vec2 >, osgText::Text::GlyphQuads::Coords2)
TYPE_NAME_ALIAS(std::vector< osg::Vec3 >, osgText::Text::GlyphQuads::Coords3)
TYPE_NAME_ALIAS(std::vector< osg::Vec2 >, osgText::Text::GlyphQuads::TexCoords)
TYPE_NAME_ALIAS(std::vector< osg::Vec4 >, osgText::Text::GlyphQuads::ColorCoords)
BEGIN_VALUE_REFLECTOR(osgText::Text::GlyphQuads)
I_DeclaringFile("osgText/Text");
I_Constructor0(____GlyphQuads,
"",
"");
I_Method0(osgText::Text::GlyphQuads::Glyphs, getGlyphs,
Properties::NON_VIRTUAL,
__Glyphs__getGlyphs,
"",
"");
I_Method0(const osgText::Text::GlyphQuads::Glyphs, getGlyphs,
Properties::NON_VIRTUAL,
__C5_Glyphs__getGlyphs,
"",
"");
I_Method0(osgText::Text::GlyphQuads::Coords2 &, getCoords,
Properties::NON_VIRTUAL,
__Coords2_R1__getCoords,
"",
"");
I_Method0(const osgText::Text::GlyphQuads::Coords2 &, getCoords,
Properties::NON_VIRTUAL,
__C5_Coords2_R1__getCoords,
"",
"");
I_Method1(osgText::Text::GlyphQuads::Coords3 &, getTransformedCoords, IN, unsigned int, contexID,
Properties::NON_VIRTUAL,
__Coords3_R1__getTransformedCoords__unsigned_int,
"",
"");
I_Method1(const osgText::Text::GlyphQuads::Coords3 &, getTransformedCoords, IN, unsigned int, contexID,
Properties::NON_VIRTUAL,
__C5_Coords3_R1__getTransformedCoords__unsigned_int,
"",
"");
I_Method0(osgText::Text::GlyphQuads::TexCoords &, getTexCoords,
Properties::NON_VIRTUAL,
__TexCoords_R1__getTexCoords,
"",
"");
I_Method0(const osgText::Text::GlyphQuads::TexCoords &, getTexCoords,
Properties::NON_VIRTUAL,
__C5_TexCoords_R1__getTexCoords,
"",
"");
I_Method0(osgText::Text::GlyphQuads::LineNumbers &, getLineNumbers,
Properties::NON_VIRTUAL,
__LineNumbers_R1__getLineNumbers,
"",
"");
I_Method0(const osgText::Text::GlyphQuads::LineNumbers &, getLineNumbers,
Properties::NON_VIRTUAL,
__C5_LineNumbers_R1__getLineNumbers,
"",
"");
I_SimpleProperty(osgText::Text::GlyphQuads::Coords2 &, Coords,
__Coords2_R1__getCoords,
0);
I_SimpleProperty(osgText::Text::GlyphQuads::Glyphs, Glyphs,
__Glyphs__getGlyphs,
0);
I_SimpleProperty(osgText::Text::GlyphQuads::LineNumbers &, LineNumbers,
__LineNumbers_R1__getLineNumbers,
0);
I_SimpleProperty(osgText::Text::GlyphQuads::TexCoords &, TexCoords,
__TexCoords_R1__getTexCoords,
0);
I_PublicMemberProperty(osgText::Text::GlyphQuads::Glyphs, _glyphs);
I_PublicMemberProperty(osgText::Text::GlyphQuads::Coords2, _coords);
I_PublicMemberProperty(osg::buffered_object< osgText::Text::GlyphQuads::Coords3 >, _transformedCoords);
I_PublicMemberProperty(osgText::Text::GlyphQuads::TexCoords, _texcoords);
I_PublicMemberProperty(osgText::Text::GlyphQuads::LineNumbers, _lineNumbers);
I_PublicMemberProperty(osgText::Text::GlyphQuads::ColorCoords, _colorCoords);
END_REFLECTOR
BEGIN_ENUM_REFLECTOR(osgText::Text::BackdropType) BEGIN_ENUM_REFLECTOR(osgText::Text::BackdropType)
I_DeclaringFile("osgText/Text"); I_DeclaringFile("osgText/Text");
@@ -135,7 +50,6 @@ BEGIN_ENUM_REFLECTOR(osgText::Text::BackdropImplementation)
I_EnumLabel(osgText::Text::NO_DEPTH_BUFFER); I_EnumLabel(osgText::Text::NO_DEPTH_BUFFER);
I_EnumLabel(osgText::Text::DEPTH_RANGE); I_EnumLabel(osgText::Text::DEPTH_RANGE);
I_EnumLabel(osgText::Text::STENCIL_BUFFER); I_EnumLabel(osgText::Text::STENCIL_BUFFER);
I_EnumLabel(osgText::Text::DELAYED_DEPTH_WRITES);
END_REFLECTOR END_REFLECTOR
BEGIN_ENUM_REFLECTOR(osgText::Text::ColorGradientMode) BEGIN_ENUM_REFLECTOR(osgText::Text::ColorGradientMode)
@@ -145,8 +59,6 @@ BEGIN_ENUM_REFLECTOR(osgText::Text::ColorGradientMode)
I_EnumLabel(osgText::Text::OVERALL); I_EnumLabel(osgText::Text::OVERALL);
END_REFLECTOR END_REFLECTOR
TYPE_NAME_ALIAS(std::map< osg::ref_ptr< osgText::Font::GlyphTexture > COMMA osgText::Text::GlyphQuads >, osgText::Text::TextureGlyphQuadMap)
BEGIN_OBJECT_REFLECTOR(osgText::Text) BEGIN_OBJECT_REFLECTOR(osgText::Text)
I_DeclaringFile("osgText/Text"); I_DeclaringFile("osgText/Text");
I_BaseType(osgText::TextBase); I_BaseType(osgText::TextBase);
@@ -212,16 +124,6 @@ BEGIN_OBJECT_REFLECTOR(osgText::Text)
__C5_osg_Vec4_R1__getColor, __C5_osg_Vec4_R1__getColor,
"", "",
""); "");
I_Method0(bool, setEnableDepthWrites,
Properties::NON_VIRTUAL,
__bool__setEnableDepthWrites,
"Turns off writing to the depth buffer when rendering text. ",
"This only affects text with no backdrop or text using the DELAYED_DEPTH_WRITES implementation, since the other backdrop implementations are really only useful for backwards compatibility and are not worth updating to utilize this flag. ");
I_Method1(void, setEnableDepthWrites, IN, bool, enable,
Properties::NON_VIRTUAL,
__void__setEnableDepthWrites__bool,
"",
"");
I_Method1(void, setBackdropType, IN, osgText::Text::BackdropType, type, I_Method1(void, setBackdropType, IN, osgText::Text::BackdropType, type,
Properties::NON_VIRTUAL, Properties::NON_VIRTUAL,
__void__setBackdropType__BackdropType, __void__setBackdropType__BackdropType,
@@ -440,12 +342,6 @@ BEGIN_OBJECT_REFLECTOR(osgText::Text)
__void__drawForegroundText__osg_State_R1__C5_GlyphQuads_R1__C5_osg_Vec4_R1, __void__drawForegroundText__osg_State_R1__C5_GlyphQuads_R1__C5_osg_Vec4_R1,
"", "",
""); "");
I_ProtectedMethod2(void, drawTextWithBackdrop, IN, osg::State &, state, IN, const osg::Vec4 &, colorMultiplier,
Properties::NON_VIRTUAL,
Properties::CONST,
__void__drawTextWithBackdrop__osg_State_R1__C5_osg_Vec4_R1,
"",
"");
I_ProtectedMethod2(void, renderOnlyForegroundText, IN, osg::State &, state, IN, const osg::Vec4 &, colorMultiplier, I_ProtectedMethod2(void, renderOnlyForegroundText, IN, osg::State &, state, IN, const osg::Vec4 &, colorMultiplier,
Properties::NON_VIRTUAL, Properties::NON_VIRTUAL,
Properties::CONST, Properties::CONST,
@@ -476,12 +372,6 @@ BEGIN_OBJECT_REFLECTOR(osgText::Text)
__void__renderWithStencilBuffer__osg_State_R1__C5_osg_Vec4_R1, __void__renderWithStencilBuffer__osg_State_R1__C5_osg_Vec4_R1,
"", "",
""); "");
I_ProtectedMethod2(void, renderWithDelayedDepthWrites, IN, osg::State &, state, IN, const osg::Vec4 &, colorMultiplier,
Properties::NON_VIRTUAL,
Properties::CONST,
__void__renderWithDelayedDepthWrites__osg_State_R1__C5_osg_Vec4_R1,
"",
"");
I_ProtectedMethod10(float, bilinearInterpolate, IN, float, x1, IN, float, x2, IN, float, y1, IN, float, y2, IN, float, x, IN, float, y, IN, float, q11, IN, float, q12, IN, float, q21, IN, float, q22, I_ProtectedMethod10(float, bilinearInterpolate, IN, float, x1, IN, float, x2, IN, float, y1, IN, float, y2, IN, float, x, IN, float, y, IN, float, q11, IN, float, q12, IN, float, q21, IN, float, q22,
Properties::NON_VIRTUAL, Properties::NON_VIRTUAL,
Properties::CONST, Properties::CONST,
@@ -536,9 +426,6 @@ BEGIN_OBJECT_REFLECTOR(osgText::Text)
I_SimpleProperty(const osg::Vec4 &, ColorGradientTopRight, I_SimpleProperty(const osg::Vec4 &, ColorGradientTopRight,
__C5_osg_Vec4_R1__getColorGradientTopRight, __C5_osg_Vec4_R1__getColorGradientTopRight,
0); 0);
I_SimpleProperty(bool, EnableDepthWrites,
0,
__void__setEnableDepthWrites__bool);
I_SimpleProperty(osg::ref_ptr< osgText::Font >, Font, I_SimpleProperty(osg::ref_ptr< osgText::Font >, Font,
0, 0,
__void__setFont__osg_ref_ptrT1_Font_); __void__setFont__osg_ref_ptrT1_Font_);
@@ -550,6 +437,93 @@ BEGIN_OBJECT_REFLECTOR(osgText::Text)
__void__setThreadSafeRefUnref__bool); __void__setThreadSafeRefUnref__bool);
END_REFLECTOR END_REFLECTOR
TYPE_NAME_ALIAS(std::vector< osgText::Font::Glyph * >, osgText::Text::GlyphQuads::Glyphs)
TYPE_NAME_ALIAS(std::vector< unsigned int >, osgText::Text::GlyphQuads::LineNumbers)
TYPE_NAME_ALIAS(std::vector< osg::Vec2 >, osgText::Text::GlyphQuads::Coords2)
TYPE_NAME_ALIAS(std::vector< osg::Vec3 >, osgText::Text::GlyphQuads::Coords3)
TYPE_NAME_ALIAS(std::vector< osg::Vec2 >, osgText::Text::GlyphQuads::TexCoords)
TYPE_NAME_ALIAS(std::vector< osg::Vec4 >, osgText::Text::GlyphQuads::ColorCoords)
BEGIN_VALUE_REFLECTOR(osgText::Text::GlyphQuads)
I_DeclaringFile("osgText/Text");
I_Constructor0(____GlyphQuads,
"",
"");
I_Method0(osgText::Text::GlyphQuads::Glyphs, getGlyphs,
Properties::NON_VIRTUAL,
__Glyphs__getGlyphs,
"",
"");
I_Method0(const osgText::Text::GlyphQuads::Glyphs, getGlyphs,
Properties::NON_VIRTUAL,
__C5_Glyphs__getGlyphs,
"",
"");
I_Method0(osgText::Text::GlyphQuads::Coords2 &, getCoords,
Properties::NON_VIRTUAL,
__Coords2_R1__getCoords,
"",
"");
I_Method0(const osgText::Text::GlyphQuads::Coords2 &, getCoords,
Properties::NON_VIRTUAL,
__C5_Coords2_R1__getCoords,
"",
"");
I_Method1(osgText::Text::GlyphQuads::Coords3 &, getTransformedCoords, IN, unsigned int, contexID,
Properties::NON_VIRTUAL,
__Coords3_R1__getTransformedCoords__unsigned_int,
"",
"");
I_Method1(const osgText::Text::GlyphQuads::Coords3 &, getTransformedCoords, IN, unsigned int, contexID,
Properties::NON_VIRTUAL,
__C5_Coords3_R1__getTransformedCoords__unsigned_int,
"",
"");
I_Method0(osgText::Text::GlyphQuads::TexCoords &, getTexCoords,
Properties::NON_VIRTUAL,
__TexCoords_R1__getTexCoords,
"",
"");
I_Method0(const osgText::Text::GlyphQuads::TexCoords &, getTexCoords,
Properties::NON_VIRTUAL,
__C5_TexCoords_R1__getTexCoords,
"",
"");
I_Method0(osgText::Text::GlyphQuads::LineNumbers &, getLineNumbers,
Properties::NON_VIRTUAL,
__LineNumbers_R1__getLineNumbers,
"",
"");
I_Method0(const osgText::Text::GlyphQuads::LineNumbers &, getLineNumbers,
Properties::NON_VIRTUAL,
__C5_LineNumbers_R1__getLineNumbers,
"",
"");
I_SimpleProperty(osgText::Text::GlyphQuads::Coords2 &, Coords,
__Coords2_R1__getCoords,
0);
I_SimpleProperty(osgText::Text::GlyphQuads::Glyphs, Glyphs,
__Glyphs__getGlyphs,
0);
I_SimpleProperty(osgText::Text::GlyphQuads::LineNumbers &, LineNumbers,
__LineNumbers_R1__getLineNumbers,
0);
I_SimpleProperty(osgText::Text::GlyphQuads::TexCoords &, TexCoords,
__TexCoords_R1__getTexCoords,
0);
I_PublicMemberProperty(osgText::Text::GlyphQuads::Glyphs, _glyphs);
I_PublicMemberProperty(osgText::Text::GlyphQuads::Coords2, _coords);
I_PublicMemberProperty(osg::buffered_object< osgText::Text::GlyphQuads::Coords3 >, _transformedCoords);
I_PublicMemberProperty(osgText::Text::GlyphQuads::TexCoords, _texcoords);
I_PublicMemberProperty(osgText::Text::GlyphQuads::LineNumbers, _lineNumbers);
I_PublicMemberProperty(osgText::Text::GlyphQuads::ColorCoords, _colorCoords);
END_REFLECTOR
BEGIN_VALUE_REFLECTOR(osg::ref_ptr< osgText::Font >) BEGIN_VALUE_REFLECTOR(osg::ref_ptr< osgText::Font >)
I_DeclaringFile("osg/ref_ptr"); I_DeclaringFile("osg/ref_ptr");
I_Constructor0(____ref_ptr, I_Constructor0(____ref_ptr,