BaseImporter.cpp 20 KB

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