ComputeUVMappingProcess.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2022, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. /** @file GenUVCoords step */
  34. #include "ComputeUVMappingProcess.h"
  35. #include "ProcessHelper.h"
  36. #include <assimp/Exceptional.h>
  37. using namespace Assimp;
  38. namespace {
  39. const static aiVector3D base_axis_y(0.0,1.0,0.0);
  40. const static aiVector3D base_axis_x(1.0,0.0,0.0);
  41. const static aiVector3D base_axis_z(0.0,0.0,1.0);
  42. const static ai_real angle_epsilon = ai_real( 0.95 );
  43. }
  44. // ------------------------------------------------------------------------------------------------
  45. // Returns whether the processing step is present in the given flag field.
  46. bool ComputeUVMappingProcess::IsActive( unsigned int pFlags) const
  47. {
  48. return (pFlags & aiProcess_GenUVCoords) != 0;
  49. }
  50. // ------------------------------------------------------------------------------------------------
  51. // Check whether a ray intersects a plane and find the intersection point
  52. inline bool PlaneIntersect(const aiRay& ray, const aiVector3D& planePos,
  53. const aiVector3D& planeNormal, aiVector3D& pos)
  54. {
  55. const ai_real b = planeNormal * (planePos - ray.pos);
  56. ai_real h = ray.dir * planeNormal;
  57. if ((h < 10e-5 && h > -10e-5) || (h = b/h) < 0)
  58. return false;
  59. pos = ray.pos + (ray.dir * h);
  60. return true;
  61. }
  62. // ------------------------------------------------------------------------------------------------
  63. // Find the first empty UV channel in a mesh
  64. inline unsigned int FindEmptyUVChannel (aiMesh* mesh)
  65. {
  66. for (unsigned int m = 0; m < AI_MAX_NUMBER_OF_TEXTURECOORDS;++m)
  67. if (!mesh->mTextureCoords[m])return m;
  68. ASSIMP_LOG_ERROR("Unable to compute UV coordinates, no free UV slot found");
  69. return UINT_MAX;
  70. }
  71. // ------------------------------------------------------------------------------------------------
  72. // Try to remove UV seams
  73. void RemoveUVSeams (aiMesh* mesh, aiVector3D* out)
  74. {
  75. // TODO: just a very rough algorithm. I think it could be done
  76. // much easier, but I don't know how and am currently too tired to
  77. // to think about a better solution.
  78. const static ai_real LOWER_LIMIT = ai_real( 0.1 );
  79. const static ai_real UPPER_LIMIT = ai_real( 0.9 );
  80. const static ai_real LOWER_EPSILON = ai_real( 10e-3 );
  81. const static ai_real UPPER_EPSILON = ai_real( 1.0-10e-3 );
  82. for (unsigned int fidx = 0; fidx < mesh->mNumFaces;++fidx)
  83. {
  84. const aiFace& face = mesh->mFaces[fidx];
  85. if (face.mNumIndices < 3) continue; // triangles and polygons only, please
  86. unsigned int smallV = face.mNumIndices, large = smallV;
  87. bool zero = false, one = false, round_to_zero = false;
  88. // Check whether this face lies on a UV seam. We can just guess,
  89. // but the assumption that a face with at least one very small
  90. // on the one side and one very large U coord on the other side
  91. // lies on a UV seam should work for most cases.
  92. for (unsigned int n = 0; n < face.mNumIndices;++n)
  93. {
  94. if (out[face.mIndices[n]].x < LOWER_LIMIT)
  95. {
  96. smallV = n;
  97. // If we have a U value very close to 0 we can't
  98. // round the others to 0, too.
  99. if (out[face.mIndices[n]].x <= LOWER_EPSILON)
  100. zero = true;
  101. else round_to_zero = true;
  102. }
  103. if (out[face.mIndices[n]].x > UPPER_LIMIT)
  104. {
  105. large = n;
  106. // If we have a U value very close to 1 we can't
  107. // round the others to 1, too.
  108. if (out[face.mIndices[n]].x >= UPPER_EPSILON)
  109. one = true;
  110. }
  111. }
  112. if (smallV != face.mNumIndices && large != face.mNumIndices)
  113. {
  114. for (unsigned int n = 0; n < face.mNumIndices;++n)
  115. {
  116. // If the u value is over the upper limit and no other u
  117. // value of that face is 0, round it to 0
  118. if (out[face.mIndices[n]].x > UPPER_LIMIT && !zero)
  119. out[face.mIndices[n]].x = 0.0;
  120. // If the u value is below the lower limit and no other u
  121. // value of that face is 1, round it to 1
  122. else if (out[face.mIndices[n]].x < LOWER_LIMIT && !one)
  123. out[face.mIndices[n]].x = 1.0;
  124. // The face contains both 0 and 1 as UV coords. This can occur
  125. // for faces which have an edge that lies directly on the seam.
  126. // Due to numerical inaccuracies one U coord becomes 0, the
  127. // other 1. But we do still have a third UV coord to determine
  128. // to which side we must round to.
  129. else if (one && zero)
  130. {
  131. if (round_to_zero && out[face.mIndices[n]].x >= UPPER_EPSILON)
  132. out[face.mIndices[n]].x = 0.0;
  133. else if (!round_to_zero && out[face.mIndices[n]].x <= LOWER_EPSILON)
  134. out[face.mIndices[n]].x = 1.0;
  135. }
  136. }
  137. }
  138. }
  139. }
  140. // ------------------------------------------------------------------------------------------------
  141. void ComputeUVMappingProcess::ComputeSphereMapping(aiMesh* mesh,const aiVector3D& axis, aiVector3D* out)
  142. {
  143. aiVector3D center, min, max;
  144. FindMeshCenter(mesh, center, min, max);
  145. // If the axis is one of x,y,z run a faster code path. It's worth the extra effort ...
  146. // currently the mapping axis will always be one of x,y,z, except if the
  147. // PretransformVertices step is used (it transforms the meshes into worldspace,
  148. // thus changing the mapping axis)
  149. if (axis * base_axis_x >= angle_epsilon) {
  150. // For each point get a normalized projection vector in the sphere,
  151. // get its longitude and latitude and map them to their respective
  152. // UV axes. Problems occur around the poles ... unsolvable.
  153. //
  154. // The spherical coordinate system looks like this:
  155. // x = cos(lon)*cos(lat)
  156. // y = sin(lon)*cos(lat)
  157. // z = sin(lat)
  158. //
  159. // Thus we can derive:
  160. // lat = arcsin (z)
  161. // lon = arctan (y/x)
  162. for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) {
  163. const aiVector3D diff = (mesh->mVertices[pnt]-center).Normalize();
  164. out[pnt] = aiVector3D((std::atan2(diff.z, diff.y) + AI_MATH_PI_F ) / AI_MATH_TWO_PI_F,
  165. (std::asin (diff.x) + AI_MATH_HALF_PI_F) / AI_MATH_PI_F, 0.0);
  166. }
  167. }
  168. else if (axis * base_axis_y >= angle_epsilon) {
  169. // ... just the same again
  170. for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) {
  171. const aiVector3D diff = (mesh->mVertices[pnt]-center).Normalize();
  172. out[pnt] = aiVector3D((std::atan2(diff.x, diff.z) + AI_MATH_PI_F ) / AI_MATH_TWO_PI_F,
  173. (std::asin (diff.y) + AI_MATH_HALF_PI_F) / AI_MATH_PI_F, 0.0);
  174. }
  175. }
  176. else if (axis * base_axis_z >= angle_epsilon) {
  177. // ... just the same again
  178. for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) {
  179. const aiVector3D diff = (mesh->mVertices[pnt]-center).Normalize();
  180. out[pnt] = aiVector3D((std::atan2(diff.y, diff.x) + AI_MATH_PI_F ) / AI_MATH_TWO_PI_F,
  181. (std::asin (diff.z) + AI_MATH_HALF_PI_F) / AI_MATH_PI_F, 0.0);
  182. }
  183. }
  184. // slower code path in case the mapping axis is not one of the coordinate system axes
  185. else {
  186. aiMatrix4x4 mTrafo;
  187. aiMatrix4x4::FromToMatrix(axis,base_axis_y,mTrafo);
  188. // again the same, except we're applying a transformation now
  189. for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) {
  190. const aiVector3D diff = ((mTrafo*mesh->mVertices[pnt])-center).Normalize();
  191. out[pnt] = aiVector3D((std::atan2(diff.y, diff.x) + AI_MATH_PI_F ) / AI_MATH_TWO_PI_F,
  192. (std::asin(diff.z) + AI_MATH_HALF_PI_F) / AI_MATH_PI_F, 0.0);
  193. }
  194. }
  195. // Now find and remove UV seams. A seam occurs if a face has a tcoord
  196. // close to zero on the one side, and a tcoord close to one on the
  197. // other side.
  198. RemoveUVSeams(mesh,out);
  199. }
  200. // ------------------------------------------------------------------------------------------------
  201. void ComputeUVMappingProcess::ComputeCylinderMapping(aiMesh* mesh,const aiVector3D& axis, aiVector3D* out)
  202. {
  203. aiVector3D center, min, max;
  204. // If the axis is one of x,y,z run a faster code path. It's worth the extra effort ...
  205. // currently the mapping axis will always be one of x,y,z, except if the
  206. // PretransformVertices step is used (it transforms the meshes into worldspace,
  207. // thus changing the mapping axis)
  208. if (axis * base_axis_x >= angle_epsilon) {
  209. FindMeshCenter(mesh, center, min, max);
  210. const ai_real diff = max.x - min.x;
  211. // If the main axis is 'z', the z coordinate of a point 'p' is mapped
  212. // directly to the texture V axis. The other axis is derived from
  213. // the angle between ( p.x - c.x, p.y - c.y ) and (1,0), where
  214. // 'c' is the center point of the mesh.
  215. for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) {
  216. const aiVector3D& pos = mesh->mVertices[pnt];
  217. aiVector3D& uv = out[pnt];
  218. uv.y = (pos.x - min.x) / diff;
  219. uv.x = (std::atan2( pos.z - center.z, pos.y - center.y) +(ai_real)AI_MATH_PI ) / (ai_real)AI_MATH_TWO_PI;
  220. }
  221. }
  222. else if (axis * base_axis_y >= angle_epsilon) {
  223. FindMeshCenter(mesh, center, min, max);
  224. const ai_real diff = max.y - min.y;
  225. // just the same ...
  226. for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) {
  227. const aiVector3D& pos = mesh->mVertices[pnt];
  228. aiVector3D& uv = out[pnt];
  229. uv.y = (pos.y - min.y) / diff;
  230. uv.x = (std::atan2( pos.x - center.x, pos.z - center.z) +(ai_real)AI_MATH_PI ) / (ai_real)AI_MATH_TWO_PI;
  231. }
  232. }
  233. else if (axis * base_axis_z >= angle_epsilon) {
  234. FindMeshCenter(mesh, center, min, max);
  235. const ai_real diff = max.z - min.z;
  236. // just the same ...
  237. for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) {
  238. const aiVector3D& pos = mesh->mVertices[pnt];
  239. aiVector3D& uv = out[pnt];
  240. uv.y = (pos.z - min.z) / diff;
  241. uv.x = (std::atan2( pos.y - center.y, pos.x - center.x) +(ai_real)AI_MATH_PI ) / (ai_real)AI_MATH_TWO_PI;
  242. }
  243. }
  244. // slower code path in case the mapping axis is not one of the coordinate system axes
  245. else {
  246. aiMatrix4x4 mTrafo;
  247. aiMatrix4x4::FromToMatrix(axis,base_axis_y,mTrafo);
  248. FindMeshCenterTransformed(mesh, center, min, max,mTrafo);
  249. const ai_real diff = max.y - min.y;
  250. // again the same, except we're applying a transformation now
  251. for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt){
  252. const aiVector3D pos = mTrafo* mesh->mVertices[pnt];
  253. aiVector3D& uv = out[pnt];
  254. uv.y = (pos.y - min.y) / diff;
  255. uv.x = (std::atan2( pos.x - center.x, pos.z - center.z) +(ai_real)AI_MATH_PI ) / (ai_real)AI_MATH_TWO_PI;
  256. }
  257. }
  258. // Now find and remove UV seams. A seam occurs if a face has a tcoord
  259. // close to zero on the one side, and a tcoord close to one on the
  260. // other side.
  261. RemoveUVSeams(mesh,out);
  262. }
  263. // ------------------------------------------------------------------------------------------------
  264. void ComputeUVMappingProcess::ComputePlaneMapping(aiMesh* mesh,const aiVector3D& axis, aiVector3D* out)
  265. {
  266. ai_real diffu,diffv;
  267. aiVector3D center, min, max;
  268. // If the axis is one of x,y,z run a faster code path. It's worth the extra effort ...
  269. // currently the mapping axis will always be one of x,y,z, except if the
  270. // PretransformVertices step is used (it transforms the meshes into worldspace,
  271. // thus changing the mapping axis)
  272. if (axis * base_axis_x >= angle_epsilon) {
  273. FindMeshCenter(mesh, center, min, max);
  274. diffu = max.z - min.z;
  275. diffv = max.y - min.y;
  276. for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) {
  277. const aiVector3D& pos = mesh->mVertices[pnt];
  278. out[pnt].Set((pos.z - min.z) / diffu,(pos.y - min.y) / diffv,0.0);
  279. }
  280. }
  281. else if (axis * base_axis_y >= angle_epsilon) {
  282. FindMeshCenter(mesh, center, min, max);
  283. diffu = max.x - min.x;
  284. diffv = max.z - min.z;
  285. for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) {
  286. const aiVector3D& pos = mesh->mVertices[pnt];
  287. out[pnt].Set((pos.x - min.x) / diffu,(pos.z - min.z) / diffv,0.0);
  288. }
  289. }
  290. else if (axis * base_axis_z >= angle_epsilon) {
  291. FindMeshCenter(mesh, center, min, max);
  292. diffu = max.x - min.x;
  293. diffv = max.y - min.y;
  294. for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) {
  295. const aiVector3D& pos = mesh->mVertices[pnt];
  296. out[pnt].Set((pos.x - min.x) / diffu,(pos.y - min.y) / diffv,0.0);
  297. }
  298. }
  299. // slower code path in case the mapping axis is not one of the coordinate system axes
  300. else
  301. {
  302. aiMatrix4x4 mTrafo;
  303. aiMatrix4x4::FromToMatrix(axis,base_axis_y,mTrafo);
  304. FindMeshCenterTransformed(mesh, center, min, max,mTrafo);
  305. diffu = max.x - min.x;
  306. diffv = max.z - min.z;
  307. // again the same, except we're applying a transformation now
  308. for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) {
  309. const aiVector3D pos = mTrafo * mesh->mVertices[pnt];
  310. out[pnt].Set((pos.x - min.x) / diffu,(pos.z - min.z) / diffv,0.0);
  311. }
  312. }
  313. // shouldn't be necessary to remove UV seams ...
  314. }
  315. // ------------------------------------------------------------------------------------------------
  316. void ComputeUVMappingProcess::ComputeBoxMapping( aiMesh*, aiVector3D* )
  317. {
  318. ASSIMP_LOG_ERROR("Mapping type currently not implemented");
  319. }
  320. // ------------------------------------------------------------------------------------------------
  321. void ComputeUVMappingProcess::Execute( aiScene* pScene)
  322. {
  323. ASSIMP_LOG_DEBUG("GenUVCoordsProcess begin");
  324. char buffer[1024];
  325. if (pScene->mFlags & AI_SCENE_FLAGS_NON_VERBOSE_FORMAT)
  326. throw DeadlyImportError("Post-processing order mismatch: expecting pseudo-indexed (\"verbose\") vertices here");
  327. std::list<MappingInfo> mappingStack;
  328. /* Iterate through all materials and search for non-UV mapped textures
  329. */
  330. for (unsigned int i = 0; i < pScene->mNumMaterials;++i)
  331. {
  332. mappingStack.clear();
  333. aiMaterial* mat = pScene->mMaterials[i];
  334. for (unsigned int a = 0; a < mat->mNumProperties;++a)
  335. {
  336. aiMaterialProperty* prop = mat->mProperties[a];
  337. if (!::strcmp( prop->mKey.data, "$tex.mapping"))
  338. {
  339. aiTextureMapping& mapping = *((aiTextureMapping*)prop->mData);
  340. if (aiTextureMapping_UV != mapping)
  341. {
  342. if (!DefaultLogger::isNullLogger())
  343. {
  344. ai_snprintf(buffer, 1024, "Found non-UV mapped texture (%s,%u). Mapping type: %s",
  345. aiTextureTypeToString((aiTextureType)prop->mSemantic),prop->mIndex,
  346. MappingTypeToString(mapping));
  347. ASSIMP_LOG_INFO(buffer);
  348. }
  349. if (aiTextureMapping_OTHER == mapping)
  350. continue;
  351. MappingInfo info (mapping);
  352. // Get further properties - currently only the major axis
  353. for (unsigned int a2 = 0; a2 < mat->mNumProperties;++a2)
  354. {
  355. aiMaterialProperty* prop2 = mat->mProperties[a2];
  356. if (prop2->mSemantic != prop->mSemantic || prop2->mIndex != prop->mIndex)
  357. continue;
  358. if ( !::strcmp( prop2->mKey.data, "$tex.mapaxis")) {
  359. info.axis = *((aiVector3D*)prop2->mData);
  360. break;
  361. }
  362. }
  363. unsigned int idx( 99999999 );
  364. // Check whether we have this mapping mode already
  365. std::list<MappingInfo>::iterator it = std::find (mappingStack.begin(),mappingStack.end(), info);
  366. if (mappingStack.end() != it)
  367. {
  368. idx = (*it).uv;
  369. }
  370. else
  371. {
  372. /* We have found a non-UV mapped texture. Now
  373. * we need to find all meshes using this material
  374. * that we can compute UV channels for them.
  375. */
  376. for (unsigned int m = 0; m < pScene->mNumMeshes;++m)
  377. {
  378. aiMesh* mesh = pScene->mMeshes[m];
  379. unsigned int outIdx = 0;
  380. if ( mesh->mMaterialIndex != i || ( outIdx = FindEmptyUVChannel(mesh) ) == UINT_MAX ||
  381. !mesh->mNumVertices)
  382. {
  383. continue;
  384. }
  385. // Allocate output storage
  386. aiVector3D* p = mesh->mTextureCoords[outIdx] = new aiVector3D[mesh->mNumVertices];
  387. switch (mapping)
  388. {
  389. case aiTextureMapping_SPHERE:
  390. ComputeSphereMapping(mesh,info.axis,p);
  391. break;
  392. case aiTextureMapping_CYLINDER:
  393. ComputeCylinderMapping(mesh,info.axis,p);
  394. break;
  395. case aiTextureMapping_PLANE:
  396. ComputePlaneMapping(mesh,info.axis,p);
  397. break;
  398. case aiTextureMapping_BOX:
  399. ComputeBoxMapping(mesh,p);
  400. break;
  401. default:
  402. ai_assert(false);
  403. }
  404. if (m && idx != outIdx)
  405. {
  406. ASSIMP_LOG_WARN("UV index mismatch. Not all meshes assigned to "
  407. "this material have equal numbers of UV channels. The UV index stored in "
  408. "the material structure does therefore not apply for all meshes. ");
  409. }
  410. idx = outIdx;
  411. }
  412. info.uv = idx;
  413. mappingStack.push_back(info);
  414. }
  415. // Update the material property list
  416. mapping = aiTextureMapping_UV;
  417. ((aiMaterial*)mat)->AddProperty(&idx,1,AI_MATKEY_UVWSRC(prop->mSemantic,prop->mIndex));
  418. }
  419. }
  420. }
  421. }
  422. ASSIMP_LOG_DEBUG("GenUVCoordsProcess finished");
  423. }