PlyLoader.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2025, 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 PlyLoader.cpp
  35. * @brief Implementation of the PLY importer class
  36. */
  37. #ifndef ASSIMP_BUILD_NO_PLY_IMPORTER
  38. // internal headers
  39. #include "PlyLoader.h"
  40. #include <assimp/IOStreamBuffer.h>
  41. #include <assimp/importerdesc.h>
  42. #include <assimp/scene.h>
  43. #include <assimp/IOSystem.hpp>
  44. #include <memory>
  45. namespace Assimp {
  46. static constexpr aiImporterDesc desc = {
  47. "Stanford Polygon Library (PLY) Importer",
  48. "",
  49. "",
  50. "",
  51. aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_SupportTextFlavour,
  52. 0,
  53. 0,
  54. 0,
  55. 0,
  56. "ply"
  57. };
  58. // ------------------------------------------------------------------------------------------------
  59. // Internal stuff
  60. namespace {
  61. // ------------------------------------------------------------------------------------------------
  62. // Checks that property index is within range
  63. template <class T>
  64. inline const T &GetProperty(const std::vector<T> &props, int idx) {
  65. if (static_cast<size_t>(idx) >= props.size()) {
  66. throw DeadlyImportError("Invalid .ply file: Property index is out of range.");
  67. }
  68. return props[idx];
  69. }
  70. // ------------------------------------------------------------------------------------------------
  71. static bool isBigEndian(const char *szMe) {
  72. ai_assert(nullptr != szMe);
  73. // binary_little_endian
  74. // binary_big_endian
  75. bool isBigEndian{ false };
  76. #if (defined AI_BUILD_BIG_ENDIAN)
  77. if ('l' == *szMe || 'L' == *szMe) {
  78. isBigEndian = true;
  79. }
  80. #else
  81. if ('b' == *szMe || 'B' == *szMe) {
  82. isBigEndian = true;
  83. }
  84. #endif // ! AI_BUILD_BIG_ENDIAN
  85. return isBigEndian;
  86. }
  87. } // namespace
  88. // ------------------------------------------------------------------------------------------------
  89. // Constructor to be privately used by Importer
  90. PLYImporter::PLYImporter() :
  91. mBuffer(nullptr),
  92. pcDOM(nullptr),
  93. mGeneratedMesh(nullptr) {
  94. // empty
  95. }
  96. // ------------------------------------------------------------------------------------------------
  97. PLYImporter::~PLYImporter() {
  98. delete mGeneratedMesh;
  99. }
  100. // ------------------------------------------------------------------------------------------------
  101. // Returns whether the class can handle the format of the given file.
  102. bool PLYImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool /*checkSig*/) const {
  103. static const char *tokens[] = { "ply" };
  104. return SearchFileHeaderForToken(pIOHandler, pFile, tokens, AI_COUNT_OF(tokens));
  105. }
  106. // ------------------------------------------------------------------------------------------------
  107. const aiImporterDesc *PLYImporter::GetInfo() const {
  108. return &desc;
  109. }
  110. // ------------------------------------------------------------------------------------------------
  111. // Imports the given file into the given scene structure.
  112. void PLYImporter::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler) {
  113. const std::string mode = "rb";
  114. std::unique_ptr<IOStream> fileStream(pIOHandler->Open(pFile, mode));
  115. if (!fileStream) {
  116. throw DeadlyImportError("Failed to open file ", pFile, ".");
  117. }
  118. // Get the file-size
  119. const size_t fileSize = fileStream->FileSize();
  120. if (0 == fileSize) {
  121. throw DeadlyImportError("File ", pFile, " is empty.");
  122. }
  123. IOStreamBuffer<char> streamedBuffer(1024 * 1024);
  124. streamedBuffer.open(fileStream.get());
  125. // the beginning of the file must be PLY - magic, magic
  126. std::vector<char> headerCheck;
  127. streamedBuffer.getNextLine(headerCheck);
  128. if ((headerCheck.size() < 3) ||
  129. (headerCheck[0] != 'P' && headerCheck[0] != 'p') ||
  130. (headerCheck[1] != 'L' && headerCheck[1] != 'l') ||
  131. (headerCheck[2] != 'Y' && headerCheck[2] != 'y')) {
  132. streamedBuffer.close();
  133. throw DeadlyImportError("Invalid .ply file: Incorrect magic number (expected 'ply' or 'PLY').");
  134. }
  135. std::vector<char> mBuffer2;
  136. streamedBuffer.getNextLine(mBuffer2);
  137. mBuffer = (unsigned char *)&mBuffer2[0];
  138. char *szMe = (char *)&this->mBuffer[0];
  139. const char *end = &mBuffer2[0] + mBuffer2.size();
  140. SkipSpacesAndLineEnd(szMe, (const char **)&szMe, end);
  141. // determine the format of the file data and construct the aiMesh
  142. PLY::DOM sPlyDom;
  143. this->pcDOM = &sPlyDom;
  144. if (TokenMatch(szMe, "format", 6)) {
  145. if (TokenMatch(szMe, "ascii", 5)) {
  146. SkipLine(szMe, (const char **)&szMe, end);
  147. if (!PLY::DOM::ParseInstance(streamedBuffer, &sPlyDom, this)) {
  148. if (mGeneratedMesh != nullptr) {
  149. delete (mGeneratedMesh);
  150. mGeneratedMesh = nullptr;
  151. }
  152. streamedBuffer.close();
  153. throw DeadlyImportError("Invalid .ply file: Unable to build DOM (#1)");
  154. }
  155. } else if (!::strncmp(szMe, "binary_", 7)) {
  156. szMe += 7;
  157. const bool bIsBE = isBigEndian(szMe);
  158. // skip the line, parse the rest of the header and build the DOM
  159. if (!PLY::DOM::ParseInstanceBinary(streamedBuffer, &sPlyDom, this, bIsBE)) {
  160. if (mGeneratedMesh != nullptr) {
  161. delete (mGeneratedMesh);
  162. mGeneratedMesh = nullptr;
  163. }
  164. streamedBuffer.close();
  165. throw DeadlyImportError("Invalid .ply file: Unable to build DOM (#2)");
  166. }
  167. } else {
  168. if (mGeneratedMesh != nullptr) {
  169. delete (mGeneratedMesh);
  170. mGeneratedMesh = nullptr;
  171. }
  172. streamedBuffer.close();
  173. throw DeadlyImportError("Invalid .ply file: Unknown file format");
  174. }
  175. } else {
  176. AI_DEBUG_INVALIDATE_PTR(this->mBuffer);
  177. if (mGeneratedMesh != nullptr) {
  178. delete (mGeneratedMesh);
  179. mGeneratedMesh = nullptr;
  180. }
  181. streamedBuffer.close();
  182. throw DeadlyImportError("Invalid .ply file: Missing format specification");
  183. }
  184. // free the file buffer
  185. streamedBuffer.close();
  186. if (mGeneratedMesh == nullptr) {
  187. throw DeadlyImportError("Invalid .ply file: Unable to extract mesh data ");
  188. }
  189. // if no face list is existing we assume that the vertex
  190. // list is containing a list of points
  191. bool pointsOnly = mGeneratedMesh->mFaces == nullptr ? true : false;
  192. if (pointsOnly) {
  193. mGeneratedMesh->mPrimitiveTypes = aiPrimitiveType::aiPrimitiveType_POINT;
  194. }
  195. // now load a list of all materials
  196. std::vector<aiMaterial *> avMaterials;
  197. std::string defaultTexture;
  198. LoadMaterial(&avMaterials, defaultTexture, pointsOnly);
  199. // now generate the output scene object. Fill the material list
  200. pScene->mNumMaterials = (unsigned int)avMaterials.size();
  201. pScene->mMaterials = new aiMaterial *[pScene->mNumMaterials];
  202. for (unsigned int i = 0; i < pScene->mNumMaterials; ++i) {
  203. pScene->mMaterials[i] = avMaterials[i];
  204. }
  205. // fill the mesh list
  206. pScene->mNumMeshes = 1;
  207. pScene->mMeshes = new aiMesh *[pScene->mNumMeshes];
  208. pScene->mMeshes[0] = mGeneratedMesh;
  209. // Move the mesh ownership into the scene instance
  210. mGeneratedMesh = nullptr;
  211. // generate a simple node structure
  212. pScene->mRootNode = new aiNode();
  213. pScene->mRootNode->mNumMeshes = pScene->mNumMeshes;
  214. pScene->mRootNode->mMeshes = new unsigned int[pScene->mNumMeshes];
  215. for (unsigned int i = 0; i < pScene->mRootNode->mNumMeshes; ++i) {
  216. pScene->mRootNode->mMeshes[i] = i;
  217. }
  218. }
  219. static constexpr ai_uint NotSet = 0xFFFFFFFF;
  220. void PLYImporter::LoadVertex(const PLY::Element *pcElement, const PLY::ElementInstance *instElement, unsigned int pos) {
  221. ai_assert(nullptr != pcElement);
  222. ai_assert(nullptr != instElement);
  223. ai_uint aiPositions[3] = { NotSet, NotSet, NotSet };
  224. PLY::EDataType aiTypes[3] = { EDT_Char, EDT_Char, EDT_Char };
  225. ai_uint aiNormal[3] = { NotSet, NotSet, NotSet };
  226. PLY::EDataType aiNormalTypes[3] = { EDT_Char, EDT_Char, EDT_Char };
  227. unsigned int aiColors[4] = { NotSet, NotSet, NotSet, NotSet };
  228. PLY::EDataType aiColorsTypes[4] = { EDT_Char, EDT_Char, EDT_Char, EDT_Char };
  229. unsigned int aiTexcoord[2] = { NotSet, NotSet };
  230. PLY::EDataType aiTexcoordTypes[2] = { EDT_Char, EDT_Char };
  231. // now check whether which normal components are available
  232. unsigned int _a(0), cnt(0);
  233. for (std::vector<PLY::Property>::const_iterator a = pcElement->alProperties.begin();
  234. a != pcElement->alProperties.end(); ++a, ++_a) {
  235. if ((*a).bIsList) {
  236. continue;
  237. }
  238. // Positions
  239. if (PLY::EST_XCoord == (*a).Semantic) {
  240. ++cnt;
  241. aiPositions[0] = _a;
  242. aiTypes[0] = (*a).eType;
  243. } else if (PLY::EST_YCoord == (*a).Semantic) {
  244. ++cnt;
  245. aiPositions[1] = _a;
  246. aiTypes[1] = (*a).eType;
  247. } else if (PLY::EST_ZCoord == (*a).Semantic) {
  248. ++cnt;
  249. aiPositions[2] = _a;
  250. aiTypes[2] = (*a).eType;
  251. } else if (PLY::EST_XNormal == (*a).Semantic) {
  252. // Normals
  253. ++cnt;
  254. aiNormal[0] = _a;
  255. aiNormalTypes[0] = (*a).eType;
  256. } else if (PLY::EST_YNormal == (*a).Semantic) {
  257. ++cnt;
  258. aiNormal[1] = _a;
  259. aiNormalTypes[1] = (*a).eType;
  260. } else if (PLY::EST_ZNormal == (*a).Semantic) {
  261. ++cnt;
  262. aiNormal[2] = _a;
  263. aiNormalTypes[2] = (*a).eType;
  264. } else if (PLY::EST_Red == (*a).Semantic) {
  265. // Colors
  266. ++cnt;
  267. aiColors[0] = _a;
  268. aiColorsTypes[0] = (*a).eType;
  269. } else if (PLY::EST_Green == (*a).Semantic) {
  270. ++cnt;
  271. aiColors[1] = _a;
  272. aiColorsTypes[1] = (*a).eType;
  273. } else if (PLY::EST_Blue == (*a).Semantic) {
  274. ++cnt;
  275. aiColors[2] = _a;
  276. aiColorsTypes[2] = (*a).eType;
  277. } else if (PLY::EST_Alpha == (*a).Semantic) {
  278. ++cnt;
  279. aiColors[3] = _a;
  280. aiColorsTypes[3] = (*a).eType;
  281. } else if (PLY::EST_UTextureCoord == (*a).Semantic) {
  282. // Texture coordinates
  283. ++cnt;
  284. aiTexcoord[0] = _a;
  285. aiTexcoordTypes[0] = (*a).eType;
  286. } else if (PLY::EST_VTextureCoord == (*a).Semantic) {
  287. ++cnt;
  288. aiTexcoord[1] = _a;
  289. aiTexcoordTypes[1] = (*a).eType;
  290. }
  291. }
  292. // check whether we have a valid source for the vertex data
  293. if (0 != cnt) {
  294. // Position
  295. aiVector3D vOut;
  296. if (NotSet != aiPositions[0]) {
  297. vOut.x = PLY::PropertyInstance::ConvertTo<ai_real>(
  298. GetProperty(instElement->alProperties, aiPositions[0]).avList.front(), aiTypes[0]);
  299. }
  300. if (NotSet != aiPositions[1]) {
  301. vOut.y = PLY::PropertyInstance::ConvertTo<ai_real>(
  302. GetProperty(instElement->alProperties, aiPositions[1]).avList.front(), aiTypes[1]);
  303. }
  304. if (NotSet != aiPositions[2]) {
  305. vOut.z = PLY::PropertyInstance::ConvertTo<ai_real>(
  306. GetProperty(instElement->alProperties, aiPositions[2]).avList.front(), aiTypes[2]);
  307. }
  308. // Normals
  309. aiVector3D nOut;
  310. bool haveNormal = false;
  311. if (NotSet != aiNormal[0]) {
  312. nOut.x = PLY::PropertyInstance::ConvertTo<ai_real>(
  313. GetProperty(instElement->alProperties, aiNormal[0]).avList.front(), aiNormalTypes[0]);
  314. haveNormal = true;
  315. }
  316. if (NotSet != aiNormal[1]) {
  317. nOut.y = PLY::PropertyInstance::ConvertTo<ai_real>(
  318. GetProperty(instElement->alProperties, aiNormal[1]).avList.front(), aiNormalTypes[1]);
  319. haveNormal = true;
  320. }
  321. if (NotSet != aiNormal[2]) {
  322. nOut.z = PLY::PropertyInstance::ConvertTo<ai_real>(
  323. GetProperty(instElement->alProperties, aiNormal[2]).avList.front(), aiNormalTypes[2]);
  324. haveNormal = true;
  325. }
  326. // Colors
  327. aiColor4D cOut;
  328. bool haveColor = false;
  329. if (NotSet != aiColors[0]) {
  330. cOut.r = NormalizeColorValue(GetProperty(instElement->alProperties,
  331. aiColors[0])
  332. .avList.front(),
  333. aiColorsTypes[0]);
  334. haveColor = true;
  335. }
  336. if (NotSet != aiColors[1]) {
  337. cOut.g = NormalizeColorValue(GetProperty(instElement->alProperties,
  338. aiColors[1])
  339. .avList.front(),
  340. aiColorsTypes[1]);
  341. haveColor = true;
  342. }
  343. if (NotSet != aiColors[2]) {
  344. cOut.b = NormalizeColorValue(GetProperty(instElement->alProperties,
  345. aiColors[2])
  346. .avList.front(),
  347. aiColorsTypes[2]);
  348. haveColor = true;
  349. }
  350. // assume 1.0 for the alpha channel if it is not set
  351. if (NotSet == aiColors[3]) {
  352. cOut.a = 1.0;
  353. } else {
  354. cOut.a = NormalizeColorValue(GetProperty(instElement->alProperties,
  355. aiColors[3])
  356. .avList.front(),
  357. aiColorsTypes[3]);
  358. haveColor = true;
  359. }
  360. // Texture coordinates
  361. aiVector3D tOut;
  362. tOut.z = 0;
  363. bool haveTextureCoords = false;
  364. if (NotSet != aiTexcoord[0]) {
  365. tOut.x = PLY::PropertyInstance::ConvertTo<ai_real>(
  366. GetProperty(instElement->alProperties, aiTexcoord[0]).avList.front(), aiTexcoordTypes[0]);
  367. haveTextureCoords = true;
  368. }
  369. if (NotSet != aiTexcoord[1]) {
  370. tOut.y = PLY::PropertyInstance::ConvertTo<ai_real>(
  371. GetProperty(instElement->alProperties, aiTexcoord[1]).avList.front(), aiTexcoordTypes[1]);
  372. haveTextureCoords = true;
  373. }
  374. // create aiMesh if needed
  375. if (nullptr == mGeneratedMesh) {
  376. mGeneratedMesh = new aiMesh();
  377. mGeneratedMesh->mMaterialIndex = 0;
  378. }
  379. if (nullptr == mGeneratedMesh->mVertices) {
  380. mGeneratedMesh->mNumVertices = pcElement->NumOccur;
  381. mGeneratedMesh->mVertices = new aiVector3D[mGeneratedMesh->mNumVertices];
  382. }
  383. if (pos >= mGeneratedMesh->mNumVertices) {
  384. throw DeadlyImportError("Invalid .ply file: Too many vertices");
  385. }
  386. mGeneratedMesh->mVertices[pos] = vOut;
  387. if (haveNormal) {
  388. if (nullptr == mGeneratedMesh->mNormals)
  389. mGeneratedMesh->mNormals = new aiVector3D[mGeneratedMesh->mNumVertices];
  390. mGeneratedMesh->mNormals[pos] = nOut;
  391. }
  392. if (haveColor) {
  393. if (nullptr == mGeneratedMesh->mColors[0])
  394. mGeneratedMesh->mColors[0] = new aiColor4D[mGeneratedMesh->mNumVertices];
  395. mGeneratedMesh->mColors[0][pos] = cOut;
  396. }
  397. if (haveTextureCoords) {
  398. if (nullptr == mGeneratedMesh->mTextureCoords[0]) {
  399. mGeneratedMesh->mNumUVComponents[0] = 2;
  400. mGeneratedMesh->mTextureCoords[0] = new aiVector3D[mGeneratedMesh->mNumVertices];
  401. }
  402. mGeneratedMesh->mTextureCoords[0][pos] = tOut;
  403. }
  404. }
  405. }
  406. // ------------------------------------------------------------------------------------------------
  407. // Convert a color component to [0...1]
  408. ai_real PLYImporter::NormalizeColorValue(PLY::PropertyInstance::ValueUnion val, PLY::EDataType eType) {
  409. switch (eType) {
  410. case EDT_Float:
  411. return val.fFloat;
  412. case EDT_Double:
  413. return (ai_real)val.fDouble;
  414. case EDT_UChar:
  415. return (ai_real)val.iUInt / (ai_real)0xFF;
  416. case EDT_Char:
  417. return (ai_real)(val.iInt + (0xFF / 2)) / (ai_real)0xFF;
  418. case EDT_UShort:
  419. return (ai_real)val.iUInt / (ai_real)0xFFFF;
  420. case EDT_Short:
  421. return (ai_real)(val.iInt + (0xFFFF / 2)) / (ai_real)0xFFFF;
  422. case EDT_UInt:
  423. return (ai_real)val.iUInt / (ai_real)0xFFFF;
  424. case EDT_Int:
  425. return ((ai_real)val.iInt / (ai_real)0xFF) + 0.5f;
  426. default:
  427. break;
  428. }
  429. return 0.0f;
  430. }
  431. // ------------------------------------------------------------------------------------------------
  432. // Try to extract proper faces from the PLY DOM
  433. void PLYImporter::LoadFace(const PLY::Element *pcElement, const PLY::ElementInstance *instElement,
  434. unsigned int pos) {
  435. ai_assert(nullptr != pcElement);
  436. ai_assert(nullptr != instElement);
  437. if (mGeneratedMesh == nullptr) {
  438. throw DeadlyImportError("Invalid .ply file: Vertices should be declared before faces");
  439. }
  440. bool bOne = false;
  441. // index of the vertex index list
  442. unsigned int iProperty = NotSet;
  443. PLY::EDataType eType = EDT_Char;
  444. bool bIsTriStrip = false;
  445. // texture coordinates
  446. unsigned int iTextureCoord = NotSet;
  447. PLY::EDataType eType3 = EDT_Char;
  448. // face = unique number of vertex indices
  449. if (PLY::EEST_Face == pcElement->eSemantic) {
  450. unsigned int _a = 0;
  451. for (std::vector<PLY::Property>::const_iterator a = pcElement->alProperties.begin();
  452. a != pcElement->alProperties.end(); ++a, ++_a) {
  453. if (PLY::EST_VertexIndex == (*a).Semantic) {
  454. // must be a dynamic list!
  455. if (!(*a).bIsList) {
  456. continue;
  457. }
  458. iProperty = _a;
  459. bOne = true;
  460. eType = (*a).eType;
  461. } else if (PLY::EST_TextureCoordinates == (*a).Semantic) {
  462. // must be a dynamic list!
  463. if (!(*a).bIsList) {
  464. continue;
  465. }
  466. iTextureCoord = _a;
  467. bOne = true;
  468. eType3 = (*a).eType;
  469. }
  470. }
  471. }
  472. // triangle strip
  473. // TODO: triangle strip and material index support???
  474. else if (PLY::EEST_TriStrip == pcElement->eSemantic) {
  475. unsigned int _a = 0;
  476. for (std::vector<PLY::Property>::const_iterator a = pcElement->alProperties.begin();
  477. a != pcElement->alProperties.end(); ++a, ++_a) {
  478. // must be a dynamic list!
  479. if (!(*a).bIsList) {
  480. continue;
  481. }
  482. iProperty = _a;
  483. bOne = true;
  484. bIsTriStrip = true;
  485. eType = (*a).eType;
  486. break;
  487. }
  488. }
  489. // check whether we have at least one per-face information set
  490. if (bOne) {
  491. if (mGeneratedMesh->mFaces == nullptr) {
  492. mGeneratedMesh->mNumFaces = pcElement->NumOccur;
  493. mGeneratedMesh->mFaces = new aiFace[mGeneratedMesh->mNumFaces];
  494. } else {
  495. if (mGeneratedMesh->mNumFaces < pcElement->NumOccur) {
  496. throw DeadlyImportError("Invalid .ply file: Too many faces");
  497. }
  498. }
  499. if (!bIsTriStrip) {
  500. // parse the list of vertex indices
  501. if (NotSet != iProperty) {
  502. const unsigned int iNum = (unsigned int)GetProperty(instElement->alProperties, iProperty).avList.size();
  503. mGeneratedMesh->mFaces[pos].mNumIndices = iNum;
  504. mGeneratedMesh->mFaces[pos].mIndices = new unsigned int[iNum];
  505. std::vector<PLY::PropertyInstance::ValueUnion>::const_iterator p =
  506. GetProperty(instElement->alProperties, iProperty).avList.begin();
  507. for (unsigned int a = 0; a < iNum; ++a, ++p) {
  508. mGeneratedMesh->mFaces[pos].mIndices[a] = PLY::PropertyInstance::ConvertTo<unsigned int>(*p, eType);
  509. }
  510. }
  511. if (NotSet != iTextureCoord) {
  512. const unsigned int iNum = (unsigned int)GetProperty(instElement->alProperties, iTextureCoord).avList.size();
  513. // should be 6 coords
  514. std::vector<PLY::PropertyInstance::ValueUnion>::const_iterator p =
  515. GetProperty(instElement->alProperties, iTextureCoord).avList.begin();
  516. if ((iNum / 3) == 2) // X Y coord
  517. {
  518. for (unsigned int a = 0; a < iNum; ++a, ++p) {
  519. unsigned int vindex = mGeneratedMesh->mFaces[pos].mIndices[a / 2];
  520. if (vindex < mGeneratedMesh->mNumVertices) {
  521. if (mGeneratedMesh->mTextureCoords[0] == nullptr) {
  522. mGeneratedMesh->mNumUVComponents[0] = 2;
  523. mGeneratedMesh->mTextureCoords[0] = new aiVector3D[mGeneratedMesh->mNumVertices];
  524. }
  525. if (a % 2 == 0) {
  526. mGeneratedMesh->mTextureCoords[0][vindex].x = PLY::PropertyInstance::ConvertTo<ai_real>(*p, eType3);
  527. } else {
  528. mGeneratedMesh->mTextureCoords[0][vindex].y = PLY::PropertyInstance::ConvertTo<ai_real>(*p, eType3);
  529. }
  530. mGeneratedMesh->mTextureCoords[0][vindex].z = 0;
  531. }
  532. }
  533. }
  534. }
  535. } else { // triangle strips
  536. // normally we have only one triangle strip instance where
  537. // a value of -1 indicates a restart of the strip
  538. bool flip = false;
  539. const std::vector<PLY::PropertyInstance::ValueUnion> &quak = GetProperty(instElement->alProperties, iProperty).avList;
  540. // pvOut->reserve(pvOut->size() + quak.size() + (quak.size()>>2u)); //Limits memory consumption
  541. int aiTable[2] = { -1, -1 };
  542. for (std::vector<PLY::PropertyInstance::ValueUnion>::const_iterator a = quak.begin(); a != quak.end(); ++a) {
  543. const int p = PLY::PropertyInstance::ConvertTo<int>(*a, eType);
  544. if (-1 == p) {
  545. // restart the strip ...
  546. aiTable[0] = aiTable[1] = -1;
  547. flip = false;
  548. continue;
  549. }
  550. if (-1 == aiTable[0]) {
  551. aiTable[0] = p;
  552. continue;
  553. }
  554. if (-1 == aiTable[1]) {
  555. aiTable[1] = p;
  556. continue;
  557. }
  558. if (mGeneratedMesh->mFaces == nullptr) {
  559. mGeneratedMesh->mNumFaces = pcElement->NumOccur;
  560. mGeneratedMesh->mFaces = new aiFace[mGeneratedMesh->mNumFaces];
  561. }
  562. mGeneratedMesh->mFaces[pos].mNumIndices = 3;
  563. mGeneratedMesh->mFaces[pos].mIndices = new unsigned int[3];
  564. mGeneratedMesh->mFaces[pos].mIndices[0] = aiTable[0];
  565. mGeneratedMesh->mFaces[pos].mIndices[1] = aiTable[1];
  566. mGeneratedMesh->mFaces[pos].mIndices[2] = p;
  567. // every second pass swap the indices.
  568. flip = !flip;
  569. if (flip) {
  570. std::swap(mGeneratedMesh->mFaces[pos].mIndices[0], mGeneratedMesh->mFaces[pos].mIndices[1]);
  571. }
  572. aiTable[0] = aiTable[1];
  573. aiTable[1] = p;
  574. }
  575. }
  576. }
  577. }
  578. // ------------------------------------------------------------------------------------------------
  579. // Get a RGBA color in [0...1] range
  580. void PLYImporter::GetMaterialColor(const std::vector<PLY::PropertyInstance> &avList,
  581. unsigned int aiPositions[4],
  582. PLY::EDataType aiTypes[4],
  583. aiColor4D *clrOut) {
  584. ai_assert(nullptr != clrOut);
  585. if (NotSet == aiPositions[0]) {
  586. clrOut->r = 0.0f;
  587. } else {
  588. clrOut->r = NormalizeColorValue(GetProperty(avList, aiPositions[0]).avList.front(), aiTypes[0]);
  589. }
  590. if (NotSet == aiPositions[1]) {
  591. clrOut->g = 0.0f;
  592. } else {
  593. clrOut->g = NormalizeColorValue(GetProperty(avList, aiPositions[1]).avList.front(), aiTypes[1]);
  594. }
  595. if (NotSet == aiPositions[2])
  596. clrOut->b = 0.0f;
  597. else {
  598. clrOut->b = NormalizeColorValue(GetProperty(avList, aiPositions[2]).avList.front(), aiTypes[2]);
  599. }
  600. // assume 1.0 for the alpha channel ifit is not set
  601. if (NotSet == aiPositions[3])
  602. clrOut->a = 1.0f;
  603. else {
  604. clrOut->a = NormalizeColorValue(GetProperty(avList, aiPositions[3]).avList.front(), aiTypes[3]);
  605. }
  606. }
  607. // ------------------------------------------------------------------------------------------------
  608. // Extract a material from the PLY DOM
  609. void PLYImporter::LoadMaterial(std::vector<aiMaterial *> *pvOut, std::string &defaultTexture, const bool pointsOnly) {
  610. ai_assert(nullptr != pvOut);
  611. // diffuse[4], specular[4], ambient[4]
  612. // rgba order
  613. unsigned int aaiPositions[3][4] = {
  614. { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF },
  615. { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF },
  616. { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF },
  617. };
  618. PLY::EDataType aaiTypes[3][4] = {
  619. { EDT_Char, EDT_Char, EDT_Char, EDT_Char },
  620. { EDT_Char, EDT_Char, EDT_Char, EDT_Char },
  621. { EDT_Char, EDT_Char, EDT_Char, EDT_Char }
  622. };
  623. PLY::ElementInstanceList *pcList = nullptr;
  624. unsigned int iPhong = 0xFFFFFFFF;
  625. PLY::EDataType ePhong = EDT_Char;
  626. unsigned int iOpacity = 0xFFFFFFFF;
  627. PLY::EDataType eOpacity = EDT_Char;
  628. // search in the DOM for a vertex entry
  629. unsigned int _i = 0;
  630. for (std::vector<PLY::Element>::const_iterator i = this->pcDOM->alElements.begin();
  631. i != this->pcDOM->alElements.end(); ++i, ++_i) {
  632. if (PLY::EEST_Material == (*i).eSemantic) {
  633. pcList = &this->pcDOM->alElementData[_i];
  634. // now check whether which coordinate sets are available
  635. unsigned int _a = 0;
  636. for (std::vector<PLY::Property>::const_iterator
  637. a = (*i).alProperties.begin();
  638. a != (*i).alProperties.end(); ++a, ++_a) {
  639. if ((*a).bIsList) continue;
  640. // pohng specularity -----------------------------------
  641. if (PLY::EST_PhongPower == (*a).Semantic) {
  642. iPhong = _a;
  643. ePhong = (*a).eType;
  644. }
  645. // general opacity -----------------------------------
  646. if (PLY::EST_Opacity == (*a).Semantic) {
  647. iOpacity = _a;
  648. eOpacity = (*a).eType;
  649. }
  650. // diffuse color channels -----------------------------------
  651. if (PLY::EST_DiffuseRed == (*a).Semantic) {
  652. aaiPositions[0][0] = _a;
  653. aaiTypes[0][0] = (*a).eType;
  654. } else if (PLY::EST_DiffuseGreen == (*a).Semantic) {
  655. aaiPositions[0][1] = _a;
  656. aaiTypes[0][1] = (*a).eType;
  657. } else if (PLY::EST_DiffuseBlue == (*a).Semantic) {
  658. aaiPositions[0][2] = _a;
  659. aaiTypes[0][2] = (*a).eType;
  660. } else if (PLY::EST_DiffuseAlpha == (*a).Semantic) {
  661. aaiPositions[0][3] = _a;
  662. aaiTypes[0][3] = (*a).eType;
  663. }
  664. // specular color channels -----------------------------------
  665. else if (PLY::EST_SpecularRed == (*a).Semantic) {
  666. aaiPositions[1][0] = _a;
  667. aaiTypes[1][0] = (*a).eType;
  668. } else if (PLY::EST_SpecularGreen == (*a).Semantic) {
  669. aaiPositions[1][1] = _a;
  670. aaiTypes[1][1] = (*a).eType;
  671. } else if (PLY::EST_SpecularBlue == (*a).Semantic) {
  672. aaiPositions[1][2] = _a;
  673. aaiTypes[1][2] = (*a).eType;
  674. } else if (PLY::EST_SpecularAlpha == (*a).Semantic) {
  675. aaiPositions[1][3] = _a;
  676. aaiTypes[1][3] = (*a).eType;
  677. }
  678. // ambient color channels -----------------------------------
  679. else if (PLY::EST_AmbientRed == (*a).Semantic) {
  680. aaiPositions[2][0] = _a;
  681. aaiTypes[2][0] = (*a).eType;
  682. } else if (PLY::EST_AmbientGreen == (*a).Semantic) {
  683. aaiPositions[2][1] = _a;
  684. aaiTypes[2][1] = (*a).eType;
  685. } else if (PLY::EST_AmbientBlue == (*a).Semantic) {
  686. aaiPositions[2][2] = _a;
  687. aaiTypes[2][2] = (*a).eType;
  688. } else if (PLY::EST_AmbientAlpha == (*a).Semantic) {
  689. aaiPositions[2][3] = _a;
  690. aaiTypes[2][3] = (*a).eType;
  691. }
  692. }
  693. break;
  694. } else if (PLY::EEST_TextureFile == (*i).eSemantic) {
  695. defaultTexture = (*i).szName;
  696. }
  697. }
  698. // check whether we have a valid source for the material data
  699. if (nullptr != pcList) {
  700. for (std::vector<ElementInstance>::const_iterator i = pcList->alInstances.begin(); i != pcList->alInstances.end(); ++i) {
  701. aiColor4D clrOut;
  702. aiMaterial *pcHelper = new aiMaterial();
  703. // build the diffuse material color
  704. GetMaterialColor((*i).alProperties, aaiPositions[0], aaiTypes[0], &clrOut);
  705. pcHelper->AddProperty<aiColor4D>(&clrOut, 1, AI_MATKEY_COLOR_DIFFUSE);
  706. // build the specular material color
  707. GetMaterialColor((*i).alProperties, aaiPositions[1], aaiTypes[1], &clrOut);
  708. pcHelper->AddProperty<aiColor4D>(&clrOut, 1, AI_MATKEY_COLOR_SPECULAR);
  709. // build the ambient material color
  710. GetMaterialColor((*i).alProperties, aaiPositions[2], aaiTypes[2], &clrOut);
  711. pcHelper->AddProperty<aiColor4D>(&clrOut, 1, AI_MATKEY_COLOR_AMBIENT);
  712. // handle phong power and shading mode
  713. int iMode = (int)aiShadingMode_Gouraud;
  714. if (0xFFFFFFFF != iPhong) {
  715. ai_real fSpec = PLY::PropertyInstance::ConvertTo<ai_real>(GetProperty((*i).alProperties, iPhong).avList.front(), ePhong);
  716. // if shininess is 0 (and the pow() calculation would therefore always
  717. // become 1, not depending on the angle), use gouraud lighting
  718. if (fSpec) {
  719. // scale this with 15 ... hopefully this is correct
  720. fSpec *= 15;
  721. pcHelper->AddProperty<ai_real>(&fSpec, 1, AI_MATKEY_SHININESS);
  722. iMode = (int)aiShadingMode_Phong;
  723. }
  724. }
  725. pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
  726. // handle opacity
  727. if (0xFFFFFFFF != iOpacity) {
  728. ai_real fOpacity = PLY::PropertyInstance::ConvertTo<ai_real>(GetProperty((*i).alProperties, iPhong).avList.front(), eOpacity);
  729. pcHelper->AddProperty<ai_real>(&fOpacity, 1, AI_MATKEY_OPACITY);
  730. }
  731. // The face order is absolutely undefined for PLY, so we have to
  732. // use two-sided rendering to be sure it's ok.
  733. const int two_sided = 1;
  734. pcHelper->AddProperty(&two_sided, 1, AI_MATKEY_TWOSIDED);
  735. // default texture
  736. if (!defaultTexture.empty()) {
  737. const aiString name(defaultTexture.c_str());
  738. pcHelper->AddProperty(&name, _AI_MATKEY_TEXTURE_BASE, aiTextureType_DIFFUSE, 0);
  739. }
  740. if (!pointsOnly) {
  741. pcHelper->AddProperty(&two_sided, 1, AI_MATKEY_TWOSIDED);
  742. }
  743. // set to wireframe, so when using this material info we can switch to points rendering
  744. if (pointsOnly) {
  745. const int wireframe = 1;
  746. pcHelper->AddProperty(&wireframe, 1, AI_MATKEY_ENABLE_WIREFRAME);
  747. }
  748. // add the newly created material instance to the list
  749. pvOut->push_back(pcHelper);
  750. }
  751. } else {
  752. // generate a default material
  753. aiMaterial *pcHelper = new aiMaterial();
  754. // fill in a default material
  755. int iMode = (int)aiShadingMode_Gouraud;
  756. pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
  757. // generate white material most 3D engine just multiply ambient / diffuse color with actual ambient / light color
  758. aiColor3D clr;
  759. clr.b = clr.g = clr.r = 1.0f;
  760. pcHelper->AddProperty<aiColor3D>(&clr, 1, AI_MATKEY_COLOR_DIFFUSE);
  761. pcHelper->AddProperty<aiColor3D>(&clr, 1, AI_MATKEY_COLOR_SPECULAR);
  762. clr.b = clr.g = clr.r = 1.0f;
  763. pcHelper->AddProperty<aiColor3D>(&clr, 1, AI_MATKEY_COLOR_AMBIENT);
  764. // The face order is absolutely undefined for PLY, so we have to
  765. // use two-sided rendering to be sure it's ok.
  766. if (!pointsOnly) {
  767. const int two_sided = 1;
  768. pcHelper->AddProperty(&two_sided, 1, AI_MATKEY_TWOSIDED);
  769. }
  770. // default texture
  771. if (!defaultTexture.empty()) {
  772. const aiString name(defaultTexture.c_str());
  773. pcHelper->AddProperty(&name, _AI_MATKEY_TEXTURE_BASE, aiTextureType_DIFFUSE, 0);
  774. }
  775. // set to wireframe, so when using this material info we can switch to points rendering
  776. if (pointsOnly) {
  777. const int wireframe = 1;
  778. pcHelper->AddProperty(&wireframe, 1, AI_MATKEY_ENABLE_WIREFRAME);
  779. }
  780. pvOut->push_back(pcHelper);
  781. }
  782. }
  783. } // namespace Assimp
  784. #endif // !! ASSIMP_BUILD_NO_PLY_IMPORTER