TextureTransform.cpp 21 KB

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