Commit eb218095 authored by chili's avatar chili
Browse files

update assimp version

parent 1da10a89
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2018, 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.
----------------------------------------------------------------------
*/
/** @file LogAux.h
* @brief Common logging usage patterns for importer implementations
*/
#ifndef INCLUDED_AI_LOGAUX_H
#define INCLUDED_AI_LOGAUX_H
#include <assimp/TinyFormatter.h>
#include <assimp/Exceptional.h>
#include <assimp/DefaultLogger.hpp>
namespace Assimp {
template<class TDeriving>
class LogFunctions {
public:
// ------------------------------------------------------------------------------------------------
static void ThrowException(const std::string& msg)
{
throw DeadlyImportError(Prefix()+msg);
}
// ------------------------------------------------------------------------------------------------
static void LogWarn(const Formatter::format& message) {
if (!DefaultLogger::isNullLogger()) {
ASSIMP_LOG_WARN(Prefix()+(std::string)message);
}
}
// ------------------------------------------------------------------------------------------------
static void LogError(const Formatter::format& message) {
if (!DefaultLogger::isNullLogger()) {
ASSIMP_LOG_ERROR(Prefix()+(std::string)message);
}
}
// ------------------------------------------------------------------------------------------------
static void LogInfo(const Formatter::format& message) {
if (!DefaultLogger::isNullLogger()) {
ASSIMP_LOG_INFO(Prefix()+(std::string)message);
}
}
// ------------------------------------------------------------------------------------------------
static void LogDebug(const Formatter::format& message) {
if (!DefaultLogger::isNullLogger()) {
ASSIMP_LOG_DEBUG(Prefix()+(std::string)message);
}
}
// https://sourceforge.net/tracker/?func=detail&atid=1067632&aid=3358562&group_id=226462
#if !defined(__GNUC__) || !defined(__APPLE__) || __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
// ------------------------------------------------------------------------------------------------
static void LogWarn (const char* message) {
if (!DefaultLogger::isNullLogger()) {
LogWarn(Formatter::format(message));
}
}
// ------------------------------------------------------------------------------------------------
static void LogError (const char* message) {
if (!DefaultLogger::isNullLogger()) {
LogError(Formatter::format(message));
}
}
// ------------------------------------------------------------------------------------------------
static void LogInfo (const char* message) {
if (!DefaultLogger::isNullLogger()) {
LogInfo(Formatter::format(message));
}
}
// ------------------------------------------------------------------------------------------------
static void LogDebug (const char* message) {
if (!DefaultLogger::isNullLogger()) {
LogDebug(Formatter::format(message));
}
}
#endif
private:
static const char* Prefix();
};
} // ! Assimp
#endif
......@@ -2,7 +2,8 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2017, assimp team
Copyright (c) 2006-2018, assimp team
All rights reserved.
......
......@@ -2,7 +2,8 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2017, assimp team
Copyright (c) 2006-2018, assimp team
All rights reserved.
......@@ -45,7 +46,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef INCLUDED_AI_LOGGER_H
#define INCLUDED_AI_LOGGER_H
#include "types.h"
#include <assimp/types.h>
#include <assimp/TinyFormatter.h>
namespace Assimp {
......@@ -58,7 +60,7 @@ class LogStream;
/** @brief CPP-API: Abstract interface for logger implementations.
* Assimp provides a default implementation and uses it for almost all
* logging stuff ('DefaultLogger'). This class defines just basic logging
* behaviour and is not of interest for you. Instead, take a look at #DefaultLogger. */
* behavior and is not of interest for you. Instead, take a look at #DefaultLogger. */
class ASSIMP_API Logger
#ifndef SWIG
: public Intern::AllocateFromAssimpHeap
......@@ -70,8 +72,7 @@ public:
/** @enum LogSeverity
* @brief Log severity to describe the granularity of logging.
*/
enum LogSeverity
{
enum LogSeverity {
NORMAL, //!< Normal granularity of logging
VERBOSE //!< Debug infos will be logged, too
};
......@@ -84,8 +85,7 @@ public:
* A LogStream doesn't receive any messages of a specific type
* if it doesn't specify the corresponding ErrorSeverity flag.
*/
enum ErrorSeverity
{
enum ErrorSeverity {
Debugging = 1, //!< Debug log message
Info = 2, //!< Info log message
Warn = 4, //!< Warn log message
......@@ -101,25 +101,25 @@ public:
/** @brief Writes a debug message
* @param message Debug message*/
void debug(const char* message);
inline void debug(const std::string &message);
void debug(const std::string &message);
// ----------------------------------------------------------------------
/** @brief Writes a info message
* @param message Info message*/
void info(const char* message);
inline void info(const std::string &message);
void info(const std::string &message);
// ----------------------------------------------------------------------
/** @brief Writes a warning message
* @param message Warn message*/
void warn(const char* message);
inline void warn(const std::string &message);
void warn(const std::string &message);
// ----------------------------------------------------------------------
/** @brief Writes an error message
* @param message Error message*/
void error(const char* message);
inline void error(const std::string &message);
void error(const std::string &message);
// ----------------------------------------------------------------------
/** @brief Set a new log severity.
......@@ -158,15 +158,19 @@ public:
unsigned int severity = Debugging | Err | Warn | Info) = 0;
protected:
/** Default constructor */
/**
* Default constructor
*/
Logger();
/** Construction with a given log severity */
/**
* Construction with a given log severity
*/
explicit Logger(LogSeverity severity);
// ----------------------------------------------------------------------
/** @brief Called as a request to write a specific debug message
/**
* @brief Called as a request to write a specific debug message
* @param message Debug message. Never longer than
* MAX_LOG_MESSAGE_LENGTH characters (excluding the '0').
* @note The message string is only valid until the scope of
......@@ -175,7 +179,8 @@ protected:
virtual void OnDebug(const char* message)= 0;
// ----------------------------------------------------------------------
/** @brief Called as a request to write a specific info message
/**
* @brief Called as a request to write a specific info message
* @param message Info message. Never longer than
* MAX_LOG_MESSAGE_LENGTH characters (ecxluding the '0').
* @note The message string is only valid until the scope of
......@@ -184,7 +189,8 @@ protected:
virtual void OnInfo(const char* message) = 0;
// ----------------------------------------------------------------------
/** @brief Called as a request to write a specific warn message
/**
* @brief Called as a request to write a specific warn message
* @param message Warn message. Never longer than
* MAX_LOG_MESSAGE_LENGTH characters (exluding the '0').
* @note The message string is only valid until the scope of
......@@ -193,7 +199,8 @@ protected:
virtual void OnWarn(const char* essage) = 0;
// ----------------------------------------------------------------------
/** @brief Called as a request to write a specific error message
/**
* @brief Called as a request to write a specific error message
* @param message Error message. Never longer than
* MAX_LOG_MESSAGE_LENGTH characters (exluding the '0').
* @note The message string is only valid until the scope of
......@@ -202,66 +209,94 @@ protected:
virtual void OnError(const char* message) = 0;
protected:
//! Logger severity
LogSeverity m_Severity;
};
// ----------------------------------------------------------------------------------
// Default constructor
inline Logger::Logger() {
inline
Logger::Logger() {
setLogSeverity(NORMAL);
}
// ----------------------------------------------------------------------------------
// Virtual destructor
inline Logger::~Logger()
{
inline
Logger::~Logger() {
// empty
}
// ----------------------------------------------------------------------------------
// Construction with given logging severity
inline Logger::Logger(LogSeverity severity) {
inline
Logger::Logger(LogSeverity severity) {
setLogSeverity(severity);
}
// ----------------------------------------------------------------------------------
// Log severity setter
inline void Logger::setLogSeverity(LogSeverity log_severity){
inline
void Logger::setLogSeverity(LogSeverity log_severity){
m_Severity = log_severity;
}
// ----------------------------------------------------------------------------------
// Log severity getter
inline Logger::LogSeverity Logger::getLogSeverity() const {
inline
Logger::LogSeverity Logger::getLogSeverity() const {
return m_Severity;
}
// ----------------------------------------------------------------------------------
inline void Logger::debug(const std::string &message)
{
inline
void Logger::debug(const std::string &message) {
return debug(message.c_str());
}
// ----------------------------------------------------------------------------------
inline void Logger::error(const std::string &message)
{
inline
void Logger::error(const std::string &message) {
return error(message.c_str());
}
// ----------------------------------------------------------------------------------
inline void Logger::warn(const std::string &message)
{
inline
void Logger::warn(const std::string &message) {
return warn(message.c_str());
}
// ----------------------------------------------------------------------------------
inline void Logger::info(const std::string &message)
{
inline
void Logger::info(const std::string &message) {
return info(message.c_str());
}
// ----------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
#define ASSIMP_LOG_WARN_F(string,...)\
DefaultLogger::get()->warn((Formatter::format(string),__VA_ARGS__))
#define ASSIMP_LOG_ERROR_F(string,...)\
DefaultLogger::get()->error((Formatter::format(string),__VA_ARGS__))
#define ASSIMP_LOG_DEBUG_F(string,...)\
DefaultLogger::get()->debug((Formatter::format(string),__VA_ARGS__))
#define ASSIMP_LOG_INFO_F(string,...)\
DefaultLogger::get()->info((Formatter::format(string),__VA_ARGS__))
#define ASSIMP_LOG_WARN(string)\
DefaultLogger::get()->warn(string)
#define ASSIMP_LOG_ERROR(string)\
DefaultLogger::get()->error(string)
#define ASSIMP_LOG_DEBUG(string)\
DefaultLogger::get()->debug(string)
#define ASSIMP_LOG_INFO(string)\
DefaultLogger::get()->info(string)
} // Namespace Assimp
......
/*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2012, 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.
---------------------------------------------------------------------------
*/
/* Helper macro to set a pointer to NULL in debug builds
*/
#if (defined ASSIMP_BUILD_DEBUG)
# define AI_DEBUG_INVALIDATE_PTR(x) x = NULL;
#else
# define AI_DEBUG_INVALIDATE_PTR(x)
#endif
/*
---------------------------------------------------------------------------
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.
---------------------------------------------------------------------------
*/
/** @file MathFunctions.h
* @brief Implementation of the math functions (gcd and lcm)
*
* Copied from BoostWorkaround/math
*/
namespace Assimp {
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;
}
}
}
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2018, 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.
----------------------------------------------------------------------
*/
/** @file MemoryIOWrapper.h
* Handy IOStream/IOSystem implemetation to read directly from a memory buffer */
#ifndef AI_MEMORYIOSTREAM_H_INC
#define AI_MEMORYIOSTREAM_H_INC
#include <assimp/IOStream.hpp>
#include <assimp/IOSystem.hpp>
#include <assimp/ai_assert.h>
#include <stdint.h>
namespace Assimp {
#define AI_MEMORYIO_MAGIC_FILENAME "$$$___magic___$$$"
#define AI_MEMORYIO_MAGIC_FILENAME_LENGTH 17
// ----------------------------------------------------------------------------------
/** Implementation of IOStream to read directly from a memory buffer */
// ----------------------------------------------------------------------------------
class MemoryIOStream : public IOStream
{
//friend class MemoryIOSystem;
public:
MemoryIOStream (const uint8_t* buff, size_t len, bool own = false)
: buffer (buff)
, length(len)
, pos((size_t)0)
, own(own)
{
}
public:
~MemoryIOStream () {
if(own) {
delete[] buffer;
}
}
// -------------------------------------------------------------------
// Read from stream
size_t Read(void* pvBuffer, size_t pSize, size_t pCount) {
const size_t cnt = std::min(pCount,(length-pos)/pSize),ofs = pSize*cnt;
memcpy(pvBuffer,buffer+pos,ofs);
pos += ofs;
return cnt;
}
// -------------------------------------------------------------------
// Write to stream
size_t Write(const void* /*pvBuffer*/, size_t /*pSize*/,size_t /*pCount*/) {
ai_assert(false); // won't be needed
return 0;
}
// -------------------------------------------------------------------
// Seek specific position
aiReturn Seek(size_t pOffset, aiOrigin pOrigin) {
if (aiOrigin_SET == pOrigin) {
if (pOffset > length) {
return AI_FAILURE;
}
pos = pOffset;
}
else if (aiOrigin_END == pOrigin) {
if (pOffset > length) {
return AI_FAILURE;
}
pos = length-pOffset;
}
else {
if (pOffset+pos > length) {
return AI_FAILURE;
}
pos += pOffset;
}
return AI_SUCCESS;
}
// -------------------------------------------------------------------
// Get current seek position
size_t Tell() const {
return pos;
}
// -------------------------------------------------------------------
// Get size of file
size_t FileSize() const {
return length;
}
// -------------------------------------------------------------------
// Flush file contents
void Flush() {
ai_assert(false); // won't be needed
}
private:
const uint8_t* buffer;
size_t length,pos;
bool own;
};
// ---------------------------------------------------------------------------
/** Dummy IO system to read from a memory buffer */
class MemoryIOSystem : public IOSystem
{
public:
/** Constructor. */
MemoryIOSystem (const uint8_t* buff, size_t len)
: buffer (buff), length(len) {
}
/** Destructor. */
~MemoryIOSystem() {
}
// -------------------------------------------------------------------
/** Tests for the existence of a file at the given path. */
bool Exists( const char* pFile) const {
return !strncmp(pFile,AI_MEMORYIO_MAGIC_FILENAME,AI_MEMORYIO_MAGIC_FILENAME_LENGTH);
}
// -------------------------------------------------------------------
/** Returns the directory separator. */
char getOsSeparator() const {
return '/'; // why not? it doesn't care
}
// -------------------------------------------------------------------
/** Open a new file with a given path. */
IOStream* Open( const char* pFile, const char* /*pMode*/ = "rb") {
if (strncmp(pFile,AI_MEMORYIO_MAGIC_FILENAME,AI_MEMORYIO_MAGIC_FILENAME_LENGTH)) {
return NULL;
}
return new MemoryIOStream(buffer,length);
}
// -------------------------------------------------------------------
/** Closes the given file and releases all resources associated with it. */
void Close( IOStream* pFile) {
delete pFile;
}
// -------------------------------------------------------------------
/** Compare two paths */
bool ComparePaths (const char* /*one*/, const char* /*second*/) const {
return false;
}
private:
const uint8_t* buffer;
size_t length;
};
} // end namespace Assimp
#endif
......@@ -2,7 +2,8 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2017, assimp team
Copyright (c) 2006-2018, assimp team
All rights reserved.
......
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2018, 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.
----------------------------------------------------------------------
*/
/** @file ParsingUtils.h
* @brief Defines helper functions for text parsing
*/
#ifndef AI_PARSING_UTILS_H_INC
#define AI_PARSING_UTILS_H_INC
#include "StringComparison.h"
#include "StringUtils.h"
#include <assimp/defs.h>
namespace Assimp {
// NOTE: the functions below are mostly intended as replacement for
// std::upper, std::lower, std::isupper, std::islower, std::isspace.
// we don't bother of locales. We don't want them. We want reliable
// (i.e. identical) results across all locales.
// The functions below accept any character type, but know only
// about ASCII. However, UTF-32 is the only safe ASCII superset to
// use since it doesn't have multi-byte sequences.
static const unsigned int BufferSize = 4096;
// ---------------------------------------------------------------------------------
template <class char_t>
AI_FORCE_INLINE
char_t ToLower( char_t in ) {
return (in >= (char_t)'A' && in <= (char_t)'Z') ? (char_t)(in+0x20) : in;
}
// ---------------------------------------------------------------------------------
template <class char_t>
AI_FORCE_INLINE
char_t ToUpper( char_t in) {
return (in >= (char_t)'a' && in <= (char_t)'z') ? (char_t)(in-0x20) : in;
}
// ---------------------------------------------------------------------------------
template <class char_t>
AI_FORCE_INLINE
bool IsUpper( char_t in) {
return (in >= (char_t)'A' && in <= (char_t)'Z');
}
// ---------------------------------------------------------------------------------
template <class char_t>
AI_FORCE_INLINE
bool IsLower( char_t in) {
return (in >= (char_t)'a' && in <= (char_t)'z');
}
// ---------------------------------------------------------------------------------
template <class char_t>
AI_FORCE_INLINE
bool IsSpace( char_t in) {
return (in == (char_t)' ' || in == (char_t)'\t');
}
// ---------------------------------------------------------------------------------
template <class char_t>
AI_FORCE_INLINE
bool IsLineEnd( char_t in) {
return (in==(char_t)'\r'||in==(char_t)'\n'||in==(char_t)'\0'||in==(char_t)'\f');
}
// ---------------------------------------------------------------------------------
template <class char_t>
AI_FORCE_INLINE
bool IsSpaceOrNewLine( char_t in) {
return IsSpace<char_t>(in) || IsLineEnd<char_t>(in);
}
// ---------------------------------------------------------------------------------
template <class char_t>
AI_FORCE_INLINE
bool SkipSpaces( const char_t* in, const char_t** out) {
while( *in == ( char_t )' ' || *in == ( char_t )'\t' ) {
++in;
}
*out = in;
return !IsLineEnd<char_t>(*in);
}
// ---------------------------------------------------------------------------------
template <class char_t>
AI_FORCE_INLINE
bool SkipSpaces( const char_t** inout) {
return SkipSpaces<char_t>(*inout,inout);
}
// ---------------------------------------------------------------------------------
template <class char_t>
AI_FORCE_INLINE
bool SkipLine( const char_t* in, const char_t** out) {
while( *in != ( char_t )'\r' && *in != ( char_t )'\n' && *in != ( char_t )'\0' ) {
++in;
}
// files are opened in binary mode. Ergo there are both NL and CR
while( *in == ( char_t )'\r' || *in == ( char_t )'\n' ) {
++in;
}
*out = in;
return *in != (char_t)'\0';
}
// ---------------------------------------------------------------------------------
template <class char_t>
AI_FORCE_INLINE
bool SkipLine( const char_t** inout) {
return SkipLine<char_t>(*inout,inout);
}
// ---------------------------------------------------------------------------------
template <class char_t>
AI_FORCE_INLINE
bool SkipSpacesAndLineEnd( const char_t* in, const char_t** out) {
while( *in == ( char_t )' ' || *in == ( char_t )'\t' || *in == ( char_t )'\r' || *in == ( char_t )'\n' ) {
++in;
}
*out = in;
return *in != '\0';
}
// ---------------------------------------------------------------------------------
template <class char_t>
AI_FORCE_INLINE
bool SkipSpacesAndLineEnd( const char_t** inout) {
return SkipSpacesAndLineEnd<char_t>(*inout,inout);
}
// ---------------------------------------------------------------------------------
template <class char_t>
AI_FORCE_INLINE
bool GetNextLine( const char_t*& buffer, char_t out[ BufferSize ] ) {
if( ( char_t )'\0' == *buffer ) {
return false;
}
char* _out = out;
char* const end = _out + BufferSize;
while( !IsLineEnd( *buffer ) && _out < end ) {
*_out++ = *buffer++;
}
*_out = (char_t)'\0';
while( IsLineEnd( *buffer ) && '\0' != *buffer ) {
++buffer;
}
return true;
}
// ---------------------------------------------------------------------------------
template <class char_t>
AI_FORCE_INLINE bool IsNumeric( char_t in)
{
return ( in >= '0' && in <= '9' ) || '-' == in || '+' == in;
}
// ---------------------------------------------------------------------------------
template <class char_t>
AI_FORCE_INLINE
bool TokenMatch(char_t*& in, const char* token, unsigned int len)
{
if (!::strncmp(token,in,len) && IsSpaceOrNewLine(in[len])) {
if (in[len] != '\0') {
in += len+1;
} else {
// If EOF after the token make sure we don't go past end of buffer
in += len;
}
return true;
}
return false;
}
// ---------------------------------------------------------------------------------
/** @brief Case-ignoring version of TokenMatch
* @param in Input
* @param token Token to check for
* @param len Number of characters to check
*/
AI_FORCE_INLINE
bool TokenMatchI(const char*& in, const char* token, unsigned int len) {
if (!ASSIMP_strincmp(token,in,len) && IsSpaceOrNewLine(in[len])) {
in += len+1;
return true;
}
return false;
}
// ---------------------------------------------------------------------------------
AI_FORCE_INLINE
void SkipToken(const char*& in) {
SkipSpaces(&in);
while ( !IsSpaceOrNewLine( *in ) ) {
++in;
}
}
// ---------------------------------------------------------------------------------
AI_FORCE_INLINE
std::string GetNextToken(const char*& in) {
SkipSpacesAndLineEnd(&in);
const char* cur = in;
while ( !IsSpaceOrNewLine( *in ) ) {
++in;
}
return std::string(cur,(size_t)(in-cur));
}
// ---------------------------------------------------------------------------------
} // ! namespace Assimp
#endif // ! AI_PARSING_UTILS_H_INC
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2018, 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.
----------------------------------------------------------------------
*/
/** @file Profiler.h
* @brief Utility to measure the respective runtime of each import step
*/
#ifndef INCLUDED_PROFILER_H
#define INCLUDED_PROFILER_H
#include <chrono>
#include <assimp/DefaultLogger.hpp>
#include "TinyFormatter.h"
#include <map>
namespace Assimp {
namespace Profiling {
using namespace Formatter;
// ------------------------------------------------------------------------------------------------
/** Simple wrapper around boost::timer to simplify reporting. Timings are automatically
* dumped to the log file.
*/
class Profiler {
public:
Profiler() {
// empty
}
public:
/** Start a named timer */
void BeginRegion(const std::string& region) {
regions[region] = std::chrono::system_clock::now();
ASSIMP_LOG_DEBUG((format("START `"),region,"`"));
}
/** End a specific named timer and write its end time to the log */
void EndRegion(const std::string& region) {
RegionMap::const_iterator it = regions.find(region);
if (it == regions.end()) {
return;
}
std::chrono::duration<double> elapsedSeconds = std::chrono::system_clock::now() - regions[region];
ASSIMP_LOG_DEBUG((format("END `"),region,"`, dt= ", elapsedSeconds.count()," s"));
}
private:
typedef std::map<std::string,std::chrono::time_point<std::chrono::system_clock>> RegionMap;
RegionMap regions;
};
}
}
#endif
......@@ -2,7 +2,8 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2017, assimp team
Copyright (c) 2006-2018, assimp team
All rights reserved.
......
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2018, 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.
----------------------------------------------------------------------
*/
/** @file Declares a helper class, "CommentRemover", which can be
* used to remove comments (single and multi line) from a text file.
*/
#ifndef AI_REMOVE_COMMENTS_H_INC
#define AI_REMOVE_COMMENTS_H_INC
#include <assimp/defs.h>
namespace Assimp {
// ---------------------------------------------------------------------------
/** \brief Helper class to remove single and multi line comments from a file
*
* Some mesh formats like MD5 have comments that are quite similar
* to those in C or C++ so this code has been moved to a separate
* module.
*/
class ASSIMP_API CommentRemover
{
// class cannot be instanced
CommentRemover() {}
public:
//! Remove single-line comments. The end of a line is
//! expected to be either NL or CR or NLCR.
//! \param szComment The start sequence of the comment, e.g. "//"
//! \param szBuffer Buffer to work with
//! \param chReplacement Character to be used as replacement
//! for commented lines. By default this is ' '
static void RemoveLineComments(const char* szComment,
char* szBuffer, char chReplacement = ' ');
//! Remove multi-line comments. The end of a line is
//! expected to be either NL or CR or NLCR. Multi-line comments
//! may not be nested (as in C).
//! \param szCommentStart The start sequence of the comment, e.g. "/*"
//! \param szCommentEnd The end sequence of the comment, e.g. "*/"
//! \param szBuffer Buffer to work with
//! \param chReplacement Character to be used as replacement
//! for commented lines. By default this is ' '
static void RemoveMultiLineComments(const char* szCommentStart,
const char* szCommentEnd,char* szBuffer,
char chReplacement = ' ');
};
} // ! Assimp
#endif // !! AI_REMOVE_COMMENTS_H_INC
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2018, 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.
----------------------------------------------------------------------
*/
/** Small helper classes to optimize finding vertices close to a given location
*/
#ifndef AI_D3DSSPATIALSORT_H_INC
#define AI_D3DSSPATIALSORT_H_INC
#include <assimp/types.h>
#include <vector>
#include <stdint.h>
namespace Assimp {
// ----------------------------------------------------------------------------------
/** Specialized version of SpatialSort to support smoothing groups
* This is used in by the 3DS, ASE and LWO loaders. 3DS and ASE share their
* normal computation code in SmoothingGroups.inl, the LWO loader has its own
* implementation to handle all details of its file format correctly.
*/
// ----------------------------------------------------------------------------------
class ASSIMP_API SGSpatialSort
{
public:
SGSpatialSort();
// -------------------------------------------------------------------
/** Construction from a given face array, handling smoothing groups
* properly
*/
explicit SGSpatialSort(const std::vector<aiVector3D>& vPositions);
// -------------------------------------------------------------------
/** Add a vertex to the spatial sort
* @param vPosition Vertex position to be added
* @param index Index of the vrtex
* @param smoothingGroup SmoothingGroup for this vertex
*/
void Add(const aiVector3D& vPosition, unsigned int index,
unsigned int smoothingGroup);
// -------------------------------------------------------------------
/** Prepare the spatial sorter for use. This step runs in O(logn)
*/
void Prepare();
/** Destructor */
~SGSpatialSort();
// -------------------------------------------------------------------
/** Returns an iterator for all positions close to the given position.
* @param pPosition The position to look for vertices.
* @param pSG Only included vertices with at least one shared smooth group
* @param pRadius Maximal distance from the position a vertex may have
* to be counted in.
* @param poResults The container to store the indices of the found
* positions. Will be emptied by the call so it may contain anything.
* @param exactMatch Specifies whether smoothing groups are bit masks
* (false) or integral values (true). In the latter case, a vertex
* cannot belong to more than one smoothing group.
* @return An iterator to iterate over all vertices in the given area.
*/
// -------------------------------------------------------------------
void FindPositions( const aiVector3D& pPosition, uint32_t pSG,
float pRadius, std::vector<unsigned int>& poResults,
bool exactMatch = false) const;
protected:
/** Normal of the sorting plane, normalized. The center is always at (0, 0, 0) */
aiVector3D mPlaneNormal;
// -------------------------------------------------------------------
/** An entry in a spatially sorted position array. Consists of a
* vertex index, its position and its precalculated distance from
* the reference plane */
// -------------------------------------------------------------------
struct Entry
{
unsigned int mIndex; ///< The vertex referred by this entry
aiVector3D mPosition; ///< Position
uint32_t mSmoothGroups;
float mDistance; ///< Distance of this vertex to the sorting plane
Entry() { /** intentionally not initialized.*/ }
Entry( unsigned int pIndex, const aiVector3D& pPosition, float pDistance,uint32_t pSG)
:
mIndex( pIndex),
mPosition( pPosition),
mSmoothGroups (pSG),
mDistance( pDistance)
{ }
bool operator < (const Entry& e) const { return mDistance < e.mDistance; }
};
// all positions, sorted by distance to the sorting plane
std::vector<Entry> mPositions;
};
} // end of namespace Assimp
#endif // AI_SPATIALSORT_H_INC
......@@ -2,7 +2,8 @@
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2017, assimp team
Copyright (c) 2006-2018, assimp team
All rights reserved.
......
/** Helper class to construct a dummy mesh for file formats containing only motion data */
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2018, 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.
----------------------------------------------------------------------
*/
/** @file SkeletonMeshBuilder.h
* Declares SkeletonMeshBuilder, a tiny utility to build dummy meshes
* for animation skeletons.
*/
#ifndef AI_SKELETONMESHBUILDER_H_INC
#define AI_SKELETONMESHBUILDER_H_INC
#include <vector>
#include <assimp/mesh.h>
struct aiMaterial;
struct aiScene;
struct aiNode;
namespace Assimp {
// ---------------------------------------------------------------------------
/**
* This little helper class constructs a dummy mesh for a given scene
* the resembles the node hierarchy. This is useful for file formats
* that don't carry any mesh data but only animation data.
*/
class ASSIMP_API SkeletonMeshBuilder
{
public:
// -------------------------------------------------------------------
/** The constructor processes the given scene and adds a mesh there.
*
* Does nothing if the scene already has mesh data.
* @param pScene The scene for which a skeleton mesh should be constructed.
* @param root The node to start with. NULL is the scene root
* @param bKnobsOnly Set this to true if you don't want the connectors
* between the knobs representing the nodes.
*/
SkeletonMeshBuilder( aiScene* pScene, aiNode* root = NULL,
bool bKnobsOnly = false);
protected:
// -------------------------------------------------------------------
/** Recursively builds a simple mesh representation for the given node
* and also creates a joint for the node that affects this part of
* the mesh.
* @param pNode The node to build geometry for.
*/
void CreateGeometry( const aiNode* pNode);
// -------------------------------------------------------------------
/** Creates the mesh from the internally accumulated stuff and returns it.
*/
aiMesh* CreateMesh();
// -------------------------------------------------------------------
/** Creates a dummy material and returns it. */
aiMaterial* CreateMaterial();
protected:
/** space to assemble the mesh data: points */
std::vector<aiVector3D> mVertices;
/** faces */
struct Face
{
unsigned int mIndices[3];
Face();
Face( unsigned int p0, unsigned int p1, unsigned int p2)
{ mIndices[0] = p0; mIndices[1] = p1; mIndices[2] = p2; }
};
std::vector<Face> mFaces;
/** bones */
std::vector<aiBone*> mBones;
bool mKnobsOnly;
};
} // end of namespace Assimp
#endif // AI_SKELETONMESHBUILDER_H_INC
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2018, 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.
----------------------------------------------------------------------
*/
/** @file Defines the helper data structures for importing 3DS files.
http://www.jalix.org/ressources/graphics/3DS/_unofficials/3ds-unofficial.txt */
#ifndef AI_SMOOTHINGGROUPS_H_INC
#define AI_SMOOTHINGGROUPS_H_INC
#include <assimp/vector3.h>
#include <stdint.h>
#include <vector>
// ---------------------------------------------------------------------------
/** Helper structure representing a face with smoothing groups assigned */
struct FaceWithSmoothingGroup
{
FaceWithSmoothingGroup()
: mIndices(),
iSmoothGroup(0)
{
// in debug builds set all indices to a common magic value
#ifdef ASSIMP_BUILD_DEBUG
this->mIndices[0] = 0xffffffff;
this->mIndices[1] = 0xffffffff;
this->mIndices[2] = 0xffffffff;
#endif
}
//! Indices. .3ds is using uint16. However, after
//! an unique vertex set has been generated,
//! individual index values might exceed 2^16
uint32_t mIndices[3];
//! specifies to which smoothing group the face belongs to
uint32_t iSmoothGroup;
};
// ---------------------------------------------------------------------------
/** Helper structure representing a mesh whose faces have smoothing
groups assigned. This allows us to reuse the code for normal computations
from smoothings groups for several loaders (3DS, ASE). All of them
use face structures which inherit from #FaceWithSmoothingGroup,
but as they add extra members and need to be copied by value we
need to use a template here.
*/
template <class T>
struct MeshWithSmoothingGroups
{
//! Vertex positions
std::vector<aiVector3D> mPositions;
//! Face lists
std::vector<T> mFaces;
//! List of normal vectors
std::vector<aiVector3D> mNormals;
};
// ---------------------------------------------------------------------------
/** Computes normal vectors for the mesh
*/
template <class T>
void ComputeNormalsWithSmoothingsGroups(MeshWithSmoothingGroups<T>& sMesh);
// include implementations
#include "SmoothingGroups.inl"
#endif // !! AI_SMOOTHINGGROUPS_H_INC
/*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2012, 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.
---------------------------------------------------------------------------
*/
/** @file Generation of normal vectors basing on smoothing groups */
#ifndef AI_SMOOTHINGGROUPS_INL_INCLUDED
#define AI_SMOOTHINGGROUPS_INL_INCLUDED
// internal headers
#include <assimp/SGSpatialSort.h>
// CRT header
#include <algorithm>
using namespace Assimp;
// ------------------------------------------------------------------------------------------------
template <class T>
void ComputeNormalsWithSmoothingsGroups(MeshWithSmoothingGroups<T>& sMesh)
{
// First generate face normals
sMesh.mNormals.resize(sMesh.mPositions.size(),aiVector3D());
for( unsigned int a = 0; a < sMesh.mFaces.size(); a++)
{
T& face = sMesh.mFaces[a];
aiVector3D* pV1 = &sMesh.mPositions[face.mIndices[0]];
aiVector3D* pV2 = &sMesh.mPositions[face.mIndices[1]];
aiVector3D* pV3 = &sMesh.mPositions[face.mIndices[2]];
aiVector3D pDelta1 = *pV2 - *pV1;
aiVector3D pDelta2 = *pV3 - *pV1;
aiVector3D vNor = pDelta1 ^ pDelta2;
for (unsigned int c = 0; c < 3;++c)
sMesh.mNormals[face.mIndices[c]] = vNor;
}
// calculate the position bounds so we have a reliable epsilon to check position differences against
aiVector3D minVec( 1e10f, 1e10f, 1e10f), maxVec( -1e10f, -1e10f, -1e10f);
for( unsigned int a = 0; a < sMesh.mPositions.size(); a++)
{
minVec.x = std::min( minVec.x, sMesh.mPositions[a].x);
minVec.y = std::min( minVec.y, sMesh.mPositions[a].y);
minVec.z = std::min( minVec.z, sMesh.mPositions[a].z);
maxVec.x = std::max( maxVec.x, sMesh.mPositions[a].x);
maxVec.y = std::max( maxVec.y, sMesh.mPositions[a].y);
maxVec.z = std::max( maxVec.z, sMesh.mPositions[a].z);
}
const float posEpsilon = (maxVec - minVec).Length() * 1e-5f;
std::vector<aiVector3D> avNormals;
avNormals.resize(sMesh.mNormals.size());
// now generate the spatial sort tree
SGSpatialSort sSort;
for( typename std::vector<T>::iterator i = sMesh.mFaces.begin();
i != sMesh.mFaces.end();++i)
{
for (unsigned int c = 0; c < 3;++c)
sSort.Add(sMesh.mPositions[(*i).mIndices[c]],(*i).mIndices[c],(*i).iSmoothGroup);
}
sSort.Prepare();
std::vector<bool> vertexDone(sMesh.mPositions.size(),false);
for( typename std::vector<T>::iterator i = sMesh.mFaces.begin();
i != sMesh.mFaces.end();++i)
{
std::vector<unsigned int> poResult;
for (unsigned int c = 0; c < 3;++c)
{
unsigned int idx = (*i).mIndices[c];
if (vertexDone[idx])continue;
sSort.FindPositions(sMesh.mPositions[idx],(*i).iSmoothGroup,
posEpsilon,poResult);
aiVector3D vNormals;
for (std::vector<unsigned int>::const_iterator
a = poResult.begin();
a != poResult.end();++a)
{
vNormals += sMesh.mNormals[(*a)];
}
vNormals.NormalizeSafe();
// write back into all affected normals
for (std::vector<unsigned int>::const_iterator
a = poResult.begin();
a != poResult.end();++a)
{
idx = *a;
avNormals [idx] = vNormals;
vertexDone[idx] = true;
}
}
}
sMesh.mNormals = avNormals;
}
#endif // !! AI_SMOOTHINGGROUPS_INL_INCLUDED
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2018, 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.
----------------------------------------------------------------------
*/
/** Small helper classes to optimise finding vertizes close to a given location */
#ifndef AI_SPATIALSORT_H_INC
#define AI_SPATIALSORT_H_INC
#include <vector>
#include <assimp/types.h>
namespace Assimp {
// ------------------------------------------------------------------------------------------------
/** A little helper class to quickly find all vertices in the epsilon environment of a given
* position. Construct an instance with an array of positions. The class stores the given positions
* by their indices and sorts them by their distance to an arbitrary chosen plane.
* You can then query the instance for all vertices close to a given position in an average O(log n)
* time, with O(n) worst case complexity when all vertices lay on the plane. The plane is chosen
* so that it avoids common planes in usual data sets. */
// ------------------------------------------------------------------------------------------------
class ASSIMP_API SpatialSort
{
public:
SpatialSort();
// ------------------------------------------------------------------------------------
/** Constructs a spatially sorted representation from the given position array.
* Supply the positions in its layout in memory, the class will only refer to them
* by index.
* @param pPositions Pointer to the first position vector of the array.
* @param pNumPositions Number of vectors to expect in that array.
* @param pElementOffset Offset in bytes from the beginning of one vector in memory
* to the beginning of the next vector. */
SpatialSort( const aiVector3D* pPositions, unsigned int pNumPositions,
unsigned int pElementOffset);
/** Destructor */
~SpatialSort();
public:
// ------------------------------------------------------------------------------------
/** Sets the input data for the SpatialSort. This replaces existing data, if any.
* The new data receives new indices in ascending order.
*
* @param pPositions Pointer to the first position vector of the array.
* @param pNumPositions Number of vectors to expect in that array.
* @param pElementOffset Offset in bytes from the beginning of one vector in memory
* to the beginning of the next vector.
* @param pFinalize Specifies whether the SpatialSort's internal representation
* is finalized after the new data has been added. Finalization is
* required in order to use #FindPosition() or #GenerateMappingTable().
* If you don't finalize yet, you can use #Append() to add data from
* other sources.*/
void Fill( const aiVector3D* pPositions, unsigned int pNumPositions,
unsigned int pElementOffset,
bool pFinalize = true);
// ------------------------------------------------------------------------------------
/** Same as #Fill(), except the method appends to existing data in the #SpatialSort. */
void Append( const aiVector3D* pPositions, unsigned int pNumPositions,
unsigned int pElementOffset,
bool pFinalize = true);
// ------------------------------------------------------------------------------------
/** Finalize the spatial hash data structure. This can be useful after
* multiple calls to #Append() with the pFinalize parameter set to false.
* This is finally required before one of #FindPositions() and #GenerateMappingTable()
* can be called to query the spatial sort.*/
void Finalize();
// ------------------------------------------------------------------------------------
/** Returns an iterator for all positions close to the given position.
* @param pPosition The position to look for vertices.
* @param pRadius Maximal distance from the position a vertex may have to be counted in.
* @param poResults The container to store the indices of the found positions.
* Will be emptied by the call so it may contain anything.
* @return An iterator to iterate over all vertices in the given area.*/
void FindPositions( const aiVector3D& pPosition, ai_real pRadius,
std::vector<unsigned int>& poResults) const;
// ------------------------------------------------------------------------------------
/** Fills an array with indices of all positions identical to the given position. In
* opposite to FindPositions(), not an epsilon is used but a (very low) tolerance of
* four floating-point units.
* @param pPosition The position to look for vertices.
* @param poResults The container to store the indices of the found positions.
* Will be emptied by the call so it may contain anything.*/
void FindIdenticalPositions( const aiVector3D& pPosition,
std::vector<unsigned int>& poResults) const;
// ------------------------------------------------------------------------------------
/** Compute a table that maps each vertex ID referring to a spatially close
* enough position to the same output ID. Output IDs are assigned in ascending order
* from 0...n.
* @param fill Will be filled with numPositions entries.
* @param pRadius Maximal distance from the position a vertex may have to
* be counted in.
* @return Number of unique vertices (n). */
unsigned int GenerateMappingTable(std::vector<unsigned int>& fill,
ai_real pRadius) const;
protected:
/** Normal of the sorting plane, normalized. The center is always at (0, 0, 0) */
aiVector3D mPlaneNormal;
/** An entry in a spatially sorted position array. Consists of a vertex index,
* its position and its pre-calculated distance from the reference plane */
struct Entry {
unsigned int mIndex; ///< The vertex referred by this entry
aiVector3D mPosition; ///< Position
ai_real mDistance; ///< Distance of this vertex to the sorting plane
Entry()
: mIndex( 999999999 ), mPosition(), mDistance( 99999. ) {
// empty
}
Entry( unsigned int pIndex, const aiVector3D& pPosition, ai_real pDistance)
: mIndex( pIndex), mPosition( pPosition), mDistance( pDistance) {
// empty
}
bool operator < (const Entry& e) const { return mDistance < e.mDistance; }
};
// all positions, sorted by distance to the sorting plane
std::vector<Entry> mPositions;
};
} // end of namespace Assimp
#endif // AI_SPATIALSORT_H_INC
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2018, 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.
----------------------------------------------------------------------
*/
/** @file Declares a helper class, "StandardShapes" which generates
* vertices for standard shapes, such as cylnders, cones, spheres ..
*/
#ifndef AI_STANDARD_SHAPES_H_INC
#define AI_STANDARD_SHAPES_H_INC
#include <assimp/vector3.h>
#include <vector>
struct aiMesh;
namespace Assimp {
// ---------------------------------------------------------------------------
/** \brief Helper class to generate vertex buffers for standard geometric
* shapes, such as cylinders, cones, boxes, spheres, elipsoids ... .
*/
class ASSIMP_API StandardShapes
{
// class cannot be instanced
StandardShapes() {}
public:
// ----------------------------------------------------------------
/** Generates a mesh from an array of vertex positions.
*
* @param positions List of vertex positions
* @param numIndices Number of indices per primitive
* @return Output mesh
*/
static aiMesh* MakeMesh(const std::vector<aiVector3D>& positions,
unsigned int numIndices);
static aiMesh* MakeMesh ( unsigned int (*GenerateFunc)
(std::vector<aiVector3D>&));
static aiMesh* MakeMesh ( unsigned int (*GenerateFunc)
(std::vector<aiVector3D>&, bool));
static aiMesh* MakeMesh ( unsigned int n, void (*GenerateFunc)
(unsigned int,std::vector<aiVector3D>&));
// ----------------------------------------------------------------
/** @brief Generates a hexahedron (cube)
*
* Hexahedrons can be scaled on all axes.
* @param positions Receives output triangles.
* @param polygons If you pass true here quads will be returned
* @return Number of vertices per face
*/
static unsigned int MakeHexahedron(
std::vector<aiVector3D>& positions,
bool polygons = false);
// ----------------------------------------------------------------
/** @brief Generates an icosahedron
*
* @param positions Receives output triangles.
* @return Number of vertices per face
*/
static unsigned int MakeIcosahedron(
std::vector<aiVector3D>& positions);
// ----------------------------------------------------------------
/** @brief Generates a dodecahedron
*
* @param positions Receives output triangles
* @param polygons If you pass true here pentagons will be returned
* @return Number of vertices per face
*/
static unsigned int MakeDodecahedron(
std::vector<aiVector3D>& positions,
bool polygons = false);
// ----------------------------------------------------------------
/** @brief Generates an octahedron
*
* @param positions Receives output triangles.
* @return Number of vertices per face
*/
static unsigned int MakeOctahedron(
std::vector<aiVector3D>& positions);
// ----------------------------------------------------------------
/** @brief Generates a tetrahedron
*
* @param positions Receives output triangles.
* @return Number of vertices per face
*/
static unsigned int MakeTetrahedron(
std::vector<aiVector3D>& positions);
// ----------------------------------------------------------------
/** @brief Generates a sphere
*
* @param tess Number of subdivions - 0 generates a octahedron
* @param positions Receives output triangles.
*/
static void MakeSphere(unsigned int tess,
std::vector<aiVector3D>& positions);
// ----------------------------------------------------------------
/** @brief Generates a cone or a cylinder, either open or closed.
*
* @code
*
* |-----| <- radius 1
*
* __x__ <- ] ^
* / \ | height |
* / \ | Y
* / \ |
* / \ |
* /______x______\ <- ] <- end cap
*
* |-------------| <- radius 2
*
* @endcode
*
* @param height Height of the cone
* @param radius1 First radius
* @param radius2 Second radius
* @param tess Number of triangles.
* @param bOpened true for an open cone/cylinder. An open shape has
* no 'end caps'
* @param positions Receives output triangles
*/
static void MakeCone(ai_real height,ai_real radius1,
ai_real radius2,unsigned int tess,
std::vector<aiVector3D>& positions,bool bOpen= false);
// ----------------------------------------------------------------
/** @brief Generates a flat circle
*
* The circle is constructed in the planned formed by the x,z
* axes of the cartesian coordinate system.
*
* @param radius Radius of the circle
* @param tess Number of segments.
* @param positions Receives output triangles.
*/
static void MakeCircle(ai_real radius, unsigned int tess,
std::vector<aiVector3D>& positions);
};
} // ! Assimp
#endif // !! AI_STANDARD_SHAPES_H_INC
/*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2018, 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.
---------------------------------------------------------------------------
*/
/** @file Defines the StreamReader class which reads data from
* a binary stream with a well-defined endianness.
*/
#ifndef AI_STREAMREADER_H_INCLUDED
#define AI_STREAMREADER_H_INCLUDED
#include "ByteSwapper.h"
#include "Exceptional.h"
#include <memory>
#include <assimp/IOStream.hpp>
#include <assimp/Defines.h>
namespace Assimp {
// --------------------------------------------------------------------------------------------
/** Wrapper class around IOStream to allow for consistent reading of binary data in both
* little and big endian format. Don't attempt to instance the template directly. Use
* StreamReaderLE to read from a little-endian stream and StreamReaderBE to read from a
* BE stream. The class expects that the endianness of any input data is known at
* compile-time, which should usually be true (#BaseImporter::ConvertToUTF8 implements
* runtime endianness conversions for text files).
*
* XXX switch from unsigned int for size types to size_t? or ptrdiff_t?*/
// --------------------------------------------------------------------------------------------
template <bool SwapEndianess = false, bool RuntimeSwitch = false>
class StreamReader
{
public:
// FIXME: use these data types throughout the whole library,
// then change them to 64 bit values :-)
typedef int diff;
typedef unsigned int pos;
public:
// ---------------------------------------------------------------------
/** Construction from a given stream with a well-defined endianness.
*
* The StreamReader holds a permanent strong reference to the
* stream, which is released upon destruction.
* @param stream Input stream. The stream is not restarted if
* its file pointer is not at 0. Instead, the stream reader
* reads from the current position to the end of the stream.
* @param le If @c RuntimeSwitch is true: specifies whether the
* stream is in little endian byte order. Otherwise the
* endianness information is contained in the @c SwapEndianess
* template parameter and this parameter is meaningless. */
StreamReader(std::shared_ptr<IOStream> stream, bool le = false)
: stream(stream)
, le(le)
{
ai_assert(stream);
InternBegin();
}
// ---------------------------------------------------------------------
StreamReader(IOStream* stream, bool le = false)
: stream(std::shared_ptr<IOStream>(stream))
, le(le)
{
ai_assert(stream);
InternBegin();
}
// ---------------------------------------------------------------------
~StreamReader() {
delete[] buffer;
}
public:
// deprecated, use overloaded operator>> instead
// ---------------------------------------------------------------------
/** Read a float from the stream */
float GetF4()
{
return Get<float>();
}
// ---------------------------------------------------------------------
/** Read a double from the stream */
double GetF8() {
return Get<double>();
}
// ---------------------------------------------------------------------
/** Read a signed 16 bit integer from the stream */
int16_t GetI2() {
return Get<int16_t>();
}
// ---------------------------------------------------------------------
/** Read a signed 8 bit integer from the stream */
int8_t GetI1() {
return Get<int8_t>();
}
// ---------------------------------------------------------------------
/** Read an signed 32 bit integer from the stream */
int32_t GetI4() {
return Get<int32_t>();
}
// ---------------------------------------------------------------------
/** Read a signed 64 bit integer from the stream */
int64_t GetI8() {
return Get<int64_t>();
}
// ---------------------------------------------------------------------
/** Read a unsigned 16 bit integer from the stream */
uint16_t GetU2() {
return Get<uint16_t>();
}
// ---------------------------------------------------------------------
/** Read a unsigned 8 bit integer from the stream */
uint8_t GetU1() {
return Get<uint8_t>();
}
// ---------------------------------------------------------------------
/** Read an unsigned 32 bit integer from the stream */
uint32_t GetU4() {
return Get<uint32_t>();
}
// ---------------------------------------------------------------------
/** Read a unsigned 64 bit integer from the stream */
uint64_t GetU8() {
return Get<uint64_t>();
}
public:
// ---------------------------------------------------------------------
/** Get the remaining stream size (to the end of the stream) */
unsigned int GetRemainingSize() const {
return (unsigned int)(end - current);
}
// ---------------------------------------------------------------------
/** Get the remaining stream size (to the current read limit). The
* return value is the remaining size of the stream if no custom
* read limit has been set. */
unsigned int GetRemainingSizeToLimit() const {
return (unsigned int)(limit - current);
}
// ---------------------------------------------------------------------
/** Increase the file pointer (relative seeking) */
void IncPtr(intptr_t plus) {
current += plus;
if (current > limit) {
throw DeadlyImportError("End of file or read limit was reached");
}
}
// ---------------------------------------------------------------------
/** Get the current file pointer */
int8_t* GetPtr() const {
return current;
}
// ---------------------------------------------------------------------
/** Set current file pointer (Get it from #GetPtr). This is if you
* prefer to do pointer arithmetics on your own or want to copy
* large chunks of data at once.
* @param p The new pointer, which is validated against the size
* limit and buffer boundaries. */
void SetPtr(int8_t* p) {
current = p;
if (current > limit || current < buffer) {
throw DeadlyImportError("End of file or read limit was reached");
}
}
// ---------------------------------------------------------------------
/** Copy n bytes to an external buffer
* @param out Destination for copying
* @param bytes Number of bytes to copy */
void CopyAndAdvance(void* out, size_t bytes) {
int8_t* ur = GetPtr();
SetPtr(ur+bytes); // fire exception if eof
::memcpy(out,ur,bytes);
}
// ---------------------------------------------------------------------
/** Get the current offset from the beginning of the file */
int GetCurrentPos() const {
return (unsigned int)(current - buffer);
}
void SetCurrentPos(size_t pos) {
SetPtr(buffer + pos);
}
// ---------------------------------------------------------------------
/** Setup a temporary read limit
*
* @param limit Maximum number of bytes to be read from
* the beginning of the file. Specifying UINT_MAX
* resets the limit to the original end of the stream.
* Returns the previously set limit. */
unsigned int SetReadLimit(unsigned int _limit) {
unsigned int prev = GetReadLimit();
if (UINT_MAX == _limit) {
limit = end;
return prev;
}
limit = buffer + _limit;
if (limit > end) {
throw DeadlyImportError("StreamReader: Invalid read limit");
}
return prev;
}
// ---------------------------------------------------------------------
/** Get the current read limit in bytes. Reading over this limit
* accidentally raises an exception. */
unsigned int GetReadLimit() const {
return (unsigned int)(limit - buffer);
}
// ---------------------------------------------------------------------
/** Skip to the read limit in bytes. Reading over this limit
* accidentally raises an exception. */
void SkipToReadLimit() {
current = limit;
}
// ---------------------------------------------------------------------
/** overload operator>> and allow chaining of >> ops. */
template <typename T>
StreamReader& operator >> (T& f) {
f = Get<T>();
return *this;
}
// ---------------------------------------------------------------------
/** Generic read method. ByteSwap::Swap(T*) *must* be defined */
template <typename T>
T Get() {
if ( current + sizeof(T) > limit) {
throw DeadlyImportError("End of file or stream limit was reached");
}
T f;
::memcpy (&f, current, sizeof(T));
Intern::Getter<SwapEndianess,T,RuntimeSwitch>() (&f,le);
current += sizeof(T);
return f;
}
private:
// ---------------------------------------------------------------------
void InternBegin() {
if (!stream) {
// in case someone wonders: StreamReader is frequently invoked with
// no prior validation whether the input stream is valid. Since
// no one bothers changing the error message, this message here
// is passed down to the caller and 'unable to open file'
// simply describes best what happened.
throw DeadlyImportError("StreamReader: Unable to open file");
}
const size_t s = stream->FileSize() - stream->Tell();
if (!s) {
throw DeadlyImportError("StreamReader: File is empty or EOF is already reached");
}
current = buffer = new int8_t[s];
const size_t read = stream->Read(current,1,s);
// (read < s) can only happen if the stream was opened in text mode, in which case FileSize() is not reliable
ai_assert(read <= s);
end = limit = &buffer[read];
}
private:
std::shared_ptr<IOStream> stream;
int8_t *buffer, *current, *end, *limit;
bool le;
};
// --------------------------------------------------------------------------------------------
// `static` StreamReaders. Their byte order is fixed and they might be a little bit faster.
#ifdef AI_BUILD_BIG_ENDIAN
typedef StreamReader<true> StreamReaderLE;
typedef StreamReader<false> StreamReaderBE;
#else
typedef StreamReader<true> StreamReaderBE;
typedef StreamReader<false> StreamReaderLE;
#endif
// `dynamic` StreamReader. The byte order of the input data is specified in the
// c'tor. This involves runtime branching and might be a little bit slower.
typedef StreamReader<true,true> StreamReaderAny;
} // end namespace Assimp
#endif // !! AI_STREAMREADER_H_INCLUDED
This diff is collapsed.
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment