BaseImporter.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. /*
  2. Open Asset Import Library (ASSIMP)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2008, ASSIMP Development Team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the ASSIMP team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the ASSIMP Development Team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. /** @file Definition of the base class for all importer worker classes. */
  34. #ifndef INCLUDED_AI_BASEIMPORTER_H
  35. #define INCLUDED_AI_BASEIMPORTER_H
  36. #include <string>
  37. #include "./../include/aiTypes.h"
  38. struct aiScene;
  39. namespace Assimp {
  40. class IOSystem;
  41. class Importer;
  42. // utility to do char4 to uint32 in a portable manner
  43. #define AI_MAKE_MAGIC(string) ((uint32_t)((string[0] << 24) + \
  44. (string[1] << 16) + (string[2] << 8) + string[3]))
  45. // ---------------------------------------------------------------------------
  46. /** FOR IMPORTER PLUGINS ONLY: Simple exception class to be thrown if an
  47. * error occurs while importing. */
  48. class ASSIMP_API ImportErrorException
  49. {
  50. public:
  51. /** Constructor with arguments */
  52. ImportErrorException( const std::string& pErrorText) {
  53. mErrorText = pErrorText;
  54. }
  55. // -------------------------------------------------------------------
  56. /** Returns the error text provided when throwing the exception */
  57. inline const std::string& GetErrorText() const
  58. { return mErrorText; }
  59. private:
  60. std::string mErrorText;
  61. };
  62. //! @cond never
  63. // ---------------------------------------------------------------------------
  64. /** @brief Internal PIMPL implementation for Assimp::Importer
  65. *
  66. * Using this idiom here allows us to drop the dependency from
  67. * std::vector and std::map in the public headers. Furthermore we are dropping
  68. * any STL interface problems caused by mismatching STL settings. All
  69. * size calculation are now done by us, not the app heap. */
  70. class ASSIMP_API ImporterPimpl
  71. {
  72. public:
  73. // Data type to store the key hash
  74. typedef unsigned int KeyType;
  75. // typedefs for our three configuration maps.
  76. // We don't need more, so there is no need for a generic solution
  77. typedef std::map<KeyType, int> IntPropertyMap;
  78. typedef std::map<KeyType, float> FloatPropertyMap;
  79. typedef std::map<KeyType, std::string> StringPropertyMap;
  80. public:
  81. /** IO handler to use for all file accesses. */
  82. IOSystem* mIOHandler;
  83. bool mIsDefaultHandler;
  84. /** Format-specific importer worker objects - one for each format we can read.*/
  85. std::vector<BaseImporter*> mImporter;
  86. /** Post processing steps we can apply at the imported data. */
  87. std::vector<BaseProcess*> mPostProcessingSteps;
  88. /** The imported data, if ReadFile() was successful, NULL otherwise. */
  89. aiScene* mScene;
  90. /** The error description, if there was one. */
  91. std::string mErrorString;
  92. /** List of integer properties */
  93. IntPropertyMap mIntProperties;
  94. /** List of floating-point properties */
  95. FloatPropertyMap mFloatProperties;
  96. /** List of string properties */
  97. StringPropertyMap mStringProperties;
  98. /** Used for testing - extra verbose mode causes the ValidateDataStructure-Step
  99. * to be executed before and after every single postprocess step */
  100. bool bExtraVerbose;
  101. /** Used by post-process steps to share data */
  102. SharedPostProcessInfo* mPPShared;
  103. };
  104. //! @endcond
  105. // ---------------------------------------------------------------------------
  106. /** FOR IMPORTER PLUGINS ONLY: The BaseImporter defines a common interface
  107. * for all importer worker classes.
  108. *
  109. * The interface defines two functions: CanRead() is used to check if the
  110. * importer can handle the format of the given file. If an implementation of
  111. * this function returns true, the importer then calls ReadFile() which
  112. * imports the given file. ReadFile is not overridable, it just calls
  113. * InternReadFile() and catches any ImportErrorException that might occur.
  114. */
  115. class ASSIMP_API BaseImporter
  116. {
  117. friend class Importer;
  118. protected:
  119. /** Constructor to be privately used by #Importer */
  120. BaseImporter();
  121. /** Destructor, private as well */
  122. virtual ~BaseImporter();
  123. public:
  124. // -------------------------------------------------------------------
  125. /** Returns whether the class can handle the format of the given file.
  126. *
  127. * The implementation should be as quick as possible. A check for
  128. * the file extension is enough. If no suitable loader is found with
  129. * this strategy, CanRead() is called again, the 'checkSig' parameter
  130. * set to true this time. Now the implementation is expected to
  131. * perform a full check of the file structure, possibly searching the
  132. * first bytes of the file for magic identifiers or keywords.
  133. *
  134. * @param pFile Path and file name of the file to be examined.
  135. * @param pIOHandler The IO handler to use for accessing any file.
  136. * @param checkSig Set to true if this method is called a second time.
  137. * This time, the implementation may take more time to examine the
  138. * contents of the file to be loaded for magic bytes, keywords, etc
  139. * to be able to load files with unknown/not existent file extensions.
  140. * @return true if the class can read this file, false if not.
  141. */
  142. virtual bool CanRead(
  143. const std::string& pFile,
  144. IOSystem* pIOHandler,
  145. bool checkSig
  146. ) const = 0;
  147. // -------------------------------------------------------------------
  148. /** Imports the given file and returns the imported data.
  149. * If the import succeeds, ownership of the data is transferred to
  150. * the caller. If the import fails, NULL is returned. The function
  151. * takes care that any partially constructed data is destroyed
  152. * beforehand.
  153. *
  154. * @param pFile Path of the file to be imported.
  155. * @param pIOHandler IO-Handler used to open this and possible other files.
  156. * @return The imported data or NULL if failed. If it failed a
  157. * human-readable error description can be retrieved by calling
  158. * GetErrorText()
  159. *
  160. * @note This function is not intended to be overridden. Implement
  161. * InternReadFile() to do the import. If an exception is thrown somewhere
  162. * in InternReadFile(), this function will catch it and transform it into
  163. * a suitable response to the caller.
  164. */
  165. aiScene* ReadFile(
  166. const std::string& pFile,
  167. IOSystem* pIOHandler
  168. );
  169. // -------------------------------------------------------------------
  170. /** Returns the error description of the last error that occured.
  171. * @return A description of the last error that occured. An empty
  172. * string if there was no error.
  173. */
  174. const std::string& GetErrorText() const {
  175. return mErrorText;
  176. }
  177. // -------------------------------------------------------------------
  178. /** Called prior to ReadFile().
  179. * The function is a request to the importer to update its configuration
  180. * basing on the Importer's configuration property list.
  181. * @param pImp Importer instance
  182. */
  183. virtual void SetupProperties(
  184. const Importer* pImp
  185. );
  186. protected:
  187. // -------------------------------------------------------------------
  188. /** Called by Importer::GetExtensionList() for each loaded importer.
  189. * Implementations are expected to insert() all file extensions
  190. * handled by them into the extension set. A loader capable of
  191. * reading certain files with the extension BLA would place the
  192. * string bla (lower-case!) in the output set.
  193. * @param extensions Output set. */
  194. virtual void GetExtensionList(
  195. std::set<std::string>& extensions
  196. ) = 0;
  197. // -------------------------------------------------------------------
  198. /** Imports the given file into the given scene structure. The
  199. * function is expected to throw an ImportErrorException if there is
  200. * an error. If it terminates normally, the data in aiScene is
  201. * expected to be correct. Override this function to implement the
  202. * actual importing.
  203. * <br>
  204. * The output scene must meet the following requirements:<br>
  205. * <ul>
  206. * <li>At least a root node must be there, even if its only purpose
  207. * is to reference one mesh.</li>
  208. * <li>aiMesh::mPrimitiveTypes may be 0. The types of primitives
  209. * in the mesh are determined automatically in this case.</li>
  210. * <li>the vertex data is stored in a pseudo-indexed "verbose" format.
  211. * In fact this means that every vertex that is referenced by
  212. * a face is unique. Or the other way round: a vertex index may
  213. * not occur twice in a single aiMesh.</li>
  214. * <li>aiAnimation::mDuration may be -1. Assimp determines the length
  215. * of the animation automatically in this case as the length of
  216. * the longest animation channel.</li>
  217. * <li>aiMesh::mBitangents may be NULL if tangents and normals are
  218. * given. In this case bitangents are computed as the cross product
  219. * between normal and tangent.</li>
  220. * <li>There needn't be a material. If none is there a default material
  221. * is generated. However, it is recommended practice for loaders
  222. * to generate a default material for yourself that matches the
  223. * default material setting for the file format better than Assimp's
  224. * generic default material. Note that default materials *should*
  225. * be named AI_DEFAULT_MATERIAL_NAME if they're just color-shaded
  226. * or AI_DEFAULT_TEXTURED_MATERIAL_NAME if they define a (dummy)
  227. * texture. </li>
  228. * </ul>
  229. * If the AI_SCENE_FLAGS_INCOMPLETE-Flag is <b>not</b> set:<ul>
  230. * <li> at least one mesh must be there</li>
  231. * <li> there may be no meshes with 0 vertices or faces</li>
  232. * </ul>
  233. * This won't be checked (except by the validation step): Assimp will
  234. * crash if one of the conditions is not met!
  235. *
  236. * @param pFile Path of the file to be imported.
  237. * @param pScene The scene object to hold the imported data.
  238. * NULL is not a valid parameter.
  239. * @param pIOHandler The IO handler to use for any file access.
  240. * NULL is not a valid parameter. */
  241. virtual void InternReadFile(
  242. const std::string& pFile,
  243. aiScene* pScene,
  244. IOSystem* pIOHandler
  245. ) = 0;
  246. public: // static utilities
  247. // -------------------------------------------------------------------
  248. /** A utility for CanRead().
  249. *
  250. * The function searches the header of a file for a specific token
  251. * and returns true if this token is found. This works for text
  252. * files only. There is a rudimentary handling of UNICODE files.
  253. * The comparison is case independent.
  254. *
  255. * @param pIOSystem IO System to work with
  256. * @param file File name of the file
  257. * @param tokens List of tokens to search for
  258. * @param numTokens Size of the token array
  259. * @param searchBytes Number of bytes to be searched for the tokens.
  260. */
  261. static bool SearchFileHeaderForToken(
  262. IOSystem* pIOSystem,
  263. const std::string& file,
  264. const char** tokens,
  265. unsigned int numTokens,
  266. unsigned int searchBytes = 200);
  267. // -------------------------------------------------------------------
  268. /** @brief Check whether a file has a specific file extension
  269. * @param pFile Input file
  270. * @param ext0 Extension to check for. Lowercase characters only, no dot!
  271. * @param ext1 Optional second extension
  272. * @param ext2 Optional third extension
  273. * @note Case-insensitive
  274. */
  275. static bool SimpleExtensionCheck (
  276. const std::string& pFile,
  277. const char* ext0,
  278. const char* ext1 = NULL,
  279. const char* ext2 = NULL);
  280. // -------------------------------------------------------------------
  281. /** @brief Extract file extension from a string
  282. * @param pFile Input file
  283. * @return Extension without trailing dot, all lowercase
  284. */
  285. static std::string GetExtension (
  286. const std::string& pFile);
  287. // -------------------------------------------------------------------
  288. /** @brief Check whether a file starts with one or more magic tokens
  289. * @param pFile Input file
  290. * @param pIOHandler IO system to be used
  291. * @param magic n magic tokens
  292. * @params num Size of magic
  293. * @param offset Offset from file start where tokens are located
  294. * @param Size of one token, in bytes. Maximally 16 bytes.
  295. * @return true if one of the given tokens was found
  296. *
  297. * @note For convinence, the check is also performed for the
  298. * byte-swapped variant of all tokens (big endian). Only for
  299. * tokens of size 2,4.
  300. */
  301. static bool CheckMagicToken(
  302. IOSystem* pIOHandler,
  303. const std::string& pFile,
  304. const void* magic,
  305. unsigned int num,
  306. unsigned int offset = 0,
  307. unsigned int size = 4);
  308. // -------------------------------------------------------------------
  309. /** An utility for all text file loaders. It converts a file to our
  310. * UTF8 character set. Errors are reported, but ignored.
  311. *
  312. * @param data File buffer to be converted to UTF8 data. The buffer
  313. * is resized as appropriate. */
  314. static void ConvertToUTF8(
  315. std::vector<char>& data);
  316. // -------------------------------------------------------------------
  317. /** Utility for text file loaders which copies the contents of the
  318. * file into a memory buffer and converts it to our UTF8
  319. * representation.
  320. * @param stream Stream to read from.
  321. * @param data Output buffer to be resized and filled with the
  322. * converted text file data. The buffer is terminated with
  323. * a binary 0. */
  324. static void TextFileToBuffer(
  325. IOStream* stream,
  326. std::vector<char>& data);
  327. protected:
  328. /** Error description in case there was one. */
  329. std::string mErrorText;
  330. };
  331. struct BatchData;
  332. // ---------------------------------------------------------------------------
  333. /** FOR IMPORTER PLUGINS ONLY: A helper class for the pleasure of importers
  334. * which need to load many extern meshes recursively.
  335. *
  336. * The class uses several threads to load these meshes (or at least it
  337. * could, this has not yet been implemented at the moment).
  338. *
  339. * @note The class may not be used by more than one thread*/
  340. class ASSIMP_API BatchLoader
  341. {
  342. // friend of Importer
  343. public:
  344. //! @cond never
  345. // -------------------------------------------------------------------
  346. /** Wraps a full list of configuration properties for an importer.
  347. * Properties can be set using SetGenericProperty */
  348. struct PropertyMap
  349. {
  350. ImporterPimpl::IntPropertyMap ints;
  351. ImporterPimpl::FloatPropertyMap floats;
  352. ImporterPimpl::StringPropertyMap strings;
  353. bool operator == (const PropertyMap& prop) const {
  354. // fixme: really isocpp? gcc complains
  355. return ints == prop.ints && floats == prop.floats && strings == prop.strings;
  356. }
  357. bool empty () const {
  358. return ints.empty() && floats.empty() && strings.empty();
  359. }
  360. };
  361. //! @endcond
  362. public:
  363. // -------------------------------------------------------------------
  364. /** Construct a batch loader from a given IO system to be used
  365. * to acess external files */
  366. BatchLoader(IOSystem* pIO);
  367. ~BatchLoader();
  368. // -------------------------------------------------------------------
  369. /** Add a new file to the list of files to be loaded.
  370. * @param file File to be loaded
  371. * @param steps Post-processing steps to be executed on the file
  372. * @param map Optional configuration properties
  373. * @return 'Load request channel' - an unique ID that can later
  374. * be used to access the imported file data.
  375. * @see GetImport */
  376. unsigned int AddLoadRequest (
  377. const std::string& file,
  378. unsigned int steps = 0,
  379. const PropertyMap* map = NULL
  380. );
  381. // -------------------------------------------------------------------
  382. /** Get an imported scene.
  383. * This polls the import from the internal request list.
  384. * If an import is requested several times, this function
  385. * can be called several times, too.
  386. *
  387. * @param which LRWC returned by AddLoadRequest().
  388. * @return NULL if there is no scene with this file name
  389. * in the queue of the scene hasn't been loaded yet. */
  390. aiScene* GetImport(
  391. unsigned int which
  392. );
  393. // -------------------------------------------------------------------
  394. /** Waits until all scenes have been loaded. This returns
  395. * immediately if no scenes are queued.*/
  396. void LoadAll();
  397. private:
  398. // No need to have that in the public API ...
  399. BatchData* data;
  400. };
  401. } // end of namespace Assimp
  402. #endif // AI_BASEIMPORTER_H_INC