TextureTransform.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2025, 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 A helper class that processes texture transformations */
  34. #include "TextureTransform.h"
  35. #include <assimp/Importer.hpp>
  36. #include <assimp/postprocess.h>
  37. #include <assimp/DefaultLogger.hpp>
  38. #include <assimp/scene.h>
  39. #include <assimp/StringUtils.h>
  40. namespace Assimp {
  41. // ------------------------------------------------------------------------------------------------
  42. // Returns whether the processing step is present in the given flag field.
  43. bool TextureTransformStep::IsActive( unsigned int pFlags) const {
  44. return (pFlags & aiProcess_TransformUVCoords) != 0;
  45. }
  46. // ------------------------------------------------------------------------------------------------
  47. // Setup properties
  48. void TextureTransformStep::SetupProperties(const Importer* pImp) {
  49. configFlags = pImp->GetPropertyInteger(AI_CONFIG_PP_TUV_EVALUATE,AI_UVTRAFO_ALL);
  50. }
  51. // ------------------------------------------------------------------------------------------------
  52. void TextureTransformStep::PreProcessUVTransform(STransformVecInfo& info) {
  53. /* This function tries to simplify the input UV transformation.
  54. * That's very important as it allows us to reduce the number
  55. * of output UV channels. The order in which the transformations
  56. * are applied is - as always - scaling, rotation, translation.
  57. */
  58. int rounded;
  59. char szTemp[512] = {};
  60. /* Optimize the rotation angle. That's slightly difficult as
  61. * we have an inprecise floating-point number (when comparing
  62. * UV transformations we'll take that into account by using
  63. * an epsilon of 5 degrees). If there is a rotation value, we can't
  64. * perform any further optimizations.
  65. */
  66. if (info.mRotation) {
  67. float out = info.mRotation;
  68. rounded = static_cast<int>((info.mRotation / static_cast<float>(AI_MATH_TWO_PI)));
  69. if (rounded) {
  70. out -= rounded * static_cast<float>(AI_MATH_PI);
  71. ASSIMP_LOG_INFO("Texture coordinate rotation ", info.mRotation, " can be simplified to ", out);
  72. }
  73. // Next step - convert negative rotation angles to positives
  74. if (out < 0.f)
  75. out = (float)AI_MATH_TWO_PI * 2 + out;
  76. info.mRotation = out;
  77. return;
  78. }
  79. /* Optimize UV translation in the U direction. To determine whether
  80. * or not we can optimize we need to look at the requested mapping
  81. * type (e.g. if mirroring is active there IS a difference between
  82. * offset 2 and 3)
  83. */
  84. rounded = (int)info.mTranslation.x;
  85. if (rounded) {
  86. float out = 0.0f;
  87. szTemp[0] = 0;
  88. if (aiTextureMapMode_Wrap == info.mapU) {
  89. // Wrap - simple take the fraction of the field
  90. out = info.mTranslation.x-(float)rounded;
  91. ai_snprintf(szTemp, 512, "[w] UV U offset %f can be simplified to %f", info.mTranslation.x, out);
  92. }
  93. else if (aiTextureMapMode_Mirror == info.mapU && 1 != rounded) {
  94. // Mirror
  95. if (rounded % 2)
  96. rounded--;
  97. out = info.mTranslation.x-(float)rounded;
  98. ai_snprintf(szTemp,512,"[m/d] UV U offset %f can be simplified to %f",info.mTranslation.x,out);
  99. }
  100. else if (aiTextureMapMode_Clamp == info.mapU || aiTextureMapMode_Decal == info.mapU) {
  101. // Clamp - translations beyond 1,1 are senseless
  102. ai_snprintf(szTemp,512,"[c] UV U offset %f can be clamped to 1.0f",info.mTranslation.x);
  103. out = 1.f;
  104. }
  105. if (szTemp[0]) {
  106. ASSIMP_LOG_INFO(szTemp);
  107. info.mTranslation.x = out;
  108. }
  109. }
  110. /* Optimize UV translation in the V direction. To determine whether
  111. * or not we can optimize we need to look at the requested mapping
  112. * type (e.g. if mirroring is active there IS a difference between
  113. * offset 2 and 3)
  114. */
  115. rounded = (int)info.mTranslation.y;
  116. if (rounded) {
  117. float out = 0.0f;
  118. szTemp[0] = 0;
  119. if (aiTextureMapMode_Wrap == info.mapV) {
  120. // Wrap - simple take the fraction of the field
  121. out = info.mTranslation.y-(float)rounded;
  122. ::ai_snprintf(szTemp,512,"[w] UV V offset %f can be simplified to %f",info.mTranslation.y,out);
  123. }
  124. else if (aiTextureMapMode_Mirror == info.mapV && 1 != rounded) {
  125. // Mirror
  126. if (rounded % 2)
  127. rounded--;
  128. out = info.mTranslation.x-(float)rounded;
  129. ::ai_snprintf(szTemp,512,"[m/d] UV V offset %f can be simplified to %f",info.mTranslation.y,out);
  130. }
  131. else if (aiTextureMapMode_Clamp == info.mapV || aiTextureMapMode_Decal == info.mapV) {
  132. // Clamp - translations beyond 1,1 are senseless
  133. ::ai_snprintf(szTemp,512,"[c] UV V offset %f can be clamped to 1.0f",info.mTranslation.y);
  134. out = 1.f;
  135. }
  136. if (szTemp[0]) {
  137. ASSIMP_LOG_INFO(szTemp);
  138. info.mTranslation.y = out;
  139. }
  140. }
  141. }
  142. // ------------------------------------------------------------------------------------------------
  143. void UpdateUVIndex(const std::list<TTUpdateInfo>& l, unsigned int n) {
  144. // Don't set if == 0 && wasn't set before
  145. for (std::list<TTUpdateInfo>::const_iterator it = l.begin();it != l.end(); ++it) {
  146. const TTUpdateInfo& info = *it;
  147. if (info.directShortcut)
  148. *info.directShortcut = n;
  149. else if (!n)
  150. {
  151. info.mat->AddProperty<int>((int*)&n,1,AI_MATKEY_UVWSRC(info.semantic,info.index));
  152. }
  153. }
  154. }
  155. // ------------------------------------------------------------------------------------------------
  156. inline static const char* MappingModeToChar(aiTextureMapMode map) {
  157. if (aiTextureMapMode_Wrap == map)
  158. return "-w";
  159. if (aiTextureMapMode_Mirror == map)
  160. return "-m";
  161. return "-c";
  162. }
  163. // ------------------------------------------------------------------------------------------------
  164. void TextureTransformStep::Execute( aiScene* pScene) {
  165. ASSIMP_LOG_DEBUG("TransformUVCoordsProcess begin");
  166. /* We build a per-mesh list of texture transformations we'll need
  167. * to apply. To achieve this, we iterate through all materials,
  168. * find all textures and get their transformations and UV indices.
  169. * Then we search for all meshes using this material.
  170. */
  171. typedef std::list<STransformVecInfo> MeshTrafoList;
  172. std::vector<MeshTrafoList> meshLists(pScene->mNumMeshes);
  173. for (unsigned int i = 0; i < pScene->mNumMaterials;++i) {
  174. aiMaterial* mat = pScene->mMaterials[i];
  175. for (unsigned int a = 0; a < mat->mNumProperties;++a) {
  176. aiMaterialProperty* prop = mat->mProperties[a];
  177. if (!::strcmp( prop->mKey.data, "$tex.file")) {
  178. STransformVecInfo info;
  179. // Setup a shortcut structure to allow for a fast updating
  180. // of the UV index later
  181. TTUpdateInfo update;
  182. update.mat = (aiMaterial*) mat;
  183. update.semantic = prop->mSemantic;
  184. update.index = prop->mIndex;
  185. // Get textured properties and transform
  186. for (unsigned int a2 = 0; a2 < mat->mNumProperties;++a2) {
  187. aiMaterialProperty* prop2 = mat->mProperties[a2];
  188. if (prop2->mSemantic != prop->mSemantic || prop2->mIndex != prop->mIndex) {
  189. continue;
  190. }
  191. if ( !::strcmp( prop2->mKey.data, "$tex.uvwsrc")) {
  192. info.uvIndex = *((int*)prop2->mData);
  193. // Store a direct pointer for later use
  194. update.directShortcut = (unsigned int*) prop2->mData;
  195. }
  196. else if ( !::strcmp( prop2->mKey.data, "$tex.mapmodeu")) {
  197. info.mapU = *((aiTextureMapMode*)prop2->mData);
  198. }
  199. else if ( !::strcmp( prop2->mKey.data, "$tex.mapmodev")) {
  200. info.mapV = *((aiTextureMapMode*)prop2->mData);
  201. }
  202. else if ( !::strcmp( prop2->mKey.data, "$tex.uvtrafo")) {
  203. // ValidateDS should check this
  204. ai_assert(prop2->mDataLength >= 20);
  205. ::memcpy(&info.mTranslation.x,prop2->mData,sizeof(float)*5);
  206. // Directly remove this property from the list
  207. mat->mNumProperties--;
  208. for (unsigned int a3 = a2; a3 < mat->mNumProperties;++a3) {
  209. mat->mProperties[a3] = mat->mProperties[a3+1];
  210. }
  211. delete prop2;
  212. // Warn: could be an underflow, but this does not invoke undefined behaviour
  213. --a2;
  214. }
  215. }
  216. // Find out which transformations are to be evaluated
  217. if (!(configFlags & AI_UVTRAFO_ROTATION)) {
  218. info.mRotation = 0.f;
  219. }
  220. if (!(configFlags & AI_UVTRAFO_SCALING)) {
  221. info.mScaling = aiVector2D(1.f,1.f);
  222. }
  223. if (!(configFlags & AI_UVTRAFO_TRANSLATION)) {
  224. info.mTranslation = aiVector2D(0.f,0.f);
  225. }
  226. // Do some preprocessing
  227. PreProcessUVTransform(info);
  228. info.uvIndex = std::min(info.uvIndex,AI_MAX_NUMBER_OF_TEXTURECOORDS -1u);
  229. // Find out whether this material is used by more than
  230. // one mesh. This will make our task much, much more difficult!
  231. unsigned int cnt = 0;
  232. for (unsigned int n = 0; n < pScene->mNumMeshes;++n) {
  233. if (pScene->mMeshes[n]->mMaterialIndex == i)
  234. ++cnt;
  235. }
  236. if (!cnt)
  237. continue;
  238. else if (1 != cnt) {
  239. // This material is referenced by more than one mesh!
  240. // So we need to make sure the UV index for the texture
  241. // is identical for each of it ...
  242. info.lockedPos = AI_TT_UV_IDX_LOCK_TBD;
  243. }
  244. // Get all corresponding meshes
  245. for (unsigned int n = 0; n < pScene->mNumMeshes;++n) {
  246. aiMesh* mesh = pScene->mMeshes[n];
  247. if (mesh->mMaterialIndex != i || !mesh->mTextureCoords[0])
  248. continue;
  249. unsigned int uv = info.uvIndex;
  250. if (!mesh->mTextureCoords[uv]) {
  251. // If the requested UV index is not available, take the first one instead.
  252. uv = 0;
  253. }
  254. if (mesh->mNumUVComponents[info.uvIndex] >= 3){
  255. ASSIMP_LOG_WARN("UV transformations on 3D mapping channels are not supported");
  256. continue;
  257. }
  258. MeshTrafoList::iterator it;
  259. // Check whether we have this transform setup already
  260. for (it = meshLists[n].begin();it != meshLists[n].end(); ++it) {
  261. if ((*it) == info && (*it).uvIndex == uv) {
  262. (*it).updateList.push_back(update);
  263. break;
  264. }
  265. }
  266. if (it == meshLists[n].end()) {
  267. meshLists[n].push_back(info);
  268. meshLists[n].back().uvIndex = uv;
  269. meshLists[n].back().updateList.push_back(update);
  270. }
  271. }
  272. }
  273. }
  274. }
  275. char buffer[1024]; // should be sufficiently large
  276. unsigned int outChannels = 0, inChannels = 0, transformedChannels = 0;
  277. // Now process all meshes. Important: we don't remove unreferenced UV channels.
  278. // This is a job for the RemoveUnreferencedData-Step.
  279. for (unsigned int q = 0; q < pScene->mNumMeshes;++q) {
  280. aiMesh* mesh = pScene->mMeshes[q];
  281. MeshTrafoList& trafo = meshLists[q];
  282. inChannels += mesh->GetNumUVChannels();
  283. if (!mesh->mTextureCoords[0] || trafo.empty() || (trafo.size() == 1 && trafo.begin()->IsUntransformed())) {
  284. outChannels += mesh->GetNumUVChannels();
  285. continue;
  286. }
  287. // Move untransformed UV channels to the first position in the list ....
  288. // except if we need a new locked index which should be as small as possible
  289. bool veto = false, need = false;
  290. unsigned int cnt = 0;
  291. unsigned int untransformed = 0;
  292. MeshTrafoList::iterator it,it2;
  293. for (it = trafo.begin();it != trafo.end(); ++it,++cnt) {
  294. if (!(*it).IsUntransformed()) {
  295. need = true;
  296. }
  297. if ((*it).lockedPos == AI_TT_UV_IDX_LOCK_TBD) {
  298. // Lock this index and make sure it won't be changed
  299. (*it).lockedPos = cnt;
  300. veto = true;
  301. continue;
  302. }
  303. if (!veto && it != trafo.begin() && (*it).IsUntransformed()) {
  304. for (it2 = trafo.begin();it2 != it; ++it2) {
  305. if (!(*it2).IsUntransformed())
  306. break;
  307. }
  308. trafo.insert(it2,*it);
  309. trafo.erase(it);
  310. break;
  311. }
  312. }
  313. if (!need)
  314. continue;
  315. // Find all that are not at their 'locked' position and move them to it.
  316. // Conflicts are possible but quite unlikely.
  317. cnt = 0;
  318. for (it = trafo.begin();it != trafo.end(); ++it,++cnt) {
  319. if ((*it).lockedPos != AI_TT_UV_IDX_LOCK_NONE && (*it).lockedPos != cnt) {
  320. it2 = trafo.begin();
  321. while ((*it2).lockedPos != (*it).lockedPos)
  322. ++it2;
  323. if ((*it2).lockedPos != AI_TT_UV_IDX_LOCK_NONE) {
  324. ASSIMP_LOG_ERROR("Channel mismatch, can't compute all transformations properly [design bug]");
  325. continue;
  326. }
  327. std::swap(*it2,*it);
  328. if ((*it).lockedPos == untransformed)
  329. untransformed = cnt;
  330. }
  331. }
  332. // ... and add dummies for all unreferenced channels
  333. // at the end of the list
  334. bool ref[AI_MAX_NUMBER_OF_TEXTURECOORDS];
  335. for (unsigned int n = 0; n < AI_MAX_NUMBER_OF_TEXTURECOORDS;++n)
  336. ref[n] = !mesh->mTextureCoords[n];
  337. for (it = trafo.begin();it != trafo.end(); ++it)
  338. ref[(*it).uvIndex] = true;
  339. for (unsigned int n = 0; n < AI_MAX_NUMBER_OF_TEXTURECOORDS;++n) {
  340. if (ref[n])
  341. continue;
  342. trafo.emplace_back();
  343. trafo.back().uvIndex = n;
  344. }
  345. // Then check whether this list breaks the channel limit.
  346. // The unimportant ones are at the end of the list, so
  347. // it shouldn't be too worse if we remove them.
  348. unsigned int size = (unsigned int)trafo.size();
  349. if (size > AI_MAX_NUMBER_OF_TEXTURECOORDS) {
  350. if (!DefaultLogger::isNullLogger()) {
  351. ASSIMP_LOG_ERROR(static_cast<unsigned int>(trafo.size()), " UV channels required but just ",
  352. AI_MAX_NUMBER_OF_TEXTURECOORDS, " available");
  353. }
  354. size = AI_MAX_NUMBER_OF_TEXTURECOORDS;
  355. }
  356. aiVector3D* old[AI_MAX_NUMBER_OF_TEXTURECOORDS];
  357. for (unsigned int n = 0; n < AI_MAX_NUMBER_OF_TEXTURECOORDS;++n)
  358. old[n] = mesh->mTextureCoords[n];
  359. // Now continue and generate the output channels. Channels
  360. // that we're not going to need later can be overridden.
  361. it = trafo.begin();
  362. for (unsigned int n = 0; n < trafo.size();++n,++it) {
  363. if (n >= size) {
  364. // Try to use an untransformed channel for all channels we threw over board
  365. UpdateUVIndex((*it).updateList,untransformed);
  366. continue;
  367. }
  368. ++outChannels;
  369. // Write to the log
  370. if (!DefaultLogger::isNullLogger()) {
  371. ::ai_snprintf(buffer,1024,"Mesh %u, channel %u: t(%.3f,%.3f), s(%.3f,%.3f), r(%.3f), %s%s",
  372. q,n,
  373. (*it).mTranslation.x,
  374. (*it).mTranslation.y,
  375. (*it).mScaling.x,
  376. (*it).mScaling.y,
  377. AI_RAD_TO_DEG( (*it).mRotation),
  378. MappingModeToChar ((*it).mapU),
  379. MappingModeToChar ((*it).mapV));
  380. ASSIMP_LOG_INFO(buffer);
  381. }
  382. // Check whether we need a new buffer here
  383. if (mesh->mTextureCoords[n]) {
  384. it2 = it;
  385. ++it2;
  386. for (unsigned int m = n+1; m < size;++m, ++it2) {
  387. if ((*it2).uvIndex == n){
  388. it2 = trafo.begin();
  389. break;
  390. }
  391. }
  392. if (it2 == trafo.begin()) {
  393. {
  394. std::unique_ptr<aiVector3D[]> oldTextureCoords(mesh->mTextureCoords[n]);
  395. }
  396. mesh->mTextureCoords[n] = new aiVector3D[mesh->mNumVertices];
  397. }
  398. }
  399. else mesh->mTextureCoords[n] = new aiVector3D[mesh->mNumVertices];
  400. aiVector3D* src = old[(*it).uvIndex];
  401. aiVector3D* dest, *end;
  402. dest = mesh->mTextureCoords[n];
  403. ai_assert(nullptr != src);
  404. // Copy the data to the destination array
  405. if (dest != src) {
  406. ::memcpy(dest,src,sizeof(aiVector3D)*mesh->mNumVertices);
  407. }
  408. end = dest + mesh->mNumVertices;
  409. // Build a transformation matrix and transform all UV coords with it
  410. if (!(*it).IsUntransformed()) {
  411. const aiVector2D& trl = (*it).mTranslation;
  412. const aiVector2D& scl = (*it).mScaling;
  413. // fixme: simplify ..
  414. ++transformedChannels;
  415. aiMatrix3x3 matrix;
  416. aiMatrix3x3 m2,m3,m4,m5;
  417. m4.a1 = scl.x;
  418. m4.b2 = scl.y;
  419. m2.a3 = m2.b3 = 0.5f;
  420. m3.a3 = m3.b3 = -0.5f;
  421. if ((*it).mRotation > AI_TT_ROTATION_EPSILON )
  422. aiMatrix3x3::RotationZ((*it).mRotation,matrix);
  423. m5.a3 += trl.x; m5.b3 += trl.y;
  424. matrix = m2 * m4 * matrix * m3 * m5;
  425. for (src = dest; src != end; ++src) { /* manual homogeneous divide */
  426. src->z = 1.f;
  427. *src = matrix * *src;
  428. src->x /= src->z;
  429. src->y /= src->z;
  430. src->z = 0.f;
  431. }
  432. }
  433. // Update all UV indices
  434. UpdateUVIndex((*it).updateList,n);
  435. }
  436. }
  437. // Print some detailed statistics into the log
  438. if (!DefaultLogger::isNullLogger()) {
  439. if (transformedChannels) {
  440. ASSIMP_LOG_INFO("TransformUVCoordsProcess end: ", outChannels, " output channels (in: ", inChannels, ", modified: ", transformedChannels,")");
  441. } else {
  442. ASSIMP_LOG_INFO("TransformUVCoordsProcess finished");
  443. }
  444. }
  445. }
  446. } // namespace Assimp