BaseImporter.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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. /** Simple exception class to be thrown if an error occurs while importing. */
  47. class ASSIMP_API ImportErrorException
  48. {
  49. public:
  50. /** Constructor with arguments */
  51. ImportErrorException( const std::string& pErrorText)
  52. {
  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. // ---------------------------------------------------------------------------
  63. /** @brief Internal PIMPL implementation for Assimp::Importer
  64. *
  65. * Using this idiom here allows us to drop the dependency from
  66. * std::vector and std::map in the public headers. Furthermore we are dropping
  67. * any STL interface problems caused by mismatching STL settings. All
  68. * size calculation are now done by us, not the app heap.
  69. */
  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. // ---------------------------------------------------------------------------
  105. /** The BaseImporter defines a common interface for all importer worker
  106. * classes.
  107. *
  108. * The interface defines two functions: CanRead() is used to check if the
  109. * importer can handle the format of the given file. If an implementation of
  110. * this function returns true, the importer then calls ReadFile() which
  111. * imports the given file. ReadFile is not overridable, it just calls
  112. * InternReadFile() and catches any ImportErrorException that might occur.
  113. */
  114. class ASSIMP_API BaseImporter
  115. {
  116. friend class Importer;
  117. protected:
  118. /** Constructor to be privately used by #Importer */
  119. BaseImporter();
  120. /** Destructor, private as well */
  121. virtual ~BaseImporter();
  122. public:
  123. // -------------------------------------------------------------------
  124. /** Returns whether the class can handle the format of the given file.
  125. *
  126. * The implementation should be as quick as possible. A check for
  127. * the file extension is enough. If no suitable loader is found with
  128. * this strategy, CanRead() is called again, the 'checkSig' parameter
  129. * set to true this time. Now the implementation is expected to
  130. * perform a full check of the file format, possibly searching the
  131. * first bytes of the file for magic identifiers or keywords.
  132. *
  133. * @param pFile Path and file name of the file to be examined.
  134. * @param pIOHandler The IO handler to use for accessing any file.
  135. * @param checkSig Set to true if this method is called a second time.
  136. * This time, the implementation may take more time to examine the
  137. * contents of the file to be loaded for magic bytes, keywords, etc
  138. * to be able to load files with unknown/not existent file extensions.
  139. * @return true if the class can read this file, false if not.
  140. *
  141. * @note Sometimes ASSIMP uses this method to determine whether a
  142. * a given file extension is generally supported. In this case the
  143. * file extension is passed in the pFile parameter, pIOHandler is NULL
  144. */
  145. virtual bool CanRead( const std::string& pFile,
  146. IOSystem* pIOHandler, bool checkSig) 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( const std::string& pFile, IOSystem* pIOHandler);
  166. // -------------------------------------------------------------------
  167. /** Returns the error description of the last error that occured.
  168. * @return A description of the last error that occured. An empty
  169. * string if there was no error.
  170. */
  171. const std::string& GetErrorText() const {
  172. return mErrorText;
  173. }
  174. // -------------------------------------------------------------------
  175. /** Called prior to ReadFile().
  176. * The function is a request to the importer to update its configuration
  177. * basing on the Importer's configuration property list.
  178. * @param pImp Importer instance
  179. * @param ppFlags Post-processing steps to be executed on the data
  180. * returned by the loaders. This value is provided to allow some
  181. * internal optimizations.
  182. */
  183. virtual void SetupProperties(const Importer* pImp /*,
  184. unsigned int ppFlags*/);
  185. protected:
  186. // -------------------------------------------------------------------
  187. /** Called by Importer::GetExtensionList() for each loaded importer.
  188. * Importer implementations should append all file extensions
  189. * which they supported to the passed string.
  190. * Example: "*.blabb;*.quak;*.gug;*.foo" (no delimiter after the last!)
  191. * @param append Output string
  192. */
  193. virtual void GetExtensionList(std::string& append) = 0;
  194. // -------------------------------------------------------------------
  195. /** Imports the given file into the given scene structure. The
  196. * function is expected to throw an ImportErrorException if there is
  197. * an error. If it terminates normally, the data in aiScene is
  198. * expected to be correct. Override this function to implement the
  199. * actual importing.
  200. * <br>
  201. * The output scene must meet the following requirements:<br>
  202. * <ul>
  203. * <li>At least a root node must be there, even if its only purpose
  204. * is to reference one mesh.</li>
  205. * <li>aiMesh::mPrimitiveTypes may be 0. The types of primitives
  206. * in the mesh are determined automatically in this case.</li>
  207. * <li>the vertex data is stored in a pseudo-indexed "verbose" format.
  208. * In fact this means that every vertex that is referenced by
  209. * a face is unique. Or the other way round: a vertex index may
  210. * not occur twice in a single aiMesh.</li>
  211. * <li>aiAnimation::mDuration may be -1. Assimp determines the length
  212. * of the animation automatically in this case as the length of
  213. * the longest animation channel.</li>
  214. * <li>aiMesh::mBitangents may be NULL if tangents and normals are
  215. * given. In this case bitangents are computed as the cross product
  216. * between normal and tangent.</li>
  217. * <li>There needn't be a material. If none is there a default material
  218. * is generated. However, it is recommended practice for loaders
  219. * to generate a default material for yourself that matches the
  220. * default material setting for the file format better than Assimp's
  221. * generic default material. Note that default materials *should*
  222. * be named AI_DEFAULT_MATERIAL_NAME if they're just color-shaded
  223. * or AI_DEFAULT_TEXTURED_MATERIAL_NAME if they define a (dummy)
  224. * texture. </li>
  225. * </ul>
  226. * If the AI_SCENE_FLAGS_INCOMPLETE-Flag is <b>not</b> set:<ul>
  227. * <li> at least one mesh must be there</li>
  228. * <li> there may be no meshes with 0 vertices or faces</li>
  229. * </ul>
  230. * This won't be checked (except by the validation step): Assimp will
  231. * crash if one of the conditions is not met!
  232. *
  233. * @param pFile Path of the file to be imported.
  234. * @param pScene The scene object to hold the imported data.
  235. * NULL is not a valid parameter.
  236. * @param pIOHandler The IO handler to use for any file access.
  237. * NULL is not a valid parameter.
  238. */
  239. virtual void InternReadFile( const std::string& pFile,
  240. aiScene* pScene, IOSystem* pIOHandler) = 0;
  241. // -------------------------------------------------------------------
  242. /** A utility for CanRead().
  243. *
  244. * The function searches the header of a file for a specific token
  245. * and returns true if this token is found. This works for text
  246. * files only. There is a rudimentary handling of UNICODE files.
  247. * The comparison is case independent.
  248. *
  249. * @param pIOSystem IO System to work with
  250. * @param file File name of the file
  251. * @param tokens List of tokens to search for
  252. * @param numTokens Size of the token array
  253. * @param searchBytes Number of bytes to be searched for the tokens.
  254. */
  255. static bool SearchFileHeaderForToken(IOSystem* pIOSystem,
  256. const std::string& file,
  257. const char** tokens,
  258. unsigned int numTokens,
  259. unsigned int searchBytes = 200);
  260. // -------------------------------------------------------------------
  261. /** @brief Check whether a file has a specific file extension
  262. * @param pFile Input file
  263. * @param ext0 Extension to check for. Lowercase characters only, no dot!
  264. * @param ext1 Optional second extension
  265. * @param ext2 Optional third extension
  266. * @note Case-insensitive
  267. */
  268. static bool SimpleExtensionCheck (const std::string& pFile,
  269. const char* ext0,
  270. const char* ext1 = NULL,
  271. const char* ext2 = NULL);
  272. // -------------------------------------------------------------------
  273. /** @brief Extract file extension from a string
  274. * @param pFile Input file
  275. * @return Extension without trailing dot, all lowercase
  276. */
  277. static std::string GetExtension (const std::string& pFile);
  278. // -------------------------------------------------------------------
  279. /** @brief Check whether a file starts with one or more magic tokens
  280. * @param pFile Input file
  281. * @param pIOHandler IO system to be used
  282. * @param magic n magic tokens
  283. * @params num Size of magic
  284. * @param offset Offset from file start where tokens are located
  285. * @param Size of one token, in bytes. Maximally 16 bytes.
  286. * @return true if one of the given tokens was found
  287. *
  288. * @note For convinence, the check is also performed for the
  289. * byte-swapped variant of all tokens (big endian). Only for
  290. * tokens of size 2,4.
  291. */
  292. static bool CheckMagicToken(IOSystem* pIOHandler, const std::string& pFile,
  293. const void* magic,
  294. unsigned int num,
  295. unsigned int offset = 0,
  296. unsigned int size = 4);
  297. #if 0 /** TODO **/
  298. // -------------------------------------------------------------------
  299. /** An utility for all text file loaders. It converts a file to our
  300. * ASCII/UTF8 character set. Special unicode characters are lost.
  301. *
  302. * @param buffer Input buffer. Needn't be terminated with zero.
  303. * @param length Length of the input buffer, in bytes. Receives the
  304. * number of output characters, excluding the terminal char.
  305. * @return true if the source format did not match our internal
  306. * format so it was converted.
  307. */
  308. static bool ConvertToUTF8(const char* buffer,
  309. unsigned int& length);
  310. #endif
  311. protected:
  312. /** Error description in case there was one. */
  313. std::string mErrorText;
  314. };
  315. struct BatchData;
  316. // ---------------------------------------------------------------------------
  317. /** A helper class that can be used by importers which need to load many
  318. * extern meshes recursively.
  319. *
  320. * The class uses several threads to load these meshes (or at least it
  321. * could, this has not yet been implemented at the moment).
  322. *
  323. * @note The class may not be used by more than one thread
  324. */
  325. class ASSIMP_API BatchLoader
  326. {
  327. // friend of Importer
  328. public:
  329. /** Represents a full list of configuration properties
  330. * for the importer.
  331. *
  332. * Properties can be set using SetGenericProperty
  333. */
  334. struct PropertyMap
  335. {
  336. ImporterPimpl::IntPropertyMap ints;
  337. ImporterPimpl::FloatPropertyMap floats;
  338. ImporterPimpl::StringPropertyMap strings;
  339. bool operator == (const PropertyMap& prop) const {
  340. // fixme: really isocpp? gcc complains
  341. return ints == prop.ints && floats == prop.floats && strings == prop.strings;
  342. }
  343. bool empty () const {
  344. return ints.empty() && floats.empty() && strings.empty();
  345. }
  346. };
  347. public:
  348. /** Construct a batch loader from a given IO system
  349. */
  350. BatchLoader(IOSystem* pIO);
  351. ~BatchLoader();
  352. /** Add a new file to the list of files to be loaded.
  353. *
  354. * @param file File to be loaded
  355. * @param steps Steps to be executed on the file
  356. * @param map Optional configuration properties
  357. * @return 'Load request channel' - an unique ID that can later
  358. * be used to access the imported file data.
  359. */
  360. unsigned int AddLoadRequest (const std::string& file,
  361. unsigned int steps = 0, const PropertyMap* map = NULL);
  362. /** Get an imported scene.
  363. *
  364. * This polls the import from the internal request list.
  365. * If an import is requested several times, this function
  366. * can be called several times, too.
  367. *
  368. * @param which LRWC returned by AddLoadRequest().
  369. * @return NULL if there is no scene with this file name
  370. * in the queue of the scene hasn't been loaded yet.
  371. */
  372. aiScene* GetImport (unsigned int which);
  373. /** Waits until all scenes have been loaded.
  374. */
  375. void LoadAll();
  376. private:
  377. // No need to have that in the public API ...
  378. BatchData* data;
  379. };
  380. } // end of namespace Assimp
  381. #endif // AI_BASEIMPORTER_H_INC