TextureTransform.cpp 18 KB

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