PlyLoader.cpp 36 KB

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