BaseImporter.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2016, 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 BaseImporter.cpp
  35. * @brief Implementation of BaseImporter
  36. */
  37. #include "BaseImporter.h"
  38. #include "FileSystemFilter.h"
  39. #include "Importer.h"
  40. #include "ByteSwapper.h"
  41. #include <assimp/scene.h>
  42. #include <assimp/Importer.hpp>
  43. #include <assimp/postprocess.h>
  44. #include <ios>
  45. #include <list>
  46. #include <memory>
  47. #include <sstream>
  48. #include <cctype>
  49. using namespace Assimp;
  50. // ------------------------------------------------------------------------------------------------
  51. // Constructor to be privately used by Importer
  52. BaseImporter::BaseImporter()
  53. : m_progress()
  54. {
  55. // nothing to do here
  56. }
  57. // ------------------------------------------------------------------------------------------------
  58. // Destructor, private as well
  59. BaseImporter::~BaseImporter()
  60. {
  61. // nothing to do here
  62. }
  63. // ------------------------------------------------------------------------------------------------
  64. // Imports the given file and returns the imported data.
  65. aiScene* BaseImporter::ReadFile(const Importer* pImp, const std::string& pFile, IOSystem* pIOHandler)
  66. {
  67. m_progress = pImp->GetProgressHandler();
  68. ai_assert(m_progress);
  69. // Gather configuration properties for this run
  70. SetupProperties( pImp );
  71. // Construct a file system filter to improve our success ratio at reading external files
  72. FileSystemFilter filter(pFile,pIOHandler);
  73. // create a scene object to hold the data
  74. ScopeGuard<aiScene> sc(new aiScene());
  75. // dispatch importing
  76. try
  77. {
  78. InternReadFile( pFile, sc, &filter);
  79. } catch( const std::exception& err ) {
  80. // extract error description
  81. m_ErrorText = err.what();
  82. DefaultLogger::get()->error(m_ErrorText);
  83. return NULL;
  84. }
  85. // return what we gathered from the import.
  86. sc.dismiss();
  87. return sc;
  88. }
  89. // ------------------------------------------------------------------------------------------------
  90. void BaseImporter::SetupProperties(const Importer* /*pImp*/)
  91. {
  92. // the default implementation does nothing
  93. }
  94. // ------------------------------------------------------------------------------------------------
  95. void BaseImporter::GetExtensionList(std::set<std::string>& extensions)
  96. {
  97. const aiImporterDesc* desc = GetInfo();
  98. ai_assert(desc != NULL);
  99. const char* ext = desc->mFileExtensions;
  100. ai_assert(ext != NULL);
  101. const char* last = ext;
  102. do {
  103. if (!*ext || *ext == ' ') {
  104. extensions.insert(std::string(last,ext-last));
  105. ai_assert(ext-last > 0);
  106. last = ext;
  107. while(*last == ' ') {
  108. ++last;
  109. }
  110. }
  111. }
  112. while(*ext++);
  113. }
  114. // ------------------------------------------------------------------------------------------------
  115. /*static*/ bool BaseImporter::SearchFileHeaderForToken( IOSystem* pIOHandler,
  116. const std::string& pFile,
  117. const char** tokens,
  118. unsigned int numTokens,
  119. unsigned int searchBytes /* = 200 */,
  120. bool tokensSol /* false */)
  121. {
  122. ai_assert( NULL != tokens );
  123. ai_assert( 0 != numTokens );
  124. ai_assert( 0 != searchBytes);
  125. if (!pIOHandler)
  126. return false;
  127. std::unique_ptr<IOStream> pStream (pIOHandler->Open(pFile));
  128. if (pStream.get() ) {
  129. // read 200 characters from the file
  130. std::unique_ptr<char[]> _buffer (new char[searchBytes+1 /* for the '\0' */]);
  131. char* buffer = _buffer.get();
  132. if( NULL == buffer ) {
  133. return false;
  134. }
  135. const size_t read = pStream->Read(buffer,1,searchBytes);
  136. if( !read ) {
  137. return false;
  138. }
  139. for( size_t i = 0; i < read; ++i ) {
  140. buffer[ i ] = ::tolower( buffer[ i ] );
  141. }
  142. // It is not a proper handling of unicode files here ...
  143. // ehm ... but it works in most cases.
  144. char* cur = buffer,*cur2 = buffer,*end = &buffer[read];
  145. while (cur != end) {
  146. if( *cur ) {
  147. *cur2++ = *cur;
  148. }
  149. ++cur;
  150. }
  151. *cur2 = '\0';
  152. for (unsigned int i = 0; i < numTokens;++i) {
  153. ai_assert(NULL != tokens[i]);
  154. const char* r = strstr(buffer,tokens[i]);
  155. if( !r ) {
  156. continue;
  157. }
  158. // We got a match, either we don't care where it is, or it happens to
  159. // be in the beginning of the file / line
  160. if (!tokensSol || r == buffer || r[-1] == '\r' || r[-1] == '\n') {
  161. DefaultLogger::get()->debug(std::string("Found positive match for header keyword: ") + tokens[i]);
  162. return true;
  163. }
  164. }
  165. }
  166. return false;
  167. }
  168. // ------------------------------------------------------------------------------------------------
  169. // Simple check for file extension
  170. /*static*/ bool BaseImporter::SimpleExtensionCheck (const std::string& pFile,
  171. const char* ext0,
  172. const char* ext1,
  173. const char* ext2)
  174. {
  175. std::string::size_type pos = pFile.find_last_of('.');
  176. // no file extension - can't read
  177. if( pos == std::string::npos)
  178. return false;
  179. const char* ext_real = & pFile[ pos+1 ];
  180. if( !ASSIMP_stricmp(ext_real,ext0) )
  181. return true;
  182. // check for other, optional, file extensions
  183. if (ext1 && !ASSIMP_stricmp(ext_real,ext1))
  184. return true;
  185. if (ext2 && !ASSIMP_stricmp(ext_real,ext2))
  186. return true;
  187. return false;
  188. }
  189. // ------------------------------------------------------------------------------------------------
  190. // Get file extension from path
  191. /*static*/ std::string BaseImporter::GetExtension (const std::string& pFile)
  192. {
  193. std::string::size_type pos = pFile.find_last_of('.');
  194. // no file extension at all
  195. if( pos == std::string::npos)
  196. return "";
  197. std::string ret = pFile.substr(pos+1);
  198. std::transform(ret.begin(),ret.end(),ret.begin(),::tolower); // thanks to Andy Maloney for the hint
  199. return ret;
  200. }
  201. // ------------------------------------------------------------------------------------------------
  202. // Check for magic bytes at the beginning of the file.
  203. /* static */ bool BaseImporter::CheckMagicToken(IOSystem* pIOHandler, const std::string& pFile,
  204. const void* _magic, unsigned int num, unsigned int offset, unsigned int size)
  205. {
  206. ai_assert(size <= 16 && _magic);
  207. if (!pIOHandler) {
  208. return false;
  209. }
  210. union {
  211. const char* magic;
  212. const uint16_t* magic_u16;
  213. const uint32_t* magic_u32;
  214. };
  215. magic = reinterpret_cast<const char*>(_magic);
  216. std::unique_ptr<IOStream> pStream (pIOHandler->Open(pFile));
  217. if (pStream.get() ) {
  218. // skip to offset
  219. pStream->Seek(offset,aiOrigin_SET);
  220. // read 'size' characters from the file
  221. union {
  222. char data[16];
  223. uint16_t data_u16[8];
  224. uint32_t data_u32[4];
  225. };
  226. if(size != pStream->Read(data,1,size)) {
  227. return false;
  228. }
  229. for (unsigned int i = 0; i < num; ++i) {
  230. // also check against big endian versions of tokens with size 2,4
  231. // that's just for convenience, the chance that we cause conflicts
  232. // is quite low and it can save some lines and prevent nasty bugs
  233. if (2 == size) {
  234. uint16_t rev = *magic_u16;
  235. ByteSwap::Swap(&rev);
  236. if (data_u16[0] == *magic_u16 || data_u16[0] == rev) {
  237. return true;
  238. }
  239. }
  240. else if (4 == size) {
  241. uint32_t rev = *magic_u32;
  242. ByteSwap::Swap(&rev);
  243. if (data_u32[0] == *magic_u32 || data_u32[0] == rev) {
  244. return true;
  245. }
  246. }
  247. else {
  248. // any length ... just compare
  249. if(!memcmp(magic,data,size)) {
  250. return true;
  251. }
  252. }
  253. magic += size;
  254. }
  255. }
  256. return false;
  257. }
  258. #include "../contrib/ConvertUTF/ConvertUTF.h"
  259. // ------------------------------------------------------------------------------------------------
  260. void ReportResult(ConversionResult res)
  261. {
  262. if(res == sourceExhausted) {
  263. DefaultLogger::get()->error("Source ends with incomplete character sequence, transformation to UTF-8 fails");
  264. }
  265. else if(res == sourceIllegal) {
  266. DefaultLogger::get()->error("Source contains illegal character sequence, transformation to UTF-8 fails");
  267. }
  268. }
  269. // ------------------------------------------------------------------------------------------------
  270. // Convert to UTF8 data
  271. void BaseImporter::ConvertToUTF8(std::vector<char>& data)
  272. {
  273. ConversionResult result;
  274. if(data.size() < 8) {
  275. throw DeadlyImportError("File is too small");
  276. }
  277. // UTF 8 with BOM
  278. if((uint8_t)data[0] == 0xEF && (uint8_t)data[1] == 0xBB && (uint8_t)data[2] == 0xBF) {
  279. DefaultLogger::get()->debug("Found UTF-8 BOM ...");
  280. std::copy(data.begin()+3,data.end(),data.begin());
  281. data.resize(data.size()-3);
  282. return;
  283. }
  284. // UTF 32 BE with BOM
  285. if(*((uint32_t*)&data.front()) == 0xFFFE0000) {
  286. // swap the endianness ..
  287. for(uint32_t* p = (uint32_t*)&data.front(), *end = (uint32_t*)&data.back(); p <= end; ++p) {
  288. AI_SWAP4P(p);
  289. }
  290. }
  291. // UTF 32 LE with BOM
  292. if(*((uint32_t*)&data.front()) == 0x0000FFFE) {
  293. DefaultLogger::get()->debug("Found UTF-32 BOM ...");
  294. const uint32_t* sstart = (uint32_t*)&data.front()+1, *send = (uint32_t*)&data.back()+1;
  295. char* dstart,*dend;
  296. std::vector<char> output;
  297. do {
  298. output.resize(output.size()?output.size()*3/2:data.size()/2);
  299. dstart = &output.front(),dend = &output.back()+1;
  300. result = ConvertUTF32toUTF8((const UTF32**)&sstart,(const UTF32*)send,(UTF8**)&dstart,(UTF8*)dend,lenientConversion);
  301. } while(result == targetExhausted);
  302. ReportResult(result);
  303. // copy to output buffer.
  304. const size_t outlen = (size_t)(dstart-&output.front());
  305. data.assign(output.begin(),output.begin()+outlen);
  306. return;
  307. }
  308. // UTF 16 BE with BOM
  309. if(*((uint16_t*)&data.front()) == 0xFFFE) {
  310. // swap the endianness ..
  311. for(uint16_t* p = (uint16_t*)&data.front(), *end = (uint16_t*)&data.back(); p <= end; ++p) {
  312. ByteSwap::Swap2(p);
  313. }
  314. }
  315. // UTF 16 LE with BOM
  316. if(*((uint16_t*)&data.front()) == 0xFEFF) {
  317. DefaultLogger::get()->debug("Found UTF-16 BOM ...");
  318. const uint16_t* sstart = (uint16_t*)&data.front()+1, *send = (uint16_t*)(&data.back()+1);
  319. char* dstart,*dend;
  320. std::vector<char> output;
  321. do {
  322. output.resize(output.size()?output.size()*3/2:data.size()*3/4);
  323. dstart = &output.front(),dend = &output.back()+1;
  324. result = ConvertUTF16toUTF8((const UTF16**)&sstart,(const UTF16*)send,(UTF8**)&dstart,(UTF8*)dend,lenientConversion);
  325. } while(result == targetExhausted);
  326. ReportResult(result);
  327. // copy to output buffer.
  328. const size_t outlen = (size_t)(dstart-&output.front());
  329. data.assign(output.begin(),output.begin()+outlen);
  330. return;
  331. }
  332. }
  333. // ------------------------------------------------------------------------------------------------
  334. // Convert to UTF8 data to ISO-8859-1
  335. void BaseImporter::ConvertUTF8toISO8859_1(std::string& data)
  336. {
  337. size_t size = data.size();
  338. size_t i = 0, j = 0;
  339. while(i < size) {
  340. if ((unsigned char) data[i] < (size_t) 0x80) {
  341. data[j] = data[i];
  342. } else if(i < size - 1) {
  343. if((unsigned char) data[i] == 0xC2) {
  344. data[j] = data[++i];
  345. } else if((unsigned char) data[i] == 0xC3) {
  346. data[j] = ((unsigned char) data[++i] + 0x40);
  347. } else {
  348. std::stringstream stream;
  349. stream << "UTF8 code " << std::hex << data[i] << data[i + 1] << " can not be converted into ISA-8859-1.";
  350. DefaultLogger::get()->error(stream.str());
  351. data[j++] = data[i++];
  352. data[j] = data[i];
  353. }
  354. } else {
  355. DefaultLogger::get()->error("UTF8 code but only one character remaining");
  356. data[j] = data[i];
  357. }
  358. i++; j++;
  359. }
  360. data.resize(j);
  361. }
  362. // ------------------------------------------------------------------------------------------------
  363. void BaseImporter::TextFileToBuffer(IOStream* stream,
  364. std::vector<char>& data,
  365. TextFileMode mode)
  366. {
  367. ai_assert(NULL != stream);
  368. const size_t fileSize = stream->FileSize();
  369. if (mode == FORBID_EMPTY) {
  370. if(!fileSize) {
  371. throw DeadlyImportError("File is empty");
  372. }
  373. }
  374. data.reserve(fileSize+1);
  375. data.resize(fileSize);
  376. if(fileSize > 0) {
  377. if(fileSize != stream->Read( &data[0], 1, fileSize)) {
  378. throw DeadlyImportError("File read error");
  379. }
  380. ConvertToUTF8(data);
  381. }
  382. // append a binary zero to simplify string parsing
  383. data.push_back(0);
  384. }
  385. // ------------------------------------------------------------------------------------------------
  386. namespace Assimp {
  387. // Represents an import request
  388. struct LoadRequest {
  389. LoadRequest(const std::string& _file, unsigned int _flags,const BatchLoader::PropertyMap* _map, unsigned int _id)
  390. : file(_file)
  391. , flags(_flags)
  392. , refCnt(1)
  393. , scene(NULL)
  394. , loaded(false)
  395. , id(_id) {
  396. if ( _map ) {
  397. map = *_map;
  398. }
  399. }
  400. bool operator== ( const std::string& f ) const {
  401. return file == f;
  402. }
  403. const std::string file;
  404. unsigned int flags;
  405. unsigned int refCnt;
  406. aiScene *scene;
  407. bool loaded;
  408. BatchLoader::PropertyMap map;
  409. unsigned int id;
  410. };
  411. }
  412. // ------------------------------------------------------------------------------------------------
  413. // BatchLoader::pimpl data structure
  414. struct Assimp::BatchData {
  415. BatchData( IOSystem* pIO, bool validate )
  416. : pIOSystem( pIO )
  417. , pImporter( nullptr )
  418. , next_id(0xffff)
  419. , validate( validate ) {
  420. ai_assert( NULL != pIO );
  421. pImporter = new Importer();
  422. pImporter->SetIOHandler( pIO );
  423. }
  424. ~BatchData() {
  425. pImporter->SetIOHandler( NULL ); /* get pointer back into our possession */
  426. delete pImporter;
  427. }
  428. // IO system to be used for all imports
  429. IOSystem* pIOSystem;
  430. // Importer used to load all meshes
  431. Importer* pImporter;
  432. // List of all imports
  433. std::list<LoadRequest> requests;
  434. // Base path
  435. std::string pathBase;
  436. // Id for next item
  437. unsigned int next_id;
  438. // Validation enabled state
  439. bool validate;
  440. };
  441. typedef std::list<LoadRequest>::iterator LoadReqIt;
  442. // ------------------------------------------------------------------------------------------------
  443. BatchLoader::BatchLoader(IOSystem* pIO, bool validate )
  444. {
  445. ai_assert(NULL != pIO);
  446. m_data = new BatchData( pIO, validate );
  447. }
  448. // ------------------------------------------------------------------------------------------------
  449. BatchLoader::~BatchLoader()
  450. {
  451. // delete all scenes what have not been polled by the user
  452. for ( LoadReqIt it = m_data->requests.begin();it != m_data->requests.end(); ++it) {
  453. delete (*it).scene;
  454. }
  455. delete m_data;
  456. }
  457. // ------------------------------------------------------------------------------------------------
  458. void BatchLoader::setValidation( bool enabled ) {
  459. m_data->validate = enabled;
  460. }
  461. // ------------------------------------------------------------------------------------------------
  462. bool BatchLoader::getValidation() const {
  463. return m_data->validate;
  464. }
  465. // ------------------------------------------------------------------------------------------------
  466. unsigned int BatchLoader::AddLoadRequest(const std::string& file,
  467. unsigned int steps /*= 0*/, const PropertyMap* map /*= NULL*/)
  468. {
  469. ai_assert(!file.empty());
  470. // check whether we have this loading request already
  471. for ( LoadReqIt it = m_data->requests.begin();it != m_data->requests.end(); ++it) {
  472. // Call IOSystem's path comparison function here
  473. if ( m_data->pIOSystem->ComparePaths((*it).file,file)) {
  474. if (map) {
  475. if ( !( ( *it ).map == *map ) ) {
  476. continue;
  477. }
  478. }
  479. else if ( !( *it ).map.empty() ) {
  480. continue;
  481. }
  482. (*it).refCnt++;
  483. return (*it).id;
  484. }
  485. }
  486. // no, we don't have it. So add it to the queue ...
  487. m_data->requests.push_back(LoadRequest(file,steps,map, m_data->next_id));
  488. return m_data->next_id++;
  489. }
  490. // ------------------------------------------------------------------------------------------------
  491. aiScene* BatchLoader::GetImport( unsigned int which )
  492. {
  493. for ( LoadReqIt it = m_data->requests.begin();it != m_data->requests.end(); ++it) {
  494. if ((*it).id == which && (*it).loaded) {
  495. aiScene* sc = (*it).scene;
  496. if (!(--(*it).refCnt)) {
  497. m_data->requests.erase(it);
  498. }
  499. return sc;
  500. }
  501. }
  502. return NULL;
  503. }
  504. // ------------------------------------------------------------------------------------------------
  505. void BatchLoader::LoadAll()
  506. {
  507. // no threaded implementation for the moment
  508. for ( LoadReqIt it = m_data->requests.begin();it != m_data->requests.end(); ++it) {
  509. // force validation in debug builds
  510. unsigned int pp = (*it).flags;
  511. if ( m_data->validate ) {
  512. pp |= aiProcess_ValidateDataStructure;
  513. }
  514. // setup config properties if necessary
  515. ImporterPimpl* pimpl = m_data->pImporter->Pimpl();
  516. pimpl->mFloatProperties = (*it).map.floats;
  517. pimpl->mIntProperties = (*it).map.ints;
  518. pimpl->mStringProperties = (*it).map.strings;
  519. pimpl->mMatrixProperties = (*it).map.matrices;
  520. if (!DefaultLogger::isNullLogger())
  521. {
  522. DefaultLogger::get()->info("%%% BEGIN EXTERNAL FILE %%%");
  523. DefaultLogger::get()->info("File: " + (*it).file);
  524. }
  525. m_data->pImporter->ReadFile((*it).file,pp);
  526. (*it).scene = m_data->pImporter->GetOrphanedScene();
  527. (*it).loaded = true;
  528. DefaultLogger::get()->info("%%% END EXTERNAL FILE %%%");
  529. }
  530. }