OFFLoader.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2024, 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 OFFLoader.cpp
  35. * @brief Implementation of the OFF importer class
  36. */
  37. #ifndef ASSIMP_BUILD_NO_OFF_IMPORTER
  38. // internal headers
  39. #include "OFFLoader.h"
  40. #include <assimp/ParsingUtils.h>
  41. #include <assimp/fast_atof.h>
  42. #include <memory>
  43. #include <assimp/IOSystem.hpp>
  44. #include <assimp/scene.h>
  45. #include <assimp/DefaultLogger.hpp>
  46. #include <assimp/importerdesc.h>
  47. namespace Assimp {
  48. static constexpr aiImporterDesc desc = {
  49. "OFF Importer",
  50. "",
  51. "",
  52. "",
  53. aiImporterFlags_SupportBinaryFlavour,
  54. 0,
  55. 0,
  56. 0,
  57. 0,
  58. "off"
  59. };
  60. // ------------------------------------------------------------------------------------------------
  61. // Returns whether the class can handle the format of the given file.
  62. bool OFFImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool /*checkSig*/) const {
  63. static const char *tokens[] = { "off" };
  64. return SearchFileHeaderForToken(pIOHandler, pFile, tokens, AI_COUNT_OF(tokens), 3);
  65. }
  66. // ------------------------------------------------------------------------------------------------
  67. const aiImporterDesc *OFFImporter::GetInfo() const {
  68. return &desc;
  69. }
  70. // skip blank space, lines and comments
  71. static void NextToken(const char **car, const char *end) {
  72. SkipSpacesAndLineEnd(car, end);
  73. while (*car < end && (**car == '#' || **car == '\n' || **car == '\r')) {
  74. SkipLine(car, end);
  75. SkipSpacesAndLineEnd(car, end);
  76. }
  77. }
  78. // ------------------------------------------------------------------------------------------------
  79. // Imports the given file into the given scene structure.
  80. void OFFImporter::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler) {
  81. std::unique_ptr<IOStream> file(pIOHandler->Open(pFile, "rb"));
  82. // Check whether we can read from the file
  83. if (file == nullptr) {
  84. throw DeadlyImportError("Failed to open OFF file ", pFile, ".");
  85. }
  86. // allocate storage and copy the contents of the file to a memory buffer
  87. std::vector<char> mBuffer2;
  88. TextFileToBuffer(file.get(), mBuffer2);
  89. const char *buffer = &mBuffer2[0];
  90. // Proper OFF header parser. We only implement normal loading for now.
  91. bool hasTexCoord = false, hasNormals = false, hasColors = false;
  92. bool hasHomogenous = false, hasDimension = false;
  93. unsigned int dimensions = 3;
  94. const char *car = buffer;
  95. const char *end = buffer + mBuffer2.size();
  96. NextToken(&car, end);
  97. if (car < end - 2 && car[0] == 'S' && car[1] == 'T') {
  98. hasTexCoord = true;
  99. car += 2;
  100. }
  101. if (car < end - 1 && car[0] == 'C') {
  102. hasColors = true;
  103. car++;
  104. }
  105. if (car < end - 1 && car[0] == 'N') {
  106. hasNormals = true;
  107. car++;
  108. }
  109. if (car < end - 1 && car[0] == '4') {
  110. hasHomogenous = true;
  111. car++;
  112. }
  113. if (car < end - 1 && car[0] == 'n') {
  114. hasDimension = true;
  115. car++;
  116. }
  117. if (car < end - 3 && car[0] == 'O' && car[1] == 'F' && car[2] == 'F') {
  118. car += 3;
  119. NextToken(&car, end);
  120. } else {
  121. // in case there is no OFF header (which is allowed by the
  122. // specification...), then we might have unintentionally read an
  123. // additional dimension from the primitive count fields
  124. dimensions = 3;
  125. hasHomogenous = false;
  126. NextToken(&car, end);
  127. // at this point the next token should be an integer number
  128. if (car >= end - 1 || *car < '0' || *car > '9') {
  129. throw DeadlyImportError("OFF: Header is invalid");
  130. }
  131. }
  132. if (hasDimension) {
  133. dimensions = strtoul10(car, &car);
  134. NextToken(&car, end);
  135. }
  136. if (dimensions > 3) {
  137. throw DeadlyImportError("OFF: Number of vertex coordinates higher than 3 unsupported");
  138. }
  139. NextToken(&car, end);
  140. const unsigned int numVertices = strtoul10(car, &car);
  141. NextToken(&car, end);
  142. const unsigned int numFaces = strtoul10(car, &car);
  143. NextToken(&car, end);
  144. strtoul10(car, &car); // skip edge count
  145. NextToken(&car, end);
  146. if (!numVertices) {
  147. throw DeadlyImportError("OFF: There are no valid vertices");
  148. }
  149. if (!numFaces) {
  150. throw DeadlyImportError("OFF: There are no valid faces");
  151. }
  152. pScene->mNumMeshes = 1;
  153. pScene->mMeshes = new aiMesh *[pScene->mNumMeshes];
  154. aiMesh *mesh = new aiMesh();
  155. pScene->mMeshes[0] = mesh;
  156. mesh->mNumFaces = numFaces;
  157. aiFace *faces = new aiFace[mesh->mNumFaces];
  158. mesh->mFaces = faces;
  159. mesh->mNumVertices = numVertices;
  160. mesh->mVertices = new aiVector3D[numVertices];
  161. mesh->mNormals = hasNormals ? new aiVector3D[numVertices] : nullptr;
  162. mesh->mColors[0] = hasColors ? new aiColor4D[numVertices] : nullptr;
  163. if (hasTexCoord) {
  164. mesh->mNumUVComponents[0] = 2;
  165. mesh->mTextureCoords[0] = new aiVector3D[numVertices];
  166. }
  167. char line[4096];
  168. buffer = car;
  169. const char *sz = car;
  170. const char *lineEnd = &line[4096];
  171. // now read all vertex lines
  172. for (unsigned int i = 0; i < numVertices; ++i) {
  173. if (!GetNextLine(buffer, line)) {
  174. ASSIMP_LOG_ERROR("OFF: The number of verts in the header is incorrect");
  175. break;
  176. }
  177. aiVector3D &v = mesh->mVertices[i];
  178. sz = line;
  179. // helper array to write a for loop over possible dimension values
  180. ai_real *vec[3] = { &v.x, &v.y, &v.z };
  181. // stop at dimensions: this allows loading 1D or 2D coordinate vertices
  182. for (unsigned int dim = 0; dim < dimensions; ++dim) {
  183. SkipSpaces(&sz, lineEnd);
  184. sz = fast_atoreal_move<ai_real>(sz, *vec[dim]);
  185. }
  186. // if has homogeneous coordinate, divide others by this one
  187. if (hasHomogenous) {
  188. SkipSpaces(&sz, lineEnd);
  189. ai_real w = 1.;
  190. sz = fast_atoreal_move<ai_real>(sz, w);
  191. for (unsigned int dim = 0; dim < dimensions; ++dim) {
  192. *(vec[dim]) /= w;
  193. }
  194. }
  195. // read optional normals
  196. if (hasNormals) {
  197. aiVector3D &n = mesh->mNormals[i];
  198. SkipSpaces(&sz, lineEnd);
  199. sz = fast_atoreal_move<ai_real>(sz, (ai_real &)n.x);
  200. SkipSpaces(&sz, lineEnd);
  201. sz = fast_atoreal_move<ai_real>(sz, (ai_real &)n.y);
  202. SkipSpaces(&sz, lineEnd);
  203. fast_atoreal_move<ai_real>(sz, (ai_real &)n.z);
  204. }
  205. // reading colors is a pain because the specification says it can be
  206. // integers or floats, and any number of them between 1 and 4 included,
  207. // until the next comment or end of line
  208. // in theory should be testing type !
  209. if (hasColors) {
  210. aiColor4D &c = mesh->mColors[0][i];
  211. SkipSpaces(&sz, lineEnd);
  212. sz = fast_atoreal_move<ai_real>(sz, (ai_real &)c.r);
  213. if (*sz != '#' && *sz != '\n' && *sz != '\r') {
  214. SkipSpaces(&sz, lineEnd);
  215. sz = fast_atoreal_move<ai_real>(sz, (ai_real &)c.g);
  216. } else {
  217. c.g = 0.;
  218. }
  219. if (*sz != '#' && *sz != '\n' && *sz != '\r') {
  220. SkipSpaces(&sz, lineEnd);
  221. sz = fast_atoreal_move<ai_real>(sz, (ai_real &)c.b);
  222. } else {
  223. c.b = 0.;
  224. }
  225. if (*sz != '#' && *sz != '\n' && *sz != '\r') {
  226. SkipSpaces(&sz, lineEnd);
  227. sz = fast_atoreal_move<ai_real>(sz, (ai_real &)c.a);
  228. } else {
  229. c.a = 1.;
  230. }
  231. }
  232. if (hasTexCoord) {
  233. aiVector3D &t = mesh->mTextureCoords[0][i];
  234. SkipSpaces(&sz, lineEnd);
  235. sz = fast_atoreal_move<ai_real>(sz, (ai_real &)t.x);
  236. SkipSpaces(&sz, lineEnd);
  237. fast_atoreal_move<ai_real>(sz, (ai_real &)t.y);
  238. }
  239. }
  240. // load faces with their indices
  241. faces = mesh->mFaces;
  242. for (unsigned int i = 0; i < numFaces;) {
  243. if (!GetNextLine(buffer, line)) {
  244. ASSIMP_LOG_ERROR("OFF: The number of faces in the header is incorrect");
  245. throw DeadlyImportError("OFF: The number of faces in the header is incorrect");
  246. }
  247. unsigned int idx;
  248. sz = line;
  249. SkipSpaces(&sz, lineEnd);
  250. idx = strtoul10(sz, &sz);
  251. if (!idx || idx > 9) {
  252. ASSIMP_LOG_ERROR("OFF: Faces with zero indices aren't allowed");
  253. --mesh->mNumFaces;
  254. ++i;
  255. continue;
  256. }
  257. faces->mNumIndices = idx;
  258. faces->mIndices = new unsigned int[faces->mNumIndices];
  259. for (unsigned int m = 0; m < faces->mNumIndices; ++m) {
  260. SkipSpaces(&sz, lineEnd);
  261. idx = strtoul10(sz, &sz);
  262. if (idx >= numVertices) {
  263. ASSIMP_LOG_ERROR("OFF: Vertex index is out of range");
  264. idx = numVertices - 1;
  265. }
  266. faces->mIndices[m] = idx;
  267. }
  268. ++i;
  269. ++faces;
  270. }
  271. // generate the output node graph
  272. pScene->mRootNode = new aiNode();
  273. pScene->mRootNode->mName.Set("<OFFRoot>");
  274. pScene->mRootNode->mNumMeshes = 1;
  275. pScene->mRootNode->mMeshes = new unsigned int[pScene->mRootNode->mNumMeshes];
  276. pScene->mRootNode->mMeshes[0] = 0;
  277. // generate a default material
  278. pScene->mNumMaterials = 1;
  279. pScene->mMaterials = new aiMaterial *[pScene->mNumMaterials];
  280. aiMaterial *pcMat = new aiMaterial();
  281. aiColor4D clr(0.6f, 0.6f, 0.6f, 1.0f);
  282. pcMat->AddProperty(&clr, 1, AI_MATKEY_COLOR_DIFFUSE);
  283. pScene->mMaterials[0] = pcMat;
  284. const int twosided = 1;
  285. pcMat->AddProperty(&twosided, 1, AI_MATKEY_TWOSIDED);
  286. }
  287. } // namespace Assimp
  288. #endif // !! ASSIMP_BUILD_NO_OFF_IMPORTER