OgreImporter.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242
  1. //
  2. // Copyright (c) 2008-2017 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include <Urho3D/Core/Context.h>
  23. #include <Urho3D/Core/ProcessUtils.h>
  24. #include <Urho3D/Core/StringUtils.h>
  25. #include <Urho3D/Graphics/Tangent.h>
  26. #include <Urho3D/IO/File.h>
  27. #include <Urho3D/IO/FileSystem.h>
  28. #include <Urho3D/Resource/XMLFile.h>
  29. #include "OgreImporterUtils.h"
  30. #ifdef WIN32
  31. #include <windows.h>
  32. #endif
  33. #include <Urho3D/DebugNew.h>
  34. static const int VERTEX_CACHE_SIZE = 32;
  35. SharedPtr<Context> context_(new Context());
  36. SharedPtr<XMLFile> meshFile_(new XMLFile(context_));
  37. SharedPtr<XMLFile> skelFile_(new XMLFile(context_));
  38. Vector<ModelIndexBuffer> indexBuffers_;
  39. Vector<ModelVertexBuffer> vertexBuffers_;
  40. Vector<Vector<ModelSubGeometryLodLevel> > subGeometries_;
  41. Vector<Vector3> subGeometryCenters_;
  42. Vector<ModelBone> bones_;
  43. Vector<ModelMorph> morphs_;
  44. Vector<String> materialNames_;
  45. BoundingBox boundingBox_;
  46. unsigned maxBones_ = 64;
  47. unsigned numSubMeshes_ = 0;
  48. bool useOneBuffer_ = true;
  49. int main(int argc, char** argv);
  50. void Run(const Vector<String>& arguments);
  51. void LoadSkeleton(const String& skeletonFileName);
  52. void LoadMesh(const String& inputFileName, bool generateTangents, bool splitSubMeshes, bool exportMorphs);
  53. void WriteOutput(const String& outputFileName, bool exportAnimations, bool rotationsOnly, bool saveMaterialList);
  54. void OptimizeIndices(ModelSubGeometryLodLevel* subGeom, ModelVertexBuffer* vb, ModelIndexBuffer* ib);
  55. void CalculateScore(ModelVertex& vertex);
  56. String SanitateAssetName(const String& name);
  57. int main(int argc, char** argv)
  58. {
  59. Vector<String> arguments;
  60. #ifdef WIN32
  61. arguments = ParseArguments(GetCommandLineW());
  62. #else
  63. arguments = ParseArguments(argc, argv);
  64. #endif
  65. Run(arguments);
  66. return 0;
  67. }
  68. void Run(const Vector<String>& arguments)
  69. {
  70. if (arguments.Size() < 2)
  71. {
  72. ErrorExit(
  73. "Usage: OgreImporter <input file> <output file> [options]\n\n"
  74. "Options:\n"
  75. "-l Output a material list file\n"
  76. "-na Do not output animations\n"
  77. "-nm Do not output morphs\n"
  78. "-r Output only rotations from animations\n"
  79. "-s Split each submesh into own vertex buffer\n"
  80. "-t Generate tangents\n"
  81. "-mb <x> Maximum number of bones per submesh, default 64\n"
  82. );
  83. }
  84. bool generateTangents = false;
  85. bool splitSubMeshes = false;
  86. bool exportAnimations = true;
  87. bool exportMorphs = true;
  88. bool rotationsOnly = false;
  89. bool saveMaterialList = false;
  90. if (arguments.Size() > 2)
  91. {
  92. for (unsigned i = 2; i < arguments.Size(); ++i)
  93. {
  94. if (arguments[i].Length() > 1 && arguments[i][0] == '-')
  95. {
  96. String argument = arguments[i].Substring(1).ToLower();
  97. if (argument == "l")
  98. saveMaterialList = true;
  99. else if (argument == "r")
  100. rotationsOnly = true;
  101. else if (argument == "s")
  102. splitSubMeshes = true;
  103. else if (argument == "t")
  104. generateTangents = true;
  105. else if (argument.Length() == 2 && argument[0] == 'n')
  106. {
  107. switch (tolower(argument[1]))
  108. {
  109. case 'a':
  110. exportAnimations = false;
  111. break;
  112. case 'm':
  113. exportMorphs = false;
  114. break;
  115. }
  116. break;
  117. }
  118. else if (argument == "mb" && i < arguments.Size() - 1)
  119. {
  120. maxBones_ = ToUInt(arguments[i + 1]);
  121. if (maxBones_ < 1)
  122. maxBones_ = 1;
  123. ++i;
  124. }
  125. }
  126. }
  127. }
  128. LoadMesh(arguments[0], generateTangents, splitSubMeshes, exportMorphs);
  129. WriteOutput(arguments[1], exportAnimations, rotationsOnly, saveMaterialList);
  130. PrintLine("Finished");
  131. }
  132. void LoadSkeleton(const String& skeletonFileName)
  133. {
  134. // Process skeleton first (if found)
  135. XMLElement skeletonRoot;
  136. File skeletonFileSource(context_);
  137. skeletonFileSource.Open(skeletonFileName);
  138. if (!skelFile_->Load(skeletonFileSource))
  139. PrintLine("Failed to load skeleton " + skeletonFileName);
  140. skeletonRoot = skelFile_->GetRoot();
  141. if (skeletonRoot)
  142. {
  143. XMLElement bonesRoot = skeletonRoot.GetChild("bones");
  144. XMLElement bone = bonesRoot.GetChild("bone");
  145. while (bone)
  146. {
  147. unsigned index = bone.GetInt("id");
  148. String name = bone.GetAttribute("name");
  149. if (index >= bones_.Size())
  150. bones_.Resize(index + 1);
  151. // Convert from right- to left-handed
  152. XMLElement position = bone.GetChild("position");
  153. float x = position.GetFloat("x");
  154. float y = position.GetFloat("y");
  155. float z = position.GetFloat("z");
  156. Vector3 pos(x, y, -z);
  157. XMLElement rotation = bone.GetChild("rotation");
  158. XMLElement axis = rotation.GetChild("axis");
  159. float angle = -rotation.GetFloat("angle") * M_RADTODEG;
  160. x = axis.GetFloat("x");
  161. y = axis.GetFloat("y");
  162. z = axis.GetFloat("z");
  163. Vector3 axisVec(x, y, -z);
  164. Quaternion rot(angle, axisVec);
  165. bones_[index].name_ = name;
  166. bones_[index].parentIndex_ = index; // Fill in the correct parent later
  167. bones_[index].bindPosition_ = pos;
  168. bones_[index].bindRotation_ = rot;
  169. bones_[index].bindScale_ = Vector3::ONE;
  170. bones_[index].collisionMask_ = 0;
  171. bones_[index].radius_ = 0.0f;
  172. bone = bone.GetNext("bone");
  173. }
  174. // Go through the bone hierarchy
  175. XMLElement boneHierarchy = skeletonRoot.GetChild("bonehierarchy");
  176. XMLElement boneParent = boneHierarchy.GetChild("boneparent");
  177. while (boneParent)
  178. {
  179. String bone = boneParent.GetAttribute("bone");
  180. String parent = boneParent.GetAttribute("parent");
  181. unsigned i = 0, j = 0;
  182. for (i = 0; i < bones_.Size() && bones_[i].name_ != bone; ++i);
  183. for (j = 0; j < bones_.Size() && bones_[j].name_ != parent; ++j);
  184. if (i >= bones_.Size() || j >= bones_.Size())
  185. ErrorExit("Found indeterminate parent bone assignment");
  186. bones_[i].parentIndex_ = j;
  187. boneParent = boneParent.GetNext("boneparent");
  188. }
  189. // Calculate bone derived positions
  190. for (unsigned i = 0; i < bones_.Size(); ++i)
  191. {
  192. Vector3 derivedPosition = bones_[i].bindPosition_;
  193. Quaternion derivedRotation = bones_[i].bindRotation_;
  194. Vector3 derivedScale = bones_[i].bindScale_;
  195. unsigned index = bones_[i].parentIndex_;
  196. if (index != i)
  197. {
  198. for (;;)
  199. {
  200. derivedPosition = bones_[index].bindPosition_ + (bones_[index].bindRotation_ * (bones_[index].bindScale_ * derivedPosition));
  201. derivedRotation = bones_[index].bindRotation_ * derivedRotation;
  202. derivedScale = bones_[index].bindScale_ * derivedScale;
  203. if (bones_[index].parentIndex_ != index)
  204. index = bones_[index].parentIndex_;
  205. else
  206. break;
  207. }
  208. }
  209. bones_[i].derivedPosition_ = derivedPosition;
  210. bones_[i].derivedRotation_ = derivedRotation;
  211. bones_[i].derivedScale_ = derivedScale;
  212. bones_[i].worldTransform_ = Matrix3x4(derivedPosition, derivedRotation, derivedScale);
  213. bones_[i].inverseWorldTransform_ = bones_[i].worldTransform_.Inverse();
  214. }
  215. PrintLine("Processed skeleton");
  216. }
  217. }
  218. void LoadMesh(const String& inputFileName, bool generateTangents, bool splitSubMeshes, bool exportMorphs)
  219. {
  220. File meshFileSource(context_);
  221. meshFileSource.Open(inputFileName);
  222. if (!meshFile_->Load(meshFileSource))
  223. ErrorExit("Could not load input file " + inputFileName);
  224. XMLElement root = meshFile_->GetRoot("mesh");
  225. XMLElement subMeshes = root.GetChild("submeshes");
  226. XMLElement skeletonLink = root.GetChild("skeletonlink");
  227. if (root.IsNull())
  228. ErrorExit("Could not load input file " + inputFileName);
  229. String skeletonName = skeletonLink.GetAttribute("name");
  230. if (!skeletonName.Empty())
  231. LoadSkeleton(GetPath(inputFileName) + GetFileName(skeletonName) + ".skeleton.xml");
  232. // Check whether there's benefit of avoiding 32bit indices by splitting each submesh into own buffer
  233. XMLElement subMesh = subMeshes.GetChild("submesh");
  234. unsigned totalVertices = 0;
  235. unsigned maxSubMeshVertices = 0;
  236. while (subMesh)
  237. {
  238. materialNames_.Push(subMesh.GetAttribute("material"));
  239. XMLElement geometry = subMesh.GetChild("geometry");
  240. if (geometry)
  241. {
  242. unsigned vertices = geometry.GetInt("vertexcount");
  243. totalVertices += vertices;
  244. if (maxSubMeshVertices < vertices)
  245. maxSubMeshVertices = vertices;
  246. }
  247. ++numSubMeshes_;
  248. subMesh = subMesh.GetNext("submesh");
  249. }
  250. XMLElement sharedGeometry = root.GetChild("sharedgeometry");
  251. if (sharedGeometry)
  252. {
  253. unsigned vertices = sharedGeometry.GetInt("vertexcount");
  254. totalVertices += vertices;
  255. if (maxSubMeshVertices < vertices)
  256. maxSubMeshVertices = vertices;
  257. }
  258. if (!sharedGeometry && (splitSubMeshes || (totalVertices > 65535 && maxSubMeshVertices <= 65535)))
  259. {
  260. useOneBuffer_ = false;
  261. vertexBuffers_.Resize(numSubMeshes_);
  262. indexBuffers_.Resize(numSubMeshes_);
  263. }
  264. else
  265. {
  266. vertexBuffers_.Resize(1);
  267. indexBuffers_.Resize(1);
  268. }
  269. subMesh = subMeshes.GetChild("submesh");
  270. unsigned indexStart = 0;
  271. unsigned vertexStart = 0;
  272. unsigned subMeshIndex = 0;
  273. PODVector<unsigned> vertexStarts;
  274. vertexStarts.Resize(numSubMeshes_);
  275. while (subMesh)
  276. {
  277. XMLElement geometry = subMesh.GetChild("geometry");
  278. XMLElement faces = subMesh.GetChild("faces");
  279. // If no submesh vertexbuffer, process the shared geometry, but do it only once
  280. unsigned vertices = 0;
  281. if (!geometry)
  282. {
  283. vertexStart = 0;
  284. if (!subMeshIndex)
  285. geometry = root.GetChild("sharedgeometry");
  286. }
  287. if (geometry)
  288. vertices = geometry.GetInt("vertexcount");
  289. ModelSubGeometryLodLevel subGeometryLodLevel;
  290. ModelVertexBuffer* vBuf;
  291. ModelIndexBuffer* iBuf;
  292. if (useOneBuffer_)
  293. {
  294. vBuf = &vertexBuffers_[0];
  295. if (vertices)
  296. vBuf->vertices_.Resize(vertexStart + vertices);
  297. iBuf = &indexBuffers_[0];
  298. subGeometryLodLevel.vertexBuffer_ = 0;
  299. subGeometryLodLevel.indexBuffer_ = 0;
  300. }
  301. else
  302. {
  303. vertexStart = 0;
  304. indexStart = 0;
  305. vBuf = &vertexBuffers_[subMeshIndex];
  306. vBuf->vertices_.Resize(vertices);
  307. iBuf = &indexBuffers_[subMeshIndex];
  308. subGeometryLodLevel.vertexBuffer_ = subMeshIndex;
  309. subGeometryLodLevel.indexBuffer_ = subMeshIndex;
  310. }
  311. // Store the start vertex for later use
  312. vertexStarts[subMeshIndex] = vertexStart;
  313. // Ogre may have multiple buffers in one submesh. These will be merged into one
  314. XMLElement bufferDef;
  315. if (geometry)
  316. bufferDef = geometry.GetChild("vertexbuffer");
  317. while (bufferDef)
  318. {
  319. if (bufferDef.HasAttribute("positions"))
  320. vBuf->elementMask_ |= MASK_POSITION;
  321. if (bufferDef.HasAttribute("normals"))
  322. vBuf->elementMask_ |= MASK_NORMAL;
  323. if (bufferDef.HasAttribute("texture_coords"))
  324. {
  325. vBuf->elementMask_ |= MASK_TEXCOORD1;
  326. if (bufferDef.GetInt("texture_coords") > 1)
  327. vBuf->elementMask_ |= MASK_TEXCOORD2;
  328. }
  329. unsigned vertexNum = vertexStart;
  330. if (vertices)
  331. {
  332. XMLElement vertex = bufferDef.GetChild("vertex");
  333. while (vertex)
  334. {
  335. XMLElement position = vertex.GetChild("position");
  336. if (position)
  337. {
  338. // Convert from right- to left-handed
  339. float x = position.GetFloat("x");
  340. float y = position.GetFloat("y");
  341. float z = position.GetFloat("z");
  342. Vector3 vec(x, y, -z);
  343. vBuf->vertices_[vertexNum].position_ = vec;
  344. boundingBox_.Merge(vec);
  345. }
  346. XMLElement normal = vertex.GetChild("normal");
  347. if (normal)
  348. {
  349. // Convert from right- to left-handed
  350. float x = normal.GetFloat("x");
  351. float y = normal.GetFloat("y");
  352. float z = normal.GetFloat("z");
  353. Vector3 vec(x, y, -z);
  354. vBuf->vertices_[vertexNum].normal_ = vec;
  355. }
  356. XMLElement uv = vertex.GetChild("texcoord");
  357. if (uv)
  358. {
  359. float x = uv.GetFloat("u");
  360. float y = uv.GetFloat("v");
  361. Vector2 vec(x, y);
  362. vBuf->vertices_[vertexNum].texCoord1_ = vec;
  363. if (vBuf->elementMask_ & MASK_TEXCOORD2)
  364. {
  365. uv = uv.GetNext("texcoord");
  366. if (uv)
  367. {
  368. float x = uv.GetFloat("u");
  369. float y = uv.GetFloat("v");
  370. Vector2 vec(x, y);
  371. vBuf->vertices_[vertexNum].texCoord2_ = vec;
  372. }
  373. }
  374. }
  375. vertexNum++;
  376. vertex = vertex.GetNext("vertex");
  377. }
  378. }
  379. bufferDef = bufferDef.GetNext("vertexbuffer");
  380. }
  381. unsigned triangles = faces.GetInt("count");
  382. unsigned indices = triangles * 3;
  383. XMLElement triangle = faces.GetChild("face");
  384. while (triangle)
  385. {
  386. unsigned v1 = triangle.GetInt("v1");
  387. unsigned v2 = triangle.GetInt("v2");
  388. unsigned v3 = triangle.GetInt("v3");
  389. iBuf->indices_.Push(v3 + vertexStart);
  390. iBuf->indices_.Push(v2 + vertexStart);
  391. iBuf->indices_.Push(v1 + vertexStart);
  392. triangle = triangle.GetNext("face");
  393. }
  394. subGeometryLodLevel.indexStart_ = indexStart;
  395. subGeometryLodLevel.indexCount_ = indices;
  396. if (vertexStart + vertices > 65535)
  397. iBuf->indexSize_ = sizeof(unsigned);
  398. XMLElement boneAssignments = subMesh.GetChild("boneassignments");
  399. if (bones_.Size())
  400. {
  401. if (boneAssignments)
  402. {
  403. XMLElement boneAssignment = boneAssignments.GetChild("vertexboneassignment");
  404. while (boneAssignment)
  405. {
  406. unsigned vertex = boneAssignment.GetInt("vertexindex") + vertexStart;
  407. unsigned bone = boneAssignment.GetInt("boneindex");
  408. float weight = boneAssignment.GetFloat("weight");
  409. BoneWeightAssignment assign;
  410. assign.boneIndex_ = bone;
  411. assign.weight_ = weight;
  412. // Source data might have 0 weights. Disregard these
  413. if (assign.weight_ > 0.0f)
  414. {
  415. subGeometryLodLevel.boneWeights_[vertex].Push(assign);
  416. // Require skinning weight to be sufficiently large before vertex contributes to bone hitbox
  417. if (assign.weight_ > 0.33f)
  418. {
  419. // Check distance of vertex from bone to get bone max. radius information
  420. Vector3 bonePos = bones_[bone].derivedPosition_;
  421. Vector3 vertexPos = vBuf->vertices_[vertex].position_;
  422. float distance = (bonePos - vertexPos).Length();
  423. if (distance > bones_[bone].radius_)
  424. {
  425. bones_[bone].collisionMask_ |= 1;
  426. bones_[bone].radius_ = distance;
  427. }
  428. // Build the hitbox for the bone
  429. bones_[bone].boundingBox_.Merge(bones_[bone].inverseWorldTransform_ * (vertexPos));
  430. bones_[bone].collisionMask_ |= 2;
  431. }
  432. }
  433. boneAssignment = boneAssignment.GetNext("vertexboneassignment");
  434. }
  435. }
  436. if ((subGeometryLodLevel.boneWeights_.Size()) && bones_.Size())
  437. {
  438. vBuf->elementMask_ |= MASK_BLENDWEIGHTS | MASK_BLENDINDICES;
  439. bool sorted = false;
  440. // If amount of bones is larger than supported by HW skinning, must remap per submesh
  441. if (bones_.Size() > maxBones_)
  442. {
  443. HashMap<unsigned, unsigned> usedBoneMap;
  444. unsigned remapIndex = 0;
  445. for (HashMap<unsigned, PODVector<BoneWeightAssignment> >::Iterator i =
  446. subGeometryLodLevel.boneWeights_.Begin(); i != subGeometryLodLevel.boneWeights_.End(); ++i)
  447. {
  448. // Sort the bone assigns by weight
  449. Sort(i->second_.Begin(), i->second_.End(), CompareWeights);
  450. // Use only the first 4 weights
  451. for (unsigned j = 0; j < i->second_.Size() && j < 4; ++j)
  452. {
  453. unsigned originalIndex = i->second_[j].boneIndex_;
  454. if (!usedBoneMap.Contains(originalIndex))
  455. {
  456. usedBoneMap[originalIndex] = remapIndex;
  457. remapIndex++;
  458. }
  459. i->second_[j].boneIndex_ = usedBoneMap[originalIndex];
  460. }
  461. }
  462. // If still too many bones in one subgeometry, error
  463. if (usedBoneMap.Size() > maxBones_)
  464. ErrorExit("Too many bones (limit " + String(maxBones_) + ") in submesh " + String(subMeshIndex + 1));
  465. // Write mapping of vertex buffer bone indices to original bone indices
  466. subGeometryLodLevel.boneMapping_.Resize(usedBoneMap.Size());
  467. for (HashMap<unsigned, unsigned>::Iterator j = usedBoneMap.Begin(); j != usedBoneMap.End(); ++j)
  468. subGeometryLodLevel.boneMapping_[j->second_] = j->first_;
  469. sorted = true;
  470. }
  471. for (HashMap<unsigned, PODVector<BoneWeightAssignment> >::Iterator i = subGeometryLodLevel.boneWeights_.Begin();
  472. i != subGeometryLodLevel.boneWeights_.End(); ++i)
  473. {
  474. // Sort the bone assigns by weight, if not sorted yet in bone remapping pass
  475. if (!sorted)
  476. Sort(i->second_.Begin(), i->second_.End(), CompareWeights);
  477. float totalWeight = 0.0f;
  478. float normalizationFactor = 0.0f;
  479. // Calculate normalization factor in case there are more than 4 blend weights, or they do not add up to 1
  480. for (unsigned j = 0; j < i->second_.Size() && j < 4; ++j)
  481. totalWeight += i->second_[j].weight_;
  482. if (totalWeight > 0.0f)
  483. normalizationFactor = 1.0f / totalWeight;
  484. for (unsigned j = 0; j < i->second_.Size() && j < 4; ++j)
  485. {
  486. vBuf->vertices_[i->first_].blendIndices_[j] = i->second_[j].boneIndex_;
  487. vBuf->vertices_[i->first_].blendWeights_[j] = i->second_[j].weight_ * normalizationFactor;
  488. }
  489. // If there are less than 4 blend weights, fill rest with zero
  490. for (unsigned j = i->second_.Size(); j < 4; ++j)
  491. {
  492. vBuf->vertices_[i->first_].blendIndices_[j] = 0;
  493. vBuf->vertices_[i->first_].blendWeights_[j] = 0.0f;
  494. }
  495. vBuf->vertices_[i->first_].hasBlendWeights_ = true;
  496. }
  497. }
  498. }
  499. else if (boneAssignments)
  500. PrintLine("No skeleton loaded, skipping skinning information");
  501. // Calculate center for the subgeometry
  502. Vector3 center = Vector3::ZERO;
  503. for (unsigned i = 0; i < iBuf->indices_.Size(); i += 3)
  504. {
  505. center += vBuf->vertices_[iBuf->indices_[i]].position_;
  506. center += vBuf->vertices_[iBuf->indices_[i + 1]].position_;
  507. center += vBuf->vertices_[iBuf->indices_[i + 2]].position_;
  508. }
  509. if (iBuf->indices_.Size())
  510. center /= (float)iBuf->indices_.Size();
  511. subGeometryCenters_.Push(center);
  512. indexStart += indices;
  513. vertexStart += vertices;
  514. OptimizeIndices(&subGeometryLodLevel, vBuf, iBuf);
  515. PrintLine("Processed submesh " + String(subMeshIndex + 1) + ": " + String(vertices) + " vertices " +
  516. String(triangles) + " triangles");
  517. Vector<ModelSubGeometryLodLevel> thisSubGeometry;
  518. thisSubGeometry.Push(subGeometryLodLevel);
  519. subGeometries_.Push(thisSubGeometry);
  520. subMesh = subMesh.GetNext("submesh");
  521. subMeshIndex++;
  522. }
  523. // Process LOD levels, if any
  524. XMLElement lods = root.GetChild("levelofdetail");
  525. if (lods)
  526. {
  527. try
  528. {
  529. // For now, support only generated LODs, where the vertices are the same
  530. XMLElement lod = lods.GetChild("lodgenerated");
  531. while (lod)
  532. {
  533. float distance = M_EPSILON;
  534. if (lod.HasAttribute("fromdepthsquared"))
  535. distance = sqrtf(lod.GetFloat("fromdepthsquared"));
  536. if (lod.HasAttribute("value"))
  537. distance = lod.GetFloat("value");
  538. XMLElement lodSubMesh = lod.GetChild("lodfacelist");
  539. while (lodSubMesh)
  540. {
  541. unsigned subMeshIndex = lodSubMesh.GetInt("submeshindex");
  542. unsigned triangles = lodSubMesh.GetInt("numfaces");
  543. ModelSubGeometryLodLevel newLodLevel;
  544. ModelSubGeometryLodLevel& originalLodLevel = subGeometries_[subMeshIndex][0];
  545. // Copy all initial values
  546. newLodLevel = originalLodLevel;
  547. ModelVertexBuffer* vBuf;
  548. ModelIndexBuffer* iBuf;
  549. if (useOneBuffer_)
  550. {
  551. vBuf = &vertexBuffers_[0];
  552. iBuf = &indexBuffers_[0];
  553. }
  554. else
  555. {
  556. vBuf = &vertexBuffers_[subMeshIndex];
  557. iBuf = &indexBuffers_[subMeshIndex];
  558. }
  559. unsigned indexStart = iBuf->indices_.Size();
  560. unsigned indexCount = triangles * 3;
  561. unsigned vertexStart = vertexStarts[subMeshIndex];
  562. newLodLevel.distance_ = distance;
  563. newLodLevel.indexStart_ = indexStart;
  564. newLodLevel.indexCount_ = indexCount;
  565. // Append indices to the original index buffer
  566. XMLElement triangle = lodSubMesh.GetChild("face");
  567. while (triangle)
  568. {
  569. unsigned v1 = triangle.GetInt("v1");
  570. unsigned v2 = triangle.GetInt("v2");
  571. unsigned v3 = triangle.GetInt("v3");
  572. iBuf->indices_.Push(v3 + vertexStart);
  573. iBuf->indices_.Push(v2 + vertexStart);
  574. iBuf->indices_.Push(v1 + vertexStart);
  575. triangle = triangle.GetNext("face");
  576. }
  577. OptimizeIndices(&newLodLevel, vBuf, iBuf);
  578. subGeometries_[subMeshIndex].Push(newLodLevel);
  579. PrintLine("Processed LOD level for submesh " + String(subMeshIndex + 1) + ": distance " + String(distance));
  580. lodSubMesh = lodSubMesh.GetNext("lodfacelist");
  581. }
  582. lod = lod.GetNext("lodgenerated");
  583. }
  584. }
  585. catch (...) {}
  586. }
  587. // Process poses/morphs
  588. // First find out all pose definitions
  589. if (exportMorphs)
  590. {
  591. try
  592. {
  593. Vector<XMLElement> poses;
  594. XMLElement posesRoot = root.GetChild("poses");
  595. if (posesRoot)
  596. {
  597. XMLElement pose = posesRoot.GetChild("pose");
  598. while (pose)
  599. {
  600. poses.Push(pose);
  601. pose = pose.GetNext("pose");
  602. }
  603. }
  604. // Then process animations using the poses
  605. XMLElement animsRoot = root.GetChild("animations");
  606. if (animsRoot)
  607. {
  608. XMLElement anim = animsRoot.GetChild("animation");
  609. while (anim)
  610. {
  611. String name = anim.GetAttribute("name");
  612. float length = anim.GetFloat("length");
  613. HashSet<unsigned> usedPoses;
  614. XMLElement tracks = anim.GetChild("tracks");
  615. if (tracks)
  616. {
  617. XMLElement track = tracks.GetChild("track");
  618. while (track)
  619. {
  620. XMLElement keyframes = track.GetChild("keyframes");
  621. if (keyframes)
  622. {
  623. XMLElement keyframe = keyframes.GetChild("keyframe");
  624. while (keyframe)
  625. {
  626. float time = keyframe.GetFloat("time");
  627. XMLElement poseref = keyframe.GetChild("poseref");
  628. // Get only the end pose
  629. if (poseref && time == length)
  630. usedPoses.Insert(poseref.GetInt("poseindex"));
  631. keyframe = keyframe.GetNext("keyframe");
  632. }
  633. }
  634. track = track.GetNext("track");
  635. }
  636. }
  637. if (usedPoses.Size())
  638. {
  639. ModelMorph newMorph;
  640. newMorph.name_ = name;
  641. if (useOneBuffer_)
  642. newMorph.buffers_.Resize(1);
  643. else
  644. newMorph.buffers_.Resize(usedPoses.Size());
  645. unsigned bufIndex = 0;
  646. for (HashSet<unsigned>::Iterator i = usedPoses.Begin(); i != usedPoses.End(); ++i)
  647. {
  648. XMLElement pose = poses[*i];
  649. unsigned targetSubMesh = pose.GetInt("index");
  650. XMLElement poseOffset = pose.GetChild("poseoffset");
  651. if (useOneBuffer_)
  652. newMorph.buffers_[bufIndex].vertexBuffer_ = 0;
  653. else
  654. newMorph.buffers_[bufIndex].vertexBuffer_ = targetSubMesh;
  655. newMorph.buffers_[bufIndex].elementMask_ = MASK_POSITION;
  656. ModelVertexBuffer* vBuf = &vertexBuffers_[newMorph.buffers_[bufIndex].vertexBuffer_];
  657. while (poseOffset)
  658. {
  659. // Convert from right- to left-handed
  660. unsigned vertexIndex = poseOffset.GetInt("index") + vertexStarts[targetSubMesh];
  661. float x = poseOffset.GetFloat("x");
  662. float y = poseOffset.GetFloat("y");
  663. float z = poseOffset.GetFloat("z");
  664. Vector3 vec(x, y, -z);
  665. if (vBuf->morphCount_ == 0)
  666. {
  667. vBuf->morphStart_ = vertexIndex;
  668. vBuf->morphCount_ = 1;
  669. }
  670. else
  671. {
  672. unsigned first = vBuf->morphStart_;
  673. unsigned last = first + vBuf->morphCount_ - 1;
  674. if (vertexIndex < first)
  675. first = vertexIndex;
  676. if (vertexIndex > last)
  677. last = vertexIndex;
  678. vBuf->morphStart_ = first;
  679. vBuf->morphCount_ = last - first + 1;
  680. }
  681. ModelVertex newVertex;
  682. newVertex.position_ = vec;
  683. newMorph.buffers_[bufIndex].vertices_.Push(MakePair(vertexIndex, newVertex));
  684. poseOffset = poseOffset.GetNext("poseoffset");
  685. }
  686. if (!useOneBuffer_)
  687. ++bufIndex;
  688. }
  689. morphs_.Push(newMorph);
  690. PrintLine("Processed morph " + name + " with " + String(usedPoses.Size()) + " sub-poses");
  691. }
  692. anim = anim.GetNext("animation");
  693. }
  694. }
  695. }
  696. catch (...) {}
  697. }
  698. // Check any of the buffers for vertices with missing blend weight assignments
  699. for (unsigned i = 0; i < vertexBuffers_.Size(); ++i)
  700. {
  701. if (vertexBuffers_[i].elementMask_ & MASK_BLENDWEIGHTS)
  702. {
  703. for (unsigned j = 0; j < vertexBuffers_[i].vertices_.Size(); ++j)
  704. if (!vertexBuffers_[i].vertices_[j].hasBlendWeights_)
  705. ErrorExit("Found a vertex with missing skinning information");
  706. }
  707. }
  708. // Tangent generation
  709. if (generateTangents)
  710. {
  711. for (unsigned i = 0; i < subGeometries_.Size(); ++i)
  712. {
  713. for (unsigned j = 0; j < subGeometries_[i].Size(); ++j)
  714. {
  715. ModelVertexBuffer& vBuf = vertexBuffers_[subGeometries_[i][j].vertexBuffer_];
  716. ModelIndexBuffer& iBuf = indexBuffers_[subGeometries_[i][j].indexBuffer_];
  717. unsigned indexStart = subGeometries_[i][j].indexStart_;
  718. unsigned indexCount = subGeometries_[i][j].indexCount_;
  719. // If already has tangents, do not regenerate
  720. if (vBuf.elementMask_ & MASK_TANGENT || vBuf.vertices_.Empty() || iBuf.indices_.Empty())
  721. continue;
  722. vBuf.elementMask_ |= MASK_TANGENT;
  723. if ((vBuf.elementMask_ & (MASK_POSITION | MASK_NORMAL | MASK_TEXCOORD1)) != (MASK_POSITION | MASK_NORMAL |
  724. MASK_TEXCOORD1))
  725. ErrorExit("To generate tangents, positions normals and texcoords are required");
  726. GenerateTangents(&vBuf.vertices_[0], sizeof(ModelVertex), &iBuf.indices_[0], sizeof(unsigned), indexStart,
  727. indexCount, offsetof(ModelVertex, normal_), offsetof(ModelVertex, texCoord1_), offsetof(ModelVertex,
  728. tangent_));
  729. PrintLine("Generated tangents");
  730. }
  731. }
  732. }
  733. }
  734. void WriteOutput(const String& outputFileName, bool exportAnimations, bool rotationsOnly, bool saveMaterialList)
  735. {
  736. /// \todo Use save functions of Model & Animation classes
  737. // Begin serialization
  738. {
  739. File dest(context_);
  740. if (!dest.Open(outputFileName, FILE_WRITE))
  741. ErrorExit("Could not open output file " + outputFileName);
  742. // ID
  743. dest.WriteFileID("UMD2");
  744. // Vertexbuffers
  745. dest.WriteUInt(vertexBuffers_.Size());
  746. for (unsigned i = 0; i < vertexBuffers_.Size(); ++i)
  747. vertexBuffers_[i].WriteData(dest);
  748. // Indexbuffers
  749. dest.WriteUInt(indexBuffers_.Size());
  750. for (unsigned i = 0; i < indexBuffers_.Size(); ++i)
  751. indexBuffers_[i].WriteData(dest);
  752. // Subgeometries
  753. dest.WriteUInt(subGeometries_.Size());
  754. for (unsigned i = 0; i < subGeometries_.Size(); ++i)
  755. {
  756. // Write bone mapping info from the first LOD level. It does not change for further LODs
  757. dest.WriteUInt(subGeometries_[i][0].boneMapping_.Size());
  758. for (unsigned k = 0; k < subGeometries_[i][0].boneMapping_.Size(); ++k)
  759. dest.WriteUInt(subGeometries_[i][0].boneMapping_[k]);
  760. // Lod levels for this subgeometry
  761. dest.WriteUInt(subGeometries_[i].Size());
  762. for (unsigned j = 0; j < subGeometries_[i].Size(); ++j)
  763. {
  764. dest.WriteFloat(subGeometries_[i][j].distance_);
  765. dest.WriteUInt((unsigned)subGeometries_[i][j].primitiveType_);
  766. dest.WriteUInt(subGeometries_[i][j].vertexBuffer_);
  767. dest.WriteUInt(subGeometries_[i][j].indexBuffer_);
  768. dest.WriteUInt(subGeometries_[i][j].indexStart_);
  769. dest.WriteUInt(subGeometries_[i][j].indexCount_);
  770. }
  771. }
  772. // Morphs
  773. dest.WriteUInt(morphs_.Size());
  774. for (unsigned i = 0; i < morphs_.Size(); ++i)
  775. morphs_[i].WriteData(dest);
  776. // Skeleton
  777. dest.WriteUInt(bones_.Size());
  778. for (unsigned i = 0; i < bones_.Size(); ++i)
  779. {
  780. dest.WriteString(bones_[i].name_);
  781. dest.WriteUInt(bones_[i].parentIndex_);
  782. dest.WriteVector3(bones_[i].bindPosition_);
  783. dest.WriteQuaternion(bones_[i].bindRotation_);
  784. dest.WriteVector3(bones_[i].bindScale_);
  785. Matrix3x4 offsetMatrix(bones_[i].derivedPosition_, bones_[i].derivedRotation_, bones_[i].derivedScale_);
  786. offsetMatrix = offsetMatrix.Inverse();
  787. dest.Write(offsetMatrix.Data(), sizeof(Matrix3x4));
  788. dest.WriteUByte(bones_[i].collisionMask_);
  789. if (bones_[i].collisionMask_ & 1)
  790. dest.WriteFloat(bones_[i].radius_);
  791. if (bones_[i].collisionMask_ & 2)
  792. dest.WriteBoundingBox(bones_[i].boundingBox_);
  793. }
  794. // Bounding box
  795. dest.WriteBoundingBox(boundingBox_);
  796. // Geometry centers
  797. for (unsigned i = 0; i < subGeometryCenters_.Size(); ++i)
  798. dest.WriteVector3(subGeometryCenters_[i]);
  799. }
  800. if (saveMaterialList)
  801. {
  802. String materialListName = ReplaceExtension(outputFileName, ".txt");
  803. File listFile(context_);
  804. if (listFile.Open(materialListName, FILE_WRITE))
  805. {
  806. for (unsigned i = 0; i < materialNames_.Size(); ++i)
  807. {
  808. // Assume the materials will be located inside the standard Materials subdirectory
  809. listFile.WriteLine("Materials/" + ReplaceExtension(SanitateAssetName(materialNames_[i]), ".xml"));
  810. }
  811. }
  812. else
  813. PrintLine("Warning: could not write material list file " + materialListName);
  814. }
  815. XMLElement skeletonRoot = skelFile_->GetRoot("skeleton");
  816. if (skeletonRoot && exportAnimations)
  817. {
  818. // Go through animations
  819. XMLElement animationsRoot = skeletonRoot.GetChild("animations");
  820. if (animationsRoot)
  821. {
  822. XMLElement animation = animationsRoot.GetChild("animation");
  823. while (animation)
  824. {
  825. ModelAnimation newAnimation;
  826. newAnimation.name_ = animation.GetAttribute("name");
  827. newAnimation.length_ = animation.GetFloat("length");
  828. XMLElement tracksRoot = animation.GetChild("tracks");
  829. XMLElement track = tracksRoot.GetChild("track");
  830. while (track)
  831. {
  832. String trackName = track.GetAttribute("bone");
  833. ModelBone* bone = nullptr;
  834. for (unsigned i = 0; i < bones_.Size(); ++i)
  835. {
  836. if (bones_[i].name_ == trackName)
  837. {
  838. bone = &bones_[i];
  839. break;
  840. }
  841. }
  842. if (!bone)
  843. ErrorExit("Found animation track for unknown bone " + trackName);
  844. AnimationTrack newAnimationTrack;
  845. newAnimationTrack.name_ = trackName;
  846. if (!rotationsOnly)
  847. newAnimationTrack.channelMask_ = CHANNEL_POSITION | CHANNEL_ROTATION;
  848. else
  849. newAnimationTrack.channelMask_ = CHANNEL_ROTATION;
  850. XMLElement keyFramesRoot = track.GetChild("keyframes");
  851. XMLElement keyFrame = keyFramesRoot.GetChild("keyframe");
  852. while (keyFrame)
  853. {
  854. AnimationKeyFrame newKeyFrame;
  855. // Convert from right- to left-handed
  856. XMLElement position = keyFrame.GetChild("translate");
  857. float x = position.GetFloat("x");
  858. float y = position.GetFloat("y");
  859. float z = position.GetFloat("z");
  860. Vector3 pos(x, y, -z);
  861. XMLElement rotation = keyFrame.GetChild("rotate");
  862. XMLElement axis = rotation.GetChild("axis");
  863. float angle = -rotation.GetFloat("angle") * M_RADTODEG;
  864. x = axis.GetFloat("x");
  865. y = axis.GetFloat("y");
  866. z = axis.GetFloat("z");
  867. Vector3 axisVec(x, y, -z);
  868. Quaternion rot(angle, axisVec);
  869. // Transform from bind-pose relative into absolute
  870. pos = bone->bindPosition_ + pos;
  871. rot = bone->bindRotation_ * rot;
  872. newKeyFrame.time_ = keyFrame.GetFloat("time");
  873. newKeyFrame.position_ = pos;
  874. newKeyFrame.rotation_ = rot;
  875. newAnimationTrack.keyFrames_.Push(newKeyFrame);
  876. keyFrame = keyFrame.GetNext("keyframe");
  877. }
  878. // Make sure keyframes are sorted from beginning to end
  879. Sort(newAnimationTrack.keyFrames_.Begin(), newAnimationTrack.keyFrames_.End(), CompareKeyFrames);
  880. // Do not add tracks with no keyframes
  881. if (newAnimationTrack.keyFrames_.Size())
  882. newAnimation.tracks_.Push(newAnimationTrack);
  883. track = track.GetNext("track");
  884. }
  885. // Write each animation into a separate file
  886. String animationFileName = outputFileName.Replaced(".mdl", "");
  887. animationFileName += "_" + newAnimation.name_ + ".ani";
  888. File dest(context_);
  889. if (!dest.Open(animationFileName, FILE_WRITE))
  890. ErrorExit("Could not open output file " + animationFileName);
  891. dest.WriteFileID("UANI");
  892. dest.WriteString(newAnimation.name_);
  893. dest.WriteFloat(newAnimation.length_);
  894. dest.WriteUInt(newAnimation.tracks_.Size());
  895. for (unsigned i = 0; i < newAnimation.tracks_.Size(); ++i)
  896. {
  897. AnimationTrack& track = newAnimation.tracks_[i];
  898. dest.WriteString(track.name_);
  899. dest.WriteUByte(track.channelMask_);
  900. dest.WriteUInt(track.keyFrames_.Size());
  901. for (unsigned j = 0; j < track.keyFrames_.Size(); ++j)
  902. {
  903. AnimationKeyFrame& keyFrame = track.keyFrames_[j];
  904. dest.WriteFloat(keyFrame.time_);
  905. if (track.channelMask_ & CHANNEL_POSITION)
  906. dest.WriteVector3(keyFrame.position_);
  907. if (track.channelMask_ & CHANNEL_ROTATION)
  908. dest.WriteQuaternion(keyFrame.rotation_);
  909. if (track.channelMask_ & CHANNEL_SCALE)
  910. dest.WriteVector3(keyFrame.scale_);
  911. }
  912. }
  913. animation = animation.GetNext("animation");
  914. PrintLine("Processed animation " + newAnimation.name_);
  915. }
  916. }
  917. }
  918. }
  919. void OptimizeIndices(ModelSubGeometryLodLevel* subGeom, ModelVertexBuffer* vb, ModelIndexBuffer* ib)
  920. {
  921. PODVector<Triangle> oldTriangles;
  922. PODVector<Triangle> newTriangles;
  923. if (subGeom->indexCount_ % 3)
  924. {
  925. PrintLine("Index count is not divisible by 3, skipping index optimization");
  926. return;
  927. }
  928. for (unsigned i = 0; i < vb->vertices_.Size(); ++i)
  929. {
  930. vb->vertices_[i].useCount_ = 0;
  931. vb->vertices_[i].cachePosition_ = -1;
  932. }
  933. for (unsigned i = subGeom->indexStart_; i < subGeom->indexStart_ + subGeom->indexCount_; i += 3)
  934. {
  935. Triangle triangle;
  936. triangle.v0_ = ib->indices_[i];
  937. triangle.v1_ = ib->indices_[i + 1];
  938. triangle.v2_ = ib->indices_[i + 2];
  939. vb->vertices_[triangle.v0_].useCount_++;
  940. vb->vertices_[triangle.v1_].useCount_++;
  941. vb->vertices_[triangle.v2_].useCount_++;
  942. oldTriangles.Push(triangle);
  943. }
  944. for (unsigned i = 0; i < vb->vertices_.Size(); ++i)
  945. CalculateScore(vb->vertices_[i]);
  946. PODVector<unsigned> vertexCache;
  947. while (oldTriangles.Size())
  948. {
  949. unsigned bestTriangle = M_MAX_UNSIGNED;
  950. float bestTriangleScore = -1.0f;
  951. // Find the best triangle at this point
  952. for (unsigned i = 0; i < oldTriangles.Size(); ++i)
  953. {
  954. Triangle& triangle = oldTriangles[i];
  955. float triangleScore =
  956. vb->vertices_[triangle.v0_].score_ +
  957. vb->vertices_[triangle.v1_].score_ +
  958. vb->vertices_[triangle.v2_].score_;
  959. if (triangleScore > bestTriangleScore)
  960. {
  961. bestTriangle = i;
  962. bestTriangleScore = triangleScore;
  963. }
  964. }
  965. if (bestTriangle == M_MAX_UNSIGNED)
  966. {
  967. PrintLine("Could not find next triangle, aborting index optimization");
  968. return;
  969. }
  970. // Add the best triangle
  971. Triangle triangleCopy = oldTriangles[bestTriangle];
  972. newTriangles.Push(triangleCopy);
  973. oldTriangles.Erase(oldTriangles.Begin() + bestTriangle);
  974. // Reduce the use count
  975. vb->vertices_[triangleCopy.v0_].useCount_--;
  976. vb->vertices_[triangleCopy.v1_].useCount_--;
  977. vb->vertices_[triangleCopy.v2_].useCount_--;
  978. // Model the LRU cache behaviour
  979. // Erase the triangle vertices from the middle of the cache, if they were there
  980. for (unsigned i = 0; i < vertexCache.Size(); ++i)
  981. {
  982. if ((vertexCache[i] == triangleCopy.v0_) ||
  983. (vertexCache[i] == triangleCopy.v1_) ||
  984. (vertexCache[i] == triangleCopy.v2_))
  985. {
  986. vertexCache.Erase(vertexCache.Begin() + i);
  987. --i;
  988. }
  989. }
  990. // Then push them to the front
  991. vertexCache.Insert(vertexCache.Begin(), triangleCopy.v0_);
  992. vertexCache.Insert(vertexCache.Begin(), triangleCopy.v1_);
  993. vertexCache.Insert(vertexCache.Begin(), triangleCopy.v2_);
  994. // Update positions & scores of all vertices in the cache
  995. // Give position -1 if vertex is going to be erased
  996. for (unsigned i = 0; i < vertexCache.Size(); ++i)
  997. {
  998. ModelVertex& vertex = vb->vertices_[vertexCache[i]];
  999. if (i >= VERTEX_CACHE_SIZE)
  1000. vertex.cachePosition_ = -1;
  1001. else
  1002. vertex.cachePosition_ = i;
  1003. CalculateScore(vertex);
  1004. }
  1005. // Finally erase the extra vertices
  1006. if (vertexCache.Size() > VERTEX_CACHE_SIZE)
  1007. vertexCache.Resize(VERTEX_CACHE_SIZE);
  1008. }
  1009. // Rewrite the index data now
  1010. unsigned i = subGeom->indexStart_;
  1011. for (unsigned j = 0; j < newTriangles.Size(); ++j)
  1012. {
  1013. ib->indices_[i++] = newTriangles[j].v0_;
  1014. ib->indices_[i++] = newTriangles[j].v1_;
  1015. ib->indices_[i++] = newTriangles[j].v2_;
  1016. }
  1017. }
  1018. void CalculateScore(ModelVertex& vertex)
  1019. {
  1020. // Linear-Speed Vertex Cache Optimisation by Tom Forsyth from
  1021. // http://home.comcast.net/~tom_forsyth/papers/fast_vert_cache_opt.html
  1022. const float cacheDecayPower = 1.5f;
  1023. const float lastTriScore = 0.75f;
  1024. const float valenceBoostScale = 2.0f;
  1025. const float valenceBoostPower = 0.5f;
  1026. if (vertex.useCount_ == 0)
  1027. {
  1028. // No tri needs this vertex!
  1029. vertex.score_ = -1.0f;
  1030. return;
  1031. }
  1032. float score = 0.0f;
  1033. int cachePosition = vertex.cachePosition_;
  1034. if (cachePosition < 0)
  1035. {
  1036. // Vertex is not in FIFO cache - no score.
  1037. }
  1038. else
  1039. {
  1040. if (cachePosition < 3)
  1041. {
  1042. // This vertex was used in the last triangle,
  1043. // so it has a fixed score, whichever of the three
  1044. // it's in. Otherwise, you can get very different
  1045. // answers depending on whether you add
  1046. // the triangle 1,2,3 or 3,1,2 - which is silly.
  1047. score = lastTriScore;
  1048. }
  1049. else
  1050. {
  1051. // Points for being high in the cache.
  1052. const float scaler = 1.0f / (VERTEX_CACHE_SIZE - 3);
  1053. score = 1.0f - (cachePosition - 3) * scaler;
  1054. score = powf(score, cacheDecayPower);
  1055. }
  1056. }
  1057. // Bonus points for having a low number of tris still to
  1058. // use the vert, so we get rid of lone verts quickly.
  1059. float valenceBoost = powf((float)vertex.useCount_, -valenceBoostPower);
  1060. score += valenceBoostScale * valenceBoost;
  1061. vertex.score_ = score;
  1062. }
  1063. String SanitateAssetName(const String& name)
  1064. {
  1065. String fixedName = name;
  1066. fixedName.Replace("<", "");
  1067. fixedName.Replace(">", "");
  1068. fixedName.Replace("?", "");
  1069. fixedName.Replace("*", "");
  1070. fixedName.Replace(":", "");
  1071. fixedName.Replace("\"", "");
  1072. fixedName.Replace("/", "");
  1073. fixedName.Replace("\\", "");
  1074. fixedName.Replace("|", "");
  1075. return fixedName;
  1076. }