BaseImporter.cpp 15 KB

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