Importer.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (ASSIMP)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2010, ASSIMP Development 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 Development 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/aiVersion.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. #if defined(ASSIMP_BUILD_X86_32BIT_ARCHITECTURE)
  448. << " x86"
  449. #elif defined(ASSIMP_BUILD_X86_64BIT_ARCHITECTURE)
  450. << " amd64"
  451. #elif defined(ASSIMP_BUILD_IA_64BIT_ARCHITECTURE)
  452. << " itanium"
  453. #elif defined(ASSIMP_BUILD_PPC_32BIT_ARCHITECTURE)
  454. << " ppc32"
  455. #elif defined(ASSIMP_BUILD_ARM_32BIT_ARCHITECTURE)
  456. << " arm"
  457. #else
  458. # error unknown architecture
  459. #endif
  460. #if defined(_MSC_VER)
  461. << " msvc"
  462. #elif defined(__GNUC__)
  463. << " gcc"
  464. #else
  465. # error unknown compiler
  466. #endif
  467. #ifndef NDEBUG
  468. << " debug"
  469. #endif
  470. << (flags & ASSIMP_CFLAGS_NOBOOST ? " noboost" : "")
  471. << (flags & ASSIMP_CFLAGS_SHARED ? " shared" : "")
  472. << (flags & ASSIMP_CFLAGS_SINGLETHREADED ? " singlethreaded" : "")
  473. );
  474. }
  475. // ------------------------------------------------------------------------------------------------
  476. // Reads the given file and returns its contents if successful.
  477. const aiScene* Importer::ReadFile( const char* _pFile, unsigned int pFlags)
  478. {
  479. ASSIMP_BEGIN_EXCEPTION_REGION();
  480. const std::string pFile(_pFile);
  481. // ----------------------------------------------------------------------
  482. // Put a large try block around everything to catch all std::exception's
  483. // that might be thrown by STL containers or by new().
  484. // ImportErrorException's are throw by ourselves and caught elsewhere.
  485. //-----------------------------------------------------------------------
  486. WriteLogOpening(pFile);
  487. #ifdef ASSIMP_CATCH_GLOBAL_EXCEPTIONS
  488. try
  489. #endif // ! ASSIMP_CATCH_GLOBAL_EXCEPTIONS
  490. {
  491. // Check whether this Importer instance has already loaded
  492. // a scene. In this case we need to delete the old one
  493. if (pimpl->mScene) {
  494. DefaultLogger::get()->debug("(Deleting previous scene)");
  495. FreeScene();
  496. }
  497. // First check if the file is accessable at all
  498. if( !pimpl->mIOHandler->Exists( pFile)) {
  499. pimpl->mErrorString = "Unable to open file \"" + pFile + "\".";
  500. DefaultLogger::get()->error(pimpl->mErrorString);
  501. return NULL;
  502. }
  503. boost::scoped_ptr<Profiler> profiler(GetPropertyInteger(AI_CONFIG_GLOB_MEASURE_TIME,0)?new Profiler():NULL);
  504. if (profiler) {
  505. profiler->BeginRegion("total");
  506. }
  507. // Find an worker class which can handle the file
  508. BaseImporter* imp = NULL;
  509. for( unsigned int a = 0; a < pimpl->mImporter.size(); a++) {
  510. if( pimpl->mImporter[a]->CanRead( pFile, pimpl->mIOHandler, false)) {
  511. imp = pimpl->mImporter[a];
  512. break;
  513. }
  514. }
  515. if (!imp) {
  516. // not so bad yet ... try format auto detection.
  517. const std::string::size_type s = pFile.find_last_of('.');
  518. if (s != std::string::npos) {
  519. DefaultLogger::get()->info("File extension not known, trying signature-based detection");
  520. for( unsigned int a = 0; a < pimpl->mImporter.size(); a++) {
  521. if( pimpl->mImporter[a]->CanRead( pFile, pimpl->mIOHandler, true)) {
  522. imp = pimpl->mImporter[a];
  523. break;
  524. }
  525. }
  526. }
  527. // Put a proper error message if no suitable importer was found
  528. if( !imp) {
  529. pimpl->mErrorString = "No suitable reader found for the file format of file \"" + pFile + "\".";
  530. DefaultLogger::get()->error(pimpl->mErrorString);
  531. return NULL;
  532. }
  533. }
  534. // Dispatch the reading to the worker class for this format
  535. DefaultLogger::get()->info("Found a matching importer for this file format");
  536. pimpl->mProgressHandler->Update();
  537. if (profiler) {
  538. profiler->BeginRegion("import");
  539. }
  540. pimpl->mScene = imp->ReadFile( this, pFile, pimpl->mIOHandler);
  541. pimpl->mProgressHandler->Update();
  542. if (profiler) {
  543. profiler->EndRegion("import");
  544. }
  545. // If successful, apply all active post processing steps to the imported data
  546. if( pimpl->mScene) {
  547. #ifndef ASSIMP_BUILD_NO_VALIDATEDS_PROCESS
  548. // The ValidateDS process is an exception. It is executed first, even before ScenePreprocessor is called.
  549. if (pFlags & aiProcess_ValidateDataStructure)
  550. {
  551. ValidateDSProcess ds;
  552. ds.ExecuteOnScene (this);
  553. if (!pimpl->mScene) {
  554. return NULL;
  555. }
  556. }
  557. #endif // no validation
  558. // Preprocess the scene and prepare it for post-processing
  559. if (profiler) {
  560. profiler->BeginRegion("preprocess");
  561. }
  562. ScenePreprocessor pre(pimpl->mScene);
  563. pre.ProcessScene();
  564. pimpl->mProgressHandler->Update();
  565. if (profiler) {
  566. profiler->EndRegion("preprocess");
  567. }
  568. // Ensure that the validation process won't be called twice
  569. ApplyPostProcessing(pFlags & (~aiProcess_ValidateDataStructure));
  570. }
  571. // if failed, extract the error string
  572. else if( !pimpl->mScene) {
  573. pimpl->mErrorString = imp->GetErrorText();
  574. }
  575. // clear any data allocated by post-process steps
  576. pimpl->mPPShared->Clean();
  577. if (profiler) {
  578. profiler->EndRegion("total");
  579. }
  580. }
  581. #ifdef ASSIMP_CATCH_GLOBAL_EXCEPTIONS
  582. catch (std::exception &e)
  583. {
  584. #if (defined _MSC_VER) && (defined _CPPRTTI)
  585. // if we have RTTI get the full name of the exception that occured
  586. pimpl->mErrorString = std::string(typeid( e ).name()) + ": " + e.what();
  587. #else
  588. pimpl->mErrorString = std::string("std::exception: ") + e.what();
  589. #endif
  590. DefaultLogger::get()->error(pimpl->mErrorString);
  591. delete pimpl->mScene; pimpl->mScene = NULL;
  592. }
  593. #endif // ! ASSIMP_CATCH_GLOBAL_EXCEPTIONS
  594. // either successful or failure - the pointer expresses it anyways
  595. ASSIMP_END_EXCEPTION_REGION(const aiScene*);
  596. return pimpl->mScene;
  597. }
  598. // ------------------------------------------------------------------------------------------------
  599. // Apply post-processing to the currently bound scene
  600. const aiScene* Importer::ApplyPostProcessing(unsigned int pFlags)
  601. {
  602. ASSIMP_BEGIN_EXCEPTION_REGION();
  603. // Return immediately if no scene is active
  604. if (!pimpl->mScene) {
  605. return NULL;
  606. }
  607. // If no flags are given, return the current scene with no further action
  608. if (!pFlags) {
  609. return pimpl->mScene;
  610. }
  611. // In debug builds: run basic flag validation
  612. ai_assert(_ValidateFlags(pFlags));
  613. DefaultLogger::get()->info("Entering post processing pipeline");
  614. #ifndef ASSIMP_BUILD_NO_VALIDATEDS_PROCESS
  615. // The ValidateDS process plays an exceptional role. It isn't contained in the global
  616. // list of post-processing steps, so we need to call it manually.
  617. if (pFlags & aiProcess_ValidateDataStructure)
  618. {
  619. ValidateDSProcess ds;
  620. ds.ExecuteOnScene (this);
  621. if (!pimpl->mScene) {
  622. return NULL;
  623. }
  624. }
  625. #endif // no validation
  626. #ifdef _DEBUG
  627. if (pimpl->bExtraVerbose)
  628. {
  629. #ifndef ASSIMP_BUILD_NO_VALIDATEDS_PROCESS
  630. DefaultLogger::get()->error("Verbose Import is not available due to build settings");
  631. #endif // no validation
  632. pFlags |= aiProcess_ValidateDataStructure;
  633. }
  634. #else
  635. if (pimpl->bExtraVerbose) {
  636. DefaultLogger::get()->warn("Not a debug build, ignoring extra verbose setting");
  637. }
  638. #endif // ! DEBUG
  639. boost::scoped_ptr<Profiler> profiler(GetPropertyInteger(AI_CONFIG_GLOB_MEASURE_TIME,0)?new Profiler():NULL);
  640. for( unsigned int a = 0; a < pimpl->mPostProcessingSteps.size(); a++) {
  641. BaseProcess* process = pimpl->mPostProcessingSteps[a];
  642. if( process->IsActive( pFlags)) {
  643. if (profiler) {
  644. profiler->BeginRegion("postprocess");
  645. }
  646. process->ExecuteOnScene ( this );
  647. pimpl->mProgressHandler->Update();
  648. if (profiler) {
  649. profiler->EndRegion("postprocess");
  650. }
  651. }
  652. if( !pimpl->mScene) {
  653. break;
  654. }
  655. #ifdef _DEBUG
  656. #ifndef ASSIMP_BUILD_NO_VALIDATEDS_PROCESS
  657. continue;
  658. #endif // no validation
  659. // If the extra verbose mode is active, execute the ValidateDataStructureStep again - after each step
  660. if (pimpl->bExtraVerbose) {
  661. DefaultLogger::get()->debug("Verbose Import: revalidating data structures");
  662. ValidateDSProcess ds;
  663. ds.ExecuteOnScene (this);
  664. if( !pimpl->mScene) {
  665. DefaultLogger::get()->error("Verbose Import: failed to revalidate data structures");
  666. break;
  667. }
  668. }
  669. #endif // ! DEBUG
  670. }
  671. // update private scene flags
  672. ScenePriv(pimpl->mScene)->mPPStepsApplied |= pFlags;
  673. // clear any data allocated by post-process steps
  674. pimpl->mPPShared->Clean();
  675. DefaultLogger::get()->info("Leaving post processing pipeline");
  676. ASSIMP_END_EXCEPTION_REGION(const aiScene*);
  677. return pimpl->mScene;
  678. }
  679. // ------------------------------------------------------------------------------------------------
  680. // Helper function to check whether an extension is supported by ASSIMP
  681. bool Importer::IsExtensionSupported(const char* szExtension) const
  682. {
  683. return NULL != FindLoader(szExtension);
  684. }
  685. // ------------------------------------------------------------------------------------------------
  686. // Find a loader plugin for a given file extension
  687. BaseImporter* Importer::FindLoader (const char* szExtension) const
  688. {
  689. ai_assert(szExtension);
  690. ASSIMP_BEGIN_EXCEPTION_REGION();
  691. // skip over wildcard and dot characters at string head --
  692. for(;*szExtension == '*' || *szExtension == '.'; ++szExtension);
  693. std::string ext(szExtension);
  694. if (ext.empty()) {
  695. return NULL;
  696. }
  697. std::transform(ext.begin(),ext.end(), ext.begin(), tolower);
  698. std::set<std::string> str;
  699. for (std::vector<BaseImporter*>::const_iterator i = pimpl->mImporter.begin();i != pimpl->mImporter.end();++i) {
  700. str.clear();
  701. (*i)->GetExtensionList(str);
  702. for (std::set<std::string>::const_iterator it = str.begin(); it != str.end(); ++it) {
  703. if (ext == *it) {
  704. return (*i);
  705. }
  706. }
  707. }
  708. ASSIMP_END_EXCEPTION_REGION(BaseImporter*);
  709. return NULL;
  710. }
  711. // ------------------------------------------------------------------------------------------------
  712. // Helper function to build a list of all file extensions supported by ASSIMP
  713. void Importer::GetExtensionList(aiString& szOut) const
  714. {
  715. ASSIMP_BEGIN_EXCEPTION_REGION();
  716. std::set<std::string> str;
  717. for (std::vector<BaseImporter*>::const_iterator i = pimpl->mImporter.begin();i != pimpl->mImporter.end();++i) {
  718. (*i)->GetExtensionList(str);
  719. }
  720. for (std::set<std::string>::const_iterator it = str.begin();; ) {
  721. szOut.Append("*.");
  722. szOut.Append((*it).c_str());
  723. if (++it == str.end()) {
  724. break;
  725. }
  726. szOut.Append(";");
  727. }
  728. ASSIMP_END_EXCEPTION_REGION(void);
  729. }
  730. // ------------------------------------------------------------------------------------------------
  731. // Set a configuration property
  732. void Importer::SetPropertyInteger(const char* szName, int iValue,
  733. bool* bWasExisting /*= NULL*/)
  734. {
  735. ASSIMP_BEGIN_EXCEPTION_REGION();
  736. SetGenericProperty<int>(pimpl->mIntProperties, szName,iValue,bWasExisting);
  737. ASSIMP_END_EXCEPTION_REGION(void);
  738. }
  739. // ------------------------------------------------------------------------------------------------
  740. // Set a configuration property
  741. void Importer::SetPropertyFloat(const char* szName, float iValue,
  742. bool* bWasExisting /*= NULL*/)
  743. {
  744. ASSIMP_BEGIN_EXCEPTION_REGION();
  745. SetGenericProperty<float>(pimpl->mFloatProperties, szName,iValue,bWasExisting);
  746. ASSIMP_END_EXCEPTION_REGION(void);
  747. }
  748. // ------------------------------------------------------------------------------------------------
  749. // Set a configuration property
  750. void Importer::SetPropertyString(const char* szName, const std::string& value,
  751. bool* bWasExisting /*= NULL*/)
  752. {
  753. ASSIMP_BEGIN_EXCEPTION_REGION();
  754. SetGenericProperty<std::string>(pimpl->mStringProperties, szName,value,bWasExisting);
  755. ASSIMP_END_EXCEPTION_REGION(void);
  756. }
  757. // ------------------------------------------------------------------------------------------------
  758. // Get a configuration property
  759. int Importer::GetPropertyInteger(const char* szName,
  760. int iErrorReturn /*= 0xffffffff*/) const
  761. {
  762. return GetGenericProperty<int>(pimpl->mIntProperties,szName,iErrorReturn);
  763. }
  764. // ------------------------------------------------------------------------------------------------
  765. // Get a configuration property
  766. float Importer::GetPropertyFloat(const char* szName,
  767. float iErrorReturn /*= 10e10*/) const
  768. {
  769. return GetGenericProperty<float>(pimpl->mFloatProperties,szName,iErrorReturn);
  770. }
  771. // ------------------------------------------------------------------------------------------------
  772. // Get a configuration property
  773. const std::string& Importer::GetPropertyString(const char* szName,
  774. const std::string& iErrorReturn /*= ""*/) const
  775. {
  776. return GetGenericProperty<std::string>(pimpl->mStringProperties,szName,iErrorReturn);
  777. }
  778. // ------------------------------------------------------------------------------------------------
  779. // Get the memory requirements of a single node
  780. inline void AddNodeWeight(unsigned int& iScene,const aiNode* pcNode)
  781. {
  782. iScene += sizeof(aiNode);
  783. iScene += sizeof(unsigned int) * pcNode->mNumMeshes;
  784. iScene += sizeof(void*) * pcNode->mNumChildren;
  785. for (unsigned int i = 0; i < pcNode->mNumChildren;++i) {
  786. AddNodeWeight(iScene,pcNode->mChildren[i]);
  787. }
  788. }
  789. // ------------------------------------------------------------------------------------------------
  790. // Get the memory requirements of the scene
  791. void Importer::GetMemoryRequirements(aiMemoryInfo& in) const
  792. {
  793. in = aiMemoryInfo();
  794. aiScene* mScene = pimpl->mScene;
  795. // return if we have no scene loaded
  796. if (!pimpl->mScene)
  797. return;
  798. in.total = sizeof(aiScene);
  799. // add all meshes
  800. for (unsigned int i = 0; i < mScene->mNumMeshes;++i)
  801. {
  802. in.meshes += sizeof(aiMesh);
  803. if (mScene->mMeshes[i]->HasPositions()) {
  804. in.meshes += sizeof(aiVector3D) * mScene->mMeshes[i]->mNumVertices;
  805. }
  806. if (mScene->mMeshes[i]->HasNormals()) {
  807. in.meshes += sizeof(aiVector3D) * mScene->mMeshes[i]->mNumVertices;
  808. }
  809. if (mScene->mMeshes[i]->HasTangentsAndBitangents()) {
  810. in.meshes += sizeof(aiVector3D) * mScene->mMeshes[i]->mNumVertices * 2;
  811. }
  812. for (unsigned int a = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS;++a) {
  813. if (mScene->mMeshes[i]->HasVertexColors(a)) {
  814. in.meshes += sizeof(aiColor4D) * mScene->mMeshes[i]->mNumVertices;
  815. }
  816. else break;
  817. }
  818. for (unsigned int a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS;++a) {
  819. if (mScene->mMeshes[i]->HasTextureCoords(a)) {
  820. in.meshes += sizeof(aiVector3D) * mScene->mMeshes[i]->mNumVertices;
  821. }
  822. else break;
  823. }
  824. if (mScene->mMeshes[i]->HasBones()) {
  825. in.meshes += sizeof(void*) * mScene->mMeshes[i]->mNumBones;
  826. for (unsigned int p = 0; p < mScene->mMeshes[i]->mNumBones;++p) {
  827. in.meshes += sizeof(aiBone);
  828. in.meshes += mScene->mMeshes[i]->mBones[p]->mNumWeights * sizeof(aiVertexWeight);
  829. }
  830. }
  831. in.meshes += (sizeof(aiFace) + 3 * sizeof(unsigned int))*mScene->mMeshes[i]->mNumFaces;
  832. }
  833. in.total += in.meshes;
  834. // add all embedded textures
  835. for (unsigned int i = 0; i < mScene->mNumTextures;++i) {
  836. const aiTexture* pc = mScene->mTextures[i];
  837. in.textures += sizeof(aiTexture);
  838. if (pc->mHeight) {
  839. in.textures += 4 * pc->mHeight * pc->mWidth;
  840. }
  841. else in.textures += pc->mWidth;
  842. }
  843. in.total += in.textures;
  844. // add all animations
  845. for (unsigned int i = 0; i < mScene->mNumAnimations;++i) {
  846. const aiAnimation* pc = mScene->mAnimations[i];
  847. in.animations += sizeof(aiAnimation);
  848. // add all bone anims
  849. for (unsigned int a = 0; a < pc->mNumChannels; ++a) {
  850. const aiNodeAnim* pc2 = pc->mChannels[i];
  851. in.animations += sizeof(aiNodeAnim);
  852. in.animations += pc2->mNumPositionKeys * sizeof(aiVectorKey);
  853. in.animations += pc2->mNumScalingKeys * sizeof(aiVectorKey);
  854. in.animations += pc2->mNumRotationKeys * sizeof(aiQuatKey);
  855. }
  856. }
  857. in.total += in.animations;
  858. // add all cameras and all lights
  859. in.total += in.cameras = sizeof(aiCamera) * mScene->mNumCameras;
  860. in.total += in.lights = sizeof(aiLight) * mScene->mNumLights;
  861. // add all nodes
  862. AddNodeWeight(in.nodes,mScene->mRootNode);
  863. in.total += in.nodes;
  864. // add all materials
  865. for (unsigned int i = 0; i < mScene->mNumMaterials;++i) {
  866. const aiMaterial* pc = mScene->mMaterials[i];
  867. in.materials += sizeof(aiMaterial);
  868. in.materials += pc->mNumAllocated * sizeof(void*);
  869. for (unsigned int a = 0; a < pc->mNumProperties;++a) {
  870. in.materials += pc->mProperties[a]->mDataLength;
  871. }
  872. }
  873. in.total += in.materials;
  874. }