Merge pull request #11 from assimp/master

Update fork
pull/1350/head
Madrich 2016-08-05 09:22:08 +02:00 committed by GitHub
commit 8513089060
467 changed files with 21253 additions and 9709 deletions

2
.gitignore vendored
View File

@ -18,6 +18,7 @@ assimp.pc
revision.h revision.h
contrib/zlib/zconf.h contrib/zlib/zconf.h
contrib/zlib/zlib.pc contrib/zlib/zlib.pc
include/assimp/config.h
# CMake # CMake
CMakeCache.txt CMakeCache.txt
@ -72,3 +73,4 @@ lib64/assimp-vc120-mtd.pdb
lib64/assimp-vc120-mtd.ilk lib64/assimp-vc120-mtd.ilk
lib64/assimp-vc120-mtd.exp lib64/assimp-vc120-mtd.exp
lib64/assimp-vc120-mt.exp lib64/assimp-vc120-mt.exp
xcuserdata

View File

@ -11,6 +11,6 @@ else
&& sudo make install \ && sudo make install \
&& sudo ldconfig \ && sudo ldconfig \
&& (cd test/unit; ../../bin/unit) \ && (cd test/unit; ../../bin/unit) \
#&& (cd test/regression; chmod 755 run.py; ./run.py; \ #&& (cd test/regression; chmod 755 run.py; ./run.py ../../bin/assimp; \
#chmod 755 result_checker.py; ./result_checker.py) # chmod 755 result_checker.py; ./result_checker.py)
fi fi

View File

@ -19,7 +19,7 @@ env:
- ANDROID=1 - ANDROID=1
language: cpp language: cpp
compiler: compiler:
- gcc - gcc
- clang - clang

View File

@ -1,28 +1,65 @@
set(CMAKE_LEGACY_CYGWIN_WIN32 0) # Remove when CMake >= 2.8.4 is required # Open Asset Import Library (assimp)
# ----------------------------------------------------------------------
#
# Copyright (c) 2006-2016, assimp team
# All rights reserved.
#
# Redistribution and use of this software in source and binary forms,
# with or without modification, are permitted provided that the
# following conditions are met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the
# following disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the
# following disclaimer in the documentation and/or other
# materials provided with the distribution.
#
# * Neither the name of the assimp team, nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior
# written permission of the assimp team.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#----------------------------------------------------------------------
SET(CMAKE_LEGACY_CYGWIN_WIN32 0) # Remove when CMake >= 2.8.4 is required
cmake_minimum_required( VERSION 2.8 ) cmake_minimum_required( VERSION 2.8 )
PROJECT( Assimp ) PROJECT( Assimp )
option(BUILD_SHARED_LIBS "Build package with shared libraries." ON) OPTION(BUILD_SHARED_LIBS "Build package with shared libraries." ON)
if(NOT BUILD_SHARED_LIBS) IF(NOT BUILD_SHARED_LIBS)
#set(CMAKE_EXE_LINKER_FLAGS "-static") SET(LINK_SEARCH_START_STATIC TRUE)
set(LINK_SEARCH_START_STATIC TRUE) ENDIF(NOT BUILD_SHARED_LIBS)
endif(NOT BUILD_SHARED_LIBS)
# Define here the needed parameters # Define here the needed parameters
set (ASSIMP_VERSION_MAJOR 3) SET (ASSIMP_VERSION_MAJOR 3)
set (ASSIMP_VERSION_MINOR 2) SET (ASSIMP_VERSION_MINOR 3)
set (ASSIMP_VERSION_PATCH 0) # subversion revision? SET (ASSIMP_VERSION_PATCH 1) # subversion revision?
set (ASSIMP_VERSION ${ASSIMP_VERSION_MAJOR}.${ASSIMP_VERSION_MINOR}.${ASSIMP_VERSION_PATCH}) SET (ASSIMP_VERSION ${ASSIMP_VERSION_MAJOR}.${ASSIMP_VERSION_MINOR}.${ASSIMP_VERSION_PATCH})
set (ASSIMP_SOVERSION 3) SET (ASSIMP_SOVERSION 3)
set (PROJECT_VERSION "${ASSIMP_VERSION}") SET (PROJECT_VERSION "${ASSIMP_VERSION}")
set(ASSIMP_PACKAGE_VERSION "0" CACHE STRING "the package-specific version used for uploading the sources") SET(ASSIMP_PACKAGE_VERSION "0" CACHE STRING "the package-specific version used for uploading the sources")
# Needed for openddl_parser config, no use of c++11 at this moment # Needed for openddl_parser config, no use of c++11 at this moment
add_definitions( -DOPENDDL_NO_USE_CPP11 ) add_definitions( -DOPENDDL_NO_USE_CPP11 )
set_property( GLOBAL PROPERTY CXX_STANDARD 11 )
# Get the current working branch # Get the current working branch
execute_process( EXECUTE_PROCESS(
COMMAND git rev-parse --abbrev-ref HEAD COMMAND git rev-parse --abbrev-ref HEAD
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
OUTPUT_VARIABLE GIT_BRANCH OUTPUT_VARIABLE GIT_BRANCH
@ -31,7 +68,7 @@ execute_process(
) )
# Get the latest abbreviated commit hash of the working branch # Get the latest abbreviated commit hash of the working branch
execute_process( EXECUTE_PROCESS(
COMMAND git log -1 --format=%h COMMAND git log -1 --format=%h
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
OUTPUT_VARIABLE GIT_COMMIT_HASH OUTPUT_VARIABLE GIT_COMMIT_HASH
@ -39,41 +76,63 @@ execute_process(
ERROR_QUIET ERROR_QUIET
) )
if(NOT GIT_COMMIT_HASH) IF(NOT GIT_COMMIT_HASH)
set(GIT_COMMIT_HASH 0) SET(GIT_COMMIT_HASH 0)
endif(NOT GIT_COMMIT_HASH) ENDIF(NOT GIT_COMMIT_HASH)
OPTION(ASSIMP_DOUBLE_PRECISION
"Set to ON to enable double precision processing"
OFF
)
IF(ASSIMP_DOUBLE_PRECISION)
ADD_DEFINITIONS(-DAI_DOUBLE_PRECISION)
ENDIF(ASSIMP_DOUBLE_PRECISION)
configure_file( configure_file(
${CMAKE_CURRENT_SOURCE_DIR}/revision.h.in ${CMAKE_CURRENT_LIST_DIR}/revision.h.in
${CMAKE_CURRENT_BINARY_DIR}/revision.h ${CMAKE_CURRENT_BINARY_DIR}/revision.h
) )
include_directories(${CMAKE_CURRENT_BINARY_DIR}) configure_file(
${CMAKE_CURRENT_LIST_DIR}/include/assimp/config.h.in
${CMAKE_CURRENT_LIST_DIR}/include/assimp/config.h
)
option(ASSIMP_OPT_BUILD_PACKAGES "Set to ON to generate CPack configuration files and packaging targets" OFF) include_directories(
set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake-modules" ) ./
set(LIBASSIMP_COMPONENT "libassimp${ASSIMP_VERSION_MAJOR}.${ASSIMP_VERSION_MINOR}.${ASSIMP_VERSION_PATCH}" ) ${CMAKE_CURRENT_BINARY_DIR}
set(LIBASSIMP-DEV_COMPONENT "libassimp${ASSIMP_VERSION_MAJOR}.${ASSIMP_VERSION_MINOR}.${ASSIMP_VERSION_PATCH}-dev" ) ${CMAKE_CURRENT_BINARY_DIR}/include
set(CPACK_COMPONENTS_ALL assimp-bin ${LIBASSIMP_COMPONENT} ${LIBASSIMP-DEV_COMPONENT} assimp-dev) )
set(ASSIMP_LIBRARY_SUFFIX "" CACHE STRING "Suffix to append to library names")
option(ASSIMP_ANDROID_JNIIOSYSTEM "Android JNI IOSystem support is active" OFF) OPTION(ASSIMP_OPT_BUILD_PACKAGES "Set to ON to generate CPack configuration files and packaging targets" OFF)
SET(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake-modules" )
SET(LIBASSIMP_COMPONENT "libassimp${ASSIMP_VERSION_MAJOR}.${ASSIMP_VERSION_MINOR}.${ASSIMP_VERSION_PATCH}" )
SET(LIBASSIMP-DEV_COMPONENT "libassimp${ASSIMP_VERSION_MAJOR}.${ASSIMP_VERSION_MINOR}.${ASSIMP_VERSION_PATCH}-dev" )
SET(CPACK_COMPONENTS_ALL assimp-bin ${LIBASSIMP_COMPONENT} ${LIBASSIMP-DEV_COMPONENT} assimp-dev)
SET(ASSIMP_LIBRARY_SUFFIX "" CACHE STRING "Suffix to append to library names")
OPTION(ASSIMP_ANDROID_JNIIOSYSTEM "Android JNI IOSystem support is active" OFF)
# Workaround to be able to deal with compiler bug "Too many sections" with mingw. # Workaround to be able to deal with compiler bug "Too many sections" with mingw.
if( CMAKE_COMPILER_IS_MINGW ) IF( CMAKE_COMPILER_IS_MINGW )
ADD_DEFINITIONS(-DASSIMP_BUILD_NO_IFC_IMPORTER ) ADD_DEFINITIONS(-DASSIMP_BUILD_NO_IFC_IMPORTER )
endif() ENDIF()
if((CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX) AND NOT CMAKE_COMPILER_IS_MINGW) IF((CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX) AND NOT CMAKE_COMPILER_IS_MINGW)
if (BUILD_SHARED_LIBS AND CMAKE_SIZEOF_VOID_P EQUAL 8) # -fPIC is only required for shared libs on 64 bit IF (BUILD_SHARED_LIBS AND CMAKE_SIZEOF_VOID_P EQUAL 8) # -fPIC is only required for shared libs on 64 bit
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC") SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC")
endif() ENDIF()
# hide all not-exported symbols # hide all not-exported symbols
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden -Wall" ) SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden -Wall -std=c++0x" )
elseif(MSVC) ELSEIF(MSVC)
# enable multi-core compilation with MSVC # enable multi-core compilation with MSVC
add_definitions(/MP) add_compile_options(/MP)
endif() ELSEIF ( "${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang" )
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden -Wall -Wno-long-long -pedantic -std=c++11" )
ELSEIF( CMAKE_COMPILER_IS_MINGW )
SET( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden -Wall -Wno-long-long -pedantic -std=c++11" )
ENDIF()
INCLUDE (FindPkgConfig) INCLUDE (FindPkgConfig)
INCLUDE_DIRECTORIES( include ) INCLUDE_DIRECTORIES( include )
@ -91,11 +150,11 @@ IF ( CMAKE_SOURCE_DIR STREQUAL CMAKE_BINARY_DIR )
ENDIF ( CMAKE_SOURCE_DIR STREQUAL CMAKE_BINARY_DIR ) ENDIF ( CMAKE_SOURCE_DIR STREQUAL CMAKE_BINARY_DIR )
# Cache these to allow the user to override them manually. # Cache these to allow the user to override them manually.
SET( ASSIMP_LIB_INSTALL_DIR "lib" CACHE PATH SET( ASSIMP_LIB_INSTALL_DIR "lib" CACHE STRING
"Path the built library files are installed to." ) "Path the built library files are installed to." )
SET( ASSIMP_INCLUDE_INSTALL_DIR "include" CACHE PATH SET( ASSIMP_INCLUDE_INSTALL_DIR "include" CACHE STRING
"Path the header files are installed to." ) "Path the header files are installed to." )
SET( ASSIMP_BIN_INSTALL_DIR "bin" CACHE PATH SET( ASSIMP_BIN_INSTALL_DIR "bin" CACHE STRING
"Path the tool executables are installed to." ) "Path the tool executables are installed to." )
IF (CMAKE_BUILD_TYPE STREQUAL "Debug") IF (CMAKE_BUILD_TYPE STREQUAL "Debug")
@ -111,32 +170,7 @@ IF (NOT TARGET uninstall)
add_custom_target(uninstall "${CMAKE_COMMAND}" -P "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake") add_custom_target(uninstall "${CMAKE_COMMAND}" -P "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake")
ENDIF() ENDIF()
# Globally enable Boost resp. the Boost workaround – it is also needed by the
# tools which include the Assimp headers.
option ( ASSIMP_ENABLE_BOOST_WORKAROUND
"If a simple implementation of the used Boost functions is used. Slightly reduces functionality, but enables builds without Boost available."
ON
)
IF ( ASSIMP_ENABLE_BOOST_WORKAROUND )
INCLUDE_DIRECTORIES( code/BoostWorkaround )
ADD_DEFINITIONS( -DASSIMP_BUILD_BOOST_WORKAROUND )
MESSAGE( STATUS "Building a non-boost version of Assimp." )
ELSE ( ASSIMP_ENABLE_BOOST_WORKAROUND )
SET( Boost_DETAILED_FAILURE_MSG ON )
IF ( NOT Boost_ADDITIONAL_VERSIONS )
SET( Boost_ADDITIONAL_VERSIONS "1.47" "1.47.0" "1.48.0" "1.48" "1.49" "1.49.0" "1.50" "1.50.0" "1.51" "1.51.0" "1.52.0" "1.53.0" "1.54.0" "1.55" "1.55.0" "1.56" "1.56.0" "1.57" "1.57.0" "1.58" "1.58.0" "1.59" "1.59.0")
ENDIF ( NOT Boost_ADDITIONAL_VERSIONS )
FIND_PACKAGE( Boost )
IF ( NOT Boost_FOUND )
MESSAGE( FATAL_ERROR
"Boost libraries (http://www.boost.org/) not found. "
"You can build a non-boost version of Assimp with slightly reduced "
"functionality by specifying -DASSIMP_ENABLE_BOOST_WORKAROUND=ON."
)
ENDIF ( NOT Boost_FOUND )
INCLUDE_DIRECTORIES( ${Boost_INCLUDE_DIRS} )
ENDIF ( ASSIMP_ENABLE_BOOST_WORKAROUND )
# cmake configuration files # cmake configuration files
configure_file("${CMAKE_CURRENT_SOURCE_DIR}/assimp-config.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/assimp-config.cmake" @ONLY IMMEDIATE) configure_file("${CMAKE_CURRENT_SOURCE_DIR}/assimp-config.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/assimp-config.cmake" @ONLY IMMEDIATE)
@ -145,38 +179,46 @@ install(FILES "${CMAKE_CURRENT_BINARY_DIR}/assimp-config.cmake" "${C
FIND_PACKAGE( DirectX ) FIND_PACKAGE( DirectX )
option ( ASSIMP_NO_EXPORT OPTION ( ASSIMP_NO_EXPORT
"Disable Assimp's export functionality." "Disable Assimp's export functionality."
OFF OFF
) )
if( CMAKE_COMPILER_IS_GNUCXX ) IF( CMAKE_COMPILER_IS_GNUCXX )
set(LIBSTDC++_LIBRARIES -lstdc++) SET(LIBSTDC++_LIBRARIES -lstdc++)
endif( CMAKE_COMPILER_IS_GNUCXX ) ENDIF( CMAKE_COMPILER_IS_GNUCXX )
# Search for external dependencies, and build them from source if not found # Search for external dependencies, and build them from source if not found
# Search for zlib # Search for zlib
find_package(ZLIB) OPTION(ASSIMP_BUILD_ZLIB
if( NOT ZLIB_FOUND ) "Build your own zlib"
OFF
)
IF ( NOT ASSIMP_BUILD_ZLIB )
find_package(ZLIB)
ENDIF( NOT ASSIMP_BUILD_ZLIB )
IF( NOT ZLIB_FOUND )
message(STATUS "compiling zlib from souces") message(STATUS "compiling zlib from souces")
include(CheckIncludeFile) include(CheckIncludeFile)
include(CheckTypeSize) include(CheckTypeSize)
include(CheckFunctionExists) include(CheckFunctionExists)
# compile from sources # compile from sources
add_subdirectory(contrib/zlib) add_subdirectory(contrib/zlib)
set(ZLIB_FOUND 1) SET(ZLIB_FOUND 1)
set(ZLIB_LIBRARIES zlibstatic) SET(ZLIB_LIBRARIES zlibstatic)
set(ZLIB_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/contrib/zlib ${CMAKE_CURRENT_BINARY_DIR}/contrib/zlib) SET(ZLIB_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/contrib/zlib ${CMAKE_CURRENT_BINARY_DIR}/contrib/zlib)
else(NOT ZLIB_FOUND) else(NOT ZLIB_FOUND)
ADD_DEFINITIONS(-DASSIMP_BUILD_NO_OWN_ZLIB) ADD_DEFINITIONS(-DASSIMP_BUILD_NO_OWN_ZLIB)
set(ZLIB_LIBRARIES_LINKED -lz) SET(ZLIB_LIBRARIES_LINKED -lz)
endif(NOT ZLIB_FOUND) ENDIF(NOT ZLIB_FOUND)
INCLUDE_DIRECTORIES(${ZLIB_INCLUDE_DIR}) INCLUDE_DIRECTORIES(${ZLIB_INCLUDE_DIR})
# Search for unzip # Search for unzip
if (PKG_CONFIG_FOUND) IF (PKG_CONFIG_FOUND)
PKG_CHECK_MODULES(UNZIP minizip) PKG_CHECK_MODULES(UNZIP minizip)
endif (PKG_CONFIG_FOUND) ENDIF (PKG_CONFIG_FOUND)
IF ( ASSIMP_NO_EXPORT ) IF ( ASSIMP_NO_EXPORT )
ADD_DEFINITIONS( -DASSIMP_BUILD_NO_EXPORT) ADD_DEFINITIONS( -DASSIMP_BUILD_NO_EXPORT)
@ -204,60 +246,91 @@ MARK_AS_ADVANCED ( ASSIMP_BUILD_ARCHITECTURE ASSIMP_BUILD_COMPILER )
SET ( ASSIMP_BUILD_NONFREE_C4D_IMPORTER OFF CACHE BOOL SET ( ASSIMP_BUILD_NONFREE_C4D_IMPORTER OFF CACHE BOOL
"Build the C4D importer, which relies on the non-free Melange SDK." "Build the C4D importer, which relies on the non-free Melange SDK."
) )
IF (ASSIMP_BUILD_NONFREE_C4D_IMPORTER) IF (ASSIMP_BUILD_NONFREE_C4D_IMPORTER)
IF ( MSVC ) IF ( MSVC )
SET(C4D_INCLUDES "${CMAKE_CURRENT_SOURCE_DIR}/contrib/Melange/_melange/includes") SET(C4D_INCLUDES "${CMAKE_CURRENT_SOURCE_DIR}/contrib/Melange/includes")
# pick the correct prebuilt library # pick the correct prebuilt library
IF(MSVC11) IF(MSVC14)
SET(C4D_LIB_POSTFIX "_2012md") SET(C4D_LIB_POSTFIX "_2015")
ELSEIF(MSVC12)
SET(C4D_LIB_POSTFIX "_2013")
ELSEIF(MSVC11)
SET(C4D_LIB_POSTFIX "_2012")
ELSEIF(MSVC10) ELSEIF(MSVC10)
SET(C4D_LIB_POSTFIX "_2010md") SET(C4D_LIB_POSTFIX "_2010")
ELSEIF(MSVC90)
SET(C4D_LIB_POSTFIX "_2008md")
ELSE() ELSE()
MESSAGE( FATAL_ERROR MESSAGE( FATAL_ERROR
"C4D is currently only supported with MSVC 9, 10, 11" "C4D is currently only supported with MSVC 10, 11, 12, 14"
) )
ENDIF() ENDIF()
IF(CMAKE_CL_64) SET(C4D_LIB_BASE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/contrib/Melange/libraries/win")
SET(C4D_LIB_ARCH_POSTFIX "_x64")
ELSE() SET(C4D_DEBUG_LIBRARIES
SET(C4D_LIB_ARCH_POSTFIX "") "${C4D_LIB_BASE_PATH}/melangelib${C4D_LIB_POSTFIX}/melangelib_debug.lib"
ENDIF() "${C4D_LIB_BASE_PATH}/jpeglib${C4D_LIB_POSTFIX}/jpeglib_debug.lib"
)
SET(C4D_LIB_BASE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/contrib/Melange/_melange/lib/WIN") SET(C4D_RELEASE_LIBRARIES
"${C4D_LIB_BASE_PATH}/melangelib${C4D_LIB_POSTFIX}/melangelib_release.lib"
SET(C4D_DEBUG_LIBRARY "${C4D_LIB_BASE_PATH}/debug/_melange_lib${C4D_LIB_ARCH_POSTFIX}${C4D_LIB_POSTFIX}.lib") "${C4D_LIB_BASE_PATH}/jpeglib${C4D_LIB_POSTFIX}/jpeglib_release.lib"
SET(C4D_RELEASE_LIBRARY "${C4D_LIB_BASE_PATH}/release/_melange_lib${C4D_LIB_ARCH_POSTFIX}${C4D_LIB_POSTFIX}.lib") )
# winsock and winmm are necessary dependencies of melange (this is undocumented, but true.) # winsock and winmm are necessary dependencies of melange (this is undocumented, but true.)
SET(C4D_EXTRA_LIBRARIES WSock32.lib Winmm.lib) SET(C4D_EXTRA_LIBRARIES WSock32.lib Winmm.lib)
ELSE () ELSE ()
MESSAGE( FATAL_ERROR MESSAGE( FATAL_ERROR
"C4D is currently only available on Windows with melange SDK installed in contrib/Melange" "C4D is currently only available on Windows with melange SDK installed in contrib/Melange"
) )
ENDIF ( MSVC ) ENDIF ( MSVC )
else (ASSIMP_BUILD_NONFREE_C4D_IMPORTER) ELSE (ASSIMP_BUILD_NONFREE_C4D_IMPORTER)
ADD_DEFINITIONS( -DASSIMP_BUILD_NO_C4D_IMPORTER ) ADD_DEFINITIONS( -DASSIMP_BUILD_NO_C4D_IMPORTER )
ENDIF (ASSIMP_BUILD_NONFREE_C4D_IMPORTER) ENDIF (ASSIMP_BUILD_NONFREE_C4D_IMPORTER)
ADD_SUBDIRECTORY( code/ ) ADD_SUBDIRECTORY( code/ )
option ( ASSIMP_BUILD_ASSIMP_TOOLS option ( ASSIMP_BUILD_ASSIMP_TOOLS
"If the supplementary tools for Assimp are built in addition to the library." "If the supplementary tools for Assimp are built in addition to the library."
ON ON
) )
IF ( ASSIMP_BUILD_ASSIMP_TOOLS ) IF ( ASSIMP_BUILD_ASSIMP_TOOLS )
IF ( WIN32 AND DirectX_FOUND ) IF ( WIN32 )
ADD_SUBDIRECTORY( tools/assimp_view/ ) option ( ASSIMP_BUILD_ASSIMP_VIEW "If the Assimp view tool is built. (requires DirectX)" ${DirectX_FOUND} )
ENDIF ( WIN32 AND DirectX_FOUND ) IF ( ASSIMP_BUILD_ASSIMP_VIEW )
ADD_SUBDIRECTORY( tools/assimp_view/ )
ENDIF ( ASSIMP_BUILD_ASSIMP_VIEW )
ENDIF ( WIN32 )
ADD_SUBDIRECTORY( tools/assimp_cmd/ ) ADD_SUBDIRECTORY( tools/assimp_cmd/ )
# Check dependencies for assimp_qt_viewer.
# Why here? Maybe user do not want Qt viewer and have no Qt.
# Why assimp_qt_viewer/CMakeLists.txt still contain similar check?
# Because viewer can be build independently of Assimp.
FIND_PACKAGE(Qt4 QUIET)
FIND_PACKAGE(DevIL QUIET)
FIND_PACKAGE(OpenGL QUIET)
IF ( Qt4_FOUND AND IL_FOUND AND OPENGL_FOUND)
ADD_SUBDIRECTORY( tools/assimp_qt_viewer/ )
ELSE()
SET ( ASSIMP_QT_VIEWER_DEPENDENCIES "")
IF (NOT Qt4_FOUND)
SET ( ASSIMP_QT_VIEWER_DEPENDENCIES "${ASSIMP_QT_VIEWER_DEPENDENCIES} Qt4")
ENDIF (NOT Qt4_FOUND)
IF (NOT IL_FOUND)
SET ( ASSIMP_QT_VIEWER_DEPENDENCIES "${ASSIMP_QT_VIEWER_DEPENDENCIES} DevIL")
ENDIF (NOT IL_FOUND)
IF (NOT OPENGL_FOUND)
SET ( ASSIMP_QT_VIEWER_DEPENDENCIES "${ASSIMP_QT_VIEWER_DEPENDENCIES} OpengGL")
ENDIF (NOT OPENGL_FOUND)
MESSAGE (WARNING "Build of assimp_qt_viewer is disabled. Unsatisfied dendencies: ${ASSIMP_QT_VIEWER_DEPENDENCIES}")
ENDIF ( Qt4_FOUND AND IL_FOUND AND OPENGL_FOUND)
ENDIF ( ASSIMP_BUILD_ASSIMP_TOOLS ) ENDIF ( ASSIMP_BUILD_ASSIMP_TOOLS )
option ( ASSIMP_BUILD_SAMPLES option ( ASSIMP_BUILD_SAMPLES
@ -272,7 +345,7 @@ IF ( ASSIMP_BUILD_SAMPLES)
ADD_SUBDIRECTORY( samples/SimpleOpenGL/ ) ADD_SUBDIRECTORY( samples/SimpleOpenGL/ )
ENDIF ( ASSIMP_BUILD_SAMPLES ) ENDIF ( ASSIMP_BUILD_SAMPLES )
option ( ASSIMP_BUILD_TESTS OPTION ( ASSIMP_BUILD_TESTS
"If the test suite for Assimp is built in addition to the library." "If the test suite for Assimp is built in addition to the library."
ON ON
) )
@ -282,7 +355,7 @@ IF ( ASSIMP_BUILD_TESTS )
ENDIF ( ASSIMP_BUILD_TESTS ) ENDIF ( ASSIMP_BUILD_TESTS )
IF(MSVC) IF(MSVC)
option ( ASSIMP_INSTALL_PDB OPTION ( ASSIMP_INSTALL_PDB
"Install MSVC debug files." "Install MSVC debug files."
ON ON
) )
@ -292,72 +365,72 @@ ENDIF(MSVC)
CONFIGURE_FILE( "${PROJECT_SOURCE_DIR}/assimp.pc.in" "${PROJECT_BINARY_DIR}/assimp.pc" @ONLY ) CONFIGURE_FILE( "${PROJECT_SOURCE_DIR}/assimp.pc.in" "${PROJECT_BINARY_DIR}/assimp.pc" @ONLY )
INSTALL( FILES "${PROJECT_BINARY_DIR}/assimp.pc" DESTINATION ${ASSIMP_LIB_INSTALL_DIR}/pkgconfig/ COMPONENT ${LIBASSIMP-DEV_COMPONENT}) INSTALL( FILES "${PROJECT_BINARY_DIR}/assimp.pc" DESTINATION ${ASSIMP_LIB_INSTALL_DIR}/pkgconfig/ COMPONENT ${LIBASSIMP-DEV_COMPONENT})
if(CMAKE_CPACK_COMMAND AND UNIX AND ASSIMP_OPT_BUILD_PACKAGES) IF(CMAKE_CPACK_COMMAND AND UNIX AND ASSIMP_OPT_BUILD_PACKAGES)
# Packing information # Packing information
set(CPACK_PACKAGE_NAME "assimp{ASSIMP_VERSION_MAJOR}") SET(CPACK_PACKAGE_NAME "assimp{ASSIMP_VERSION_MAJOR}")
set(CPACK_PACKAGE_CONTACT "" CACHE STRING "Package maintainer and PGP signer.") SET(CPACK_PACKAGE_CONTACT "" CACHE STRING "Package maintainer and PGP signer.")
set(CPACK_PACKAGE_VENDOR "http://assimp.sourceforge.net/") SET(CPACK_PACKAGE_VENDOR "https://github.com/assimp")
set(CPACK_PACKAGE_DISPLAY_NAME "Assimp ${ASSIMP_VERSION}") SET(CPACK_PACKAGE_DISPLAY_NAME "Assimp ${ASSIMP_VERSION}")
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY " - Open Asset Import Library ${ASSIMP_VERSION}") SET(CPACK_PACKAGE_DESCRIPTION_SUMMARY " - Open Asset Import Library ${ASSIMP_VERSION}")
set(CPACK_PACKAGE_VERSION "${ASSIMP_VERSION}.${ASSIMP_PACKAGE_VERSION}" ) SET(CPACK_PACKAGE_VERSION "${ASSIMP_VERSION}.${ASSIMP_PACKAGE_VERSION}" )
set(CPACK_PACKAGE_VERSION_MAJOR "${ASSIMP_VERSION_MAJOR}") SET(CPACK_PACKAGE_VERSION_MAJOR "${ASSIMP_VERSION_MAJOR}")
set(CPACK_PACKAGE_VERSION_MINOR "${ASSIMP_VERSION_MINOR}") SET(CPACK_PACKAGE_VERSION_MINOR "${ASSIMP_VERSION_MINOR}")
set(CPACK_PACKAGE_VERSION_PATCH "${ASSIMP_VERSION_PATCH}") SET(CPACK_PACKAGE_VERSION_PATCH "${ASSIMP_VERSION_PATCH}")
set(CPACK_PACKAGE_INSTALL_DIRECTORY "assimp${ASSIMP_VERSION_MAJOR}.${ASSIMP_VERSION_MINOR}") SET(CPACK_PACKAGE_INSTALL_DIRECTORY "assimp${ASSIMP_VERSION_MAJOR}.${ASSIMP_VERSION_MINOR}")
set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE") SET(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE")
string(TOUPPER ${LIBASSIMP_COMPONENT} "LIBASSIMP_COMPONENT_UPPER") string(TOUPPER ${LIBASSIMP_COMPONENT} "LIBASSIMP_COMPONENT_UPPER")
string(TOUPPER ${LIBASSIMP-DEV_COMPONENT} "LIBASSIMP-DEV_COMPONENT_UPPER") string(TOUPPER ${LIBASSIMP-DEV_COMPONENT} "LIBASSIMP-DEV_COMPONENT_UPPER")
set(CPACK_COMPONENT_ASSIMP-BIN_DISPLAY_NAME "tools") SET(CPACK_COMPONENT_ASSIMP-BIN_DISPLAY_NAME "tools")
set(CPACK_COMPONENT_ASSIMP-BIN_DEPENDS "${LIBASSIMP_COMPONENT}" ) SET(CPACK_COMPONENT_ASSIMP-BIN_DEPENDS "${LIBASSIMP_COMPONENT}" )
set(CPACK_COMPONENT_${LIBASSIMP_COMPONENT_UPPER}_DISPLAY_NAME "libraries") SET(CPACK_COMPONENT_${LIBASSIMP_COMPONENT_UPPER}_DISPLAY_NAME "libraries")
set(CPACK_COMPONENT_${LIBASSIMP-DEV_COMPONENT_UPPER}_DISPLAY_NAME "common headers and installs") SET(CPACK_COMPONENT_${LIBASSIMP-DEV_COMPONENT_UPPER}_DISPLAY_NAME "common headers and installs")
set(CPACK_COMPONENT_${LIBASSIMP-DEV_COMPONENT_UPPER}_DEPENDS $ "{LIBASSIMP_COMPONENT}" ) SET(CPACK_COMPONENT_${LIBASSIMP-DEV_COMPONENT_UPPER}_DEPENDS $ "{LIBASSIMP_COMPONENT}" )
set(CPACK_COMPONENT_ASSIMP-DEV_DISPLAY_NAME "${CPACK_COMPONENT_${LIBASSIMP-DEV_COMPONENT}_DISPLAY_NAME}" ) SET(CPACK_COMPONENT_ASSIMP-DEV_DISPLAY_NAME "${CPACK_COMPONENT_${LIBASSIMP-DEV_COMPONENT}_DISPLAY_NAME}" )
set(CPACK_COMPONENT_ASSIMP-DEV_DEPENDS "${LIBASSIMP-DEV_COMPONENT}" ) SET(CPACK_COMPONENT_ASSIMP-DEV_DEPENDS "${LIBASSIMP-DEV_COMPONENT}" )
set(CPACK_DEBIAN_BUILD_DEPENDS debhelper cmake libboost-dev libboost-thread-dev libboost-math-dev zlib1g-dev pkg-config) SET(CPACK_DEBIAN_BUILD_DEPENDS debhelper cmake zlib1g-dev pkg-config)
# debian # debian
set(CPACK_DEBIAN_PACKAGE_PRIORITY "optional") SET(CPACK_DEBIAN_PACKAGE_PRIORITY "optional")
set(CPACK_DEBIAN_CMAKE_OPTIONS "-DBUILD_ASSIMP_SAMPLES:BOOL=${ASSIMP_BUILD_SAMPLES}") SET(CPACK_DEBIAN_CMAKE_OPTIONS "-DBUILD_ASSIMP_SAMPLES:BOOL=${ASSIMP_BUILD_SAMPLES}")
set(CPACK_DEBIAN_PACKAGE_SECTION "libs" ) SET(CPACK_DEBIAN_PACKAGE_SECTION "libs" )
set(CPACK_DEBIAN_PACKAGE_DEPENDS "${CPACK_COMPONENTS_ALL}") SET(CPACK_DEBIAN_PACKAGE_DEPENDS "${CPACK_COMPONENTS_ALL}")
set(CPACK_DEBIAN_PACKAGE_SUGGESTS) SET(CPACK_DEBIAN_PACKAGE_SUGGESTS)
set(CPACK_DEBIAN_PACKAGE_NAME "assimp") SET(CPACK_DEBIAN_PACKAGE_NAME "assimp")
set(CPACK_DEBIAN_PACKAGE_REMOVE_SOURCE_FILES contrib/cppunit-1.12.1 contrib/cppunit_note.txt contrib/zlib workspaces test doc obj samples packaging) SET(CPACK_DEBIAN_PACKAGE_REMOVE_SOURCE_FILES contrib/cppunit-1.12.1 contrib/cppunit_note.txt contrib/zlib workspaces test doc obj samples packaging)
set(CPACK_DEBIAN_PACKAGE_SOURCE_COPY svn export --force) SET(CPACK_DEBIAN_PACKAGE_SOURCE_COPY svn export --force)
set(CPACK_DEBIAN_CHANGELOG) SET(CPACK_DEBIAN_CHANGELOG)
execute_process(COMMAND lsb_release -is execute_process(COMMAND lsb_release -is
OUTPUT_VARIABLE _lsb_distribution OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE _lsb_distribution OUTPUT_STRIP_TRAILING_WHITESPACE
RESULT_VARIABLE _lsb_release_failed) RESULT_VARIABLE _lsb_release_failed)
set(CPACK_DEBIAN_DISTRIBUTION_NAME ${_lsb_distribution} CACHE STRING "Name of the distrubiton") SET(CPACK_DEBIAN_DISTRIBUTION_NAME ${_lsb_distribution} CACHE STRING "Name of the distrubiton")
string(TOLOWER ${CPACK_DEBIAN_DISTRIBUTION_NAME} CPACK_DEBIAN_DISTRIBUTION_NAME) STRING(TOLOWER ${CPACK_DEBIAN_DISTRIBUTION_NAME} CPACK_DEBIAN_DISTRIBUTION_NAME)
if( ${CPACK_DEBIAN_DISTRIBUTION_NAME} STREQUAL "ubuntu" ) IF( ${CPACK_DEBIAN_DISTRIBUTION_NAME} STREQUAL "ubuntu" )
set(CPACK_DEBIAN_DISTRIBUTION_RELEASES lucid maverick natty oneiric precise CACHE STRING "Release code-names of the distrubiton release") SET(CPACK_DEBIAN_DISTRIBUTION_RELEASES lucid maverick natty oneiric precise CACHE STRING "Release code-names of the distrubiton release")
endif() ENDIF()
set(DPUT_HOST "" CACHE STRING "PPA repository to upload the debian sources") SET(DPUT_HOST "" CACHE STRING "PPA repository to upload the debian sources")
include(CPack) include(CPack)
include(DebSourcePPA) include(DebSourcePPA)
endif() ENDIF()
if(WIN32) if(WIN32)
if (CMAKE_SIZEOF_VOID_P EQUAL 8) if (CMAKE_SIZEOF_VOID_P EQUAL 8)
set(BIN_DIR "${PROJECT_SOURCE_DIR}/bin64/") SET(BIN_DIR "${PROJECT_SOURCE_DIR}/bin64/")
set(LIB_DIR "${PROJECT_SOURCE_DIR}/lib64/") SET(LIB_DIR "${PROJECT_SOURCE_DIR}/lib64/")
elseif() elseif()
set(BIN_DIR "${PROJECT_SOURCE_DIR}/bin32/") SET(BIN_DIR "${PROJECT_SOURCE_DIR}/bin32/")
set(LIB_DIR "${PROJECT_SOURCE_DIR}/lib32/") SET(LIB_DIR "${PROJECT_SOURCE_DIR}/lib32/")
endif() ENDIF()
if(MSVC12) if(MSVC12)
set(ASSIMP_MSVC_VERSION "vc120") SET(ASSIMP_MSVC_VERSION "vc120")
elseif(MSVC14) elseif(MSVC14)
set(ASSIMP_MSVC_VERSION "vc140") SET(ASSIMP_MSVC_VERSION "vc140")
endif(MSVC12) ENDIF(MSVC12)
if(MSVC12 OR MSVC14) if(MSVC12 OR MSVC14)
add_custom_target(UpdateAssimpLibsDebugSymbolsAndDLLs COMMENT "Copying Assimp Libraries ..." VERBATIM) add_custom_target(UpdateAssimpLibsDebugSymbolsAndDLLs COMMENT "Copying Assimp Libraries ..." VERBATIM)
add_custom_command(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Release/assimp-${ASSIMP_MSVC_VERSION}-mt.dll ${BIN_DIR}assimp-${ASSIMP_MSVC_VERSION}-mt.dll VERBATIM) add_custom_command(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Release/assimp-${ASSIMP_MSVC_VERSION}-mt.dll ${BIN_DIR}assimp-${ASSIMP_MSVC_VERSION}-mt.dll VERBATIM)
add_custom_command(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Release/assimp-${ASSIMP_MSVC_VERSION}-mt.exp ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mt.exp VERBATIM) add_custom_command(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Release/assimp-${ASSIMP_MSVC_VERSION}-mt.exp ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mt.exp VERBATIM)
add_custom_command(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Release/assimp-${ASSIMP_MSVC_VERSION}-mt.lib ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mt.lib VERBATIM) add_custom_command(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Release/assimp-${ASSIMP_MSVC_VERSION}-mt.lib ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mt.lib VERBATIM)
@ -366,5 +439,5 @@ if(WIN32)
add_custom_command(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Debug/assimp-${ASSIMP_MSVC_VERSION}-mtd.ilk ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.ilk VERBATIM) add_custom_command(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Debug/assimp-${ASSIMP_MSVC_VERSION}-mtd.ilk ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.ilk VERBATIM)
add_custom_command(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Debug/assimp-${ASSIMP_MSVC_VERSION}-mtd.lib ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.lib VERBATIM) add_custom_command(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Debug/assimp-${ASSIMP_MSVC_VERSION}-mtd.lib ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.lib VERBATIM)
add_custom_command(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Debug/assimp-${ASSIMP_MSVC_VERSION}-mtd.pdb ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.pdb VERBATIM) add_custom_command(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Debug/assimp-${ASSIMP_MSVC_VERSION}-mtd.pdb ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.pdb VERBATIM)
endif(MSVC12 OR MSVC14) ENDIF(MSVC12 OR MSVC14)
endif (WIN32) ENDIF (WIN32)

View File

@ -30,7 +30,7 @@ Ogre Loader, VC2010 fixes and CMake fixes.
- Sebastian Hempel, - Sebastian Hempel,
PyAssimp (first version) PyAssimp (first version)
Compile-Bugfixes for mingw, add enviroment for static library support in make. Compile-Bugfixes for mingw, add environment for static library support in make.
- Jonathan Pokrass - Jonathan Pokrass
Supplied a bugfix concerning the scaling in the md3 loader. Supplied a bugfix concerning the scaling in the md3 loader.
@ -114,7 +114,7 @@ Contributes a fix for the configure script environment.
Contributed AssimpDelphi (/port/AssimpDelphi). Contributed AssimpDelphi (/port/AssimpDelphi).
- rdb - rdb
Contributes a bundle of fixes and improvments for the bsp-importer. Contributes a bundle of fixes and improvements for the bsp-importer.
- Mick P - Mick P
For contributing the De-bone postprocessing step and filing various bug reports. For contributing the De-bone postprocessing step and filing various bug reports.

View File

@ -1,6 +1,5 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
================================== ==================================
Open Asset Import Library is a library to load various 3d file formats into a shared, in-memory format. It supports more than __40 file formats__ for import and a growing selection of file formats for export.
APIs are provided for C and C++. There are various bindings to other languages (C#, Java, Python, Delphi, D). Assimp also runs on Android and iOS. APIs are provided for C and C++. There are various bindings to other languages (C#, Java, Python, Delphi, D). Assimp also runs on Android and iOS.
@ -15,7 +14,8 @@ Coverity<a href="https://scan.coverity.com/projects/5607">
<img alt="Coverity Scan Build Status" <img alt="Coverity Scan Build Status"
src="https://scan.coverity.com/projects/5607/badge.svg"/> src="https://scan.coverity.com/projects/5607/badge.svg"/>
</a> </a>
Gitter [![Join the chat at https://gitter.im/assimp/assimp](https://badges.gitter.im/assimp/assimp.svg)](https://gitter.im/assimp/assimp?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
<br>
__[open3mod](https://github.com/acgessler/open3mod) is a powerful 3D model viewer based on Assimp's import and export abilities.__ __[open3mod](https://github.com/acgessler/open3mod) is a powerful 3D model viewer based on Assimp's import and export abilities.__
#### Supported file formats #### #### Supported file formats ####
@ -60,7 +60,8 @@ __Importers__:
- Ogre XML - Ogre XML
- Q3D - Q3D
- ASSBIN (Assimp custom format) - ASSBIN (Assimp custom format)
- glTF - glTF (partial)
- 3MF
Additionally, some formats are supported by dependency on non-free code or external SDKs (not built by default): Additionally, some formats are supported by dependency on non-free code or external SDKs (not built by default):
@ -76,7 +77,8 @@ __Exporters__:
- 3DS - 3DS
- JSON (for WebGl, via https://github.com/acgessler/assimp2json) - JSON (for WebGl, via https://github.com/acgessler/assimp2json)
- ASSBIN - ASSBIN
- glTF - STEP
- glTF (partial)
### Building ### ### Building ###
Take a look into the `INSTALL` file. Our build system is CMake, if you used CMake before there is a good chance you know what to do. Take a look into the `INSTALL` file. Our build system is CMake, if you used CMake before there is a good chance you know what to do.
@ -100,7 +102,7 @@ Open Asset Import Library is implemented in C++. The directory structure is:
/tools Tools (old assimp viewer, command line `assimp`) /tools Tools (old assimp viewer, command line `assimp`)
/samples A small number of samples to illustrate possible /samples A small number of samples to illustrate possible
use cases for Assimp use cases for Assimp
/workspaces Build enviroments for vc,xcode,... (deprecated, /workspaces Build environments for vc,xcode,... (deprecated,
CMake has superseeded all legacy build options!) CMake has superseeded all legacy build options!)
@ -113,6 +115,8 @@ If the docs don't solve your problem, ask on [StackOverflow](http://stackoverflo
For development discussions, there is also a (very low-volume) mailing list, _assimp-discussions_ For development discussions, there is also a (very low-volume) mailing list, _assimp-discussions_
[(subscribe here)]( https://lists.sourceforge.net/lists/listinfo/assimp-discussions) [(subscribe here)]( https://lists.sourceforge.net/lists/listinfo/assimp-discussions)
Open Asset Import Library is a library to load various 3d file formats into a shared, in-memory format. It supports more than __40 file formats__ for import and a growing selection of file formats for export.
And we also have an IRC-channel at freenode: #assetimporterlib . You can easily join us via: [KiwiIRC/freenote](https://kiwiirc.com/client/irc.freenode.net), choose your nickname and type And we also have an IRC-channel at freenode: #assetimporterlib . You can easily join us via: [KiwiIRC/freenote](https://kiwiirc.com/client/irc.freenode.net), choose your nickname and type
> /join #assetimporterlib > /join #assetimporterlib
@ -120,6 +124,10 @@ And we also have an IRC-channel at freenode: #assetimporterlib . You can easily
Contributions to assimp are highly appreciated. The easiest way to get involved is to submit Contributions to assimp are highly appreciated. The easiest way to get involved is to submit
a pull request with your changes against the main repository's `master` branch. a pull request with your changes against the main repository's `master` branch.
### Donate ###
If you like assimp, consider buying us a beer (or two):
[Donate](http://sourceforge.net/donate/index.php?group_id=226462)
### License ### ### License ###
Our license is based on the modified, __3-clause BSD__-License. Our license is based on the modified, __3-clause BSD__-License.

View File

@ -18,7 +18,7 @@ configuration:
- 14 2015 - 14 2015
- 12 2013 - 12 2013
#- MinGW #- MinGW
- 10 2010 # only works for x86 #- 10 2010 # only works for x86
init: init:
- if "%platform%" EQU "x64" ( for %%a in (2008 2010 MinGW) do ( if "%Configuration%"=="%%a" (echo "Skipping unsupported configuration" && exit /b 1 ) ) ) - if "%platform%" EQU "x64" ( for %%a in (2008 2010 MinGW) do ( if "%Configuration%"=="%%a" (echo "Skipping unsupported configuration" && exit /b 1 ) ) )

View File

@ -64,7 +64,7 @@ set( ASSIMP_LIBRARIES ${ASSIMP_LIBRARIES}@CMAKE_DEBUG_POSTFIX@)
# the boost version assimp was compiled with # the boost version assimp was compiled with
set( ASSIMP_Boost_VERSION "@Boost_MAJOR_VERSION@.@Boost_MINOR_VERSION@") set( ASSIMP_Boost_VERSION "@Boost_MAJOR_VERSION@.@Boost_MINOR_VERSION@")
# for compatibility wiht pkg-config # for compatibility with pkg-config
set(ASSIMP_CFLAGS_OTHER "${ASSIMP_CXX_FLAGS}") set(ASSIMP_CFLAGS_OTHER "${ASSIMP_CXX_FLAGS}")
set(ASSIMP_LDFLAGS_OTHER "${ASSIMP_LINK_FLAGS}") set(ASSIMP_LDFLAGS_OTHER "${ASSIMP_LINK_FLAGS}")

View File

@ -1,5 +1,5 @@
prefix=@CMAKE_INSTALL_PREFIX@ prefix=@CMAKE_INSTALL_PREFIX@
exec_prefix=@CMAKE_INSTALL_PREFIX@/@ASSIMP_BIN_INSTALL_DIR@ exec_prefix=@CMAKE_INSTALL_PREFIX@/
libdir=@CMAKE_INSTALL_PREFIX@/@ASSIMP_LIB_INSTALL_DIR@ libdir=@CMAKE_INSTALL_PREFIX@/@ASSIMP_LIB_INSTALL_DIR@
includedir=@CMAKE_INSTALL_PREFIX@/@ASSIMP_INCLUDE_INSTALL_DIR@/assimp includedir=@CMAKE_INSTALL_PREFIX@/@ASSIMP_INCLUDE_INSTALL_DIR@/assimp

View File

@ -47,10 +47,10 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// internal headers // internal headers
#include "3DSLoader.h" #include "3DSLoader.h"
#include "TargetAnimation.h" #include "TargetAnimation.h"
#include "../include/assimp/scene.h" #include <assimp/scene.h>
#include "../include/assimp/DefaultLogger.hpp" #include <assimp/DefaultLogger.hpp>
#include "StringComparison.h" #include "StringComparison.h"
#include <boost/scoped_array.hpp> #include <memory>
#include <cctype> #include <cctype>
using namespace Assimp; using namespace Assimp;
@ -197,7 +197,7 @@ void CopyTexture(aiMaterial& mat, D3DS::Texture& texture, aiTextureType type)
// Setup the texture blend factor // Setup the texture blend factor
if (is_not_qnan(texture.mTextureBlend)) if (is_not_qnan(texture.mTextureBlend))
mat.AddProperty<float>( &texture.mTextureBlend, 1, AI_MATKEY_TEXBLEND(type,0)); mat.AddProperty<ai_real>( &texture.mTextureBlend, 1, AI_MATKEY_TEXBLEND(type,0));
// Setup the texture mapping mode // Setup the texture mapping mode
mat.AddProperty<int>((int*)&texture.mMapMode,1,AI_MATKEY_MAPPINGMODE_U(type,0)); mat.AddProperty<int>((int*)&texture.mMapMode,1,AI_MATKEY_MAPPINGMODE_U(type,0));
@ -207,14 +207,14 @@ void CopyTexture(aiMaterial& mat, D3DS::Texture& texture, aiTextureType type)
// FIXME: this is not really correct ... // FIXME: this is not really correct ...
if (texture.mMapMode == aiTextureMapMode_Mirror) if (texture.mMapMode == aiTextureMapMode_Mirror)
{ {
texture.mScaleU *= 2.f; texture.mScaleU *= 2.0;
texture.mScaleV *= 2.f; texture.mScaleV *= 2.0;
texture.mOffsetU /= 2.f; texture.mOffsetU /= 2.0;
texture.mOffsetV /= 2.f; texture.mOffsetV /= 2.0;
} }
// Setup texture UV transformations // Setup texture UV transformations
mat.AddProperty<float>(&texture.mOffsetU,5,AI_MATKEY_UVTRANSFORM(type,0)); mat.AddProperty<ai_real>(&texture.mOffsetU,5,AI_MATKEY_UVTRANSFORM(type,0));
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
@ -265,10 +265,10 @@ void Discreet3DSImporter::ConvertMaterial(D3DS::Material& oldMat,
} }
// Opacity // Opacity
mat.AddProperty<float>( &oldMat.mTransparency,1,AI_MATKEY_OPACITY); mat.AddProperty<ai_real>( &oldMat.mTransparency,1,AI_MATKEY_OPACITY);
// Bump height scaling // Bump height scaling
mat.AddProperty<float>( &oldMat.mBumpHeight,1,AI_MATKEY_BUMPSCALING); mat.AddProperty<ai_real>( &oldMat.mBumpHeight,1,AI_MATKEY_BUMPSCALING);
// Two sided rendering? // Two sided rendering?
if (oldMat.mTwoSided) if (oldMat.mTwoSided)
@ -359,7 +359,7 @@ void Discreet3DSImporter::ConvertMeshes(aiScene* pcOut)
// we need to split all meshes by their materials // we need to split all meshes by their materials
for (std::vector<D3DS::Mesh>::iterator i = mScene->mMeshes.begin(); i != mScene->mMeshes.end();++i) { for (std::vector<D3DS::Mesh>::iterator i = mScene->mMeshes.begin(); i != mScene->mMeshes.end();++i) {
boost::scoped_array< std::vector<unsigned int> > aiSplit(new std::vector<unsigned int>[mScene->mMaterials.size()]); std::unique_ptr< std::vector<unsigned int>[] > aiSplit(new std::vector<unsigned int>[mScene->mMaterials.size()]);
name.length = ASSIMP_itoa10(name.data,num++); name.length = ASSIMP_itoa10(name.data,num++);

View File

@ -47,9 +47,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "SceneCombiner.h" #include "SceneCombiner.h"
#include "SplitLargeMeshes.h" #include "SplitLargeMeshes.h"
#include "StringComparison.h" #include "StringComparison.h"
#include "../include/assimp/IOSystem.hpp" #include <assimp/IOSystem.hpp>
#include "../include/assimp/DefaultLogger.hpp" #include <assimp/DefaultLogger.hpp>
#include "../include/assimp/Exporter.hpp" #include <assimp/Exporter.hpp>
#include <memory> #include <memory>
using namespace Assimp; using namespace Assimp;
@ -150,7 +150,7 @@ namespace {
// Worker function for exporting a scene to 3DS. Prototyped and registered in Exporter.cpp // Worker function for exporting a scene to 3DS. Prototyped and registered in Exporter.cpp
void ExportScene3DS(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* pProperties) void ExportScene3DS(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* pProperties)
{ {
boost::shared_ptr<IOStream> outfile (pIOSystem->Open(pFile, "wb")); std::shared_ptr<IOStream> outfile (pIOSystem->Open(pFile, "wb"));
if(!outfile) { if(!outfile) {
throw DeadlyExportError("Could not open output .3ds file: " + std::string(pFile)); throw DeadlyExportError("Could not open output .3ds file: " + std::string(pFile));
} }
@ -164,7 +164,7 @@ void ExportScene3DS(const char* pFile, IOSystem* pIOSystem, const aiScene* pScen
// in |Exporter::ExportFormatEntry|. // in |Exporter::ExportFormatEntry|.
aiScene* scenecopy_tmp; aiScene* scenecopy_tmp;
SceneCombiner::CopyScene(&scenecopy_tmp,pScene); SceneCombiner::CopyScene(&scenecopy_tmp,pScene);
std::auto_ptr<aiScene> scenecopy(scenecopy_tmp); std::unique_ptr<aiScene> scenecopy(scenecopy_tmp);
SplitLargeMeshesProcess_Triangle tri_splitter; SplitLargeMeshesProcess_Triangle tri_splitter;
tri_splitter.SetLimit(0xffff); tri_splitter.SetLimit(0xffff);
@ -181,7 +181,7 @@ void ExportScene3DS(const char* pFile, IOSystem* pIOSystem, const aiScene* pScen
} // end of namespace Assimp } // end of namespace Assimp
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
Discreet3DSExporter:: Discreet3DSExporter(boost::shared_ptr<IOStream> outfile, const aiScene* scene) Discreet3DSExporter:: Discreet3DSExporter(std::shared_ptr<IOStream> outfile, const aiScene* scene)
: scene(scene) : scene(scene)
, writer(outfile) , writer(outfile)
{ {

View File

@ -45,7 +45,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define AI_3DSEXPORTER_H_INC #define AI_3DSEXPORTER_H_INC
#include <map> #include <map>
#include <boost/shared_ptr.hpp> #include <memory>
#include "StreamWriter.h" #include "StreamWriter.h"
#include "./../include/assimp/material.h" #include "./../include/assimp/material.h"
@ -64,7 +64,7 @@ namespace Assimp
class Discreet3DSExporter class Discreet3DSExporter
{ {
public: public:
Discreet3DSExporter(boost::shared_ptr<IOStream> outfile, const aiScene* pScene); Discreet3DSExporter(std::shared_ptr<IOStream> outfile, const aiScene* pScene);
private: private:

View File

@ -327,11 +327,11 @@ struct Texture
{ {
//! Default constructor //! Default constructor
Texture() Texture()
: mOffsetU (0.0f) : mOffsetU (0.0)
, mOffsetV (0.0f) , mOffsetV (0.0)
, mScaleU (1.0f) , mScaleU (1.0)
, mScaleV (1.0f) , mScaleV (1.0)
, mRotation (0.0f) , mRotation (0.0)
, mMapMode (aiTextureMapMode_Wrap) , mMapMode (aiTextureMapMode_Wrap)
, bPrivate() , bPrivate()
, iUVSrc (0) , iUVSrc (0)
@ -340,17 +340,17 @@ struct Texture
} }
//! Specifies the blend factor for the texture //! Specifies the blend factor for the texture
float mTextureBlend; ai_real mTextureBlend;
//! Specifies the filename of the texture //! Specifies the filename of the texture
std::string mMapName; std::string mMapName;
//! Specifies texture coordinate offsets/scaling/rotations //! Specifies texture coordinate offsets/scaling/rotations
float mOffsetU; ai_real mOffsetU;
float mOffsetV; ai_real mOffsetV;
float mScaleU; ai_real mScaleU;
float mScaleV; ai_real mScaleV;
float mRotation; ai_real mRotation;
//! Specifies the mapping mode to be used for the texture //! Specifies the mapping mode to be used for the texture
aiTextureMapMode mMapMode; aiTextureMapMode mMapMode;
@ -369,12 +369,12 @@ struct Material
//! Default constructor. Builds a default name for the material //! Default constructor. Builds a default name for the material
Material() Material()
: :
mDiffuse (0.6f,0.6f,0.6f), // FIX ... we won't want object to be black mDiffuse (0.6,0.6,0.6), // FIX ... we won't want object to be black
mSpecularExponent (0.0f), mSpecularExponent (0.0),
mShininessStrength (1.0f), mShininessStrength (1.0),
mShading(Discreet3DS::Gouraud), mShading(Discreet3DS::Gouraud),
mTransparency (1.0f), mTransparency (1.0),
mBumpHeight (1.0f), mBumpHeight (1.0),
mTwoSided (false) mTwoSided (false)
{ {
static int iCnt = 0; static int iCnt = 0;
@ -389,9 +389,9 @@ struct Material
//! Diffuse color of the material //! Diffuse color of the material
aiColor3D mDiffuse; aiColor3D mDiffuse;
//! Specular exponent //! Specular exponent
float mSpecularExponent; ai_real mSpecularExponent;
//! Shininess strength, in percent //! Shininess strength, in percent
float mShininessStrength; ai_real mShininessStrength;
//! Specular color of the material //! Specular color of the material
aiColor3D mSpecular; aiColor3D mSpecular;
//! Ambient color of the material //! Ambient color of the material
@ -399,7 +399,7 @@ struct Material
//! Shading type to be used //! Shading type to be used
Discreet3DS::shadetype3ds mShading; Discreet3DS::shadetype3ds mShading;
//! Opacity of the material //! Opacity of the material
float mTransparency; ai_real mTransparency;
//! Diffuse texture channel //! Diffuse texture channel
Texture sTexDiffuse; Texture sTexDiffuse;
//! Opacity texture channel //! Opacity texture channel
@ -415,7 +415,7 @@ struct Material
//! Shininess texture channel //! Shininess texture channel
Texture sTexShininess; Texture sTexShininess;
//! Scaling factor for the bump values //! Scaling factor for the bump values
float mBumpHeight; ai_real mBumpHeight;
//! Emissive color //! Emissive color
aiColor3D mEmissive; aiColor3D mEmissive;
//! Ambient texture channel //! Ambient texture channel
@ -459,7 +459,7 @@ struct Mesh : public MeshWithSmoothingGroups<D3DS::Face>
struct aiFloatKey struct aiFloatKey
{ {
double mTime; ///< The time of this key double mTime; ///< The time of this key
float mValue; ///< The value of this key ai_real mValue; ///< The value of this key
#ifdef __cplusplus #ifdef __cplusplus

View File

@ -51,9 +51,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// internal headers // internal headers
#include "3DSLoader.h" #include "3DSLoader.h"
#include "Macros.h" #include "Macros.h"
#include "../include/assimp/IOSystem.hpp" #include <assimp/IOSystem.hpp>
#include "../include/assimp/scene.h" #include <assimp/scene.h>
#include "../include/assimp/DefaultLogger.hpp" #include <assimp/DefaultLogger.hpp>
#include "StringComparison.h" #include "StringComparison.h"
using namespace Assimp; using namespace Assimp;
@ -186,18 +186,17 @@ void Discreet3DSImporter::InternReadFile( const std::string& pFile,
// internal verbose representation. Finally compute normal // internal verbose representation. Finally compute normal
// vectors from the smoothing groups we read from the // vectors from the smoothing groups we read from the
// file. // file.
for (std::vector<D3DS::Mesh>::iterator i = mScene->mMeshes.begin(), for (auto &mesh : mScene->mMeshes) {
end = mScene->mMeshes.end(); i != end;++i) { if (mesh.mFaces.size() > 0 && mesh.mPositions.size() == 0) {
if ((*i).mFaces.size() > 0 && (*i).mPositions.size() == 0) {
delete mScene; delete mScene;
throw DeadlyImportError("3DS file contains faces but no vertices: " + pFile); throw DeadlyImportError("3DS file contains faces but no vertices: " + pFile);
} }
CheckIndices(*i); CheckIndices(mesh);
MakeUnique (*i); MakeUnique (mesh);
ComputeNormalsWithSmoothingsGroups<D3DS::Face>(*i); ComputeNormalsWithSmoothingsGroups<D3DS::Face>(mesh);
} }
// Replace all occurences of the default material with a // Replace all occurrences of the default material with a
// valid material. Generate it if no material containing // valid material. Generate it if no material containing
// DEFAULT in its name has been found in the file // DEFAULT in its name has been found in the file
ReplaceDefaultMaterial(); ReplaceDefaultMaterial();
@ -459,20 +458,20 @@ void Discreet3DSImporter::ParseChunk(const char* name, unsigned int num)
camera->mLookAt.x = stream->GetF4() - camera->mPosition.x; camera->mLookAt.x = stream->GetF4() - camera->mPosition.x;
camera->mLookAt.y = stream->GetF4() - camera->mPosition.y; camera->mLookAt.y = stream->GetF4() - camera->mPosition.y;
camera->mLookAt.z = stream->GetF4() - camera->mPosition.z; camera->mLookAt.z = stream->GetF4() - camera->mPosition.z;
float len = camera->mLookAt.Length(); ai_real len = camera->mLookAt.Length();
if (len < 1e-5f) { if (len < 1e-5) {
// There are some files with lookat == position. Don't know why or whether it's ok or not. // There are some files with lookat == position. Don't know why or whether it's ok or not.
DefaultLogger::get()->error("3DS: Unable to read proper camera look-at vector"); DefaultLogger::get()->error("3DS: Unable to read proper camera look-at vector");
camera->mLookAt = aiVector3D(0.f,1.f,0.f); camera->mLookAt = aiVector3D(0.0,1.0,0.0);
} }
else camera->mLookAt /= len; else camera->mLookAt /= len;
// And finally - the camera rotation angle, in counter clockwise direction // And finally - the camera rotation angle, in counter clockwise direction
const float angle = AI_DEG_TO_RAD( stream->GetF4() ); const ai_real angle = AI_DEG_TO_RAD( stream->GetF4() );
aiQuaternion quat(camera->mLookAt,angle); aiQuaternion quat(camera->mLookAt,angle);
camera->mUp = quat.GetMatrix() * aiVector3D(0.f,1.f,0.f); camera->mUp = quat.GetMatrix() * aiVector3D(0.0,1.0,0.0);
// Read the lense angle // Read the lense angle
camera->mHorizontalFOV = AI_DEG_TO_RAD ( stream->GetF4() ); camera->mHorizontalFOV = AI_DEG_TO_RAD ( stream->GetF4() );
@ -1168,13 +1167,13 @@ void Discreet3DSImporter::ParseMaterialChunk()
case Discreet3DS::CHUNK_MAT_TRANSPARENCY: case Discreet3DS::CHUNK_MAT_TRANSPARENCY:
{ {
// This is the material's transparency // This is the material's transparency
float* pcf = &mScene->mMaterials.back().mTransparency; ai_real* pcf = &mScene->mMaterials.back().mTransparency;
*pcf = ParsePercentageChunk(); *pcf = ParsePercentageChunk();
// NOTE: transparency, not opacity // NOTE: transparency, not opacity
if (is_qnan(*pcf)) if (is_qnan(*pcf))
*pcf = 1.0f; *pcf = 1.0;
else *pcf = 1.0f - *pcf * (float)0xFFFF / 100.0f; else *pcf = 1.0 - *pcf * (ai_real)0xFFFF / 100.0;
} }
break; break;
@ -1190,30 +1189,30 @@ void Discreet3DSImporter::ParseMaterialChunk()
case Discreet3DS::CHUNK_MAT_SHININESS: case Discreet3DS::CHUNK_MAT_SHININESS:
{ // This is the shininess of the material { // This is the shininess of the material
float* pcf = &mScene->mMaterials.back().mSpecularExponent; ai_real* pcf = &mScene->mMaterials.back().mSpecularExponent;
*pcf = ParsePercentageChunk(); *pcf = ParsePercentageChunk();
if (is_qnan(*pcf)) if (is_qnan(*pcf))
*pcf = 0.0f; *pcf = 0.0;
else *pcf *= (float)0xFFFF; else *pcf *= (ai_real)0xFFFF;
} }
break; break;
case Discreet3DS::CHUNK_MAT_SHININESS_PERCENT: case Discreet3DS::CHUNK_MAT_SHININESS_PERCENT:
{ // This is the shininess strength of the material { // This is the shininess strength of the material
float* pcf = &mScene->mMaterials.back().mShininessStrength; ai_real* pcf = &mScene->mMaterials.back().mShininessStrength;
*pcf = ParsePercentageChunk(); *pcf = ParsePercentageChunk();
if (is_qnan(*pcf)) if (is_qnan(*pcf))
*pcf = 0.0f; *pcf = 0.0;
else *pcf *= (float)0xffff / 100.0f; else *pcf *= (ai_real)0xffff / 100.0;
} }
break; break;
case Discreet3DS::CHUNK_MAT_SELF_ILPCT: case Discreet3DS::CHUNK_MAT_SELF_ILPCT:
{ // This is the self illumination strength of the material { // This is the self illumination strength of the material
float f = ParsePercentageChunk(); ai_real f = ParsePercentageChunk();
if (is_qnan(f)) if (is_qnan(f))
f = 0.0f; f = 0.0;
else f *= (float)0xFFFF / 100.0f; else f *= (ai_real)0xFFFF / 100.0;
mScene->mMaterials.back().mEmissive = aiColor3D(f,f,f); mScene->mMaterials.back().mEmissive = aiColor3D(f,f,f);
} }
break; break;
@ -1278,7 +1277,7 @@ void Discreet3DSImporter::ParseTextureChunk(D3DS::Texture* pcOut)
case Discreet3DS::CHUNK_PERCENTW: case Discreet3DS::CHUNK_PERCENTW:
// Manually parse the blend factor // Manually parse the blend factor
pcOut->mTextureBlend = (float)((uint16_t)stream->GetI2()) / 100.0f; pcOut->mTextureBlend = (ai_real)((uint16_t)stream->GetI2()) / 100.0;
break; break;
case Discreet3DS::CHUNK_MAT_MAP_USCALE: case Discreet3DS::CHUNK_MAT_MAP_USCALE:
@ -1337,7 +1336,7 @@ void Discreet3DSImporter::ParseTextureChunk(D3DS::Texture* pcOut)
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// Read a percentage chunk // Read a percentage chunk
float Discreet3DSImporter::ParsePercentageChunk() ai_real Discreet3DSImporter::ParsePercentageChunk()
{ {
Discreet3DS::Chunk chunk; Discreet3DS::Chunk chunk;
ReadChunk(&chunk); ReadChunk(&chunk);
@ -1345,7 +1344,7 @@ float Discreet3DSImporter::ParsePercentageChunk()
if (Discreet3DS::CHUNK_PERCENTF == chunk.Flag) if (Discreet3DS::CHUNK_PERCENTF == chunk.Flag)
return stream->GetF4(); return stream->GetF4();
else if (Discreet3DS::CHUNK_PERCENTW == chunk.Flag) else if (Discreet3DS::CHUNK_PERCENTW == chunk.Flag)
return (float)((uint16_t)stream->GetI2()) / (float)0xFFFF; return (ai_real)((uint16_t)stream->GetI2()) / (ai_real)0xFFFF;
return get_qnan(); return get_qnan();
} }
@ -1357,7 +1356,7 @@ void Discreet3DSImporter::ParseColorChunk(aiColor3D* out,
ai_assert(out != NULL); ai_assert(out != NULL);
// error return value // error return value
const float qnan = get_qnan(); const ai_real qnan = get_qnan();
static const aiColor3D clrError = aiColor3D(qnan,qnan,qnan); static const aiColor3D clrError = aiColor3D(qnan,qnan,qnan);
Discreet3DS::Chunk chunk; Discreet3DS::Chunk chunk;
@ -1373,7 +1372,7 @@ void Discreet3DSImporter::ParseColorChunk(aiColor3D* out,
bGamma = true; bGamma = true;
case Discreet3DS::CHUNK_RGBF: case Discreet3DS::CHUNK_RGBF:
if (sizeof(float) * 3 > diff) { if (sizeof(ai_real) * 3 > diff) {
*out = clrError; *out = clrError;
return; return;
} }
@ -1389,9 +1388,9 @@ void Discreet3DSImporter::ParseColorChunk(aiColor3D* out,
*out = clrError; *out = clrError;
return; return;
} }
out->r = (float)(uint8_t)stream->GetI1() / 255.0f; out->r = (ai_real)(uint8_t)stream->GetI1() / 255.0;
out->g = (float)(uint8_t)stream->GetI1() / 255.0f; out->g = (ai_real)(uint8_t)stream->GetI1() / 255.0;
out->b = (float)(uint8_t)stream->GetI1() / 255.0f; out->b = (ai_real)(uint8_t)stream->GetI1() / 255.0;
break; break;
// Percentage chunks are accepted, too. // Percentage chunks are accepted, too.
@ -1405,7 +1404,7 @@ void Discreet3DSImporter::ParseColorChunk(aiColor3D* out,
case Discreet3DS::CHUNK_PERCENTW: case Discreet3DS::CHUNK_PERCENTW:
if (acceptPercent && 1 <= diff) { if (acceptPercent && 1 <= diff) {
out->g = out->b = out->r = (float)(uint8_t)stream->GetI1() / 255.0f; out->g = out->b = out->r = (ai_real)(uint8_t)stream->GetI1() / 255.0;
break; break;
} }
*out = clrError; *out = clrError;

View File

@ -46,7 +46,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define AI_3DSIMPORTER_H_INC #define AI_3DSIMPORTER_H_INC
#include "BaseImporter.h" #include "BaseImporter.h"
#include "../include/assimp/types.h" #include <assimp/types.h>
#ifndef ASSIMP_BUILD_NO_3DS_IMPORTER #ifndef ASSIMP_BUILD_NO_3DS_IMPORTER
@ -119,7 +119,7 @@ protected:
* chunk behind afterwards. If no percentage chunk is found * chunk behind afterwards. If no percentage chunk is found
* QNAN is returned. * QNAN is returned.
*/ */
float ParsePercentageChunk(); ai_real ParsePercentageChunk();
// ------------------------------------------------------------------- // -------------------------------------------------------------------
/** Parse a color chunk. mCurrent will point to the next /** Parse a color chunk. mCurrent will point to the next
@ -265,7 +265,7 @@ protected:
aiColor3D mClrAmbient; aiColor3D mClrAmbient;
/** Master scaling factor of the scene */ /** Master scaling factor of the scene */
float mMasterScale; ai_real mMasterScale;
/** Path to the background image of the scene */ /** Path to the background image of the scene */
std::string mBackgroundImage; std::string mBackgroundImage;

View File

@ -53,14 +53,14 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "Subdivision.h" #include "Subdivision.h"
#include "Importer.h" #include "Importer.h"
#include "BaseImporter.h" #include "BaseImporter.h"
#include "../include/assimp/Importer.hpp" #include <assimp/Importer.hpp>
#include "../include/assimp/light.h" #include <assimp/light.h>
#include "../include/assimp/DefaultLogger.hpp" #include <assimp/DefaultLogger.hpp>
#include "../include/assimp/material.h" #include <assimp/material.h>
#include "../include/assimp/scene.h" #include <assimp/scene.h>
#include "../include/assimp/config.h" #include <assimp/config.h>
#include "../include/assimp/IOSystem.hpp" #include <assimp/IOSystem.hpp>
#include <boost/scoped_ptr.hpp> #include <memory>
using namespace Assimp; using namespace Assimp;
@ -708,7 +708,7 @@ aiNode* AC3DImporter::ConvertObjectSection(Object& object,
// collect all meshes using the same material group. // collect all meshes using the same material group.
if (object.subDiv) { if (object.subDiv) {
if (configEvalSubdivision) { if (configEvalSubdivision) {
boost::scoped_ptr<Subdivider> div(Subdivider::Create(Subdivider::CATMULL_CLARKE)); std::unique_ptr<Subdivider> div(Subdivider::Create(Subdivider::CATMULL_CLARKE));
DefaultLogger::get()->info("AC3D: Evaluating subdivision surface: "+object.name); DefaultLogger::get()->info("AC3D: Evaluating subdivision surface: "+object.name);
std::vector<aiMesh*> cpy(meshes.size()-oldm,NULL); std::vector<aiMesh*> cpy(meshes.size()-oldm,NULL);
@ -787,7 +787,7 @@ void AC3DImporter::SetupProperties(const Importer* pImp)
void AC3DImporter::InternReadFile( const std::string& pFile, void AC3DImporter::InternReadFile( const std::string& pFile,
aiScene* pScene, IOSystem* pIOHandler) aiScene* pScene, IOSystem* pIOHandler)
{ {
boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb")); std::unique_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
// Check whether we can read from the file // Check whether we can read from the file
if( file.get() == NULL) if( file.get() == NULL)
@ -884,7 +884,7 @@ void AC3DImporter::InternReadFile( const std::string& pFile,
// copy meshes // copy meshes
if (meshes.empty()) if (meshes.empty())
{ {
throw DeadlyImportError("An unknown error occured during converting"); throw DeadlyImportError("An unknown error occurred during converting");
} }
pScene->mNumMeshes = (unsigned int)meshes.size(); pScene->mNumMeshes = (unsigned int)meshes.size();
pScene->mMeshes = new aiMesh*[pScene->mNumMeshes]; pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];

View File

@ -47,7 +47,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <vector> #include <vector>
#include "BaseImporter.h" #include "BaseImporter.h"
#include "../include/assimp/types.h" #include <assimp/types.h>
struct aiNode; struct aiNode;
struct aiMesh; struct aiMesh;

View File

@ -50,12 +50,12 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "StringComparison.h" #include "StringComparison.h"
#include "SkeletonMeshBuilder.h" #include "SkeletonMeshBuilder.h"
#include "TargetAnimation.h" #include "TargetAnimation.h"
#include "../include/assimp/Importer.hpp" #include <assimp/Importer.hpp>
#include <boost/scoped_ptr.hpp> #include <assimp/IOSystem.hpp>
#include "../include/assimp/IOSystem.hpp" #include <assimp/DefaultLogger.hpp>
#include "../include/assimp/DefaultLogger.hpp" #include <assimp/scene.h>
#include "../include/assimp/scene.h"
#include <memory>
// utilities // utilities
#include "fast_atof.h" #include "fast_atof.h"
@ -130,7 +130,7 @@ void ASEImporter::SetupProperties(const Importer* pImp)
void ASEImporter::InternReadFile( const std::string& pFile, void ASEImporter::InternReadFile( const std::string& pFile,
aiScene* pScene, IOSystem* pIOHandler) aiScene* pScene, IOSystem* pIOHandler)
{ {
boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb")); std::unique_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
// Check whether we can read from the file // Check whether we can read from the file
if( file.get() == NULL) { if( file.get() == NULL) {
@ -225,17 +225,13 @@ void ASEImporter::InternReadFile( const std::string& pFile,
+ mParser->m_vCameras.size() + mParser->m_vDummies.size()); + mParser->m_vCameras.size() + mParser->m_vDummies.size());
// Lights // Lights
for (std::vector<ASE::Light>::iterator it = mParser->m_vLights.begin(), for (auto &light : mParser->m_vLights)nodes.push_back(&light);
end = mParser->m_vLights.end();it != end; ++it)nodes.push_back(&(*it));
// Cameras // Cameras
for (std::vector<ASE::Camera>::iterator it = mParser->m_vCameras.begin(), for (auto &camera : mParser->m_vCameras)nodes.push_back(&camera);
end = mParser->m_vCameras.end();it != end; ++it)nodes.push_back(&(*it));
// Meshes // Meshes
for (std::vector<ASE::Mesh>::iterator it = mParser->m_vMeshes.begin(), for (auto &mesh : mParser->m_vMeshes)nodes.push_back(&mesh);
end = mParser->m_vMeshes.end();it != end; ++it)nodes.push_back(&(*it));
// Dummies // Dummies
for (std::vector<ASE::Dummy>::iterator it = mParser->m_vDummies.begin(), for (auto &dummy : mParser->m_vDummies)nodes.push_back(&dummy);
end = mParser->m_vDummies.end();it != end; ++it)nodes.push_back(&(*it));
// build the final node graph // build the final node graph
BuildNodes(nodes); BuildNodes(nodes);
@ -657,8 +653,8 @@ void ASEImporter::BuildNodes(std::vector<BaseNode*>& nodes) {
ch->mParent = root; ch->mParent = root;
// Change the transformation matrix of all nodes // Change the transformation matrix of all nodes
for (std::vector<BaseNode*>::iterator it = nodes.begin(), end = nodes.end();it != end; ++it) { for (BaseNode *node : nodes) {
aiMatrix4x4& m = (*it)->mTransform; aiMatrix4x4& m = node->mTransform;
m.Transpose(); // row-order vs column-order m.Transpose(); // row-order vs column-order
} }
@ -823,10 +819,10 @@ void CopyASETexture(aiMaterial& mat, ASE::Texture& texture, aiTextureType type)
// Setup the texture blend factor // Setup the texture blend factor
if (is_not_qnan(texture.mTextureBlend)) if (is_not_qnan(texture.mTextureBlend))
mat.AddProperty<float>( &texture.mTextureBlend, 1, AI_MATKEY_TEXBLEND(type,0)); mat.AddProperty<ai_real>( &texture.mTextureBlend, 1, AI_MATKEY_TEXBLEND(type,0));
// Setup texture UV transformations // Setup texture UV transformations
mat.AddProperty<float>(&texture.mOffsetU,5,AI_MATKEY_UVTRANSFORM(type,0)); mat.AddProperty<ai_real>(&texture.mOffsetU,5,AI_MATKEY_UVTRANSFORM(type,0));
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
@ -869,7 +865,7 @@ void ASEImporter::ConvertMaterial(ASE::Material& mat)
} }
// opacity // opacity
mat.pcInstance->AddProperty<float>( &mat.mTransparency,1,AI_MATKEY_OPACITY); mat.pcInstance->AddProperty<ai_real>( &mat.mTransparency,1,AI_MATKEY_OPACITY);
// Two sided rendering? // Two sided rendering?
if (mat.mTwoSided) if (mat.mTwoSided)

View File

@ -45,7 +45,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define AI_ASELOADER_H_INCLUDED #define AI_ASELOADER_H_INCLUDED
#include "BaseImporter.h" #include "BaseImporter.h"
#include "../include/assimp/types.h" #include <assimp/types.h>
struct aiNode; struct aiNode;
#include "ASEParser.h" #include "ASEParser.h"

View File

@ -51,7 +51,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "ASELoader.h" #include "ASELoader.h"
#include "MaterialSystem.h" #include "MaterialSystem.h"
#include "fast_atof.h" #include "fast_atof.h"
#include "../include/assimp/DefaultLogger.hpp" #include <assimp/DefaultLogger.hpp>
using namespace Assimp; using namespace Assimp;
using namespace Assimp::ASE; using namespace Assimp::ASE;
@ -431,7 +431,7 @@ void Parser::ParseLV1SoftSkinBlock()
ParseString(bone,"*MESH_SOFTSKINVERTS.Bone"); ParseString(bone,"*MESH_SOFTSKINVERTS.Bone");
// Find the bone in the mesh's list // Find the bone in the mesh's list
std::pair<int,float> me; std::pair<int,ai_real> me;
me.first = -1; me.first = -1;
for (unsigned int n = 0; n < curMesh->mBones.size();++n) for (unsigned int n = 0; n < curMesh->mBones.size();++n)
@ -618,12 +618,12 @@ void Parser::ParseLV2MaterialBlock(ASE::Material& mat)
if (TokenMatch(filePtr,"MATERIAL_TRANSPARENCY",21)) if (TokenMatch(filePtr,"MATERIAL_TRANSPARENCY",21))
{ {
ParseLV4MeshFloat(mat.mTransparency); ParseLV4MeshFloat(mat.mTransparency);
mat.mTransparency = 1.0f - mat.mTransparency;continue; mat.mTransparency = 1.0 - mat.mTransparency;continue;
} }
// material self illumination // material self illumination
if (TokenMatch(filePtr,"MATERIAL_SELFILLUM",18)) if (TokenMatch(filePtr,"MATERIAL_SELFILLUM",18))
{ {
float f = 0.0f; ai_real f = 0.0;
ParseLV4MeshFloat(f); ParseLV4MeshFloat(f);
mat.mEmissive.r = f; mat.mEmissive.r = f;
@ -1251,7 +1251,7 @@ void Parser::ParseLV3RotAnimationBlock(ASE::Animation& anim)
{ {
anim.akeyRotations.push_back(aiQuatKey()); anim.akeyRotations.push_back(aiQuatKey());
aiQuatKey& key = anim.akeyRotations.back(); aiQuatKey& key = anim.akeyRotations.back();
aiVector3D v;float f; aiVector3D v;ai_real f;
ParseLV4MeshFloatTriple(&v.x,iIndex); ParseLV4MeshFloatTriple(&v.x,iIndex);
ParseLV4MeshFloat(f); ParseLV4MeshFloat(f);
key.mTime = (double)iIndex; key.mTime = (double)iIndex;
@ -1604,7 +1604,7 @@ void Parser::ParseLV4MeshBonesVertices(unsigned int iNumVertices,ASE::Mesh& mesh
} }
// --- ignored // --- ignored
float afVert[3]; ai_real afVert[3];
ParseLV4MeshFloatTriple(afVert); ParseLV4MeshFloatTriple(afVert);
std::pair<int,float> pairOut; std::pair<int,float> pairOut;
@ -2102,7 +2102,7 @@ void Parser::ParseLV4MeshLongTriple(unsigned int* apOut, unsigned int& rIndexOut
ParseLV4MeshLongTriple(apOut); ParseLV4MeshLongTriple(apOut);
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
void Parser::ParseLV4MeshFloatTriple(float* apOut, unsigned int& rIndexOut) void Parser::ParseLV4MeshFloatTriple(ai_real* apOut, unsigned int& rIndexOut)
{ {
ai_assert(NULL != apOut); ai_assert(NULL != apOut);
@ -2113,7 +2113,7 @@ void Parser::ParseLV4MeshFloatTriple(float* apOut, unsigned int& rIndexOut)
ParseLV4MeshFloatTriple(apOut); ParseLV4MeshFloatTriple(apOut);
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
void Parser::ParseLV4MeshFloatTriple(float* apOut) void Parser::ParseLV4MeshFloatTriple(ai_real* apOut)
{ {
ai_assert(NULL != apOut); ai_assert(NULL != apOut);
@ -2121,19 +2121,19 @@ void Parser::ParseLV4MeshFloatTriple(float* apOut)
ParseLV4MeshFloat(apOut[i]); ParseLV4MeshFloat(apOut[i]);
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
void Parser::ParseLV4MeshFloat(float& fOut) void Parser::ParseLV4MeshFloat(ai_real& fOut)
{ {
// skip spaces and tabs // skip spaces and tabs
if(!SkipSpaces(&filePtr)) if(!SkipSpaces(&filePtr))
{ {
// LOG // LOG
LogWarning("Unable to parse float: unexpected EOL [#1]"); LogWarning("Unable to parse float: unexpected EOL [#1]");
fOut = 0.0f; fOut = 0.0;
++iLineNumber; ++iLineNumber;
return; return;
} }
// parse the first float // parse the first float
filePtr = fast_atoreal_move<float>(filePtr,fOut); filePtr = fast_atoreal_move<ai_real>(filePtr,fOut);
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
void Parser::ParseLV4MeshLong(unsigned int& iOut) void Parser::ParseLV4MeshLong(unsigned int& iOut)

View File

@ -43,15 +43,10 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef AI_ASEFILEHELPER_H_INC #ifndef AI_ASEFILEHELPER_H_INC
#define AI_ASEFILEHELPER_H_INC #define AI_ASEFILEHELPER_H_INC
// STL/CRT headers
#include <string>
#include <vector>
#include <list>
// public ASSIMP headers // public ASSIMP headers
#include "../include/assimp/types.h" #include <assimp/types.h>
#include "../include/assimp/mesh.h" #include <assimp/mesh.h>
#include "../include/assimp/anim.h" #include <assimp/anim.h>
// for some helper routines like IsSpace() // for some helper routines like IsSpace()
#include "ParsingUtils.h" #include "ParsingUtils.h"
@ -227,7 +222,7 @@ struct BaseNode
mName = szTemp; mName = szTemp;
// Set mTargetPosition to qnan // Set mTargetPosition to qnan
const float qnan = get_qnan(); const ai_real qnan = get_qnan();
mTargetPosition.x = qnan; mTargetPosition.x = qnan;
} }
@ -322,9 +317,9 @@ struct Light : public BaseNode
LightType mLightType; LightType mLightType;
aiColor3D mColor; aiColor3D mColor;
float mIntensity; ai_real mIntensity;
float mAngle; // in degrees ai_real mAngle; // in degrees
float mFalloff; ai_real mFalloff;
}; };
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@ -347,7 +342,7 @@ struct Camera : public BaseNode
{ {
} }
float mFOV, mNear, mFar; ai_real mFOV, mNear, mFar;
CameraType mCameraType; CameraType mCameraType;
}; };
@ -549,13 +544,13 @@ private:
//! (also works for MESH_TVERT, MESH_CFACE, MESH_VERTCOL ...) //! (also works for MESH_TVERT, MESH_CFACE, MESH_VERTCOL ...)
//! \param apOut Output buffer (3 floats) //! \param apOut Output buffer (3 floats)
//! \param rIndexOut Output index //! \param rIndexOut Output index
void ParseLV4MeshFloatTriple(float* apOut, unsigned int& rIndexOut); void ParseLV4MeshFloatTriple(ai_real* apOut, unsigned int& rIndexOut);
// ------------------------------------------------------------------- // -------------------------------------------------------------------
//! Parse a *MESH_VERT block in a file //! Parse a *MESH_VERT block in a file
//! (also works for MESH_TVERT, MESH_CFACE, MESH_VERTCOL ...) //! (also works for MESH_TVERT, MESH_CFACE, MESH_VERTCOL ...)
//! \param apOut Output buffer (3 floats) //! \param apOut Output buffer (3 floats)
void ParseLV4MeshFloatTriple(float* apOut); void ParseLV4MeshFloatTriple(ai_real* apOut);
// ------------------------------------------------------------------- // -------------------------------------------------------------------
//! Parse a *MESH_TFACE block in a file //! Parse a *MESH_TFACE block in a file
@ -573,7 +568,7 @@ private:
// ------------------------------------------------------------------- // -------------------------------------------------------------------
//! Parse a single float element //! Parse a single float element
//! \param fOut Output float //! \param fOut Output float
void ParseLV4MeshFloat(float& fOut); void ParseLV4MeshFloat(ai_real& fOut);
// ------------------------------------------------------------------- // -------------------------------------------------------------------
//! Parse a single int element //! Parse a single int element
@ -609,7 +604,7 @@ private:
//! \param out Output string //! \param out Output string
//! \param szName Name of the enclosing element -> used in error //! \param szName Name of the enclosing element -> used in error
//! messages. //! messages.
//! \return false if an error occured //! \return false if an error occurred
bool ParseString(std::string& out,const char* szName); bool ParseString(std::string& out,const char* szName);
public: public:

View File

@ -41,13 +41,12 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* ASSBIN exporter main code * ASSBIN exporter main code
*/ */
#include "assbin_chunks.h" #include "assbin_chunks.h"
#include "../include/assimp/version.h" #include <assimp/version.h>
#include "../include/assimp/IOStream.hpp" #include <assimp/IOStream.hpp>
#include "../include/assimp/IOSystem.hpp" #include <assimp/IOSystem.hpp>
#include "../include/assimp/Exporter.hpp" #include <assimp/Exporter.hpp>
#include "ProcessHelper.h" #include "ProcessHelper.h"
#include "Exceptional.h" #include "Exceptional.h"
#include <boost/static_assert.hpp>
#ifdef ASSIMP_BUILD_NO_OWN_ZLIB #ifdef ASSIMP_BUILD_NO_OWN_ZLIB
# include <zlib.h> # include <zlib.h>
@ -103,7 +102,7 @@ inline size_t Write<unsigned int>(IOStream * stream, const unsigned int& w)
template <> template <>
inline size_t Write<uint16_t>(IOStream * stream, const uint16_t& w) inline size_t Write<uint16_t>(IOStream * stream, const uint16_t& w)
{ {
BOOST_STATIC_ASSERT(sizeof(uint16_t)==2); static_assert(sizeof(uint16_t)==2, "sizeof(uint16_t)==2");
stream->Write(&w,2,1); stream->Write(&w,2,1);
return 2; return 2;
} }
@ -113,7 +112,7 @@ inline size_t Write<uint16_t>(IOStream * stream, const uint16_t& w)
template <> template <>
inline size_t Write<float>(IOStream * stream, const float& f) inline size_t Write<float>(IOStream * stream, const float& f)
{ {
BOOST_STATIC_ASSERT(sizeof(float)==4); static_assert(sizeof(float)==4, "sizeof(float)==4");
stream->Write(&f,4,1); stream->Write(&f,4,1);
return 4; return 4;
} }
@ -123,7 +122,7 @@ inline size_t Write<float>(IOStream * stream, const float& f)
template <> template <>
inline size_t Write<double>(IOStream * stream, const double& f) inline size_t Write<double>(IOStream * stream, const double& f)
{ {
BOOST_STATIC_ASSERT(sizeof(double)==8); static_assert(sizeof(double)==8, "sizeof(double)==8");
stream->Write(&f,8,1); stream->Write(&f,8,1);
return 8; return 8;
} }
@ -472,7 +471,7 @@ inline size_t WriteArray(IOStream * stream, const T* in, unsigned int size)
uint32_t tmp = f.mNumIndices; uint32_t tmp = f.mNumIndices;
hash = SuperFastHash(reinterpret_cast<const char*>(&tmp),sizeof tmp,hash); hash = SuperFastHash(reinterpret_cast<const char*>(&tmp),sizeof tmp,hash);
for (unsigned int i = 0; i < f.mNumIndices; ++i) { for (unsigned int i = 0; i < f.mNumIndices; ++i) {
BOOST_STATIC_ASSERT(AI_MAX_VERTICES <= 0xffffffff); static_assert(AI_MAX_VERTICES <= 0xffffffff, "AI_MAX_VERTICES <= 0xffffffff");
tmp = static_cast<uint32_t>( f.mIndices[i] ); tmp = static_cast<uint32_t>( f.mIndices[i] );
hash = SuperFastHash(reinterpret_cast<const char*>(&tmp),sizeof tmp,hash); hash = SuperFastHash(reinterpret_cast<const char*>(&tmp),sizeof tmp,hash);
} }
@ -486,7 +485,7 @@ inline size_t WriteArray(IOStream * stream, const T* in, unsigned int size)
for (unsigned int i = 0; i < mesh->mNumFaces;++i) { for (unsigned int i = 0; i < mesh->mNumFaces;++i) {
const aiFace& f = mesh->mFaces[i]; const aiFace& f = mesh->mFaces[i];
BOOST_STATIC_ASSERT(AI_MAX_FACE_INDICES <= 0xffff); static_assert(AI_MAX_FACE_INDICES <= 0xffff, "AI_MAX_FACE_INDICES <= 0xffff");
Write<uint16_t>(&chunk,f.mNumIndices); Write<uint16_t>(&chunk,f.mNumIndices);
for (unsigned int a = 0; a < f.mNumIndices;++a) { for (unsigned int a = 0; a < f.mNumIndices;++a) {

View File

@ -51,15 +51,14 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "AssbinLoader.h" #include "AssbinLoader.h"
#include "assbin_chunks.h" #include "assbin_chunks.h"
#include "MemoryIOWrapper.h" #include "MemoryIOWrapper.h"
#include "../include/assimp/mesh.h" #include <assimp/mesh.h>
#include "../include/assimp/anim.h" #include <assimp/anim.h>
#include "../include/assimp/scene.h" #include <assimp/scene.h>
#include <boost/static_assert.hpp>
#ifdef ASSIMP_BUILD_NO_OWN_ZLIB #ifdef ASSIMP_BUILD_NO_OWN_ZLIB
# include <zlib.h> # include <zlib.h>
#else #else
# include "../contrib/zlib/zlib.h" # include <contrib/zlib/zlib.h>
#endif #endif
using namespace Assimp; using namespace Assimp;
@ -351,7 +350,7 @@ void AssbinImporter::ReadBinaryMesh( IOStream * stream, aiMesh* mesh )
for (unsigned int i = 0; i < mesh->mNumFaces;++i) { for (unsigned int i = 0; i < mesh->mNumFaces;++i) {
aiFace& f = mesh->mFaces[i]; aiFace& f = mesh->mFaces[i];
BOOST_STATIC_ASSERT(AI_MAX_FACE_INDICES <= 0xffff); static_assert(AI_MAX_FACE_INDICES <= 0xffff, "AI_MAX_FACE_INDICES <= 0xffff");
f.mNumIndices = Read<uint16_t>(stream); f.mNumIndices = Read<uint16_t>(stream);
f.mIndices = new unsigned int[f.mNumIndices]; f.mIndices = new unsigned int[f.mNumIndices];

View File

@ -46,7 +46,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define AI_ASSBINIMPORTER_H_INC #define AI_ASSBINIMPORTER_H_INC
#include "BaseImporter.h" #include "BaseImporter.h"
#include "../include/assimp/types.h" #include <assimp/types.h>
struct aiMesh; struct aiMesh;
struct aiNode; struct aiNode;

View File

@ -59,8 +59,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
#ifndef ASSIMP_BUILD_SINGLETHREADED #ifndef ASSIMP_BUILD_SINGLETHREADED
# include <boost/thread/thread.hpp> # include <thread>
# include <boost/thread/mutex.hpp> # include <mutex>
#endif #endif
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
using namespace Assimp; using namespace Assimp;
@ -103,7 +103,7 @@ namespace Assimp
#ifndef ASSIMP_BUILD_SINGLETHREADED #ifndef ASSIMP_BUILD_SINGLETHREADED
/** Global mutex to manage the access to the log-stream map */ /** Global mutex to manage the access to the log-stream map */
static boost::mutex gLogStreamMutex; static std::mutex gLogStreamMutex;
#endif #endif
@ -119,7 +119,7 @@ public:
~LogToCallbackRedirector() { ~LogToCallbackRedirector() {
#ifndef ASSIMP_BUILD_SINGLETHREADED #ifndef ASSIMP_BUILD_SINGLETHREADED
boost::mutex::scoped_lock lock(gLogStreamMutex); std::lock_guard<std::mutex> lock(gLogStreamMutex);
#endif #endif
// (HACK) Check whether the 'stream.user' pointer points to a // (HACK) Check whether the 'stream.user' pointer points to a
// custom LogStream allocated by #aiGetPredefinedLogStream. // custom LogStream allocated by #aiGetPredefinedLogStream.
@ -321,8 +321,8 @@ ASSIMP_API const aiScene* aiApplyPostProcessing(const aiScene* pScene,
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
ASSIMP_API const aiScene *aiApplyCustomizedPostProcessing( const aiScene *scene, ASSIMP_API const aiScene *aiApplyCustomizedPostProcessing( const aiScene *scene,
BaseProcess* process, BaseProcess* process,
bool requestValidation ) { bool requestValidation ) {
const aiScene* sc( NULL ); const aiScene* sc( NULL );
@ -343,7 +343,7 @@ ASSIMP_API const aiScene *aiApplyCustomizedPostProcessing( const aiScene *scene,
} }
ASSIMP_END_EXCEPTION_REGION( const aiScene* ); ASSIMP_END_EXCEPTION_REGION( const aiScene* );
return sc; return sc;
} }
@ -383,7 +383,7 @@ ASSIMP_API void aiAttachLogStream( const aiLogStream* stream )
ASSIMP_BEGIN_EXCEPTION_REGION(); ASSIMP_BEGIN_EXCEPTION_REGION();
#ifndef ASSIMP_BUILD_SINGLETHREADED #ifndef ASSIMP_BUILD_SINGLETHREADED
boost::mutex::scoped_lock lock(gLogStreamMutex); std::lock_guard<std::mutex> lock(gLogStreamMutex);
#endif #endif
LogStream* lg = new LogToCallbackRedirector(*stream); LogStream* lg = new LogToCallbackRedirector(*stream);
@ -402,7 +402,7 @@ ASSIMP_API aiReturn aiDetachLogStream( const aiLogStream* stream)
ASSIMP_BEGIN_EXCEPTION_REGION(); ASSIMP_BEGIN_EXCEPTION_REGION();
#ifndef ASSIMP_BUILD_SINGLETHREADED #ifndef ASSIMP_BUILD_SINGLETHREADED
boost::mutex::scoped_lock lock(gLogStreamMutex); std::lock_guard<std::mutex> lock(gLogStreamMutex);
#endif #endif
// find the log-stream associated with this data // find the log-stream associated with this data
LogStreamMap::iterator it = gActiveLogStreams.find( *stream); LogStreamMap::iterator it = gActiveLogStreams.find( *stream);
@ -427,7 +427,7 @@ ASSIMP_API void aiDetachAllLogStreams(void)
{ {
ASSIMP_BEGIN_EXCEPTION_REGION(); ASSIMP_BEGIN_EXCEPTION_REGION();
#ifndef ASSIMP_BUILD_SINGLETHREADED #ifndef ASSIMP_BUILD_SINGLETHREADED
boost::mutex::scoped_lock lock(gLogStreamMutex); std::lock_guard<std::mutex> lock(gLogStreamMutex);
#endif #endif
Logger *logger( DefaultLogger::get() ); Logger *logger( DefaultLogger::get() );
if ( NULL == logger ) { if ( NULL == logger ) {
@ -440,7 +440,7 @@ ASSIMP_API void aiDetachAllLogStreams(void)
} }
gActiveLogStreams.clear(); gActiveLogStreams.clear();
DefaultLogger::kill(); DefaultLogger::kill();
ASSIMP_END_EXCEPTION_REGION(void); ASSIMP_END_EXCEPTION_REGION(void);
} }
@ -546,11 +546,11 @@ ASSIMP_API void aiSetImportPropertyInteger(aiPropertyStore* p, const char* szNam
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// Importer::SetPropertyFloat // Importer::SetPropertyFloat
ASSIMP_API void aiSetImportPropertyFloat(aiPropertyStore* p, const char* szName, float value) ASSIMP_API void aiSetImportPropertyFloat(aiPropertyStore* p, const char* szName, ai_real value)
{ {
ASSIMP_BEGIN_EXCEPTION_REGION(); ASSIMP_BEGIN_EXCEPTION_REGION();
PropertyMap* pp = reinterpret_cast<PropertyMap*>(p); PropertyMap* pp = reinterpret_cast<PropertyMap*>(p);
SetGenericProperty<float>(pp->floats,szName,value); SetGenericProperty<ai_real>(pp->floats,szName,value);
ASSIMP_END_EXCEPTION_REGION(void); ASSIMP_END_EXCEPTION_REGION(void);
} }

View File

@ -47,7 +47,7 @@ Assimp C export interface. See Exporter.cpp for some notes.
#include "CInterfaceIOWrapper.h" #include "CInterfaceIOWrapper.h"
#include "SceneCombiner.h" #include "SceneCombiner.h"
#include "ScenePrivate.h" #include "ScenePrivate.h"
#include "../include/assimp/Exporter.hpp" #include <assimp/Exporter.hpp>
using namespace Assimp; using namespace Assimp;

View File

@ -43,14 +43,14 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <stdarg.h> #include <stdarg.h>
#include "./../include/assimp/version.h" #include "./../include/assimp/version.h"
#include "ProcessHelper.h" #include "ProcessHelper.h"
#include "../include/assimp/IOStream.hpp" #include <assimp/IOStream.hpp>
#include "../include/assimp/IOSystem.hpp" #include <assimp/IOSystem.hpp>
#include "../include/assimp/Exporter.hpp" #include <assimp/Exporter.hpp>
#ifdef ASSIMP_BUILD_NO_OWN_ZLIB #ifdef ASSIMP_BUILD_NO_OWN_ZLIB
# include <zlib.h> # include <zlib.h>
#else #else
# include "../contrib/zlib/zlib.h" # include <contrib/zlib/zlib.h>
#endif #endif
#include <time.h> #include <time.h>
@ -65,13 +65,21 @@ namespace Assimp {
namespace AssxmlExport { namespace AssxmlExport {
int ioprintf( IOStream * io, const char * format, ... ) // -----------------------------------------------------------------------------------
{ static int ioprintf( IOStream * io, const char *format, ... ) {
char sz[4096]; using namespace std;
if ( nullptr == io ) {
return -1;
}
static const size_t Size = 4096;
char sz[ Size ];
size_t len( strlen( format ) );
::memset( sz, '\0', Size );
va_list va; va_list va;
va_start( va, format ); va_start( va, format );
int nSize = ai_snprintf( sz, 4096, format, va ); int nSize = vsnprintf( sz, Size-1, format, va );
ai_assert( nSize < 4096 ); ai_assert( nSize < Size );
va_end( va ); va_end( va );
io->Write( sz, sizeof(char), nSize ); io->Write( sz, sizeof(char), nSize );
@ -81,8 +89,7 @@ int ioprintf( IOStream * io, const char * format, ... )
// ----------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------
// Convert a name to standard XML format // Convert a name to standard XML format
void ConvertName(aiString& out, const aiString& in) static void ConvertName(aiString& out, const aiString& in) {
{
out.length = 0; out.length = 0;
for (unsigned int i = 0; i < in.length; ++i) { for (unsigned int i = 0; i < in.length; ++i) {
switch (in.data[i]) { switch (in.data[i]) {
@ -105,8 +112,7 @@ void ConvertName(aiString& out, const aiString& in)
// ----------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------
// Write a single node as text dump // Write a single node as text dump
void WriteNode(const aiNode* node, IOStream * io, unsigned int depth) static void WriteNode(const aiNode* node, IOStream * io, unsigned int depth) {
{
char prefix[512]; char prefix[512];
for (unsigned int i = 0; i < depth;++i) for (unsigned int i = 0; i < depth;++i)
prefix[i] = '\t'; prefix[i] = '\t';
@ -156,47 +162,46 @@ void WriteNode(const aiNode* node, IOStream * io, unsigned int depth)
// Some chuncks of text will need to be encoded for XML // Some chuncks of text will need to be encoded for XML
// http://stackoverflow.com/questions/5665231/most-efficient-way-to-escape-xml-html-in-c-string#5665377 // http://stackoverflow.com/questions/5665231/most-efficient-way-to-escape-xml-html-in-c-string#5665377
static std::string encodeXML(const std::string& data) { static std::string encodeXML(const std::string& data) {
std::string buffer; std::string buffer;
buffer.reserve(data.size()); buffer.reserve(data.size());
for(size_t pos = 0; pos != data.size(); ++pos) { for(size_t pos = 0; pos != data.size(); ++pos) {
switch(data[pos]) { switch(data[pos]) {
case '&': buffer.append("&amp;"); break; case '&': buffer.append("&amp;"); break;
case '\"': buffer.append("&quot;"); break; case '\"': buffer.append("&quot;"); break;
case '\'': buffer.append("&apos;"); break; case '\'': buffer.append("&apos;"); break;
case '<': buffer.append("&lt;"); break; case '<': buffer.append("&lt;"); break;
case '>': buffer.append("&gt;"); break; case '>': buffer.append("&gt;"); break;
default: buffer.append(&data[pos], 1); break; default: buffer.append(&data[pos], 1); break;
} }
} }
return buffer; return buffer;
} }
// ----------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------
// Write a text model dump // Write a text model dump
void WriteDump(const aiScene* scene, IOStream* io, bool shortened) static
{ void WriteDump(const aiScene* scene, IOStream* io, bool shortened) {
time_t tt = ::time(NULL); time_t tt = ::time( NULL );
tm* p = ::gmtime(&tt); tm* p = ::gmtime( &tt );
ai_assert( nullptr != p );
aiString name;
// write header // write header
ioprintf(io, std::string header(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<ASSIMP format_id=\"1\">\n\n" "<ASSIMP format_id=\"1\">\n\n"
"<!-- XML Model dump produced by assimp dump\n" "<!-- XML Model dump produced by assimp dump\n"
" Library version: %i.%i.%i\n" " Library version: %i.%i.%i\n"
" %s\n" " %s\n"
"-->" "-->"
" \n\n" " \n\n"
"<Scene flags=\"%i\" postprocessing=\"%i\">\n", "<Scene flags=\"%d\" postprocessing=\"%i\">\n"
);
aiGetVersionMajor(),aiGetVersionMinor(),aiGetVersionRevision(),asctime(p), const unsigned int majorVersion( aiGetVersionMajor() );
scene->mFlags, const unsigned int minorVersion( aiGetVersionMinor() );
0 /*globalImporter->GetEffectivePostProcessing()*/); const unsigned int rev( aiGetVersionRevision() );
const char *curtime( asctime( p ) );
ioprintf( io, header.c_str(), majorVersion, minorVersion, rev, curtime, scene->mFlags, 0 );
// write the node graph // write the node graph
WriteNode(scene->mRootNode, io, 0); WriteNode(scene->mRootNode, io, 0);
@ -266,6 +271,7 @@ void WriteDump(const aiScene* scene, IOStream* io, bool shortened)
ioprintf(io,"\t</Light>\n"); ioprintf(io,"\t</Light>\n");
} }
#endif #endif
aiString name;
// write textures // write textures
if (scene->mNumTextures) { if (scene->mNumTextures) {
@ -301,9 +307,10 @@ void WriteDump(const aiScene* scene, IOStream* io, bool shortened)
unsigned int r = tx->r,g=tx->g,b=tx->b,a=tx->a; unsigned int r = tx->r,g=tx->g,b=tx->b,a=tx->a;
ioprintf(io,"\t\t\t%2x %2x %2x %2x",r,g,b,a); ioprintf(io,"\t\t\t%2x %2x %2x %2x",r,g,b,a);
// group by four for readibility // group by four for readability
if (0 == (x+y*tex->mWidth) % 4) if ( 0 == ( x + y*tex->mWidth ) % 4 ) {
ioprintf(io,"\n"); ioprintf( io, "\n" );
}
} }
} }
} }

View File

@ -7,8 +7,8 @@ Copyright (c) 2006-2016, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following with or without modification, are permitted provided that the following
conditions are met: conditions are met:
* Redistributions of source code must retain the above * Redistributions of source code must retain the above
@ -25,16 +25,16 @@ conditions are met:
derived from this software without specific prior derived from this software without specific prior
written permission of the assimp team. written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
*/ */
@ -51,11 +51,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "TextureTransform.h" #include "TextureTransform.h"
#include "ConvertToLHProcess.h" #include "ConvertToLHProcess.h"
#include "StringUtils.h" #include "StringUtils.h"
#include <boost/scoped_ptr.hpp> #include <memory>
#include "../include/assimp/IOSystem.hpp" #include <assimp/IOSystem.hpp>
#include "../include/assimp/anim.h" #include <assimp/anim.h>
#include "../include/assimp/scene.h" #include <assimp/scene.h>
#include "../include/assimp/DefaultLogger.hpp" #include <assimp/DefaultLogger.hpp>
using namespace Assimp; using namespace Assimp;
@ -71,11 +71,11 @@ static const aiImporterDesc desc = {
0, 0,
0, 0,
0, 0,
"b3d" "b3d"
}; };
// (fixme, Aramis) quick workaround to get rid of all those signed to unsigned warnings // (fixme, Aramis) quick workaround to get rid of all those signed to unsigned warnings
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning (disable: 4018) # pragma warning (disable: 4018)
#endif #endif
@ -114,7 +114,7 @@ void B3DImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOS
cout<<"Hello world from the B3DImporter!"<<endl; cout<<"Hello world from the B3DImporter!"<<endl;
#endif #endif
boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile)); std::unique_ptr<IOStream> file( pIOHandler->Open( pFile));
// Check whether we can read from the file // Check whether we can read from the file
if( file.get() == NULL) if( file.get() == NULL)
@ -280,12 +280,12 @@ void B3DImporter::ReadBRUS(){
aiMaterial *mat=new aiMaterial; aiMaterial *mat=new aiMaterial;
_materials.push_back( mat ); _materials.push_back( mat );
// Name // Name
aiString ainame( name ); aiString ainame( name );
mat->AddProperty( &ainame,AI_MATKEY_NAME ); mat->AddProperty( &ainame,AI_MATKEY_NAME );
// Diffuse color // Diffuse color
mat->AddProperty( &color,1,AI_MATKEY_COLOR_DIFFUSE ); mat->AddProperty( &color,1,AI_MATKEY_COLOR_DIFFUSE );
// Opacity // Opacity
@ -294,16 +294,16 @@ void B3DImporter::ReadBRUS(){
// Specular color // Specular color
aiColor3D speccolor( shiny,shiny,shiny ); aiColor3D speccolor( shiny,shiny,shiny );
mat->AddProperty( &speccolor,1,AI_MATKEY_COLOR_SPECULAR ); mat->AddProperty( &speccolor,1,AI_MATKEY_COLOR_SPECULAR );
// Specular power // Specular power
float specpow=shiny*128; float specpow=shiny*128;
mat->AddProperty( &specpow,1,AI_MATKEY_SHININESS ); mat->AddProperty( &specpow,1,AI_MATKEY_SHININESS );
// Double sided // Double sided
if( fx & 0x10 ){ if( fx & 0x10 ){
int i=1; int i=1;
mat->AddProperty( &i,1,AI_MATKEY_TWOSIDED ); mat->AddProperty( &i,1,AI_MATKEY_TWOSIDED );
} }
//Textures //Textures
for( int i=0;i<n_texs;++i ){ for( int i=0;i<n_texs;++i ){
@ -569,7 +569,7 @@ void B3DImporter::ReadBB3D( aiScene *scene ){
string t=ReadChunk(); string t=ReadChunk();
if( t=="BB3D" ){ if( t=="BB3D" ){
int version=ReadInt(); int version=ReadInt();
if (!DefaultLogger::isNullLogger()) { if (!DefaultLogger::isNullLogger()) {
char dmp[128]; char dmp[128];
ai_snprintf(dmp, 128, "B3D file format version: %i",version); ai_snprintf(dmp, 128, "B3D file format version: %i",version);
@ -669,7 +669,7 @@ void B3DImporter::ReadBB3D( aiScene *scene ){
} }
scene->mNumMaterials=_materials.size(); scene->mNumMaterials=_materials.size();
scene->mMaterials=to_array( _materials ); scene->mMaterials=to_array( _materials );
//meshes //meshes
scene->mNumMeshes=_meshes.size(); scene->mNumMeshes=_meshes.size();
scene->mMeshes=to_array( _meshes ); scene->mMeshes=to_array( _meshes );

View File

@ -43,9 +43,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef AI_B3DIMPORTER_H_INC #ifndef AI_B3DIMPORTER_H_INC
#define AI_B3DIMPORTER_H_INC #define AI_B3DIMPORTER_H_INC
#include "../include/assimp/types.h" #include <assimp/types.h>
#include "../include/assimp/mesh.h" #include <assimp/mesh.h>
#include "../include/assimp/material.h" #include <assimp/material.h>
#include "BaseImporter.h" #include "BaseImporter.h"
#include <string> #include <string>

View File

@ -46,13 +46,14 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "BVHLoader.h" #include "BVHLoader.h"
#include "fast_atof.h" #include "fast_atof.h"
#include "SkeletonMeshBuilder.h" #include "SkeletonMeshBuilder.h"
#include "../include/assimp/Importer.hpp" #include <assimp/Importer.hpp>
#include <boost/scoped_ptr.hpp> #include <memory>
#include <boost/format.hpp> #include "TinyFormatter.h"
#include "../include/assimp/IOSystem.hpp" #include <assimp/IOSystem.hpp>
#include "../include/assimp/scene.h" #include <assimp/scene.h>
using namespace Assimp; using namespace Assimp;
using namespace Assimp::Formatter;
static const aiImporterDesc desc = { static const aiImporterDesc desc = {
"BVH Importer (MoCap)", "BVH Importer (MoCap)",
@ -118,7 +119,7 @@ void BVHLoader::InternReadFile( const std::string& pFile, aiScene* pScene, IOSys
mFileName = pFile; mFileName = pFile;
// read file into memory // read file into memory
boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile)); std::unique_ptr<IOStream> file( pIOHandler->Open( pFile));
if( file.get() == NULL) if( file.get() == NULL)
throw DeadlyImportError( "Failed to open file " + pFile + "."); throw DeadlyImportError( "Failed to open file " + pFile + ".");
@ -179,12 +180,12 @@ aiNode* BVHLoader::ReadNode()
// first token is name // first token is name
std::string nodeName = GetNextToken(); std::string nodeName = GetNextToken();
if( nodeName.empty() || nodeName == "{") if( nodeName.empty() || nodeName == "{")
ThrowException( boost::str( boost::format( "Expected node name, but found \"%s\".") % nodeName)); ThrowException( format() << "Expected node name, but found \"" << nodeName << "\"." );
// then an opening brace should follow // then an opening brace should follow
std::string openBrace = GetNextToken(); std::string openBrace = GetNextToken();
if( openBrace != "{") if( openBrace != "{")
ThrowException( boost::str( boost::format( "Expected opening brace \"{\", but found \"%s\".") % openBrace)); ThrowException( format() << "Expected opening brace \"{\", but found \"" << openBrace << "\"." );
// Create a node // Create a node
aiNode* node = new aiNode( nodeName); aiNode* node = new aiNode( nodeName);
@ -216,7 +217,7 @@ aiNode* BVHLoader::ReadNode()
// The real symbol is "End Site". Second part comes in a separate token // The real symbol is "End Site". Second part comes in a separate token
std::string siteToken = GetNextToken(); std::string siteToken = GetNextToken();
if( siteToken != "Site") if( siteToken != "Site")
ThrowException( boost::str( boost::format( "Expected \"End Site\" keyword, but found \"%s %s\".") % token % siteToken)); ThrowException( format() << "Expected \"End Site\" keyword, but found \"" << token << " " << siteToken << "\"." );
aiNode* child = ReadEndSite( nodeName); aiNode* child = ReadEndSite( nodeName);
child->mParent = node; child->mParent = node;
@ -229,7 +230,7 @@ aiNode* BVHLoader::ReadNode()
} else } else
{ {
// everything else is a parse error // everything else is a parse error
ThrowException( boost::str( boost::format( "Unknown keyword \"%s\".") % token)); ThrowException( format() << "Unknown keyword \"" << token << "\"." );
} }
} }
@ -252,7 +253,7 @@ aiNode* BVHLoader::ReadEndSite( const std::string& pParentName)
// check opening brace // check opening brace
std::string openBrace = GetNextToken(); std::string openBrace = GetNextToken();
if( openBrace != "{") if( openBrace != "{")
ThrowException( boost::str( boost::format( "Expected opening brace \"{\", but found \"%s\".") % openBrace)); ThrowException( format() << "Expected opening brace \"{\", but found \"" << openBrace << "\".");
// Create a node // Create a node
aiNode* node = new aiNode( "EndSite_" + pParentName); aiNode* node = new aiNode( "EndSite_" + pParentName);
@ -274,7 +275,7 @@ aiNode* BVHLoader::ReadEndSite( const std::string& pParentName)
} else } else
{ {
// everything else is a parse error // everything else is a parse error
ThrowException( boost::str( boost::format( "Unknown keyword \"%s\".") % token)); ThrowException( format() << "Unknown keyword \"" << token << "\"." );
} }
} }
@ -321,7 +322,7 @@ void BVHLoader::ReadNodeChannels( BVHLoader::Node& pNode)
else if( channelToken == "Zrotation") else if( channelToken == "Zrotation")
pNode.mChannels.push_back( Channel_RotationZ); pNode.mChannels.push_back( Channel_RotationZ);
else else
ThrowException( boost::str( boost::format( "Invalid channel specifier \"%s\".") % channelToken)); ThrowException( format() << "Invalid channel specifier \"" << channelToken << "\"." );
} }
} }
@ -332,7 +333,7 @@ void BVHLoader::ReadMotion( aiScene* /*pScene*/)
// Read number of frames // Read number of frames
std::string tokenFrames = GetNextToken(); std::string tokenFrames = GetNextToken();
if( tokenFrames != "Frames:") if( tokenFrames != "Frames:")
ThrowException( boost::str( boost::format( "Expected frame count \"Frames:\", but found \"%s\".") % tokenFrames)); ThrowException( format() << "Expected frame count \"Frames:\", but found \"" << tokenFrames << "\".");
float numFramesFloat = GetNextTokenAsFloat(); float numFramesFloat = GetNextTokenAsFloat();
mAnimNumFrames = (unsigned int) numFramesFloat; mAnimNumFrames = (unsigned int) numFramesFloat;
@ -341,7 +342,7 @@ void BVHLoader::ReadMotion( aiScene* /*pScene*/)
std::string tokenDuration1 = GetNextToken(); std::string tokenDuration1 = GetNextToken();
std::string tokenDuration2 = GetNextToken(); std::string tokenDuration2 = GetNextToken();
if( tokenDuration1 != "Frame" || tokenDuration2 != "Time:") if( tokenDuration1 != "Frame" || tokenDuration2 != "Time:")
ThrowException( boost::str( boost::format( "Expected frame duration \"Frame Time:\", but found \"%s %s\".") % tokenDuration1 % tokenDuration2)); ThrowException( format() << "Expected frame duration \"Frame Time:\", but found \"" << tokenDuration1 << " " << tokenDuration2 << "\"." );
mAnimTickDuration = GetNextTokenAsFloat(); mAnimTickDuration = GetNextTokenAsFloat();
@ -368,7 +369,7 @@ void BVHLoader::ReadMotion( aiScene* /*pScene*/)
// Retrieves the next token // Retrieves the next token
std::string BVHLoader::GetNextToken() std::string BVHLoader::GetNextToken()
{ {
// skip any preceeding whitespace // skip any preceding whitespace
while( mReader != mBuffer.end()) while( mReader != mBuffer.end())
{ {
if( !isspace( *mReader)) if( !isspace( *mReader))
@ -414,7 +415,7 @@ float BVHLoader::GetNextTokenAsFloat()
ctoken = fast_atoreal_move<float>( ctoken, result); ctoken = fast_atoreal_move<float>( ctoken, result);
if( ctoken != token.c_str() + token.length()) if( ctoken != token.c_str() + token.length())
ThrowException( boost::str( boost::format( "Expected a floating point number, but found \"%s\".") % token)); ThrowException( format() << "Expected a floating point number, but found \"" << token << "\"." );
return result; return result;
} }
@ -423,7 +424,7 @@ float BVHLoader::GetNextTokenAsFloat()
// Aborts the file reading with an exception // Aborts the file reading with an exception
AI_WONT_RETURN void BVHLoader::ThrowException( const std::string& pError) AI_WONT_RETURN void BVHLoader::ThrowException( const std::string& pError)
{ {
throw DeadlyImportError( boost::str( boost::format( "%s:%d - %s") % mFileName % mLine % pError)); throw DeadlyImportError( format() << mFileName << ":" << mLine << " - " << pError);
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------

View File

@ -47,13 +47,12 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "FileSystemFilter.h" #include "FileSystemFilter.h"
#include "Importer.h" #include "Importer.h"
#include "ByteSwapper.h" #include "ByteSwapper.h"
#include "../include/assimp/scene.h" #include <assimp/scene.h>
#include "../include/assimp/Importer.hpp" #include <assimp/Importer.hpp>
#include "../include/assimp/postprocess.h" #include <assimp/postprocess.h>
#include <ios> #include <ios>
#include <list> #include <list>
#include <boost/scoped_ptr.hpp> #include <memory>
#include <boost/scoped_array.hpp>
#include <sstream> #include <sstream>
#include <cctype> #include <cctype>
@ -149,10 +148,10 @@ void BaseImporter::GetExtensionList(std::set<std::string>& extensions)
if (!pIOHandler) if (!pIOHandler)
return false; return false;
boost::scoped_ptr<IOStream> pStream (pIOHandler->Open(pFile)); std::unique_ptr<IOStream> pStream (pIOHandler->Open(pFile));
if (pStream.get() ) { if (pStream.get() ) {
// read 200 characters from the file // read 200 characters from the file
boost::scoped_array<char> _buffer (new char[searchBytes+1 /* for the '\0' */]); std::unique_ptr<char[]> _buffer (new char[searchBytes+1 /* for the '\0' */]);
char* buffer = _buffer.get(); char* buffer = _buffer.get();
if( NULL == buffer ) { if( NULL == buffer ) {
return false; return false;
@ -256,7 +255,7 @@ void BaseImporter::GetExtensionList(std::set<std::string>& extensions)
const uint32_t* magic_u32; const uint32_t* magic_u32;
}; };
magic = reinterpret_cast<const char*>(_magic); magic = reinterpret_cast<const char*>(_magic);
boost::scoped_ptr<IOStream> pStream (pIOHandler->Open(pFile)); std::unique_ptr<IOStream> pStream (pIOHandler->Open(pFile));
if (pStream.get() ) { if (pStream.get() ) {
// skip to offset // skip to offset
@ -336,7 +335,7 @@ void BaseImporter::ConvertToUTF8(std::vector<char>& data)
// UTF 32 BE with BOM // UTF 32 BE with BOM
if(*((uint32_t*)&data.front()) == 0xFFFE0000) { if(*((uint32_t*)&data.front()) == 0xFFFE0000) {
// swap the endianess .. // swap the endianness ..
for(uint32_t* p = (uint32_t*)&data.front(), *end = (uint32_t*)&data.back(); p <= end; ++p) { for(uint32_t* p = (uint32_t*)&data.front(), *end = (uint32_t*)&data.back(); p <= end; ++p) {
AI_SWAP4P(p); AI_SWAP4P(p);
} }
@ -367,7 +366,7 @@ void BaseImporter::ConvertToUTF8(std::vector<char>& data)
// UTF 16 BE with BOM // UTF 16 BE with BOM
if(*((uint16_t*)&data.front()) == 0xFFFE) { if(*((uint16_t*)&data.front()) == 0xFFFE) {
// swap the endianess .. // swap the endianness ..
for(uint16_t* p = (uint16_t*)&data.front(), *end = (uint16_t*)&data.back(); p <= end; ++p) { for(uint16_t* p = (uint16_t*)&data.front(), *end = (uint16_t*)&data.back(); p <= end; ++p) {
ByteSwap::Swap2(p); ByteSwap::Swap2(p);
} }
@ -534,7 +533,7 @@ BatchLoader::~BatchLoader()
delete (*it).scene; delete (*it).scene;
} }
data->pImporter->SetIOHandler(NULL); /* get pointer back into our posession */ data->pImporter->SetIOHandler(NULL); /* get pointer back into our possession */
delete data->pImporter; delete data->pImporter;
delete data; delete data;
} }

View File

@ -48,8 +48,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <map> #include <map>
#include <vector> #include <vector>
#include <set> #include <set>
#include "../include/assimp/types.h" #include <assimp/types.h>
#include "../include/assimp/ProgressHandler.hpp" #include <assimp/ProgressHandler.hpp>
struct aiScene; struct aiScene;
@ -176,8 +176,8 @@ public:
); );
// ------------------------------------------------------------------- // -------------------------------------------------------------------
/** Returns the error description of the last error that occured. /** Returns the error description of the last error that occurred.
* @return A description of the last error that occured. An empty * @return A description of the last error that occurred. An empty
* string if there was no error. * string if there was no error.
*/ */
const std::string& GetErrorText() const { const std::string& GetErrorText() const {
@ -347,7 +347,7 @@ public: // static utilities
static void ConvertUTF8toISO8859_1( static void ConvertUTF8toISO8859_1(
std::string& data); std::string& data);
enum TextFileMode { ALLOW_EMPTY, FORBID_EMPTY }; enum TextFileMode { ALLOW_EMPTY, FORBID_EMPTY };
// ------------------------------------------------------------------- // -------------------------------------------------------------------
/** Utility for text file loaders which copies the contents of the /** Utility for text file loaders which copies the contents of the
@ -375,7 +375,7 @@ public: // static utilities
T*& out, T*& out,
unsigned int& outLength) unsigned int& outLength)
{ {
outLength = vec.size(); outLength = unsigned(vec.size());
if (outLength) { if (outLength) {
out = new T[outLength]; out = new T[outLength];
std::swap_ranges(vec.begin(), vec.end(), out); std::swap_ranges(vec.begin(), vec.end(), out);

View File

@ -43,8 +43,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "BaseImporter.h" #include "BaseImporter.h"
#include "BaseProcess.h" #include "BaseProcess.h"
#include "../include/assimp/DefaultLogger.hpp" #include <assimp/DefaultLogger.hpp>
#include "../include/assimp/scene.h" #include <assimp/scene.h>
#include "Importer.h" #include "Importer.h"
using namespace Assimp; using namespace Assimp;

View File

@ -44,7 +44,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <map> #include <map>
#include "../include/assimp/types.h" #include <assimp/types.h>
#include "GenericProperty.h" #include "GenericProperty.h"
struct aiScene; struct aiScene;

View File

@ -47,8 +47,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "Bitmap.h" #include "Bitmap.h"
#include "../include/assimp/texture.h" #include <assimp/texture.h>
#include "../include/assimp/IOStream.hpp" #include <assimp/IOStream.hpp>
#include "ByteSwapper.h" #include "ByteSwapper.h"
namespace Assimp { namespace Assimp {

View File

@ -48,14 +48,13 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "BlenderDNA.h" #include "BlenderDNA.h"
#include "StreamReader.h" #include "StreamReader.h"
#include "fast_atof.h" #include "fast_atof.h"
#include <boost/foreach.hpp>
using namespace Assimp; using namespace Assimp;
using namespace Assimp::Blender; using namespace Assimp::Blender;
using namespace Assimp::Formatter; using namespace Assimp::Formatter;
#define for_each BOOST_FOREACH static bool match4(StreamReaderAny& stream, const char* string) {
bool match4(StreamReaderAny& stream, const char* string) { ai_assert( nullptr != string );
char tmp[] = { char tmp[] = {
(stream).GetI1(), (stream).GetI1(),
(stream).GetI1(), (stream).GetI1(),
@ -71,7 +70,7 @@ struct Type {
}; };
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
void DNAParser :: Parse () void DNAParser::Parse ()
{ {
StreamReaderAny& stream = *db.reader.get(); StreamReaderAny& stream = *db.reader.get();
DNA& dna = db.dna; DNA& dna = db.dna;
@ -86,7 +85,7 @@ void DNAParser :: Parse ()
} }
std::vector<std::string> names (stream.GetI4()); std::vector<std::string> names (stream.GetI4());
for_each(std::string& s, names) { for(std::string& s : names) {
while (char c = stream.GetI1()) { while (char c = stream.GetI1()) {
s += c; s += c;
} }
@ -99,7 +98,7 @@ void DNAParser :: Parse ()
} }
std::vector<Type> types (stream.GetI4()); std::vector<Type> types (stream.GetI4());
for_each(Type& s, types) { for(Type& s : types) {
while (char c = stream.GetI1()) { while (char c = stream.GetI1()) {
s.name += c; s.name += c;
} }
@ -111,7 +110,7 @@ void DNAParser :: Parse ()
throw DeadlyImportError("BlenderDNA: Expected TLEN field"); throw DeadlyImportError("BlenderDNA: Expected TLEN field");
} }
for_each(Type& s, types) { for(Type& s : types) {
s.size = stream.GetI2(); s.size = stream.GetI2();
} }
@ -238,13 +237,15 @@ void DNA :: DumpToFile()
f << "Field format: type name offset size" << "\n"; f << "Field format: type name offset size" << "\n";
f << "Structure format: name size" << "\n"; f << "Structure format: name size" << "\n";
for_each(const Structure& s, structures) { for(const Structure& s : structures) {
f << s.name << " " << s.size << "\n\n"; f << s.name << " " << s.size << "\n\n";
for_each(const Field& ff, s.fields) { for(const Field& ff : s.fields) {
f << "\t" << ff.type << " " << ff.name << " " << ff.offset << " " << ff.size << std::endl; f << "\t" << ff.type << " " << ff.name << " " << ff.offset << " " << ff.size << "\n";
} }
f << std::endl; f << "\n";
} }
f << std::flush;
DefaultLogger::get()->info("BlenderDNA: Dumped dna to dna.txt"); DefaultLogger::get()->info("BlenderDNA: Dumped dna to dna.txt");
} }
#endif #endif
@ -270,17 +271,17 @@ void DNA :: DumpToFile()
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
boost::shared_ptr< ElemBase > DNA :: ConvertBlobToStructure( std::shared_ptr< ElemBase > DNA :: ConvertBlobToStructure(
const Structure& structure, const Structure& structure,
const FileDatabase& db const FileDatabase& db
) const ) const
{ {
std::map<std::string, FactoryPair >::const_iterator it = converters.find(structure.name); std::map<std::string, FactoryPair >::const_iterator it = converters.find(structure.name);
if (it == converters.end()) { if (it == converters.end()) {
return boost::shared_ptr< ElemBase >(); return std::shared_ptr< ElemBase >();
} }
boost::shared_ptr< ElemBase > ret = (structure.*((*it).second.first))(); std::shared_ptr< ElemBase > ret = (structure.*((*it).second.first))();
(structure.*((*it).second.second))(ret,db); (structure.*((*it).second.second))(ret,db);
return ret; return ret;

View File

@ -48,9 +48,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "BaseImporter.h" #include "BaseImporter.h"
#include "TinyFormatter.h" #include "TinyFormatter.h"
#include "StreamReader.h" #include "StreamReader.h"
#include "../include/assimp/DefaultLogger.hpp" #include <assimp/DefaultLogger.hpp>
#include <stdint.h> #include <stdint.h>
#include <boost/shared_ptr.hpp> #include <memory>
// enable verbose log output. really verbose, so be careful. // enable verbose log output. really verbose, so be careful.
@ -61,15 +61,17 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// #define ASSIMP_BUILD_BLENDER_NO_STATS // #define ASSIMP_BUILD_BLENDER_NO_STATS
namespace Assimp { namespace Assimp {
template <bool,bool> class StreamReader;
typedef StreamReader<true,true> StreamReaderAny;
namespace Blender { template <bool,bool> class StreamReader;
class FileDatabase; typedef StreamReader<true,true> StreamReaderAny;
struct FileBlockHead;
template <template <typename> class TOUT> namespace Blender {
class ObjectCache;
class FileDatabase;
struct FileBlockHead;
template <template <typename> class TOUT>
class ObjectCache;
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
/** Exception class used by the blender loader to selectively catch exceptions /** Exception class used by the blender loader to selectively catch exceptions
@ -78,62 +80,65 @@ namespace Assimp {
* the loader itself, it will still be caught by Assimp due to its * the loader itself, it will still be caught by Assimp due to its
* ancestry. */ * ancestry. */
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
struct Error : DeadlyImportError struct Error : DeadlyImportError {
{
Error (const std::string& s) Error (const std::string& s)
: DeadlyImportError(s) : DeadlyImportError(s) {
{} // empty
}
}; };
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
/** The only purpose of this structure is to feed a virtual dtor into its /** The only purpose of this structure is to feed a virtual dtor into its
* descendents. It serves as base class for all data structure fields. */ * descendents. It serves as base class for all data structure fields. */
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
struct ElemBase struct ElemBase {
{ virtual ~ElemBase() {
virtual ~ElemBase() {} // empty
}
/** Type name of the element. The type /** Type name of the element. The type
* string points is the `c_str` of the `name` attribute of the * string points is the `c_str` of the `name` attribute of the
* corresponding `Structure`, that is, it is only valid as long * corresponding `Structure`, that is, it is only valid as long
* as the DNA is not modified. The dna_type is only set if the * as the DNA is not modified. The dna_type is only set if the
* data type is not static, i.e. a boost::shared_ptr<ElemBase> * data type is not static, i.e. a std::shared_ptr<ElemBase>
* in the scene description would have its type resolved * in the scene description would have its type resolved
* at runtime, so this member is always set. */ * at runtime, so this member is always set. */
const char* dna_type; const char* dna_type;
}; };
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
/** Represents a generic pointer to a memory location, which can be either 32 /** Represents a generic pointer to a memory location, which can be either 32
* or 64 bits. These pointers are loaded from the BLEND file and finally * or 64 bits. These pointers are loaded from the BLEND file and finally
* fixed to point to the real, converted representation of the objects * fixed to point to the real, converted representation of the objects
* they used to point to.*/ * they used to point to.*/
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
struct Pointer struct Pointer {
{ Pointer()
Pointer() : val() {} : val() {
// empty
}
uint64_t val; uint64_t val;
}; };
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
/** Represents a generic offset within a BLEND file */ /** Represents a generic offset within a BLEND file */
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
struct FileOffset struct FileOffset {
{ FileOffset()
FileOffset() : val() {} : val() {
// empty
}
uint64_t val; uint64_t val;
}; };
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
/** Dummy derivate of std::vector to be able to use it in templates simultaenously /** Dummy derivate of std::vector to be able to use it in templates simultaenously
* with boost::shared_ptr, which takes only one template argument * with std::shared_ptr, which takes only one template argument
* while std::vector takes three. Also we need to provide some special member * while std::vector takes three. Also we need to provide some special member
* functions of shared_ptr */ * functions of shared_ptr */
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
template <typename T> template <typename T>
class vector : public std::vector<T> class vector : public std::vector<T> {
{
public: public:
using std::vector<T>::resize; using std::vector<T>::resize;
using std::vector<T>::empty; using std::vector<T>::empty;
@ -150,8 +155,7 @@ public:
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
/** Mixed flags for use in #Field */ /** Mixed flags for use in #Field */
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
enum FieldFlags enum FieldFlags {
{
FieldFlag_Pointer = 0x1, FieldFlag_Pointer = 0x1,
FieldFlag_Array = 0x2 FieldFlag_Array = 0x2
}; };
@ -159,8 +163,7 @@ enum FieldFlags
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
/** Represents a single member of a data structure in a BLEND file */ /** Represents a single member of a data structure in a BLEND file */
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
struct Field struct Field {
{
std::string name; std::string name;
std::string type; std::string type;
@ -180,8 +183,7 @@ struct Field
* mission critical so we need them, while others can silently be default * mission critical so we need them, while others can silently be default
* initialized and no animations are harmed. */ * initialized and no animations are harmed. */
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
enum ErrorPolicy enum ErrorPolicy {
{
/** Substitute default value and ignore */ /** Substitute default value and ignore */
ErrorPolicy_Igno, ErrorPolicy_Igno,
/** Substitute default value and write to log */ /** Substitute default value and write to log */
@ -202,15 +204,14 @@ enum ErrorPolicy
* binary `blob` read from the file to such a structure instance with * binary `blob` read from the file to such a structure instance with
* meaningful contents. */ * meaningful contents. */
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
class Structure class Structure {
{
template <template <typename> class> friend class ObjectCache; template <template <typename> class> friend class ObjectCache;
public: public:
Structure() Structure()
: cache_idx(-1) : cache_idx(static_cast<size_t>(-1) ){
{} // empty
}
public: public:
@ -260,11 +261,11 @@ public:
// -------------------------------------------------------- // --------------------------------------------------------
// generic converter // generic converter
template <typename T> template <typename T>
void Convert(boost::shared_ptr<ElemBase> in,const FileDatabase& db) const; void Convert(std::shared_ptr<ElemBase> in,const FileDatabase& db) const;
// -------------------------------------------------------- // --------------------------------------------------------
// generic allocator // generic allocator
template <typename T> boost::shared_ptr<ElemBase> Allocate() const; template <typename T> std::shared_ptr<ElemBase> Allocate() const;
@ -282,7 +283,7 @@ public:
// -------------------------------------------------------- // --------------------------------------------------------
// field parsing for pointer or dynamic array types // field parsing for pointer or dynamic array types
// (boost::shared_ptr or boost::shared_array) // (std::shared_ptr)
// The return value indicates whether the data was already cached. // The return value indicates whether the data was already cached.
template <int error_policy, template <typename> class TOUT, typename T> template <int error_policy, template <typename> class TOUT, typename T>
bool ReadFieldPtr(TOUT<T>& out, const char* name, bool ReadFieldPtr(TOUT<T>& out, const char* name,
@ -291,7 +292,7 @@ public:
// -------------------------------------------------------- // --------------------------------------------------------
// field parsing for static arrays of pointer or dynamic // field parsing for static arrays of pointer or dynamic
// array types (boost::shared_ptr[] or boost::shared_array[]) // array types (std::shared_ptr[])
// The return value indicates whether the data was already cached. // The return value indicates whether the data was already cached.
template <int error_policy, template <typename> class TOUT, typename T, size_t N> template <int error_policy, template <typename> class TOUT, typename T, size_t N>
bool ReadFieldPtr(TOUT<T> (&out)[N], const char* name, bool ReadFieldPtr(TOUT<T> (&out)[N], const char* name,
@ -318,7 +319,7 @@ private:
const FileDatabase& db, const Field& f, bool) const; const FileDatabase& db, const Field& f, bool) const;
// -------------------------------------------------------- // --------------------------------------------------------
bool ResolvePointer( boost::shared_ptr< FileOffset >& out, const Pointer & ptrval, bool ResolvePointer( std::shared_ptr< FileOffset >& out, const Pointer & ptrval,
const FileDatabase& db, const Field& f, bool) const; const FileDatabase& db, const Field& f, bool) const;
// -------------------------------------------------------- // --------------------------------------------------------
@ -329,8 +330,8 @@ private:
private: private:
// ------------------------------------------------------------------------------ // ------------------------------------------------------------------------------
template <typename T> T* _allocate(boost::shared_ptr<T>& out, size_t& s) const { template <typename T> T* _allocate(std::shared_ptr<T>& out, size_t& s) const {
out = boost::shared_ptr<T>(new T()); out = std::shared_ptr<T>(new T());
s = 1; s = 1;
return out.get(); return out.get();
} }
@ -394,7 +395,7 @@ template <> struct Structure :: _defaultInitializer<ErrorPolicy_Fail> {
}; };
// ------------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------------
template <> inline bool Structure :: ResolvePointer<boost::shared_ptr,ElemBase>(boost::shared_ptr<ElemBase>& out, template <> inline bool Structure :: ResolvePointer<std::shared_ptr,ElemBase>(std::shared_ptr<ElemBase>& out,
const Pointer & ptrval, const Pointer & ptrval,
const FileDatabase& db, const FileDatabase& db,
const Field& f, const Field& f,
@ -413,11 +414,11 @@ class DNA
public: public:
typedef void (Structure::*ConvertProcPtr) ( typedef void (Structure::*ConvertProcPtr) (
boost::shared_ptr<ElemBase> in, std::shared_ptr<ElemBase> in,
const FileDatabase& const FileDatabase&
) const; ) const;
typedef boost::shared_ptr<ElemBase> ( typedef std::shared_ptr<ElemBase> (
Structure::*AllocProcPtr) () const; Structure::*AllocProcPtr) () const;
typedef std::pair< AllocProcPtr, ConvertProcPtr > FactoryPair; typedef std::pair< AllocProcPtr, ConvertProcPtr > FactoryPair;
@ -464,7 +465,7 @@ public:
* @param structure Destination structure definition * @param structure Destination structure definition
* @param db File database. * @param db File database.
* @return A null pointer if no appropriate converter is available.*/ * @return A null pointer if no appropriate converter is available.*/
boost::shared_ptr< ElemBase > ConvertBlobToStructure( std::shared_ptr< ElemBase > ConvertBlobToStructure(
const Structure& structure, const Structure& structure,
const FileDatabase& db const FileDatabase& db
) const; ) const;
@ -709,8 +710,6 @@ class FileDatabase
template <template <typename> class TOUT> friend class ObjectCache; template <template <typename> class TOUT> friend class ObjectCache;
public: public:
FileDatabase() FileDatabase()
: _cacheArrays(*this) : _cacheArrays(*this)
, _cache(*this) , _cache(*this)
@ -718,13 +717,12 @@ public:
{} {}
public: public:
// publicly accessible fields // publicly accessible fields
bool i64bit; bool i64bit;
bool little; bool little;
DNA dna; DNA dna;
boost::shared_ptr< StreamReaderAny > reader; std::shared_ptr< StreamReaderAny > reader;
vector< FileBlockHead > entries; vector< FileBlockHead > entries;
public: public:
@ -738,7 +736,7 @@ public:
// arrays of objects are never cached because we can't easily // arrays of objects are never cached because we can't easily
// ensure their proper destruction. // ensure their proper destruction.
template <typename T> template <typename T>
ObjectCache<boost::shared_ptr>& cache(boost::shared_ptr<T>& /*in*/) const { ObjectCache<std::shared_ptr>& cache(std::shared_ptr<T>& /*in*/) const {
return _cache; return _cache;
} }
@ -755,7 +753,7 @@ private:
#endif #endif
mutable ObjectCache<vector> _cacheArrays; mutable ObjectCache<vector> _cacheArrays;
mutable ObjectCache<boost::shared_ptr> _cache; mutable ObjectCache<std::shared_ptr> _cache;
mutable size_t next_cache_idx; mutable size_t next_cache_idx;
}; };

View File

@ -5,8 +5,8 @@ Open Asset Import Library (assimp)
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2016, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the with or without modification, are permitted provided that the
following conditions are met: following conditions are met:
* Redistributions of source code must retain the above * Redistributions of source code must retain the above
@ -23,29 +23,29 @@ following conditions are met:
derived from this software without specific prior derived from this software without specific prior
written permission of the assimp team. written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------- ----------------------------------------------------------------------
*/ */
/** @file BlenderDNA.inl /** @file BlenderDNA.inl
* @brief Blender `DNA` (file format specification embedded in * @brief Blender `DNA` (file format specification embedded in
* blend file itself) loader. * blend file itself) loader.
*/ */
#ifndef INCLUDED_AI_BLEND_DNA_INL #ifndef INCLUDED_AI_BLEND_DNA_INL
#define INCLUDED_AI_BLEND_DNA_INL #define INCLUDED_AI_BLEND_DNA_INL
#include <boost/shared_ptr.hpp> #include <memory>
namespace Assimp { namespace Assimp {
namespace Blender { namespace Blender {
@ -71,7 +71,7 @@ const Field* Structure :: Get (const std::string& ss) const
} }
//-------------------------------------------------------------------------------- //--------------------------------------------------------------------------------
const Field& Structure :: operator [] (const size_t i) const const Field& Structure :: operator [] (const size_t i) const
{ {
if (i >= fields.size()) { if (i >= fields.size()) {
throw Error((Formatter::format(), throw Error((Formatter::format(),
@ -83,15 +83,15 @@ const Field& Structure :: operator [] (const size_t i) const
} }
//-------------------------------------------------------------------------------- //--------------------------------------------------------------------------------
template <typename T> boost::shared_ptr<ElemBase> Structure :: Allocate() const template <typename T> std::shared_ptr<ElemBase> Structure :: Allocate() const
{ {
return boost::shared_ptr<T>(new T()); return std::shared_ptr<T>(new T());
} }
//-------------------------------------------------------------------------------- //--------------------------------------------------------------------------------
template <typename T> void Structure :: Convert( template <typename T> void Structure :: Convert(
boost::shared_ptr<ElemBase> in, std::shared_ptr<ElemBase> in,
const FileDatabase& db) const const FileDatabase& db) const
{ {
Convert<T> (*static_cast<T*> ( in.get() ),db); Convert<T> (*static_cast<T*> ( in.get() ),db);
} }
@ -226,7 +226,7 @@ bool Structure :: ReadFieldPtr(TOUT<T>& out, const char* name, const FileDatabas
//-------------------------------------------------------------------------------- //--------------------------------------------------------------------------------
template <int error_policy, template <typename> class TOUT, typename T, size_t N> template <int error_policy, template <typename> class TOUT, typename T, size_t N>
bool Structure :: ReadFieldPtr(TOUT<T> (&out)[N], const char* name, bool Structure :: ReadFieldPtr(TOUT<T> (&out)[N], const char* name,
const FileDatabase& db) const const FileDatabase& db) const
{ {
// XXX see if we can reduce this to call to the 'normal' ReadFieldPtr // XXX see if we can reduce this to call to the 'normal' ReadFieldPtr
@ -306,12 +306,12 @@ void Structure :: ReadField(T& out, const char* name, const FileDatabase& db) co
//-------------------------------------------------------------------------------- //--------------------------------------------------------------------------------
template <template <typename> class TOUT, typename T> template <template <typename> class TOUT, typename T>
bool Structure :: ResolvePointer(TOUT<T>& out, const Pointer & ptrval, const FileDatabase& db, bool Structure :: ResolvePointer(TOUT<T>& out, const Pointer & ptrval, const FileDatabase& db,
const Field& f, const Field& f,
bool non_recursive /*= false*/) const bool non_recursive /*= false*/) const
{ {
out.reset(); // ensure null pointers work out.reset(); // ensure null pointers work
if (!ptrval.val) { if (!ptrval.val) {
return false; return false;
} }
const Structure& s = db.dna[f.type]; const Structure& s = db.dna[f.type];
@ -328,7 +328,7 @@ bool Structure :: ResolvePointer(TOUT<T>& out, const Pointer & ptrval, const Fil
} }
// try to retrieve the object from the cache // try to retrieve the object from the cache
db.cache(out).get(s,out,ptrval); db.cache(out).get(s,out,ptrval);
if (out) { if (out) {
return true; return true;
} }
@ -340,11 +340,11 @@ bool Structure :: ResolvePointer(TOUT<T>& out, const Pointer & ptrval, const Fil
// I really ought to improve StreamReader to work with 64 bit indices exclusively. // I really ought to improve StreamReader to work with 64 bit indices exclusively.
// continue conversion after allocating the required storage // continue conversion after allocating the required storage
size_t num = block->size / ss.size; size_t num = block->size / ss.size;
T* o = _allocate(out,num); T* o = _allocate(out,num);
// cache the object before we convert it to avoid cyclic recursion. // cache the object before we convert it to avoid cyclic recursion.
db.cache(out).set(s,out,ptrval); db.cache(out).set(s,out,ptrval);
// if the non_recursive flag is set, we don't do anything but leave // if the non_recursive flag is set, we don't do anything but leave
// the cursor at the correct position to resolve the object. // the cursor at the correct position to resolve the object.
@ -366,45 +366,45 @@ bool Structure :: ResolvePointer(TOUT<T>& out, const Pointer & ptrval, const Fil
//-------------------------------------------------------------------------------- //--------------------------------------------------------------------------------
inline bool Structure :: ResolvePointer( boost::shared_ptr< FileOffset >& out, const Pointer & ptrval, inline bool Structure :: ResolvePointer( std::shared_ptr< FileOffset >& out, const Pointer & ptrval,
const FileDatabase& db, const FileDatabase& db,
const Field&, const Field&,
bool) const bool) const
{ {
// Currently used exclusively by PackedFile::data to represent // Currently used exclusively by PackedFile::data to represent
// a simple offset into the mapped BLEND file. // a simple offset into the mapped BLEND file.
out.reset(); out.reset();
if (!ptrval.val) { if (!ptrval.val) {
return false; return false;
} }
// find the file block the pointer is pointing to // find the file block the pointer is pointing to
const FileBlockHead* block = LocateFileBlockForAddress(ptrval,db); const FileBlockHead* block = LocateFileBlockForAddress(ptrval,db);
out = boost::shared_ptr< FileOffset > (new FileOffset()); out = std::shared_ptr< FileOffset > (new FileOffset());
out->val = block->start+ static_cast<size_t>((ptrval.val - block->address.val) ); out->val = block->start+ static_cast<size_t>((ptrval.val - block->address.val) );
return false; return false;
} }
//-------------------------------------------------------------------------------- //--------------------------------------------------------------------------------
template <template <typename> class TOUT, typename T> template <template <typename> class TOUT, typename T>
bool Structure :: ResolvePointer(vector< TOUT<T> >& out, const Pointer & ptrval, bool Structure :: ResolvePointer(vector< TOUT<T> >& out, const Pointer & ptrval,
const FileDatabase& db, const FileDatabase& db,
const Field& f, const Field& f,
bool) const bool) const
{ {
// This is a function overload, not a template specialization. According to // This is a function overload, not a template specialization. According to
// the partial ordering rules, it should be selected by the compiler // the partial ordering rules, it should be selected by the compiler
// for array-of-pointer inputs, i.e. Object::mats. // for array-of-pointer inputs, i.e. Object::mats.
out.reset(); out.reset();
if (!ptrval.val) { if (!ptrval.val) {
return false; return false;
} }
// find the file block the pointer is pointing to // find the file block the pointer is pointing to
const FileBlockHead* block = LocateFileBlockForAddress(ptrval,db); const FileBlockHead* block = LocateFileBlockForAddress(ptrval,db);
const size_t num = block->size / (db.i64bit?8:4); const size_t num = block->size / (db.i64bit?8:4);
// keep the old stream position // keep the old stream position
const StreamReaderAny::pos pold = db.reader->GetCurrentPos(); const StreamReaderAny::pos pold = db.reader->GetCurrentPos();
@ -418,7 +418,7 @@ bool Structure :: ResolvePointer(vector< TOUT<T> >& out, const Pointer & ptrval,
Convert(val,db); Convert(val,db);
// and resolve the pointees // and resolve the pointees
res = ResolvePointer(out[i],val,db,f) && res; res = ResolvePointer(out[i],val,db,f) && res;
} }
db.reader->SetCurrentPos(pold); db.reader->SetCurrentPos(pold);
@ -426,18 +426,18 @@ bool Structure :: ResolvePointer(vector< TOUT<T> >& out, const Pointer & ptrval,
} }
//-------------------------------------------------------------------------------- //--------------------------------------------------------------------------------
template <> bool Structure :: ResolvePointer<boost::shared_ptr,ElemBase>(boost::shared_ptr<ElemBase>& out, template <> bool Structure :: ResolvePointer<std::shared_ptr,ElemBase>(std::shared_ptr<ElemBase>& out,
const Pointer & ptrval, const Pointer & ptrval,
const FileDatabase& db, const FileDatabase& db,
const Field&, const Field&,
bool bool
) const ) const
{ {
// Special case when the data type needs to be determined at runtime. // Special case when the data type needs to be determined at runtime.
// Less secure than in the `strongly-typed` case. // Less secure than in the `strongly-typed` case.
out.reset(); out.reset();
if (!ptrval.val) { if (!ptrval.val) {
return false; return false;
} }
@ -448,7 +448,7 @@ template <> bool Structure :: ResolvePointer<boost::shared_ptr,ElemBase>(boost::
const Structure& s = db.dna[block->dna_index]; const Structure& s = db.dna[block->dna_index];
// try to retrieve the object from the cache // try to retrieve the object from the cache
db.cache(out).get(s,out,ptrval); db.cache(out).get(s,out,ptrval);
if (out) { if (out) {
return true; return true;
} }
@ -473,15 +473,15 @@ template <> bool Structure :: ResolvePointer<boost::shared_ptr,ElemBase>(boost::
// allocate the object hull // allocate the object hull
out = (s.*builders.first)(); out = (s.*builders.first)();
// cache the object immediately to prevent infinite recursion in a // cache the object immediately to prevent infinite recursion in a
// circular list with a single element (i.e. a self-referencing element). // circular list with a single element (i.e. a self-referencing element).
db.cache(out).set(s,out,ptrval); db.cache(out).set(s,out,ptrval);
// and do the actual conversion // and do the actual conversion
(s.*builders.second)(out,db); (s.*builders.second)(out,db);
db.reader->SetCurrentPos(pold); db.reader->SetCurrentPos(pold);
// store a pointer to the name string of the actual type // store a pointer to the name string of the actual type
// in the object itself. This allows the conversion code // in the object itself. This allows the conversion code
// to perform additional type checking. // to perform additional type checking.
@ -495,10 +495,10 @@ template <> bool Structure :: ResolvePointer<boost::shared_ptr,ElemBase>(boost::
} }
//-------------------------------------------------------------------------------- //--------------------------------------------------------------------------------
const FileBlockHead* Structure :: LocateFileBlockForAddress(const Pointer & ptrval, const FileDatabase& db) const const FileBlockHead* Structure :: LocateFileBlockForAddress(const Pointer & ptrval, const FileDatabase& db) const
{ {
// the file blocks appear in list sorted by // the file blocks appear in list sorted by
// with ascending base addresses so we can run a // with ascending base addresses so we can run a
// binary search to locate the pointee quickly. // binary search to locate the pointee quickly.
// NOTE: Blender seems to distinguish between side-by-side // NOTE: Blender seems to distinguish between side-by-side
@ -525,16 +525,16 @@ const FileBlockHead* Structure :: LocateFileBlockForAddress(const Pointer & ptrv
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// NOTE: The MSVC debugger keeps showing up this annoying `a cast to a smaller data type has // NOTE: The MSVC debugger keeps showing up this annoying `a cast to a smaller data type has
// caused a loss of data`-warning. Avoid this warning by a masking with an appropriate bitmask. // caused a loss of data`-warning. Avoid this warning by a masking with an appropriate bitmask.
template <typename T> struct signless; template <typename T> struct signless;
template <> struct signless<char> {typedef unsigned char type;}; template <> struct signless<char> {typedef unsigned char type;};
template <> struct signless<short> {typedef unsigned short type;}; template <> struct signless<short> {typedef unsigned short type;};
template <> struct signless<int> {typedef unsigned int type;}; template <> struct signless<int> {typedef unsigned int type;};
template <> struct signless<unsigned char> { typedef unsigned char type; };
template <typename T> template <typename T>
struct static_cast_silent { struct static_cast_silent {
template <typename V> template <typename V>
T operator()(V in) { T operator()(V in) {
return static_cast<T>(in & static_cast<typename signless<T>::type>(-1)); return static_cast<T>(in & static_cast<typename signless<T>::type>(-1));
@ -554,7 +554,7 @@ template <> struct static_cast_silent<double> {
}; };
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
template <typename T> inline void ConvertDispatcher(T& out, const Structure& in,const FileDatabase& db) template <typename T> inline void ConvertDispatcher(T& out, const Structure& in,const FileDatabase& db)
{ {
if (in.name == "int") { if (in.name == "int") {
out = static_cast_silent<T>()(db.reader->GetU4()); out = static_cast_silent<T>()(db.reader->GetU4());
@ -614,6 +614,22 @@ template <> inline void Structure :: Convert<char> (char& dest,const FileDatab
ConvertDispatcher(dest,*this,db); ConvertDispatcher(dest,*this,db);
} }
// ------------------------------------------------------------------------------------------------
template <> inline void Structure::Convert<unsigned char>(unsigned char& dest, const FileDatabase& db) const
{
// automatic rescaling from char to float and vice versa (seems useful for RGB colors)
if (name == "float") {
dest = static_cast<unsigned char>(db.reader->GetF4() * 255.f);
return;
}
else if (name == "double") {
dest = static_cast<unsigned char>(db.reader->GetF8() * 255.f);
return;
}
ConvertDispatcher(dest, *this, db);
}
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
template <> inline void Structure :: Convert<float> (float& dest,const FileDatabase& db) const template <> inline void Structure :: Convert<float> (float& dest,const FileDatabase& db) const
{ {
@ -677,7 +693,7 @@ const Structure* DNA :: Get (const std::string& ss) const
} }
//-------------------------------------------------------------------------------- //--------------------------------------------------------------------------------
const Structure& DNA :: operator [] (const size_t i) const const Structure& DNA :: operator [] (const size_t i) const
{ {
if (i >= structures.size()) { if (i >= structures.size()) {
throw Error((Formatter::format(), throw Error((Formatter::format(),
@ -690,8 +706,8 @@ const Structure& DNA :: operator [] (const size_t i) const
//-------------------------------------------------------------------------------- //--------------------------------------------------------------------------------
template <template <typename> class TOUT> template <typename T> void ObjectCache<TOUT> :: get ( template <template <typename> class TOUT> template <typename T> void ObjectCache<TOUT> :: get (
const Structure& s, const Structure& s,
TOUT<T>& out, TOUT<T>& out,
const Pointer& ptr const Pointer& ptr
) const { ) const {
@ -703,7 +719,7 @@ template <template <typename> class TOUT> template <typename T> void ObjectCache
typename StructureCache::const_iterator it = caches[s.cache_idx].find(ptr); typename StructureCache::const_iterator it = caches[s.cache_idx].find(ptr);
if (it != caches[s.cache_idx].end()) { if (it != caches[s.cache_idx].end()) {
out = boost::static_pointer_cast<T>( (*it).second ); out = std::static_pointer_cast<T>( (*it).second );
#ifndef ASSIMP_BUILD_BLENDER_NO_STATS #ifndef ASSIMP_BUILD_BLENDER_NO_STATS
++db.stats().cache_hits; ++db.stats().cache_hits;
@ -715,7 +731,7 @@ template <template <typename> class TOUT> template <typename T> void ObjectCache
//-------------------------------------------------------------------------------- //--------------------------------------------------------------------------------
template <template <typename> class TOUT> template <typename T> void ObjectCache<TOUT> :: set ( template <template <typename> class TOUT> template <typename T> void ObjectCache<TOUT> :: set (
const Structure& s, const Structure& s,
const TOUT<T>& out, const TOUT<T>& out,
const Pointer& ptr const Pointer& ptr
) { ) {
@ -723,7 +739,7 @@ template <template <typename> class TOUT> template <typename T> void ObjectCache
s.cache_idx = db.next_cache_idx++; s.cache_idx = db.next_cache_idx++;
caches.resize(db.next_cache_idx); caches.resize(db.next_cache_idx);
} }
caches[s.cache_idx][ptr] = boost::static_pointer_cast<ElemBase>( out ); caches[s.cache_idx][ptr] = std::static_pointer_cast<ElemBase>( out );
#ifndef ASSIMP_BUILD_BLENDER_NO_STATS #ifndef ASSIMP_BUILD_BLENDER_NO_STATS
++db.stats().cached_objects; ++db.stats().cached_objects;

View File

@ -49,14 +49,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "BlenderDNA.h" #include "BlenderDNA.h"
#include "BlenderScene.h" #include "BlenderScene.h"
#include "BlenderSceneGen.h" #include "BlenderSceneGen.h"
#include <boost/foreach.hpp>
#include <deque> #include <deque>
#include "./../include/assimp/material.h" #include "./../include/assimp/material.h"
struct aiTexture; struct aiTexture;
#define for_each(x,y) BOOST_FOREACH(x,y)
namespace Assimp { namespace Assimp {
namespace Blender { namespace Blender {
@ -71,7 +68,7 @@ namespace Blender {
} }
~TempArray () { ~TempArray () {
for_each(T* elem, arr) { for(T* elem : arr) {
delete elem; delete elem;
} }
} }
@ -126,7 +123,8 @@ namespace Blender {
struct ObjectCompare { struct ObjectCompare {
bool operator() (const Object* left, const Object* right) const { bool operator() (const Object* left, const Object* right) const {
return strcmp(left->id.name, right->id.name) == -1; printf( "left: %s, right: %s\n", left->id.name, right->id.name );
return ::strncmp(left->id.name, right->id.name, strlen( left->id.name ) ) == 0;
} }
}; };
@ -147,7 +145,8 @@ namespace Blender {
struct ObjectCompare { struct ObjectCompare {
bool operator() (const Object* left, const Object* right) const { bool operator() (const Object* left, const Object* right) const {
return strcmp(left->id.name, right->id.name) == -1; printf( "left: %s, right: %s\n", left->id.name, right->id.name );
return ::strncmp( left->id.name, right->id.name, strlen( left->id.name ) ) == 0;
} }
}; };
@ -160,7 +159,7 @@ namespace Blender {
TempArray <std::vector, aiTexture> textures; TempArray <std::vector, aiTexture> textures;
// set of all materials referenced by at least one mesh in the scene // set of all materials referenced by at least one mesh in the scene
std::deque< boost::shared_ptr< Material > > materials_raw; std::deque< std::shared_ptr< Material > > materials_raw;
// counter to name sentinel textures inserted as substitutes for procedural textures. // counter to name sentinel textures inserted as substitutes for procedural textures.
unsigned int sentinel_cnt; unsigned int sentinel_cnt;

View File

@ -53,7 +53,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "BlenderModifier.h" #include "BlenderModifier.h"
#include "BlenderBMesh.h" #include "BlenderBMesh.h"
#include "StringUtils.h" #include "StringUtils.h"
#include "../include/assimp/scene.h" #include <assimp/scene.h>
#include "StringComparison.h" #include "StringComparison.h"
#include "StreamReader.h" #include "StreamReader.h"
@ -164,7 +164,7 @@ void BlenderImporter::InternReadFile( const std::string& pFile,
#endif #endif
FileDatabase file; FileDatabase file;
boost::shared_ptr<IOStream> stream(pIOHandler->Open(pFile,"rb")); std::shared_ptr<IOStream> stream(pIOHandler->Open(pFile,"rb"));
if (!stream) { if (!stream) {
ThrowException("Could not open file for reading"); ThrowException("Could not open file for reading");
} }
@ -190,7 +190,7 @@ void BlenderImporter::InternReadFile( const std::string& pFile,
// http://www.gzip.org/zlib/rfc-gzip.html#header-trailer // http://www.gzip.org/zlib/rfc-gzip.html#header-trailer
stream->Seek(0L,aiOrigin_SET); stream->Seek(0L,aiOrigin_SET);
boost::shared_ptr<StreamReaderLE> reader = boost::shared_ptr<StreamReaderLE>(new StreamReaderLE(stream)); std::shared_ptr<StreamReaderLE> reader = std::shared_ptr<StreamReaderLE>(new StreamReaderLE(stream));
// build a zlib stream // build a zlib stream
z_stream zstream; z_stream zstream;
@ -260,9 +260,9 @@ void BlenderImporter::InternReadFile( const std::string& pFile,
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
void BlenderImporter::ParseBlendFile(FileDatabase& out, boost::shared_ptr<IOStream> stream) void BlenderImporter::ParseBlendFile(FileDatabase& out, std::shared_ptr<IOStream> stream)
{ {
out.reader = boost::shared_ptr<StreamReaderAny>(new StreamReaderAny(stream,out.little)); out.reader = std::shared_ptr<StreamReaderAny>(new StreamReaderAny(stream,out.little));
DNAParser dna_reader(out); DNAParser dna_reader(out);
const DNA* dna = NULL; const DNA* dna = NULL;
@ -305,7 +305,7 @@ void BlenderImporter::ExtractScene(Scene& out, const FileDatabase& file)
const Structure& ss = file.dna.structures[(*it).second]; const Structure& ss = file.dna.structures[(*it).second];
// we need a scene somewhere to start with. // we need a scene somewhere to start with.
for_each(const FileBlockHead& bl,file.entries) { for(const FileBlockHead& bl :file.entries) {
// Fix: using the DNA index is more reliable to locate scenes // Fix: using the DNA index is more reliable to locate scenes
//if (bl.id == "SC") { //if (bl.id == "SC") {
@ -342,7 +342,7 @@ void BlenderImporter::ConvertBlendFile(aiScene* out, const Scene& in,const FileD
// the file. This is terrible. Here, we're first looking for // the file. This is terrible. Here, we're first looking for
// all objects which don't have parent objects at all - // all objects which don't have parent objects at all -
std::deque<const Object*> no_parents; std::deque<const Object*> no_parents;
for (boost::shared_ptr<Base> cur = boost::static_pointer_cast<Base> ( in.base.first ); cur; cur = cur->next) { for (std::shared_ptr<Base> cur = std::static_pointer_cast<Base> ( in.base.first ); cur; cur = cur->next) {
if (cur->object) { if (cur->object) {
if(!cur->object->parent) { if(!cur->object->parent) {
no_parents.push_back(cur->object.get()); no_parents.push_back(cur->object.get());
@ -350,7 +350,7 @@ void BlenderImporter::ConvertBlendFile(aiScene* out, const Scene& in,const FileD
else conv.objects.insert(cur->object.get()); else conv.objects.insert(cur->object.get());
} }
} }
for (boost::shared_ptr<Base> cur = in.basact; cur; cur = cur->next) { for (std::shared_ptr<Base> cur = in.basact; cur; cur = cur->next) {
if (cur->object) { if (cur->object) {
if(cur->object->parent) { if(cur->object->parent) {
conv.objects.insert(cur->object.get()); conv.objects.insert(cur->object.get());
@ -554,18 +554,16 @@ void BlenderImporter::ResolveTexture(aiMaterial* out, const Material* mat, const
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
void BlenderImporter::BuildMaterials(ConversionData& conv_data) void BlenderImporter::BuildDefaultMaterial(Blender::ConversionData& conv_data)
{ {
conv_data.materials->reserve(conv_data.materials_raw.size());
// add a default material if necessary // add a default material if necessary
unsigned int index = static_cast<unsigned int>( -1 ); unsigned int index = static_cast<unsigned int>( -1 );
for_each( aiMesh* mesh, conv_data.meshes.get() ) { for( aiMesh* mesh : conv_data.meshes.get() ) {
if (mesh->mMaterialIndex == static_cast<unsigned int>( -1 )) { if (mesh->mMaterialIndex == static_cast<unsigned int>( -1 )) {
if (index == static_cast<unsigned int>( -1 )) { if (index == static_cast<unsigned int>( -1 )) {
// Setup a default material. // Setup a default material.
boost::shared_ptr<Material> p(new Material()); std::shared_ptr<Material> p(new Material());
ai_assert(::strlen(AI_DEFAULT_MATERIAL_NAME) < sizeof(p->id.name)-2); ai_assert(::strlen(AI_DEFAULT_MATERIAL_NAME) < sizeof(p->id.name)-2);
strcpy( p->id.name+2, AI_DEFAULT_MATERIAL_NAME ); strcpy( p->id.name+2, AI_DEFAULT_MATERIAL_NAME );
@ -588,8 +586,126 @@ void BlenderImporter::BuildMaterials(ConversionData& conv_data)
mesh->mMaterialIndex = index; mesh->mMaterialIndex = index;
} }
} }
}
for_each(boost::shared_ptr<Material> mat, conv_data.materials_raw) { void BlenderImporter::AddBlendParams(aiMaterial* result, const Material* source)
{
aiColor3D diffuseColor(source->r, source->g, source->b);
result->AddProperty(&diffuseColor, 1, "$mat.blend.diffuse.color", 0, 0);
float diffuseIntensity = source->ref;
result->AddProperty(&diffuseIntensity, 1, "$mat.blend.diffuse.intensity", 0, 0);
int diffuseShader = source->diff_shader;
result->AddProperty(&diffuseShader, 1, "$mat.blend.diffuse.shader", 0, 0);
int diffuseRamp = 0;
result->AddProperty(&diffuseRamp, 1, "$mat.blend.diffuse.ramp", 0, 0);
aiColor3D specularColor(source->specr, source->specg, source->specb);
result->AddProperty(&specularColor, 1, "$mat.blend.specular.color", 0, 0);
float specularIntensity = source->spec;
result->AddProperty(&specularIntensity, 1, "$mat.blend.specular.intensity", 0, 0);
int specularShader = source->spec_shader;
result->AddProperty(&specularShader, 1, "$mat.blend.specular.shader", 0, 0);
int specularRamp = 0;
result->AddProperty(&specularRamp, 1, "$mat.blend.specular.ramp", 0, 0);
int specularHardness = source->har;
result->AddProperty(&specularHardness, 1, "$mat.blend.specular.hardness", 0, 0);
int transparencyUse = source->mode & MA_TRANSPARENCY ? 1 : 0;
result->AddProperty(&transparencyUse, 1, "$mat.blend.transparency.use", 0, 0);
int transparencyMethod = source->mode & MA_RAYTRANSP ? 2 : (source->mode & MA_ZTRANSP ? 1 : 0);
result->AddProperty(&transparencyMethod, 1, "$mat.blend.transparency.method", 0, 0);
float transparencyAlpha = source->alpha;
result->AddProperty(&transparencyAlpha, 1, "$mat.blend.transparency.alpha", 0, 0);
float transparencySpecular = source->spectra;
result->AddProperty(&transparencySpecular, 1, "$mat.blend.transparency.specular", 0, 0);
float transparencyFresnel = source->fresnel_tra;
result->AddProperty(&transparencyFresnel, 1, "$mat.blend.transparency.fresnel", 0, 0);
float transparencyBlend = source->fresnel_tra_i;
result->AddProperty(&transparencyBlend, 1, "$mat.blend.transparency.blend", 0, 0);
float transparencyIor = source->ang;
result->AddProperty(&transparencyIor, 1, "$mat.blend.transparency.ior", 0, 0);
float transparencyFilter = source->filter;
result->AddProperty(&transparencyFilter, 1, "$mat.blend.transparency.filter", 0, 0);
float transparencyFalloff = source->tx_falloff;
result->AddProperty(&transparencyFalloff, 1, "$mat.blend.transparency.falloff", 0, 0);
float transparencyLimit = source->tx_limit;
result->AddProperty(&transparencyLimit, 1, "$mat.blend.transparency.limit", 0, 0);
int transparencyDepth = source->ray_depth_tra;
result->AddProperty(&transparencyDepth, 1, "$mat.blend.transparency.depth", 0, 0);
float transparencyGlossAmount = source->gloss_tra;
result->AddProperty(&transparencyGlossAmount, 1, "$mat.blend.transparency.glossAmount", 0, 0);
float transparencyGlossThreshold = source->adapt_thresh_tra;
result->AddProperty(&transparencyGlossThreshold, 1, "$mat.blend.transparency.glossThreshold", 0, 0);
int transparencyGlossSamples = source->samp_gloss_tra;
result->AddProperty(&transparencyGlossSamples, 1, "$mat.blend.transparency.glossSamples", 0, 0);
int mirrorUse = source->mode & MA_RAYMIRROR ? 1 : 0;
result->AddProperty(&mirrorUse, 1, "$mat.blend.mirror.use", 0, 0);
float mirrorReflectivity = source->ray_mirror;
result->AddProperty(&mirrorReflectivity, 1, "$mat.blend.mirror.reflectivity", 0, 0);
aiColor3D mirrorColor(source->mirr, source->mirg, source->mirb);
result->AddProperty(&mirrorColor, 1, "$mat.blend.mirror.color", 0, 0);
float mirrorFresnel = source->fresnel_mir;
result->AddProperty(&mirrorFresnel, 1, "$mat.blend.mirror.fresnel", 0, 0);
float mirrorBlend = source->fresnel_mir_i;
result->AddProperty(&mirrorBlend, 1, "$mat.blend.mirror.blend", 0, 0);
int mirrorDepth = source->ray_depth;
result->AddProperty(&mirrorDepth, 1, "$mat.blend.mirror.depth", 0, 0);
float mirrorMaxDist = source->dist_mir;
result->AddProperty(&mirrorMaxDist, 1, "$mat.blend.mirror.maxDist", 0, 0);
int mirrorFadeTo = source->fadeto_mir;
result->AddProperty(&mirrorFadeTo, 1, "$mat.blend.mirror.fadeTo", 0, 0);
float mirrorGlossAmount = source->gloss_mir;
result->AddProperty(&mirrorGlossAmount, 1, "$mat.blend.mirror.glossAmount", 0, 0);
float mirrorGlossThreshold = source->adapt_thresh_mir;
result->AddProperty(&mirrorGlossThreshold, 1, "$mat.blend.mirror.glossThreshold", 0, 0);
int mirrorGlossSamples = source->samp_gloss_mir;
result->AddProperty(&mirrorGlossSamples, 1, "$mat.blend.mirror.glossSamples", 0, 0);
float mirrorGlossAnisotropic = source->aniso_gloss_mir;
result->AddProperty(&mirrorGlossAnisotropic, 1, "$mat.blend.mirror.glossAnisotropic", 0, 0);
}
void BlenderImporter::BuildMaterials(ConversionData& conv_data)
{
conv_data.materials->reserve(conv_data.materials_raw.size());
BuildDefaultMaterial(conv_data);
for(std::shared_ptr<Material> mat : conv_data.materials_raw) {
// reset per material global counters // reset per material global counters
for (size_t i = 0; i < sizeof(conv_data.next_texture)/sizeof(conv_data.next_texture[0]);++i) { for (size_t i = 0; i < sizeof(conv_data.next_texture)/sizeof(conv_data.next_texture[0]);++i) {
@ -604,7 +720,6 @@ void BlenderImporter::BuildMaterials(ConversionData& conv_data)
aiString name = aiString(mat->id.name+2); // skip over the name prefix 'MA' aiString name = aiString(mat->id.name+2); // skip over the name prefix 'MA'
mout->AddProperty(&name,AI_MATKEY_NAME); mout->AddProperty(&name,AI_MATKEY_NAME);
// basic material colors // basic material colors
aiColor3D col(mat->r,mat->g,mat->b); aiColor3D col(mat->r,mat->g,mat->b);
if (mat->r || mat->g || mat->b ) { if (mat->r || mat->g || mat->b ) {
@ -631,6 +746,12 @@ void BlenderImporter::BuildMaterials(ConversionData& conv_data)
col = aiColor3D(mat->ambr,mat->ambg,mat->ambb); col = aiColor3D(mat->ambr,mat->ambg,mat->ambb);
mout->AddProperty(&col,1,AI_MATKEY_COLOR_AMBIENT); mout->AddProperty(&col,1,AI_MATKEY_COLOR_AMBIENT);
// is mirror enabled?
if( mat->mode & MA_RAYMIRROR ) {
const float ray_mirror = mat->ray_mirror;
mout->AddProperty(&ray_mirror,1,AI_MATKEY_REFLECTIVITY);
}
col = aiColor3D(mat->mirr,mat->mirg,mat->mirb); col = aiColor3D(mat->mirr,mat->mirg,mat->mirb);
mout->AddProperty(&col,1,AI_MATKEY_COLOR_REFLECTIVE); mout->AddProperty(&col,1,AI_MATKEY_COLOR_REFLECTIVE);
@ -641,6 +762,8 @@ void BlenderImporter::BuildMaterials(ConversionData& conv_data)
ResolveTexture(mout,mat.get(),mat->mtex[i].get(),conv_data); ResolveTexture(mout,mat.get(),mat->mtex[i].get(),conv_data);
} }
AddBlendParams(mout, mat.get());
} }
} }
@ -716,7 +839,7 @@ void BlenderImporter::ConvertMesh(const Scene& /*in*/, const Object* /*obj*/, co
temp->reserve(temp->size() + per_mat.size()); temp->reserve(temp->size() + per_mat.size());
std::map<size_t,size_t> mat_num_to_mesh_idx; std::map<size_t,size_t> mat_num_to_mesh_idx;
for_each(MyPair& it, per_mat) { for(MyPair& it : per_mat) {
mat_num_to_mesh_idx[it.first] = temp->size(); mat_num_to_mesh_idx[it.first] = temp->size();
temp->push_back(new aiMesh()); temp->push_back(new aiMesh());
@ -743,8 +866,8 @@ void BlenderImporter::ConvertMesh(const Scene& /*in*/, const Object* /*obj*/, co
ThrowException("Material index is out of range"); ThrowException("Material index is out of range");
} }
boost::shared_ptr<Material> mat = mesh->mat[it.first]; std::shared_ptr<Material> mat = mesh->mat[it.first];
const std::deque< boost::shared_ptr<Material> >::iterator has = std::find( const std::deque< std::shared_ptr<Material> >::iterator has = std::find(
conv_data.materials_raw.begin(), conv_data.materials_raw.begin(),
conv_data.materials_raw.end(),mat conv_data.materials_raw.end(),mat
); );
@ -995,12 +1118,13 @@ void BlenderImporter::ConvertMesh(const Scene& /*in*/, const Object* /*obj*/, co
const aiFace& f = out->mFaces[out->mNumFaces++]; const aiFace& f = out->mFaces[out->mNumFaces++];
aiColor4D* vo = &out->mColors[0][out->mNumVertices]; aiColor4D* vo = &out->mColors[0][out->mNumVertices];
const ai_real scaleZeroToOne = 1.f/255.f;
for (unsigned int j = 0; j < f.mNumIndices; ++j,++vo,++out->mNumVertices) { for (unsigned int j = 0; j < f.mNumIndices; ++j,++vo,++out->mNumVertices) {
const MLoopCol& col = mesh->mloopcol[v.loopstart + j]; const MLoopCol& col = mesh->mloopcol[v.loopstart + j];
vo->r = col.r; vo->r = ai_real(col.r) * scaleZeroToOne;
vo->g = col.g; vo->g = ai_real(col.g) * scaleZeroToOne;
vo->b = col.b; vo->b = ai_real(col.b) * scaleZeroToOne;
vo->a = col.a; vo->a = ai_real(col.a) * scaleZeroToOne;
} }
} }
@ -1043,7 +1167,24 @@ aiLight* BlenderImporter::ConvertLight(const Scene& /*in*/, const Object* obj, c
// blender orients directional lights as facing toward -z // blender orients directional lights as facing toward -z
out->mDirection = aiVector3D(0.f, 0.f, -1.f); out->mDirection = aiVector3D(0.f, 0.f, -1.f);
out->mUp = aiVector3D(0.f, 1.f, 0.f);
break; break;
case Lamp::Type_Area:
out->mType = aiLightSource_AREA;
if (lamp->area_shape == 0) {
out->mSize = aiVector2D(lamp->area_size, lamp->area_size);
}
else {
out->mSize = aiVector2D(lamp->area_size, lamp->area_sizey);
}
// blender orients directional lights as facing toward -z
out->mDirection = aiVector3D(0.f, 0.f, -1.f);
out->mUp = aiVector3D(0.f, 1.f, 0.f);
break;
default: default:
break; break;
} }
@ -1151,7 +1292,7 @@ aiNode* BlenderImporter::ConvertNode(const Scene& in, const Object* obj, Convers
if (children.size()) { if (children.size()) {
node->mNumChildren = static_cast<unsigned int>(children.size()); node->mNumChildren = static_cast<unsigned int>(children.size());
aiNode** nd = node->mChildren = new aiNode*[node->mNumChildren](); aiNode** nd = node->mChildren = new aiNode*[node->mNumChildren]();
for_each (const Object* nobj,children) { for (const Object* nobj :children) {
*nd = ConvertNode(in,nobj,conv_data,node->mTransformation * parentTransform); *nd = ConvertNode(in,nobj,conv_data,node->mTransformation * parentTransform);
(*nd++)->mParent = node; (*nd++)->mParent = node;
} }

View File

@ -46,7 +46,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "BaseImporter.h" #include "BaseImporter.h"
#include "LogAux.h" #include "LogAux.h"
#include <boost/shared_ptr.hpp> #include <memory>
struct aiNode; struct aiNode;
struct aiMesh; struct aiMesh;
@ -133,7 +133,7 @@ protected:
// -------------------- // --------------------
void ParseBlendFile(Blender::FileDatabase& out, void ParseBlendFile(Blender::FileDatabase& out,
boost::shared_ptr<IOStream> stream std::shared_ptr<IOStream> stream
); );
// -------------------- // --------------------
@ -179,9 +179,18 @@ private:
); );
// -------------------- // --------------------
void BuildDefaultMaterial(
Blender::ConversionData& conv_data
);
void AddBlendParams(
aiMaterial* result,
const Blender::Material* source
);
void BuildMaterials( void BuildMaterials(
Blender::ConversionData& conv_data Blender::ConversionData& conv_data
) ; );
// -------------------- // --------------------
void ResolveTexture( void ResolveTexture(

View File

@ -47,10 +47,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "BlenderModifier.h" #include "BlenderModifier.h"
#include "SceneCombiner.h" #include "SceneCombiner.h"
#include "Subdivision.h" #include "Subdivision.h"
#include "../include/assimp/scene.h" #include <assimp/scene.h>
#include <boost/scoped_ptr.hpp> #include <memory>
#include <boost/scoped_array.hpp>
#include <boost/pointer_cast.hpp>
#include <functional> #include <functional>
@ -113,8 +111,8 @@ void BlenderModifierShowcase::ApplyModifiers(aiNode& out, ConversionData& conv_d
// we're allowed to dereference the pointers without risking to crash. We might still be // we're allowed to dereference the pointers without risking to crash. We might still be
// invoking UB btw - we're assuming that the ModifierData member of the respective modifier // invoking UB btw - we're assuming that the ModifierData member of the respective modifier
// structures is at offset sizeof(vftable) with no padding. // structures is at offset sizeof(vftable) with no padding.
const SharedModifierData* cur = boost::static_pointer_cast<const SharedModifierData> ( orig_object.modifiers.first.get() ); const SharedModifierData* cur = static_cast<const SharedModifierData *> ( orig_object.modifiers.first.get() );
for (; cur; cur = boost::static_pointer_cast<const SharedModifierData> ( cur->modifier.next.get() ), ++ful) { for (; cur; cur = static_cast<const SharedModifierData *> ( cur->modifier.next.get() ), ++ful) {
ai_assert(cur->dna_type); ai_assert(cur->dna_type);
const Structure* s = conv_data.db.dna.Get( cur->dna_type ); const Structure* s = conv_data.db.dna.Get( cur->dna_type );
@ -153,7 +151,7 @@ void BlenderModifierShowcase::ApplyModifiers(aiNode& out, ConversionData& conv_d
BlenderModifier* const modifier = *curmod; BlenderModifier* const modifier = *curmod;
if(modifier->IsActive(dat)) { if(modifier->IsActive(dat)) {
modifier->DoIt(out,conv_data,*boost::static_pointer_cast<const ElemBase>(cur),in,orig_object); modifier->DoIt(out,conv_data,*static_cast<const ElemBase *>(cur),in,orig_object);
cnt++; cnt++;
curgod = NULL; curgod = NULL;
@ -312,11 +310,11 @@ void BlenderModifier_Subdivision :: DoIt(aiNode& out, ConversionData& conv_data
return; return;
}; };
boost::scoped_ptr<Subdivider> subd(Subdivider::Create(algo)); std::unique_ptr<Subdivider> subd(Subdivider::Create(algo));
ai_assert(subd); ai_assert(subd);
aiMesh** const meshes = &conv_data.meshes[conv_data.meshes->size() - out.mNumMeshes]; aiMesh** const meshes = &conv_data.meshes[conv_data.meshes->size() - out.mNumMeshes];
boost::scoped_array<aiMesh*> tempmeshes(new aiMesh*[out.mNumMeshes]()); std::unique_ptr<aiMesh*[]> tempmeshes(new aiMesh*[out.mNumMeshes]());
subd->Subdivide(meshes,out.mNumMeshes,tempmeshes.get(),std::max( mir.renderLevels, mir.levels ),true); subd->Subdivide(meshes,out.mNumMeshes,tempmeshes.get(),std::max( mir.renderLevels, mir.levels ),true);
std::copy(tempmeshes.get(),tempmeshes.get()+out.mNumMeshes,meshes); std::copy(tempmeshes.get(),tempmeshes.get()+out.mNumMeshes,meshes);

View File

@ -46,8 +46,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "BlenderIntermediate.h" #include "BlenderIntermediate.h"
#include "TinyFormatter.h" #include "TinyFormatter.h"
namespace Assimp { namespace Assimp {
namespace Blender { namespace Blender {
// ------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------
/** Dummy base class for all blender modifiers. Modifiers are reused between imports, so /** Dummy base class for all blender modifiers. Modifiers are reused between imports, so
@ -56,8 +57,8 @@ namespace Assimp {
class BlenderModifier class BlenderModifier
{ {
public: public:
virtual ~BlenderModifier() { virtual ~BlenderModifier() {
// empty
} }
public: public:

View File

@ -2,7 +2,7 @@
Open Asset Import Library (ASSIMP) Open Asset Import Library (ASSIMP)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2010, ASSIMP Development Team Copyright (c) 2006-2016, ASSIMP Development Team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -64,7 +64,7 @@ template <> void Structure :: Convert<Object> (
ReadFieldArray2<ErrorPolicy_Warn>(dest.parentinv,"parentinv",db); ReadFieldArray2<ErrorPolicy_Warn>(dest.parentinv,"parentinv",db);
ReadFieldArray<ErrorPolicy_Warn>(dest.parsubstr,"parsubstr",db); ReadFieldArray<ErrorPolicy_Warn>(dest.parsubstr,"parsubstr",db);
{ {
boost::shared_ptr<Object> parent; std::shared_ptr<Object> parent;
ReadFieldPtr<ErrorPolicy_Warn>(parent,"*parent",db); ReadFieldPtr<ErrorPolicy_Warn>(parent,"*parent",db);
dest.parent = parent.get(); dest.parent = parent.get();
} }
@ -206,6 +206,10 @@ template <> void Structure :: Convert<Lamp> (
ReadField<ErrorPolicy_Igno>(dest.att2,"att2",db); ReadField<ErrorPolicy_Igno>(dest.att2,"att2",db);
ReadField<ErrorPolicy_Igno>((int&)dest.falloff_type,"falloff_type",db); ReadField<ErrorPolicy_Igno>((int&)dest.falloff_type,"falloff_type",db);
ReadField<ErrorPolicy_Igno>(dest.sun_brightness,"sun_brightness",db); ReadField<ErrorPolicy_Igno>(dest.sun_brightness,"sun_brightness",db);
ReadField<ErrorPolicy_Igno>(dest.area_size,"area_size",db);
ReadField<ErrorPolicy_Igno>(dest.area_sizey,"area_sizey",db);
ReadField<ErrorPolicy_Igno>(dest.area_sizez,"area_sizez",db);
ReadField<ErrorPolicy_Igno>(dest.area_shape,"area_shape",db);
db.reader->IncPtr(size); db.reader->IncPtr(size);
} }
@ -297,7 +301,6 @@ template <> void Structure :: Convert<Material> (
const FileDatabase& db const FileDatabase& db
) const ) const
{ {
ReadField<ErrorPolicy_Fail>(dest.id,"id",db); ReadField<ErrorPolicy_Fail>(dest.id,"id",db);
ReadField<ErrorPolicy_Warn>(dest.r,"r",db); ReadField<ErrorPolicy_Warn>(dest.r,"r",db);
ReadField<ErrorPolicy_Warn>(dest.g,"g",db); ReadField<ErrorPolicy_Warn>(dest.g,"g",db);
@ -313,9 +316,11 @@ template <> void Structure :: Convert<Material> (
ReadField<ErrorPolicy_Igno>(dest.mirg,"mirg",db); ReadField<ErrorPolicy_Igno>(dest.mirg,"mirg",db);
ReadField<ErrorPolicy_Igno>(dest.mirb,"mirb",db); ReadField<ErrorPolicy_Igno>(dest.mirb,"mirb",db);
ReadField<ErrorPolicy_Warn>(dest.emit,"emit",db); ReadField<ErrorPolicy_Warn>(dest.emit,"emit",db);
ReadField<ErrorPolicy_Igno>(dest.ray_mirror,"ray_mirror",db);
ReadField<ErrorPolicy_Warn>(dest.alpha,"alpha",db); ReadField<ErrorPolicy_Warn>(dest.alpha,"alpha",db);
ReadField<ErrorPolicy_Igno>(dest.ref,"ref",db); ReadField<ErrorPolicy_Igno>(dest.ref,"ref",db);
ReadField<ErrorPolicy_Igno>(dest.translucency,"translucency",db); ReadField<ErrorPolicy_Igno>(dest.translucency,"translucency",db);
ReadField<ErrorPolicy_Igno>(dest.mode,"mode",db);
ReadField<ErrorPolicy_Igno>(dest.roughness,"roughness",db); ReadField<ErrorPolicy_Igno>(dest.roughness,"roughness",db);
ReadField<ErrorPolicy_Igno>(dest.darkness,"darkness",db); ReadField<ErrorPolicy_Igno>(dest.darkness,"darkness",db);
ReadField<ErrorPolicy_Igno>(dest.refrac,"refrac",db); ReadField<ErrorPolicy_Igno>(dest.refrac,"refrac",db);
@ -324,6 +329,91 @@ template <> void Structure :: Convert<Material> (
ReadField<ErrorPolicy_Warn>(dest.spec_shader,"spec_shader",db); ReadField<ErrorPolicy_Warn>(dest.spec_shader,"spec_shader",db);
ReadFieldPtr<ErrorPolicy_Igno>(dest.mtex,"*mtex",db); ReadFieldPtr<ErrorPolicy_Igno>(dest.mtex,"*mtex",db);
ReadField<ErrorPolicy_Igno>(dest.amb, "amb", db);
ReadField<ErrorPolicy_Igno>(dest.ang, "ang", db);
ReadField<ErrorPolicy_Igno>(dest.spectra, "spectra", db);
ReadField<ErrorPolicy_Igno>(dest.spec, "spec", db);
ReadField<ErrorPolicy_Igno>(dest.zoffs, "zoffs", db);
ReadField<ErrorPolicy_Igno>(dest.add, "add", db);
ReadField<ErrorPolicy_Igno>(dest.fresnel_mir, "fresnel_mir", db);
ReadField<ErrorPolicy_Igno>(dest.fresnel_mir_i, "fresnel_mir_i", db);
ReadField<ErrorPolicy_Igno>(dest.fresnel_tra, "fresnel_tra", db);
ReadField<ErrorPolicy_Igno>(dest.fresnel_tra_i, "fresnel_tra_i", db);
ReadField<ErrorPolicy_Igno>(dest.filter, "filter", db);
ReadField<ErrorPolicy_Igno>(dest.tx_limit, "tx_limit", db);
ReadField<ErrorPolicy_Igno>(dest.tx_falloff, "tx_falloff", db);
ReadField<ErrorPolicy_Igno>(dest.gloss_mir, "gloss_mir", db);
ReadField<ErrorPolicy_Igno>(dest.gloss_tra, "gloss_tra", db);
ReadField<ErrorPolicy_Igno>(dest.adapt_thresh_mir, "adapt_thresh_mir", db);
ReadField<ErrorPolicy_Igno>(dest.adapt_thresh_tra, "adapt_thresh_tra", db);
ReadField<ErrorPolicy_Igno>(dest.aniso_gloss_mir, "aniso_gloss_mir", db);
ReadField<ErrorPolicy_Igno>(dest.dist_mir, "dist_mir", db);
ReadField<ErrorPolicy_Igno>(dest.hasize, "hasize", db);
ReadField<ErrorPolicy_Igno>(dest.flaresize, "flaresize", db);
ReadField<ErrorPolicy_Igno>(dest.subsize, "subsize", db);
ReadField<ErrorPolicy_Igno>(dest.flareboost, "flareboost", db);
ReadField<ErrorPolicy_Igno>(dest.strand_sta, "strand_sta", db);
ReadField<ErrorPolicy_Igno>(dest.strand_end, "strand_end", db);
ReadField<ErrorPolicy_Igno>(dest.strand_ease, "strand_ease", db);
ReadField<ErrorPolicy_Igno>(dest.strand_surfnor, "strand_surfnor", db);
ReadField<ErrorPolicy_Igno>(dest.strand_min, "strand_min", db);
ReadField<ErrorPolicy_Igno>(dest.strand_widthfade, "strand_widthfade", db);
ReadField<ErrorPolicy_Igno>(dest.sbias, "sbias", db);
ReadField<ErrorPolicy_Igno>(dest.lbias, "lbias", db);
ReadField<ErrorPolicy_Igno>(dest.shad_alpha, "shad_alpha", db);
ReadField<ErrorPolicy_Igno>(dest.param, "param", db);
ReadField<ErrorPolicy_Igno>(dest.rms, "rms", db);
ReadField<ErrorPolicy_Igno>(dest.rampfac_col, "rampfac_col", db);
ReadField<ErrorPolicy_Igno>(dest.rampfac_spec, "rampfac_spec", db);
ReadField<ErrorPolicy_Igno>(dest.friction, "friction", db);
ReadField<ErrorPolicy_Igno>(dest.fh, "fh", db);
ReadField<ErrorPolicy_Igno>(dest.reflect, "reflect", db);
ReadField<ErrorPolicy_Igno>(dest.fhdist, "fhdist", db);
ReadField<ErrorPolicy_Igno>(dest.xyfrict, "xyfrict", db);
ReadField<ErrorPolicy_Igno>(dest.sss_radius, "sss_radius", db);
ReadField<ErrorPolicy_Igno>(dest.sss_col, "sss_col", db);
ReadField<ErrorPolicy_Igno>(dest.sss_error, "sss_error", db);
ReadField<ErrorPolicy_Igno>(dest.sss_scale, "sss_scale", db);
ReadField<ErrorPolicy_Igno>(dest.sss_ior, "sss_ior", db);
ReadField<ErrorPolicy_Igno>(dest.sss_colfac, "sss_colfac", db);
ReadField<ErrorPolicy_Igno>(dest.sss_texfac, "sss_texfac", db);
ReadField<ErrorPolicy_Igno>(dest.sss_front, "sss_front", db);
ReadField<ErrorPolicy_Igno>(dest.sss_back, "sss_back", db);
ReadField<ErrorPolicy_Igno>(dest.material_type, "material_type", db);
ReadField<ErrorPolicy_Igno>(dest.flag, "flag", db);
ReadField<ErrorPolicy_Igno>(dest.ray_depth, "ray_depth", db);
ReadField<ErrorPolicy_Igno>(dest.ray_depth_tra, "ray_depth_tra", db);
ReadField<ErrorPolicy_Igno>(dest.samp_gloss_mir, "samp_gloss_mir", db);
ReadField<ErrorPolicy_Igno>(dest.samp_gloss_tra, "samp_gloss_tra", db);
ReadField<ErrorPolicy_Igno>(dest.fadeto_mir, "fadeto_mir", db);
ReadField<ErrorPolicy_Igno>(dest.shade_flag, "shade_flag", db);
ReadField<ErrorPolicy_Igno>(dest.flarec, "flarec", db);
ReadField<ErrorPolicy_Igno>(dest.starc, "starc", db);
ReadField<ErrorPolicy_Igno>(dest.linec, "linec", db);
ReadField<ErrorPolicy_Igno>(dest.ringc, "ringc", db);
ReadField<ErrorPolicy_Igno>(dest.pr_lamp, "pr_lamp", db);
ReadField<ErrorPolicy_Igno>(dest.pr_texture, "pr_texture", db);
ReadField<ErrorPolicy_Igno>(dest.ml_flag, "ml_flag", db);
ReadField<ErrorPolicy_Igno>(dest.diff_shader, "diff_shader", db);
ReadField<ErrorPolicy_Igno>(dest.spec_shader, "spec_shader", db);
ReadField<ErrorPolicy_Igno>(dest.texco, "texco", db);
ReadField<ErrorPolicy_Igno>(dest.mapto, "mapto", db);
ReadField<ErrorPolicy_Igno>(dest.ramp_show, "ramp_show", db);
ReadField<ErrorPolicy_Igno>(dest.pad3, "pad3", db);
ReadField<ErrorPolicy_Igno>(dest.dynamode, "dynamode", db);
ReadField<ErrorPolicy_Igno>(dest.pad2, "pad2", db);
ReadField<ErrorPolicy_Igno>(dest.sss_flag, "sss_flag", db);
ReadField<ErrorPolicy_Igno>(dest.sss_preset, "sss_preset", db);
ReadField<ErrorPolicy_Igno>(dest.shadowonly_flag, "shadowonly_flag", db);
ReadField<ErrorPolicy_Igno>(dest.index, "index", db);
ReadField<ErrorPolicy_Igno>(dest.vcol_alpha, "vcol_alpha", db);
ReadField<ErrorPolicy_Igno>(dest.pad4, "pad4", db);
ReadField<ErrorPolicy_Igno>(dest.seed1, "seed1", db);
ReadField<ErrorPolicy_Igno>(dest.seed2, "seed2", db);
db.reader->IncPtr(size); db.reader->IncPtr(size);
} }
@ -335,7 +425,7 @@ template <> void Structure :: Convert<MTexPoly> (
{ {
{ {
boost::shared_ptr<Image> tpage; std::shared_ptr<Image> tpage;
ReadFieldPtr<ErrorPolicy_Igno>(tpage,"*tpage",db); ReadFieldPtr<ErrorPolicy_Igno>(tpage,"*tpage",db);
dest.tpage = tpage.get(); dest.tpage = tpage.get();
} }

View File

@ -47,7 +47,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "BlenderDNA.h" #include "BlenderDNA.h"
namespace Assimp { namespace Assimp {
namespace Blender { namespace Blender {
// Minor parts of this file are extracts from blender data structures, // Minor parts of this file are extracts from blender data structures,
// declared in the ./source/blender/makesdna directory. // declared in the ./source/blender/makesdna directory.
@ -73,7 +73,7 @@ namespace Assimp {
// //
// * Pointers to other structures or primitive types are allowed. // * Pointers to other structures or primitive types are allowed.
// No references or double pointers or arrays of pointers. // No references or double pointers or arrays of pointers.
// A pointer to a T is normally written as boost::shared_ptr, while a // A pointer to a T is normally written as std::shared_ptr, while a
// pointer to an array of elements is written as boost:: // pointer to an array of elements is written as boost::
// shared_array. To avoid cyclic pointers, use raw pointers in // shared_array. To avoid cyclic pointers, use raw pointers in
// one direction. // one direction.
@ -98,6 +98,8 @@ struct Object;
struct MTex; struct MTex;
struct Image; struct Image;
#include <memory>
#define AI_BLEND_MESH_MAX_VERTS 2000000000L #define AI_BLEND_MESH_MAX_VERTS 2000000000L
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
@ -110,8 +112,8 @@ struct ID : ElemBase {
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
struct ListBase : ElemBase { struct ListBase : ElemBase {
boost::shared_ptr<ElemBase> first; std::shared_ptr<ElemBase> first;
boost::shared_ptr<ElemBase> last; std::shared_ptr<ElemBase> last;
}; };
@ -119,14 +121,14 @@ struct ListBase : ElemBase {
struct PackedFile : ElemBase { struct PackedFile : ElemBase {
int size WARN; int size WARN;
int seek WARN; int seek WARN;
boost::shared_ptr< FileOffset > data WARN; std::shared_ptr< FileOffset > data WARN;
}; };
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
struct GroupObject : ElemBase { struct GroupObject : ElemBase {
boost::shared_ptr<GroupObject> prev,next FAIL; std::shared_ptr<GroupObject> prev,next FAIL;
boost::shared_ptr<Object> ob; std::shared_ptr<Object> ob;
}; };
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
@ -134,7 +136,7 @@ struct Group : ElemBase {
ID id FAIL; ID id FAIL;
int layer; int layer;
boost::shared_ptr<GroupObject> gobject; std::shared_ptr<GroupObject> gobject;
}; };
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
@ -173,7 +175,7 @@ struct MLoopUV : ElemBase {
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
// Note that red and blue are not swapped, as with MCol // Note that red and blue are not swapped, as with MCol
struct MLoopCol : ElemBase { struct MLoopCol : ElemBase {
char r, g, b, a; unsigned char r, g, b, a;
}; };
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
@ -222,7 +224,7 @@ struct MTFace : ElemBase {
short tile; short tile;
short unwrap; short unwrap;
// boost::shared_ptr<Image> tpage; // std::shared_ptr<Image> tpage;
}; };
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
@ -239,6 +241,11 @@ struct MDeformVert : ElemBase {
}; };
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
#define MA_RAYMIRROR 0x40000
#define MA_TRANSPARENCY 0x10000
#define MA_RAYTRANSP 0x20000
#define MA_ZTRANSP 0x00040
struct Material : ElemBase { struct Material : ElemBase {
ID id FAIL; ID id FAIL;
@ -248,19 +255,104 @@ struct Material : ElemBase {
float ambr,ambg,ambb WARN; float ambr,ambg,ambb WARN;
float mirr,mirg,mirb; float mirr,mirg,mirb;
float emit WARN; float emit WARN;
float ray_mirror;
float alpha WARN; float alpha WARN;
float ref; float ref;
float translucency; float translucency;
int mode;
float roughness; float roughness;
float darkness; float darkness;
float refrac; float refrac;
boost::shared_ptr<Group> group;
float amb;
float ang;
float spectra;
float spec;
float zoffs;
float add;
float fresnel_mir;
float fresnel_mir_i;
float fresnel_tra;
float fresnel_tra_i;
float filter;
float tx_limit;
float tx_falloff;
float gloss_mir;
float gloss_tra;
float adapt_thresh_mir;
float adapt_thresh_tra;
float aniso_gloss_mir;
float dist_mir;
float hasize;
float flaresize;
float subsize;
float flareboost;
float strand_sta;
float strand_end;
float strand_ease;
float strand_surfnor;
float strand_min;
float strand_widthfade;
float sbias;
float lbias;
float shad_alpha;
float param;
float rms;
float rampfac_col;
float rampfac_spec;
float friction;
float fh;
float reflect;
float fhdist;
float xyfrict;
float sss_radius;
float sss_col;
float sss_error;
float sss_scale;
float sss_ior;
float sss_colfac;
float sss_texfac;
float sss_front;
float sss_back;
short material_type;
short flag;
short ray_depth;
short ray_depth_tra;
short samp_gloss_mir;
short samp_gloss_tra;
short fadeto_mir;
short shade_flag;
short flarec;
short starc;
short linec;
short ringc;
short pr_lamp;
short pr_texture;
short ml_flag;
short texco;
short mapto;
short ramp_show;
short pad3;
short dynamode;
short pad2;
short sss_flag;
short sss_preset;
short shadowonly_flag;
short index;
short vcol_alpha;
short pad4;
char seed1;
char seed2;
std::shared_ptr<Group> group;
short diff_shader WARN; short diff_shader WARN;
short spec_shader WARN; short spec_shader WARN;
boost::shared_ptr<MTex> mtex[18]; std::shared_ptr<MTex> mtex[18];
}; };
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
@ -291,7 +383,7 @@ struct Mesh : ElemBase {
vector<MDeformVert> dvert; vector<MDeformVert> dvert;
vector<MCol> mcol; vector<MCol> mcol;
vector< boost::shared_ptr<Material> > mat FAIL; vector< std::shared_ptr<Material> > mat FAIL;
}; };
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
@ -300,7 +392,7 @@ struct Library : ElemBase {
char name[240] WARN; char name[240] WARN;
char filename[240] FAIL; char filename[240] FAIL;
boost::shared_ptr<Library> parent WARN; std::shared_ptr<Library> parent WARN;
}; };
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
@ -365,8 +457,8 @@ struct Lamp : ElemBase {
//short ray_samp, ray_sampy, ray_sampz; //short ray_samp, ray_sampy, ray_sampz;
//short ray_samp_type; //short ray_samp_type;
//short area_shape; short area_shape;
//float area_size, area_sizey, area_sizez; float area_size, area_sizey, area_sizez;
//float adapt_thresh; //float adapt_thresh;
//short ray_samp_method; //short ray_samp_method;
@ -440,8 +532,8 @@ struct ModifierData : ElemBase {
eModifierType_ShapeKey eModifierType_ShapeKey
}; };
boost::shared_ptr<ElemBase> next WARN; std::shared_ptr<ElemBase> next WARN;
boost::shared_ptr<ElemBase> prev WARN; std::shared_ptr<ElemBase> prev WARN;
int type, mode; int type, mode;
char name[32]; char name[32];
@ -485,7 +577,7 @@ struct MirrorModifierData : ElemBase {
short axis, flag; short axis, flag;
float tolerance; float tolerance;
boost::shared_ptr<Object> mirror_ob; std::shared_ptr<Object> mirror_ob;
}; };
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
@ -513,11 +605,11 @@ struct Object : ElemBase {
char parsubstr[32] WARN; char parsubstr[32] WARN;
Object* parent WARN; Object* parent WARN;
boost::shared_ptr<Object> track WARN; std::shared_ptr<Object> track WARN;
boost::shared_ptr<Object> proxy,proxy_from,proxy_group WARN; std::shared_ptr<Object> proxy,proxy_from,proxy_group WARN;
boost::shared_ptr<Group> dup_group WARN; std::shared_ptr<Group> dup_group WARN;
boost::shared_ptr<ElemBase> data FAIL; std::shared_ptr<ElemBase> data FAIL;
ListBase modifiers; ListBase modifiers;
}; };
@ -526,17 +618,17 @@ struct Object : ElemBase {
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
struct Base : ElemBase { struct Base : ElemBase {
Base* prev WARN; Base* prev WARN;
boost::shared_ptr<Base> next WARN; std::shared_ptr<Base> next WARN;
boost::shared_ptr<Object> object WARN; std::shared_ptr<Object> object WARN;
}; };
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
struct Scene : ElemBase { struct Scene : ElemBase {
ID id FAIL; ID id FAIL;
boost::shared_ptr<Object> camera WARN; std::shared_ptr<Object> camera WARN;
boost::shared_ptr<World> world WARN; std::shared_ptr<World> world WARN;
boost::shared_ptr<Base> basact WARN; std::shared_ptr<Base> basact WARN;
ListBase base; ListBase base;
}; };
@ -560,7 +652,7 @@ struct Image : ElemBase {
//unsigned int bindcode; //unsigned int bindcode;
//unsigned int *repbind; //unsigned int *repbind;
boost::shared_ptr<PackedFile> packedfile; std::shared_ptr<PackedFile> packedfile;
//struct PreviewImage * preview; //struct PreviewImage * preview;
float lastupdate; float lastupdate;
@ -646,7 +738,7 @@ struct Tex : ElemBase {
//bNodeTree *nodetree; //bNodeTree *nodetree;
//Ipo *ipo; //Ipo *ipo;
boost::shared_ptr<Image> ima WARN; std::shared_ptr<Image> ima WARN;
//PluginTex *plugin; //PluginTex *plugin;
//ColorBand *coba; //ColorBand *coba;
//EnvMap *env; //EnvMap *env;
@ -713,8 +805,8 @@ struct MTex : ElemBase {
MapType mapto; MapType mapto;
BlendType blendtype; BlendType blendtype;
boost::shared_ptr<Object> object; std::shared_ptr<Object> object;
boost::shared_ptr<Tex> tex; std::shared_ptr<Tex> tex;
char uvname[32]; char uvname[32];
Projection projx,projy,projz; Projection projx,projy,projz;

View File

@ -2,7 +2,7 @@
Open Asset Import Library (ASSIMP) Open Asset Import Library (ASSIMP)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2010, ASSIMP Development Team Copyright (c) 2006-2016, ASSIMP Development Team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -48,8 +48,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "BlenderScene.h" #include "BlenderScene.h"
namespace Assimp { namespace Assimp {
namespace Blender { namespace Blender {
template <> void Structure :: Convert<Object> ( template <> void Structure :: Convert<Object> (
Object& dest, Object& dest,

View File

@ -2,7 +2,7 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2013, assimp team Copyright (c) 2006-2016, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -50,6 +50,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "BlenderBMesh.h" #include "BlenderBMesh.h"
#include "BlenderTessellator.h" #include "BlenderTessellator.h"
#include <stddef.h>
static const unsigned int BLEND_TESS_MAGIC = 0x83ed9ac3; static const unsigned int BLEND_TESS_MAGIC = 0x83ed9ac3;
#if ASSIMP_BLEND_WITH_GLU_TESSELLATE #if ASSIMP_BLEND_WITH_GLU_TESSELLATE
@ -140,7 +142,7 @@ void BlenderTessellatorGL::TriangulateDrawCalls( const TessDataGL& tessData )
{ {
// NOTE - Because we are supplying a callback to GLU_TESS_EDGE_FLAG_DATA we don't technically // NOTE - Because we are supplying a callback to GLU_TESS_EDGE_FLAG_DATA we don't technically
// need support for GL_TRIANGLE_STRIP and GL_TRIANGLE_FAN but we'll keep it here in case // need support for GL_TRIANGLE_STRIP and GL_TRIANGLE_FAN but we'll keep it here in case
// GLU tessellate changes or tristrips and fans are wanted. // GLU tessellate changes or tri-strips and fans are wanted.
// See: http://www.opengl.org/sdk/docs/man2/xhtml/gluTessCallback.xml // See: http://www.opengl.org/sdk/docs/man2/xhtml/gluTessCallback.xml
for ( unsigned int i = 0; i < tessData.drawCalls.size( ); ++i ) for ( unsigned int i = 0; i < tessData.drawCalls.size( ); ++i )
{ {
@ -164,7 +166,7 @@ void BlenderTessellatorGL::TriangulateDrawCalls( const TessDataGL& tessData )
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
void BlenderTessellatorGL::MakeFacesFromTris( const VertexGL* vertices, int vertexCount ) void BlenderTessellatorGL::MakeFacesFromTris( const VertexGL* vertices, int vertexCount )
{ {
int triangleCount = vertexCount / 3; const int triangleCount = vertexCount / 3;
for ( int i = 0; i < triangleCount; ++i ) for ( int i = 0; i < triangleCount; ++i )
{ {
int vertexBase = i * 3; int vertexBase = i * 3;
@ -175,7 +177,7 @@ void BlenderTessellatorGL::MakeFacesFromTris( const VertexGL* vertices, int vert
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
void BlenderTessellatorGL::MakeFacesFromTriStrip( const VertexGL* vertices, int vertexCount ) void BlenderTessellatorGL::MakeFacesFromTriStrip( const VertexGL* vertices, int vertexCount )
{ {
int triangleCount = vertexCount - 2; const int triangleCount = vertexCount - 2;
for ( int i = 0; i < triangleCount; ++i ) for ( int i = 0; i < triangleCount; ++i )
{ {
int vertexBase = i; int vertexBase = i;
@ -186,7 +188,7 @@ void BlenderTessellatorGL::MakeFacesFromTriStrip( const VertexGL* vertices, int
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
void BlenderTessellatorGL::MakeFacesFromTriFan( const VertexGL* vertices, int vertexCount ) void BlenderTessellatorGL::MakeFacesFromTriFan( const VertexGL* vertices, int vertexCount )
{ {
int triangleCount = vertexCount - 2; const int triangleCount = vertexCount - 2;
for ( int i = 0; i < triangleCount; ++i ) for ( int i = 0; i < triangleCount; ++i )
{ {
int vertexBase = i; int vertexBase = i;
@ -353,7 +355,7 @@ aiMatrix4x4 BlenderTessellatorP2T::GeneratePointTransformMatrix( const Blender::
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
void BlenderTessellatorP2T::TransformAndFlattenVectices( const aiMatrix4x4& transform, std::vector< Blender::PointP2T >& vertices ) const void BlenderTessellatorP2T::TransformAndFlattenVectices( const aiMatrix4x4& transform, std::vector< Blender::PointP2T >& vertices ) const
{ {
for ( unsigned int i = 0; i < vertices.size( ); ++i ) for ( size_t i = 0; i < vertices.size( ); ++i )
{ {
PointP2T& point = vertices[ i ]; PointP2T& point = vertices[ i ];
point.point3D = transform * point.point3D; point.point3D = transform * point.point3D;
@ -365,21 +367,16 @@ void BlenderTessellatorP2T::TransformAndFlattenVectices( const aiMatrix4x4& tran
void BlenderTessellatorP2T::ReferencePoints( std::vector< Blender::PointP2T >& points, std::vector< p2t::Point* >& pointRefs ) const void BlenderTessellatorP2T::ReferencePoints( std::vector< Blender::PointP2T >& points, std::vector< p2t::Point* >& pointRefs ) const
{ {
pointRefs.resize( points.size( ) ); pointRefs.resize( points.size( ) );
for ( unsigned int i = 0; i < points.size( ); ++i ) for ( size_t i = 0; i < points.size( ); ++i )
{ {
pointRefs[ i ] = &points[ i ].point2D; pointRefs[ i ] = &points[ i ].point2D;
} }
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// Yes this is filthy... but we have no choice
#define OffsetOf( Class, Member ) ( static_cast< unsigned int >( \
reinterpret_cast<uint8_t*>(&( reinterpret_cast< Class* >( NULL )->*( &Class::Member ) )) - \
static_cast<uint8_t*>(NULL) ) )
inline PointP2T& BlenderTessellatorP2T::GetActualPointStructure( p2t::Point& point ) const inline PointP2T& BlenderTessellatorP2T::GetActualPointStructure( p2t::Point& point ) const
{ {
unsigned int pointOffset = OffsetOf( PointP2T, point2D ); unsigned int pointOffset = offsetof( PointP2T, point2D );
PointP2T& pointStruct = *reinterpret_cast< PointP2T* >( reinterpret_cast< char* >( &point ) - pointOffset ); PointP2T& pointStruct = *reinterpret_cast< PointP2T* >( reinterpret_cast< char* >( &point ) - pointOffset );
if ( pointStruct.magic != static_cast<int>( BLEND_TESS_MAGIC ) ) if ( pointStruct.magic != static_cast<int>( BLEND_TESS_MAGIC ) )
{ {
@ -391,7 +388,7 @@ inline PointP2T& BlenderTessellatorP2T::GetActualPointStructure( p2t::Point& poi
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
void BlenderTessellatorP2T::MakeFacesFromTriangles( std::vector< p2t::Triangle* >& triangles ) const void BlenderTessellatorP2T::MakeFacesFromTriangles( std::vector< p2t::Triangle* >& triangles ) const
{ {
for ( unsigned int i = 0; i < triangles.size( ); ++i ) for ( size_t i = 0; i < triangles.size( ); ++i )
{ {
p2t::Triangle& Triangle = *triangles[ i ]; p2t::Triangle& Triangle = *triangles[ i ];
@ -415,9 +412,9 @@ float BlenderTessellatorP2T::FindLargestMatrixElem( const aiMatrix3x3& mtx ) con
{ {
float result = 0.0f; float result = 0.0f;
for ( int x = 0; x < 3; ++x ) for ( size_t x = 0; x < 3; ++x )
{ {
for ( int y = 0; y < 3; ++y ) for ( size_t y = 0; y < 3; ++y )
{ {
result = p2tMax( std::fabs( mtx[ x ][ y ] ), result ); result = p2tMax( std::fabs( mtx[ x ][ y ] ), result );
} }
@ -427,14 +424,14 @@ float BlenderTessellatorP2T::FindLargestMatrixElem( const aiMatrix3x3& mtx ) con
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// Aparently Assimp doesn't have matrix scaling // Apparently Assimp doesn't have matrix scaling
aiMatrix3x3 BlenderTessellatorP2T::ScaleMatrix( const aiMatrix3x3& mtx, float scale ) const aiMatrix3x3 BlenderTessellatorP2T::ScaleMatrix( const aiMatrix3x3& mtx, float scale ) const
{ {
aiMatrix3x3 result; aiMatrix3x3 result;
for ( int x = 0; x < 3; ++x ) for ( size_t x = 0; x < 3; ++x )
{ {
for ( int y = 0; y < 3; ++y ) for ( size_t y = 0; y < 3; ++y )
{ {
result[ x ][ y ] = mtx[ x ][ y ] * scale; result[ x ][ y ] = mtx[ x ][ y ] * scale;
} }
@ -448,7 +445,7 @@ aiMatrix3x3 BlenderTessellatorP2T::ScaleMatrix( const aiMatrix3x3& mtx, float sc
// Adapted from: http://missingbytes.blogspot.co.uk/2012/06/fitting-plane-to-point-cloud.html // Adapted from: http://missingbytes.blogspot.co.uk/2012/06/fitting-plane-to-point-cloud.html
aiVector3D BlenderTessellatorP2T::GetEigenVectorFromLargestEigenValue( const aiMatrix3x3& mtx ) const aiVector3D BlenderTessellatorP2T::GetEigenVectorFromLargestEigenValue( const aiMatrix3x3& mtx ) const
{ {
float scale = FindLargestMatrixElem( mtx ); const float scale = FindLargestMatrixElem( mtx );
aiMatrix3x3 mc = ScaleMatrix( mtx, 1.0f / scale ); aiMatrix3x3 mc = ScaleMatrix( mtx, 1.0f / scale );
mc = mc * mc * mc; mc = mc * mc * mc;
@ -473,20 +470,20 @@ PlaneP2T BlenderTessellatorP2T::FindLLSQPlane( const std::vector< PointP2T >& po
{ {
PlaneP2T result; PlaneP2T result;
aiVector3D sum( 0.0f ); aiVector3D sum( 0.0 );
for ( unsigned int i = 0; i < points.size( ); ++i ) for ( size_t i = 0; i < points.size( ); ++i )
{ {
sum += points[ i ].point3D; sum += points[ i ].point3D;
} }
result.centre = sum * ( 1.0f / points.size( ) ); result.centre = sum * (ai_real)( 1.0 / points.size( ) );
float sumXX = 0.0f; ai_real sumXX = 0.0;
float sumXY = 0.0f; ai_real sumXY = 0.0;
float sumXZ = 0.0f; ai_real sumXZ = 0.0;
float sumYY = 0.0f; ai_real sumYY = 0.0;
float sumYZ = 0.0f; ai_real sumYZ = 0.0;
float sumZZ = 0.0f; ai_real sumZZ = 0.0;
for ( unsigned int i = 0; i < points.size( ); ++i ) for ( size_t i = 0; i < points.size( ); ++i )
{ {
aiVector3D offset = points[ i ].point3D - result.centre; aiVector3D offset = points[ i ].point3D - result.centre;
sumXX += offset.x * offset.x; sumXX += offset.x * offset.x;
@ -499,7 +496,7 @@ PlaneP2T BlenderTessellatorP2T::FindLLSQPlane( const std::vector< PointP2T >& po
aiMatrix3x3 mtx( sumXX, sumXY, sumXZ, sumXY, sumYY, sumYZ, sumXZ, sumYZ, sumZZ ); aiMatrix3x3 mtx( sumXX, sumXY, sumXZ, sumXY, sumYY, sumYZ, sumXZ, sumYZ, sumZZ );
float det = mtx.Determinant( ); const ai_real det = mtx.Determinant( );
if ( det == 0.0f ) if ( det == 0.0f )
{ {
result.normal = aiVector3D( 0.0f ); result.normal = aiVector3D( 0.0f );

View File

@ -2,7 +2,7 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2013, assimp team Copyright (c) 2006-2016, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,

View File

@ -49,7 +49,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "./../include/assimp/cexport.h" #include "./../include/assimp/cexport.h"
#include "./../include/assimp/IOSystem.hpp" #include "./../include/assimp/IOSystem.hpp"
#include "./../include/assimp/DefaultLogger.hpp" #include "./../include/assimp/DefaultLogger.hpp"
#include <boost/foreach.hpp>
#include <stdint.h> #include <stdint.h>
#include <set> #include <set>
#include <vector> #include <vector>
@ -224,7 +223,7 @@ public:
virtual ~BlobIOSystem() virtual ~BlobIOSystem()
{ {
BOOST_FOREACH(BlobEntry& blobby, blobs) { for(BlobEntry& blobby : blobs) {
delete blobby.second; delete blobby.second;
} }
} }
@ -243,7 +242,7 @@ public:
{ {
// one must be the master // one must be the master
aiExportDataBlob* master = NULL, *cur; aiExportDataBlob* master = NULL, *cur;
BOOST_FOREACH(const BlobEntry& blobby, blobs) { for(const BlobEntry& blobby : blobs) {
if (blobby.first == AI_BLOBIO_MAGIC) { if (blobby.first == AI_BLOBIO_MAGIC) {
master = blobby.second; master = blobby.second;
break; break;
@ -257,7 +256,7 @@ public:
master->name.Set(""); master->name.Set("");
cur = master; cur = master;
BOOST_FOREACH(const BlobEntry& blobby, blobs) { for(const BlobEntry& blobby : blobs) {
if (blobby.second == master) { if (blobby.second == master) {
continue; continue;
} }

View File

@ -1,23 +0,0 @@
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

View File

@ -1,99 +0,0 @@
#ifndef BOOST_FOREACH
///////////////////////////////////////////////////////////////////////////////
// A stripped down version of FOREACH for
// illustration purposes. NOT FOR GENERAL USE.
// For a complete implementation, see BOOST_FOREACH at
// http://boost-sandbox.sourceforge.net/vault/index.php?directory=eric_niebler
//
// Copyright 2004 Eric Niebler.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Adapted to Assimp November 29th, 2008 (Alexander Gessler).
// Added code to handle both const and non-const iterators, simplified some
// parts.
///////////////////////////////////////////////////////////////////////////////
namespace boost {
namespace foreach_detail {
///////////////////////////////////////////////////////////////////////////////
// auto_any
struct auto_any_base
{
operator bool() const { return false; }
};
template<typename T>
struct auto_any : auto_any_base
{
auto_any(T const& t) : item(t) {}
mutable T item;
};
template<typename T>
T& auto_any_cast(auto_any_base const& any)
{
return static_cast<auto_any<T> const&>(any).item;
}
///////////////////////////////////////////////////////////////////////////////
// FOREACH helper function
template<typename T>
auto_any<typename T::const_iterator> begin(T const& t)
{
return t.begin();
}
template<typename T>
auto_any<typename T::const_iterator> end(T const& t)
{
return t.end();
}
// iterator
template<typename T>
bool done(auto_any_base const& cur, auto_any_base const& end, T&)
{
typedef typename T::iterator iter_type;
return auto_any_cast<iter_type>(cur) == auto_any_cast<iter_type>(end);
}
template<typename T>
void next(auto_any_base const& cur, T&)
{
++auto_any_cast<typename T::iterator>(cur);
}
template<typename T>
typename T::reference deref(auto_any_base const& cur, T&)
{
return *auto_any_cast<typename T::iterator>(cur);
}
template<typename T>
typename T::const_reference deref(auto_any_base const& cur, const T&)
{
return *auto_any_cast<typename T::iterator>(cur);
}
} // end foreach_detail
///////////////////////////////////////////////////////////////////////////////
// FOREACH
#define BOOST_FOREACH(item, container) \
if(boost::foreach_detail::auto_any_base const& foreach_magic_b = boost::foreach_detail::begin(container)) {} else \
if(boost::foreach_detail::auto_any_base const& foreach_magic_e = boost::foreach_detail::end(container)) {} else \
for(;!boost::foreach_detail::done(foreach_magic_b,foreach_magic_e,container); boost::foreach_detail::next(foreach_magic_b,container)) \
if (bool ugly_and_unique_break = false) {} else \
for(item = boost::foreach_detail::deref(foreach_magic_b,container); !ugly_and_unique_break; ugly_and_unique_break = true)
} // end boost
#endif

View File

@ -1,82 +0,0 @@
/* DEPRECATED! - use code/TinyFormatter.h instead.
*
*
* */
#ifndef AI_BOOST_FORMAT_DUMMY_INCLUDED
#define AI_BOOST_FORMAT_DUMMY_INCLUDED
#if (!defined BOOST_FORMAT_HPP) || (defined ASSIMP_FORCE_NOBOOST)
#include <string>
#include <vector>
#include <sstream>
namespace boost
{
class format
{
public:
format (const std::string& _d)
: d(_d)
{
}
template <typename T>
format& operator % (T in)
{
// XXX add replacement for boost::lexical_cast?
std::ostringstream ss;
ss << in; // note: ss cannot be an rvalue, or the global operator << (const char*) is not called for T == const char*.
chunks.push_back( ss.str());
return *this;
}
operator std::string () const {
std::string res; // pray for NRVO to kick in
size_t start = 0, last = 0;
std::vector<std::string>::const_iterator chunkin = chunks.begin();
for ( start = d.find('%');start != std::string::npos; start = d.find('%',last)) {
res += d.substr(last,start-last);
last = start+2;
if (d[start+1] == '%') {
res += "%";
continue;
}
if (chunkin == chunks.end()) {
break;
}
res += *chunkin++;
}
res += d.substr(last);
return res;
}
private:
std::string d;
std::vector<std::string> chunks;
};
inline std::string str(const std::string& s) {
return s;
}
}
#else
# error "format.h was already included"
#endif //
#endif // !! AI_BOOST_FORMAT_DUMMY_INCLUDED

View File

@ -1,26 +0,0 @@
/// A quick replacement for boost::lexical_cast for all the Boost haters out there
#ifndef __AI_BOOST_WORKAROUND_LEXICAL_CAST
#define __AI_BOOST_WORKAROUND_LEXICAL_CAST
#include <sstream>
namespace boost
{
/// A quick replacement for boost::lexical_cast - should work for all types a stringstream can handle
template <typename TargetType, typename SourceType>
TargetType lexical_cast( const SourceType& source)
{
std::stringstream stream;
TargetType result;
stream << source;
stream >> result;
return result;
}
} // namespace boost
#endif // __AI_BOOST_WORKAROUND_LEXICAL_CAST

View File

@ -1,57 +0,0 @@
// please note that this replacement implementation does not
// provide the performance benefit of the original, which
// makes only one allocation as opposed to two allocations
// (smart pointer counter and payload) which are usually
// required if object and smart pointer are constructed
// independently.
#ifndef INCLUDED_AI_BOOST_MAKE_SHARED
#define INCLUDED_AI_BOOST_MAKE_SHARED
namespace boost {
template <typename T>
shared_ptr<T> make_shared() {
return shared_ptr<T>(new T());
}
template <typename T, typename T0>
shared_ptr<T> make_shared(const T0& t0) {
return shared_ptr<T>(new T(t0));
}
template <typename T, typename T0,typename T1>
shared_ptr<T> make_shared(const T0& t0, const T1& t1) {
return shared_ptr<T>(new T(t0,t1));
}
template <typename T, typename T0,typename T1,typename T2>
shared_ptr<T> make_shared(const T0& t0, const T1& t1, const T2& t2) {
return shared_ptr<T>(new T(t0,t1,t2));
}
template <typename T, typename T0,typename T1,typename T2,typename T3>
shared_ptr<T> make_shared(const T0& t0, const T1& t1, const T2& t2, const T3& t3) {
return shared_ptr<T>(new T(t0,t1,t2,t3));
}
template <typename T, typename T0,typename T1,typename T2,typename T3, typename T4>
shared_ptr<T> make_shared(const T0& t0, const T1& t1, const T2& t2, const T3& t3, const T4& t4) {
return shared_ptr<T>(new T(t0,t1,t2,t3,t4));
}
template <typename T, typename T0,typename T1,typename T2,typename T3, typename T4, typename T5>
shared_ptr<T> make_shared(const T0& t0, const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5) {
return shared_ptr<T>(new T(t0,t1,t2,t3,t4,t5));
}
template <typename T, typename T0,typename T1,typename T2,typename T3, typename T4, typename T5, typename T6>
shared_ptr<T> make_shared(const T0& t0, const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6) {
return shared_ptr<T>(new T(t0,t1,t2,t3,t4,t5,t6));
}
}
#endif

View File

@ -1,37 +0,0 @@
#ifndef BOOST_MATH_COMMON_FACTOR_RT_HPP
#define BOOST_MATH_COMMON_FACTOR_RT_HPP
namespace boost {
namespace math {
// TODO: use binary GCD for unsigned integers ....
template < typename IntegerType >
IntegerType gcd( IntegerType a, IntegerType b )
{
const IntegerType zero = (IntegerType)0;
while ( true )
{
if ( a == zero )
return b;
b %= a;
if ( b == zero )
return a;
a %= b;
}
}
template < typename IntegerType >
IntegerType lcm( IntegerType a, IntegerType b )
{
const IntegerType t = gcd (a,b);
if (!t)return t;
return a / t * b;
}
}}
#endif

View File

@ -1,36 +0,0 @@
// Boost noncopyable.hpp header file --------------------------------------//
// (C) Copyright Beman Dawes 1999-2003. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/utility for documentation.
#ifndef BOOST_NONCOPYABLE_HPP_INCLUDED
#define BOOST_NONCOPYABLE_HPP_INCLUDED
namespace boost {
// Private copy constructor and copy assignment ensure classes derived from
// class noncopyable cannot be copied.
// Contributed by Dave Abrahams
namespace noncopyable_ // protection from unintended ADL
{
class noncopyable
{
protected:
noncopyable() {}
~noncopyable() {}
private: // emphasize the following members are private
noncopyable( const noncopyable& );
const noncopyable& operator=( const noncopyable& );
};
}
typedef noncopyable_::noncopyable noncopyable;
} // namespace boost
#endif // BOOST_NONCOPYABLE_HPP_INCLUDED

View File

@ -1,45 +0,0 @@
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2005.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_POINTER_CAST_HPP
#define BOOST_POINTER_CAST_HPP
namespace boost {
//static_pointer_cast overload for raw pointers
template<class T, class U>
inline T* static_pointer_cast(U *ptr)
{
return static_cast<T*>(ptr);
}
//dynamic_pointer_cast overload for raw pointers
template<class T, class U>
inline T* dynamic_pointer_cast(U *ptr)
{
return dynamic_cast<T*>(ptr);
}
//const_pointer_cast overload for raw pointers
template<class T, class U>
inline T* const_pointer_cast(U *ptr)
{
return const_cast<T*>(ptr);
}
//reinterpret_pointer_cast overload for raw pointers
template<class T, class U>
inline T* reinterpret_pointer_cast(U *ptr)
{
return reinterpret_cast<T*>(ptr);
}
} // namespace boost
#endif //BOOST_POINTER_CAST_HPP

View File

@ -1,79 +0,0 @@
#ifndef __AI_BOOST_SCOPED_ARRAY_INCLUDED
#define __AI_BOOST_SCOPED_ARRAY_INCLUDED
#ifndef BOOST_SCOPED_ARRAY_HPP_INCLUDED
namespace boost {
// small replacement for boost::scoped_array
template <class T>
class scoped_array
{
public:
// provide a default construtctor
scoped_array()
: ptr(0)
{
}
// construction from an existing heap object of type T
scoped_array(T* _ptr)
: ptr(_ptr)
{
}
// automatic destruction of the wrapped object at the
// end of our lifetime
~scoped_array()
{
delete[] ptr;
}
inline T* get()
{
return ptr;
}
inline T* operator-> ()
{
return ptr;
}
inline void reset (T* t = 0)
{
delete[] ptr;
ptr = t;
}
T & operator[](std::ptrdiff_t i) const
{
return ptr[i];
}
void swap(scoped_array & b)
{
std::swap(ptr, b.ptr);
}
private:
// encapsulated object pointer
T* ptr;
};
template<class T>
inline void swap(scoped_array<T> & a, scoped_array<T> & b)
{
a.swap(b);
}
} // end of namespace boost
#else
# error "scoped_array.h was already included"
#endif
#endif // __AI_BOOST_SCOPED_ARRAY_INCLUDED

View File

@ -1,79 +0,0 @@
#ifndef __AI_BOOST_SCOPED_PTR_INCLUDED
#define __AI_BOOST_SCOPED_PTR_INCLUDED
#ifndef BOOST_SCOPED_PTR_HPP_INCLUDED
namespace boost {
// small replacement for boost::scoped_ptr
template <class T>
class scoped_ptr
{
public:
// provide a default construtctor
scoped_ptr()
: ptr(0)
{
}
// construction from an existing heap object of type T
scoped_ptr(T* _ptr)
: ptr(_ptr)
{
}
// automatic destruction of the wrapped object at the
// end of our lifetime
~scoped_ptr()
{
delete ptr;
}
inline T* get() const
{
return ptr;
}
inline operator T*()
{
return ptr;
}
inline T* operator-> ()
{
return ptr;
}
inline void reset (T* t = 0)
{
delete ptr;
ptr = t;
}
void swap(scoped_ptr & b)
{
std::swap(ptr, b.ptr);
}
private:
// encapsulated object pointer
T* ptr;
};
template<class T>
inline void swap(scoped_ptr<T> & a, scoped_ptr<T> & b)
{
a.swap(b);
}
} // end of namespace boost
#else
# error "scoped_ptr.h was already included"
#endif
#endif // __AI_BOOST_SCOPED_PTR_INCLUDED

View File

@ -1,228 +0,0 @@
#ifndef INCLUDED_AI_BOOST_SHARED_ARRAY
#define INCLUDED_AI_BOOST_SHARED_ARRAY
#ifndef BOOST_SHARED_ARRAY_HPP_INCLUDED
// ------------------------------
// Internal stub
namespace boost {
namespace array_detail {
class controller {
public:
controller()
: cnt(1)
{}
public:
template <typename T>
controller* decref(T* pt) {
if (--cnt <= 0) {
delete this;
delete[] pt;
}
return NULL;
}
controller* incref() {
++cnt;
return this;
}
long get() const {
return cnt;
}
private:
long cnt;
};
struct empty {};
template <typename DEST, typename SRC>
struct is_convertible_stub {
struct yes {char s[1];};
struct no {char s[2];};
static yes foo(DEST*);
static no foo(...);
enum {result = (sizeof(foo((SRC*)0)) == sizeof(yes) ? 1 : 0)};
};
template <bool> struct enable_if {};
template <> struct enable_if<true> {
typedef empty result;
};
template <typename DEST, typename SRC>
struct is_convertible : public enable_if<is_convertible_stub<DEST,SRC>::result > {
};
}
// ------------------------------
// Small replacement for boost::shared_array, not threadsafe because no
// atomic reference counter is in use.
// ------------------------------
template <class T>
class shared_array
{
template <typename TT> friend class shared_array;
template<class TT> friend bool operator== (const shared_array<TT>& a, const shared_array<TT>& b);
template<class TT> friend bool operator!= (const shared_array<TT>& a, const shared_array<TT>& b);
template<class TT> friend bool operator< (const shared_array<TT>& a, const shared_array<TT>& b);
public:
typedef T element_type;
public:
// provide a default constructor
shared_array()
: ptr()
, ctr(NULL)
{
}
// construction from an existing object of type T
explicit shared_array(T* ptr)
: ptr(ptr)
, ctr(ptr ? new array_detail::controller() : NULL)
{
}
shared_array(const shared_array& r)
: ptr(r.ptr)
, ctr(r.ctr ? r.ctr->incref() : NULL)
{
}
template <typename Y>
shared_array(const shared_array<Y>& r,typename detail::is_convertible<T,Y>::result = detail::empty())
: ptr(r.ptr)
, ctr(r.ctr ? r.ctr->incref() : NULL)
{
}
// automatic destruction of the wrapped object when all
// references are freed.
~shared_array() {
if (ctr) {
ctr = ctr->decref(ptr);
}
}
shared_array& operator=(const shared_array& r) {
if (this == &r) {
return *this;
}
if (ctr) {
ctr->decref(ptr);
}
ptr = r.ptr;
ctr = ptr?r.ctr->incref():NULL;
return *this;
}
template <typename Y>
shared_array& operator=(const shared_array<Y>& r) {
if (this == &r) {
return *this;
}
if (ctr) {
ctr->decref(ptr);
}
ptr = r.ptr;
ctr = ptr?r.ctr->incref():NULL;
return *this;
}
// pointer access
inline operator T*() {
return ptr;
}
inline T* operator-> () const {
return ptr;
}
// standard semantics
inline T* get() {
return ptr;
}
T& operator[] (std::ptrdiff_t index) const {
return ptr[index];
}
inline const T* get() const {
return ptr;
}
inline operator bool () const {
return ptr != NULL;
}
inline bool unique() const {
return use_count() == 1;
}
inline long use_count() const {
return ctr->get();
}
inline void reset (T* t = 0) {
if (ctr) {
ctr->decref(ptr);
}
ptr = t;
ctr = ptr?new array_detail::controller():NULL;
}
void swap(shared_array & b) {
std::swap(ptr, b.ptr);
std::swap(ctr, b.ctr);
}
private:
// encapsulated object pointer
T* ptr;
// control block
array_detail::controller* ctr;
};
template<class T>
inline void swap(shared_array<T> & a, shared_array<T> & b)
{
a.swap(b);
}
template<class T>
bool operator== (const shared_array<T>& a, const shared_array<T>& b) {
return a.ptr == b.ptr;
}
template<class T>
bool operator!= (const shared_array<T>& a, const shared_array<T>& b) {
return a.ptr != b.ptr;
}
template<class T>
bool operator< (const shared_array<T>& a, const shared_array<T>& b) {
return a.ptr < b.ptr;
}
} // end of namespace boost
#else
# error "shared_array.h was already included"
#endif
#endif // INCLUDED_AI_BOOST_SHARED_ARRAY

View File

@ -1,260 +0,0 @@
#ifndef INCLUDED_AI_BOOST_SHARED_PTR
#define INCLUDED_AI_BOOST_SHARED_PTR
#ifndef BOOST_SHARED_PTR_HPP_INCLUDED
// ------------------------------
// Internal stub
#include <stddef.h> //NULL
#include <algorithm> //std::swap
namespace boost {
namespace detail {
class controller {
public:
controller()
: cnt(1)
{}
public:
template <typename T>
controller* decref(T* pt) {
if (--cnt <= 0) {
delete this;
delete pt;
}
return NULL;
}
controller* incref() {
++cnt;
return this;
}
long get() const {
return cnt;
}
private:
long cnt;
};
struct empty {};
template <typename DEST, typename SRC>
struct is_convertible_stub {
struct yes {char s[1];};
struct no {char s[2];};
static yes foo(DEST*);
static no foo(...);
enum {result = (sizeof(foo((SRC*)0)) == sizeof(yes) ? 1 : 0)};
};
template <bool> struct enable_if {};
template <> struct enable_if<true> {
typedef empty result;
};
template <typename DEST, typename SRC>
struct is_convertible : public enable_if<is_convertible_stub<DEST,SRC>::result > {
};
}
// ------------------------------
// Small replacement for boost::shared_ptr, not threadsafe because no
// atomic reference counter is in use.
// ------------------------------
template <class T>
class shared_ptr
{
template <typename TT> friend class shared_ptr;
template<class TT, class U> friend shared_ptr<TT> static_pointer_cast (shared_ptr<U> ptr);
template<class TT, class U> friend shared_ptr<TT> dynamic_pointer_cast (shared_ptr<U> ptr);
template<class TT, class U> friend shared_ptr<TT> const_pointer_cast (shared_ptr<U> ptr);
template<class TT> friend bool operator== (const shared_ptr<TT>& a, const shared_ptr<TT>& b);
template<class TT> friend bool operator!= (const shared_ptr<TT>& a, const shared_ptr<TT>& b);
template<class TT> friend bool operator< (const shared_ptr<TT>& a, const shared_ptr<TT>& b);
public:
typedef T element_type;
public:
// provide a default constructor
shared_ptr()
: ptr()
, ctr(NULL)
{
}
// construction from an existing object of type T
explicit shared_ptr(T* ptr)
: ptr(ptr)
, ctr(ptr ? new detail::controller() : NULL)
{
}
shared_ptr(const shared_ptr& r)
: ptr(r.ptr)
, ctr(r.ctr ? r.ctr->incref() : NULL)
{
}
template <typename Y>
shared_ptr(const shared_ptr<Y>& r,typename detail::is_convertible<T,Y>::result = detail::empty())
: ptr(r.ptr)
, ctr(r.ctr ? r.ctr->incref() : NULL)
{
}
// automatic destruction of the wrapped object when all
// references are freed.
~shared_ptr() {
if (ctr) {
ctr = ctr->decref(ptr);
}
}
shared_ptr& operator=(const shared_ptr& r) {
if (this == &r) {
return *this;
}
if (ctr) {
ctr->decref(ptr);
}
ptr = r.ptr;
ctr = ptr?r.ctr->incref():NULL;
return *this;
}
template <typename Y>
shared_ptr& operator=(const shared_ptr<Y>& r) {
if (this == &r) {
return *this;
}
if (ctr) {
ctr->decref(ptr);
}
ptr = r.ptr;
ctr = ptr?r.ctr->incref():NULL;
return *this;
}
// pointer access
inline operator T*() const {
return ptr;
}
inline T* operator-> () const {
return ptr;
}
// standard semantics
inline T* get() {
return ptr;
}
inline const T* get() const {
return ptr;
}
inline operator bool () const {
return ptr != NULL;
}
inline bool unique() const {
return use_count() == 1;
}
inline long use_count() const {
return ctr->get();
}
inline void reset (T* t = 0) {
if (ctr) {
ctr->decref(ptr);
}
ptr = t;
ctr = ptr?new detail::controller():NULL;
}
void swap(shared_ptr & b) {
std::swap(ptr, b.ptr);
std::swap(ctr, b.ctr);
}
private:
// for use by the various xxx_pointer_cast helper templates
explicit shared_ptr(T* ptr, detail::controller* ctr)
: ptr(ptr)
, ctr(ctr->incref())
{
}
private:
// encapsulated object pointer
T* ptr;
// control block
detail::controller* ctr;
};
template<class T>
inline void swap(shared_ptr<T> & a, shared_ptr<T> & b)
{
a.swap(b);
}
template<class T>
bool operator== (const shared_ptr<T>& a, const shared_ptr<T>& b) {
return a.ptr == b.ptr;
}
template<class T>
bool operator!= (const shared_ptr<T>& a, const shared_ptr<T>& b) {
return a.ptr != b.ptr;
}
template<class T>
bool operator< (const shared_ptr<T>& a, const shared_ptr<T>& b) {
return a.ptr < b.ptr;
}
template<class T, class U>
inline shared_ptr<T> static_pointer_cast( shared_ptr<U> ptr)
{
return shared_ptr<T>(static_cast<T*>(ptr.ptr),ptr.ctr);
}
template<class T, class U>
inline shared_ptr<T> dynamic_pointer_cast( shared_ptr<U> ptr)
{
return shared_ptr<T>(dynamic_cast<T*>(ptr.ptr),ptr.ctr);
}
template<class T, class U>
inline shared_ptr<T> const_pointer_cast( shared_ptr<U> ptr)
{
return shared_ptr<T>(const_cast<T*>(ptr.ptr),ptr.ctr);
}
} // end of namespace boost
#else
# error "shared_ptr.h was already included"
#endif
#endif // INCLUDED_AI_BOOST_SHARED_PTR

View File

@ -1,20 +0,0 @@
#ifndef AI_BOOST_STATIC_ASSERT_INCLUDED
#define AI_BOOST_STATIC_ASSERT_INCLUDED
#ifndef BOOST_STATIC_ASSERT
namespace boost {
namespace detail {
template <bool b> class static_assertion_failure;
template <> class static_assertion_failure<true> {};
}
}
#define BOOST_STATIC_ASSERT(eval) \
{boost::detail::static_assertion_failure<(eval)> assert_dummy;(void)assert_dummy;}
#endif
#endif // !! AI_BOOST_STATIC_ASSERT_INCLUDED

View File

@ -1,73 +0,0 @@
// boost timer.hpp header file ---------------------------------------------//
// Copyright Beman Dawes 1994-99. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/timer for documentation.
// Revision History
// 01 Apr 01 Modified to use new <boost/limits.hpp> header. (JMaddock)
// 12 Jan 01 Change to inline implementation to allow use without library
// builds. See docs for more rationale. (Beman Dawes)
// 25 Sep 99 elapsed_max() and elapsed_min() added (John Maddock)
// 16 Jul 99 Second beta
// 6 Jul 99 Initial boost version
#ifndef BOOST_TIMER_HPP
#define BOOST_TIMER_HPP
//#include <boost/config.hpp>
#include <ctime>
#include <limits>
//#include <boost/limits.hpp>
# ifdef BOOST_NO_STDC_NAMESPACE
namespace std { using ::clock_t; using ::clock; }
# endif
namespace boost {
// timer -------------------------------------------------------------------//
// A timer object measures elapsed time.
// It is recommended that implementations measure wall clock rather than CPU
// time since the intended use is performance measurement on systems where
// total elapsed time is more important than just process or CPU time.
// Warnings: The maximum measurable elapsed time may well be only 596.5+ hours
// due to implementation limitations. The accuracy of timings depends on the
// accuracy of timing information provided by the underlying platform, and
// this varies a great deal from platform to platform.
class timer
{
public:
timer() { _start_time = std::clock(); } // postcondition: elapsed()==0
// timer( const timer& src ); // post: elapsed()==src.elapsed()
// ~timer(){}
// timer& operator=( const timer& src ); // post: elapsed()==src.elapsed()
void restart() { _start_time = std::clock(); } // post: elapsed()==0
double elapsed() const // return elapsed time in seconds
{ return double(std::clock() - _start_time) / CLOCKS_PER_SEC; }
double elapsed_max() const // return estimated maximum value for elapsed()
// Portability warning: elapsed_max() may return too high a value on systems
// where std::clock_t overflows or resets at surprising values.
{
return (double((std::numeric_limits<std::clock_t>::max)())
- double(_start_time)) / double(CLOCKS_PER_SEC);
}
double elapsed_min() const // return minimum value for elapsed()
{ return double(1)/double(CLOCKS_PER_SEC); }
private:
std::clock_t _start_time;
}; // timer
} // namespace boost
#endif // BOOST_TIMER_HPP

View File

@ -1,283 +0,0 @@
// A very small replacement for boost::tuple
// (c) Alexander Gessler, 2008 [alexander.gessler@gmx.net]
#ifndef BOOST_TUPLE_INCLUDED
#define BOOST_TUPLE_INCLUDED
namespace boost {
namespace detail {
// Represents an empty tuple slot (up to 5 supported)
struct nulltype {};
// For readable error messages
struct tuple_component_idx_out_of_bounds;
// To share some code for the const/nonconst versions of the getters
template <bool b, typename T>
struct ConstIf {
typedef T t;
};
template <typename T>
struct ConstIf<true,T> {
typedef const T t;
};
// Predeclare some stuff
template <typename, unsigned, typename, bool, unsigned> struct value_getter;
// Helper to obtain the type of a tuple element
template <typename T, unsigned NIDX, typename TNEXT, unsigned N /*= 0*/>
struct type_getter {
typedef type_getter<typename TNEXT::type,NIDX+1,typename TNEXT::next_type,N> next_elem_getter;
typedef typename next_elem_getter::type type;
};
template <typename T, unsigned NIDX, typename TNEXT >
struct type_getter <T,NIDX,TNEXT,NIDX> {
typedef T type;
};
// Base class for all explicit specializations of list_elem
template <typename T, unsigned NIDX, typename TNEXT >
struct list_elem_base {
// Store template parameters
typedef TNEXT next_type;
typedef T type;
static const unsigned nidx = NIDX;
};
// Represents an element in the tuple component list
template <typename T, unsigned NIDX, typename TNEXT >
struct list_elem : list_elem_base<T,NIDX,TNEXT>{
// Real members
T me;
TNEXT next;
// Get the value of a specific tuple element
template <unsigned N>
typename type_getter<T,NIDX,TNEXT,N>::type& get () {
value_getter <T,NIDX,TNEXT,false,N> s;
return s(*this);
}
// Get the value of a specific tuple element
template <unsigned N>
const typename type_getter<T,NIDX,TNEXT,N>::type& get () const {
value_getter <T,NIDX,TNEXT,true,N> s;
return s(*this);
}
// Explicit cast
template <typename T2, typename TNEXT2 >
operator list_elem<T2,NIDX,TNEXT2> () const {
list_elem<T2,NIDX,TNEXT2> ret;
ret.me = (T2)me;
ret.next = next;
return ret;
}
// Recursively compare two elements (last element returns always true)
bool operator == (const list_elem& s) const {
return (me == s.me && next == s.next);
}
};
// Represents a non-used tuple element - the very last element processed
template <typename TNEXT, unsigned NIDX >
struct list_elem<nulltype,NIDX,TNEXT> : list_elem_base<nulltype,NIDX,TNEXT> {
template <unsigned N, bool IS_CONST = true> struct value_getter {
/* just dummy members to produce readable error messages */
tuple_component_idx_out_of_bounds operator () (typename ConstIf<IS_CONST,list_elem>::t& me);
};
template <unsigned N> struct type_getter {
/* just dummy members to produce readable error messages */
typedef tuple_component_idx_out_of_bounds type;
};
// dummy
list_elem& operator = (const list_elem& /*other*/) {
return *this;
}
// dummy
bool operator == (const list_elem& other) {
return true;
}
};
// Represents the absolute end of the list
typedef list_elem<nulltype,0,int> list_end;
// Helper obtain to query the value of a tuple element
// NOTE: This can't be a nested class as the compiler won't accept a full or
// partial specialization of a nested class of a non-specialized template
template <typename T, unsigned NIDX, typename TNEXT, bool IS_CONST, unsigned N>
struct value_getter {
// calling list_elem
typedef list_elem<T,NIDX,TNEXT> outer_elem;
// typedef for the getter for next element
typedef value_getter<typename TNEXT::type,NIDX+1,typename TNEXT::next_type,
IS_CONST, N> next_value_getter;
typename ConstIf<IS_CONST,typename type_getter<T,NIDX,TNEXT,N>::type>::t&
operator () (typename ConstIf<IS_CONST,outer_elem >::t& me) {
next_value_getter s;
return s(me.next);
}
};
template <typename T, unsigned NIDX, typename TNEXT, bool IS_CONST>
struct value_getter <T,NIDX,TNEXT,IS_CONST,NIDX> {
typedef list_elem<T,NIDX,TNEXT> outer_elem;
typename ConstIf<IS_CONST,T>::t& operator () (typename ConstIf<IS_CONST,outer_elem >::t& me) {
return me.me;
}
};
}
// A very minimal implementation for up to 5 elements
template <typename T0 = detail::nulltype,
typename T1 = detail::nulltype,
typename T2 = detail::nulltype,
typename T3 = detail::nulltype,
typename T4 = detail::nulltype>
class tuple {
template <typename T0b,
typename T1b,
typename T2b,
typename T3b,
typename T4b >
friend class tuple;
private:
typedef detail::list_elem<T0,0,
detail::list_elem<T1,1,
detail::list_elem<T2,2,
detail::list_elem<T3,3,
detail::list_elem<T4,4,
detail::list_end > > > > > very_long;
very_long m;
public:
// Get a specific tuple element
template <unsigned N>
typename detail::type_getter<T0,0,typename very_long::next_type, N>::type& get () {
return m.template get<N>();
}
// ... and the const version
template <unsigned N>
const typename detail::type_getter<T0,0,typename very_long::next_type, N>::type& get () const {
return m.template get<N>();
}
// comparison operators
bool operator== (const tuple& other) const {
return m == other.m;
}
// ... and the other way round
bool operator!= (const tuple& other) const {
return !(m == other.m);
}
// cast to another tuple - all single elements must be convertible
template <typename T0b, typename T1b,typename T2b,typename T3b, typename T4b>
operator tuple <T0b,T1b,T2b,T3b,T4b> () const {
tuple <T0b,T1b,T2b,T3b,T4b> s;
s.m = (typename tuple <T0b,T1b,T2b,T3b,T4b>::very_long)m;
return s;
}
};
// Another way to access an element ...
template <unsigned N,typename T0,typename T1,typename T2,typename T3,typename T4>
inline typename tuple<T0,T1,T2,T3,T4>::very_long::template type_getter<N>::type& get (
tuple<T0,T1,T2,T3,T4>& m) {
return m.template get<N>();
}
// ... and the const version
template <unsigned N,typename T0,typename T1,typename T2,typename T3,typename T4>
inline const typename tuple<T0,T1,T2,T3,T4>::very_long::template type_getter<N>::type& get (
const tuple<T0,T1,T2,T3,T4>& m) {
return m.template get<N>();
}
// Constructs a tuple with 5 elements
template <typename T0,typename T1,typename T2,typename T3,typename T4>
inline tuple <T0,T1,T2,T3,T4> make_tuple (const T0& t0,
const T1& t1,const T2& t2,const T3& t3,const T4& t4) {
tuple <T0,T1,T2,T3,T4> t;
t.template get<0>() = t0;
t.template get<1>() = t1;
t.template get<2>() = t2;
t.template get<3>() = t3;
t.template get<4>() = t4;
return t;
}
// Constructs a tuple with 4 elements
template <typename T0,typename T1,typename T2,typename T3>
inline tuple <T0,T1,T2,T3> make_tuple (const T0& t0,
const T1& t1,const T2& t2,const T3& t3) {
tuple <T0,T1,T2,T3> t;
t.template get<0>() = t0;
t.template get<1>() = t1;
t.template get<2>() = t2;
t.template get<3>() = t3;
return t;
}
// Constructs a tuple with 3 elements
template <typename T0,typename T1,typename T2>
inline tuple <T0,T1,T2> make_tuple (const T0& t0,
const T1& t1,const T2& t2) {
tuple <T0,T1,T2> t;
t.template get<0>() = t0;
t.template get<1>() = t1;
t.template get<2>() = t2;
return t;
}
// Constructs a tuple with 2 elements
template <typename T0,typename T1>
inline tuple <T0,T1> make_tuple (const T0& t0,
const T1& t1) {
tuple <T0,T1> t;
t.template get<0>() = t0;
t.template get<1>() = t1;
return t;
}
// Constructs a tuple with 1 elements (well ...)
template <typename T0>
inline tuple <T0> make_tuple (const T0& t0) {
tuple <T0> t;
t.template get<0>() = t0;
return t;
}
// Constructs a tuple with 0 elements (well ...)
inline tuple <> make_tuple () {
tuple <> t;
return t;
}
}
#endif // !! BOOST_TUPLE_INCLUDED

View File

@ -43,8 +43,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef AI_BYTESWAPPER_H_INC #ifndef AI_BYTESWAPPER_H_INC
#define AI_BYTESWAPPER_H_INC #define AI_BYTESWAPPER_H_INC
#include "../include/assimp/ai_assert.h" #include <assimp/ai_assert.h>
#include "../include/assimp/types.h" #include <assimp/types.h>
#include <stdint.h> #include <stdint.h>
#if _MSC_VER >= 1400 #if _MSC_VER >= 1400

View File

@ -52,6 +52,10 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "C4DImporter.h" #include "C4DImporter.h"
#include "TinyFormatter.h" #include "TinyFormatter.h"
#include <memory>
#include <assimp/IOSystem.hpp>
#include <assimp/scene.h>
#include <assimp/ai_assert.h>
#if defined(_M_X64) || defined(__amd64__) #if defined(_M_X64) || defined(__amd64__)
# define __C4D_64BIT # define __C4D_64BIT
@ -61,10 +65,10 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "c4d_file.h" #include "c4d_file.h"
#include "default_alien_overloads.h" #include "default_alien_overloads.h"
using namespace _melange_; using namespace melange;
// overload this function and fill in your own unique data // overload this function and fill in your own unique data
void GetWriterInfo(LONG &id, String &appname) void GetWriterInfo(int &id, String &appname)
{ {
id = 2424226; id = 2424226;
appname = "Open Asset Import Library"; appname = "Open Asset Import Library";
@ -131,7 +135,7 @@ void C4DImporter::SetupProperties(const Importer* /*pImp*/)
void C4DImporter::InternReadFile( const std::string& pFile, void C4DImporter::InternReadFile( const std::string& pFile,
aiScene* pScene, IOSystem* pIOHandler) aiScene* pScene, IOSystem* pIOHandler)
{ {
boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile)); std::unique_ptr<IOStream> file( pIOHandler->Open( pFile));
if( file.get() == NULL) { if( file.get() == NULL) {
ThrowException("failed to open file " + pFile); ThrowException("failed to open file " + pFile);
@ -161,7 +165,7 @@ void C4DImporter::InternReadFile( const std::string& pFile,
RecurseHierarchy(doc->GetFirstObject(), pScene->mRootNode); RecurseHierarchy(doc->GetFirstObject(), pScene->mRootNode);
} }
catch(...) { catch(...) {
BOOST_FOREACH(aiMesh* mesh, meshes) { for(aiMesh* mesh : meshes) {
delete mesh; delete mesh;
} }
BaseDocument::Free(doc); BaseDocument::Free(doc);
@ -176,7 +180,7 @@ void C4DImporter::InternReadFile( const std::string& pFile,
// copy materials over, adding a default material if necessary // copy materials over, adding a default material if necessary
unsigned int mat_count = static_cast<unsigned int>(materials.size()); unsigned int mat_count = static_cast<unsigned int>(materials.size());
BOOST_FOREACH(aiMesh* mesh, meshes) { for(aiMesh* mesh : meshes) {
ai_assert(mesh->mMaterialIndex <= mat_count); ai_assert(mesh->mMaterialIndex <= mat_count);
if(mesh->mMaterialIndex >= mat_count) { if(mesh->mMaterialIndex >= mat_count) {
++mat_count; ++mat_count;
@ -197,7 +201,7 @@ void C4DImporter::InternReadFile( const std::string& pFile,
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
bool C4DImporter::ReadShader(aiMaterial* out, _melange_::BaseShader* shader) bool C4DImporter::ReadShader(aiMaterial* out, melange::BaseShader* shader)
{ {
// based on Melange sample code (C4DImportExport.cpp) // based on Melange sample code (C4DImportExport.cpp)
while(shader) { while(shader) {
@ -263,7 +267,7 @@ bool C4DImporter::ReadShader(aiMaterial* out, _melange_::BaseShader* shader)
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
void C4DImporter::ReadMaterials(_melange_::BaseMaterial* mat) void C4DImporter::ReadMaterials(melange::BaseMaterial* mat)
{ {
// based on Melange sample code // based on Melange sample code
while (mat) while (mat)
@ -288,7 +292,7 @@ void C4DImporter::ReadMaterials(_melange_::BaseMaterial* mat)
mat->GetParameter(MATERIAL_COLOR_COLOR, data); mat->GetParameter(MATERIAL_COLOR_COLOR, data);
Vector color = data.GetVector(); Vector color = data.GetVector();
mat->GetParameter(MATERIAL_COLOR_BRIGHTNESS, data); mat->GetParameter(MATERIAL_COLOR_BRIGHTNESS, data);
const Real brightness = data.GetReal(); const Float brightness = data.GetFloat();
color *= brightness; color *= brightness;
@ -507,11 +511,13 @@ aiMesh* C4DImporter::ReadMesh(BaseObject* object)
// copy normals // copy normals
if (normals_src) { if (normals_src) {
if(i >= normals_src->GetNormalCount()) { if(i >= normals_src->GetDataCount()) {
LogError("unexpected number of normals, ignoring"); LogError("unexpected number of normals, ignoring");
} }
else { else {
const NormalStruct& nor = normals_src->GetNormals(i); ConstNormalHandle normal_handle = normals_src->GetDataAddressR();
NormalStruct nor;
NormalTag::Get(normal_handle, i, nor);
normals->x = nor.a.x; normals->x = nor.a.x;
normals->y = nor.a.y; normals->y = nor.a.y;
normals->z = nor.a.z; normals->z = nor.a.z;

View File

@ -54,7 +54,7 @@ struct aiMaterial;
struct aiImporterDesc; struct aiImporterDesc;
namespace _melange_ { namespace melange {
class BaseObject; // c4d_file.h class BaseObject; // c4d_file.h
class PolygonObject; class PolygonObject;
class BaseMaterial; class BaseMaterial;
@ -103,17 +103,17 @@ protected:
private: private:
void ReadMaterials(_melange_::BaseMaterial* mat); void ReadMaterials(melange::BaseMaterial* mat);
void RecurseHierarchy(_melange_::BaseObject* object, aiNode* parent); void RecurseHierarchy(melange::BaseObject* object, aiNode* parent);
aiMesh* ReadMesh(_melange_::BaseObject* object); aiMesh* ReadMesh(melange::BaseObject* object);
unsigned int ResolveMaterial(_melange_::PolygonObject* obj); unsigned int ResolveMaterial(melange::PolygonObject* obj);
bool ReadShader(aiMaterial* out, _melange_::BaseShader* shader); bool ReadShader(aiMaterial* out, melange::BaseShader* shader);
std::vector<aiMesh*> meshes; std::vector<aiMesh*> meshes;
std::vector<aiMaterial*> materials; std::vector<aiMaterial*> materials;
typedef std::map<_melange_::BaseMaterial*, unsigned int> MaterialMap; typedef std::map<melange::BaseMaterial*, unsigned int> MaterialMap;
MaterialMap material_mapping; MaterialMap material_mapping;
}; // !class C4DImporter }; // !class C4DImporter

View File

@ -44,9 +44,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef AI_CIOSYSTEM_H_INCLUDED #ifndef AI_CIOSYSTEM_H_INCLUDED
#define AI_CIOSYSTEM_H_INCLUDED #define AI_CIOSYSTEM_H_INCLUDED
#include "../include/assimp/cfileio.h" #include <assimp/cfileio.h>
#include "../include/assimp/IOStream.hpp" #include <assimp/IOStream.hpp>
#include "../include/assimp/IOSystem.hpp" #include <assimp/IOSystem.hpp>
namespace Assimp { namespace Assimp {

View File

@ -1,3 +1,41 @@
# Open Asset Import Library (assimp)
# ----------------------------------------------------------------------
#
# Copyright (c) 2006-2016, assimp team
# All rights reserved.
#
# Redistribution and use of this software in source and binary forms,
# with or without modification, are permitted provided that the
# following conditions are met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the
# following disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the
# following disclaimer in the documentation and/or other
# materials provided with the distribution.
#
# * Neither the name of the assimp team, nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior
# written permission of the assimp team.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#----------------------------------------------------------------------
# Listing and grouping of all the source files. # Listing and grouping of all the source files.
# 1) Set the file lists for each component # 1) Set the file lists for each component
# 2) Create a Source Group for each component, for IDE project orginization # 2) Create a Source Group for each component, for IDE project orginization
@ -61,20 +99,6 @@ SET( Core_SRCS
Assimp.cpp Assimp.cpp
) )
SET( Boost_SRCS
BoostWorkaround/boost/math/common_factor_rt.hpp
BoostWorkaround/boost/foreach.hpp
BoostWorkaround/boost/format.hpp
BoostWorkaround/boost/scoped_array.hpp
BoostWorkaround/boost/scoped_ptr.hpp
BoostWorkaround/boost/shared_array.hpp
BoostWorkaround/boost/shared_ptr.hpp
BoostWorkaround/boost/make_shared.hpp
BoostWorkaround/boost/static_assert.hpp
BoostWorkaround/boost/tuple/tuple.hpp
)
SOURCE_GROUP(Boost FILES ${Boost_SRCS})
SET( Logging_SRCS SET( Logging_SRCS
${HEADER_PATH}/DefaultLogger.hpp ${HEADER_PATH}/DefaultLogger.hpp
${HEADER_PATH}/LogStream.hpp ${HEADER_PATH}/LogStream.hpp
@ -178,7 +202,7 @@ SET(ASSIMP_LOADER_SRCS "")
SET(ASSIMP_IMPORTERS_ENABLED "") # list of enabled importers SET(ASSIMP_IMPORTERS_ENABLED "") # list of enabled importers
SET(ASSIMP_IMPORTERS_DISABLED "") # disabled list (used to print) SET(ASSIMP_IMPORTERS_DISABLED "") # disabled list (used to print)
ADD_ASSIMP_IMPORTER(3DS ADD_ASSIMP_IMPORTER( 3DS
3DSConverter.cpp 3DSConverter.cpp
3DSHelper.h 3DSHelper.h
3DSLoader.cpp 3DSLoader.cpp
@ -187,41 +211,41 @@ ADD_ASSIMP_IMPORTER(3DS
3DSExporter.cpp 3DSExporter.cpp
) )
ADD_ASSIMP_IMPORTER(AC ADD_ASSIMP_IMPORTER( AC
ACLoader.cpp ACLoader.cpp
ACLoader.h ACLoader.h
) )
ADD_ASSIMP_IMPORTER(ASE ADD_ASSIMP_IMPORTER( ASE
ASELoader.cpp ASELoader.cpp
ASELoader.h ASELoader.h
ASEParser.cpp ASEParser.cpp
ASEParser.h ASEParser.h
) )
ADD_ASSIMP_IMPORTER(ASSBIN ADD_ASSIMP_IMPORTER( ASSBIN
AssbinExporter.h AssbinExporter.h
AssbinExporter.cpp AssbinExporter.cpp
AssbinLoader.h AssbinLoader.h
AssbinLoader.cpp AssbinLoader.cpp
) )
ADD_ASSIMP_IMPORTER(ASSXML ADD_ASSIMP_IMPORTER( ASSXML
AssxmlExporter.h AssxmlExporter.h
AssxmlExporter.cpp AssxmlExporter.cpp
) )
ADD_ASSIMP_IMPORTER(B3D ADD_ASSIMP_IMPORTER( B3D
B3DImporter.cpp B3DImporter.cpp
B3DImporter.h B3DImporter.h
) )
ADD_ASSIMP_IMPORTER(BVH ADD_ASSIMP_IMPORTER( BVH
BVHLoader.cpp BVHLoader.cpp
BVHLoader.h BVHLoader.h
) )
ADD_ASSIMP_IMPORTER(COLLADA ADD_ASSIMP_IMPORTER( COLLADA
ColladaHelper.h ColladaHelper.h
ColladaLoader.cpp ColladaLoader.cpp
ColladaLoader.h ColladaLoader.h
@ -231,35 +255,39 @@ ADD_ASSIMP_IMPORTER(COLLADA
ColladaExporter.cpp ColladaExporter.cpp
) )
ADD_ASSIMP_IMPORTER(DXF ADD_ASSIMP_IMPORTER( DXF
DXFLoader.cpp DXFLoader.cpp
DXFLoader.h DXFLoader.h
DXFHelper.h DXFHelper.h
) )
ADD_ASSIMP_IMPORTER(CSM ADD_ASSIMP_IMPORTER( CSM
CSMLoader.cpp CSMLoader.cpp
CSMLoader.h CSMLoader.h
) )
ADD_ASSIMP_IMPORTER(HMP ADD_ASSIMP_IMPORTER( HMP
HMPFileData.h HMPFileData.h
HMPLoader.cpp HMPLoader.cpp
HMPLoader.h HMPLoader.h
HalfLifeFileData.h HalfLifeFileData.h
) )
#FIXME: allow to set IRRMESH by option ADD_ASSIMP_IMPORTER( IRRMESH
ADD_ASSIMP_IMPORTER(IRR
IRRLoader.cpp
IRRLoader.h
IRRMeshLoader.cpp IRRMeshLoader.cpp
IRRMeshLoader.h IRRMeshLoader.h
IRRShared.cpp IRRShared.cpp
IRRShared.h IRRShared.h
) )
ADD_ASSIMP_IMPORTER(LWO ADD_ASSIMP_IMPORTER( IRR
IRRLoader.cpp
IRRLoader.h
IRRShared.cpp
IRRShared.h
)
ADD_ASSIMP_IMPORTER( LWO
LWOAnimation.cpp LWOAnimation.cpp
LWOAnimation.h LWOAnimation.h
LWOBLoader.cpp LWOBLoader.cpp
@ -269,39 +297,39 @@ ADD_ASSIMP_IMPORTER(LWO
LWOMaterial.cpp LWOMaterial.cpp
) )
ADD_ASSIMP_IMPORTER(LWS ADD_ASSIMP_IMPORTER( LWS
LWSLoader.cpp LWSLoader.cpp
LWSLoader.h LWSLoader.h
) )
ADD_ASSIMP_IMPORTER(MD2 ADD_ASSIMP_IMPORTER( MD2
MD2FileData.h MD2FileData.h
MD2Loader.cpp MD2Loader.cpp
MD2Loader.h MD2Loader.h
MD2NormalTable.h MD2NormalTable.h
) )
ADD_ASSIMP_IMPORTER(MD3 ADD_ASSIMP_IMPORTER( MD3
MD3FileData.h MD3FileData.h
MD3Loader.cpp MD3Loader.cpp
MD3Loader.h MD3Loader.h
) )
ADD_ASSIMP_IMPORTER(MD5 ADD_ASSIMP_IMPORTER( MD5
MD5Loader.cpp MD5Loader.cpp
MD5Loader.h MD5Loader.h
MD5Parser.cpp MD5Parser.cpp
MD5Parser.h MD5Parser.h
) )
ADD_ASSIMP_IMPORTER(MDC ADD_ASSIMP_IMPORTER( MDC
MDCFileData.h MDCFileData.h
MDCLoader.cpp MDCLoader.cpp
MDCLoader.h MDCLoader.h
MDCNormalTable.h MDCNormalTable.h
) )
ADD_ASSIMP_IMPORTER(MDL ADD_ASSIMP_IMPORTER( MDL
MDLDefaultColorMap.h MDLDefaultColorMap.h
MDLFileData.h MDLFileData.h
MDLLoader.cpp MDLLoader.cpp
@ -315,22 +343,22 @@ SET( MaterialSystem_SRCS
) )
SOURCE_GROUP( MaterialSystem FILES ${MaterialSystem_SRCS}) SOURCE_GROUP( MaterialSystem FILES ${MaterialSystem_SRCS})
ADD_ASSIMP_IMPORTER(NFF ADD_ASSIMP_IMPORTER( NFF
NFFLoader.cpp NFFLoader.cpp
NFFLoader.h NFFLoader.h
) )
ADD_ASSIMP_IMPORTER(NDO ADD_ASSIMP_IMPORTER( NDO
NDOLoader.cpp NDOLoader.cpp
NDOLoader.h NDOLoader.h
) )
ADD_ASSIMP_IMPORTER(OFF ADD_ASSIMP_IMPORTER( OFF
OFFLoader.cpp OFFLoader.cpp
OFFLoader.h OFFLoader.h
) )
ADD_ASSIMP_IMPORTER(OBJ ADD_ASSIMP_IMPORTER( OBJ
ObjFileData.h ObjFileData.h
ObjFileImporter.cpp ObjFileImporter.cpp
ObjFileImporter.h ObjFileImporter.h
@ -339,12 +367,11 @@ ADD_ASSIMP_IMPORTER(OBJ
ObjFileParser.cpp ObjFileParser.cpp
ObjFileParser.h ObjFileParser.h
ObjTools.h ObjTools.h
ObjExporter.h ObjExporter.h
ObjExporter.cpp ObjExporter.cpp
) )
ADD_ASSIMP_IMPORTER(OGRE ADD_ASSIMP_IMPORTER( OGRE
OgreImporter.h OgreImporter.h
OgreStructs.h OgreStructs.h
OgreParsingUtils.h OgreParsingUtils.h
@ -357,7 +384,7 @@ ADD_ASSIMP_IMPORTER(OGRE
OgreMaterial.cpp OgreMaterial.cpp
) )
ADD_ASSIMP_IMPORTER(OPENGEX ADD_ASSIMP_IMPORTER( OPENGEX
OpenGEXExporter.cpp OpenGEXExporter.cpp
OpenGEXExporter.h OpenGEXExporter.h
OpenGEXImporter.cpp OpenGEXImporter.cpp
@ -365,7 +392,7 @@ ADD_ASSIMP_IMPORTER(OPENGEX
OpenGEXStructs.h OpenGEXStructs.h
) )
ADD_ASSIMP_IMPORTER(PLY ADD_ASSIMP_IMPORTER( PLY
PlyLoader.cpp PlyLoader.cpp
PlyLoader.h PlyLoader.h
PlyParser.cpp PlyParser.cpp
@ -374,18 +401,18 @@ ADD_ASSIMP_IMPORTER(PLY
PlyExporter.h PlyExporter.h
) )
ADD_ASSIMP_IMPORTER(MS3D ADD_ASSIMP_IMPORTER( MS3D
MS3DLoader.cpp MS3DLoader.cpp
MS3DLoader.h MS3DLoader.h
) )
ADD_ASSIMP_IMPORTER(COB ADD_ASSIMP_IMPORTER( COB
COBLoader.cpp COBLoader.cpp
COBLoader.h COBLoader.h
COBScene.h COBScene.h
) )
ADD_ASSIMP_IMPORTER(BLEND ADD_ASSIMP_IMPORTER( BLEND
BlenderLoader.cpp BlenderLoader.cpp
BlenderLoader.h BlenderLoader.h
BlenderDNA.cpp BlenderDNA.cpp
@ -403,7 +430,7 @@ ADD_ASSIMP_IMPORTER(BLEND
BlenderTessellator.cpp BlenderTessellator.cpp
) )
ADD_ASSIMP_IMPORTER(IFC ADD_ASSIMP_IMPORTER( IFC
IFCLoader.cpp IFCLoader.cpp
IFCLoader.h IFCLoader.h
IFCReaderGen.cpp IFCReaderGen.cpp
@ -422,14 +449,17 @@ ADD_ASSIMP_IMPORTER(IFC
STEPFileEncoding.cpp STEPFileEncoding.cpp
STEPFileEncoding.h STEPFileEncoding.h
) )
if (MSVC AND ASSIMP_BUILD_IFC_IMPORTER)
set_source_files_properties(IFCReaderGen.cpp PROPERTIES COMPILE_FLAGS "/bigobj")
endif (MSVC AND ASSIMP_BUILD_IFC_IMPORTER)
ADD_ASSIMP_IMPORTER(XGL ADD_ASSIMP_IMPORTER( XGL
XGLLoader.cpp XGLLoader.cpp
XGLLoader.h XGLLoader.h
) )
ADD_ASSIMP_IMPORTER(FBX ADD_ASSIMP_IMPORTER( FBX
FBXImporter.cpp FBXImporter.cpp
FBXCompileConfig.h FBXCompileConfig.h
FBXImporter.h FBXImporter.h
@ -446,6 +476,7 @@ ADD_ASSIMP_IMPORTER(FBX
FBXDocument.cpp FBXDocument.cpp
FBXProperties.h FBXProperties.h
FBXProperties.cpp FBXProperties.cpp
FBXMeshGeometry.h
FBXMeshGeometry.cpp FBXMeshGeometry.cpp
FBXMaterial.cpp FBXMaterial.cpp
FBXModel.cpp FBXModel.cpp
@ -511,12 +542,12 @@ SET( PostProcessing_SRCS
) )
SOURCE_GROUP( PostProcessing FILES ${PostProcessing_SRCS}) SOURCE_GROUP( PostProcessing FILES ${PostProcessing_SRCS})
ADD_ASSIMP_IMPORTER(Q3D ADD_ASSIMP_IMPORTER( Q3D
Q3DLoader.cpp Q3DLoader.cpp
Q3DLoader.h Q3DLoader.h
) )
ADD_ASSIMP_IMPORTER(Q3BSP ADD_ASSIMP_IMPORTER( Q3BSP
Q3BSPFileData.h Q3BSPFileData.h
Q3BSPFileParser.h Q3BSPFileParser.h
Q3BSPFileParser.cpp Q3BSPFileParser.cpp
@ -526,39 +557,39 @@ ADD_ASSIMP_IMPORTER(Q3BSP
Q3BSPZipArchive.cpp Q3BSPZipArchive.cpp
) )
ADD_ASSIMP_IMPORTER(RAW ADD_ASSIMP_IMPORTER( RAW
RawLoader.cpp RawLoader.cpp
RawLoader.h RawLoader.h
) )
ADD_ASSIMP_IMPORTER(SIB ADD_ASSIMP_IMPORTER( SIB
SIBImporter.cpp SIBImporter.cpp
SIBImporter.h SIBImporter.h
) )
ADD_ASSIMP_IMPORTER(SMD ADD_ASSIMP_IMPORTER( SMD
SMDLoader.cpp SMDLoader.cpp
SMDLoader.h SMDLoader.h
) )
ADD_ASSIMP_IMPORTER(STL ADD_ASSIMP_IMPORTER( STL
STLLoader.cpp STLLoader.cpp
STLLoader.h STLLoader.h
STLExporter.h STLExporter.h
STLExporter.cpp STLExporter.cpp
) )
ADD_ASSIMP_IMPORTER(TERRAGEN ADD_ASSIMP_IMPORTER( TERRAGEN
TerragenLoader.cpp TerragenLoader.cpp
TerragenLoader.h TerragenLoader.h
) )
ADD_ASSIMP_IMPORTER(3D ADD_ASSIMP_IMPORTER( 3D
UnrealLoader.cpp UnrealLoader.cpp
UnrealLoader.h UnrealLoader.h
) )
ADD_ASSIMP_IMPORTER(X ADD_ASSIMP_IMPORTER( X
XFileHelper.h XFileHelper.h
XFileImporter.cpp XFileImporter.cpp
XFileImporter.h XFileImporter.h
@ -568,19 +599,26 @@ ADD_ASSIMP_IMPORTER(X
XFileExporter.cpp XFileExporter.cpp
) )
ADD_ASSIMP_IMPORTER(GLTF ADD_ASSIMP_IMPORTER( GLTF
glTFAsset.h glTFAsset.h
glTFAsset.inl glTFAsset.inl
glTFAssetWriter.h glTFAssetWriter.h
glTFAssetWriter.inl glTFAssetWriter.inl
glTFImporter.cpp glTFImporter.cpp
glTFImporter.h glTFImporter.h
glTFExporter.h glTFExporter.h
glTFExporter.cpp glTFExporter.cpp
) )
ADD_ASSIMP_IMPORTER( 3MF
D3MFImporter.h
D3MFImporter.cpp
D3MFOpcPackage.h
D3MFOpcPackage.cpp
)
SET( Step_SRCS SET( Step_SRCS
StepExporter.h StepExporter.h
StepExporter.cpp StepExporter.cpp
@ -710,13 +748,12 @@ SET( assimp_src
${Clipper_SRCS} ${Clipper_SRCS}
${openddl_parser_SRCS} ${openddl_parser_SRCS}
# Necessary to show the headers in the project when using the VC++ generator: # Necessary to show the headers in the project when using the VC++ generator:
${Boost_SRCS}
${PUBLIC_HEADERS} ${PUBLIC_HEADERS}
${COMPILER_HEADERS} ${COMPILER_HEADERS}
) )
add_definitions( -DOPENDDLPARSER_BUILD ) ADD_DEFINITIONS( -DOPENDDLPARSER_BUILD )
INCLUDE_DIRECTORIES( INCLUDE_DIRECTORIES(
../contrib/openddlparser/include ../contrib/openddlparser/include
@ -738,8 +775,8 @@ if(ANDROID AND ASSIMP_ANDROID_JNIIOSYSTEM)
endif(ANDROID AND ASSIMP_ANDROID_JNIIOSYSTEM) endif(ANDROID AND ASSIMP_ANDROID_JNIIOSYSTEM)
IF (ASSIMP_BUILD_NONFREE_C4D_IMPORTER) IF (ASSIMP_BUILD_NONFREE_C4D_IMPORTER)
TARGET_LINK_LIBRARIES(assimp optimized ${C4D_RELEASE_LIBRARY}) TARGET_LINK_LIBRARIES(assimp optimized ${C4D_RELEASE_LIBRARIES})
TARGET_LINK_LIBRARIES(assimp debug ${C4D_DEBUG_LIBRARY}) TARGET_LINK_LIBRARIES(assimp debug ${C4D_DEBUG_LIBRARIES})
TARGET_LINK_LIBRARIES(assimp ${C4D_EXTRA_LIBRARIES}) TARGET_LINK_LIBRARIES(assimp ${C4D_EXTRA_LIBRARIES})
ENDIF (ASSIMP_BUILD_NONFREE_C4D_IMPORTER) ENDIF (ASSIMP_BUILD_NONFREE_C4D_IMPORTER)
@ -772,7 +809,7 @@ SET_TARGET_PROPERTIES( assimp PROPERTIES
) )
if (APPLE) if (APPLE)
SET_TARGET_PROPERTIES( assimp PROPERTIES INSTALL_NAME_DIR "${CMAKE_INSTALL_PREFIX}/${LIB_INSTALL_DIR}") SET_TARGET_PROPERTIES( assimp PROPERTIES INSTALL_NAME_DIR "${CMAKE_INSTALL_PREFIX}/${ASSIMP_LIB_INSTALL_DIR}")
endif() endif()
# Build against external unzip, or add ../contrib/unzip so # Build against external unzip, or add ../contrib/unzip so
@ -781,7 +818,7 @@ if (UNZIP_FOUND)
INCLUDE_DIRECTORIES(${UNZIP_INCLUDE_DIRS}) INCLUDE_DIRECTORIES(${UNZIP_INCLUDE_DIRS})
TARGET_LINK_LIBRARIES(assimp ${UNZIP_LIBRARIES}) TARGET_LINK_LIBRARIES(assimp ${UNZIP_LIBRARIES})
else (UNZIP_FOUND) else (UNZIP_FOUND)
INCLUDE_DIRECTORIES("../contrib/unzip") INCLUDE_DIRECTORIES("../")
endif (UNZIP_FOUND) endif (UNZIP_FOUND)
INSTALL( TARGETS assimp INSTALL( TARGETS assimp

View File

@ -53,19 +53,16 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "LineSplitter.h" #include "LineSplitter.h"
#include "TinyFormatter.h" #include "TinyFormatter.h"
#include <boost/scoped_ptr.hpp> #include <memory>
#include <boost/foreach.hpp> #include <assimp/IOSystem.hpp>
#include "../include/assimp/IOSystem.hpp" #include <assimp/DefaultLogger.hpp>
#include "../include/assimp/DefaultLogger.hpp" #include <assimp/scene.h>
#include "../include/assimp/scene.h"
using namespace Assimp; using namespace Assimp;
using namespace Assimp::COB; using namespace Assimp::COB;
using namespace Assimp::Formatter; using namespace Assimp::Formatter;
#define for_each BOOST_FOREACH
static const float units[] = { static const float units[] = {
1000.f, 1000.f,
@ -144,7 +141,7 @@ void COBImporter::InternReadFile( const std::string& pFile,
aiScene* pScene, IOSystem* pIOHandler) aiScene* pScene, IOSystem* pIOHandler)
{ {
COB::Scene scene; COB::Scene scene;
boost::scoped_ptr<StreamReaderLE> stream(new StreamReaderLE( pIOHandler->Open(pFile,"rb")) ); std::unique_ptr<StreamReaderLE> stream(new StreamReaderLE( pIOHandler->Open(pFile,"rb")) );
// check header // check header
char head[32]; char head[32];
@ -170,17 +167,17 @@ void COBImporter::InternReadFile( const std::string& pFile,
} }
// sort faces by material indices // sort faces by material indices
for_each(boost::shared_ptr< Node >& n,scene.nodes) { for(std::shared_ptr< Node >& n : scene.nodes) {
if (n->type == Node::TYPE_MESH) { if (n->type == Node::TYPE_MESH) {
Mesh& mesh = (Mesh&)(*n.get()); Mesh& mesh = (Mesh&)(*n.get());
for_each(Face& f,mesh.faces) { for(Face& f : mesh.faces) {
mesh.temp_map[f.material].push_back(&f); mesh.temp_map[f.material].push_back(&f);
} }
} }
} }
// count meshes // count meshes
for_each(boost::shared_ptr< Node >& n,scene.nodes) { for(std::shared_ptr< Node >& n : scene.nodes) {
if (n->type == Node::TYPE_MESH) { if (n->type == Node::TYPE_MESH) {
Mesh& mesh = (Mesh&)(*n.get()); Mesh& mesh = (Mesh&)(*n.get());
if (mesh.vertex_positions.size() && mesh.texture_coords.size()) { if (mesh.vertex_positions.size() && mesh.texture_coords.size()) {
@ -193,7 +190,7 @@ void COBImporter::InternReadFile( const std::string& pFile,
pScene->mNumMeshes = 0; pScene->mNumMeshes = 0;
// count lights and cameras // count lights and cameras
for_each(boost::shared_ptr< Node >& n,scene.nodes) { for(std::shared_ptr< Node >& n : scene.nodes) {
if (n->type == Node::TYPE_LIGHT) { if (n->type == Node::TYPE_LIGHT) {
++pScene->mNumLights; ++pScene->mNumLights;
} }
@ -211,7 +208,7 @@ void COBImporter::InternReadFile( const std::string& pFile,
pScene->mNumLights = pScene->mNumCameras = 0; pScene->mNumLights = pScene->mNumCameras = 0;
// resolve parents by their IDs and build the output graph // resolve parents by their IDs and build the output graph
boost::scoped_ptr<Node> root(new Group()); std::unique_ptr<Node> root(new Group());
for(size_t n = 0; n < scene.nodes.size(); ++n) { for(size_t n = 0; n < scene.nodes.size(); ++n) {
const Node& nn = *scene.nodes[n].get(); const Node& nn = *scene.nodes[n].get();
if(nn.parent_id==0) { if(nn.parent_id==0) {
@ -230,7 +227,7 @@ void COBImporter::InternReadFile( const std::string& pFile,
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
void ConvertTexture(boost::shared_ptr< Texture > tex, aiMaterial* out, aiTextureType type) void ConvertTexture(std::shared_ptr< Texture > tex, aiMaterial* out, aiTextureType type)
{ {
const aiString path( tex->path ); const aiString path( tex->path );
out->AddProperty(&path,AI_MATKEY_TEXTURE(type,0)); out->AddProperty(&path,AI_MATKEY_TEXTURE(type,0));
@ -251,10 +248,10 @@ aiNode* COBImporter::BuildNodes(const Node& root,const Scene& scin,aiScene* fill
if (ndmesh.vertex_positions.size() && ndmesh.texture_coords.size()) { if (ndmesh.vertex_positions.size() && ndmesh.texture_coords.size()) {
typedef std::pair<unsigned int,Mesh::FaceRefList> Entry; typedef std::pair<unsigned int,Mesh::FaceRefList> Entry;
for_each(const Entry& reflist,ndmesh.temp_map) { for(const Entry& reflist : ndmesh.temp_map) {
{ // create mesh { // create mesh
size_t n = 0; size_t n = 0;
for_each(Face* f, reflist.second) { for(Face* f : reflist.second) {
n += f->indices.size(); n += f->indices.size();
} }
if (!n) { if (!n) {
@ -267,7 +264,7 @@ aiNode* COBImporter::BuildNodes(const Node& root,const Scene& scin,aiScene* fill
outmesh->mTextureCoords[0] = new aiVector3D[n]; outmesh->mTextureCoords[0] = new aiVector3D[n];
outmesh->mFaces = new aiFace[reflist.second.size()](); outmesh->mFaces = new aiFace[reflist.second.size()]();
for_each(Face* f, reflist.second) { for(Face* f : reflist.second) {
if (f->indices.empty()) { if (f->indices.empty()) {
continue; continue;
} }
@ -275,7 +272,7 @@ aiNode* COBImporter::BuildNodes(const Node& root,const Scene& scin,aiScene* fill
aiFace& fout = outmesh->mFaces[outmesh->mNumFaces++]; aiFace& fout = outmesh->mFaces[outmesh->mNumFaces++];
fout.mIndices = new unsigned int[f->indices.size()]; fout.mIndices = new unsigned int[f->indices.size()];
for_each(VertexIndex& v, f->indices) { for(VertexIndex& v : f->indices) {
if (v.pos_idx >= ndmesh.vertex_positions.size()) { if (v.pos_idx >= ndmesh.vertex_positions.size()) {
ThrowException("Position index out of range"); ThrowException("Position index out of range");
} }
@ -295,13 +292,13 @@ aiNode* COBImporter::BuildNodes(const Node& root,const Scene& scin,aiScene* fill
outmesh->mMaterialIndex = fill->mNumMaterials; outmesh->mMaterialIndex = fill->mNumMaterials;
}{ // create material }{ // create material
const Material* min = NULL; const Material* min = NULL;
for_each(const Material& m, scin.materials) { for(const Material& m : scin.materials) {
if (m.parent_id == ndmesh.id && m.matnum == reflist.first) { if (m.parent_id == ndmesh.id && m.matnum == reflist.first) {
min = &m; min = &m;
break; break;
} }
} }
boost::scoped_ptr<const Material> defmat; std::unique_ptr<const Material> defmat;
if(!min) { if(!min) {
DefaultLogger::get()->debug(format()<<"Could not resolve material index " DefaultLogger::get()->debug(format()<<"Could not resolve material index "
<<reflist.first<<" - creating default material for this slot"); <<reflist.first<<" - creating default material for this slot");
@ -396,7 +393,7 @@ aiNode* COBImporter::BuildNodes(const Node& root,const Scene& scin,aiScene* fill
// add children recursively // add children recursively
nd->mChildren = new aiNode*[root.temp_children.size()](); nd->mChildren = new aiNode*[root.temp_children.size()]();
for_each(const Node* n, root.temp_children) { for(const Node* n : root.temp_children) {
(nd->mChildren[nd->mNumChildren++] = BuildNodes(*n,scin,fill))->mParent = nd; (nd->mChildren[nd->mNumChildren++] = BuildNodes(*n,scin,fill))->mParent = nd;
} }
@ -647,7 +644,7 @@ void COBImporter::ReadUnit_Ascii(Scene& out, LineSplitter& splitter, const Chunk
// parent chunks preceede their childs, so we should have the // parent chunks preceede their childs, so we should have the
// corresponding chunk already. // corresponding chunk already.
for_each(boost::shared_ptr< Node >& nd, out.nodes) { for(std::shared_ptr< Node >& nd : out.nodes) {
if (nd->id == nfo.parent_id) { if (nd->id == nfo.parent_id) {
const unsigned int t=strtoul10(splitter[1]); const unsigned int t=strtoul10(splitter[1]);
@ -676,7 +673,7 @@ void COBImporter::ReadLght_Ascii(Scene& out, LineSplitter& splitter, const Chunk
return UnsupportedChunk_Ascii(splitter,nfo,"Lght"); return UnsupportedChunk_Ascii(splitter,nfo,"Lght");
} }
out.nodes.push_back(boost::shared_ptr<Light>(new Light())); out.nodes.push_back(std::shared_ptr<Light>(new Light()));
Light& msh = (Light&)(*out.nodes.back().get()); Light& msh = (Light&)(*out.nodes.back().get());
msh = nfo; msh = nfo;
@ -732,7 +729,7 @@ void COBImporter::ReadCame_Ascii(Scene& out, LineSplitter& splitter, const Chunk
return UnsupportedChunk_Ascii(splitter,nfo,"Came"); return UnsupportedChunk_Ascii(splitter,nfo,"Came");
} }
out.nodes.push_back(boost::shared_ptr<Camera>(new Camera())); out.nodes.push_back(std::shared_ptr<Camera>(new Camera()));
Camera& msh = (Camera&)(*out.nodes.back().get()); Camera& msh = (Camera&)(*out.nodes.back().get());
msh = nfo; msh = nfo;
@ -750,7 +747,7 @@ void COBImporter::ReadBone_Ascii(Scene& out, LineSplitter& splitter, const Chunk
return UnsupportedChunk_Ascii(splitter,nfo,"Bone"); return UnsupportedChunk_Ascii(splitter,nfo,"Bone");
} }
out.nodes.push_back(boost::shared_ptr<Bone>(new Bone())); out.nodes.push_back(std::shared_ptr<Bone>(new Bone()));
Bone& msh = (Bone&)(*out.nodes.back().get()); Bone& msh = (Bone&)(*out.nodes.back().get());
msh = nfo; msh = nfo;
@ -766,7 +763,7 @@ void COBImporter::ReadGrou_Ascii(Scene& out, LineSplitter& splitter, const Chunk
return UnsupportedChunk_Ascii(splitter,nfo,"Grou"); return UnsupportedChunk_Ascii(splitter,nfo,"Grou");
} }
out.nodes.push_back(boost::shared_ptr<Group>(new Group())); out.nodes.push_back(std::shared_ptr<Group>(new Group()));
Group& msh = (Group&)(*out.nodes.back().get()); Group& msh = (Group&)(*out.nodes.back().get());
msh = nfo; msh = nfo;
@ -780,7 +777,7 @@ void COBImporter::ReadPolH_Ascii(Scene& out, LineSplitter& splitter, const Chunk
return UnsupportedChunk_Ascii(splitter,nfo,"PolH"); return UnsupportedChunk_Ascii(splitter,nfo,"PolH");
} }
out.nodes.push_back(boost::shared_ptr<Mesh>(new Mesh())); out.nodes.push_back(std::shared_ptr<Mesh>(new Mesh()));
Mesh& msh = (Mesh&)(*out.nodes.back().get()); Mesh& msh = (Mesh&)(*out.nodes.back().get());
msh = nfo; msh = nfo;
@ -903,7 +900,7 @@ void COBImporter::ReadBitM_Ascii(Scene& /*out*/, LineSplitter& splitter, const C
void COBImporter::ReadString_Binary(std::string& out, StreamReaderLE& reader) void COBImporter::ReadString_Binary(std::string& out, StreamReaderLE& reader)
{ {
out.resize( reader.GetI2()); out.resize( reader.GetI2());
for_each(char& c,out) { for(char& c : out) {
c = reader.GetI1(); c = reader.GetI1();
} }
} }
@ -1036,21 +1033,21 @@ void COBImporter::ReadPolH_Binary(COB::Scene& out, StreamReaderLE& reader, const
} }
const chunk_guard cn(nfo,reader); const chunk_guard cn(nfo,reader);
out.nodes.push_back(boost::shared_ptr<Mesh>(new Mesh())); out.nodes.push_back(std::shared_ptr<Mesh>(new Mesh()));
Mesh& msh = (Mesh&)(*out.nodes.back().get()); Mesh& msh = (Mesh&)(*out.nodes.back().get());
msh = nfo; msh = nfo;
ReadBasicNodeInfo_Binary(msh,reader,nfo); ReadBasicNodeInfo_Binary(msh,reader,nfo);
msh.vertex_positions.resize(reader.GetI4()); msh.vertex_positions.resize(reader.GetI4());
for_each(aiVector3D& v,msh.vertex_positions) { for(aiVector3D& v : msh.vertex_positions) {
v.x = reader.GetF4(); v.x = reader.GetF4();
v.y = reader.GetF4(); v.y = reader.GetF4();
v.z = reader.GetF4(); v.z = reader.GetF4();
} }
msh.texture_coords.resize(reader.GetI4()); msh.texture_coords.resize(reader.GetI4());
for_each(aiVector2D& v,msh.texture_coords) { for(aiVector2D& v : msh.texture_coords) {
v.x = reader.GetF4(); v.x = reader.GetF4();
v.y = reader.GetF4(); v.y = reader.GetF4();
} }
@ -1226,7 +1223,7 @@ void COBImporter::ReadCame_Binary(COB::Scene& out, StreamReaderLE& reader, const
const chunk_guard cn(nfo,reader); const chunk_guard cn(nfo,reader);
out.nodes.push_back(boost::shared_ptr<Camera>(new Camera())); out.nodes.push_back(std::shared_ptr<Camera>(new Camera()));
Camera& msh = (Camera&)(*out.nodes.back().get()); Camera& msh = (Camera&)(*out.nodes.back().get());
msh = nfo; msh = nfo;
@ -1249,7 +1246,7 @@ void COBImporter::ReadLght_Binary(COB::Scene& out, StreamReaderLE& reader, const
const chunk_guard cn(nfo,reader); const chunk_guard cn(nfo,reader);
out.nodes.push_back(boost::shared_ptr<Light>(new Light())); out.nodes.push_back(std::shared_ptr<Light>(new Light()));
Light& msh = (Light&)(*out.nodes.back().get()); Light& msh = (Light&)(*out.nodes.back().get());
msh = nfo; msh = nfo;
@ -1265,7 +1262,7 @@ void COBImporter::ReadGrou_Binary(COB::Scene& out, StreamReaderLE& reader, const
const chunk_guard cn(nfo,reader); const chunk_guard cn(nfo,reader);
out.nodes.push_back(boost::shared_ptr<Group>(new Group())); out.nodes.push_back(std::shared_ptr<Group>(new Group()));
Group& msh = (Group&)(*out.nodes.back().get()); Group& msh = (Group&)(*out.nodes.back().get());
msh = nfo; msh = nfo;
@ -1283,7 +1280,7 @@ void COBImporter::ReadUnit_Binary(COB::Scene& out, StreamReaderLE& reader, const
// parent chunks preceede their childs, so we should have the // parent chunks preceede their childs, so we should have the
// corresponding chunk already. // corresponding chunk already.
for_each(boost::shared_ptr< Node >& nd, out.nodes) { for(std::shared_ptr< Node >& nd : out.nodes) {
if (nd->id == nfo.parent_id) { if (nd->id == nfo.parent_id) {
const unsigned int t=reader.GetI2(); const unsigned int t=reader.GetI2();
nd->unit_scale = t>=sizeof(units)/sizeof(units[0])?( nd->unit_scale = t>=sizeof(units)/sizeof(units[0])?(

View File

@ -44,7 +44,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef INCLUDED_AI_COB_SCENE_H #ifndef INCLUDED_AI_COB_SCENE_H
#define INCLUDED_AI_COB_SCENE_H #define INCLUDED_AI_COB_SCENE_H
#include <boost/shared_ptr.hpp> #include <memory>
#include <deque> #include <deque>
#include "BaseImporter.h" #include "BaseImporter.h"
@ -237,7 +237,7 @@ struct Material : ChunkInfo
AutoFacet autofacet; AutoFacet autofacet;
float autofacet_angle; float autofacet_angle;
boost::shared_ptr<Texture> tex_env,tex_bump,tex_color; std::shared_ptr<Texture> tex_env,tex_bump,tex_color;
}; };
// ------------------ // ------------------
@ -254,7 +254,7 @@ struct Bitmap : ChunkInfo
std::vector<char> buff_zipped; std::vector<char> buff_zipped;
}; };
typedef std::deque< boost::shared_ptr<Node> > NodeList; typedef std::deque< std::shared_ptr<Node> > NodeList;
typedef std::vector< Material > MaterialList; typedef std::vector< Material > MaterialList;
// ------------------ // ------------------

View File

@ -51,12 +51,12 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "SkeletonMeshBuilder.h" #include "SkeletonMeshBuilder.h"
#include "ParsingUtils.h" #include "ParsingUtils.h"
#include "fast_atof.h" #include "fast_atof.h"
#include "../include/assimp/Importer.hpp" #include <assimp/Importer.hpp>
#include <boost/scoped_ptr.hpp> #include <memory>
#include "../include/assimp/IOSystem.hpp" #include <assimp/IOSystem.hpp>
#include "../include/assimp/anim.h" #include <assimp/anim.h>
#include "../include/assimp/DefaultLogger.hpp" #include <assimp/DefaultLogger.hpp>
#include "../include/assimp/scene.h" #include <assimp/scene.h>
using namespace Assimp; using namespace Assimp;
@ -122,7 +122,7 @@ void CSMImporter::SetupProperties(const Importer* pImp)
void CSMImporter::InternReadFile( const std::string& pFile, void CSMImporter::InternReadFile( const std::string& pFile,
aiScene* pScene, IOSystem* pIOHandler) aiScene* pScene, IOSystem* pIOHandler)
{ {
boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb")); std::unique_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
// Check whether we can read from the file // Check whether we can read from the file
if( file.get() == NULL) { if( file.get() == NULL) {
@ -227,7 +227,7 @@ void CSMImporter::InternReadFile( const std::string& pFile,
// read x,y,z // read x,y,z
if(!SkipSpacesAndLineEnd(&buffer)) if(!SkipSpacesAndLineEnd(&buffer))
throw DeadlyImportError("CSM: Unexpected EOF occured reading sample x coord"); throw DeadlyImportError("CSM: Unexpected EOF occurred reading sample x coord");
if (TokenMatchI(buffer, "DROPOUT", 7)) { if (TokenMatchI(buffer, "DROPOUT", 7)) {
// seems this is invalid marker data; at least the doc says it's possible // seems this is invalid marker data; at least the doc says it's possible
@ -239,11 +239,11 @@ void CSMImporter::InternReadFile( const std::string& pFile,
buffer = fast_atoreal_move<float>(buffer, (float&)sub->mValue.x); buffer = fast_atoreal_move<float>(buffer, (float&)sub->mValue.x);
if(!SkipSpacesAndLineEnd(&buffer)) if(!SkipSpacesAndLineEnd(&buffer))
throw DeadlyImportError("CSM: Unexpected EOF occured reading sample y coord"); throw DeadlyImportError("CSM: Unexpected EOF occurred reading sample y coord");
buffer = fast_atoreal_move<float>(buffer, (float&)sub->mValue.y); buffer = fast_atoreal_move<float>(buffer, (float&)sub->mValue.y);
if(!SkipSpacesAndLineEnd(&buffer)) if(!SkipSpacesAndLineEnd(&buffer))
throw DeadlyImportError("CSM: Unexpected EOF occured reading sample z coord"); throw DeadlyImportError("CSM: Unexpected EOF occurred reading sample z coord");
buffer = fast_atoreal_move<float>(buffer, (float&)sub->mValue.z); buffer = fast_atoreal_move<float>(buffer, (float&)sub->mValue.z);
++s->mNumPositionKeys; ++s->mNumPositionKeys;

View File

@ -108,7 +108,7 @@ void CalcTangentsProcess::Execute( aiScene* pScene)
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// Calculates tangents and bitangents for the given mesh // Calculates tangents and bi-tangents for the given mesh
bool CalcTangentsProcess::ProcessMesh( aiMesh* pMesh, unsigned int meshIndex) bool CalcTangentsProcess::ProcessMesh( aiMesh* pMesh, unsigned int meshIndex)
{ {
// we assume that the mesh is still in the verbose vertex format where each face has its own set // we assume that the mesh is still in the verbose vertex format where each face has its own set

View File

@ -49,13 +49,13 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "SceneCombiner.h" #include "SceneCombiner.h"
#include "DefaultIOSystem.h" #include "DefaultIOSystem.h"
#include "XMLTools.h" #include "XMLTools.h"
#include "../include/assimp/IOSystem.hpp" #include <assimp/IOSystem.hpp>
#include "../include/assimp/Exporter.hpp" #include <assimp/Exporter.hpp>
#include "../include/assimp/scene.h" #include <assimp/scene.h>
#include "Exceptional.h" #include "Exceptional.h"
#include <boost/scoped_ptr.hpp> #include <memory>
#include <ctime> #include <ctime>
#include <set> #include <set>
@ -75,7 +75,7 @@ void ExportSceneCollada(const char* pFile, IOSystem* pIOSystem, const aiScene* p
ColladaExporter iDoTheExportThing( pScene, pIOSystem, path, file); ColladaExporter iDoTheExportThing( pScene, pIOSystem, path, file);
// we're still here - export successfully completed. Write result to the given IOSYstem // we're still here - export successfully completed. Write result to the given IOSYstem
boost::scoped_ptr<IOStream> outfile (pIOSystem->Open(pFile,"wt")); std::unique_ptr<IOStream> outfile (pIOSystem->Open(pFile,"wt"));
if(outfile == NULL) { if(outfile == NULL) {
throw DeadlyExportError("could not open output .dae file: " + std::string(pFile)); throw DeadlyExportError("could not open output .dae file: " + std::string(pFile));
} }
@ -94,6 +94,7 @@ ColladaExporter::ColladaExporter( const aiScene* pScene, IOSystem* pIOSystem, co
{ {
// make sure that all formatting happens using the standard, C locale and not the user's current locale // make sure that all formatting happens using the standard, C locale and not the user's current locale
mOutput.imbue( std::locale("C") ); mOutput.imbue( std::locale("C") );
mOutput.precision(16);
mScene = pScene; mScene = pScene;
mSceneOwned = false; mSceneOwned = false;
@ -148,7 +149,7 @@ void ColladaExporter::WriteFile()
// Writes the asset header // Writes the asset header
void ColladaExporter::WriteHeader() void ColladaExporter::WriteHeader()
{ {
static const float epsilon = 0.00001f; static const ai_real epsilon = 0.00001;
static const aiQuaternion x_rot(aiMatrix3x3( static const aiQuaternion x_rot(aiMatrix3x3(
0, -1, 0, 0, -1, 0,
1, 0, 0, 1, 0, 0,
@ -175,9 +176,9 @@ void ColladaExporter::WriteHeader()
bool add_root_node = false; bool add_root_node = false;
float scale = 1.0; ai_real scale = 1.0;
if(std::abs(scaling.x - scaling.y) <= epsilon && std::abs(scaling.x - scaling.z) <= epsilon && std::abs(scaling.y - scaling.z) <= epsilon) { if(std::abs(scaling.x - scaling.y) <= epsilon && std::abs(scaling.x - scaling.z) <= epsilon && std::abs(scaling.y - scaling.z) <= epsilon) {
scale = (float) ((((double) scaling.x) + ((double) scaling.y) + ((double) scaling.z)) / 3.0); scale = (ai_real) ((((double) scaling.x) + ((double) scaling.y) + ((double) scaling.z)) / 3.0);
} else { } else {
add_root_node = true; add_root_node = true;
} }
@ -268,7 +269,7 @@ void ColladaExporter::WriteTextures() {
std::string name = mFile + "_texture_" + (i < 1000 ? "0" : "") + (i < 100 ? "0" : "") + (i < 10 ? "0" : "") + str + "." + ((const char*) texture->achFormatHint); std::string name = mFile + "_texture_" + (i < 1000 ? "0" : "") + (i < 100 ? "0" : "") + (i < 10 ? "0" : "") + str + "." + ((const char*) texture->achFormatHint);
boost::scoped_ptr<IOStream> outfile(mIOSystem->Open(mPath + name, "wb")); std::unique_ptr<IOStream> outfile(mIOSystem->Open(mPath + name, "wb"));
if(outfile == NULL) { if(outfile == NULL) {
throw DeadlyExportError("could not open output texture file: " + mPath + name); throw DeadlyExportError("could not open output texture file: " + mPath + name);
} }
@ -449,7 +450,7 @@ void ColladaExporter::WriteSpotLight(const aiLight *const light){
srcLight->mFalloffAngle); srcLight->mFalloffAngle);
*/ */
const float fallOffAngle = AI_RAD_TO_DEG(light->mAngleInnerCone); const ai_real fallOffAngle = AI_RAD_TO_DEG(light->mAngleInnerCone);
mOutput << startstr <<"<falloff_angle sid=\"fall_off_angle\">" mOutput << startstr <<"<falloff_angle sid=\"fall_off_angle\">"
<< fallOffAngle << fallOffAngle
<<"</falloff_angle>" << endstr; <<"</falloff_angle>" << endstr;
@ -530,7 +531,7 @@ void ColladaExporter::ReadMaterialSurface( Surface& poSurface, const aiMaterial*
// Reimplementation of isalnum(,C locale), because AppVeyor does not see standard version. // Reimplementation of isalnum(,C locale), because AppVeyor does not see standard version.
static bool isalnum_C(char c) static bool isalnum_C(char c)
{ {
return strchr("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",c); return ( nullptr != strchr("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",c) );
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
@ -636,7 +637,7 @@ void ColladaExporter::WriteMaterials()
aiString name; aiString name;
if( mat->Get( AI_MATKEY_NAME, name) != aiReturn_SUCCESS ) if( mat->Get( AI_MATKEY_NAME, name) != aiReturn_SUCCESS )
name = "mat"; name = "mat";
materials[a].name = std::string( "m") + boost::lexical_cast<std::string> (a) + name.C_Str(); materials[a].name = std::string( "m") + std::to_string(a) + name.C_Str();
for( std::string::iterator it = materials[a].name.begin(); it != materials[a].name.end(); ++it ) { for( std::string::iterator it = materials[a].name.begin(); it != materials[a].name.end(); ++it ) {
if( !isalnum_C( *it ) ) { if( !isalnum_C( *it ) ) {
*it = '_'; *it = '_';
@ -802,18 +803,18 @@ void ColladaExporter::WriteGeometry( size_t pIndex)
PushTag(); PushTag();
// Positions // Positions
WriteFloatArray( idstr + "-positions", FloatType_Vector, (float*) mesh->mVertices, mesh->mNumVertices); WriteFloatArray( idstr + "-positions", FloatType_Vector, (ai_real*) mesh->mVertices, mesh->mNumVertices);
// Normals, if any // Normals, if any
if( mesh->HasNormals() ) if( mesh->HasNormals() )
WriteFloatArray( idstr + "-normals", FloatType_Vector, (float*) mesh->mNormals, mesh->mNumVertices); WriteFloatArray( idstr + "-normals", FloatType_Vector, (ai_real*) mesh->mNormals, mesh->mNumVertices);
// texture coords // texture coords
for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a) for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a)
{ {
if( mesh->HasTextureCoords( a) ) if( mesh->HasTextureCoords( a) )
{ {
WriteFloatArray( idstr + "-tex" + boost::lexical_cast<std::string> (a), mesh->mNumUVComponents[a] == 3 ? FloatType_TexCoord3 : FloatType_TexCoord2, WriteFloatArray( idstr + "-tex" + std::to_string(a), mesh->mNumUVComponents[a] == 3 ? FloatType_TexCoord3 : FloatType_TexCoord2,
(float*) mesh->mTextureCoords[a], mesh->mNumVertices); (ai_real*) mesh->mTextureCoords[a], mesh->mNumVertices);
} }
} }
@ -821,7 +822,7 @@ void ColladaExporter::WriteGeometry( size_t pIndex)
for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a) for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a)
{ {
if( mesh->HasVertexColors( a) ) if( mesh->HasVertexColors( a) )
WriteFloatArray( idstr + "-color" + boost::lexical_cast<std::string> (a), FloatType_Color, (float*) mesh->mColors[a], mesh->mNumVertices); WriteFloatArray( idstr + "-color" + std::to_string(a), FloatType_Color, (ai_real*) mesh->mColors[a], mesh->mNumVertices);
} }
// assemble vertex structure // assemble vertex structure
@ -872,7 +873,7 @@ void ColladaExporter::WriteGeometry( size_t pIndex)
mOutput << startstr << "</lines>" << endstr; mOutput << startstr << "</lines>" << endstr;
} }
// triangle - dont use it, because compatibility problems // triangle - don't use it, because compatibility problems
// polygons // polygons
if (countPoly) if (countPoly)
@ -916,7 +917,7 @@ void ColladaExporter::WriteGeometry( size_t pIndex)
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// Writes a float array of the given type // Writes a float array of the given type
void ColladaExporter::WriteFloatArray( const std::string& pIdString, FloatDataType pType, const float* pData, size_t pElementCount) void ColladaExporter::WriteFloatArray( const std::string& pIdString, FloatDataType pType, const ai_real* pData, size_t pElementCount)
{ {
size_t floatsPerElement = 0; size_t floatsPerElement = 0;
switch( pType ) switch( pType )
@ -1016,7 +1017,7 @@ void ColladaExporter::WriteSceneLibrary()
// start recursive write at the root node // start recursive write at the root node
for( size_t a = 0; a < mScene->mRootNode->mNumChildren; ++a ) for( size_t a = 0; a < mScene->mRootNode->mNumChildren; ++a )
WriteNode( mScene->mRootNode->mChildren[a]); WriteNode( mScene, mScene->mRootNode->mChildren[a]);
PopTag(); PopTag();
mOutput << startstr << "</visual_scene>" << endstr; mOutput << startstr << "</visual_scene>" << endstr;
@ -1024,11 +1025,26 @@ void ColladaExporter::WriteSceneLibrary()
mOutput << startstr << "</library_visual_scenes>" << endstr; mOutput << startstr << "</library_visual_scenes>" << endstr;
} }
// ------------------------------------------------------------------------------------------------
// Helper to find a bone by name in the scene
aiBone* findBone( const aiScene* scene, const char * name) {
for (size_t m=0; m<scene->mNumMeshes; m++) {
aiMesh * mesh = scene->mMeshes[m];
for (size_t b=0; b<mesh->mNumBones; b++) {
aiBone * bone = mesh->mBones[b];
if (0 == strcmp(name, bone->mName.C_Str())) {
return bone;
}
}
}
return NULL;
}
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// Recursively writes the given node // Recursively writes the given node
void ColladaExporter::WriteNode(aiNode* pNode) void ColladaExporter::WriteNode( const aiScene* pScene, aiNode* pNode)
{ {
// the must have a name // the node must have a name
if (pNode->mName.length == 0) if (pNode->mName.length == 0)
{ {
std::stringstream ss; std::stringstream ss;
@ -1036,12 +1052,25 @@ void ColladaExporter::WriteNode(aiNode* pNode)
pNode->mName.Set(ss.str()); pNode->mName.Set(ss.str());
} }
// If the node is associated with a bone, it is a joint node (JOINT)
// otherwise it is a normal node (NODE)
const char * node_type;
if (NULL == findBone(pScene, pNode->mName.C_Str())) {
node_type = "NODE";
} else {
node_type = "JOINT";
}
const std::string node_name_escaped = XMLEscape(pNode->mName.data); const std::string node_name_escaped = XMLEscape(pNode->mName.data);
mOutput << startstr << "<node id=\"" << node_name_escaped << "\" name=\"" << node_name_escaped << "\">" << endstr; mOutput << startstr
<< "<node id=\"" << node_name_escaped
<< "\" name=\"" << node_name_escaped
<< "\" type=\"" << node_type
<< "\">" << endstr;
PushTag(); PushTag();
// write transformation - we can directly put the matrix there // write transformation - we can directly put the matrix there
// TODO: (thom) decompose into scale - rot - quad to allow adressing it by animations afterwards // TODO: (thom) decompose into scale - rot - quad to allow addressing it by animations afterwards
const aiMatrix4x4& mat = pNode->mTransformation; const aiMatrix4x4& mat = pNode->mTransformation;
mOutput << startstr << "<matrix>"; mOutput << startstr << "<matrix>";
mOutput << mat.a1 << " " << mat.a2 << " " << mat.a3 << " " << mat.a4 << " "; mOutput << mat.a1 << " " << mat.a2 << " " << mat.a3 << " " << mat.a4 << " ";
@ -1102,7 +1131,7 @@ void ColladaExporter::WriteNode(aiNode* pNode)
// recurse into subnodes // recurse into subnodes
for( size_t a = 0; a < pNode->mNumChildren; ++a ) for( size_t a = 0; a < pNode->mNumChildren; ++a )
WriteNode( pNode->mChildren[a]); WriteNode( pScene, pNode->mChildren[a]);
PopTag(); PopTag();
mOutput << startstr << "</node>" << endstr; mOutput << startstr << "</node>" << endstr;

View File

@ -44,15 +44,14 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef AI_COLLADAEXPORTER_H_INC #ifndef AI_COLLADAEXPORTER_H_INC
#define AI_COLLADAEXPORTER_H_INC #define AI_COLLADAEXPORTER_H_INC
#include "../include/assimp/ai_assert.h" #include <assimp/ai_assert.h>
#include "../include/assimp/material.h" #include <assimp/material.h>
#include "../include/assimp/mesh.h" #include <assimp/mesh.h>
#include "../include/assimp/light.h" #include <assimp/light.h>
#include "../include/assimp/Exporter.hpp" #include <assimp/Exporter.hpp>
#include <sstream> #include <sstream>
#include <vector> #include <vector>
#include <map> #include <map>
#include <boost/lexical_cast.hpp>
struct aiScene; struct aiScene;
struct aiNode; struct aiNode;
@ -109,13 +108,13 @@ protected:
enum FloatDataType { FloatType_Vector, FloatType_TexCoord2, FloatType_TexCoord3, FloatType_Color }; enum FloatDataType { FloatType_Vector, FloatType_TexCoord2, FloatType_TexCoord3, FloatType_Color };
/// Writes a float array of the given type /// Writes a float array of the given type
void WriteFloatArray( const std::string& pIdString, FloatDataType pType, const float* pData, size_t pElementCount); void WriteFloatArray( const std::string& pIdString, FloatDataType pType, const ai_real* pData, size_t pElementCount);
/// Writes the scene library /// Writes the scene library
void WriteSceneLibrary(); void WriteSceneLibrary();
/// Recursively writes the given node /// Recursively writes the given node
void WriteNode( aiNode* pNode); void WriteNode( const aiScene* scene, aiNode* pNode);
/// Enters a new xml element, which increases the indentation /// Enters a new xml element, which increases the indentation
void PushTag() { startstr.append( " "); } void PushTag() { startstr.append( " "); }
@ -123,7 +122,7 @@ protected:
void PopTag() { ai_assert( startstr.length() > 1); startstr.erase( startstr.length() - 2); } void PopTag() { ai_assert( startstr.length() > 1); startstr.erase( startstr.length() - 2); }
/// Creates a mesh ID for the given mesh /// Creates a mesh ID for the given mesh
std::string GetMeshId( size_t pIndex) const { return std::string( "meshId" ) + boost::lexical_cast<std::string> (pIndex); } std::string GetMeshId( size_t pIndex) const { return std::string( "meshId" ) + std::to_string(pIndex); }
public: public:
/// Stringstream to write all output into /// Stringstream to write all output into
@ -161,10 +160,10 @@ protected:
struct Property struct Property
{ {
bool exist; bool exist;
float value; ai_real value;
Property() Property()
: exist(false) : exist(false)
, value(0.0f) , value(0.0)
{} {}
}; };

View File

@ -47,9 +47,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <map> #include <map>
#include <vector> #include <vector>
#include <stdint.h> #include <stdint.h>
#include "../include/assimp/light.h" #include <assimp/light.h>
#include "../include/assimp/mesh.h" #include <assimp/mesh.h>
#include "../include/assimp/material.h" #include <assimp/material.h>
struct aiMaterial; struct aiMaterial;
@ -94,7 +94,7 @@ struct Transform
{ {
std::string mID; ///< SID of the transform step, by which anim channels address their target node std::string mID; ///< SID of the transform step, by which anim channels address their target node
TransformType mType; TransformType mType;
float f[16]; ///< Interpretation of data depends on the type of the transformation ai_real f[16]; ///< Interpretation of data depends on the type of the transformation
}; };
/** A collada camera. */ /** A collada camera. */
@ -116,16 +116,16 @@ struct Camera
bool mOrtho; bool mOrtho;
//! Horizontal field of view in degrees //! Horizontal field of view in degrees
float mHorFov; ai_real mHorFov;
//! Vertical field of view in degrees //! Vertical field of view in degrees
float mVerFov; ai_real mVerFov;
//! Screen aspect //! Screen aspect
float mAspect; ai_real mAspect;
//! Near& far z //! Near& far z
float mZNear, mZFar; ai_real mZNear, mZFar;
}; };
#define ASSIMP_COLLADA_LIGHT_ANGLE_NOT_SET 1e9f #define ASSIMP_COLLADA_LIGHT_ANGLE_NOT_SET 1e9f
@ -152,21 +152,21 @@ struct Light
aiColor3D mColor; aiColor3D mColor;
//! Light attenuation //! Light attenuation
float mAttConstant,mAttLinear,mAttQuadratic; ai_real mAttConstant,mAttLinear,mAttQuadratic;
//! Spot light falloff //! Spot light falloff
float mFalloffAngle; ai_real mFalloffAngle;
float mFalloffExponent; ai_real mFalloffExponent;
// ----------------------------------------------------- // -----------------------------------------------------
// FCOLLADA extension from here // FCOLLADA extension from here
//! ... related stuff from maja and max extensions //! ... related stuff from maja and max extensions
float mPenumbraAngle; ai_real mPenumbraAngle;
float mOuterAngle; ai_real mOuterAngle;
//! Common light intensity //! Common light intensity
float mIntensity; ai_real mIntensity;
}; };
/** Short vertex index description */ /** Short vertex index description */
@ -275,7 +275,7 @@ struct Node
struct Data struct Data
{ {
bool mIsStringArray; bool mIsStringArray;
std::vector<float> mValues; std::vector<ai_real> mValues;
std::vector<std::string> mStrings; std::vector<std::string> mStrings;
}; };
@ -387,7 +387,7 @@ struct Controller
std::string mJointNameSource; std::string mJointNameSource;
///< The bind shape matrix, as array of floats. I'm not sure what this matrix actually describes, but it can't be ignored in all cases ///< The bind shape matrix, as array of floats. I'm not sure what this matrix actually describes, but it can't be ignored in all cases
float mBindShapeMatrix[16]; ai_real mBindShapeMatrix[16];
// accessor URL of the joint inverse bind matrices // accessor URL of the joint inverse bind matrices
std::string mJointOffsetMatrixSource; std::string mJointOffsetMatrixSource;
@ -490,11 +490,11 @@ struct Sampler
/** Weighting factor /** Weighting factor
*/ */
float mWeighting; ai_real mWeighting;
/** Mixing factor from OKINO /** Mixing factor from OKINO
*/ */
float mMixWithPrevious; ai_real mMixWithPrevious;
}; };
/** A collada effect. Can contain about anything according to the Collada spec, /** A collada effect. Can contain about anything according to the Collada spec,
@ -513,8 +513,8 @@ struct Effect
mTexTransparent, mTexBump, mTexReflective; mTexTransparent, mTexBump, mTexReflective;
// Scalar factory // Scalar factory
float mShininess, mRefractIndex, mReflectivity; ai_real mShininess, mRefractIndex, mReflectivity;
float mTransparency; ai_real mTransparency;
bool mHasTransparency; bool mHasTransparency;
bool mRGBTransparency; bool mRGBTransparency;
bool mInvertTransparency; bool mInvertTransparency;

View File

@ -44,9 +44,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef ASSIMP_BUILD_NO_COLLADA_IMPORTER #ifndef ASSIMP_BUILD_NO_COLLADA_IMPORTER
#include "../include/assimp/anim.h"
#include "../include/assimp/scene.h"
#include "ColladaLoader.h" #include "ColladaLoader.h"
#include <assimp/anim.h>
#include <assimp/scene.h>
#include <assimp/DefaultLogger.hpp>
#include <assimp/Importer.hpp>
#include "ColladaParser.h" #include "ColladaParser.h"
#include "fast_atof.h" #include "fast_atof.h"
@ -56,14 +58,12 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "time.h" #include "time.h"
#include "math.h" #include "math.h"
#include <boost/foreach.hpp>
#include "../include/assimp/DefaultLogger.hpp"
#include "../include/assimp/Importer.hpp"
#include <numeric> #include <numeric>
#include "Defines.h" #include "Defines.h"
using namespace Assimp; using namespace Assimp;
using namespace Assimp::Formatter;
static const aiImporterDesc desc = { static const aiImporterDesc desc = {
"Collada Importer", "Collada Importer",
@ -276,21 +276,20 @@ void ColladaLoader::ResolveNodeInstances( const ColladaParser& pParser, const Co
resolved.reserve(pNode->mNodeInstances.size()); resolved.reserve(pNode->mNodeInstances.size());
// ... and iterate through all nodes to be instanced as children of pNode // ... and iterate through all nodes to be instanced as children of pNode
for (std::vector<Collada::NodeInstance>::const_iterator it = pNode->mNodeInstances.begin(), for (const auto &nodeInst: pNode->mNodeInstances)
end = pNode->mNodeInstances.end(); it != end; ++it)
{ {
// find the corresponding node in the library // find the corresponding node in the library
const ColladaParser::NodeLibrary::const_iterator itt = pParser.mNodeLibrary.find((*it).mNode); const ColladaParser::NodeLibrary::const_iterator itt = pParser.mNodeLibrary.find(nodeInst.mNode);
const Collada::Node* nd = itt == pParser.mNodeLibrary.end() ? NULL : (*itt).second; const Collada::Node* nd = itt == pParser.mNodeLibrary.end() ? NULL : (*itt).second;
// FIX for http://sourceforge.net/tracker/?func=detail&aid=3054873&group_id=226462&atid=1067632 // FIX for http://sourceforge.net/tracker/?func=detail&aid=3054873&group_id=226462&atid=1067632
// need to check for both name and ID to catch all. To avoid breaking valid files, // need to check for both name and ID to catch all. To avoid breaking valid files,
// the workaround is only enabled when the first attempt to resolve the node has failed. // the workaround is only enabled when the first attempt to resolve the node has failed.
if (!nd) { if (!nd) {
nd = FindNode(pParser.mRootNode,(*it).mNode); nd = FindNode(pParser.mRootNode, nodeInst.mNode);
} }
if (!nd) if (!nd)
DefaultLogger::get()->error("Collada: Unable to resolve reference to instanced node " + (*it).mNode); DefaultLogger::get()->error("Collada: Unable to resolve reference to instanced node " + nodeInst.mNode);
else { else {
// attach this node to the list of children // attach this node to the list of children
@ -317,7 +316,7 @@ void ColladaLoader::ApplyVertexToEffectSemanticMapping(Collada::Sampler& sampler
// Builds lights for the given node and references them // Builds lights for the given node and references them
void ColladaLoader::BuildLightsForNode( const ColladaParser& pParser, const Collada::Node* pNode, aiNode* pTarget) void ColladaLoader::BuildLightsForNode( const ColladaParser& pParser, const Collada::Node* pNode, aiNode* pTarget)
{ {
BOOST_FOREACH( const Collada::LightInstance& lid, pNode->mLights) for( const Collada::LightInstance& lid : pNode->mLights)
{ {
// find the referred light // find the referred light
ColladaParser::LightLibrary::const_iterator srcLightIt = pParser.mLightLibrary.find( lid.mLight); ColladaParser::LightLibrary::const_iterator srcLightIt = pParser.mLightLibrary.find( lid.mLight);
@ -385,7 +384,7 @@ void ColladaLoader::BuildLightsForNode( const ColladaParser& pParser, const Coll
// Builds cameras for the given node and references them // Builds cameras for the given node and references them
void ColladaLoader::BuildCamerasForNode( const ColladaParser& pParser, const Collada::Node* pNode, aiNode* pTarget) void ColladaLoader::BuildCamerasForNode( const ColladaParser& pParser, const Collada::Node* pNode, aiNode* pTarget)
{ {
BOOST_FOREACH( const Collada::CameraInstance& cid, pNode->mCameras) for( const Collada::CameraInstance& cid : pNode->mCameras)
{ {
// find the referred light // find the referred light
ColladaParser::CameraLibrary::const_iterator srcCameraIt = pParser.mCameraLibrary.find( cid.mCamera); ColladaParser::CameraLibrary::const_iterator srcCameraIt = pParser.mCameraLibrary.find( cid.mCamera);
@ -447,7 +446,7 @@ void ColladaLoader::BuildMeshesForNode( const ColladaParser& pParser, const Coll
newMeshRefs.reserve(pNode->mMeshes.size()); newMeshRefs.reserve(pNode->mMeshes.size());
// add a mesh for each subgroup in each collada mesh // add a mesh for each subgroup in each collada mesh
BOOST_FOREACH( const Collada::MeshInstance& mid, pNode->mMeshes) for( const Collada::MeshInstance& mid : pNode->mMeshes)
{ {
const Collada::Mesh* srcMesh = NULL; const Collada::Mesh* srcMesh = NULL;
const Collada::Controller* srcController = NULL; const Collada::Controller* srcController = NULL;
@ -468,7 +467,7 @@ void ColladaLoader::BuildMeshesForNode( const ColladaParser& pParser, const Coll
if( !srcMesh) if( !srcMesh)
{ {
DefaultLogger::get()->warn( boost::str( boost::format( "Collada: Unable to find geometry for ID \"%s\". Skipping.") % mid.mMeshOrController)); DefaultLogger::get()->warn( format() << "Collada: Unable to find geometry for ID \"" << mid.mMeshOrController << "\". Skipping." );
continue; continue;
} }
} else } else
@ -497,7 +496,7 @@ void ColladaLoader::BuildMeshesForNode( const ColladaParser& pParser, const Coll
} }
else else
{ {
DefaultLogger::get()->warn( boost::str( boost::format( "Collada: No material specified for subgroup <%s> in geometry <%s>.") % submesh.mMaterial % mid.mMeshOrController)); DefaultLogger::get()->warn( format() << "Collada: No material specified for subgroup <" << submesh.mMaterial << "> in geometry <" << mid.mMeshOrController << ">." );
if( !mid.mMaterials.empty() ) if( !mid.mMaterials.empty() )
meshMaterial = mid.mMaterials.begin()->second.mMatName; meshMaterial = mid.mMaterials.begin()->second.mMatName;
} }
@ -663,7 +662,7 @@ aiMesh* ColladaLoader::CreateMesh( const ColladaParser& pParser, const Collada::
// joint vertex_weight name list - should refer to the same list as the joint names above. If not, report and reconsider // joint vertex_weight name list - should refer to the same list as the joint names above. If not, report and reconsider
const Collada::Accessor& weightNamesAcc = pParser.ResolveLibraryReference( pParser.mAccessorLibrary, pSrcController->mWeightInputJoints.mAccessor); const Collada::Accessor& weightNamesAcc = pParser.ResolveLibraryReference( pParser.mAccessorLibrary, pSrcController->mWeightInputJoints.mAccessor);
if( &weightNamesAcc != &jointNamesAcc) if( &weightNamesAcc != &jointNamesAcc)
throw DeadlyImportError( "Temporary implementational lazyness. If you read this, please report to the author."); throw DeadlyImportError( "Temporary implementational laziness. If you read this, please report to the author.");
// vertex weights // vertex weights
const Collada::Accessor& weightsAcc = pParser.ResolveLibraryReference( pParser.mAccessorLibrary, pSrcController->mWeightInputWeights.mAccessor); const Collada::Accessor& weightsAcc = pParser.ResolveLibraryReference( pParser.mAccessorLibrary, pSrcController->mWeightInputWeights.mAccessor);
const Collada::Data& weights = pParser.ResolveLibraryReference( pParser.mDataLibrary, weightsAcc.mSource); const Collada::Data& weights = pParser.ResolveLibraryReference( pParser.mDataLibrary, weightsAcc.mSource);
@ -705,7 +704,7 @@ aiMesh* ColladaLoader::CreateMesh( const ColladaParser& pParser, const Collada::
size_t jointIndex = iit->first; size_t jointIndex = iit->first;
size_t vertexIndex = iit->second; size_t vertexIndex = iit->second;
float weight = ReadFloat( weightsAcc, weights, vertexIndex, 0); ai_real weight = ReadFloat( weightsAcc, weights, vertexIndex, 0);
// one day I gonna kill that XSI Collada exporter // one day I gonna kill that XSI Collada exporter
if( weight > 0.0f) if( weight > 0.0f)
@ -785,7 +784,7 @@ aiMesh* ColladaLoader::CreateMesh( const ColladaParser& pParser, const Collada::
if( bnode) if( bnode)
bone->mName.Set( FindNameForNode( bnode)); bone->mName.Set( FindNameForNode( bnode));
else else
DefaultLogger::get()->warn( boost::str( boost::format( "ColladaLoader::CreateMesh(): could not find corresponding node for joint \"%s\".") % bone->mName.data)); DefaultLogger::get()->warn( format() << "ColladaLoader::CreateMesh(): could not find corresponding node for joint \"" << bone->mName.data << "\"." );
// and insert bone // and insert bone
dstMesh->mBones[boneCount++] = bone; dstMesh->mBones[boneCount++] = bone;
@ -1005,7 +1004,7 @@ void ColladaLoader::CreateAnimation( aiScene* pScene, const ColladaParser& pPars
else if( subElement == "Z") else if( subElement == "Z")
entry.mSubElement = 2; entry.mSubElement = 2;
else else
DefaultLogger::get()->warn( boost::str( boost::format( "Unknown anim subelement <%s>. Ignoring") % subElement)); DefaultLogger::get()->warn( format() << "Unknown anim subelement <" << subElement << ">. Ignoring" );
} else } else
{ {
// no subelement following, transformId is remaining string // no subelement following, transformId is remaining string
@ -1072,7 +1071,7 @@ void ColladaLoader::CreateAnimation( aiScene* pScene, const ColladaParser& pPars
continue; continue;
// resolve the data pointers for all anim channels. Find the minimum time while we're at it // resolve the data pointers for all anim channels. Find the minimum time while we're at it
float startTime = 1e20f, endTime = -1e20f; ai_real startTime = 1e20, endTime = -1e20;
for( std::vector<Collada::ChannelEntry>::iterator it = entries.begin(); it != entries.end(); ++it) for( std::vector<Collada::ChannelEntry>::iterator it = entries.begin(); it != entries.end(); ++it)
{ {
Collada::ChannelEntry& e = *it; Collada::ChannelEntry& e = *it;
@ -1083,7 +1082,7 @@ void ColladaLoader::CreateAnimation( aiScene* pScene, const ColladaParser& pPars
// time count and value count must match // time count and value count must match
if( e.mTimeAccessor->mCount != e.mValueAccessor->mCount) if( e.mTimeAccessor->mCount != e.mValueAccessor->mCount)
throw DeadlyImportError( boost::str( boost::format( "Time count / value count mismatch in animation channel \"%s\".") % e.mChannel->mTarget)); throw DeadlyImportError( format() << "Time count / value count mismatch in animation channel \"" << e.mChannel->mTarget << "\"." );
if( e.mTimeAccessor->mCount > 0 ) if( e.mTimeAccessor->mCount > 0 )
{ {
@ -1101,7 +1100,7 @@ void ColladaLoader::CreateAnimation( aiScene* pScene, const ColladaParser& pPars
// now for every unique point in time, find or interpolate the key values for that time // now for every unique point in time, find or interpolate the key values for that time
// and apply them to the transform chain. Then the node's present transformation can be calculated. // and apply them to the transform chain. Then the node's present transformation can be calculated.
float time = startTime; ai_real time = startTime;
while( 1) while( 1)
{ {
for( std::vector<Collada::ChannelEntry>::iterator it = entries.begin(); it != entries.end(); ++it) for( std::vector<Collada::ChannelEntry>::iterator it = entries.begin(); it != entries.end(); ++it)
@ -1110,7 +1109,7 @@ void ColladaLoader::CreateAnimation( aiScene* pScene, const ColladaParser& pPars
// find the keyframe behind the current point in time // find the keyframe behind the current point in time
size_t pos = 0; size_t pos = 0;
float postTime = 0.f; ai_real postTime = 0.0;
while( 1) while( 1)
{ {
if( pos >= e.mTimeAccessor->mCount) if( pos >= e.mTimeAccessor->mCount)
@ -1124,19 +1123,19 @@ void ColladaLoader::CreateAnimation( aiScene* pScene, const ColladaParser& pPars
pos = std::min( pos, e.mTimeAccessor->mCount-1); pos = std::min( pos, e.mTimeAccessor->mCount-1);
// read values from there // read values from there
float temp[16]; ai_real temp[16];
for( size_t c = 0; c < e.mValueAccessor->mSize; ++c) for( size_t c = 0; c < e.mValueAccessor->mSize; ++c)
temp[c] = ReadFloat( *e.mValueAccessor, *e.mValueData, pos, c); temp[c] = ReadFloat( *e.mValueAccessor, *e.mValueData, pos, c);
// if not exactly at the key time, interpolate with previous value set // if not exactly at the key time, interpolate with previous value set
if( postTime > time && pos > 0) if( postTime > time && pos > 0)
{ {
float preTime = ReadFloat( *e.mTimeAccessor, *e.mTimeData, pos-1, 0); ai_real preTime = ReadFloat( *e.mTimeAccessor, *e.mTimeData, pos-1, 0);
float factor = (time - postTime) / (preTime - postTime); ai_real factor = (time - postTime) / (preTime - postTime);
for( size_t c = 0; c < e.mValueAccessor->mSize; ++c) for( size_t c = 0; c < e.mValueAccessor->mSize; ++c)
{ {
float v = ReadFloat( *e.mValueAccessor, *e.mValueData, pos-1, c); ai_real v = ReadFloat( *e.mValueAccessor, *e.mValueData, pos-1, c);
temp[c] += (v - temp[c]) * factor; temp[c] += (v - temp[c]) * factor;
} }
} }
@ -1148,21 +1147,21 @@ void ColladaLoader::CreateAnimation( aiScene* pScene, const ColladaParser& pPars
// Calculate resulting transformation // Calculate resulting transformation
aiMatrix4x4 mat = pParser.CalculateResultTransform( transforms); aiMatrix4x4 mat = pParser.CalculateResultTransform( transforms);
// out of lazyness: we store the time in matrix.d4 // out of laziness: we store the time in matrix.d4
mat.d4 = time; mat.d4 = time;
resultTrafos.push_back( mat); resultTrafos.push_back( mat);
// find next point in time to evaluate. That's the closest frame larger than the current in any channel // find next point in time to evaluate. That's the closest frame larger than the current in any channel
float nextTime = 1e20f; ai_real nextTime = 1e20;
for( std::vector<Collada::ChannelEntry>::iterator it = entries.begin(); it != entries.end(); ++it) for( std::vector<Collada::ChannelEntry>::iterator it = entries.begin(); it != entries.end(); ++it)
{ {
Collada::ChannelEntry& e = *it; Collada::ChannelEntry& channelElement = *it;
// find the next time value larger than the current // find the next time value larger than the current
size_t pos = 0; size_t pos = 0;
while( pos < e.mTimeAccessor->mCount) while( pos < channelElement.mTimeAccessor->mCount)
{ {
float t = ReadFloat( *e.mTimeAccessor, *e.mTimeData, pos, 0); const ai_real t = ReadFloat( *channelElement.mTimeAccessor, *channelElement.mTimeData, pos, 0);
if( t > time) if( t > time)
{ {
nextTime = std::min( nextTime, t); nextTime = std::min( nextTime, t);
@ -1170,21 +1169,21 @@ void ColladaLoader::CreateAnimation( aiScene* pScene, const ColladaParser& pPars
} }
++pos; ++pos;
} }
// https://github.com/assimp/assimp/issues/458 // https://github.com/assimp/assimp/issues/458
// Sub-sample axis-angle channels if the delta between two consecutive // Sub-sample axis-angle channels if the delta between two consecutive
// key-frame angles is >= 180 degrees. // key-frame angles is >= 180 degrees.
if (transforms[e.mTransformIndex].mType == Collada::TF_ROTATE && e.mSubElement == 3 && pos > 0 && pos < e.mTimeAccessor->mCount) { if (transforms[channelElement.mTransformIndex].mType == Collada::TF_ROTATE && channelElement.mSubElement == 3 && pos > 0 && pos < channelElement.mTimeAccessor->mCount) {
float cur_key_angle = ReadFloat(*e.mValueAccessor, *e.mValueData, pos, 0); const ai_real cur_key_angle = ReadFloat(*channelElement.mValueAccessor, *channelElement.mValueData, pos, 0);
float last_key_angle = ReadFloat(*e.mValueAccessor, *e.mValueData, pos - 1, 0); const ai_real last_key_angle = ReadFloat(*channelElement.mValueAccessor, *channelElement.mValueData, pos - 1, 0);
float cur_key_time = ReadFloat(*e.mTimeAccessor, *e.mTimeData, pos, 0); const ai_real cur_key_time = ReadFloat(*channelElement.mTimeAccessor, *channelElement.mTimeData, pos, 0);
float last_key_time = ReadFloat(*e.mTimeAccessor, *e.mTimeData, pos - 1, 0); const ai_real last_key_time = ReadFloat(*channelElement.mTimeAccessor, *channelElement.mTimeData, pos - 1, 0);
float last_eval_angle = last_key_angle + (cur_key_angle - last_key_angle) * (time - last_key_time) / (cur_key_time - last_key_time); const ai_real last_eval_angle = last_key_angle + (cur_key_angle - last_key_angle) * (time - last_key_time) / (cur_key_time - last_key_time);
float delta = std::fabs(cur_key_angle - last_eval_angle); const ai_real delta = std::abs(cur_key_angle - last_eval_angle);
if (delta >= 180.0f) { if (delta >= 180.0) {
int subSampleCount = static_cast<int>(floorf(delta / 90.0f)); const int subSampleCount = static_cast<int>(floorf(delta / 90.0));
if (cur_key_time != time) { if (cur_key_time != time) {
float nextSampleTime = time + (cur_key_time - time) / subSampleCount; const ai_real nextSampleTime = time + (cur_key_time - time) / subSampleCount;
nextTime = std::min(nextTime, nextSampleTime); nextTime = std::min(nextTime, nextSampleTime);
} }
} }
@ -1290,11 +1289,11 @@ void ColladaLoader::AddTexture ( aiMaterial& mat, const ColladaParser& pParser,
_AI_MATKEY_TEXBLEND_BASE, type, idx); _AI_MATKEY_TEXBLEND_BASE, type, idx);
// Blend factor // Blend factor
mat.AddProperty((float*)&sampler.mWeighting , 1, mat.AddProperty((ai_real*)&sampler.mWeighting , 1,
_AI_MATKEY_TEXBLEND_BASE, type, idx); _AI_MATKEY_TEXBLEND_BASE, type, idx);
// UV source index ... if we didn't resolve the mapping, it is actually just // UV source index ... if we didn't resolve the mapping, it is actually just
// a guess but it works in most cases. We search for the frst occurence of a // a guess but it works in most cases. We search for the frst occurrence of a
// number in the channel name. We assume it is the zero-based index into the // number in the channel name. We assume it is the zero-based index into the
// UV channel array of all corresponding meshes. It could also be one-based // UV channel array of all corresponding meshes. It could also be one-based
// for some exporters, but we won't care of it unless someone complains about. // for some exporters, but we won't care of it unless someone complains about.
@ -1320,11 +1319,10 @@ void ColladaLoader::AddTexture ( aiMaterial& mat, const ColladaParser& pParser,
// Fills materials from the collada material definitions // Fills materials from the collada material definitions
void ColladaLoader::FillMaterials( const ColladaParser& pParser, aiScene* /*pScene*/) void ColladaLoader::FillMaterials( const ColladaParser& pParser, aiScene* /*pScene*/)
{ {
for (std::vector<std::pair<Collada::Effect*, aiMaterial*> >::iterator it = newMats.begin(), for (auto &elem : newMats)
end = newMats.end(); it != end; ++it)
{ {
aiMaterial& mat = (aiMaterial&)*it->second; aiMaterial& mat = (aiMaterial&)*elem.second;
Collada::Effect& effect = *it->first; Collada::Effect& effect = *elem.first;
// resolve shading mode // resolve shading mode
int shadeMode; int shadeMode;
@ -1466,11 +1464,11 @@ void ColladaLoader::BuildMaterials( ColladaParser& pParser, aiScene* /*pScene*/)
const int shadeMode = aiShadingMode_Phong; const int shadeMode = aiShadingMode_Phong;
mat->AddProperty<int>( &shadeMode, 1, AI_MATKEY_SHADING_MODEL); mat->AddProperty<int>( &shadeMode, 1, AI_MATKEY_SHADING_MODEL);
aiColor4D colAmbient( 0.2f, 0.2f, 0.2f, 1.0f), colDiffuse( 0.8f, 0.8f, 0.8f, 1.0f), colSpecular( 0.5f, 0.5f, 0.5f, 0.5f); aiColor4D colAmbient( 0.2, 0.2, 0.2, 1.0), colDiffuse( 0.8, 0.8, 0.8, 1.0), colSpecular( 0.5, 0.5, 0.5, 0.5);
mat->AddProperty( &colAmbient, 1, AI_MATKEY_COLOR_AMBIENT); mat->AddProperty( &colAmbient, 1, AI_MATKEY_COLOR_AMBIENT);
mat->AddProperty( &colDiffuse, 1, AI_MATKEY_COLOR_DIFFUSE); mat->AddProperty( &colDiffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
mat->AddProperty( &colSpecular, 1, AI_MATKEY_COLOR_SPECULAR); mat->AddProperty( &colSpecular, 1, AI_MATKEY_COLOR_SPECULAR);
const float specExp = 5.0f; const ai_real specExp = 5.0;
mat->AddProperty( &specExp, 1, AI_MATKEY_SHININESS); mat->AddProperty( &specExp, 1, AI_MATKEY_SHININESS);
} }
#endif #endif
@ -1499,8 +1497,8 @@ aiString ColladaLoader::FindFilenameForEffectTexture( const ColladaParser& pPars
ColladaParser::ImageLibrary::const_iterator imIt = pParser.mImageLibrary.find( name); ColladaParser::ImageLibrary::const_iterator imIt = pParser.mImageLibrary.find( name);
if( imIt == pParser.mImageLibrary.end()) if( imIt == pParser.mImageLibrary.end())
{ {
throw DeadlyImportError( boost::str( boost::format( throw DeadlyImportError( format() <<
"Collada: Unable to resolve effect texture entry \"%s\", ended up at ID \"%s\".") % pName % name)); "Collada: Unable to resolve effect texture entry \"" << pName << "\", ended up at ID \"" << name << "\"." );
} }
aiString result; aiString result;
@ -1589,7 +1587,7 @@ void ColladaLoader::ConvertPath (aiString& ss)
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// Reads a float value from an accessor and its data array. // Reads a float value from an accessor and its data array.
float ColladaLoader::ReadFloat( const Collada::Accessor& pAccessor, const Collada::Data& pData, size_t pIndex, size_t pOffset) const ai_real ColladaLoader::ReadFloat( const Collada::Accessor& pAccessor, const Collada::Data& pData, size_t pIndex, size_t pOffset) const
{ {
// FIXME: (thom) Test for data type here in every access? For the moment, I leave this to the caller // FIXME: (thom) Test for data type here in every access? For the moment, I leave this to the caller
size_t pos = pAccessor.mStride * pIndex + pAccessor.mOffset + pOffset; size_t pos = pAccessor.mStride * pIndex + pAccessor.mOffset + pOffset;
@ -1666,7 +1664,7 @@ std::string ColladaLoader::FindNameForNode( const Collada::Node* pNode)
{ {
// No need to worry. Unnamed nodes are no problem at all, except // No need to worry. Unnamed nodes are no problem at all, except
// if cameras or lights need to be assigned to them. // if cameras or lights need to be assigned to them.
return boost::str( boost::format( "$ColladaAutoName$_%d") % mNodeNameCounter++); return format() << "$ColladaAutoName$_" << mNodeNameCounter++;
} }
} }

View File

@ -190,7 +190,7 @@ protected:
* @param pOffset Offset into the element, for multipart elements such as vectors or matrices * @param pOffset Offset into the element, for multipart elements such as vectors or matrices
* @return the specified value * @return the specified value
*/ */
float ReadFloat( const Collada::Accessor& pAccessor, const Collada::Data& pData, size_t pIndex, size_t pOffset) const; ai_real ReadFloat( const Collada::Accessor& pAccessor, const Collada::Data& pData, size_t pIndex, size_t pOffset) const;
/** Reads a string value from an accessor and its data array. /** Reads a string value from an accessor and its data array.
* @param pAccessor The accessor to use for reading * @param pAccessor The accessor to use for reading

View File

@ -51,15 +51,18 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "ColladaParser.h" #include "ColladaParser.h"
#include "fast_atof.h" #include "fast_atof.h"
#include "ParsingUtils.h" #include "ParsingUtils.h"
#include <boost/scoped_ptr.hpp> #include "StringUtils.h"
#include <boost/foreach.hpp> #include <assimp/DefaultLogger.hpp>
#include "../include/assimp/DefaultLogger.hpp" #include <assimp/IOSystem.hpp>
#include "../include/assimp/IOSystem.hpp" #include <assimp/light.h>
#include "../include/assimp/light.h" #include "TinyFormatter.h"
#include <memory>
using namespace Assimp; using namespace Assimp;
using namespace Assimp::Collada; using namespace Assimp::Collada;
using namespace Assimp::Formatter;
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// Constructor to be privately used by Importer // Constructor to be privately used by Importer
@ -88,13 +91,13 @@ ColladaParser::ColladaParser( IOSystem* pIOHandler, const std::string& pFile)
} }
// open the file // open the file
boost::scoped_ptr<IOStream> file( pIOHandler->Open(pFile ) ); std::unique_ptr<IOStream> file( pIOHandler->Open(pFile ) );
if (file.get() == NULL) { if (file.get() == NULL) {
throw DeadlyImportError( "Failed to open file " + pFile + "." ); throw DeadlyImportError( "Failed to open file " + pFile + "." );
} }
// generate a XML reader for it // generate a XML reader for it
boost::scoped_ptr<CIrrXML_IOStreamReader> mIOWrapper(new CIrrXML_IOStreamReader(file.get())); std::unique_ptr<CIrrXML_IOStreamReader> mIOWrapper(new CIrrXML_IOStreamReader(file.get()));
mReader = irr::io::createIrrXMLReader( mIOWrapper.get()); mReader = irr::io::createIrrXMLReader( mIOWrapper.get());
if (!mReader) { if (!mReader) {
ThrowException("Collada: Unable to open file."); ThrowException("Collada: Unable to open file.");
@ -125,7 +128,7 @@ bool ColladaParser::ReadBoolFromTextContent()
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// Read float from text contents of current element // Read float from text contents of current element
float ColladaParser::ReadFloatFromTextContent() ai_real ColladaParser::ReadFloatFromTextContent()
{ {
const char* cur = GetTextContent(); const char* cur = GetTextContent();
return fast_atof(cur); return fast_atof(cur);
@ -164,7 +167,7 @@ void ColladaParser::ReadContents()
ReadStructure(); ReadStructure();
} else } else
{ {
DefaultLogger::get()->debug( boost::str( boost::format( "Ignoring global element <%s>.") % mReader->getNodeName())); DefaultLogger::get()->debug( format() << "Ignoring global element <" << mReader->getNodeName() << ">." );
SkipElement(); SkipElement();
} }
} else } else
@ -297,7 +300,7 @@ void ColladaParser::ReadAnimationClipLibrary()
else if (indexID >= 0) else if (indexID >= 0)
animName = mReader->getAttributeValue(indexID); animName = mReader->getAttributeValue(indexID);
else else
animName = "animation_" + mAnimationClipLibrary.size(); animName = std::string("animation_") + std::to_string(mAnimationClipLibrary.size());
std::pair<std::string, std::vector<std::string> > clip; std::pair<std::string, std::vector<std::string> > clip;
@ -529,10 +532,10 @@ void ColladaParser::ReadAnimation( Collada::Animation* pParent)
// it turned out to have channels - add them // it turned out to have channels - add them
if( !channels.empty()) if( !channels.empty())
{ {
// FIXME: Is this essentially doing the same as "single-anim-node" codepath in // FIXME: Is this essentially doing the same as "single-anim-node" codepath in
// ColladaLoader::StoreAnimations? For now, this has been deferred to after // ColladaLoader::StoreAnimations? For now, this has been deferred to after
// all animations and all clips have been read. Due to handling of // all animations and all clips have been read. Due to handling of
// <library_animation_clips> this cannot be done here, as the channel owner // <library_animation_clips> this cannot be done here, as the channel owner
// is lost, and some exporters make up animations by referring to multiple // is lost, and some exporters make up animations by referring to multiple
// single-channel animations from an <instance_animation>. // single-channel animations from an <instance_animation>.
/* /*
@ -616,7 +619,7 @@ void ColladaParser::ReadControllerLibrary()
{ {
if( IsElement( "controller")) if( IsElement( "controller"))
{ {
// read ID. Ask the spec if it's neccessary or optional... you might be surprised. // read ID. Ask the spec if it's necessary or optional... you might be surprised.
int attrID = GetAttribute( "id"); int attrID = GetAttribute( "id");
std::string id = mReader->getAttributeValue( attrID); std::string id = mReader->getAttributeValue( attrID);
@ -671,7 +674,7 @@ void ColladaParser::ReadController( Collada::Controller& pController)
for( unsigned int a = 0; a < 16; a++) for( unsigned int a = 0; a < 16; a++)
{ {
// read a number // read a number
content = fast_atoreal_move<float>( content, pController.mBindShapeMatrix[a]); content = fast_atoreal_move<ai_real>( content, pController.mBindShapeMatrix[a]);
// skip whitespace after it // skip whitespace after it
SkipSpacesAndLineEnd( &content); SkipSpacesAndLineEnd( &content);
} }
@ -725,7 +728,7 @@ void ColladaParser::ReadControllerJoints( Collada::Controller& pController)
// local URLS always start with a '#'. We don't support global URLs // local URLS always start with a '#'. We don't support global URLs
if( attrSource[0] != '#') if( attrSource[0] != '#')
ThrowException( boost::str( boost::format( "Unsupported URL format in \"%s\" in source attribute of <joints> data <input> element") % attrSource)); ThrowException( format() << "Unsupported URL format in \"" << attrSource << "\" in source attribute of <joints> data <input> element" );
attrSource++; attrSource++;
// parse source URL to corresponding source // parse source URL to corresponding source
@ -734,7 +737,7 @@ void ColladaParser::ReadControllerJoints( Collada::Controller& pController)
else if( strcmp( attrSemantic, "INV_BIND_MATRIX") == 0) else if( strcmp( attrSemantic, "INV_BIND_MATRIX") == 0)
pController.mJointOffsetMatrixSource = attrSource; pController.mJointOffsetMatrixSource = attrSource;
else else
ThrowException( boost::str( boost::format( "Unknown semantic \"%s\" in <joints> data <input> element") % attrSemantic)); ThrowException( format() << "Unknown semantic \"" << attrSemantic << "\" in <joints> data <input> element" );
// skip inner data, if present // skip inner data, if present
if( !mReader->isEmptyElement()) if( !mReader->isEmptyElement())
@ -784,7 +787,7 @@ void ColladaParser::ReadControllerWeights( Collada::Controller& pController)
// local URLS always start with a '#'. We don't support global URLs // local URLS always start with a '#'. We don't support global URLs
if( attrSource[0] != '#') if( attrSource[0] != '#')
ThrowException( boost::str( boost::format( "Unsupported URL format in \"%s\" in source attribute of <vertex_weights> data <input> element") % attrSource)); ThrowException( format() << "Unsupported URL format in \"" << attrSource << "\" in source attribute of <vertex_weights> data <input> element" );
channel.mAccessor = attrSource + 1; channel.mAccessor = attrSource + 1;
// parse source URL to corresponding source // parse source URL to corresponding source
@ -793,7 +796,7 @@ void ColladaParser::ReadControllerWeights( Collada::Controller& pController)
else if( strcmp( attrSemantic, "WEIGHT") == 0) else if( strcmp( attrSemantic, "WEIGHT") == 0)
pController.mWeightInputWeights = channel; pController.mWeightInputWeights = channel;
else else
ThrowException( boost::str( boost::format( "Unknown semantic \"%s\" in <vertex_weights> data <input> element") % attrSemantic)); ThrowException( format() << "Unknown semantic \"" << attrSemantic << "\" in <vertex_weights> data <input> element" );
// skip inner data, if present // skip inner data, if present
if( !mReader->isEmptyElement()) if( !mReader->isEmptyElement())
@ -1176,13 +1179,13 @@ void ColladaParser::ReadLight( Collada::Light& pLight)
// text content contains 3 floats // text content contains 3 floats
const char* content = GetTextContent(); const char* content = GetTextContent();
content = fast_atoreal_move<float>( content, (float&)pLight.mColor.r); content = fast_atoreal_move<ai_real>( content, (ai_real&)pLight.mColor.r);
SkipSpacesAndLineEnd( &content); SkipSpacesAndLineEnd( &content);
content = fast_atoreal_move<float>( content, (float&)pLight.mColor.g); content = fast_atoreal_move<ai_real>( content, (ai_real&)pLight.mColor.g);
SkipSpacesAndLineEnd( &content); SkipSpacesAndLineEnd( &content);
content = fast_atoreal_move<float>( content, (float&)pLight.mColor.b); content = fast_atoreal_move<ai_real>( content, (ai_real&)pLight.mColor.b);
SkipSpacesAndLineEnd( &content); SkipSpacesAndLineEnd( &content);
TestClosing( "color"); TestClosing( "color");
@ -1404,7 +1407,7 @@ void ColladaParser::ReadEffectProfileCommon( Collada::Effect& pEffect)
pEffect.mHasTransparency = true; pEffect.mHasTransparency = true;
const char* opaque = mReader->getAttributeValueSafe("opaque"); const char* opaque = mReader->getAttributeValueSafe("opaque");
if(::strcmp(opaque, "RGB_ZERO") == 0 || ::strcmp(opaque, "RGB_ONE") == 0) { if(::strcmp(opaque, "RGB_ZERO") == 0 || ::strcmp(opaque, "RGB_ONE") == 0) {
pEffect.mRGBTransparency = true; pEffect.mRGBTransparency = true;
} }
@ -1575,16 +1578,16 @@ void ColladaParser::ReadEffectColor( aiColor4D& pColor, Sampler& pSampler)
// text content contains 4 floats // text content contains 4 floats
const char* content = GetTextContent(); const char* content = GetTextContent();
content = fast_atoreal_move<float>( content, (float&)pColor.r); content = fast_atoreal_move<ai_real>( content, (ai_real&)pColor.r);
SkipSpacesAndLineEnd( &content); SkipSpacesAndLineEnd( &content);
content = fast_atoreal_move<float>( content, (float&)pColor.g); content = fast_atoreal_move<ai_real>( content, (ai_real&)pColor.g);
SkipSpacesAndLineEnd( &content); SkipSpacesAndLineEnd( &content);
content = fast_atoreal_move<float>( content, (float&)pColor.b); content = fast_atoreal_move<ai_real>( content, (ai_real&)pColor.b);
SkipSpacesAndLineEnd( &content); SkipSpacesAndLineEnd( &content);
content = fast_atoreal_move<float>( content, (float&)pColor.a); content = fast_atoreal_move<ai_real>( content, (ai_real&)pColor.a);
SkipSpacesAndLineEnd( &content); SkipSpacesAndLineEnd( &content);
TestClosing( "color"); TestClosing( "color");
} }
@ -1633,7 +1636,7 @@ void ColladaParser::ReadEffectColor( aiColor4D& pColor, Sampler& pSampler)
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// Reads an effect entry containing a float // Reads an effect entry containing a float
void ColladaParser::ReadEffectFloat( float& pFloat) void ColladaParser::ReadEffectFloat( ai_real& pFloat)
{ {
while( mReader->read()) while( mReader->read())
{ {
@ -1642,7 +1645,7 @@ void ColladaParser::ReadEffectFloat( float& pFloat)
{ {
// text content contains a single floats // text content contains a single floats
const char* content = GetTextContent(); const char* content = GetTextContent();
content = fast_atoreal_move<float>( content, pFloat); content = fast_atoreal_move<ai_real>( content, pFloat);
SkipSpacesAndLineEnd( &content); SkipSpacesAndLineEnd( &content);
TestClosing( "float"); TestClosing( "float");
@ -1940,9 +1943,9 @@ void ColladaParser::ReadDataArray()
if( *content == 0) if( *content == 0)
ThrowException( "Expected more values while reading float_array contents."); ThrowException( "Expected more values while reading float_array contents.");
float value; ai_real value;
// read a number // read a number
content = fast_atoreal_move<float>( content, value); content = fast_atoreal_move<ai_real>( content, value);
data.mValues.push_back( value); data.mValues.push_back( value);
// skip whitespace after it // skip whitespace after it
SkipSpacesAndLineEnd( &content); SkipSpacesAndLineEnd( &content);
@ -1963,7 +1966,7 @@ void ColladaParser::ReadAccessor( const std::string& pID)
int attrSource = GetAttribute( "source"); int attrSource = GetAttribute( "source");
const char* source = mReader->getAttributeValue( attrSource); const char* source = mReader->getAttributeValue( attrSource);
if( source[0] != '#') if( source[0] != '#')
ThrowException( boost::str( boost::format( "Unknown reference format in url \"%s\" in source attribute of <accessor> element.") % source)); ThrowException( format() << "Unknown reference format in url \"" << source << "\" in source attribute of <accessor> element." );
int attrCount = GetAttribute( "count"); int attrCount = GetAttribute( "count");
unsigned int count = (unsigned int) mReader->getAttributeValueAsInt( attrCount); unsigned int count = (unsigned int) mReader->getAttributeValueAsInt( attrCount);
int attrOffset = TestAttribute( "offset"); int attrOffset = TestAttribute( "offset");
@ -2022,7 +2025,7 @@ void ColladaParser::ReadAccessor( const std::string& pID)
else if( name == "U") acc.mSubOffset[0] = acc.mParams.size(); else if( name == "U") acc.mSubOffset[0] = acc.mParams.size();
else if( name == "V") acc.mSubOffset[1] = acc.mParams.size(); else if( name == "V") acc.mSubOffset[1] = acc.mParams.size();
//else //else
// DefaultLogger::get()->warn( boost::str( boost::format( "Unknown accessor parameter \"%s\". Ignoring data channel.") % name)); // DefaultLogger::get()->warn( format() << "Unknown accessor parameter \"" << name << "\". Ignoring data channel." );
} }
// read data type // read data type
@ -2045,7 +2048,7 @@ void ColladaParser::ReadAccessor( const std::string& pID)
SkipElement(); SkipElement();
} else } else
{ {
ThrowException( boost::str( boost::format( "Unexpected sub element <%s> in tag <accessor>") % mReader->getNodeName())); ThrowException( format() << "Unexpected sub element <" << mReader->getNodeName() << "> in tag <accessor>" );
} }
} }
else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
@ -2075,7 +2078,7 @@ void ColladaParser::ReadVertexData( Mesh* pMesh)
ReadInputChannel( pMesh->mPerVertexData); ReadInputChannel( pMesh->mPerVertexData);
} else } else
{ {
ThrowException( boost::str( boost::format( "Unexpected sub element <%s> in tag <vertices>") % mReader->getNodeName())); ThrowException( format() << "Unexpected sub element <" << mReader->getNodeName() << "> in tag <vertices>" );
} }
} }
else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
@ -2173,13 +2176,13 @@ void ColladaParser::ReadIndexData( Mesh* pMesh)
SkipElement("extra"); SkipElement("extra");
} else } else
{ {
ThrowException( boost::str( boost::format( "Unexpected sub element <%s> in tag <%s>") % mReader->getNodeName() % elementName)); ThrowException( format() << "Unexpected sub element <" << mReader->getNodeName() << "> in tag <" << elementName << ">" );
} }
} }
else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
{ {
if( mReader->getNodeName() != elementName) if( mReader->getNodeName() != elementName)
ThrowException( boost::str( boost::format( "Expected end of <%s> element.") % elementName)); ThrowException( format() << "Expected end of <" << elementName << "> element." );
break; break;
} }
@ -2212,7 +2215,7 @@ void ColladaParser::ReadInputChannel( std::vector<InputChannel>& poChannels)
int attrSource = GetAttribute( "source"); int attrSource = GetAttribute( "source");
const char* source = mReader->getAttributeValue( attrSource); const char* source = mReader->getAttributeValue( attrSource);
if( source[0] != '#') if( source[0] != '#')
ThrowException( boost::str( boost::format( "Unknown reference format in url \"%s\" in source attribute of <input> element.") % source)); ThrowException( format() << "Unknown reference format in url \"" << source << "\" in source attribute of <input> element." );
channel.mAccessor = source+1; // skipping the leading #, hopefully the remaining text is the accessor ID only channel.mAccessor = source+1; // skipping the leading #, hopefully the remaining text is the accessor ID only
// read index offset, if per-index <input> // read index offset, if per-index <input>
@ -2226,7 +2229,7 @@ void ColladaParser::ReadInputChannel( std::vector<InputChannel>& poChannels)
if(attrSet > -1){ if(attrSet > -1){
attrSet = mReader->getAttributeValueAsInt( attrSet); attrSet = mReader->getAttributeValueAsInt( attrSet);
if(attrSet < 0) if(attrSet < 0)
ThrowException( boost::str( boost::format( "Invalid index \"%i\" in set attribute of <input> element") % (attrSet))); ThrowException( format() << "Invalid index \"" << (attrSet) << "\" in set attribute of <input> element" );
channel.mIndex = attrSet; channel.mIndex = attrSet;
} }
@ -2249,7 +2252,7 @@ size_t ColladaParser::ReadPrimitives( Mesh* pMesh, std::vector<InputChannel>& pP
// find the offset index for all per-vertex channels // find the offset index for all per-vertex channels
size_t numOffsets = 1; size_t numOffsets = 1;
size_t perVertexOffset = SIZE_MAX; // invalid value size_t perVertexOffset = SIZE_MAX; // invalid value
BOOST_FOREACH( const InputChannel& channel, pPerIndexChannels) for( const InputChannel& channel : pPerIndexChannels)
{ {
numOffsets = std::max( numOffsets, channel.mOffset+1); numOffsets = std::max( numOffsets, channel.mOffset+1);
if( channel.mType == IT_Vertex) if( channel.mType == IT_Vertex)
@ -2262,7 +2265,7 @@ size_t ColladaParser::ReadPrimitives( Mesh* pMesh, std::vector<InputChannel>& pP
{ {
case Prim_Polylist: case Prim_Polylist:
{ {
BOOST_FOREACH( size_t i, pVCount) for( size_t i : pVCount)
expectedPointCount += i; expectedPointCount += i;
break; break;
} }
@ -2282,7 +2285,7 @@ size_t ColladaParser::ReadPrimitives( Mesh* pMesh, std::vector<InputChannel>& pP
if( expectedPointCount > 0) if( expectedPointCount > 0)
indices.reserve( expectedPointCount * numOffsets); indices.reserve( expectedPointCount * numOffsets);
if (pNumPrimitives > 0) // It is possible to not contain any indicies if (pNumPrimitives > 0) // It is possible to not contain any indices
{ {
const char* content = GetTextContent(); const char* content = GetTextContent();
while( *content != 0) while( *content != 0)
@ -2317,7 +2320,7 @@ size_t ColladaParser::ReadPrimitives( Mesh* pMesh, std::vector<InputChannel>& pP
// find accessor // find accessor
input.mResolved = &ResolveLibraryReference( mAccessorLibrary, input.mAccessor); input.mResolved = &ResolveLibraryReference( mAccessorLibrary, input.mAccessor);
// resolve accessor's data pointer as well, if neccessary // resolve accessor's data pointer as well, if necessary
const Accessor* acc = input.mResolved; const Accessor* acc = input.mResolved;
if( !acc->mData) if( !acc->mData)
acc->mData = &ResolveLibraryReference( mDataLibrary, acc->mSource); acc->mData = &ResolveLibraryReference( mDataLibrary, acc->mSource);
@ -2340,7 +2343,7 @@ size_t ColladaParser::ReadPrimitives( Mesh* pMesh, std::vector<InputChannel>& pP
// find accessor // find accessor
input.mResolved = &ResolveLibraryReference( mAccessorLibrary, input.mAccessor); input.mResolved = &ResolveLibraryReference( mAccessorLibrary, input.mAccessor);
// resolve accessor's data pointer as well, if neccessary // resolve accessor's data pointer as well, if necessary
const Accessor* acc = input.mResolved; const Accessor* acc = input.mResolved;
if( !acc->mData) if( !acc->mData)
acc->mData = &ResolveLibraryReference( mDataLibrary, acc->mSource); acc->mData = &ResolveLibraryReference( mDataLibrary, acc->mSource);
@ -2450,14 +2453,14 @@ void ColladaParser::ExtractDataObjectFromChannel( const InputChannel& pInput, si
const Accessor& acc = *pInput.mResolved; const Accessor& acc = *pInput.mResolved;
if( pLocalIndex >= acc.mCount) if( pLocalIndex >= acc.mCount)
ThrowException( boost::str( boost::format( "Invalid data index (%d/%d) in primitive specification") % pLocalIndex % acc.mCount)); ThrowException( format() << "Invalid data index (" << pLocalIndex << "/" << acc.mCount << ") in primitive specification" );
// get a pointer to the start of the data object referred to by the accessor and the local index // get a pointer to the start of the data object referred to by the accessor and the local index
const float* dataObject = &(acc.mData->mValues[0]) + acc.mOffset + pLocalIndex* acc.mStride; const ai_real* dataObject = &(acc.mData->mValues[0]) + acc.mOffset + pLocalIndex* acc.mStride;
// assemble according to the accessors component sub-offset list. We don't care, yet, // assemble according to the accessors component sub-offset list. We don't care, yet,
// what kind of object exactly we're extracting here // what kind of object exactly we're extracting here
float obj[4]; ai_real obj[4];
for( size_t c = 0; c < 4; ++c) for( size_t c = 0; c < 4; ++c)
obj[c] = dataObject[acc.mSubOffset[c]]; obj[c] = dataObject[acc.mSubOffset[c]];
@ -2761,7 +2764,7 @@ void ColladaParser::ReadNodeTransformation( Node* pNode, TransformType pType)
for( unsigned int a = 0; a < sNumParameters[pType]; a++) for( unsigned int a = 0; a < sNumParameters[pType]; a++)
{ {
// read a number // read a number
content = fast_atoreal_move<float>( content, tf.f[a]); content = fast_atoreal_move<ai_real>( content, tf.f[a]);
// skip whitespace after it // skip whitespace after it
SkipSpacesAndLineEnd( &content); SkipSpacesAndLineEnd( &content);
} }
@ -2876,7 +2879,7 @@ void ColladaParser::ReadScene()
if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
if( IsElement( "instance_visual_scene")) if( IsElement( "instance_visual_scene"))
{ {
// should be the first and only occurence // should be the first and only occurrence
if( mRootNode) if( mRootNode)
ThrowException( "Invalid scene containing multiple root nodes in <instance_visual_scene> element"); ThrowException( "Invalid scene containing multiple root nodes in <instance_visual_scene> element");
@ -2905,19 +2908,19 @@ void ColladaParser::ReadScene()
// Aborts the file reading with an exception // Aborts the file reading with an exception
AI_WONT_RETURN void ColladaParser::ThrowException( const std::string& pError) const AI_WONT_RETURN void ColladaParser::ThrowException( const std::string& pError) const
{ {
throw DeadlyImportError( boost::str( boost::format( "Collada: %s - %s") % mFileName % pError)); throw DeadlyImportError( format() << "Collada: " << mFileName << " - " << pError );
} }
void ColladaParser::ReportWarning(const char* msg,...) void ColladaParser::ReportWarning(const char* msg,...)
{ {
ai_assert(NULL != msg); ai_assert(NULL != msg);
va_list args; va_list args;
va_start(args,msg); va_start(args,msg);
char szBuffer[3000]; char szBuffer[3000];
const int iLen = vsprintf(szBuffer,msg,args); const int iLen = vsprintf(szBuffer,msg,args);
ai_assert(iLen > 0); ai_assert(iLen > 0);
va_end(args); va_end(args);
DefaultLogger::get()->warn("Validation warning: " + std::string(szBuffer,iLen)); DefaultLogger::get()->warn("Validation warning: " + std::string(szBuffer,iLen));
} }
@ -2956,14 +2959,14 @@ void ColladaParser::TestOpening( const char* pName)
{ {
// read element start // read element start
if( !mReader->read()) if( !mReader->read())
ThrowException( boost::str( boost::format( "Unexpected end of file while beginning of <%s> element.") % pName)); ThrowException( format() << "Unexpected end of file while beginning of <" << pName << "> element." );
// whitespace in front is ok, just read again if found // whitespace in front is ok, just read again if found
if( mReader->getNodeType() == irr::io::EXN_TEXT) if( mReader->getNodeType() == irr::io::EXN_TEXT)
if( !mReader->read()) if( !mReader->read())
ThrowException( boost::str( boost::format( "Unexpected end of file while reading beginning of <%s> element.") % pName)); ThrowException( format() << "Unexpected end of file while reading beginning of <" << pName << "> element." );
if( mReader->getNodeType() != irr::io::EXN_ELEMENT || strcmp( mReader->getNodeName(), pName) != 0) if( mReader->getNodeType() != irr::io::EXN_ELEMENT || strcmp( mReader->getNodeName(), pName) != 0)
ThrowException( boost::str( boost::format( "Expected start of <%s> element.") % pName)); ThrowException( format() << "Expected start of <" << pName << "> element." );
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
@ -2976,15 +2979,15 @@ void ColladaParser::TestClosing( const char* pName)
// if not, read some more // if not, read some more
if( !mReader->read()) if( !mReader->read())
ThrowException( boost::str( boost::format( "Unexpected end of file while reading end of <%s> element.") % pName)); ThrowException( format() << "Unexpected end of file while reading end of <" << pName << "> element." );
// whitespace in front is ok, just read again if found // whitespace in front is ok, just read again if found
if( mReader->getNodeType() == irr::io::EXN_TEXT) if( mReader->getNodeType() == irr::io::EXN_TEXT)
if( !mReader->read()) if( !mReader->read())
ThrowException( boost::str( boost::format( "Unexpected end of file while reading end of <%s> element.") % pName)); ThrowException( format() << "Unexpected end of file while reading end of <" << pName << "> element." );
// but this has the be the closing tag, or we're lost // but this has the be the closing tag, or we're lost
if( mReader->getNodeType() != irr::io::EXN_ELEMENT_END || strcmp( mReader->getNodeName(), pName) != 0) if( mReader->getNodeType() != irr::io::EXN_ELEMENT_END || strcmp( mReader->getNodeName(), pName) != 0)
ThrowException( boost::str( boost::format( "Expected end of <%s> element.") % pName)); ThrowException( format() << "Expected end of <" << pName << "> element." );
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
@ -2996,7 +2999,7 @@ int ColladaParser::GetAttribute( const char* pAttr) const
return index; return index;
// attribute not found -> throw an exception // attribute not found -> throw an exception
ThrowException( boost::str( boost::format( "Expected attribute \"%s\" for element <%s>.") % pAttr % mReader->getNodeName())); ThrowException( format() << "Expected attribute \"" << pAttr << "\" for element <" << mReader->getNodeName() << ">." );
return -1; return -1;
} }
@ -3072,7 +3075,7 @@ aiMatrix4x4 ColladaParser::CalculateResultTransform( const std::vector<Transform
case TF_ROTATE: case TF_ROTATE:
{ {
aiMatrix4x4 rot; aiMatrix4x4 rot;
float angle = tf.f[3] * float( AI_MATH_PI) / 180.0f; ai_real angle = tf.f[3] * ai_real( AI_MATH_PI) / 180.0;
aiVector3D axis( tf.f[0], tf.f[1], tf.f[2]); aiVector3D axis( tf.f[0], tf.f[1], tf.f[2]);
aiMatrix4x4::Rotation( angle, axis, rot); aiMatrix4x4::Rotation( angle, axis, rot);
res *= rot; res *= rot;
@ -3114,24 +3117,29 @@ aiMatrix4x4 ColladaParser::CalculateResultTransform( const std::vector<Transform
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// Determines the input data type for the given semantic string // Determines the input data type for the given semantic string
Collada::InputType ColladaParser::GetTypeForSemantic( const std::string& pSemantic) Collada::InputType ColladaParser::GetTypeForSemantic( const std::string& semantic)
{ {
if( pSemantic == "POSITION") if ( semantic.empty() ) {
DefaultLogger::get()->warn( format() << "Vertex input type is empty." );
return IT_Invalid;
}
if( semantic == "POSITION")
return IT_Position; return IT_Position;
else if( pSemantic == "TEXCOORD") else if( semantic == "TEXCOORD")
return IT_Texcoord; return IT_Texcoord;
else if( pSemantic == "NORMAL") else if( semantic == "NORMAL")
return IT_Normal; return IT_Normal;
else if( pSemantic == "COLOR") else if( semantic == "COLOR")
return IT_Color; return IT_Color;
else if( pSemantic == "VERTEX") else if( semantic == "VERTEX")
return IT_Vertex; return IT_Vertex;
else if( pSemantic == "BINORMAL" || pSemantic == "TEXBINORMAL") else if( semantic == "BINORMAL" || semantic == "TEXBINORMAL")
return IT_Bitangent; return IT_Bitangent;
else if( pSemantic == "TANGENT" || pSemantic == "TEXTANGENT") else if( semantic == "TANGENT" || semantic == "TEXTANGENT")
return IT_Tangent; return IT_Tangent;
DefaultLogger::get()->warn( boost::str( boost::format( "Unknown vertex input type \"%s\". Ignoring.") % pSemantic)); DefaultLogger::get()->warn( format() << "Unknown vertex input type \"" << semantic << "\". Ignoring." );
return IT_Invalid; return IT_Invalid;
} }

View File

@ -1,28 +1,28 @@
/* /*
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2016, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the with or without modification, are permitted provided that the
following conditions are met: following conditions are met:
* Redistributions of source code must retain the above * Redistributions of source code must retain the above
copyright notice, this list of conditions and the copyright notice, this list of conditions and the
following disclaimer. following disclaimer.
* Redistributions in binary form must reproduce the above * Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other following disclaimer in the documentation and/or other
materials provided with the distribution. materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its * Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products contributors may be used to endorse or promote products
derived from this software without specific prior derived from this software without specific prior
written permission of the assimp team. written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
@ -34,7 +34,7 @@
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------- ----------------------------------------------------------------------
*/ */
@ -47,13 +47,13 @@
#include "irrXMLWrapper.h" #include "irrXMLWrapper.h"
#include "ColladaHelper.h" #include "ColladaHelper.h"
#include "../include/assimp/ai_assert.h" #include <assimp/ai_assert.h>
#include <boost/format.hpp> #include "TinyFormatter.h"
#include <boost/scoped_ptr.hpp> #include <memory>
namespace Assimp namespace Assimp
{ {
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
/** Parser helper class for the Collada loader. /** Parser helper class for the Collada loader.
* *
@ -63,23 +63,23 @@ namespace Assimp
class ColladaParser class ColladaParser
{ {
friend class ColladaLoader; friend class ColladaLoader;
protected: protected:
/** Constructor from XML file */ /** Constructor from XML file */
ColladaParser( IOSystem* pIOHandler, const std::string& pFile); ColladaParser( IOSystem* pIOHandler, const std::string& pFile);
/** Destructor */ /** Destructor */
~ColladaParser(); ~ColladaParser();
/** Reads the contents of the file */ /** Reads the contents of the file */
void ReadContents(); void ReadContents();
/** Reads the structure of the file */ /** Reads the structure of the file */
void ReadStructure(); void ReadStructure();
/** Reads asset informations such as coordinate system informations and legal blah */ /** Reads asset informations such as coordinate system informations and legal blah */
void ReadAssetInfo(); void ReadAssetInfo();
/** Reads the animation library */ /** Reads the animation library */
void ReadAnimationLibrary(); void ReadAnimationLibrary();
@ -88,137 +88,137 @@ namespace Assimp
/** Re-build animations from animation clip library, if present, otherwise combine single-channel animations */ /** Re-build animations from animation clip library, if present, otherwise combine single-channel animations */
void PostProcessRootAnimations(); void PostProcessRootAnimations();
/** Reads an animation into the given parent structure */ /** Reads an animation into the given parent structure */
void ReadAnimation( Collada::Animation* pParent); void ReadAnimation( Collada::Animation* pParent);
/** Reads an animation sampler into the given anim channel */ /** Reads an animation sampler into the given anim channel */
void ReadAnimationSampler( Collada::AnimationChannel& pChannel); void ReadAnimationSampler( Collada::AnimationChannel& pChannel);
/** Reads the skeleton controller library */ /** Reads the skeleton controller library */
void ReadControllerLibrary(); void ReadControllerLibrary();
/** Reads a controller into the given mesh structure */ /** Reads a controller into the given mesh structure */
void ReadController( Collada::Controller& pController); void ReadController( Collada::Controller& pController);
/** Reads the joint definitions for the given controller */ /** Reads the joint definitions for the given controller */
void ReadControllerJoints( Collada::Controller& pController); void ReadControllerJoints( Collada::Controller& pController);
/** Reads the joint weights for the given controller */ /** Reads the joint weights for the given controller */
void ReadControllerWeights( Collada::Controller& pController); void ReadControllerWeights( Collada::Controller& pController);
/** Reads the image library contents */ /** Reads the image library contents */
void ReadImageLibrary(); void ReadImageLibrary();
/** Reads an image entry into the given image */ /** Reads an image entry into the given image */
void ReadImage( Collada::Image& pImage); void ReadImage( Collada::Image& pImage);
/** Reads the material library */ /** Reads the material library */
void ReadMaterialLibrary(); void ReadMaterialLibrary();
/** Reads a material entry into the given material */ /** Reads a material entry into the given material */
void ReadMaterial( Collada::Material& pMaterial); void ReadMaterial( Collada::Material& pMaterial);
/** Reads the camera library */ /** Reads the camera library */
void ReadCameraLibrary(); void ReadCameraLibrary();
/** Reads a camera entry into the given camera */ /** Reads a camera entry into the given camera */
void ReadCamera( Collada::Camera& pCamera); void ReadCamera( Collada::Camera& pCamera);
/** Reads the light library */ /** Reads the light library */
void ReadLightLibrary(); void ReadLightLibrary();
/** Reads a light entry into the given light */ /** Reads a light entry into the given light */
void ReadLight( Collada::Light& pLight); void ReadLight( Collada::Light& pLight);
/** Reads the effect library */ /** Reads the effect library */
void ReadEffectLibrary(); void ReadEffectLibrary();
/** Reads an effect entry into the given effect*/ /** Reads an effect entry into the given effect*/
void ReadEffect( Collada::Effect& pEffect); void ReadEffect( Collada::Effect& pEffect);
/** Reads an COMMON effect profile */ /** Reads an COMMON effect profile */
void ReadEffectProfileCommon( Collada::Effect& pEffect); void ReadEffectProfileCommon( Collada::Effect& pEffect);
/** Read sampler properties */ /** Read sampler properties */
void ReadSamplerProperties( Collada::Sampler& pSampler); void ReadSamplerProperties( Collada::Sampler& pSampler);
/** Reads an effect entry containing a color or a texture defining that color */ /** Reads an effect entry containing a color or a texture defining that color */
void ReadEffectColor( aiColor4D& pColor, Collada::Sampler& pSampler); void ReadEffectColor( aiColor4D& pColor, Collada::Sampler& pSampler);
/** Reads an effect entry containing a float */ /** Reads an effect entry containing a float */
void ReadEffectFloat( float& pFloat); void ReadEffectFloat( ai_real& pFloat);
/** Reads an effect parameter specification of any kind */ /** Reads an effect parameter specification of any kind */
void ReadEffectParam( Collada::EffectParam& pParam); void ReadEffectParam( Collada::EffectParam& pParam);
/** Reads the geometry library contents */ /** Reads the geometry library contents */
void ReadGeometryLibrary(); void ReadGeometryLibrary();
/** Reads a geometry from the geometry library. */ /** Reads a geometry from the geometry library. */
void ReadGeometry( Collada::Mesh* pMesh); void ReadGeometry( Collada::Mesh* pMesh);
/** Reads a mesh from the geometry library */ /** Reads a mesh from the geometry library */
void ReadMesh( Collada::Mesh* pMesh); void ReadMesh( Collada::Mesh* pMesh);
/** Reads a source element - a combination of raw data and an accessor defining /** Reads a source element - a combination of raw data and an accessor defining
* things that should not be redefinable. Yes, that's another rant. * things that should not be redefinable. Yes, that's another rant.
*/ */
void ReadSource(); void ReadSource();
/** Reads a data array holding a number of elements, and stores it in the global library. /** Reads a data array holding a number of elements, and stores it in the global library.
* Currently supported are array of floats and arrays of strings. * Currently supported are array of floats and arrays of strings.
*/ */
void ReadDataArray(); void ReadDataArray();
/** Reads an accessor and stores it in the global library under the given ID - /** Reads an accessor and stores it in the global library under the given ID -
* accessors use the ID of the parent <source> element * accessors use the ID of the parent <source> element
*/ */
void ReadAccessor( const std::string& pID); void ReadAccessor( const std::string& pID);
/** Reads input declarations of per-vertex mesh data into the given mesh */ /** Reads input declarations of per-vertex mesh data into the given mesh */
void ReadVertexData( Collada::Mesh* pMesh); void ReadVertexData( Collada::Mesh* pMesh);
/** Reads input declarations of per-index mesh data into the given mesh */ /** Reads input declarations of per-index mesh data into the given mesh */
void ReadIndexData( Collada::Mesh* pMesh); void ReadIndexData( Collada::Mesh* pMesh);
/** Reads a single input channel element and stores it in the given array, if valid */ /** Reads a single input channel element and stores it in the given array, if valid */
void ReadInputChannel( std::vector<Collada::InputChannel>& poChannels); void ReadInputChannel( std::vector<Collada::InputChannel>& poChannels);
/** Reads a <p> primitive index list and assembles the mesh data into the given mesh */ /** Reads a <p> primitive index list and assembles the mesh data into the given mesh */
size_t ReadPrimitives( Collada::Mesh* pMesh, std::vector<Collada::InputChannel>& pPerIndexChannels, size_t ReadPrimitives( Collada::Mesh* pMesh, std::vector<Collada::InputChannel>& pPerIndexChannels,
size_t pNumPrimitives, const std::vector<size_t>& pVCount, Collada::PrimitiveType pPrimType); size_t pNumPrimitives, const std::vector<size_t>& pVCount, Collada::PrimitiveType pPrimType);
/** Copies the data for a single primitive into the mesh, based on the InputChannels */ /** Copies the data for a single primitive into the mesh, based on the InputChannels */
void CopyVertex(size_t currentVertex, size_t numOffsets, size_t numPoints, size_t perVertexOffset, void CopyVertex(size_t currentVertex, size_t numOffsets, size_t numPoints, size_t perVertexOffset,
Collada::Mesh* pMesh, std::vector<Collada::InputChannel>& pPerIndexChannels, Collada::Mesh* pMesh, std::vector<Collada::InputChannel>& pPerIndexChannels,
size_t currentPrimitive, const std::vector<size_t>& indices); size_t currentPrimitive, const std::vector<size_t>& indices);
/** Reads one triangle of a tristrip into the mesh */ /** Reads one triangle of a tristrip into the mesh */
void ReadPrimTriStrips(size_t numOffsets, size_t perVertexOffset, Collada::Mesh* pMesh, void ReadPrimTriStrips(size_t numOffsets, size_t perVertexOffset, Collada::Mesh* pMesh,
std::vector<Collada::InputChannel>& pPerIndexChannels, size_t currentPrimitive, const std::vector<size_t>& indices); std::vector<Collada::InputChannel>& pPerIndexChannels, size_t currentPrimitive, const std::vector<size_t>& indices);
/** Extracts a single object from an input channel and stores it in the appropriate mesh data array */ /** Extracts a single object from an input channel and stores it in the appropriate mesh data array */
void ExtractDataObjectFromChannel( const Collada::InputChannel& pInput, size_t pLocalIndex, Collada::Mesh* pMesh); void ExtractDataObjectFromChannel( const Collada::InputChannel& pInput, size_t pLocalIndex, Collada::Mesh* pMesh);
/** Reads the library of node hierarchies and scene parts */ /** Reads the library of node hierarchies and scene parts */
void ReadSceneLibrary(); void ReadSceneLibrary();
/** Reads a scene node's contents including children and stores it in the given node */ /** Reads a scene node's contents including children and stores it in the given node */
void ReadSceneNode( Collada::Node* pNode); void ReadSceneNode( Collada::Node* pNode);
/** Reads a node transformation entry of the given type and adds it to the given node's transformation list. */ /** Reads a node transformation entry of the given type and adds it to the given node's transformation list. */
void ReadNodeTransformation( Collada::Node* pNode, Collada::TransformType pType); void ReadNodeTransformation( Collada::Node* pNode, Collada::TransformType pType);
/** Reads a mesh reference in a node and adds it to the node's mesh list */ /** Reads a mesh reference in a node and adds it to the node's mesh list */
void ReadNodeGeometry( Collada::Node* pNode); void ReadNodeGeometry( Collada::Node* pNode);
/** Reads the collada scene */ /** Reads the collada scene */
void ReadScene(); void ReadScene();
// Processes bind_vertex_input and bind elements // Processes bind_vertex_input and bind elements
void ReadMaterialVertexInputBinding( Collada::SemanticMappingTable& tbl); void ReadMaterialVertexInputBinding( Collada::SemanticMappingTable& tbl);
protected: protected:
/** Aborts the file reading with an exception */ /** Aborts the file reading with an exception */
AI_WONT_RETURN void ThrowException( const std::string& pError) const AI_WONT_RETURN_SUFFIX; AI_WONT_RETURN void ThrowException( const std::string& pError) const AI_WONT_RETURN_SUFFIX;
@ -226,95 +226,95 @@ namespace Assimp
/** Skips all data until the end node of the current element */ /** Skips all data until the end node of the current element */
void SkipElement(); void SkipElement();
/** Skips all data until the end node of the given element */ /** Skips all data until the end node of the given element */
void SkipElement( const char* pElement); void SkipElement( const char* pElement);
/** Compares the current xml element name to the given string and returns true if equal */ /** Compares the current xml element name to the given string and returns true if equal */
bool IsElement( const char* pName) const; bool IsElement( const char* pName) const;
/** Tests for the opening tag of the given element, throws an exception if not found */ /** Tests for the opening tag of the given element, throws an exception if not found */
void TestOpening( const char* pName); void TestOpening( const char* pName);
/** Tests for the closing tag of the given element, throws an exception if not found */ /** Tests for the closing tag of the given element, throws an exception if not found */
void TestClosing( const char* pName); void TestClosing( const char* pName);
/** Checks the present element for the presence of the attribute, returns its index /** Checks the present element for the presence of the attribute, returns its index
or throws an exception if not found */ or throws an exception if not found */
int GetAttribute( const char* pAttr) const; int GetAttribute( const char* pAttr) const;
/** Returns the index of the named attribute or -1 if not found. Does not throw, /** Returns the index of the named attribute or -1 if not found. Does not throw,
therefore useful for optional attributes */ therefore useful for optional attributes */
int TestAttribute( const char* pAttr) const; int TestAttribute( const char* pAttr) const;
/** Reads the text contents of an element, throws an exception if not given. /** Reads the text contents of an element, throws an exception if not given.
Skips leading whitespace. */ Skips leading whitespace. */
const char* GetTextContent(); const char* GetTextContent();
/** Reads the text contents of an element, returns NULL if not given. /** Reads the text contents of an element, returns NULL if not given.
Skips leading whitespace. */ Skips leading whitespace. */
const char* TestTextContent(); const char* TestTextContent();
/** Reads a single bool from current text content */ /** Reads a single bool from current text content */
bool ReadBoolFromTextContent(); bool ReadBoolFromTextContent();
/** Reads a single float from current text content */ /** Reads a single float from current text content */
float ReadFloatFromTextContent(); ai_real ReadFloatFromTextContent();
/** Calculates the resulting transformation from all the given transform steps */ /** Calculates the resulting transformation from all the given transform steps */
aiMatrix4x4 CalculateResultTransform( const std::vector<Collada::Transform>& pTransforms) const; aiMatrix4x4 CalculateResultTransform( const std::vector<Collada::Transform>& pTransforms) const;
/** Determines the input data type for the given semantic string */ /** Determines the input data type for the given semantic string */
Collada::InputType GetTypeForSemantic( const std::string& pSemantic); Collada::InputType GetTypeForSemantic( const std::string& pSemantic);
/** Finds the item in the given library by its reference, throws if not found */ /** Finds the item in the given library by its reference, throws if not found */
template <typename Type> const Type& ResolveLibraryReference( template <typename Type> const Type& ResolveLibraryReference(
const std::map<std::string, Type>& pLibrary, const std::string& pURL) const; const std::map<std::string, Type>& pLibrary, const std::string& pURL) const;
protected: protected:
/** Filename, for a verbose error message */ /** Filename, for a verbose error message */
std::string mFileName; std::string mFileName;
/** XML reader, member for everyday use */ /** XML reader, member for everyday use */
irr::io::IrrXMLReader* mReader; irr::io::IrrXMLReader* mReader;
/** All data arrays found in the file by ID. Might be referred to by actually /** All data arrays found in the file by ID. Might be referred to by actually
everyone. Collada, you are a steaming pile of indirection. */ everyone. Collada, you are a steaming pile of indirection. */
typedef std::map<std::string, Collada::Data> DataLibrary; typedef std::map<std::string, Collada::Data> DataLibrary;
DataLibrary mDataLibrary; DataLibrary mDataLibrary;
/** Same for accessors which define how the data in a data array is accessed. */ /** Same for accessors which define how the data in a data array is accessed. */
typedef std::map<std::string, Collada::Accessor> AccessorLibrary; typedef std::map<std::string, Collada::Accessor> AccessorLibrary;
AccessorLibrary mAccessorLibrary; AccessorLibrary mAccessorLibrary;
/** Mesh library: mesh by ID */ /** Mesh library: mesh by ID */
typedef std::map<std::string, Collada::Mesh*> MeshLibrary; typedef std::map<std::string, Collada::Mesh*> MeshLibrary;
MeshLibrary mMeshLibrary; MeshLibrary mMeshLibrary;
/** node library: root node of the hierarchy part by ID */ /** node library: root node of the hierarchy part by ID */
typedef std::map<std::string, Collada::Node*> NodeLibrary; typedef std::map<std::string, Collada::Node*> NodeLibrary;
NodeLibrary mNodeLibrary; NodeLibrary mNodeLibrary;
/** Image library: stores texture properties by ID */ /** Image library: stores texture properties by ID */
typedef std::map<std::string, Collada::Image> ImageLibrary; typedef std::map<std::string, Collada::Image> ImageLibrary;
ImageLibrary mImageLibrary; ImageLibrary mImageLibrary;
/** Effect library: surface attributes by ID */ /** Effect library: surface attributes by ID */
typedef std::map<std::string, Collada::Effect> EffectLibrary; typedef std::map<std::string, Collada::Effect> EffectLibrary;
EffectLibrary mEffectLibrary; EffectLibrary mEffectLibrary;
/** Material library: surface material by ID */ /** Material library: surface material by ID */
typedef std::map<std::string, Collada::Material> MaterialLibrary; typedef std::map<std::string, Collada::Material> MaterialLibrary;
MaterialLibrary mMaterialLibrary; MaterialLibrary mMaterialLibrary;
/** Light library: surface light by ID */ /** Light library: surface light by ID */
typedef std::map<std::string, Collada::Light> LightLibrary; typedef std::map<std::string, Collada::Light> LightLibrary;
LightLibrary mLightLibrary; LightLibrary mLightLibrary;
/** Camera library: surface material by ID */ /** Camera library: surface material by ID */
typedef std::map<std::string, Collada::Camera> CameraLibrary; typedef std::map<std::string, Collada::Camera> CameraLibrary;
CameraLibrary mCameraLibrary; CameraLibrary mCameraLibrary;
/** Controller library: joint controllers by ID */ /** Controller library: joint controllers by ID */
typedef std::map<std::string, Collada::Controller> ControllerLibrary; typedef std::map<std::string, Collada::Controller> ControllerLibrary;
ControllerLibrary mControllerLibrary; ControllerLibrary mControllerLibrary;
@ -326,24 +326,24 @@ namespace Assimp
/** Animation clip library: clip animation references by ID */ /** Animation clip library: clip animation references by ID */
typedef std::vector<std::pair<std::string, std::vector<std::string> > > AnimationClipLibrary; typedef std::vector<std::pair<std::string, std::vector<std::string> > > AnimationClipLibrary;
AnimationClipLibrary mAnimationClipLibrary; AnimationClipLibrary mAnimationClipLibrary;
/** Pointer to the root node. Don't delete, it just points to one of /** Pointer to the root node. Don't delete, it just points to one of
the nodes in the node library. */ the nodes in the node library. */
Collada::Node* mRootNode; Collada::Node* mRootNode;
/** Root animation container */ /** Root animation container */
Collada::Animation mAnims; Collada::Animation mAnims;
/** Size unit: how large compared to a meter */ /** Size unit: how large compared to a meter */
float mUnitSize; ai_real mUnitSize;
/** Which is the up vector */ /** Which is the up vector */
enum { UP_X, UP_Y, UP_Z } mUpDirection; enum { UP_X, UP_Y, UP_Z } mUpDirection;
/** Collada file format version */ /** Collada file format version */
Collada::FormatVersion mFormat; Collada::FormatVersion mFormat;
}; };
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// Check for element match // Check for element match
inline bool ColladaParser::IsElement( const char* pName) const inline bool ColladaParser::IsElement( const char* pName) const
@ -351,7 +351,7 @@ namespace Assimp
ai_assert( mReader->getNodeType() == irr::io::EXN_ELEMENT); ai_assert( mReader->getNodeType() == irr::io::EXN_ELEMENT);
return ::strcmp( mReader->getNodeName(), pName) == 0; return ::strcmp( mReader->getNodeName(), pName) == 0;
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// Finds the item in the given library by its reference, throws if not found // Finds the item in the given library by its reference, throws if not found
template <typename Type> template <typename Type>
@ -359,10 +359,10 @@ namespace Assimp
{ {
typename std::map<std::string, Type>::const_iterator it = pLibrary.find( pURL); typename std::map<std::string, Type>::const_iterator it = pLibrary.find( pURL);
if( it == pLibrary.end()) if( it == pLibrary.end())
ThrowException( boost::str( boost::format( "Unable to resolve library reference \"%s\".") % pURL)); ThrowException( Formatter::format() << "Unable to resolve library reference \"" << pURL << "\"." );
return it->second; return it->second;
} }
} // end of namespace Assimp } // end of namespace Assimp
#endif // AI_COLLADAPARSER_H_INC #endif // AI_COLLADAPARSER_H_INC

View File

@ -49,10 +49,10 @@ using namespace Assimp;
namespace { namespace {
const static aiVector3D base_axis_y(0.f,1.f,0.f); const static aiVector3D base_axis_y(0.0,1.0,0.0);
const static aiVector3D base_axis_x(1.f,0.f,0.f); const static aiVector3D base_axis_x(1.0,0.0,0.0);
const static aiVector3D base_axis_z(0.f,0.f,1.f); const static aiVector3D base_axis_z(0.0,0.0,1.0);
const static float angle_epsilon = 0.95f; const static ai_real angle_epsilon = 0.95;
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
@ -81,9 +81,9 @@ bool ComputeUVMappingProcess::IsActive( unsigned int pFlags) const
inline bool PlaneIntersect(const aiRay& ray, const aiVector3D& planePos, inline bool PlaneIntersect(const aiRay& ray, const aiVector3D& planePos,
const aiVector3D& planeNormal, aiVector3D& pos) const aiVector3D& planeNormal, aiVector3D& pos)
{ {
const float b = planeNormal * (planePos - ray.pos); const ai_real b = planeNormal * (planePos - ray.pos);
float h = ray.dir * planeNormal; ai_real h = ray.dir * planeNormal;
if ((h < 10e-5f && h > -10e-5f) || (h = b/h) < 0) if ((h < 10e-5 && h > -10e-5) || (h = b/h) < 0)
return false; return false;
pos = ray.pos + (ray.dir * h); pos = ray.pos + (ray.dir * h);
@ -109,11 +109,11 @@ void RemoveUVSeams (aiMesh* mesh, aiVector3D* out)
// much easier, but I don't know how and am currently too tired to // much easier, but I don't know how and am currently too tired to
// to think about a better solution. // to think about a better solution.
const static float LOWER_LIMIT = 0.1f; const static ai_real LOWER_LIMIT = 0.1;
const static float UPPER_LIMIT = 0.9f; const static ai_real UPPER_LIMIT = 0.9;
const static float LOWER_EPSILON = 10e-3f; const static ai_real LOWER_EPSILON = 10e-3;
const static float UPPER_EPSILON = 1.f-10e-3f; const static ai_real UPPER_EPSILON = 1.0-10e-3;
for (unsigned int fidx = 0; fidx < mesh->mNumFaces;++fidx) for (unsigned int fidx = 0; fidx < mesh->mNumFaces;++fidx)
{ {
@ -156,12 +156,12 @@ void RemoveUVSeams (aiMesh* mesh, aiVector3D* out)
// If the u value is over the upper limit and no other u // If the u value is over the upper limit and no other u
// value of that face is 0, round it to 0 // value of that face is 0, round it to 0
if (out[face.mIndices[n]].x > UPPER_LIMIT && !zero) if (out[face.mIndices[n]].x > UPPER_LIMIT && !zero)
out[face.mIndices[n]].x = 0.f; out[face.mIndices[n]].x = 0.0;
// If the u value is below the lower limit and no other u // If the u value is below the lower limit and no other u
// value of that face is 1, round it to 1 // value of that face is 1, round it to 1
else if (out[face.mIndices[n]].x < LOWER_LIMIT && !one) else if (out[face.mIndices[n]].x < LOWER_LIMIT && !one)
out[face.mIndices[n]].x = 1.f; out[face.mIndices[n]].x = 1.0;
// The face contains both 0 and 1 as UV coords. This can occur // The face contains both 0 and 1 as UV coords. This can occur
// for faces which have an edge that lies directly on the seam. // for faces which have an edge that lies directly on the seam.
@ -171,9 +171,9 @@ void RemoveUVSeams (aiMesh* mesh, aiVector3D* out)
else if (one && zero) else if (one && zero)
{ {
if (round_to_zero && out[face.mIndices[n]].x >= UPPER_EPSILON) if (round_to_zero && out[face.mIndices[n]].x >= UPPER_EPSILON)
out[face.mIndices[n]].x = 0.f; out[face.mIndices[n]].x = 0.0;
else if (!round_to_zero && out[face.mIndices[n]].x <= LOWER_EPSILON) else if (!round_to_zero && out[face.mIndices[n]].x <= LOWER_EPSILON)
out[face.mIndices[n]].x = 1.f; out[face.mIndices[n]].x = 1.0;
} }
} }
} }
@ -207,7 +207,7 @@ void ComputeUVMappingProcess::ComputeSphereMapping(aiMesh* mesh,const aiVector3D
for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) { for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) {
const aiVector3D diff = (mesh->mVertices[pnt]-center).Normalize(); const aiVector3D diff = (mesh->mVertices[pnt]-center).Normalize();
out[pnt] = aiVector3D((atan2 (diff.z, diff.y) + AI_MATH_PI_F ) / AI_MATH_TWO_PI_F, out[pnt] = aiVector3D((atan2 (diff.z, diff.y) + AI_MATH_PI_F ) / AI_MATH_TWO_PI_F,
(std::asin (diff.x) + AI_MATH_HALF_PI_F) / AI_MATH_PI_F, 0.f); (std::asin (diff.x) + AI_MATH_HALF_PI_F) / AI_MATH_PI_F, 0.0);
} }
} }
else if (axis * base_axis_y >= angle_epsilon) { else if (axis * base_axis_y >= angle_epsilon) {
@ -215,7 +215,7 @@ void ComputeUVMappingProcess::ComputeSphereMapping(aiMesh* mesh,const aiVector3D
for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) { for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) {
const aiVector3D diff = (mesh->mVertices[pnt]-center).Normalize(); const aiVector3D diff = (mesh->mVertices[pnt]-center).Normalize();
out[pnt] = aiVector3D((atan2 (diff.x, diff.z) + AI_MATH_PI_F ) / AI_MATH_TWO_PI_F, out[pnt] = aiVector3D((atan2 (diff.x, diff.z) + AI_MATH_PI_F ) / AI_MATH_TWO_PI_F,
(std::asin (diff.y) + AI_MATH_HALF_PI_F) / AI_MATH_PI_F, 0.f); (std::asin (diff.y) + AI_MATH_HALF_PI_F) / AI_MATH_PI_F, 0.0);
} }
} }
else if (axis * base_axis_z >= angle_epsilon) { else if (axis * base_axis_z >= angle_epsilon) {
@ -223,7 +223,7 @@ void ComputeUVMappingProcess::ComputeSphereMapping(aiMesh* mesh,const aiVector3D
for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) { for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) {
const aiVector3D diff = (mesh->mVertices[pnt]-center).Normalize(); const aiVector3D diff = (mesh->mVertices[pnt]-center).Normalize();
out[pnt] = aiVector3D((atan2 (diff.y, diff.x) + AI_MATH_PI_F ) / AI_MATH_TWO_PI_F, out[pnt] = aiVector3D((atan2 (diff.y, diff.x) + AI_MATH_PI_F ) / AI_MATH_TWO_PI_F,
(std::asin (diff.z) + AI_MATH_HALF_PI_F) / AI_MATH_PI_F, 0.f); (std::asin (diff.z) + AI_MATH_HALF_PI_F) / AI_MATH_PI_F, 0.0);
} }
} }
// slower code path in case the mapping axis is not one of the coordinate system axes // slower code path in case the mapping axis is not one of the coordinate system axes
@ -235,7 +235,7 @@ void ComputeUVMappingProcess::ComputeSphereMapping(aiMesh* mesh,const aiVector3D
for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) { for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) {
const aiVector3D diff = ((mTrafo*mesh->mVertices[pnt])-center).Normalize(); const aiVector3D diff = ((mTrafo*mesh->mVertices[pnt])-center).Normalize();
out[pnt] = aiVector3D((atan2 (diff.y, diff.x) + AI_MATH_PI_F ) / AI_MATH_TWO_PI_F, out[pnt] = aiVector3D((atan2 (diff.y, diff.x) + AI_MATH_PI_F ) / AI_MATH_TWO_PI_F,
(asin (diff.z) + AI_MATH_HALF_PI_F) / AI_MATH_PI_F, 0.f); (asin (diff.z) + AI_MATH_HALF_PI_F) / AI_MATH_PI_F, 0.0);
} }
} }
@ -257,7 +257,7 @@ void ComputeUVMappingProcess::ComputeCylinderMapping(aiMesh* mesh,const aiVector
// thus changing the mapping axis) // thus changing the mapping axis)
if (axis * base_axis_x >= angle_epsilon) { if (axis * base_axis_x >= angle_epsilon) {
FindMeshCenter(mesh, center, min, max); FindMeshCenter(mesh, center, min, max);
const float diff = max.x - min.x; const ai_real diff = max.x - min.x;
// If the main axis is 'z', the z coordinate of a point 'p' is mapped // If the main axis is 'z', the z coordinate of a point 'p' is mapped
// directly to the texture V axis. The other axis is derived from // directly to the texture V axis. The other axis is derived from
@ -268,12 +268,12 @@ void ComputeUVMappingProcess::ComputeCylinderMapping(aiMesh* mesh,const aiVector
aiVector3D& uv = out[pnt]; aiVector3D& uv = out[pnt];
uv.y = (pos.x - min.x) / diff; uv.y = (pos.x - min.x) / diff;
uv.x = (atan2 ( pos.z - center.z, pos.y - center.y) +(float)AI_MATH_PI ) / (float)AI_MATH_TWO_PI; uv.x = (atan2 ( pos.z - center.z, pos.y - center.y) +(ai_real)AI_MATH_PI ) / (ai_real)AI_MATH_TWO_PI;
} }
} }
else if (axis * base_axis_y >= angle_epsilon) { else if (axis * base_axis_y >= angle_epsilon) {
FindMeshCenter(mesh, center, min, max); FindMeshCenter(mesh, center, min, max);
const float diff = max.y - min.y; const ai_real diff = max.y - min.y;
// just the same ... // just the same ...
for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) { for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) {
@ -281,12 +281,12 @@ void ComputeUVMappingProcess::ComputeCylinderMapping(aiMesh* mesh,const aiVector
aiVector3D& uv = out[pnt]; aiVector3D& uv = out[pnt];
uv.y = (pos.y - min.y) / diff; uv.y = (pos.y - min.y) / diff;
uv.x = (atan2 ( pos.x - center.x, pos.z - center.z) +(float)AI_MATH_PI ) / (float)AI_MATH_TWO_PI; uv.x = (atan2 ( pos.x - center.x, pos.z - center.z) +(ai_real)AI_MATH_PI ) / (ai_real)AI_MATH_TWO_PI;
} }
} }
else if (axis * base_axis_z >= angle_epsilon) { else if (axis * base_axis_z >= angle_epsilon) {
FindMeshCenter(mesh, center, min, max); FindMeshCenter(mesh, center, min, max);
const float diff = max.z - min.z; const ai_real diff = max.z - min.z;
// just the same ... // just the same ...
for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) { for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) {
@ -294,7 +294,7 @@ void ComputeUVMappingProcess::ComputeCylinderMapping(aiMesh* mesh,const aiVector
aiVector3D& uv = out[pnt]; aiVector3D& uv = out[pnt];
uv.y = (pos.z - min.z) / diff; uv.y = (pos.z - min.z) / diff;
uv.x = (atan2 ( pos.y - center.y, pos.x - center.x) +(float)AI_MATH_PI ) / (float)AI_MATH_TWO_PI; uv.x = (atan2 ( pos.y - center.y, pos.x - center.x) +(ai_real)AI_MATH_PI ) / (ai_real)AI_MATH_TWO_PI;
} }
} }
// slower code path in case the mapping axis is not one of the coordinate system axes // slower code path in case the mapping axis is not one of the coordinate system axes
@ -302,7 +302,7 @@ void ComputeUVMappingProcess::ComputeCylinderMapping(aiMesh* mesh,const aiVector
aiMatrix4x4 mTrafo; aiMatrix4x4 mTrafo;
aiMatrix4x4::FromToMatrix(axis,base_axis_y,mTrafo); aiMatrix4x4::FromToMatrix(axis,base_axis_y,mTrafo);
FindMeshCenterTransformed(mesh, center, min, max,mTrafo); FindMeshCenterTransformed(mesh, center, min, max,mTrafo);
const float diff = max.y - min.y; const ai_real diff = max.y - min.y;
// again the same, except we're applying a transformation now // again the same, except we're applying a transformation now
for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt){ for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt){
@ -310,7 +310,7 @@ void ComputeUVMappingProcess::ComputeCylinderMapping(aiMesh* mesh,const aiVector
aiVector3D& uv = out[pnt]; aiVector3D& uv = out[pnt];
uv.y = (pos.y - min.y) / diff; uv.y = (pos.y - min.y) / diff;
uv.x = (atan2 ( pos.x - center.x, pos.z - center.z) +(float)AI_MATH_PI ) / (float)AI_MATH_TWO_PI; uv.x = (atan2 ( pos.x - center.x, pos.z - center.z) +(ai_real)AI_MATH_PI ) / (ai_real)AI_MATH_TWO_PI;
} }
} }
@ -323,7 +323,7 @@ void ComputeUVMappingProcess::ComputeCylinderMapping(aiMesh* mesh,const aiVector
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
void ComputeUVMappingProcess::ComputePlaneMapping(aiMesh* mesh,const aiVector3D& axis, aiVector3D* out) void ComputeUVMappingProcess::ComputePlaneMapping(aiMesh* mesh,const aiVector3D& axis, aiVector3D* out)
{ {
float diffu,diffv; ai_real diffu,diffv;
aiVector3D center, min, max; aiVector3D center, min, max;
// If the axis is one of x,y,z run a faster code path. It's worth the extra effort ... // If the axis is one of x,y,z run a faster code path. It's worth the extra effort ...
@ -337,7 +337,7 @@ void ComputeUVMappingProcess::ComputePlaneMapping(aiMesh* mesh,const aiVector3D&
for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) { for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) {
const aiVector3D& pos = mesh->mVertices[pnt]; const aiVector3D& pos = mesh->mVertices[pnt];
out[pnt].Set((pos.z - min.z) / diffu,(pos.y - min.y) / diffv,0.f); out[pnt].Set((pos.z - min.z) / diffu,(pos.y - min.y) / diffv,0.0);
} }
} }
else if (axis * base_axis_y >= angle_epsilon) { else if (axis * base_axis_y >= angle_epsilon) {
@ -347,7 +347,7 @@ void ComputeUVMappingProcess::ComputePlaneMapping(aiMesh* mesh,const aiVector3D&
for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) { for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) {
const aiVector3D& pos = mesh->mVertices[pnt]; const aiVector3D& pos = mesh->mVertices[pnt];
out[pnt].Set((pos.x - min.x) / diffu,(pos.z - min.z) / diffv,0.f); out[pnt].Set((pos.x - min.x) / diffu,(pos.z - min.z) / diffv,0.0);
} }
} }
else if (axis * base_axis_z >= angle_epsilon) { else if (axis * base_axis_z >= angle_epsilon) {
@ -357,7 +357,7 @@ void ComputeUVMappingProcess::ComputePlaneMapping(aiMesh* mesh,const aiVector3D&
for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) { for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) {
const aiVector3D& pos = mesh->mVertices[pnt]; const aiVector3D& pos = mesh->mVertices[pnt];
out[pnt].Set((pos.y - min.y) / diffu,(pos.x - min.x) / diffv,0.f); out[pnt].Set((pos.y - min.y) / diffu,(pos.x - min.x) / diffv,0.0);
} }
} }
// slower code path in case the mapping axis is not one of the coordinate system axes // slower code path in case the mapping axis is not one of the coordinate system axes
@ -372,7 +372,7 @@ void ComputeUVMappingProcess::ComputePlaneMapping(aiMesh* mesh,const aiVector3D&
// again the same, except we're applying a transformation now // again the same, except we're applying a transformation now
for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) { for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) {
const aiVector3D pos = mTrafo * mesh->mVertices[pnt]; const aiVector3D pos = mTrafo * mesh->mVertices[pnt];
out[pnt].Set((pos.x - min.x) / diffu,(pos.z - min.z) / diffv,0.f); out[pnt].Set((pos.x - min.x) / diffu,(pos.z - min.z) / diffv,0.0);
} }
} }

View File

@ -44,14 +44,13 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define AI_COMPUTEUVMAPPING_H_INC #define AI_COMPUTEUVMAPPING_H_INC
#include "BaseProcess.h" #include "BaseProcess.h"
#include "../include/assimp/mesh.h" #include <assimp/mesh.h>
#include "../include/assimp/material.h" #include <assimp/material.h>
#include "../include/assimp/types.h" #include <assimp/types.h>
class ComputeUVMappingTest; class ComputeUVMappingTest;
namespace Assimp namespace Assimp {
{
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
/** ComputeUVMappingProcess - converts special mappings, such as spherical, /** ComputeUVMappingProcess - converts special mappings, such as spherical,

View File

@ -49,9 +49,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "ConvertToLHProcess.h" #include "ConvertToLHProcess.h"
#include "../include/assimp/scene.h" #include <assimp/scene.h>
#include "../include/assimp/postprocess.h" #include <assimp/postprocess.h>
#include "../include/assimp/DefaultLogger.hpp" #include <assimp/DefaultLogger.hpp>
using namespace Assimp; using namespace Assimp;

View File

@ -49,7 +49,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef AI_CONVERTTOLHPROCESS_H_INC #ifndef AI_CONVERTTOLHPROCESS_H_INC
#define AI_CONVERTTOLHPROCESS_H_INC #define AI_CONVERTTOLHPROCESS_H_INC
#include "../include/assimp/types.h" #include <assimp/types.h>
#include "BaseProcess.h" #include "BaseProcess.h"
struct aiMesh; struct aiMesh;

View File

@ -0,0 +1,388 @@
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
#include "D3MFImporter.h"
#include <assimp/scene.h>
#include <assimp/IOStream.hpp>
#include <assimp/IOSystem.hpp>
#include <assimp/DefaultLogger.hpp>
#include <contrib/unzip/unzip.h>
#include "irrXMLWrapper.h"
#include "StringComparison.h"
#include "StringUtils.h"
#include <string>
#include <sstream>
#include <vector>
#include <map>
#include <algorithm>
#include <cassert>
#include <cstdlib>
#include <memory>
#include <assimp/ai_assert.h>
#include "D3MFOpcPackage.h"
#ifndef ASSIMP_BUILD_NO_3MF_IMPORTER
namespace Assimp {
namespace D3MF {
namespace XmlTag {
const std::string model = "model";
const std::string metadata = "metadata";
const std::string resources = "resources";
const std::string object = "object";
const std::string mesh = "mesh";
const std::string vertices = "vertices";
const std::string vertex = "vertex";
const std::string triangles = "triangles";
const std::string triangle = "triangle";
const std::string x = "x";
const std::string y = "y";
const std::string z = "z";
const std::string v1 = "v1";
const std::string v2 = "v2";
const std::string v3 = "v3";
const std::string id = "id";
const std::string name = "name";
const std::string type = "type";
const std::string build = "build";
const std::string item = "item";
const std::string objectid = "objectid";
const std::string transform = "transform";
}
class XmlSerializer
{
public:
XmlSerializer(XmlReader* xmlReader)
: xmlReader(xmlReader)
{
}
void ImportXml(aiScene* scene)
{
scene->mFlags |= AI_SCENE_FLAGS_NON_VERBOSE_FORMAT;
scene->mRootNode = new aiNode();
std::vector<aiNode*> children;
while(ReadToEndElement(D3MF::XmlTag::model))
{
if(xmlReader->getNodeName() == D3MF::XmlTag::object)
{
children.push_back(ReadObject(scene));
}
else if(xmlReader->getNodeName() == D3MF::XmlTag::build)
{
}
}
if(scene->mRootNode->mName.length == 0)
scene->mRootNode->mName.Set("3MF");
scene->mNumMeshes = static_cast<unsigned int>(meshes.size());
scene->mMeshes = new aiMesh*[scene->mNumMeshes]();
std::copy(meshes.begin(), meshes.end(), scene->mMeshes);
scene->mRootNode->mNumChildren = static_cast<unsigned int>(children.size());
scene->mRootNode->mChildren = new aiNode*[scene->mRootNode->mNumChildren]();
std::copy(children.begin(), children.end(), scene->mRootNode->mChildren);
}
private:
aiNode* ReadObject(aiScene* scene)
{
ScopeGuard<aiNode> node(new aiNode());
std::vector<unsigned long> meshIds;
int id = std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::id.c_str()));
std::string name(xmlReader->getAttributeValue(D3MF::XmlTag::name.c_str()));
std::string type(xmlReader->getAttributeValue(D3MF::XmlTag::type.c_str()));
node->mParent = scene->mRootNode;
node->mName.Set(name);
unsigned long meshIdx = meshes.size();
while(ReadToEndElement(D3MF::XmlTag::object))
{
if(xmlReader->getNodeName() == D3MF::XmlTag::mesh)
{
auto mesh = ReadMesh();
mesh->mName.Set(name);
meshes.push_back(mesh);
meshIds.push_back(meshIdx);
meshIdx++;
}
}
node->mNumMeshes = static_cast<unsigned int>(meshIds.size());
node->mMeshes = new unsigned int[node->mNumMeshes];
std::copy(meshIds.begin(), meshIds.end(), node->mMeshes);
return node.dismiss();
}
aiMesh* ReadMesh()
{
aiMesh* mesh = new aiMesh();
while(ReadToEndElement(D3MF::XmlTag::mesh))
{
if(xmlReader->getNodeName() == D3MF::XmlTag::vertices)
{
ImportVertices(mesh);
}
else if(xmlReader->getNodeName() == D3MF::XmlTag::triangles)
{
ImportTriangles(mesh);
}
}
return mesh;
}
void ImportVertices(aiMesh* mesh)
{
std::vector<aiVector3D> vertices;
while(ReadToEndElement(D3MF::XmlTag::vertices))
{
if(xmlReader->getNodeName() == D3MF::XmlTag::vertex)
{
vertices.push_back(ReadVertex());
}
}
mesh->mNumVertices = static_cast<unsigned int>(vertices.size());
mesh->mVertices = new aiVector3D[mesh->mNumVertices];
std::copy(vertices.begin(), vertices.end(), mesh->mVertices);
}
aiVector3D ReadVertex()
{
aiVector3D vertex;
vertex.x = ai_strtof(xmlReader->getAttributeValue(D3MF::XmlTag::x.c_str()), nullptr);
vertex.y = ai_strtof(xmlReader->getAttributeValue(D3MF::XmlTag::y.c_str()), nullptr);
vertex.z = ai_strtof>(xmlReader->getAttributeValue(D3MF::XmlTag::z.c_str()), nullptr);
return vertex;
}
void ImportTriangles(aiMesh* mesh)
{
std::vector<aiFace> faces;
while(ReadToEndElement(D3MF::XmlTag::triangles))
{
if(xmlReader->getNodeName() == D3MF::XmlTag::triangle)
{
faces.push_back(ReadTriangle());
}
}
mesh->mNumFaces = static_cast<unsigned int>(faces.size());
mesh->mFaces = new aiFace[mesh->mNumFaces];
mesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
std::copy(faces.begin(), faces.end(), mesh->mFaces);
}
aiFace ReadTriangle()
{
aiFace face;
face.mNumIndices = 3;
face.mIndices = new unsigned int[face.mNumIndices];
face.mIndices[0] = static_cast<unsigned int>(std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::v1.c_str())));
face.mIndices[1] = static_cast<unsigned int>(std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::v2.c_str())));
face.mIndices[2] = static_cast<unsigned int>(std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::v3.c_str())));
return face;
}
private:
bool ReadToStartElement(const std::string& startTag)
{
while(xmlReader->read())
{
if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT && xmlReader->getNodeName() == startTag)
{
return true;
}
else if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT_END &&
xmlReader->getNodeName() == startTag)
{
return false;
}
}
//DefaultLogger::get()->error("unexpected EOF, expected closing <" + closeTag + "> tag");
return false;
}
bool ReadToEndElement(const std::string& closeTag)
{
while(xmlReader->read())
{
if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT) {
return true;
}
else if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT_END
&& xmlReader->getNodeName() == closeTag)
{
return false;
}
}
DefaultLogger::get()->error("unexpected EOF, expected closing <" + closeTag + "> tag");
return false;
}
private:
std::vector<aiMesh*> meshes;
XmlReader* xmlReader;
};
} //namespace D3MF
static const aiImporterDesc desc = {
"3mf Importer",
"",
"",
"http://3mf.io/",
aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_SupportCompressedFlavour,
0,
0,
0,
0,
"3mf"
};
D3MFImporter::D3MFImporter()
{
}
D3MFImporter::~D3MFImporter()
{
}
bool D3MFImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool checkSig) const
{
const std::string extension = GetExtension(pFile);
if(extension == "3mf")
{
return true;
}
else if(!extension.length() || checkSig)
{
if(!pIOHandler)
return true;
}
return false;
}
void D3MFImporter::SetupProperties(const Importer *pImp)
{
}
const aiImporterDesc *D3MFImporter::GetInfo() const
{
return &desc;
}
void D3MFImporter::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler)
{
D3MF::D3MFOpcPackage opcPackage(pIOHandler, pFile);
std::unique_ptr<CIrrXML_IOStreamReader> xmlStream(new CIrrXML_IOStreamReader(opcPackage.RootStream()));
std::unique_ptr<D3MF::XmlReader> xmlReader(irr::io::createIrrXMLReader(xmlStream.get()));
D3MF::XmlSerializer xmlSerializer(xmlReader.get());
xmlSerializer.ImportXml(pScene);
}
}
#endif // ASSIMP_BUILD_NO_3MF_IMPORTER

View File

@ -0,0 +1,68 @@
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
#ifndef AI_D3MFLOADER_H_INCLUDED
#define AI_D3MFLOADER_H_INCLUDED
#include <vector>
#include <cstdint>
#include "BaseImporter.h"
namespace Assimp {
class D3MFImporter : public BaseImporter
{
public:
D3MFImporter();
~D3MFImporter();
// BaseImporter interface
public:
bool CanRead(const std::string &pFile, IOSystem *pIOHandler, bool checkSig) const;
void SetupProperties(const Importer *pImp);
const aiImporterDesc *GetInfo() const;
protected:
void InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler);
};
}
#endif // AI_D3MFLOADER_H_INCLUDED

View File

@ -0,0 +1,592 @@
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
#include "D3MFOpcPackage.h"
#include "Exceptional.h"
#include <contrib/unzip/unzip.h>
#include <assimp/IOStream.hpp>
#include <assimp/IOSystem.hpp>
#include <assimp/DefaultLogger.hpp>
#include <assimp/ai_assert.h>
#include <memory>
#include <vector>
#include <map>
#include <algorithm>
#include <cassert>
#include <cstdlib>
#ifndef ASSIMP_BUILD_NO_3MF_IMPORTER
namespace Assimp {
namespace D3MF {
namespace XmlTag {
const std::string CONTENT_TYPES_ARCHIVE = "[Content_Types].xml";
const std::string ROOT_RELATIONSHIPS_ARCHIVE = "_rels/.rels";
const std::string SCHEMA_CONTENTTYPES = "http://schemas.openxmlformats.org/package/2006/content-types";
const std::string SCHEMA_RELATIONSHIPS = "http://schemas.openxmlformats.org/package/2006/relationships";
const std::string RELS_RELATIONSHIP_CONTAINER = "Relationships";
const std::string RELS_RELATIONSHIP_NODE = "Relationship";
const std::string RELS_ATTRIB_TARGET = "Target";
const std::string RELS_ATTRIB_TYPE = "Type";
const std::string RELS_ATTRIB_ID = "Id";
const std::string PACKAGE_START_PART_RELATIONSHIP_TYPE = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel";
const std::string PACKAGE_PRINT_TICKET_RELATIONSHIP_TYPE = "http://schemas.microsoft.com/3dmanufacturing/2013/01/printticket";
const std::string PACKAGE_TEXTURE_RELATIONSHIP_TYPE = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dtexture";
const std::string PACKAGE_CORE_PROPERTIES_RELATIONSHIP_TYPE = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties";
const std::string PACKAGE_THUMBNAIL_RELATIONSHIP_TYPE = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail";
}
class IOSystem2Unzip {
public:
static voidpf open(voidpf opaque, const char* filename, int mode);
static uLong read(voidpf opaque, voidpf stream, void* buf, uLong size);
static uLong write(voidpf opaque, voidpf stream, const void* buf, uLong size);
static long tell(voidpf opaque, voidpf stream);
static long seek(voidpf opaque, voidpf stream, uLong offset, int origin);
static int close(voidpf opaque, voidpf stream);
static int testerror(voidpf opaque, voidpf stream);
static zlib_filefunc_def get(IOSystem* pIOHandler);
};
voidpf IOSystem2Unzip::open(voidpf opaque, const char* filename, int mode) {
IOSystem* io_system = reinterpret_cast<IOSystem*>(opaque);
const char* mode_fopen = NULL;
if((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ) {
mode_fopen = "rb";
} else {
if(mode & ZLIB_FILEFUNC_MODE_EXISTING) {
mode_fopen = "r+b";
} else {
if(mode & ZLIB_FILEFUNC_MODE_CREATE) {
mode_fopen = "wb";
}
}
}
return (voidpf) io_system->Open(filename, mode_fopen);
}
uLong IOSystem2Unzip::read(voidpf /*opaque*/, voidpf stream, void* buf, uLong size) {
IOStream* io_stream = (IOStream*) stream;
return io_stream->Read(buf, 1, size);
}
uLong IOSystem2Unzip::write(voidpf /*opaque*/, voidpf stream, const void* buf, uLong size) {
IOStream* io_stream = (IOStream*) stream;
return io_stream->Write(buf, 1, size);
}
long IOSystem2Unzip::tell(voidpf /*opaque*/, voidpf stream) {
IOStream* io_stream = (IOStream*) stream;
return io_stream->Tell();
}
long IOSystem2Unzip::seek(voidpf /*opaque*/, voidpf stream, uLong offset, int origin) {
IOStream* io_stream = (IOStream*) stream;
aiOrigin assimp_origin;
switch (origin) {
default:
case ZLIB_FILEFUNC_SEEK_CUR:
assimp_origin = aiOrigin_CUR;
break;
case ZLIB_FILEFUNC_SEEK_END:
assimp_origin = aiOrigin_END;
break;
case ZLIB_FILEFUNC_SEEK_SET:
assimp_origin = aiOrigin_SET;
break;
}
return (io_stream->Seek(offset, assimp_origin) == aiReturn_SUCCESS ? 0 : -1);
}
int IOSystem2Unzip::close(voidpf opaque, voidpf stream) {
IOSystem* io_system = (IOSystem*) opaque;
IOStream* io_stream = (IOStream*) stream;
io_system->Close(io_stream);
return 0;
}
int IOSystem2Unzip::testerror(voidpf /*opaque*/, voidpf /*stream*/) {
return 0;
}
zlib_filefunc_def IOSystem2Unzip::get(IOSystem* pIOHandler) {
zlib_filefunc_def mapping;
mapping.zopen_file = open;
mapping.zread_file = read;
mapping.zwrite_file = write;
mapping.ztell_file = tell;
mapping.zseek_file = seek;
mapping.zclose_file = close;
mapping.zerror_file = testerror;
mapping.opaque = reinterpret_cast<voidpf>(pIOHandler);
return mapping;
}
class ZipFile : public IOStream
{
friend class D3MFZipArchive;
public:
explicit ZipFile(size_t size);
~ZipFile();
size_t Read(void* pvBuffer, size_t pSize, size_t pCount );
size_t Write(const void* /*pvBuffer*/, size_t /*pSize*/, size_t /*pCount*/);
size_t FileSize() const;
aiReturn Seek(size_t /*pOffset*/, aiOrigin /*pOrigin*/);
size_t Tell() const;
void Flush();
private:
void* m_Buffer;
size_t m_Size;
};
ZipFile::ZipFile(size_t size) : m_Size(size) {
ai_assert(m_Size != 0);
m_Buffer = malloc(m_Size);
}
ZipFile::~ZipFile() {
free(m_Buffer);
m_Buffer = NULL;
}
size_t ZipFile::Read(void* pvBuffer, size_t pSize, size_t pCount) {
const size_t size = pSize * pCount;
assert(size <= m_Size);
std::memcpy(pvBuffer, m_Buffer, size);
return size;
}
size_t ZipFile::Write(const void* /*pvBuffer*/, size_t /*pSize*/, size_t /*pCount*/) {
return 0;
}
size_t ZipFile::FileSize() const {
return m_Size;
}
aiReturn ZipFile::Seek(size_t /*pOffset*/, aiOrigin /*pOrigin*/) {
return aiReturn_FAILURE;
}
size_t ZipFile::Tell() const {
return 0;
}
void ZipFile::Flush() {
// empty
}
class D3MFZipArchive : public IOSystem
{
public:
static const unsigned int FileNameSize = 256;
public:
D3MFZipArchive(IOSystem* pIOHandler, const std::string & rFile);
~D3MFZipArchive();
bool Exists(const char* pFile) const;
char getOsSeparator() const;
IOStream* Open(const char* pFile, const char* pMode = "rb");
void Close(IOStream* pFile);
bool isOpen() const;
void getFileList(std::vector<std::string> &rFileList);
private:
bool mapArchive();
private:
unzFile m_ZipFileHandle;
std::map<std::string, ZipFile*> m_ArchiveMap;
};
// ------------------------------------------------------------------------------------------------
// Constructor.
D3MFZipArchive::D3MFZipArchive(IOSystem* pIOHandler, const std::string& rFile)
: m_ZipFileHandle(NULL), m_ArchiveMap()
{
if (! rFile.empty())
{
zlib_filefunc_def mapping = IOSystem2Unzip::get(pIOHandler);
m_ZipFileHandle = unzOpen2(rFile.c_str(), &mapping);
if(m_ZipFileHandle != NULL) {
mapArchive();
}
}
}
// ------------------------------------------------------------------------------------------------
// Destructor.
D3MFZipArchive::~D3MFZipArchive() {
for(auto &file : m_ArchiveMap) {
delete file.second;
}
m_ArchiveMap.clear();
if(m_ZipFileHandle != NULL) {
unzClose(m_ZipFileHandle);
m_ZipFileHandle = NULL;
}
}
// ------------------------------------------------------------------------------------------------
// Returns true, if the archive is already open.
bool D3MFZipArchive::isOpen() const {
return (m_ZipFileHandle != NULL);
}
// ------------------------------------------------------------------------------------------------
// Returns true, if the filename is part of the archive.
bool D3MFZipArchive::Exists(const char* pFile) const {
ai_assert(pFile != NULL);
bool exist = false;
if (pFile != NULL) {
std::string rFile(pFile);
std::map<std::string, ZipFile*>::const_iterator it = m_ArchiveMap.find(rFile);
if(it != m_ArchiveMap.end()) {
exist = true;
}
}
return exist;
}
// ------------------------------------------------------------------------------------------------
// Returns the separator delimiter.
char D3MFZipArchive::getOsSeparator() const {
#ifndef _WIN32
return '/';
#else
return '\\';
#endif
}
// ------------------------------------------------------------------------------------------------
// Opens a file, which is part of the archive.
IOStream *D3MFZipArchive::Open(const char* pFile, const char* /*pMode*/) {
ai_assert(pFile != NULL);
IOStream* result = NULL;
std::map<std::string, ZipFile*>::iterator it = m_ArchiveMap.find(pFile);
if(it != m_ArchiveMap.end()) {
result = static_cast<IOStream*>(it->second);
}
return result;
}
// ------------------------------------------------------------------------------------------------
// Close a filestream.
void D3MFZipArchive::Close(IOStream *pFile) {
ai_assert(pFile != NULL);
// We don't do anything in case the file would be opened again in the future
}
// ------------------------------------------------------------------------------------------------
// Returns the file-list of the archive.
void D3MFZipArchive::getFileList(std::vector<std::string> &rFileList) {
rFileList.clear();
for(const auto &file : m_ArchiveMap) {
rFileList.push_back(file.first);
}
}
// ------------------------------------------------------------------------------------------------
// Maps the archive content.
bool D3MFZipArchive::mapArchive() {
bool success = false;
if(m_ZipFileHandle != NULL) {
if(m_ArchiveMap.empty()) {
// At first ensure file is already open
if(unzGoToFirstFile(m_ZipFileHandle) == UNZ_OK) {
// Loop over all files
do {
char filename[FileNameSize];
unz_file_info fileInfo;
if(unzGetCurrentFileInfo(m_ZipFileHandle, &fileInfo, filename, FileNameSize, NULL, 0, NULL, 0) == UNZ_OK) {
// The file has EXACTLY the size of uncompressed_size. In C
// you need to mark the last character with '\0', so add
// another character
if(fileInfo.uncompressed_size != 0 && unzOpenCurrentFile(m_ZipFileHandle) == UNZ_OK) {
std::pair<std::map<std::string, ZipFile*>::iterator, bool> result = m_ArchiveMap.insert(std::make_pair(filename, new ZipFile(fileInfo.uncompressed_size)));
if(unzReadCurrentFile(m_ZipFileHandle, result.first->second->m_Buffer, fileInfo.uncompressed_size) == (long int) fileInfo.uncompressed_size) {
if(unzCloseCurrentFile(m_ZipFileHandle) == UNZ_OK) {
// Nothing to do anymore...
}
}
}
}
} while(unzGoToNextFile(m_ZipFileHandle) != UNZ_END_OF_LIST_OF_FILE);
}
}
success = true;
}
return success;
}
// ------------------------------------------------------------------------------------------------
struct OpcPackageRelationship
{
std::string id;
std::string type;
std::string target;
};
typedef std::shared_ptr<OpcPackageRelationship> OpcPackageRelationshipPtr;
class OpcPackageRelationshipReader
{
public:
OpcPackageRelationshipReader(XmlReader* xmlReader)
{
while(xmlReader->read())
{
if(xmlReader->getNodeType() == irr::io::EXN_ELEMENT &&
xmlReader->getNodeName() == XmlTag::RELS_RELATIONSHIP_CONTAINER)
{
ParseRootNode(xmlReader);
}
}
}
void ParseRootNode(XmlReader* xmlReader)
{
ParseAttributes(xmlReader);
while(xmlReader->read())
{
if(xmlReader->getNodeType() == irr::io::EXN_ELEMENT &&
xmlReader->getNodeName() == XmlTag::RELS_RELATIONSHIP_NODE)
{
ParseChildNode(xmlReader);
}
}
}
void ParseAttributes(XmlReader*)
{
}
void ParseChildNode(XmlReader* xmlReader)
{
OpcPackageRelationshipPtr relPtr(new OpcPackageRelationship());
relPtr->id = xmlReader->getAttributeValue(XmlTag::RELS_ATTRIB_ID.c_str());
relPtr->type = xmlReader->getAttributeValue(XmlTag::RELS_ATTRIB_TYPE.c_str());
relPtr->target = xmlReader->getAttributeValue(XmlTag::RELS_ATTRIB_TARGET.c_str());
m_relationShips.push_back(relPtr);
}
std::vector<OpcPackageRelationshipPtr> m_relationShips;
};
// ------------------------------------------------------------------------------------------------
D3MFOpcPackage::D3MFOpcPackage(IOSystem* pIOHandler, const std::string& rFile)
: m_RootStream(nullptr)
{
zipArchive.reset(new D3MF::D3MFZipArchive( pIOHandler, rFile ));
if(!zipArchive->isOpen())
throw DeadlyImportError("Failed to open file " + rFile+ ".");
std::vector<std::string> fileList;
zipArchive->getFileList(fileList);
for(auto& file: fileList){
if(file == D3MF::XmlTag::ROOT_RELATIONSHIPS_ARCHIVE)
{
//PkgRelationshipReader pkgRelReader(file, archive);
ai_assert(zipArchive->Exists(file.c_str()));
IOStream *fileStream = zipArchive->Open(file.c_str());
ai_assert(fileStream != nullptr);
std::string rootFile = ReadPackageRootRelationship(fileStream);
if(rootFile.size() > 0 && rootFile[0] == '/')
rootFile = rootFile.substr(1);
DefaultLogger::get()->debug(rootFile);
m_RootStream = zipArchive->Open(rootFile.c_str());
ai_assert(m_RootStream != nullptr);
// const size_t size = zipArchive->FileSize();
// m_Data.resize( size );
// const size_t readSize = pMapFile->Read( &m_Data[0], sizeof( char ), size );
// if ( readSize != size )
// {
// m_Data.clear();
// return false;
// }
zipArchive->Close( fileStream );
}
else if( file == D3MF::XmlTag::CONTENT_TYPES_ARCHIVE)
{
}
}
}
D3MFOpcPackage::~D3MFOpcPackage()
{
}
IOStream* D3MFOpcPackage::RootStream() const
{
return m_RootStream;
}
std::string D3MFOpcPackage::ReadPackageRootRelationship(IOStream* stream)
{
std::unique_ptr<CIrrXML_IOStreamReader> xmlStream(new CIrrXML_IOStreamReader(stream));
std::unique_ptr<XmlReader> xml(irr::io::createIrrXMLReader(xmlStream.get()));
OpcPackageRelationshipReader reader(xml.get());
auto itr = std::find_if(reader.m_relationShips.begin(), reader.m_relationShips.end(), [](const OpcPackageRelationshipPtr& rel){
return rel->type == XmlTag::PACKAGE_START_PART_RELATIONSHIP_TYPE;
});
if(itr == reader.m_relationShips.end())
throw DeadlyImportError("Cannot find" + XmlTag::PACKAGE_START_PART_RELATIONSHIP_TYPE);
return (*itr)->target;
}
} //namespace D3MF
}
#endif //ASSIMP_BUILD_NO_3MF_IMPORTER

View File

@ -0,0 +1,76 @@
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
#ifndef D3MFOPCPACKAGE_H
#define D3MFOPCPACKAGE_H
#include <string>
#include <memory>
#include <assimp/IOSystem.hpp>
#include "irrXMLWrapper.h"
namespace Assimp {
namespace D3MF {
typedef irr::io::IrrXMLReader XmlReader;
typedef std::shared_ptr<XmlReader> XmlReaderPtr;
class D3MFZipArchive;
class D3MFOpcPackage
{
public:
D3MFOpcPackage(IOSystem* pIOHandler, const std::string& rFile);
~D3MFOpcPackage();
IOStream* RootStream() const;
private:
std::string ReadPackageRootRelationship(IOStream* stream);
private:
IOStream* m_RootStream;
std::unique_ptr<D3MFZipArchive> zipArchive;
};
}
}
#endif // D3MFOPCPACKAGE_H

View File

@ -50,7 +50,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "StreamReader.h" #include "StreamReader.h"
#include "fast_atof.h" #include "fast_atof.h"
#include <vector> #include <vector>
#include "../include/assimp/DefaultLogger.hpp" #include <assimp/DefaultLogger.hpp>
namespace Assimp { namespace Assimp {
namespace DXF { namespace DXF {
@ -213,7 +213,7 @@ struct InsertBlock
// keeps track of all geometry in a single BLOCK. // keeps track of all geometry in a single BLOCK.
struct Block struct Block
{ {
std::vector< boost::shared_ptr<PolyLine> > lines; std::vector< std::shared_ptr<PolyLine> > lines;
std::vector<InsertBlock> insertions; std::vector<InsertBlock> insertions;
std::string name; std::string name;

View File

@ -52,9 +52,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "fast_atof.h" #include "fast_atof.h"
#include "DXFHelper.h" #include "DXFHelper.h"
#include "../include/assimp/IOSystem.hpp" #include <assimp/IOSystem.hpp>
#include "../include/assimp/scene.h" #include <assimp/scene.h>
#include <boost/foreach.hpp>
#include <numeric> #include <numeric>
using namespace Assimp; using namespace Assimp;
@ -134,7 +133,7 @@ void DXFImporter::InternReadFile( const std::string& pFile,
aiScene* pScene, aiScene* pScene,
IOSystem* pIOHandler) IOSystem* pIOHandler)
{ {
boost::shared_ptr<IOStream> file = boost::shared_ptr<IOStream>( pIOHandler->Open( pFile) ); std::shared_ptr<IOStream> file = std::shared_ptr<IOStream>( pIOHandler->Open( pFile) );
// Check whether we can read the file // Check whether we can read the file
if( file.get() == NULL) { if( file.get() == NULL) {
@ -175,7 +174,7 @@ void DXFImporter::InternReadFile( const std::string& pFile,
} }
// skip unneeded sections entirely to avoid any problems with them // skip unneeded sections entirely to avoid any problems with them
// alltogether. // altogether.
else if (reader.Is(2,"CLASSES") || reader.Is(2,"TABLES")) { else if (reader.Is(2,"CLASSES") || reader.Is(2,"TABLES")) {
SkipSection(reader); SkipSection(reader);
continue; continue;
@ -222,8 +221,8 @@ void DXFImporter::ConvertMeshes(aiScene* pScene, DXF::FileData& output)
if (!DefaultLogger::isNullLogger()) { if (!DefaultLogger::isNullLogger()) {
unsigned int vcount = 0, icount = 0; unsigned int vcount = 0, icount = 0;
BOOST_FOREACH (const DXF::Block& bl, output.blocks) { for (const DXF::Block& bl : output.blocks) {
BOOST_FOREACH (boost::shared_ptr<const DXF::PolyLine> pl, bl.lines) { for (std::shared_ptr<const DXF::PolyLine> pl : bl.lines) {
vcount += pl->positions.size(); vcount += pl->positions.size();
icount += pl->counts.size(); icount += pl->counts.size();
} }
@ -242,7 +241,7 @@ void DXFImporter::ConvertMeshes(aiScene* pScene, DXF::FileData& output)
// index blocks by name // index blocks by name
DXF::BlockMap blocks_by_name; DXF::BlockMap blocks_by_name;
BOOST_FOREACH (DXF::Block& bl, output.blocks) { for (DXF::Block& bl : output.blocks) {
blocks_by_name[bl.name] = &bl; blocks_by_name[bl.name] = &bl;
if ( !entities && bl.name == AI_DXF_ENTITIES_MAGIC_BLOCK ) { if ( !entities && bl.name == AI_DXF_ENTITIES_MAGIC_BLOCK ) {
entities = &bl; entities = &bl;
@ -263,7 +262,7 @@ void DXFImporter::ConvertMeshes(aiScene* pScene, DXF::FileData& output)
ExpandBlockReferences(*entities,blocks_by_name); ExpandBlockReferences(*entities,blocks_by_name);
unsigned int cur = 0; unsigned int cur = 0;
BOOST_FOREACH (boost::shared_ptr<const DXF::PolyLine> pl, entities->lines) { for (std::shared_ptr<const DXF::PolyLine> pl : entities->lines) {
if (pl->positions.size()) { if (pl->positions.size()) {
std::map<std::string, unsigned int>::iterator it = layers.find(pl->layer); std::map<std::string, unsigned int>::iterator it = layers.find(pl->layer);
@ -289,12 +288,12 @@ void DXFImporter::ConvertMeshes(aiScene* pScene, DXF::FileData& output)
pScene->mMeshes = new aiMesh*[ pScene->mNumMeshes ] (); pScene->mMeshes = new aiMesh*[ pScene->mNumMeshes ] ();
BOOST_FOREACH(const LayerMap::value_type& elem, layers){ for(const LayerMap::value_type& elem : layers){
aiMesh* const mesh = pScene->mMeshes[elem.second] = new aiMesh(); aiMesh* const mesh = pScene->mMeshes[elem.second] = new aiMesh();
mesh->mName.Set(elem.first); mesh->mName.Set(elem.first);
unsigned int cvert = 0,cface = 0; unsigned int cvert = 0,cface = 0;
BOOST_FOREACH(const DXF::PolyLine* pl, corr[elem.second]){ for(const DXF::PolyLine* pl : corr[elem.second]){
// sum over all faces since we need to 'verbosify' them. // sum over all faces since we need to 'verbosify' them.
cvert += std::accumulate(pl->counts.begin(),pl->counts.end(),0); cvert += std::accumulate(pl->counts.begin(),pl->counts.end(),0);
cface += pl->counts.size(); cface += pl->counts.size();
@ -309,10 +308,10 @@ void DXFImporter::ConvertMeshes(aiScene* pScene, DXF::FileData& output)
unsigned int prims = 0; unsigned int prims = 0;
unsigned int overall_indices = 0; unsigned int overall_indices = 0;
BOOST_FOREACH(const DXF::PolyLine* pl, corr[elem.second]){ for(const DXF::PolyLine* pl : corr[elem.second]){
std::vector<unsigned int>::const_iterator it = pl->indices.begin(); std::vector<unsigned int>::const_iterator it = pl->indices.begin();
BOOST_FOREACH(unsigned int facenumv,pl->counts) { for(unsigned int facenumv : pl->counts) {
aiFace& face = *faces++; aiFace& face = *faces++;
face.mIndices = new unsigned int[face.mNumIndices = facenumv]; face.mIndices = new unsigned int[face.mNumIndices = facenumv];
@ -358,7 +357,7 @@ void DXFImporter::ConvertMeshes(aiScene* pScene, DXF::FileData& output)
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
void DXFImporter::ExpandBlockReferences(DXF::Block& bl,const DXF::BlockMap& blocks_by_name) void DXFImporter::ExpandBlockReferences(DXF::Block& bl,const DXF::BlockMap& blocks_by_name)
{ {
BOOST_FOREACH (const DXF::InsertBlock& insert, bl.insertions) { for (const DXF::InsertBlock& insert : bl.insertions) {
// first check if the referenced blocks exists ... // first check if the referenced blocks exists ...
const DXF::BlockMap::const_iterator it = blocks_by_name.find(insert.name); const DXF::BlockMap::const_iterator it = blocks_by_name.find(insert.name);
@ -372,8 +371,8 @@ void DXFImporter::ExpandBlockReferences(DXF::Block& bl,const DXF::BlockMap& bloc
// XXX this would be the place to implement recursive expansion if needed. // XXX this would be the place to implement recursive expansion if needed.
const DXF::Block& bl_src = *(*it).second; const DXF::Block& bl_src = *(*it).second;
BOOST_FOREACH (boost::shared_ptr<const DXF::PolyLine> pl_in, bl_src.lines) { for (std::shared_ptr<const DXF::PolyLine> pl_in : bl_src.lines) {
boost::shared_ptr<DXF::PolyLine> pl_out = boost::shared_ptr<DXF::PolyLine>(new DXF::PolyLine(*pl_in)); std::shared_ptr<DXF::PolyLine> pl_out = std::shared_ptr<DXF::PolyLine>(new DXF::PolyLine(*pl_in));
if (bl_src.base.Length() || insert.scale.x!=1.f || insert.scale.y!=1.f || insert.scale.z!=1.f || insert.angle || insert.pos.Length()) { if (bl_src.base.Length() || insert.scale.x!=1.f || insert.scale.y!=1.f || insert.scale.z!=1.f || insert.angle || insert.pos.Length()) {
// manual coordinate system transformation // manual coordinate system transformation
@ -388,7 +387,7 @@ void DXFImporter::ExpandBlockReferences(DXF::Block& bl,const DXF::BlockMap& bloc
DefaultLogger::get()->warn("DXF: BLOCK rotation not currently implemented"); DefaultLogger::get()->warn("DXF: BLOCK rotation not currently implemented");
} }
BOOST_FOREACH (aiVector3D& v, pl_out->positions) { for (aiVector3D& v : pl_out->positions) {
v *= trafo; v *= trafo;
} }
} }
@ -618,7 +617,7 @@ void DXFImporter::ParseInsertion(DXF::LineReader& reader, DXF::FileData& output)
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
void DXFImporter::ParsePolyLine(DXF::LineReader& reader, DXF::FileData& output) void DXFImporter::ParsePolyLine(DXF::LineReader& reader, DXF::FileData& output)
{ {
output.blocks.back().lines.push_back( boost::shared_ptr<DXF::PolyLine>( new DXF::PolyLine() ) ); output.blocks.back().lines.push_back( std::shared_ptr<DXF::PolyLine>( new DXF::PolyLine() ) );
DXF::PolyLine& line = *output.blocks.back().lines.back(); DXF::PolyLine& line = *output.blocks.back().lines.back();
unsigned int iguess = 0, vguess = 0; unsigned int iguess = 0, vguess = 0;
@ -800,7 +799,7 @@ void DXFImporter::Parse3DFace(DXF::LineReader& reader, DXF::FileData& output)
// (note) this is also used for for parsing line entities, so we // (note) this is also used for for parsing line entities, so we
// must handle the vertex_count == 2 case as well. // must handle the vertex_count == 2 case as well.
output.blocks.back().lines.push_back( boost::shared_ptr<DXF::PolyLine>( new DXF::PolyLine() ) ); output.blocks.back().lines.push_back( std::shared_ptr<DXF::PolyLine>( new DXF::PolyLine() ) );
DXF::PolyLine& line = *output.blocks.back().lines.back(); DXF::PolyLine& line = *output.blocks.back().lines.back();
aiVector3D vip[4]; aiVector3D vip[4];

View File

@ -46,8 +46,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <utility> #include <utility>
#include "BaseProcess.h" #include "BaseProcess.h"
#include "../include/assimp/mesh.h" #include <assimp/mesh.h>
#include "../include/assimp/scene.h" #include <assimp/scene.h>
class DeboneTest; class DeboneTest;

View File

@ -43,9 +43,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
#include "../include/assimp/ai_assert.h" #include <assimp/ai_assert.h>
#include "DefaultIOStream.h" #include "DefaultIOStream.h"
#include <boost/static_assert.hpp>
#include <sys/types.h> #include <sys/types.h>
#include <sys/stat.h> #include <sys/stat.h>
@ -86,8 +85,9 @@ aiReturn DefaultIOStream::Seek(size_t pOffset,
} }
// Just to check whether our enum maps one to one with the CRT constants // Just to check whether our enum maps one to one with the CRT constants
BOOST_STATIC_ASSERT(aiOrigin_CUR == SEEK_CUR && static_assert(aiOrigin_CUR == SEEK_CUR &&
aiOrigin_END == SEEK_END && aiOrigin_SET == SEEK_SET); aiOrigin_END == SEEK_END && aiOrigin_SET == SEEK_SET, "aiOrigin_CUR == SEEK_CUR && \
aiOrigin_END == SEEK_END && aiOrigin_SET == SEEK_SET");
// do the seek // do the seek
return (0 == ::fseek(mFile, (long)pOffset,(int)pOrigin) ? AI_SUCCESS : AI_FAILURE); return (0 == ::fseek(mFile, (long)pOffset,(int)pOrigin) ? AI_SUCCESS : AI_FAILURE);

View File

@ -43,8 +43,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define AI_DEFAULTIOSTREAM_H_INC #define AI_DEFAULTIOSTREAM_H_INC
#include <stdio.h> #include <stdio.h>
#include "../include/assimp/IOStream.hpp" #include <assimp/IOStream.hpp>
#include "../include/assimp/importerdesc.h" #include <assimp/importerdesc.h>
#include "Defines.h" #include "Defines.h"
namespace Assimp { namespace Assimp {
@ -55,7 +55,7 @@ namespace Assimp {
//! @note An instance of this class can exist without a valid file handle //! @note An instance of this class can exist without a valid file handle
//! attached to it. All calls fail, but the instance can nevertheless be //! attached to it. All calls fail, but the instance can nevertheless be
//! used with no restrictions. //! used with no restrictions.
class DefaultIOStream : public IOStream class ASSIMP_API DefaultIOStream : public IOStream
{ {
friend class DefaultIOSystem; friend class DefaultIOSystem;
#if __ANDROID__ #if __ANDROID__

View File

@ -44,8 +44,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "DefaultIOStream.h" #include "DefaultIOStream.h"
#include "StringComparison.h" #include "StringComparison.h"
#include "../include/assimp/DefaultLogger.hpp" #include <assimp/DefaultLogger.hpp>
#include "../include/assimp/ai_assert.h" #include <assimp/ai_assert.h>
#include <stdlib.h> #include <stdlib.h>

View File

@ -42,7 +42,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef AI_DEFAULTIOSYSTEM_H_INC #ifndef AI_DEFAULTIOSYSTEM_H_INC
#define AI_DEFAULTIOSYSTEM_H_INC #define AI_DEFAULTIOSYSTEM_H_INC
#include "../include/assimp/IOSystem.hpp" #include <assimp/IOSystem.hpp>
namespace Assimp { namespace Assimp {

View File

@ -50,17 +50,17 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "StdOStreamLogStream.h" #include "StdOStreamLogStream.h"
#include "FileLogStream.h" #include "FileLogStream.h"
#include "StringUtils.h" #include "StringUtils.h"
#include "../include/assimp/NullLogger.hpp" #include <assimp/NullLogger.hpp>
#include "../include/assimp/DefaultLogger.hpp" #include <assimp/DefaultLogger.hpp>
#include "../include/assimp/ai_assert.h" #include <assimp/ai_assert.h>
#include <iostream> #include <iostream>
#include <stdio.h> #include <stdio.h>
#ifndef ASSIMP_BUILD_SINGLETHREADED #ifndef ASSIMP_BUILD_SINGLETHREADED
# include <boost/thread/thread.hpp> # include <thread>
# include <boost/thread/mutex.hpp> # include <mutex>
boost::mutex loggerMutex; std::mutex loggerMutex;
#endif #endif
namespace Assimp { namespace Assimp {
@ -135,7 +135,7 @@ Logger *DefaultLogger::create(const char* name /*= "AssimpLog.txt"*/,
{ {
// enter the mutex here to avoid concurrency problems // enter the mutex here to avoid concurrency problems
#ifndef ASSIMP_BUILD_SINGLETHREADED #ifndef ASSIMP_BUILD_SINGLETHREADED
boost::mutex::scoped_lock lock(loggerMutex); std::lock_guard<std::mutex> lock(loggerMutex);
#endif #endif
if (m_pLogger && !isNullLogger() ) if (m_pLogger && !isNullLogger() )
@ -210,7 +210,7 @@ void DefaultLogger::set( Logger *logger )
{ {
// enter the mutex here to avoid concurrency problems // enter the mutex here to avoid concurrency problems
#ifndef ASSIMP_BUILD_SINGLETHREADED #ifndef ASSIMP_BUILD_SINGLETHREADED
boost::mutex::scoped_lock lock(loggerMutex); std::lock_guard<std::mutex> lock(loggerMutex);
#endif #endif
if (!logger)logger = &s_pNullLogger; if (!logger)logger = &s_pNullLogger;
@ -237,7 +237,7 @@ void DefaultLogger::kill()
{ {
// enter the mutex here to avoid concurrency problems // enter the mutex here to avoid concurrency problems
#ifndef ASSIMP_BUILD_SINGLETHREADED #ifndef ASSIMP_BUILD_SINGLETHREADED
boost::mutex::scoped_lock lock(loggerMutex); std::lock_guard<std::mutex> lock(loggerMutex);
#endif #endif
if ( m_pLogger == &s_pNullLogger ) { if ( m_pLogger == &s_pNullLogger ) {
@ -413,7 +413,8 @@ void DefaultLogger::WriteToStreams(const char *message, ErrorSeverity ErrorSev )
// Returns thread id, if not supported only a zero will be returned. // Returns thread id, if not supported only a zero will be returned.
unsigned int DefaultLogger::GetThreadID() unsigned int DefaultLogger::GetThreadID()
{ {
// fixme: we can get this value via boost::threads // fixme: we can get this value via std::threads
// std::this_thread::get_id().hash() returns a (big) size_t, not sure if this is useful in this case.
#ifdef WIN32 #ifdef WIN32
return (unsigned int)::GetCurrentThreadId(); return (unsigned int)::GetCurrentThreadId();
#else #else

View File

@ -44,7 +44,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef INCLUDED_AI_DEFAULTPROGRESSHANDLER_H #ifndef INCLUDED_AI_DEFAULTPROGRESSHANDLER_H
#define INCLUDED_AI_DEFAULTPROGRESSHANDLER_H #define INCLUDED_AI_DEFAULTPROGRESSHANDLER_H
#include "../include/assimp/ProgressHandler.hpp" #include <assimp/ProgressHandler.hpp>
namespace Assimp { namespace Assimp {
// ------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------

View File

@ -58,8 +58,8 @@ class DeadlyImportError
{ {
public: public:
/** Constructor with arguments */ /** Constructor with arguments */
explicit DeadlyImportError( const std::string& pErrorText) explicit DeadlyImportError( const std::string& errorText)
: runtime_error(pErrorText) : runtime_error(errorText)
{ {
} }

View File

@ -63,11 +63,11 @@ Here we implement only the C++ interface (Assimp::Exporter).
#include "ConvertToLHProcess.h" #include "ConvertToLHProcess.h"
#include "Exceptional.h" #include "Exceptional.h"
#include "ScenePrivate.h" #include "ScenePrivate.h"
#include <boost/shared_ptr.hpp> #include <memory>
#include "../include/assimp/Exporter.hpp" #include <assimp/Exporter.hpp>
#include "../include/assimp/mesh.h" #include <assimp/mesh.h>
#include "../include/assimp/postprocess.h" #include <assimp/postprocess.h>
#include "../include/assimp/scene.h" #include <assimp/scene.h>
#include <memory> #include <memory>
namespace Assimp { namespace Assimp {
@ -184,7 +184,7 @@ public:
public: public:
aiExportDataBlob* blob; aiExportDataBlob* blob;
boost::shared_ptr< Assimp::IOSystem > mIOSystem; std::shared_ptr< Assimp::IOSystem > mIOSystem;
bool mIsDefaultIOHandler; bool mIsDefaultIOHandler;
/** Post processing steps we can apply at the imported data. */ /** Post processing steps we can apply at the imported data. */
@ -254,10 +254,10 @@ const aiExportDataBlob* Exporter :: ExportToBlob( const aiScene* pScene, const
} }
boost::shared_ptr<IOSystem> old = pimpl->mIOSystem; std::shared_ptr<IOSystem> old = pimpl->mIOSystem;
BlobIOSystem* blobio = new BlobIOSystem(); BlobIOSystem* blobio = new BlobIOSystem();
pimpl->mIOSystem = boost::shared_ptr<IOSystem>( blobio ); pimpl->mIOSystem = std::shared_ptr<IOSystem>( blobio );
if (AI_SUCCESS != Export(pScene,pFormatId,blobio->GetMagicFileName())) { if (AI_SUCCESS != Export(pScene,pFormatId,blobio->GetMagicFileName())) {
pimpl->mIOSystem = old; pimpl->mIOSystem = old;
@ -324,7 +324,7 @@ aiReturn Exporter :: Export( const aiScene* pScene, const char* pFormatId, const
aiScene* scenecopy_tmp; aiScene* scenecopy_tmp;
SceneCombiner::CopyScene(&scenecopy_tmp,pScene); SceneCombiner::CopyScene(&scenecopy_tmp,pScene);
std::auto_ptr<aiScene> scenecopy(scenecopy_tmp); std::unique_ptr<aiScene> scenecopy(scenecopy_tmp);
const ScenePrivateData* const priv = ScenePriv(pScene); const ScenePrivateData* const priv = ScenePriv(pScene);
// steps that are not idempotent, i.e. we might need to run them again, usually to get back to the // steps that are not idempotent, i.e. we might need to run them again, usually to get back to the
@ -491,7 +491,7 @@ const aiExportFormatDesc* Exporter :: GetExportFormatDescription( size_t pIndex
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
aiReturn Exporter :: RegisterExporter(const ExportFormatEntry& desc) aiReturn Exporter :: RegisterExporter(const ExportFormatEntry& desc)
{ {
BOOST_FOREACH(const ExportFormatEntry& e, pimpl->mExporters) { for(const ExportFormatEntry& e : pimpl->mExporters) {
if (!strcmp(e.mDescription.id,desc.mDescription.id)) { if (!strcmp(e.mDescription.id,desc.mDescription.id)) {
return aiReturn_FAILURE; return aiReturn_FAILURE;
} }
@ -534,9 +534,9 @@ bool ExportProperties :: SetPropertyInteger(const char* szName, int iValue)
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// Set a configuration property // Set a configuration property
bool ExportProperties :: SetPropertyFloat(const char* szName, float iValue) bool ExportProperties :: SetPropertyFloat(const char* szName, ai_real iValue)
{ {
return SetGenericProperty<float>(mFloatProperties, szName,iValue); return SetGenericProperty<ai_real>(mFloatProperties, szName,iValue);
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
@ -563,10 +563,10 @@ int ExportProperties :: GetPropertyInteger(const char* szName,
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// Get a configuration property // Get a configuration property
float ExportProperties :: GetPropertyFloat(const char* szName, ai_real ExportProperties :: GetPropertyFloat(const char* szName,
float iErrorReturn /*= 10e10*/) const ai_real iErrorReturn /*= 10e10*/) const
{ {
return GetGenericProperty<float>(mFloatProperties,szName,iErrorReturn); return GetGenericProperty<ai_real>(mFloatProperties,szName,iErrorReturn);
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
@ -603,7 +603,7 @@ bool ExportProperties :: HasPropertyBool(const char* szName) const
// Has a configuration property // Has a configuration property
bool ExportProperties :: HasPropertyFloat(const char* szName) const bool ExportProperties :: HasPropertyFloat(const char* szName) const
{ {
return HasGenericProperty<float>(mFloatProperties, szName); return HasGenericProperty<ai_real>(mFloatProperties, szName);
}; };
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------

View File

@ -51,7 +51,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "FBXImportSettings.h" #include "FBXImportSettings.h"
#include "FBXDocumentUtil.h" #include "FBXDocumentUtil.h"
#include "FBXProperties.h" #include "FBXProperties.h"
#include <boost/foreach.hpp>
namespace Assimp { namespace Assimp {
namespace FBX { namespace FBX {
@ -110,7 +109,7 @@ AnimationCurveNode::AnimationCurveNode(uint64_t id, const Element& element, cons
const char* whitelist[] = {"Model","NodeAttribute"}; const char* whitelist[] = {"Model","NodeAttribute"};
const std::vector<const Connection*>& conns = doc.GetConnectionsBySourceSequenced(ID(),whitelist,2); const std::vector<const Connection*>& conns = doc.GetConnectionsBySourceSequenced(ID(),whitelist,2);
BOOST_FOREACH(const Connection* con, conns) { for(const Connection* con : conns) {
// link should go for a property // link should go for a property
if (!con->PropertyName().length()) { if (!con->PropertyName().length()) {
@ -171,7 +170,7 @@ const AnimationCurveMap& AnimationCurveNode::Curves() const
// resolve attached animation curves // resolve attached animation curves
const std::vector<const Connection*>& conns = doc.GetConnectionsByDestinationSequenced(ID(),"AnimationCurve"); const std::vector<const Connection*>& conns = doc.GetConnectionsByDestinationSequenced(ID(),"AnimationCurve");
BOOST_FOREACH(const Connection* con, conns) { for(const Connection* con : conns) {
// link should go for a property // link should go for a property
if (!con->PropertyName().length()) { if (!con->PropertyName().length()) {
@ -227,7 +226,7 @@ AnimationCurveNodeList AnimationLayer::Nodes(const char* const * target_prop_whi
const std::vector<const Connection*>& conns = doc.GetConnectionsByDestinationSequenced(ID(),"AnimationCurveNode"); const std::vector<const Connection*>& conns = doc.GetConnectionsByDestinationSequenced(ID(),"AnimationCurveNode");
nodes.reserve(conns.size()); nodes.reserve(conns.size());
BOOST_FOREACH(const Connection* con, conns) { for(const Connection* con : conns) {
// link should not go to a property // link should not go to a property
if (con->PropertyName().length()) { if (con->PropertyName().length()) {
@ -278,7 +277,7 @@ AnimationStack::AnimationStack(uint64_t id, const Element& element, const std::s
const std::vector<const Connection*>& conns = doc.GetConnectionsByDestinationSequenced(ID(),"AnimationLayer"); const std::vector<const Connection*>& conns = doc.GetConnectionsByDestinationSequenced(ID(),"AnimationLayer");
layers.reserve(conns.size()); layers.reserve(conns.size());
BOOST_FOREACH(const Connection* con, conns) { for(const Connection* con : conns) {
// link should not go to a property // link should not go to a property
if (con->PropertyName().length()) { if (con->PropertyName().length()) {

Some files were not shown because too many files have changed in this diff Show More