OFFLoader.cpp 11 KB

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