You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1097 line
34 KiB

  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. pimpl->mMatrixProperties = other.pimpl->mMatrixProperties;
  164. }
  165. // ------------------------------------------------------------------------------------------------
  166. // Register a custom post-processing step
  167. aiReturn Importer::RegisterPPStep(BaseProcess* pImp)
  168. {
  169. ai_assert(NULL != pImp);
  170. ASSIMP_BEGIN_EXCEPTION_REGION();
  171. pimpl->mPostProcessingSteps.push_back(pImp);
  172. DefaultLogger::get()->info("Registering custom post-processing step");
  173. ASSIMP_END_EXCEPTION_REGION(aiReturn);
  174. return AI_SUCCESS;
  175. }
  176. // ------------------------------------------------------------------------------------------------
  177. // Register a custom loader plugin
  178. aiReturn Importer::RegisterLoader(BaseImporter* pImp)
  179. {
  180. ai_assert(NULL != pImp);
  181. ASSIMP_BEGIN_EXCEPTION_REGION();
  182. // --------------------------------------------------------------------
  183. // Check whether we would have two loaders for the same file extension
  184. // This is absolutely OK, but we should warn the developer of the new
  185. // loader that his code will probably never be called if the first
  186. // loader is a bit too lazy in his file checking.
  187. // --------------------------------------------------------------------
  188. std::set<std::string> st;
  189. std::string baked;
  190. pImp->GetExtensionList(st);
  191. for(std::set<std::string>::const_iterator it = st.begin(); it != st.end(); ++it) {
  192. #ifdef ASSIMP_BUILD_DEBUG
  193. if (IsExtensionSupported(*it)) {
  194. DefaultLogger::get()->warn("The file extension " + *it + " is already in use");
  195. }
  196. #endif
  197. baked += *it;
  198. }
  199. // add the loader
  200. pimpl->mImporter.push_back(pImp);
  201. DefaultLogger::get()->info("Registering custom importer for these file extensions: " + baked);
  202. ASSIMP_END_EXCEPTION_REGION(aiReturn);
  203. return AI_SUCCESS;
  204. }
  205. // ------------------------------------------------------------------------------------------------
  206. // Unregister a custom loader plugin
  207. aiReturn Importer::UnregisterLoader(BaseImporter* pImp)
  208. {
  209. if(!pImp) {
  210. // unregistering a NULL importer is no problem for us ... really!
  211. return AI_SUCCESS;
  212. }
  213. ASSIMP_BEGIN_EXCEPTION_REGION();
  214. std::vector<BaseImporter*>::iterator it = std::find(pimpl->mImporter.begin(),
  215. pimpl->mImporter.end(),pImp);
  216. if (it != pimpl->mImporter.end()) {
  217. pimpl->mImporter.erase(it);
  218. std::set<std::string> st;
  219. pImp->GetExtensionList(st);
  220. DefaultLogger::get()->info("Unregistering custom importer: ");
  221. return AI_SUCCESS;
  222. }
  223. DefaultLogger::get()->warn("Unable to remove custom importer: I can't find you ...");
  224. ASSIMP_END_EXCEPTION_REGION(aiReturn);
  225. return AI_FAILURE;
  226. }
  227. // ------------------------------------------------------------------------------------------------
  228. // Unregister a custom loader plugin
  229. aiReturn Importer::UnregisterPPStep(BaseProcess* pImp)
  230. {
  231. if(!pImp) {
  232. // unregistering a NULL ppstep is no problem for us ... really!
  233. return AI_SUCCESS;
  234. }
  235. ASSIMP_BEGIN_EXCEPTION_REGION();
  236. std::vector<BaseProcess*>::iterator it = std::find(pimpl->mPostProcessingSteps.begin(),
  237. pimpl->mPostProcessingSteps.end(),pImp);
  238. if (it != pimpl->mPostProcessingSteps.end()) {
  239. pimpl->mPostProcessingSteps.erase(it);
  240. DefaultLogger::get()->info("Unregistering custom post-processing step");
  241. return AI_SUCCESS;
  242. }
  243. DefaultLogger::get()->warn("Unable to remove custom post-processing step: I can't find you ..");
  244. ASSIMP_END_EXCEPTION_REGION(aiReturn);
  245. return AI_FAILURE;
  246. }
  247. // ------------------------------------------------------------------------------------------------
  248. // Supplies a custom IO handler to the importer to open and access files.
  249. void Importer::SetIOHandler( IOSystem* pIOHandler)
  250. {
  251. ASSIMP_BEGIN_EXCEPTION_REGION();
  252. // If the new handler is zero, allocate a default IO implementation.
  253. if (!pIOHandler)
  254. {
  255. // Release pointer in the possession of the caller
  256. pimpl->mIOHandler = new DefaultIOSystem();
  257. pimpl->mIsDefaultHandler = true;
  258. }
  259. // Otherwise register the custom handler
  260. else if (pimpl->mIOHandler != pIOHandler)
  261. {
  262. delete pimpl->mIOHandler;
  263. pimpl->mIOHandler = pIOHandler;
  264. pimpl->mIsDefaultHandler = false;
  265. }
  266. ASSIMP_END_EXCEPTION_REGION(void);
  267. }
  268. // ------------------------------------------------------------------------------------------------
  269. // Get the currently set IO handler
  270. IOSystem* Importer::GetIOHandler() const
  271. {
  272. return pimpl->mIOHandler;
  273. }
  274. // ------------------------------------------------------------------------------------------------
  275. // Check whether a custom IO handler is currently set
  276. bool Importer::IsDefaultIOHandler() const
  277. {
  278. return pimpl->mIsDefaultHandler;
  279. }
  280. // ------------------------------------------------------------------------------------------------
  281. // Supplies a custom progress handler to get regular callbacks during importing
  282. void Importer::SetProgressHandler ( ProgressHandler* pHandler )
  283. {
  284. ASSIMP_BEGIN_EXCEPTION_REGION();
  285. // If the new handler is zero, allocate a default implementation.
  286. if (!pHandler)
  287. {
  288. // Release pointer in the possession of the caller
  289. pimpl->mProgressHandler = new DefaultProgressHandler();
  290. pimpl->mIsDefaultProgressHandler = true;
  291. }
  292. // Otherwise register the custom handler
  293. else if (pimpl->mProgressHandler != pHandler)
  294. {
  295. delete pimpl->mProgressHandler;
  296. pimpl->mProgressHandler = pHandler;
  297. pimpl->mIsDefaultProgressHandler = false;
  298. }
  299. ASSIMP_END_EXCEPTION_REGION(void);
  300. }
  301. // ------------------------------------------------------------------------------------------------
  302. // Get the currently set progress handler
  303. ProgressHandler* Importer::GetProgressHandler() const
  304. {
  305. return pimpl->mProgressHandler;
  306. }
  307. // ------------------------------------------------------------------------------------------------
  308. // Check whether a custom progress handler is currently set
  309. bool Importer::IsDefaultProgressHandler() const
  310. {
  311. return pimpl->mIsDefaultProgressHandler;
  312. }
  313. // ------------------------------------------------------------------------------------------------
  314. // Validate post process step flags
  315. bool _ValidateFlags(unsigned int pFlags)
  316. {
  317. if (pFlags & aiProcess_GenSmoothNormals && pFlags & aiProcess_GenNormals) {
  318. DefaultLogger::get()->error("#aiProcess_GenSmoothNormals and #aiProcess_GenNormals are incompatible");
  319. return false;
  320. }
  321. if (pFlags & aiProcess_OptimizeGraph && pFlags & aiProcess_PreTransformVertices) {
  322. DefaultLogger::get()->error("#aiProcess_OptimizeGraph and #aiProcess_PreTransformVertices are incompatible");
  323. return false;
  324. }
  325. return true;
  326. }
  327. // ------------------------------------------------------------------------------------------------
  328. // Free the current scene
  329. void Importer::FreeScene( )
  330. {
  331. ASSIMP_BEGIN_EXCEPTION_REGION();
  332. delete pimpl->mScene;
  333. pimpl->mScene = NULL;
  334. pimpl->mErrorString = "";
  335. ASSIMP_END_EXCEPTION_REGION(void);
  336. }
  337. // ------------------------------------------------------------------------------------------------
  338. // Get the current error string, if any
  339. const char* Importer::GetErrorString() const
  340. {
  341. /* Must remain valid as long as ReadFile() or FreeFile() are not called */
  342. return pimpl->mErrorString.c_str();
  343. }
  344. // ------------------------------------------------------------------------------------------------
  345. // Enable extra-verbose mode
  346. void Importer::SetExtraVerbose(bool bDo)
  347. {
  348. pimpl->bExtraVerbose = bDo;
  349. }
  350. // ------------------------------------------------------------------------------------------------
  351. // Get the current scene
  352. const aiScene* Importer::GetScene() const
  353. {
  354. return pimpl->mScene;
  355. }
  356. // ------------------------------------------------------------------------------------------------
  357. // Orphan the current scene and return it.
  358. aiScene* Importer::GetOrphanedScene()
  359. {
  360. aiScene* s = pimpl->mScene;
  361. ASSIMP_BEGIN_EXCEPTION_REGION();
  362. pimpl->mScene = NULL;
  363. pimpl->mErrorString = ""; /* reset error string */
  364. ASSIMP_END_EXCEPTION_REGION(aiScene*);
  365. return s;
  366. }
  367. // ------------------------------------------------------------------------------------------------
  368. // Validate post-processing flags
  369. bool Importer::ValidateFlags(unsigned int pFlags) const
  370. {
  371. ASSIMP_BEGIN_EXCEPTION_REGION();
  372. // run basic checks for mutually exclusive flags
  373. if(!_ValidateFlags(pFlags)) {
  374. return false;
  375. }
  376. // ValidateDS does not anymore occur in the pp list, it plays an awesome extra role ...
  377. #ifdef ASSIMP_BUILD_NO_VALIDATEDS_PROCESS
  378. if (pFlags & aiProcess_ValidateDataStructure) {
  379. return false;
  380. }
  381. #endif
  382. pFlags &= ~aiProcess_ValidateDataStructure;
  383. // Now iterate through all bits which are set in the flags and check whether we find at least
  384. // one pp plugin which handles it.
  385. for (unsigned int mask = 1; mask < (1u << (sizeof(unsigned int)*8-1));mask <<= 1) {
  386. if (pFlags & mask) {
  387. bool have = false;
  388. for( unsigned int a = 0; a < pimpl->mPostProcessingSteps.size(); a++) {
  389. if (pimpl->mPostProcessingSteps[a]-> IsActive(mask) ) {
  390. have = true;
  391. break;
  392. }
  393. }
  394. if (!have) {
  395. return false;
  396. }
  397. }
  398. }
  399. ASSIMP_END_EXCEPTION_REGION(bool);
  400. return true;
  401. }
  402. // ------------------------------------------------------------------------------------------------
  403. const aiScene* Importer::ReadFileFromMemory( const void* pBuffer,
  404. size_t pLength,
  405. unsigned int pFlags,
  406. const char* pHint /*= ""*/)
  407. {
  408. ASSIMP_BEGIN_EXCEPTION_REGION();
  409. if (!pHint) {
  410. pHint = "";
  411. }
  412. if (!pBuffer || !pLength || strlen(pHint) > 100) {
  413. pimpl->mErrorString = "Invalid parameters passed to ReadFileFromMemory()";
  414. return NULL;
  415. }
  416. // prevent deletion of the previous IOHandler
  417. IOSystem* io = pimpl->mIOHandler;
  418. pimpl->mIOHandler = NULL;
  419. SetIOHandler(new MemoryIOSystem((const uint8_t*)pBuffer,pLength));
  420. // read the file and recover the previous IOSystem
  421. char fbuff[128];
  422. sprintf(fbuff,"%s.%s",AI_MEMORYIO_MAGIC_FILENAME,pHint);
  423. ReadFile(fbuff,pFlags);
  424. SetIOHandler(io);
  425. ASSIMP_END_EXCEPTION_REGION(const aiScene*);
  426. return pimpl->mScene;
  427. }
  428. // ------------------------------------------------------------------------------------------------
  429. void WriteLogOpening(const std::string& file)
  430. {
  431. Logger* l = DefaultLogger::get();
  432. if (!l) {
  433. return;
  434. }
  435. l->info("Load " + file);
  436. // print a full version dump. This is nice because we don't
  437. // need to ask the authors of incoming bug reports for
  438. // the library version they're using - a log dump is
  439. // sufficient.
  440. const unsigned int flags = aiGetCompileFlags();
  441. l->debug(format()
  442. << "Assimp "
  443. << aiGetVersionMajor()
  444. << "."
  445. << aiGetVersionMinor()
  446. << "."
  447. << aiGetVersionRevision()
  448. << " "
  449. #if defined(ASSIMP_BUILD_ARCHITECTURE)
  450. << ASSIMP_BUILD_ARCHITECTURE
  451. #elif defined(_M_IX86) || defined(__x86_32__) || defined(__i386__)
  452. << "x86"
  453. #elif defined(_M_X64) || defined(__x86_64__)
  454. << "amd64"
  455. #elif defined(_M_IA64) || defined(__ia64__)
  456. << "itanium"
  457. #elif defined(__ppc__) || defined(__powerpc__)
  458. << "ppc32"
  459. #elif defined(__powerpc64__)
  460. << "ppc64"
  461. #elif defined(__arm__)
  462. << "arm"
  463. #else
  464. << "<unknown architecture>"
  465. #endif
  466. << " "
  467. #if defined(ASSIMP_BUILD_COMPILER)
  468. << ASSIMP_BUILD_COMPILER
  469. #elif defined(_MSC_VER)
  470. << "msvc"
  471. #elif defined(__GNUC__)
  472. << "gcc"
  473. #else
  474. << "<unknown compiler>"
  475. #endif
  476. #ifdef ASSIMP_BUILD_DEBUG
  477. << " debug"
  478. #endif
  479. << (flags & ASSIMP_CFLAGS_NOBOOST ? " noboost" : "")
  480. << (flags & ASSIMP_CFLAGS_SHARED ? " shared" : "")
  481. << (flags & ASSIMP_CFLAGS_SINGLETHREADED ? " singlethreaded" : "")
  482. );
  483. }
  484. // ------------------------------------------------------------------------------------------------
  485. // Reads the given file and returns its contents if successful.
  486. const aiScene* Importer::ReadFile( const char* _pFile, unsigned int pFlags)
  487. {
  488. ASSIMP_BEGIN_EXCEPTION_REGION();
  489. const std::string pFile(_pFile);
  490. // ----------------------------------------------------------------------
  491. // Put a large try block around everything to catch all std::exception's
  492. // that might be thrown by STL containers or by new().
  493. // ImportErrorException's are throw by ourselves and caught elsewhere.
  494. //-----------------------------------------------------------------------
  495. WriteLogOpening(pFile);
  496. #ifdef ASSIMP_CATCH_GLOBAL_EXCEPTIONS
  497. try
  498. #endif // ! ASSIMP_CATCH_GLOBAL_EXCEPTIONS
  499. {
  500. // Check whether this Importer instance has already loaded
  501. // a scene. In this case we need to delete the old one
  502. if (pimpl->mScene) {
  503. DefaultLogger::get()->debug("(Deleting previous scene)");
  504. FreeScene();
  505. }
  506. // First check if the file is accessable at all
  507. if( !pimpl->mIOHandler->Exists( pFile)) {
  508. pimpl->mErrorString = "Unable to open file \"" + pFile + "\".";
  509. DefaultLogger::get()->error(pimpl->mErrorString);
  510. return NULL;
  511. }
  512. boost::scoped_ptr<Profiler> profiler(GetPropertyInteger(AI_CONFIG_GLOB_MEASURE_TIME,0)?new Profiler():NULL);
  513. if (profiler) {
  514. profiler->BeginRegion("total");
  515. }
  516. // Find an worker class which can handle the file
  517. BaseImporter* imp = NULL;
  518. for( unsigned int a = 0; a < pimpl->mImporter.size(); a++) {
  519. if( pimpl->mImporter[a]->CanRead( pFile, pimpl->mIOHandler, false)) {
  520. imp = pimpl->mImporter[a];
  521. break;
  522. }
  523. }
  524. if (!imp) {
  525. // not so bad yet ... try format auto detection.
  526. const std::string::size_type s = pFile.find_last_of('.');
  527. if (s != std::string::npos) {
  528. DefaultLogger::get()->info("File extension not known, trying signature-based detection");
  529. for( unsigned int a = 0; a < pimpl->mImporter.size(); a++) {
  530. if( pimpl->mImporter[a]->CanRead( pFile, pimpl->mIOHandler, true)) {
  531. imp = pimpl->mImporter[a];
  532. break;
  533. }
  534. }
  535. }
  536. // Put a proper error message if no suitable importer was found
  537. if( !imp) {
  538. pimpl->mErrorString = "No suitable reader found for the file format of file \"" + pFile + "\".";
  539. DefaultLogger::get()->error(pimpl->mErrorString);
  540. return NULL;
  541. }
  542. }
  543. // Dispatch the reading to the worker class for this format
  544. DefaultLogger::get()->info("Found a matching importer for this file format");
  545. pimpl->mProgressHandler->Update();
  546. if (profiler) {
  547. profiler->BeginRegion("import");
  548. }
  549. pimpl->mScene = imp->ReadFile( this, pFile, pimpl->mIOHandler);
  550. pimpl->mProgressHandler->Update();
  551. if (profiler) {
  552. profiler->EndRegion("import");
  553. }
  554. // If successful, apply all active post processing steps to the imported data
  555. if( pimpl->mScene) {
  556. #ifndef ASSIMP_BUILD_NO_VALIDATEDS_PROCESS
  557. // The ValidateDS process is an exception. It is executed first, even before ScenePreprocessor is called.
  558. if (pFlags & aiProcess_ValidateDataStructure)
  559. {
  560. ValidateDSProcess ds;
  561. ds.ExecuteOnScene (this);
  562. if (!pimpl->mScene) {
  563. return NULL;
  564. }
  565. }
  566. #endif // no validation
  567. // Preprocess the scene and prepare it for post-processing
  568. if (profiler) {
  569. profiler->BeginRegion("preprocess");
  570. }
  571. ScenePreprocessor pre(pimpl->mScene);
  572. pre.ProcessScene();
  573. pimpl->mProgressHandler->Update();
  574. if (profiler) {
  575. profiler->EndRegion("preprocess");
  576. }
  577. // Ensure that the validation process won't be called twice
  578. ApplyPostProcessing(pFlags & (~aiProcess_ValidateDataStructure));
  579. }
  580. // if failed, extract the error string
  581. else if( !pimpl->mScene) {
  582. pimpl->mErrorString = imp->GetErrorText();
  583. }
  584. // clear any data allocated by post-process steps
  585. pimpl->mPPShared->Clean();
  586. if (profiler) {
  587. profiler->EndRegion("total");
  588. }
  589. }
  590. #ifdef ASSIMP_CATCH_GLOBAL_EXCEPTIONS
  591. catch (std::exception &e)
  592. {
  593. #if (defined _MSC_VER) && (defined _CPPRTTI)
  594. // if we have RTTI get the full name of the exception that occured
  595. pimpl->mErrorString = std::string(typeid( e ).name()) + ": " + e.what();
  596. #else
  597. pimpl->mErrorString = std::string("std::exception: ") + e.what();
  598. #endif
  599. DefaultLogger::get()->error(pimpl->mErrorString);
  600. delete pimpl->mScene; pimpl->mScene = NULL;
  601. }
  602. #endif // ! ASSIMP_CATCH_GLOBAL_EXCEPTIONS
  603. // either successful or failure - the pointer expresses it anyways
  604. ASSIMP_END_EXCEPTION_REGION(const aiScene*);
  605. return pimpl->mScene;
  606. }
  607. // ------------------------------------------------------------------------------------------------
  608. // Apply post-processing to the currently bound scene
  609. const aiScene* Importer::ApplyPostProcessing(unsigned int pFlags)
  610. {
  611. ASSIMP_BEGIN_EXCEPTION_REGION();
  612. // Return immediately if no scene is active
  613. if (!pimpl->mScene) {
  614. return NULL;
  615. }
  616. // If no flags are given, return the current scene with no further action
  617. if (!pFlags) {
  618. return pimpl->mScene;
  619. }
  620. // In debug builds: run basic flag validation
  621. ai_assert(_ValidateFlags(pFlags));
  622. DefaultLogger::get()->info("Entering post processing pipeline");
  623. #ifndef ASSIMP_BUILD_NO_VALIDATEDS_PROCESS
  624. // The ValidateDS process plays an exceptional role. It isn't contained in the global
  625. // list of post-processing steps, so we need to call it manually.
  626. if (pFlags & aiProcess_ValidateDataStructure)
  627. {
  628. ValidateDSProcess ds;
  629. ds.ExecuteOnScene (this);
  630. if (!pimpl->mScene) {
  631. return NULL;
  632. }
  633. }
  634. #endif // no validation
  635. #ifdef ASSIMP_BUILD_DEBUG
  636. if (pimpl->bExtraVerbose)
  637. {
  638. #ifdef ASSIMP_BUILD_NO_VALIDATEDS_PROCESS
  639. DefaultLogger::get()->error("Verbose Import is not available due to build settings");
  640. #endif // no validation
  641. pFlags |= aiProcess_ValidateDataStructure;
  642. }
  643. #else
  644. if (pimpl->bExtraVerbose) {
  645. DefaultLogger::get()->warn("Not a debug build, ignoring extra verbose setting");
  646. }
  647. #endif // ! DEBUG
  648. boost::scoped_ptr<Profiler> profiler(GetPropertyInteger(AI_CONFIG_GLOB_MEASURE_TIME,0)?new Profiler():NULL);
  649. for( unsigned int a = 0; a < pimpl->mPostProcessingSteps.size(); a++) {
  650. BaseProcess* process = pimpl->mPostProcessingSteps[a];
  651. if( process->IsActive( pFlags)) {
  652. if (profiler) {
  653. profiler->BeginRegion("postprocess");
  654. }
  655. process->ExecuteOnScene ( this );
  656. pimpl->mProgressHandler->Update();
  657. if (profiler) {
  658. profiler->EndRegion("postprocess");
  659. }
  660. }
  661. if( !pimpl->mScene) {
  662. break;
  663. }
  664. #ifdef ASSIMP_BUILD_DEBUG
  665. #ifdef ASSIMP_BUILD_NO_VALIDATEDS_PROCESS
  666. continue;
  667. #endif // no validation
  668. // If the extra verbose mode is active, execute the ValidateDataStructureStep again - after each step
  669. if (pimpl->bExtraVerbose) {
  670. DefaultLogger::get()->debug("Verbose Import: revalidating data structures");
  671. ValidateDSProcess ds;
  672. ds.ExecuteOnScene (this);
  673. if( !pimpl->mScene) {
  674. DefaultLogger::get()->error("Verbose Import: failed to revalidate data structures");
  675. break;
  676. }
  677. }
  678. #endif // ! DEBUG
  679. }
  680. // update private scene flags
  681. if( pimpl->mScene )
  682. ScenePriv(pimpl->mScene)->mPPStepsApplied |= pFlags;
  683. // clear any data allocated by post-process steps
  684. pimpl->mPPShared->Clean();
  685. DefaultLogger::get()->info("Leaving post processing pipeline");
  686. ASSIMP_END_EXCEPTION_REGION(const aiScene*);
  687. return pimpl->mScene;
  688. }
  689. // ------------------------------------------------------------------------------------------------
  690. // Helper function to check whether an extension is supported by ASSIMP
  691. bool Importer::IsExtensionSupported(const char* szExtension) const
  692. {
  693. return NULL != GetImporter(szExtension);
  694. }
  695. // ------------------------------------------------------------------------------------------------
  696. size_t Importer::GetImporterCount() const
  697. {
  698. return pimpl->mImporter.size();
  699. }
  700. // ------------------------------------------------------------------------------------------------
  701. const aiImporterDesc* Importer::GetImporterInfo(size_t index) const
  702. {
  703. if (index >= pimpl->mImporter.size()) {
  704. return NULL;
  705. }
  706. return pimpl->mImporter[index]->GetInfo();
  707. }
  708. // ------------------------------------------------------------------------------------------------
  709. BaseImporter* Importer::GetImporter (size_t index) const
  710. {
  711. if (index >= pimpl->mImporter.size()) {
  712. return NULL;
  713. }
  714. return pimpl->mImporter[index];
  715. }
  716. // ------------------------------------------------------------------------------------------------
  717. // Find a loader plugin for a given file extension
  718. BaseImporter* Importer::GetImporter (const char* szExtension) const
  719. {
  720. return GetImporter(GetImporterIndex(szExtension));
  721. }
  722. // ------------------------------------------------------------------------------------------------
  723. // Find a loader plugin for a given file extension
  724. size_t Importer::GetImporterIndex (const char* szExtension) const
  725. {
  726. ai_assert(szExtension);
  727. ASSIMP_BEGIN_EXCEPTION_REGION();
  728. // skip over wildcard and dot characters at string head --
  729. for(;*szExtension == '*' || *szExtension == '.'; ++szExtension);
  730. std::string ext(szExtension);
  731. if (ext.empty()) {
  732. return static_cast<size_t>(-1);
  733. }
  734. std::transform(ext.begin(),ext.end(), ext.begin(), tolower);
  735. std::set<std::string> str;
  736. for (std::vector<BaseImporter*>::const_iterator i = pimpl->mImporter.begin();i != pimpl->mImporter.end();++i) {
  737. str.clear();
  738. (*i)->GetExtensionList(str);
  739. for (std::set<std::string>::const_iterator it = str.begin(); it != str.end(); ++it) {
  740. if (ext == *it) {
  741. return std::distance(static_cast< std::vector<BaseImporter*>::const_iterator >(pimpl->mImporter.begin()), i);
  742. }
  743. }
  744. }
  745. ASSIMP_END_EXCEPTION_REGION(size_t);
  746. return static_cast<size_t>(-1);
  747. }
  748. // ------------------------------------------------------------------------------------------------
  749. // Helper function to build a list of all file extensions supported by ASSIMP
  750. void Importer::GetExtensionList(aiString& szOut) const
  751. {
  752. ASSIMP_BEGIN_EXCEPTION_REGION();
  753. std::set<std::string> str;
  754. for (std::vector<BaseImporter*>::const_iterator i = pimpl->mImporter.begin();i != pimpl->mImporter.end();++i) {
  755. (*i)->GetExtensionList(str);
  756. }
  757. for (std::set<std::string>::const_iterator it = str.begin();; ) {
  758. szOut.Append("*.");
  759. szOut.Append((*it).c_str());
  760. if (++it == str.end()) {
  761. break;
  762. }
  763. szOut.Append(";");
  764. }
  765. ASSIMP_END_EXCEPTION_REGION(void);
  766. }
  767. // ------------------------------------------------------------------------------------------------
  768. // Set a configuration property
  769. void Importer::SetPropertyInteger(const char* szName, int iValue,
  770. bool* bWasExisting /*= NULL*/)
  771. {
  772. ASSIMP_BEGIN_EXCEPTION_REGION();
  773. SetGenericProperty<int>(pimpl->mIntProperties, szName,iValue,bWasExisting);
  774. ASSIMP_END_EXCEPTION_REGION(void);
  775. }
  776. // ------------------------------------------------------------------------------------------------
  777. // Set a configuration property
  778. void Importer::SetPropertyFloat(const char* szName, float iValue,
  779. bool* bWasExisting /*= NULL*/)
  780. {
  781. ASSIMP_BEGIN_EXCEPTION_REGION();
  782. SetGenericProperty<float>(pimpl->mFloatProperties, szName,iValue,bWasExisting);
  783. ASSIMP_END_EXCEPTION_REGION(void);
  784. }
  785. // ------------------------------------------------------------------------------------------------
  786. // Set a configuration property
  787. void Importer::SetPropertyString(const char* szName, const std::string& value,
  788. bool* bWasExisting /*= NULL*/)
  789. {
  790. ASSIMP_BEGIN_EXCEPTION_REGION();
  791. SetGenericProperty<std::string>(pimpl->mStringProperties, szName,value,bWasExisting);
  792. ASSIMP_END_EXCEPTION_REGION(void);
  793. }
  794. // ------------------------------------------------------------------------------------------------
  795. // Set a configuration property
  796. void Importer::SetPropertyMatrix(const char* szName, const aiMatrix4x4& value,
  797. bool* bWasExisting /*= NULL*/)
  798. {
  799. ASSIMP_BEGIN_EXCEPTION_REGION();
  800. SetGenericProperty<aiMatrix4x4>(pimpl->mMatrixProperties, szName,value,bWasExisting);
  801. ASSIMP_END_EXCEPTION_REGION(void);
  802. }
  803. // ------------------------------------------------------------------------------------------------
  804. // Get a configuration property
  805. int Importer::GetPropertyInteger(const char* szName,
  806. int iErrorReturn /*= 0xffffffff*/) const
  807. {
  808. return GetGenericProperty<int>(pimpl->mIntProperties,szName,iErrorReturn);
  809. }
  810. // ------------------------------------------------------------------------------------------------
  811. // Get a configuration property
  812. float Importer::GetPropertyFloat(const char* szName,
  813. float iErrorReturn /*= 10e10*/) const
  814. {
  815. return GetGenericProperty<float>(pimpl->mFloatProperties,szName,iErrorReturn);
  816. }
  817. // ------------------------------------------------------------------------------------------------
  818. // Get a configuration property
  819. const std::string Importer::GetPropertyString(const char* szName,
  820. const std::string& iErrorReturn /*= ""*/) const
  821. {
  822. return GetGenericProperty<std::string>(pimpl->mStringProperties,szName,iErrorReturn);
  823. }
  824. // ------------------------------------------------------------------------------------------------
  825. // Get a configuration property
  826. const aiMatrix4x4 Importer::GetPropertyMatrix(const char* szName,
  827. const aiMatrix4x4& iErrorReturn /*= aiMatrix4x4()*/) const
  828. {
  829. return GetGenericProperty<aiMatrix4x4>(pimpl->mMatrixProperties,szName,iErrorReturn);
  830. }
  831. // ------------------------------------------------------------------------------------------------
  832. // Get the memory requirements of a single node
  833. inline void AddNodeWeight(unsigned int& iScene,const aiNode* pcNode)
  834. {
  835. iScene += sizeof(aiNode);
  836. iScene += sizeof(unsigned int) * pcNode->mNumMeshes;
  837. iScene += sizeof(void*) * pcNode->mNumChildren;
  838. for (unsigned int i = 0; i < pcNode->mNumChildren;++i) {
  839. AddNodeWeight(iScene,pcNode->mChildren[i]);
  840. }
  841. }
  842. // ------------------------------------------------------------------------------------------------
  843. // Get the memory requirements of the scene
  844. void Importer::GetMemoryRequirements(aiMemoryInfo& in) const
  845. {
  846. in = aiMemoryInfo();
  847. aiScene* mScene = pimpl->mScene;
  848. // return if we have no scene loaded
  849. if (!pimpl->mScene)
  850. return;
  851. in.total = sizeof(aiScene);
  852. // add all meshes
  853. for (unsigned int i = 0; i < mScene->mNumMeshes;++i)
  854. {
  855. in.meshes += sizeof(aiMesh);
  856. if (mScene->mMeshes[i]->HasPositions()) {
  857. in.meshes += sizeof(aiVector3D) * mScene->mMeshes[i]->mNumVertices;
  858. }
  859. if (mScene->mMeshes[i]->HasNormals()) {
  860. in.meshes += sizeof(aiVector3D) * mScene->mMeshes[i]->mNumVertices;
  861. }
  862. if (mScene->mMeshes[i]->HasTangentsAndBitangents()) {
  863. in.meshes += sizeof(aiVector3D) * mScene->mMeshes[i]->mNumVertices * 2;
  864. }
  865. for (unsigned int a = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS;++a) {
  866. if (mScene->mMeshes[i]->HasVertexColors(a)) {
  867. in.meshes += sizeof(aiColor4D) * mScene->mMeshes[i]->mNumVertices;
  868. }
  869. else break;
  870. }
  871. for (unsigned int a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS;++a) {
  872. if (mScene->mMeshes[i]->HasTextureCoords(a)) {
  873. in.meshes += sizeof(aiVector3D) * mScene->mMeshes[i]->mNumVertices;
  874. }
  875. else break;
  876. }
  877. if (mScene->mMeshes[i]->HasBones()) {
  878. in.meshes += sizeof(void*) * mScene->mMeshes[i]->mNumBones;
  879. for (unsigned int p = 0; p < mScene->mMeshes[i]->mNumBones;++p) {
  880. in.meshes += sizeof(aiBone);
  881. in.meshes += mScene->mMeshes[i]->mBones[p]->mNumWeights * sizeof(aiVertexWeight);
  882. }
  883. }
  884. in.meshes += (sizeof(aiFace) + 3 * sizeof(unsigned int))*mScene->mMeshes[i]->mNumFaces;
  885. }
  886. in.total += in.meshes;
  887. // add all embedded textures
  888. for (unsigned int i = 0; i < mScene->mNumTextures;++i) {
  889. const aiTexture* pc = mScene->mTextures[i];
  890. in.textures += sizeof(aiTexture);
  891. if (pc->mHeight) {
  892. in.textures += 4 * pc->mHeight * pc->mWidth;
  893. }
  894. else in.textures += pc->mWidth;
  895. }
  896. in.total += in.textures;
  897. // add all animations
  898. for (unsigned int i = 0; i < mScene->mNumAnimations;++i) {
  899. const aiAnimation* pc = mScene->mAnimations[i];
  900. in.animations += sizeof(aiAnimation);
  901. // add all bone anims
  902. for (unsigned int a = 0; a < pc->mNumChannels; ++a) {
  903. const aiNodeAnim* pc2 = pc->mChannels[i];
  904. in.animations += sizeof(aiNodeAnim);
  905. in.animations += pc2->mNumPositionKeys * sizeof(aiVectorKey);
  906. in.animations += pc2->mNumScalingKeys * sizeof(aiVectorKey);
  907. in.animations += pc2->mNumRotationKeys * sizeof(aiQuatKey);
  908. }
  909. }
  910. in.total += in.animations;
  911. // add all cameras and all lights
  912. in.total += in.cameras = sizeof(aiCamera) * mScene->mNumCameras;
  913. in.total += in.lights = sizeof(aiLight) * mScene->mNumLights;
  914. // add all nodes
  915. AddNodeWeight(in.nodes,mScene->mRootNode);
  916. in.total += in.nodes;
  917. // add all materials
  918. for (unsigned int i = 0; i < mScene->mNumMaterials;++i) {
  919. const aiMaterial* pc = mScene->mMaterials[i];
  920. in.materials += sizeof(aiMaterial);
  921. in.materials += pc->mNumAllocated * sizeof(void*);
  922. for (unsigned int a = 0; a < pc->mNumProperties;++a) {
  923. in.materials += pc->mProperties[a]->mDataLength;
  924. }
  925. }
  926. in.total += in.materials;
  927. }