BaseImporter.cpp 16 KB

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