PlyLoader.cpp 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2018, 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/Macros.h>
  42. #include <memory>
  43. #include <assimp/IOSystem.hpp>
  44. #include <assimp/scene.h>
  45. #include <assimp/importerdesc.h>
  46. using namespace Assimp;
  47. static const aiImporterDesc desc = {
  48. "Stanford Polygon Library (PLY) Importer",
  49. "",
  50. "",
  51. "",
  52. aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_SupportTextFlavour,
  53. 0,
  54. 0,
  55. 0,
  56. 0,
  57. "ply"
  58. };
  59. // ------------------------------------------------------------------------------------------------
  60. // Internal stuff
  61. namespace
  62. {
  63. // ------------------------------------------------------------------------------------------------
  64. // Checks that property index is within range
  65. template <class T>
  66. const T &GetProperty(const std::vector<T> &props, int idx)
  67. {
  68. if (static_cast<size_t>(idx) >= props.size()) {
  69. throw DeadlyImportError("Invalid .ply file: Property index is out of range.");
  70. }
  71. return props[idx];
  72. }
  73. }
  74. // ------------------------------------------------------------------------------------------------
  75. // Constructor to be privately used by Importer
  76. PLYImporter::PLYImporter()
  77. : mBuffer(nullptr)
  78. , pcDOM(nullptr)
  79. , mGeneratedMesh(nullptr) {
  80. // empty
  81. }
  82. // ------------------------------------------------------------------------------------------------
  83. // Destructor, private as well
  84. PLYImporter::~PLYImporter() {
  85. // empty
  86. }
  87. // ------------------------------------------------------------------------------------------------
  88. // Returns whether the class can handle the format of the given file.
  89. bool PLYImporter::CanRead(const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const {
  90. const std::string extension = GetExtension(pFile);
  91. if ( extension == "ply" ) {
  92. return true;
  93. } else if (!extension.length() || checkSig) {
  94. if ( !pIOHandler ) {
  95. return true;
  96. }
  97. static const char* tokens[] = { "ply" };
  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(NULL != 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. static 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 != NULL) {
  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 != NULL) {
  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 != NULL) {
  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 != NULL) {
  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 == NULL) {
  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 == NULL ? true : false;
  204. if (pointsOnly) {
  205. if (mGeneratedMesh->mNumVertices < 3) {
  206. if (mGeneratedMesh != NULL) {
  207. delete(mGeneratedMesh);
  208. mGeneratedMesh = nullptr;
  209. }
  210. streamedBuffer.close();
  211. throw DeadlyImportError("Invalid .ply file: Not enough "
  212. "vertices to build a proper face list. ");
  213. }
  214. const unsigned int iNum = (unsigned int)mGeneratedMesh->mNumVertices / 3;
  215. mGeneratedMesh->mNumFaces = iNum;
  216. mGeneratedMesh->mFaces = new aiFace[mGeneratedMesh->mNumFaces];
  217. for (unsigned int i = 0; i < iNum; ++i) {
  218. mGeneratedMesh->mFaces[i].mNumIndices = 3;
  219. mGeneratedMesh->mFaces[i].mIndices = new unsigned int[3];
  220. mGeneratedMesh->mFaces[i].mIndices[0] = (i * 3);
  221. mGeneratedMesh->mFaces[i].mIndices[1] = (i * 3) + 1;
  222. mGeneratedMesh->mFaces[i].mIndices[2] = (i * 3) + 2;
  223. }
  224. }
  225. // now load a list of all materials
  226. std::vector<aiMaterial*> avMaterials;
  227. std::string defaultTexture;
  228. LoadMaterial(&avMaterials, defaultTexture, pointsOnly);
  229. // now generate the output scene object. Fill the material list
  230. pScene->mNumMaterials = (unsigned int)avMaterials.size();
  231. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials];
  232. for (unsigned int i = 0; i < pScene->mNumMaterials; ++i) {
  233. pScene->mMaterials[i] = avMaterials[i];
  234. }
  235. // fill the mesh list
  236. pScene->mNumMeshes = 1;
  237. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  238. pScene->mMeshes[0] = mGeneratedMesh;
  239. mGeneratedMesh = nullptr;
  240. // generate a simple node structure
  241. pScene->mRootNode = new aiNode();
  242. pScene->mRootNode->mNumMeshes = pScene->mNumMeshes;
  243. pScene->mRootNode->mMeshes = new unsigned int[pScene->mNumMeshes];
  244. for (unsigned int i = 0; i < pScene->mRootNode->mNumMeshes; ++i) {
  245. pScene->mRootNode->mMeshes[i] = i;
  246. }
  247. }
  248. void PLYImporter::LoadVertex(const PLY::Element* pcElement, const PLY::ElementInstance* instElement, unsigned int pos) {
  249. ai_assert(NULL != pcElement);
  250. ai_assert(NULL != instElement);
  251. ai_uint aiPositions[3] = { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF };
  252. PLY::EDataType aiTypes[3] = { EDT_Char, EDT_Char, EDT_Char };
  253. ai_uint aiNormal[3] = { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF };
  254. PLY::EDataType aiNormalTypes[3] = { EDT_Char, EDT_Char, EDT_Char };
  255. unsigned int aiColors[4] = { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF };
  256. PLY::EDataType aiColorsTypes[4] = { EDT_Char, EDT_Char, EDT_Char, EDT_Char };
  257. unsigned int aiTexcoord[2] = { 0xFFFFFFFF, 0xFFFFFFFF };
  258. PLY::EDataType aiTexcoordTypes[2] = { EDT_Char, EDT_Char };
  259. // now check whether which normal components are available
  260. unsigned int _a( 0 ), cnt( 0 );
  261. for ( std::vector<PLY::Property>::const_iterator a = pcElement->alProperties.begin();
  262. a != pcElement->alProperties.end(); ++a, ++_a) {
  263. if ((*a).bIsList) {
  264. continue;
  265. }
  266. // Positions
  267. if (PLY::EST_XCoord == (*a).Semantic) {
  268. ++cnt;
  269. aiPositions[0] = _a;
  270. aiTypes[0] = (*a).eType;
  271. } else if (PLY::EST_YCoord == (*a).Semantic) {
  272. ++cnt;
  273. aiPositions[1] = _a;
  274. aiTypes[1] = (*a).eType;
  275. } else if (PLY::EST_ZCoord == (*a).Semantic) {
  276. ++cnt;
  277. aiPositions[2] = _a;
  278. aiTypes[2] = (*a).eType;
  279. } else if (PLY::EST_XNormal == (*a).Semantic) {
  280. // Normals
  281. ++cnt;
  282. aiNormal[0] = _a;
  283. aiNormalTypes[0] = (*a).eType;
  284. } else if (PLY::EST_YNormal == (*a).Semantic) {
  285. ++cnt;
  286. aiNormal[1] = _a;
  287. aiNormalTypes[1] = (*a).eType;
  288. } else if (PLY::EST_ZNormal == (*a).Semantic) {
  289. ++cnt;
  290. aiNormal[2] = _a;
  291. aiNormalTypes[2] = (*a).eType;
  292. } else if (PLY::EST_Red == (*a).Semantic) {
  293. // Colors
  294. ++cnt;
  295. aiColors[0] = _a;
  296. aiColorsTypes[0] = (*a).eType;
  297. } else if (PLY::EST_Green == (*a).Semantic) {
  298. ++cnt;
  299. aiColors[1] = _a;
  300. aiColorsTypes[1] = (*a).eType;
  301. } else if (PLY::EST_Blue == (*a).Semantic) {
  302. ++cnt;
  303. aiColors[2] = _a;
  304. aiColorsTypes[2] = (*a).eType;
  305. } else if (PLY::EST_Alpha == (*a).Semantic) {
  306. ++cnt;
  307. aiColors[3] = _a;
  308. aiColorsTypes[3] = (*a).eType;
  309. } else if (PLY::EST_UTextureCoord == (*a).Semantic) {
  310. // Texture coordinates
  311. ++cnt;
  312. aiTexcoord[0] = _a;
  313. aiTexcoordTypes[0] = (*a).eType;
  314. } else if (PLY::EST_VTextureCoord == (*a).Semantic) {
  315. ++cnt;
  316. aiTexcoord[1] = _a;
  317. aiTexcoordTypes[1] = (*a).eType;
  318. }
  319. }
  320. // check whether we have a valid source for the vertex data
  321. if (0 != cnt) {
  322. // Position
  323. aiVector3D vOut;
  324. if (0xFFFFFFFF != aiPositions[0]) {
  325. vOut.x = PLY::PropertyInstance::ConvertTo<ai_real>(
  326. GetProperty(instElement->alProperties, aiPositions[0]).avList.front(), aiTypes[0]);
  327. }
  328. if (0xFFFFFFFF != aiPositions[1]) {
  329. vOut.y = PLY::PropertyInstance::ConvertTo<ai_real>(
  330. GetProperty(instElement->alProperties, aiPositions[1]).avList.front(), aiTypes[1]);
  331. }
  332. if (0xFFFFFFFF != aiPositions[2]) {
  333. vOut.z = PLY::PropertyInstance::ConvertTo<ai_real>(
  334. GetProperty(instElement->alProperties, aiPositions[2]).avList.front(), aiTypes[2]);
  335. }
  336. // Normals
  337. aiVector3D nOut;
  338. bool haveNormal = false;
  339. if (0xFFFFFFFF != aiNormal[0]) {
  340. nOut.x = PLY::PropertyInstance::ConvertTo<ai_real>(
  341. GetProperty(instElement->alProperties, aiNormal[0]).avList.front(), aiNormalTypes[0]);
  342. haveNormal = true;
  343. }
  344. if (0xFFFFFFFF != aiNormal[1]) {
  345. nOut.y = PLY::PropertyInstance::ConvertTo<ai_real>(
  346. GetProperty(instElement->alProperties, aiNormal[1]).avList.front(), aiNormalTypes[1]);
  347. haveNormal = true;
  348. }
  349. if (0xFFFFFFFF != aiNormal[2]) {
  350. nOut.z = PLY::PropertyInstance::ConvertTo<ai_real>(
  351. GetProperty(instElement->alProperties, aiNormal[2]).avList.front(), aiNormalTypes[2]);
  352. haveNormal = true;
  353. }
  354. //Colors
  355. aiColor4D cOut;
  356. bool haveColor = false;
  357. if (0xFFFFFFFF != aiColors[0]) {
  358. cOut.r = NormalizeColorValue(GetProperty(instElement->alProperties,
  359. aiColors[0]).avList.front(), aiColorsTypes[0]);
  360. haveColor = true;
  361. }
  362. if (0xFFFFFFFF != aiColors[1]) {
  363. cOut.g = NormalizeColorValue(GetProperty(instElement->alProperties,
  364. aiColors[1]).avList.front(), aiColorsTypes[1]);
  365. haveColor = true;
  366. }
  367. if (0xFFFFFFFF != aiColors[2]) {
  368. cOut.b = NormalizeColorValue(GetProperty(instElement->alProperties,
  369. aiColors[2]).avList.front(), aiColorsTypes[2]);
  370. haveColor = true;
  371. }
  372. // assume 1.0 for the alpha channel ifit is not set
  373. if (0xFFFFFFFF == aiColors[3]) {
  374. cOut.a = 1.0;
  375. } else {
  376. cOut.a = NormalizeColorValue(GetProperty(instElement->alProperties,
  377. aiColors[3]).avList.front(), aiColorsTypes[3]);
  378. haveColor = true;
  379. }
  380. //Texture coordinates
  381. aiVector3D tOut;
  382. tOut.z = 0;
  383. bool haveTextureCoords = false;
  384. if (0xFFFFFFFF != aiTexcoord[0]) {
  385. tOut.x = PLY::PropertyInstance::ConvertTo<ai_real>(
  386. GetProperty(instElement->alProperties, aiTexcoord[0]).avList.front(), aiTexcoordTypes[0]);
  387. haveTextureCoords = true;
  388. }
  389. if (0xFFFFFFFF != aiTexcoord[1]) {
  390. tOut.y = PLY::PropertyInstance::ConvertTo<ai_real>(
  391. GetProperty(instElement->alProperties, aiTexcoord[1]).avList.front(), aiTexcoordTypes[1]);
  392. haveTextureCoords = true;
  393. }
  394. //create aiMesh if needed
  395. if ( nullptr == mGeneratedMesh ) {
  396. mGeneratedMesh = new aiMesh();
  397. mGeneratedMesh->mMaterialIndex = 0;
  398. }
  399. if (nullptr == mGeneratedMesh->mVertices) {
  400. mGeneratedMesh->mNumVertices = pcElement->NumOccur;
  401. mGeneratedMesh->mVertices = new aiVector3D[mGeneratedMesh->mNumVertices];
  402. }
  403. mGeneratedMesh->mVertices[pos] = vOut;
  404. if (haveNormal) {
  405. if (nullptr == mGeneratedMesh->mNormals)
  406. mGeneratedMesh->mNormals = new aiVector3D[mGeneratedMesh->mNumVertices];
  407. mGeneratedMesh->mNormals[pos] = nOut;
  408. }
  409. if (haveColor) {
  410. if (nullptr == mGeneratedMesh->mColors[0])
  411. mGeneratedMesh->mColors[0] = new aiColor4D[mGeneratedMesh->mNumVertices];
  412. mGeneratedMesh->mColors[0][pos] = cOut;
  413. }
  414. if (haveTextureCoords) {
  415. if (nullptr == mGeneratedMesh->mTextureCoords[0]) {
  416. mGeneratedMesh->mNumUVComponents[0] = 2;
  417. mGeneratedMesh->mTextureCoords[0] = new aiVector3D[mGeneratedMesh->mNumVertices];
  418. }
  419. mGeneratedMesh->mTextureCoords[0][pos] = tOut;
  420. }
  421. }
  422. }
  423. // ------------------------------------------------------------------------------------------------
  424. // Convert a color component to [0...1]
  425. ai_real PLYImporter::NormalizeColorValue(PLY::PropertyInstance::ValueUnion val, PLY::EDataType eType) {
  426. switch (eType)
  427. {
  428. case EDT_Float:
  429. return val.fFloat;
  430. case EDT_Double:
  431. return (ai_real)val.fDouble;
  432. case EDT_UChar:
  433. return (ai_real)val.iUInt / (ai_real)0xFF;
  434. case EDT_Char:
  435. return (ai_real)(val.iInt + (0xFF / 2)) / (ai_real)0xFF;
  436. case EDT_UShort:
  437. return (ai_real)val.iUInt / (ai_real)0xFFFF;
  438. case EDT_Short:
  439. return (ai_real)(val.iInt + (0xFFFF / 2)) / (ai_real)0xFFFF;
  440. case EDT_UInt:
  441. return (ai_real)val.iUInt / (ai_real)0xFFFF;
  442. case EDT_Int:
  443. return ((ai_real)val.iInt / (ai_real)0xFF) + 0.5f;
  444. default:;
  445. };
  446. return 0.0f;
  447. }
  448. // ------------------------------------------------------------------------------------------------
  449. // Try to extract proper faces from the PLY DOM
  450. void PLYImporter::LoadFace(const PLY::Element* pcElement, const PLY::ElementInstance* instElement, unsigned int pos)
  451. {
  452. ai_assert(NULL != pcElement);
  453. ai_assert(NULL != instElement);
  454. if (mGeneratedMesh == NULL)
  455. throw DeadlyImportError("Invalid .ply file: Vertices should be declared before faces");
  456. bool bOne = false;
  457. // index of the vertex index list
  458. unsigned int iProperty = 0xFFFFFFFF;
  459. PLY::EDataType eType = EDT_Char;
  460. bool bIsTriStrip = false;
  461. // index of the material index property
  462. //unsigned int iMaterialIndex = 0xFFFFFFFF;
  463. //PLY::EDataType eType2 = EDT_Char;
  464. // texture coordinates
  465. unsigned int iTextureCoord = 0xFFFFFFFF;
  466. PLY::EDataType eType3 = EDT_Char;
  467. // face = unique number of vertex indices
  468. if (PLY::EEST_Face == pcElement->eSemantic)
  469. {
  470. unsigned int _a = 0;
  471. for (std::vector<PLY::Property>::const_iterator a = pcElement->alProperties.begin();
  472. a != pcElement->alProperties.end(); ++a, ++_a)
  473. {
  474. if (PLY::EST_VertexIndex == (*a).Semantic)
  475. {
  476. // must be a dynamic list!
  477. if (!(*a).bIsList)
  478. continue;
  479. iProperty = _a;
  480. bOne = true;
  481. eType = (*a).eType;
  482. }
  483. /*else if (PLY::EST_MaterialIndex == (*a).Semantic)
  484. {
  485. if ((*a).bIsList)
  486. continue;
  487. iMaterialIndex = _a;
  488. bOne = true;
  489. eType2 = (*a).eType;
  490. }*/
  491. else if (PLY::EST_TextureCoordinates == (*a).Semantic)
  492. {
  493. // must be a dynamic list!
  494. if (!(*a).bIsList)
  495. continue;
  496. iTextureCoord = _a;
  497. bOne = true;
  498. eType3 = (*a).eType;
  499. }
  500. }
  501. }
  502. // triangle strip
  503. // TODO: triangle strip and material index support???
  504. else if (PLY::EEST_TriStrip == pcElement->eSemantic)
  505. {
  506. unsigned int _a = 0;
  507. for (std::vector<PLY::Property>::const_iterator a = pcElement->alProperties.begin();
  508. a != pcElement->alProperties.end(); ++a, ++_a)
  509. {
  510. // must be a dynamic list!
  511. if (!(*a).bIsList)
  512. continue;
  513. iProperty = _a;
  514. bOne = true;
  515. bIsTriStrip = true;
  516. eType = (*a).eType;
  517. break;
  518. }
  519. }
  520. // check whether we have at least one per-face information set
  521. if (bOne)
  522. {
  523. if (mGeneratedMesh->mFaces == NULL)
  524. {
  525. mGeneratedMesh->mNumFaces = pcElement->NumOccur;
  526. mGeneratedMesh->mFaces = new aiFace[mGeneratedMesh->mNumFaces];
  527. }
  528. if (!bIsTriStrip)
  529. {
  530. // parse the list of vertex indices
  531. if (0xFFFFFFFF != iProperty)
  532. {
  533. const unsigned int iNum = (unsigned int)GetProperty(instElement->alProperties, iProperty).avList.size();
  534. mGeneratedMesh->mFaces[pos].mNumIndices = iNum;
  535. mGeneratedMesh->mFaces[pos].mIndices = new unsigned int[iNum];
  536. std::vector<PLY::PropertyInstance::ValueUnion>::const_iterator p =
  537. GetProperty(instElement->alProperties, iProperty).avList.begin();
  538. for (unsigned int a = 0; a < iNum; ++a, ++p)
  539. {
  540. mGeneratedMesh->mFaces[pos].mIndices[a] = PLY::PropertyInstance::ConvertTo<unsigned int>(*p, eType);
  541. }
  542. }
  543. // parse the material index
  544. // cannot be handled without processing the whole file first
  545. /*if (0xFFFFFFFF != iMaterialIndex)
  546. {
  547. mGeneratedMesh->mFaces[pos]. = PLY::PropertyInstance::ConvertTo<unsigned int>(
  548. GetProperty(instElement->alProperties, iMaterialIndex).avList.front(), eType2);
  549. }*/
  550. if (0xFFFFFFFF != iTextureCoord)
  551. {
  552. const unsigned int iNum = (unsigned int)GetProperty(instElement->alProperties, iTextureCoord).avList.size();
  553. //should be 6 coords
  554. std::vector<PLY::PropertyInstance::ValueUnion>::const_iterator p =
  555. GetProperty(instElement->alProperties, iTextureCoord).avList.begin();
  556. if ((iNum / 3) == 2) // X Y coord
  557. {
  558. for (unsigned int a = 0; a < iNum; ++a, ++p)
  559. {
  560. unsigned int vindex = mGeneratedMesh->mFaces[pos].mIndices[a / 2];
  561. if (vindex < mGeneratedMesh->mNumVertices)
  562. {
  563. if (mGeneratedMesh->mTextureCoords[0] == NULL)
  564. {
  565. mGeneratedMesh->mNumUVComponents[0] = 2;
  566. mGeneratedMesh->mTextureCoords[0] = new aiVector3D[mGeneratedMesh->mNumVertices];
  567. }
  568. if (a % 2 == 0)
  569. mGeneratedMesh->mTextureCoords[0][vindex].x = PLY::PropertyInstance::ConvertTo<ai_real>(*p, eType3);
  570. else
  571. mGeneratedMesh->mTextureCoords[0][vindex].y = PLY::PropertyInstance::ConvertTo<ai_real>(*p, eType3);
  572. mGeneratedMesh->mTextureCoords[0][vindex].z = 0;
  573. }
  574. }
  575. }
  576. }
  577. }
  578. else // triangle strips
  579. {
  580. // normally we have only one triangle strip instance where
  581. // a value of -1 indicates a restart of the strip
  582. bool flip = false;
  583. const std::vector<PLY::PropertyInstance::ValueUnion>& quak = GetProperty(instElement->alProperties, iProperty).avList;
  584. //pvOut->reserve(pvOut->size() + quak.size() + (quak.size()>>2u)); //Limits memory consumption
  585. int aiTable[2] = { -1, -1 };
  586. for (std::vector<PLY::PropertyInstance::ValueUnion>::const_iterator a = quak.begin(); a != quak.end(); ++a) {
  587. const int p = PLY::PropertyInstance::ConvertTo<int>(*a, eType);
  588. if (-1 == p) {
  589. // restart the strip ...
  590. aiTable[0] = aiTable[1] = -1;
  591. flip = false;
  592. continue;
  593. }
  594. if (-1 == aiTable[0]) {
  595. aiTable[0] = p;
  596. continue;
  597. }
  598. if (-1 == aiTable[1]) {
  599. aiTable[1] = p;
  600. continue;
  601. }
  602. if (mGeneratedMesh->mFaces == NULL)
  603. {
  604. mGeneratedMesh->mNumFaces = pcElement->NumOccur;
  605. mGeneratedMesh->mFaces = new aiFace[mGeneratedMesh->mNumFaces];
  606. }
  607. mGeneratedMesh->mFaces[pos].mNumIndices = 3;
  608. mGeneratedMesh->mFaces[pos].mIndices = new unsigned int[3];
  609. mGeneratedMesh->mFaces[pos].mIndices[0] = aiTable[0];
  610. mGeneratedMesh->mFaces[pos].mIndices[1] = aiTable[1];
  611. mGeneratedMesh->mFaces[pos].mIndices[2] = p;
  612. if ((flip = !flip)) {
  613. std::swap(mGeneratedMesh->mFaces[pos].mIndices[0], mGeneratedMesh->mFaces[pos].mIndices[1]);
  614. }
  615. aiTable[0] = aiTable[1];
  616. aiTable[1] = p;
  617. }
  618. }
  619. }
  620. }
  621. // ------------------------------------------------------------------------------------------------
  622. // Get a RGBA color in [0...1] range
  623. void PLYImporter::GetMaterialColor(const std::vector<PLY::PropertyInstance>& avList,
  624. unsigned int aiPositions[4],
  625. PLY::EDataType aiTypes[4],
  626. aiColor4D* clrOut)
  627. {
  628. ai_assert(NULL != clrOut);
  629. if (0xFFFFFFFF == aiPositions[0])clrOut->r = 0.0f;
  630. else
  631. {
  632. clrOut->r = NormalizeColorValue(GetProperty(avList,
  633. aiPositions[0]).avList.front(), aiTypes[0]);
  634. }
  635. if (0xFFFFFFFF == aiPositions[1])clrOut->g = 0.0f;
  636. else
  637. {
  638. clrOut->g = NormalizeColorValue(GetProperty(avList,
  639. aiPositions[1]).avList.front(), aiTypes[1]);
  640. }
  641. if (0xFFFFFFFF == aiPositions[2])clrOut->b = 0.0f;
  642. else
  643. {
  644. clrOut->b = NormalizeColorValue(GetProperty(avList,
  645. aiPositions[2]).avList.front(), aiTypes[2]);
  646. }
  647. // assume 1.0 for the alpha channel ifit is not set
  648. if (0xFFFFFFFF == aiPositions[3])clrOut->a = 1.0f;
  649. else
  650. {
  651. clrOut->a = NormalizeColorValue(GetProperty(avList,
  652. aiPositions[3]).avList.front(), aiTypes[3]);
  653. }
  654. }
  655. // ------------------------------------------------------------------------------------------------
  656. // Extract a material from the PLY DOM
  657. void PLYImporter::LoadMaterial(std::vector<aiMaterial*>* pvOut, std::string &defaultTexture, const bool pointsOnly)
  658. {
  659. ai_assert(NULL != pvOut);
  660. // diffuse[4], specular[4], ambient[4]
  661. // rgba order
  662. unsigned int aaiPositions[3][4] = {
  663. { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF },
  664. { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF },
  665. { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF },
  666. };
  667. PLY::EDataType aaiTypes[3][4] = {
  668. { EDT_Char, EDT_Char, EDT_Char, EDT_Char },
  669. { EDT_Char, EDT_Char, EDT_Char, EDT_Char },
  670. { EDT_Char, EDT_Char, EDT_Char, EDT_Char }
  671. };
  672. PLY::ElementInstanceList* pcList = NULL;
  673. unsigned int iPhong = 0xFFFFFFFF;
  674. PLY::EDataType ePhong = EDT_Char;
  675. unsigned int iOpacity = 0xFFFFFFFF;
  676. PLY::EDataType eOpacity = EDT_Char;
  677. // search in the DOM for a vertex entry
  678. unsigned int _i = 0;
  679. for (std::vector<PLY::Element>::const_iterator i = this->pcDOM->alElements.begin();
  680. i != this->pcDOM->alElements.end(); ++i, ++_i)
  681. {
  682. if (PLY::EEST_Material == (*i).eSemantic)
  683. {
  684. pcList = &this->pcDOM->alElementData[_i];
  685. // now check whether which coordinate sets are available
  686. unsigned int _a = 0;
  687. for (std::vector<PLY::Property>::const_iterator
  688. a = (*i).alProperties.begin();
  689. a != (*i).alProperties.end(); ++a, ++_a)
  690. {
  691. if ((*a).bIsList)continue;
  692. // pohng specularity -----------------------------------
  693. if (PLY::EST_PhongPower == (*a).Semantic)
  694. {
  695. iPhong = _a;
  696. ePhong = (*a).eType;
  697. }
  698. // general opacity -----------------------------------
  699. if (PLY::EST_Opacity == (*a).Semantic)
  700. {
  701. iOpacity = _a;
  702. eOpacity = (*a).eType;
  703. }
  704. // diffuse color channels -----------------------------------
  705. if (PLY::EST_DiffuseRed == (*a).Semantic)
  706. {
  707. aaiPositions[0][0] = _a;
  708. aaiTypes[0][0] = (*a).eType;
  709. }
  710. else if (PLY::EST_DiffuseGreen == (*a).Semantic)
  711. {
  712. aaiPositions[0][1] = _a;
  713. aaiTypes[0][1] = (*a).eType;
  714. }
  715. else if (PLY::EST_DiffuseBlue == (*a).Semantic)
  716. {
  717. aaiPositions[0][2] = _a;
  718. aaiTypes[0][2] = (*a).eType;
  719. }
  720. else if (PLY::EST_DiffuseAlpha == (*a).Semantic)
  721. {
  722. aaiPositions[0][3] = _a;
  723. aaiTypes[0][3] = (*a).eType;
  724. }
  725. // specular color channels -----------------------------------
  726. else if (PLY::EST_SpecularRed == (*a).Semantic)
  727. {
  728. aaiPositions[1][0] = _a;
  729. aaiTypes[1][0] = (*a).eType;
  730. }
  731. else if (PLY::EST_SpecularGreen == (*a).Semantic)
  732. {
  733. aaiPositions[1][1] = _a;
  734. aaiTypes[1][1] = (*a).eType;
  735. }
  736. else if (PLY::EST_SpecularBlue == (*a).Semantic)
  737. {
  738. aaiPositions[1][2] = _a;
  739. aaiTypes[1][2] = (*a).eType;
  740. }
  741. else if (PLY::EST_SpecularAlpha == (*a).Semantic)
  742. {
  743. aaiPositions[1][3] = _a;
  744. aaiTypes[1][3] = (*a).eType;
  745. }
  746. // ambient color channels -----------------------------------
  747. else if (PLY::EST_AmbientRed == (*a).Semantic)
  748. {
  749. aaiPositions[2][0] = _a;
  750. aaiTypes[2][0] = (*a).eType;
  751. }
  752. else if (PLY::EST_AmbientGreen == (*a).Semantic)
  753. {
  754. aaiPositions[2][1] = _a;
  755. aaiTypes[2][1] = (*a).eType;
  756. }
  757. else if (PLY::EST_AmbientBlue == (*a).Semantic)
  758. {
  759. aaiPositions[2][2] = _a;
  760. aaiTypes[2][2] = (*a).eType;
  761. }
  762. else if (PLY::EST_AmbientAlpha == (*a).Semantic)
  763. {
  764. aaiPositions[2][3] = _a;
  765. aaiTypes[2][3] = (*a).eType;
  766. }
  767. }
  768. break;
  769. }
  770. else if (PLY::EEST_TextureFile == (*i).eSemantic)
  771. {
  772. defaultTexture = (*i).szName;
  773. }
  774. }
  775. // check whether we have a valid source for the material data
  776. if (NULL != pcList) {
  777. for (std::vector<ElementInstance>::const_iterator i = pcList->alInstances.begin(); i != pcList->alInstances.end(); ++i) {
  778. aiColor4D clrOut;
  779. aiMaterial* pcHelper = new aiMaterial();
  780. // build the diffuse material color
  781. GetMaterialColor((*i).alProperties, aaiPositions[0], aaiTypes[0], &clrOut);
  782. pcHelper->AddProperty<aiColor4D>(&clrOut, 1, AI_MATKEY_COLOR_DIFFUSE);
  783. // build the specular material color
  784. GetMaterialColor((*i).alProperties, aaiPositions[1], aaiTypes[1], &clrOut);
  785. pcHelper->AddProperty<aiColor4D>(&clrOut, 1, AI_MATKEY_COLOR_SPECULAR);
  786. // build the ambient material color
  787. GetMaterialColor((*i).alProperties, aaiPositions[2], aaiTypes[2], &clrOut);
  788. pcHelper->AddProperty<aiColor4D>(&clrOut, 1, AI_MATKEY_COLOR_AMBIENT);
  789. // handle phong power and shading mode
  790. int iMode = (int)aiShadingMode_Gouraud;
  791. if (0xFFFFFFFF != iPhong) {
  792. ai_real fSpec = PLY::PropertyInstance::ConvertTo<ai_real>(GetProperty((*i).alProperties, iPhong).avList.front(), ePhong);
  793. // if shininess is 0 (and the pow() calculation would therefore always
  794. // become 1, not depending on the angle), use gouraud lighting
  795. if (fSpec) {
  796. // scale this with 15 ... hopefully this is correct
  797. fSpec *= 15;
  798. pcHelper->AddProperty<ai_real>(&fSpec, 1, AI_MATKEY_SHININESS);
  799. iMode = (int)aiShadingMode_Phong;
  800. }
  801. }
  802. pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
  803. // handle opacity
  804. if (0xFFFFFFFF != iOpacity) {
  805. ai_real fOpacity = PLY::PropertyInstance::ConvertTo<ai_real>(GetProperty((*i).alProperties, iPhong).avList.front(), eOpacity);
  806. pcHelper->AddProperty<ai_real>(&fOpacity, 1, AI_MATKEY_OPACITY);
  807. }
  808. // The face order is absolutely undefined for PLY, so we have to
  809. // use two-sided rendering to be sure it's ok.
  810. const int two_sided = 1;
  811. pcHelper->AddProperty(&two_sided, 1, AI_MATKEY_TWOSIDED);
  812. //default texture
  813. if (!defaultTexture.empty())
  814. {
  815. const aiString name(defaultTexture.c_str());
  816. pcHelper->AddProperty(&name, _AI_MATKEY_TEXTURE_BASE, aiTextureType_DIFFUSE, 0);
  817. }
  818. if (!pointsOnly)
  819. {
  820. const int two_sided = 1;
  821. pcHelper->AddProperty(&two_sided, 1, AI_MATKEY_TWOSIDED);
  822. }
  823. //set to wireframe, so when using this material info we can switch to points rendering
  824. if (pointsOnly)
  825. {
  826. const int wireframe = 1;
  827. pcHelper->AddProperty(&wireframe, 1, AI_MATKEY_ENABLE_WIREFRAME);
  828. }
  829. // add the newly created material instance to the list
  830. pvOut->push_back(pcHelper);
  831. }
  832. }
  833. else
  834. {
  835. // generate a default material
  836. aiMaterial* pcHelper = new aiMaterial();
  837. // fill in a default material
  838. int iMode = (int)aiShadingMode_Gouraud;
  839. pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
  840. //generate white material most 3D engine just multiply ambient / diffuse color with actual ambient / light color
  841. aiColor3D clr;
  842. clr.b = clr.g = clr.r = 1.0f;
  843. pcHelper->AddProperty<aiColor3D>(&clr, 1, AI_MATKEY_COLOR_DIFFUSE);
  844. pcHelper->AddProperty<aiColor3D>(&clr, 1, AI_MATKEY_COLOR_SPECULAR);
  845. clr.b = clr.g = clr.r = 1.0f;
  846. pcHelper->AddProperty<aiColor3D>(&clr, 1, AI_MATKEY_COLOR_AMBIENT);
  847. // The face order is absolutely undefined for PLY, so we have to
  848. // use two-sided rendering to be sure it's ok.
  849. if (!pointsOnly)
  850. {
  851. const int two_sided = 1;
  852. pcHelper->AddProperty(&two_sided, 1, AI_MATKEY_TWOSIDED);
  853. }
  854. //default texture
  855. if (!defaultTexture.empty())
  856. {
  857. const aiString name(defaultTexture.c_str());
  858. pcHelper->AddProperty(&name, _AI_MATKEY_TEXTURE_BASE, aiTextureType_DIFFUSE, 0);
  859. }
  860. //set to wireframe, so when using this material info we can switch to points rendering
  861. if (pointsOnly)
  862. {
  863. const int wireframe = 1;
  864. pcHelper->AddProperty(&wireframe, 1, AI_MATKEY_ENABLE_WIREFRAME);
  865. }
  866. pvOut->push_back(pcHelper);
  867. }
  868. }
  869. #endif // !! ASSIMP_BUILD_NO_PLY_IMPORTER