Importer.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2012, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file Importer.cpp
  35. * @brief Implementation of the CPP-API class #Importer
  36. */
  37. #include "AssimpPCH.h"
  38. #include "../include/assimp/version.h"
  39. // ------------------------------------------------------------------------------------------------
  40. /* Uncomment this line to prevent Assimp from catching unknown exceptions.
  41. *
  42. * Note that any Exception except DeadlyImportError may lead to
  43. * undefined behaviour -> loaders could remain in an unusable state and
  44. * further imports with the same Importer instance could fail/crash/burn ...
  45. */
  46. // ------------------------------------------------------------------------------------------------
  47. #ifndef ASSIMP_BUILD_DEBUG
  48. # define ASSIMP_CATCH_GLOBAL_EXCEPTIONS
  49. #endif
  50. // ------------------------------------------------------------------------------------------------
  51. // Internal headers
  52. // ------------------------------------------------------------------------------------------------
  53. #include "Importer.h"
  54. #include "BaseProcess.h"
  55. #include "DefaultIOStream.h"
  56. #include "DefaultIOSystem.h"
  57. #include "DefaultProgressHandler.h"
  58. #include "GenericProperty.h"
  59. #include "ProcessHelper.h"
  60. #include "ScenePreprocessor.h"
  61. #include "MemoryIOWrapper.h"
  62. #include "Profiler.h"
  63. #include "TinyFormatter.h"
  64. #ifndef ASSIMP_BUILD_NO_VALIDATEDS_PROCESS
  65. # include "ValidateDataStructure.h"
  66. #endif
  67. using namespace Assimp::Profiling;
  68. using namespace Assimp::Formatter;
  69. namespace Assimp {
  70. // ImporterRegistry.cpp
  71. void GetImporterInstanceList(std::vector< BaseImporter* >& out);
  72. // PostStepRegistry.cpp
  73. void GetPostProcessingStepInstanceList(std::vector< BaseProcess* >& out);
  74. }
  75. using namespace Assimp;
  76. using namespace Assimp::Intern;
  77. // ------------------------------------------------------------------------------------------------
  78. // Intern::AllocateFromAssimpHeap serves as abstract base class. It overrides
  79. // new and delete (and their array counterparts) of public API classes (e.g. Logger) to
  80. // utilize our DLL heap.
  81. // See http://www.gotw.ca/publications/mill15.htm
  82. // ------------------------------------------------------------------------------------------------
  83. void* AllocateFromAssimpHeap::operator new ( size_t num_bytes) {
  84. return ::operator new(num_bytes);
  85. }
  86. void* AllocateFromAssimpHeap::operator new ( size_t num_bytes, const std::nothrow_t& ) throw() {
  87. try {
  88. return AllocateFromAssimpHeap::operator new( num_bytes );
  89. }
  90. catch( ... ) {
  91. return NULL;
  92. }
  93. }
  94. void AllocateFromAssimpHeap::operator delete ( void* data) {
  95. return ::operator delete(data);
  96. }
  97. void* AllocateFromAssimpHeap::operator new[] ( size_t num_bytes) {
  98. return ::operator new[](num_bytes);
  99. }
  100. void* AllocateFromAssimpHeap::operator new[] ( size_t num_bytes, const std::nothrow_t& ) throw() {
  101. try {
  102. return AllocateFromAssimpHeap::operator new[]( num_bytes );
  103. }
  104. catch( ... ) {
  105. return NULL;
  106. }
  107. }
  108. void AllocateFromAssimpHeap::operator delete[] ( void* data) {
  109. return ::operator delete[](data);
  110. }
  111. // ------------------------------------------------------------------------------------------------
  112. // Importer constructor.
  113. Importer::Importer()
  114. {
  115. // allocate the pimpl first
  116. pimpl = new ImporterPimpl();
  117. pimpl->mScene = NULL;
  118. pimpl->mErrorString = "";
  119. // Allocate a default IO handler
  120. pimpl->mIOHandler = new DefaultIOSystem;
  121. pimpl->mIsDefaultHandler = true;
  122. pimpl->bExtraVerbose = false; // disable extra verbose mode by default
  123. pimpl->mProgressHandler = new DefaultProgressHandler();
  124. pimpl->mIsDefaultProgressHandler = true;
  125. GetImporterInstanceList(pimpl->mImporter);
  126. GetPostProcessingStepInstanceList(pimpl->mPostProcessingSteps);
  127. // Allocate a SharedPostProcessInfo object and store pointers to it in all post-process steps in the list.
  128. pimpl->mPPShared = new SharedPostProcessInfo();
  129. for (std::vector<BaseProcess*>::iterator it = pimpl->mPostProcessingSteps.begin();
  130. it != pimpl->mPostProcessingSteps.end();
  131. ++it) {
  132. (*it)->SetSharedData(pimpl->mPPShared);
  133. }
  134. }
  135. // ------------------------------------------------------------------------------------------------
  136. // Destructor of Importer
  137. Importer::~Importer()
  138. {
  139. // Delete all import plugins
  140. for( unsigned int a = 0; a < pimpl->mImporter.size(); a++)
  141. delete pimpl->mImporter[a];
  142. // Delete all post-processing plug-ins
  143. for( unsigned int a = 0; a < pimpl->mPostProcessingSteps.size(); a++)
  144. delete pimpl->mPostProcessingSteps[a];
  145. // Delete the assigned IO and progress handler
  146. delete pimpl->mIOHandler;
  147. delete pimpl->mProgressHandler;
  148. // Kill imported scene. Destructors should do that recursivly
  149. delete pimpl->mScene;
  150. // Delete shared post-processing data
  151. delete pimpl->mPPShared;
  152. // and finally the pimpl itself
  153. delete pimpl;
  154. }
  155. // ------------------------------------------------------------------------------------------------
  156. // Copy constructor - copies the config of another Importer, not the scene
  157. Importer::Importer(const Importer &other)
  158. {
  159. new(this) Importer();
  160. pimpl->mIntProperties = other.pimpl->mIntProperties;
  161. pimpl->mFloatProperties = other.pimpl->mFloatProperties;
  162. pimpl->mStringProperties = other.pimpl->mStringProperties;
  163. }
  164. // ------------------------------------------------------------------------------------------------
  165. // Register a custom post-processing step
  166. aiReturn Importer::RegisterPPStep(BaseProcess* pImp)
  167. {
  168. ai_assert(NULL != pImp);
  169. ASSIMP_BEGIN_EXCEPTION_REGION();
  170. pimpl->mPostProcessingSteps.push_back(pImp);
  171. DefaultLogger::get()->info("Registering custom post-processing step");
  172. ASSIMP_END_EXCEPTION_REGION(aiReturn);
  173. return AI_SUCCESS;
  174. }
  175. // ------------------------------------------------------------------------------------------------
  176. // Register a custom loader plugin
  177. aiReturn Importer::RegisterLoader(BaseImporter* pImp)
  178. {
  179. ai_assert(NULL != pImp);
  180. ASSIMP_BEGIN_EXCEPTION_REGION();
  181. // --------------------------------------------------------------------
  182. // Check whether we would have two loaders for the same file extension
  183. // This is absolutely OK, but we should warn the developer of the new
  184. // loader that his code will probably never be called if the first
  185. // loader is a bit too lazy in his file checking.
  186. // --------------------------------------------------------------------
  187. std::set<std::string> st;
  188. std::string baked;
  189. pImp->GetExtensionList(st);
  190. for(std::set<std::string>::const_iterator it = st.begin(); it != st.end(); ++it) {
  191. #ifdef _DEBUG
  192. if (IsExtensionSupported(*it)) {
  193. DefaultLogger::get()->warn("The file extension " + *it + " is already in use");
  194. }
  195. #endif
  196. baked += *it;
  197. }
  198. // add the loader
  199. pimpl->mImporter.push_back(pImp);
  200. DefaultLogger::get()->info("Registering custom importer for these file extensions: " + baked);
  201. ASSIMP_END_EXCEPTION_REGION(aiReturn);
  202. return AI_SUCCESS;
  203. }
  204. // ------------------------------------------------------------------------------------------------
  205. // Unregister a custom loader plugin
  206. aiReturn Importer::UnregisterLoader(BaseImporter* pImp)
  207. {
  208. if(!pImp) {
  209. // unregistering a NULL importer is no problem for us ... really!
  210. return AI_SUCCESS;
  211. }
  212. ASSIMP_BEGIN_EXCEPTION_REGION();
  213. std::vector<BaseImporter*>::iterator it = std::find(pimpl->mImporter.begin(),
  214. pimpl->mImporter.end(),pImp);
  215. if (it != pimpl->mImporter.end()) {
  216. pimpl->mImporter.erase(it);
  217. std::set<std::string> st;
  218. pImp->GetExtensionList(st);
  219. DefaultLogger::get()->info("Unregistering custom importer: ");
  220. return AI_SUCCESS;
  221. }
  222. DefaultLogger::get()->warn("Unable to remove custom importer: I can't find you ...");
  223. ASSIMP_END_EXCEPTION_REGION(aiReturn);
  224. return AI_FAILURE;
  225. }
  226. // ------------------------------------------------------------------------------------------------
  227. // Unregister a custom loader plugin
  228. aiReturn Importer::UnregisterPPStep(BaseProcess* pImp)
  229. {
  230. if(!pImp) {
  231. // unregistering a NULL ppstep is no problem for us ... really!
  232. return AI_SUCCESS;
  233. }
  234. ASSIMP_BEGIN_EXCEPTION_REGION();
  235. std::vector<BaseProcess*>::iterator it = std::find(pimpl->mPostProcessingSteps.begin(),
  236. pimpl->mPostProcessingSteps.end(),pImp);
  237. if (it != pimpl->mPostProcessingSteps.end()) {
  238. pimpl->mPostProcessingSteps.erase(it);
  239. DefaultLogger::get()->info("Unregistering custom post-processing step");
  240. return AI_SUCCESS;
  241. }
  242. DefaultLogger::get()->warn("Unable to remove custom post-processing step: I can't find you ..");
  243. ASSIMP_END_EXCEPTION_REGION(aiReturn);
  244. return AI_FAILURE;
  245. }
  246. // ------------------------------------------------------------------------------------------------
  247. // Supplies a custom IO handler to the importer to open and access files.
  248. void Importer::SetIOHandler( IOSystem* pIOHandler)
  249. {
  250. ASSIMP_BEGIN_EXCEPTION_REGION();
  251. // If the new handler is zero, allocate a default IO implementation.
  252. if (!pIOHandler)
  253. {
  254. // Release pointer in the possession of the caller
  255. pimpl->mIOHandler = new DefaultIOSystem();
  256. pimpl->mIsDefaultHandler = true;
  257. }
  258. // Otherwise register the custom handler
  259. else if (pimpl->mIOHandler != pIOHandler)
  260. {
  261. delete pimpl->mIOHandler;
  262. pimpl->mIOHandler = pIOHandler;
  263. pimpl->mIsDefaultHandler = false;
  264. }
  265. ASSIMP_END_EXCEPTION_REGION(void);
  266. }
  267. // ------------------------------------------------------------------------------------------------
  268. // Get the currently set IO handler
  269. IOSystem* Importer::GetIOHandler() const
  270. {
  271. return pimpl->mIOHandler;
  272. }
  273. // ------------------------------------------------------------------------------------------------
  274. // Check whether a custom IO handler is currently set
  275. bool Importer::IsDefaultIOHandler() const
  276. {
  277. return pimpl->mIsDefaultHandler;
  278. }
  279. // ------------------------------------------------------------------------------------------------
  280. // Supplies a custom progress handler to get regular callbacks during importing
  281. void Importer::SetProgressHandler ( ProgressHandler* pHandler )
  282. {
  283. ASSIMP_BEGIN_EXCEPTION_REGION();
  284. // If the new handler is zero, allocate a default implementation.
  285. if (!pHandler)
  286. {
  287. // Release pointer in the possession of the caller
  288. pimpl->mProgressHandler = new DefaultProgressHandler();
  289. pimpl->mIsDefaultProgressHandler = true;
  290. }
  291. // Otherwise register the custom handler
  292. else if (pimpl->mProgressHandler != pHandler)
  293. {
  294. delete pimpl->mProgressHandler;
  295. pimpl->mProgressHandler = pHandler;
  296. pimpl->mIsDefaultProgressHandler = false;
  297. }
  298. ASSIMP_END_EXCEPTION_REGION(void);
  299. }
  300. // ------------------------------------------------------------------------------------------------
  301. // Get the currently set progress handler
  302. ProgressHandler* Importer::GetProgressHandler() const
  303. {
  304. return pimpl->mProgressHandler;
  305. }
  306. // ------------------------------------------------------------------------------------------------
  307. // Check whether a custom progress handler is currently set
  308. bool Importer::IsDefaultProgressHandler() const
  309. {
  310. return pimpl->mIsDefaultProgressHandler;
  311. }
  312. // ------------------------------------------------------------------------------------------------
  313. // Validate post process step flags
  314. bool _ValidateFlags(unsigned int pFlags)
  315. {
  316. if (pFlags & aiProcess_GenSmoothNormals && pFlags & aiProcess_GenNormals) {
  317. DefaultLogger::get()->error("#aiProcess_GenSmoothNormals and #aiProcess_GenNormals are incompatible");
  318. return false;
  319. }
  320. if (pFlags & aiProcess_OptimizeGraph && pFlags & aiProcess_PreTransformVertices) {
  321. DefaultLogger::get()->error("#aiProcess_OptimizeGraph and #aiProcess_PreTransformVertices are incompatible");
  322. return false;
  323. }
  324. return true;
  325. }
  326. // ------------------------------------------------------------------------------------------------
  327. // Free the current scene
  328. void Importer::FreeScene( )
  329. {
  330. ASSIMP_BEGIN_EXCEPTION_REGION();
  331. delete pimpl->mScene;
  332. pimpl->mScene = NULL;
  333. pimpl->mErrorString = "";
  334. ASSIMP_END_EXCEPTION_REGION(void);
  335. }
  336. // ------------------------------------------------------------------------------------------------
  337. // Get the current error string, if any
  338. const char* Importer::GetErrorString() const
  339. {
  340. /* Must remain valid as long as ReadFile() or FreeFile() are not called */
  341. return pimpl->mErrorString.c_str();
  342. }
  343. // ------------------------------------------------------------------------------------------------
  344. // Enable extra-verbose mode
  345. void Importer::SetExtraVerbose(bool bDo)
  346. {
  347. pimpl->bExtraVerbose = bDo;
  348. }
  349. // ------------------------------------------------------------------------------------------------
  350. // Get the current scene
  351. const aiScene* Importer::GetScene() const
  352. {
  353. return pimpl->mScene;
  354. }
  355. // ------------------------------------------------------------------------------------------------
  356. // Orphan the current scene and return it.
  357. aiScene* Importer::GetOrphanedScene()
  358. {
  359. aiScene* s = pimpl->mScene;
  360. ASSIMP_BEGIN_EXCEPTION_REGION();
  361. pimpl->mScene = NULL;
  362. pimpl->mErrorString = ""; /* reset error string */
  363. ASSIMP_END_EXCEPTION_REGION(aiScene*);
  364. return s;
  365. }
  366. // ------------------------------------------------------------------------------------------------
  367. // Validate post-processing flags
  368. bool Importer::ValidateFlags(unsigned int pFlags) const
  369. {
  370. ASSIMP_BEGIN_EXCEPTION_REGION();
  371. // run basic checks for mutually exclusive flags
  372. if(!_ValidateFlags(pFlags)) {
  373. return false;
  374. }
  375. // ValidateDS does not anymore occur in the pp list, it plays an awesome extra role ...
  376. #ifdef ASSIMP_BUILD_NO_VALIDATEDS_PROCESS
  377. if (pFlags & aiProcess_ValidateDataStructure) {
  378. return false;
  379. }
  380. #endif
  381. pFlags &= ~aiProcess_ValidateDataStructure;
  382. // Now iterate through all bits which are set in the flags and check whether we find at least
  383. // one pp plugin which handles it.
  384. for (unsigned int mask = 1; mask < (1u << (sizeof(unsigned int)*8-1));mask <<= 1) {
  385. if (pFlags & mask) {
  386. bool have = false;
  387. for( unsigned int a = 0; a < pimpl->mPostProcessingSteps.size(); a++) {
  388. if (pimpl->mPostProcessingSteps[a]-> IsActive(mask) ) {
  389. have = true;
  390. break;
  391. }
  392. }
  393. if (!have) {
  394. return false;
  395. }
  396. }
  397. }
  398. ASSIMP_END_EXCEPTION_REGION(bool);
  399. return true;
  400. }
  401. // ------------------------------------------------------------------------------------------------
  402. const aiScene* Importer::ReadFileFromMemory( const void* pBuffer,
  403. size_t pLength,
  404. unsigned int pFlags,
  405. const char* pHint /*= ""*/)
  406. {
  407. ASSIMP_BEGIN_EXCEPTION_REGION();
  408. if (!pHint) {
  409. pHint = "";
  410. }
  411. if (!pBuffer || !pLength || strlen(pHint) > 100) {
  412. pimpl->mErrorString = "Invalid parameters passed to ReadFileFromMemory()";
  413. return NULL;
  414. }
  415. // prevent deletion of the previous IOHandler
  416. IOSystem* io = pimpl->mIOHandler;
  417. pimpl->mIOHandler = NULL;
  418. SetIOHandler(new MemoryIOSystem((const uint8_t*)pBuffer,pLength));
  419. // read the file and recover the previous IOSystem
  420. char fbuff[128];
  421. sprintf(fbuff,"%s.%s",AI_MEMORYIO_MAGIC_FILENAME,pHint);
  422. ReadFile(fbuff,pFlags);
  423. SetIOHandler(io);
  424. ASSIMP_END_EXCEPTION_REGION(const aiScene*);
  425. return pimpl->mScene;
  426. }
  427. // ------------------------------------------------------------------------------------------------
  428. void WriteLogOpening(const std::string& file)
  429. {
  430. Logger* l = DefaultLogger::get();
  431. if (!l) {
  432. return;
  433. }
  434. l->info("Load " + file);
  435. // print a full version dump. This is nice because we don't
  436. // need to ask the authors of incoming bug reports for
  437. // the library version they're using - a log dump is
  438. // sufficient.
  439. const unsigned int flags = aiGetCompileFlags();
  440. l->debug(format()
  441. << "Assimp "
  442. << aiGetVersionMajor()
  443. << "."
  444. << aiGetVersionMinor()
  445. << "."
  446. << aiGetVersionRevision()
  447. << " "
  448. #if defined(ASSIMP_BUILD_ARCHITECTURE)
  449. << ASSIMP_BUILD_ARCHITECTURE
  450. #elif defined(_M_IX86) || defined(__x86_32__) || defined(__i386__)
  451. << "x86"
  452. #elif defined(_M_X64) || defined(__x86_64__)
  453. << "amd64"
  454. #elif defined(_M_IA64) || defined(__ia64__)
  455. << "itanium"
  456. #elif defined(__ppc__) || defined(__powerpc__)
  457. << "ppc32"
  458. #elif defined(__powerpc64__)
  459. << "ppc64"
  460. #elif defined(__arm__)
  461. << "arm"
  462. #else
  463. << "<unknown architecture>"
  464. #endif
  465. << " "
  466. #if defined(ASSIMP_BUILD_COMPILER)
  467. << ASSIMP_BUILD_COMPILER
  468. #elif defined(_MSC_VER)
  469. << "msvc"
  470. #elif defined(__GNUC__)
  471. << "gcc"
  472. #else
  473. << "<unknown compiler>"
  474. #endif
  475. #ifndef NDEBUG
  476. << " debug"
  477. #endif
  478. << (flags & ASSIMP_CFLAGS_NOBOOST ? " noboost" : "")
  479. << (flags & ASSIMP_CFLAGS_SHARED ? " shared" : "")
  480. << (flags & ASSIMP_CFLAGS_SINGLETHREADED ? " singlethreaded" : "")
  481. );
  482. }
  483. // ------------------------------------------------------------------------------------------------
  484. // Reads the given file and returns its contents if successful.
  485. const aiScene* Importer::ReadFile( const char* _pFile, unsigned int pFlags)
  486. {
  487. ASSIMP_BEGIN_EXCEPTION_REGION();
  488. const std::string pFile(_pFile);
  489. // ----------------------------------------------------------------------
  490. // Put a large try block around everything to catch all std::exception's
  491. // that might be thrown by STL containers or by new().
  492. // ImportErrorException's are throw by ourselves and caught elsewhere.
  493. //-----------------------------------------------------------------------
  494. WriteLogOpening(pFile);
  495. #ifdef ASSIMP_CATCH_GLOBAL_EXCEPTIONS
  496. try
  497. #endif // ! ASSIMP_CATCH_GLOBAL_EXCEPTIONS
  498. {
  499. // Check whether this Importer instance has already loaded
  500. // a scene. In this case we need to delete the old one
  501. if (pimpl->mScene) {
  502. DefaultLogger::get()->debug("(Deleting previous scene)");
  503. FreeScene();
  504. }
  505. // First check if the file is accessable at all
  506. if( !pimpl->mIOHandler->Exists( pFile)) {
  507. pimpl->mErrorString = "Unable to open file \"" + pFile + "\".";
  508. DefaultLogger::get()->error(pimpl->mErrorString);
  509. return NULL;
  510. }
  511. boost::scoped_ptr<Profiler> profiler(GetPropertyInteger(AI_CONFIG_GLOB_MEASURE_TIME,0)?new Profiler():NULL);
  512. if (profiler) {
  513. profiler->BeginRegion("total");
  514. }
  515. // Find an worker class which can handle the file
  516. BaseImporter* imp = NULL;
  517. for( unsigned int a = 0; a < pimpl->mImporter.size(); a++) {
  518. if( pimpl->mImporter[a]->CanRead( pFile, pimpl->mIOHandler, false)) {
  519. imp = pimpl->mImporter[a];
  520. break;
  521. }
  522. }
  523. if (!imp) {
  524. // not so bad yet ... try format auto detection.
  525. const std::string::size_type s = pFile.find_last_of('.');
  526. if (s != std::string::npos) {
  527. DefaultLogger::get()->info("File extension not known, trying signature-based detection");
  528. for( unsigned int a = 0; a < pimpl->mImporter.size(); a++) {
  529. if( pimpl->mImporter[a]->CanRead( pFile, pimpl->mIOHandler, true)) {
  530. imp = pimpl->mImporter[a];
  531. break;
  532. }
  533. }
  534. }
  535. // Put a proper error message if no suitable importer was found
  536. if( !imp) {
  537. pimpl->mErrorString = "No suitable reader found for the file format of file \"" + pFile + "\".";
  538. DefaultLogger::get()->error(pimpl->mErrorString);
  539. return NULL;
  540. }
  541. }
  542. // Dispatch the reading to the worker class for this format
  543. DefaultLogger::get()->info("Found a matching importer for this file format");
  544. pimpl->mProgressHandler->Update();
  545. if (profiler) {
  546. profiler->BeginRegion("import");
  547. }
  548. pimpl->mScene = imp->ReadFile( this, pFile, pimpl->mIOHandler);
  549. pimpl->mProgressHandler->Update();
  550. if (profiler) {
  551. profiler->EndRegion("import");
  552. }
  553. // If successful, apply all active post processing steps to the imported data
  554. if( pimpl->mScene) {
  555. #ifndef ASSIMP_BUILD_NO_VALIDATEDS_PROCESS
  556. // The ValidateDS process is an exception. It is executed first, even before ScenePreprocessor is called.
  557. if (pFlags & aiProcess_ValidateDataStructure)
  558. {
  559. ValidateDSProcess ds;
  560. ds.ExecuteOnScene (this);
  561. if (!pimpl->mScene) {
  562. return NULL;
  563. }
  564. }
  565. #endif // no validation
  566. // Preprocess the scene and prepare it for post-processing
  567. if (profiler) {
  568. profiler->BeginRegion("preprocess");
  569. }
  570. ScenePreprocessor pre(pimpl->mScene);
  571. pre.ProcessScene();
  572. pimpl->mProgressHandler->Update();
  573. if (profiler) {
  574. profiler->EndRegion("preprocess");
  575. }
  576. // Ensure that the validation process won't be called twice
  577. ApplyPostProcessing(pFlags & (~aiProcess_ValidateDataStructure));
  578. }
  579. // if failed, extract the error string
  580. else if( !pimpl->mScene) {
  581. pimpl->mErrorString = imp->GetErrorText();
  582. }
  583. // clear any data allocated by post-process steps
  584. pimpl->mPPShared->Clean();
  585. if (profiler) {
  586. profiler->EndRegion("total");
  587. }
  588. }
  589. #ifdef ASSIMP_CATCH_GLOBAL_EXCEPTIONS
  590. catch (std::exception &e)
  591. {
  592. #if (defined _MSC_VER) && (defined _CPPRTTI)
  593. // if we have RTTI get the full name of the exception that occured
  594. pimpl->mErrorString = std::string(typeid( e ).name()) + ": " + e.what();
  595. #else
  596. pimpl->mErrorString = std::string("std::exception: ") + e.what();
  597. #endif
  598. DefaultLogger::get()->error(pimpl->mErrorString);
  599. delete pimpl->mScene; pimpl->mScene = NULL;
  600. }
  601. #endif // ! ASSIMP_CATCH_GLOBAL_EXCEPTIONS
  602. // either successful or failure - the pointer expresses it anyways
  603. ASSIMP_END_EXCEPTION_REGION(const aiScene*);
  604. return pimpl->mScene;
  605. }
  606. // ------------------------------------------------------------------------------------------------
  607. // Apply post-processing to the currently bound scene
  608. const aiScene* Importer::ApplyPostProcessing(unsigned int pFlags)
  609. {
  610. ASSIMP_BEGIN_EXCEPTION_REGION();
  611. // Return immediately if no scene is active
  612. if (!pimpl->mScene) {
  613. return NULL;
  614. }
  615. // If no flags are given, return the current scene with no further action
  616. if (!pFlags) {
  617. return pimpl->mScene;
  618. }
  619. // In debug builds: run basic flag validation
  620. ai_assert(_ValidateFlags(pFlags));
  621. DefaultLogger::get()->info("Entering post processing pipeline");
  622. #ifndef ASSIMP_BUILD_NO_VALIDATEDS_PROCESS
  623. // The ValidateDS process plays an exceptional role. It isn't contained in the global
  624. // list of post-processing steps, so we need to call it manually.
  625. if (pFlags & aiProcess_ValidateDataStructure)
  626. {
  627. ValidateDSProcess ds;
  628. ds.ExecuteOnScene (this);
  629. if (!pimpl->mScene) {
  630. return NULL;
  631. }
  632. }
  633. #endif // no validation
  634. #ifdef _DEBUG
  635. if (pimpl->bExtraVerbose)
  636. {
  637. #ifndef ASSIMP_BUILD_NO_VALIDATEDS_PROCESS
  638. DefaultLogger::get()->error("Verbose Import is not available due to build settings");
  639. #endif // no validation
  640. pFlags |= aiProcess_ValidateDataStructure;
  641. }
  642. #else
  643. if (pimpl->bExtraVerbose) {
  644. DefaultLogger::get()->warn("Not a debug build, ignoring extra verbose setting");
  645. }
  646. #endif // ! DEBUG
  647. boost::scoped_ptr<Profiler> profiler(GetPropertyInteger(AI_CONFIG_GLOB_MEASURE_TIME,0)?new Profiler():NULL);
  648. for( unsigned int a = 0; a < pimpl->mPostProcessingSteps.size(); a++) {
  649. BaseProcess* process = pimpl->mPostProcessingSteps[a];
  650. if( process->IsActive( pFlags)) {
  651. if (profiler) {
  652. profiler->BeginRegion("postprocess");
  653. }
  654. process->ExecuteOnScene ( this );
  655. pimpl->mProgressHandler->Update();
  656. if (profiler) {
  657. profiler->EndRegion("postprocess");
  658. }
  659. }
  660. if( !pimpl->mScene) {
  661. break;
  662. }
  663. #ifdef _DEBUG
  664. #ifndef ASSIMP_BUILD_NO_VALIDATEDS_PROCESS
  665. continue;
  666. #endif // no validation
  667. // If the extra verbose mode is active, execute the ValidateDataStructureStep again - after each step
  668. if (pimpl->bExtraVerbose) {
  669. DefaultLogger::get()->debug("Verbose Import: revalidating data structures");
  670. ValidateDSProcess ds;
  671. ds.ExecuteOnScene (this);
  672. if( !pimpl->mScene) {
  673. DefaultLogger::get()->error("Verbose Import: failed to revalidate data structures");
  674. break;
  675. }
  676. }
  677. #endif // ! DEBUG
  678. }
  679. // update private scene flags
  680. if( pimpl->mScene )
  681. ScenePriv(pimpl->mScene)->mPPStepsApplied |= pFlags;
  682. // clear any data allocated by post-process steps
  683. pimpl->mPPShared->Clean();
  684. DefaultLogger::get()->info("Leaving post processing pipeline");
  685. ASSIMP_END_EXCEPTION_REGION(const aiScene*);
  686. return pimpl->mScene;
  687. }
  688. // ------------------------------------------------------------------------------------------------
  689. // Helper function to check whether an extension is supported by ASSIMP
  690. bool Importer::IsExtensionSupported(const char* szExtension) const
  691. {
  692. return NULL != GetImporter(szExtension);
  693. }
  694. // ------------------------------------------------------------------------------------------------
  695. size_t Importer::GetImporterCount() const
  696. {
  697. return pimpl->mImporter.size();
  698. }
  699. // ------------------------------------------------------------------------------------------------
  700. const aiImporterDesc* Importer::GetImporterInfo(size_t index) const
  701. {
  702. if (index >= pimpl->mImporter.size()) {
  703. return NULL;
  704. }
  705. return pimpl->mImporter[index]->GetInfo();
  706. }
  707. // ------------------------------------------------------------------------------------------------
  708. BaseImporter* Importer::GetImporter (size_t index) const
  709. {
  710. if (index >= pimpl->mImporter.size()) {
  711. return NULL;
  712. }
  713. return pimpl->mImporter[index];
  714. }
  715. // ------------------------------------------------------------------------------------------------
  716. // Find a loader plugin for a given file extension
  717. BaseImporter* Importer::GetImporter (const char* szExtension) const
  718. {
  719. return GetImporter(GetImporterIndex(szExtension));
  720. }
  721. // ------------------------------------------------------------------------------------------------
  722. // Find a loader plugin for a given file extension
  723. size_t Importer::GetImporterIndex (const char* szExtension) const
  724. {
  725. ai_assert(szExtension);
  726. ASSIMP_BEGIN_EXCEPTION_REGION();
  727. // skip over wildcard and dot characters at string head --
  728. for(;*szExtension == '*' || *szExtension == '.'; ++szExtension);
  729. std::string ext(szExtension);
  730. if (ext.empty()) {
  731. return static_cast<size_t>(-1);
  732. }
  733. std::transform(ext.begin(),ext.end(), ext.begin(), tolower);
  734. std::set<std::string> str;
  735. for (std::vector<BaseImporter*>::const_iterator i = pimpl->mImporter.begin();i != pimpl->mImporter.end();++i) {
  736. str.clear();
  737. (*i)->GetExtensionList(str);
  738. for (std::set<std::string>::const_iterator it = str.begin(); it != str.end(); ++it) {
  739. if (ext == *it) {
  740. return std::distance(static_cast< std::vector<BaseImporter*>::const_iterator >(pimpl->mImporter.begin()), i);
  741. }
  742. }
  743. }
  744. ASSIMP_END_EXCEPTION_REGION(size_t);
  745. return static_cast<size_t>(-1);
  746. }
  747. // ------------------------------------------------------------------------------------------------
  748. // Helper function to build a list of all file extensions supported by ASSIMP
  749. void Importer::GetExtensionList(aiString& szOut) const
  750. {
  751. ASSIMP_BEGIN_EXCEPTION_REGION();
  752. std::set<std::string> str;
  753. for (std::vector<BaseImporter*>::const_iterator i = pimpl->mImporter.begin();i != pimpl->mImporter.end();++i) {
  754. (*i)->GetExtensionList(str);
  755. }
  756. for (std::set<std::string>::const_iterator it = str.begin();; ) {
  757. szOut.Append("*.");
  758. szOut.Append((*it).c_str());
  759. if (++it == str.end()) {
  760. break;
  761. }
  762. szOut.Append(";");
  763. }
  764. ASSIMP_END_EXCEPTION_REGION(void);
  765. }
  766. // ------------------------------------------------------------------------------------------------
  767. // Set a configuration property
  768. void Importer::SetPropertyInteger(const char* szName, int iValue,
  769. bool* bWasExisting /*= NULL*/)
  770. {
  771. ASSIMP_BEGIN_EXCEPTION_REGION();
  772. SetGenericProperty<int>(pimpl->mIntProperties, szName,iValue,bWasExisting);
  773. ASSIMP_END_EXCEPTION_REGION(void);
  774. }
  775. // ------------------------------------------------------------------------------------------------
  776. // Set a configuration property
  777. void Importer::SetPropertyFloat(const char* szName, float iValue,
  778. bool* bWasExisting /*= NULL*/)
  779. {
  780. ASSIMP_BEGIN_EXCEPTION_REGION();
  781. SetGenericProperty<float>(pimpl->mFloatProperties, szName,iValue,bWasExisting);
  782. ASSIMP_END_EXCEPTION_REGION(void);
  783. }
  784. // ------------------------------------------------------------------------------------------------
  785. // Set a configuration property
  786. void Importer::SetPropertyString(const char* szName, const std::string& value,
  787. bool* bWasExisting /*= NULL*/)
  788. {
  789. ASSIMP_BEGIN_EXCEPTION_REGION();
  790. SetGenericProperty<std::string>(pimpl->mStringProperties, szName,value,bWasExisting);
  791. ASSIMP_END_EXCEPTION_REGION(void);
  792. }
  793. // ------------------------------------------------------------------------------------------------
  794. // Get a configuration property
  795. int Importer::GetPropertyInteger(const char* szName,
  796. int iErrorReturn /*= 0xffffffff*/) const
  797. {
  798. return GetGenericProperty<int>(pimpl->mIntProperties,szName,iErrorReturn);
  799. }
  800. // ------------------------------------------------------------------------------------------------
  801. // Get a configuration property
  802. float Importer::GetPropertyFloat(const char* szName,
  803. float iErrorReturn /*= 10e10*/) const
  804. {
  805. return GetGenericProperty<float>(pimpl->mFloatProperties,szName,iErrorReturn);
  806. }
  807. // ------------------------------------------------------------------------------------------------
  808. // Get a configuration property
  809. const std::string& Importer::GetPropertyString(const char* szName,
  810. const std::string& iErrorReturn /*= ""*/) const
  811. {
  812. return GetGenericProperty<std::string>(pimpl->mStringProperties,szName,iErrorReturn);
  813. }
  814. // ------------------------------------------------------------------------------------------------
  815. // Get the memory requirements of a single node
  816. inline void AddNodeWeight(unsigned int& iScene,const aiNode* pcNode)
  817. {
  818. iScene += sizeof(aiNode);
  819. iScene += sizeof(unsigned int) * pcNode->mNumMeshes;
  820. iScene += sizeof(void*) * pcNode->mNumChildren;
  821. for (unsigned int i = 0; i < pcNode->mNumChildren;++i) {
  822. AddNodeWeight(iScene,pcNode->mChildren[i]);
  823. }
  824. }
  825. // ------------------------------------------------------------------------------------------------
  826. // Get the memory requirements of the scene
  827. void Importer::GetMemoryRequirements(aiMemoryInfo& in) const
  828. {
  829. in = aiMemoryInfo();
  830. aiScene* mScene = pimpl->mScene;
  831. // return if we have no scene loaded
  832. if (!pimpl->mScene)
  833. return;
  834. in.total = sizeof(aiScene);
  835. // add all meshes
  836. for (unsigned int i = 0; i < mScene->mNumMeshes;++i)
  837. {
  838. in.meshes += sizeof(aiMesh);
  839. if (mScene->mMeshes[i]->HasPositions()) {
  840. in.meshes += sizeof(aiVector3D) * mScene->mMeshes[i]->mNumVertices;
  841. }
  842. if (mScene->mMeshes[i]->HasNormals()) {
  843. in.meshes += sizeof(aiVector3D) * mScene->mMeshes[i]->mNumVertices;
  844. }
  845. if (mScene->mMeshes[i]->HasTangentsAndBitangents()) {
  846. in.meshes += sizeof(aiVector3D) * mScene->mMeshes[i]->mNumVertices * 2;
  847. }
  848. for (unsigned int a = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS;++a) {
  849. if (mScene->mMeshes[i]->HasVertexColors(a)) {
  850. in.meshes += sizeof(aiColor4D) * mScene->mMeshes[i]->mNumVertices;
  851. }
  852. else break;
  853. }
  854. for (unsigned int a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS;++a) {
  855. if (mScene->mMeshes[i]->HasTextureCoords(a)) {
  856. in.meshes += sizeof(aiVector3D) * mScene->mMeshes[i]->mNumVertices;
  857. }
  858. else break;
  859. }
  860. if (mScene->mMeshes[i]->HasBones()) {
  861. in.meshes += sizeof(void*) * mScene->mMeshes[i]->mNumBones;
  862. for (unsigned int p = 0; p < mScene->mMeshes[i]->mNumBones;++p) {
  863. in.meshes += sizeof(aiBone);
  864. in.meshes += mScene->mMeshes[i]->mBones[p]->mNumWeights * sizeof(aiVertexWeight);
  865. }
  866. }
  867. in.meshes += (sizeof(aiFace) + 3 * sizeof(unsigned int))*mScene->mMeshes[i]->mNumFaces;
  868. }
  869. in.total += in.meshes;
  870. // add all embedded textures
  871. for (unsigned int i = 0; i < mScene->mNumTextures;++i) {
  872. const aiTexture* pc = mScene->mTextures[i];
  873. in.textures += sizeof(aiTexture);
  874. if (pc->mHeight) {
  875. in.textures += 4 * pc->mHeight * pc->mWidth;
  876. }
  877. else in.textures += pc->mWidth;
  878. }
  879. in.total += in.textures;
  880. // add all animations
  881. for (unsigned int i = 0; i < mScene->mNumAnimations;++i) {
  882. const aiAnimation* pc = mScene->mAnimations[i];
  883. in.animations += sizeof(aiAnimation);
  884. // add all bone anims
  885. for (unsigned int a = 0; a < pc->mNumChannels; ++a) {
  886. const aiNodeAnim* pc2 = pc->mChannels[i];
  887. in.animations += sizeof(aiNodeAnim);
  888. in.animations += pc2->mNumPositionKeys * sizeof(aiVectorKey);
  889. in.animations += pc2->mNumScalingKeys * sizeof(aiVectorKey);
  890. in.animations += pc2->mNumRotationKeys * sizeof(aiQuatKey);
  891. }
  892. }
  893. in.total += in.animations;
  894. // add all cameras and all lights
  895. in.total += in.cameras = sizeof(aiCamera) * mScene->mNumCameras;
  896. in.total += in.lights = sizeof(aiLight) * mScene->mNumLights;
  897. // add all nodes
  898. AddNodeWeight(in.nodes,mScene->mRootNode);
  899. in.total += in.nodes;
  900. // add all materials
  901. for (unsigned int i = 0; i < mScene->mNumMaterials;++i) {
  902. const aiMaterial* pc = mScene->mMaterials[i];
  903. in.materials += sizeof(aiMaterial);
  904. in.materials += pc->mNumAllocated * sizeof(void*);
  905. for (unsigned int a = 0; a < pc->mNumProperties;++a) {
  906. in.materials += pc->mProperties[a]->mDataLength;
  907. }
  908. }
  909. in.total += in.materials;
  910. }