mesh.cpp 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  1. /*
  2. Minetest
  3. Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include "mesh.h"
  17. #include "debug.h"
  18. #include "log.h"
  19. #include "irrMap.h"
  20. #include <cmath>
  21. #include <iostream>
  22. #include <IAnimatedMesh.h>
  23. #include <SAnimatedMesh.h>
  24. #include <IAnimatedMeshSceneNode.h>
  25. // In Irrlicht 1.8 the signature of ITexture::lock was changed from
  26. // (bool, u32) to (E_TEXTURE_LOCK_MODE, u32).
  27. #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 7
  28. #define MY_ETLM_READ_ONLY true
  29. #else
  30. #define MY_ETLM_READ_ONLY video::ETLM_READ_ONLY
  31. #endif
  32. inline static void applyShadeFactor(video::SColor& color, float factor)
  33. {
  34. color.setRed(core::clamp(core::round32(color.getRed()*factor), 0, 255));
  35. color.setGreen(core::clamp(core::round32(color.getGreen()*factor), 0, 255));
  36. color.setBlue(core::clamp(core::round32(color.getBlue()*factor), 0, 255));
  37. }
  38. void applyFacesShading(video::SColor &color, const v3f &normal)
  39. {
  40. /*
  41. Some drawtypes have normals set to (0, 0, 0), this must result in
  42. maximum brightness: shade factor 1.0.
  43. Shade factors for aligned cube faces are:
  44. +Y 1.000000 sqrt(1.0)
  45. -Y 0.447213 sqrt(0.2)
  46. +-X 0.670820 sqrt(0.45)
  47. +-Z 0.836660 sqrt(0.7)
  48. */
  49. float x2 = normal.X * normal.X;
  50. float y2 = normal.Y * normal.Y;
  51. float z2 = normal.Z * normal.Z;
  52. if (normal.Y < 0)
  53. applyShadeFactor(color, 0.670820f * x2 + 0.447213f * y2 + 0.836660f * z2);
  54. else if ((x2 > 1e-3) || (z2 > 1e-3))
  55. applyShadeFactor(color, 0.670820f * x2 + 1.000000f * y2 + 0.836660f * z2);
  56. }
  57. scene::IAnimatedMesh* createCubeMesh(v3f scale)
  58. {
  59. video::SColor c(255,255,255,255);
  60. video::S3DVertex vertices[24] =
  61. {
  62. // Up
  63. video::S3DVertex(-0.5,+0.5,-0.5, 0,1,0, c, 0,1),
  64. video::S3DVertex(-0.5,+0.5,+0.5, 0,1,0, c, 0,0),
  65. video::S3DVertex(+0.5,+0.5,+0.5, 0,1,0, c, 1,0),
  66. video::S3DVertex(+0.5,+0.5,-0.5, 0,1,0, c, 1,1),
  67. // Down
  68. video::S3DVertex(-0.5,-0.5,-0.5, 0,-1,0, c, 0,0),
  69. video::S3DVertex(+0.5,-0.5,-0.5, 0,-1,0, c, 1,0),
  70. video::S3DVertex(+0.5,-0.5,+0.5, 0,-1,0, c, 1,1),
  71. video::S3DVertex(-0.5,-0.5,+0.5, 0,-1,0, c, 0,1),
  72. // Right
  73. video::S3DVertex(+0.5,-0.5,-0.5, 1,0,0, c, 0,1),
  74. video::S3DVertex(+0.5,+0.5,-0.5, 1,0,0, c, 0,0),
  75. video::S3DVertex(+0.5,+0.5,+0.5, 1,0,0, c, 1,0),
  76. video::S3DVertex(+0.5,-0.5,+0.5, 1,0,0, c, 1,1),
  77. // Left
  78. video::S3DVertex(-0.5,-0.5,-0.5, -1,0,0, c, 1,1),
  79. video::S3DVertex(-0.5,-0.5,+0.5, -1,0,0, c, 0,1),
  80. video::S3DVertex(-0.5,+0.5,+0.5, -1,0,0, c, 0,0),
  81. video::S3DVertex(-0.5,+0.5,-0.5, -1,0,0, c, 1,0),
  82. // Back
  83. video::S3DVertex(-0.5,-0.5,+0.5, 0,0,1, c, 1,1),
  84. video::S3DVertex(+0.5,-0.5,+0.5, 0,0,1, c, 0,1),
  85. video::S3DVertex(+0.5,+0.5,+0.5, 0,0,1, c, 0,0),
  86. video::S3DVertex(-0.5,+0.5,+0.5, 0,0,1, c, 1,0),
  87. // Front
  88. video::S3DVertex(-0.5,-0.5,-0.5, 0,0,-1, c, 0,1),
  89. video::S3DVertex(-0.5,+0.5,-0.5, 0,0,-1, c, 0,0),
  90. video::S3DVertex(+0.5,+0.5,-0.5, 0,0,-1, c, 1,0),
  91. video::S3DVertex(+0.5,-0.5,-0.5, 0,0,-1, c, 1,1),
  92. };
  93. u16 indices[6] = {0,1,2,2,3,0};
  94. scene::SMesh *mesh = new scene::SMesh();
  95. for (u32 i=0; i<6; ++i)
  96. {
  97. scene::IMeshBuffer *buf = new scene::SMeshBuffer();
  98. buf->append(vertices + 4 * i, 4, indices, 6);
  99. // Set default material
  100. buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
  101. buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
  102. buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
  103. // Add mesh buffer to mesh
  104. mesh->addMeshBuffer(buf);
  105. buf->drop();
  106. }
  107. scene::SAnimatedMesh *anim_mesh = new scene::SAnimatedMesh(mesh);
  108. mesh->drop();
  109. scaleMesh(anim_mesh, scale); // also recalculates bounding box
  110. return anim_mesh;
  111. }
  112. void scaleMesh(scene::IMesh *mesh, v3f scale)
  113. {
  114. if (mesh == NULL)
  115. return;
  116. aabb3f bbox;
  117. bbox.reset(0, 0, 0);
  118. u32 mc = mesh->getMeshBufferCount();
  119. for (u32 j = 0; j < mc; j++) {
  120. scene::IMeshBuffer *buf = mesh->getMeshBuffer(j);
  121. const u32 stride = getVertexPitchFromType(buf->getVertexType());
  122. u32 vertex_count = buf->getVertexCount();
  123. u8 *vertices = (u8 *)buf->getVertices();
  124. for (u32 i = 0; i < vertex_count; i++)
  125. ((video::S3DVertex *)(vertices + i * stride))->Pos *= scale;
  126. buf->recalculateBoundingBox();
  127. // calculate total bounding box
  128. if (j == 0)
  129. bbox = buf->getBoundingBox();
  130. else
  131. bbox.addInternalBox(buf->getBoundingBox());
  132. }
  133. mesh->setBoundingBox(bbox);
  134. }
  135. void translateMesh(scene::IMesh *mesh, v3f vec)
  136. {
  137. if (mesh == NULL)
  138. return;
  139. aabb3f bbox;
  140. bbox.reset(0, 0, 0);
  141. u32 mc = mesh->getMeshBufferCount();
  142. for (u32 j = 0; j < mc; j++) {
  143. scene::IMeshBuffer *buf = mesh->getMeshBuffer(j);
  144. const u32 stride = getVertexPitchFromType(buf->getVertexType());
  145. u32 vertex_count = buf->getVertexCount();
  146. u8 *vertices = (u8 *)buf->getVertices();
  147. for (u32 i = 0; i < vertex_count; i++)
  148. ((video::S3DVertex *)(vertices + i * stride))->Pos += vec;
  149. buf->recalculateBoundingBox();
  150. // calculate total bounding box
  151. if (j == 0)
  152. bbox = buf->getBoundingBox();
  153. else
  154. bbox.addInternalBox(buf->getBoundingBox());
  155. }
  156. mesh->setBoundingBox(bbox);
  157. }
  158. void setMeshBufferColor(scene::IMeshBuffer *buf, const video::SColor &color)
  159. {
  160. const u32 stride = getVertexPitchFromType(buf->getVertexType());
  161. u32 vertex_count = buf->getVertexCount();
  162. u8 *vertices = (u8 *) buf->getVertices();
  163. for (u32 i = 0; i < vertex_count; i++)
  164. ((video::S3DVertex *) (vertices + i * stride))->Color = color;
  165. }
  166. void setAnimatedMeshColor(scene::IAnimatedMeshSceneNode *node, const video::SColor &color)
  167. {
  168. for (u32 i = 0; i < node->getMaterialCount(); ++i) {
  169. node->getMaterial(i).EmissiveColor = color;
  170. }
  171. }
  172. void setMeshColor(scene::IMesh *mesh, const video::SColor &color)
  173. {
  174. if (mesh == NULL)
  175. return;
  176. u32 mc = mesh->getMeshBufferCount();
  177. for (u32 j = 0; j < mc; j++)
  178. setMeshBufferColor(mesh->getMeshBuffer(j), color);
  179. }
  180. template <typename F>
  181. static void applyToMesh(scene::IMesh *mesh, const F &fn)
  182. {
  183. u16 mc = mesh->getMeshBufferCount();
  184. for (u16 j = 0; j < mc; j++) {
  185. scene::IMeshBuffer *buf = mesh->getMeshBuffer(j);
  186. const u32 stride = getVertexPitchFromType(buf->getVertexType());
  187. u32 vertex_count = buf->getVertexCount();
  188. char *vertices = reinterpret_cast<char *>(buf->getVertices());
  189. for (u32 i = 0; i < vertex_count; i++)
  190. fn(reinterpret_cast<video::S3DVertex *>(vertices + i * stride));
  191. }
  192. }
  193. void colorizeMeshBuffer(scene::IMeshBuffer *buf, const video::SColor *buffercolor)
  194. {
  195. const u32 stride = getVertexPitchFromType(buf->getVertexType());
  196. u32 vertex_count = buf->getVertexCount();
  197. u8 *vertices = (u8 *) buf->getVertices();
  198. for (u32 i = 0; i < vertex_count; i++) {
  199. video::S3DVertex *vertex = (video::S3DVertex *) (vertices + i * stride);
  200. video::SColor *vc = &(vertex->Color);
  201. // Reset color
  202. *vc = *buffercolor;
  203. // Apply shading
  204. applyFacesShading(*vc, vertex->Normal);
  205. }
  206. }
  207. void setMeshColorByNormalXYZ(scene::IMesh *mesh,
  208. const video::SColor &colorX,
  209. const video::SColor &colorY,
  210. const video::SColor &colorZ)
  211. {
  212. if (!mesh)
  213. return;
  214. auto colorizator = [=] (video::S3DVertex *vertex) {
  215. f32 x = fabs(vertex->Normal.X);
  216. f32 y = fabs(vertex->Normal.Y);
  217. f32 z = fabs(vertex->Normal.Z);
  218. if (x >= y && x >= z)
  219. vertex->Color = colorX;
  220. else if (y >= z)
  221. vertex->Color = colorY;
  222. else
  223. vertex->Color = colorZ;
  224. };
  225. applyToMesh(mesh, colorizator);
  226. }
  227. void setMeshColorByNormal(scene::IMesh *mesh, const v3f &normal,
  228. const video::SColor &color)
  229. {
  230. if (!mesh)
  231. return;
  232. auto colorizator = [normal, color] (video::S3DVertex *vertex) {
  233. if (vertex->Normal == normal)
  234. vertex->Color = color;
  235. };
  236. applyToMesh(mesh, colorizator);
  237. }
  238. template <float v3f::*U, float v3f::*V>
  239. static void rotateMesh(scene::IMesh *mesh, float degrees)
  240. {
  241. degrees *= M_PI / 180.0f;
  242. float c = std::cos(degrees);
  243. float s = std::sin(degrees);
  244. auto rotator = [c, s] (video::S3DVertex *vertex) {
  245. float u = vertex->Pos.*U;
  246. float v = vertex->Pos.*V;
  247. vertex->Pos.*U = c * u - s * v;
  248. vertex->Pos.*V = s * u + c * v;
  249. };
  250. applyToMesh(mesh, rotator);
  251. }
  252. void rotateMeshXYby(scene::IMesh *mesh, f64 degrees)
  253. {
  254. rotateMesh<&v3f::X, &v3f::Y>(mesh, degrees);
  255. }
  256. void rotateMeshXZby(scene::IMesh *mesh, f64 degrees)
  257. {
  258. rotateMesh<&v3f::X, &v3f::Z>(mesh, degrees);
  259. }
  260. void rotateMeshYZby(scene::IMesh *mesh, f64 degrees)
  261. {
  262. rotateMesh<&v3f::Y, &v3f::Z>(mesh, degrees);
  263. }
  264. void rotateMeshBy6dFacedir(scene::IMesh *mesh, int facedir)
  265. {
  266. int axisdir = facedir >> 2;
  267. facedir &= 0x03;
  268. switch (facedir) {
  269. case 1: rotateMeshXZby(mesh, -90); break;
  270. case 2: rotateMeshXZby(mesh, 180); break;
  271. case 3: rotateMeshXZby(mesh, 90); break;
  272. }
  273. switch (axisdir) {
  274. case 1: rotateMeshYZby(mesh, 90); break; // z+
  275. case 2: rotateMeshYZby(mesh, -90); break; // z-
  276. case 3: rotateMeshXYby(mesh, -90); break; // x+
  277. case 4: rotateMeshXYby(mesh, 90); break; // x-
  278. case 5: rotateMeshXYby(mesh, -180); break;
  279. }
  280. }
  281. void recalculateBoundingBox(scene::IMesh *src_mesh)
  282. {
  283. aabb3f bbox;
  284. bbox.reset(0,0,0);
  285. for (u16 j = 0; j < src_mesh->getMeshBufferCount(); j++) {
  286. scene::IMeshBuffer *buf = src_mesh->getMeshBuffer(j);
  287. buf->recalculateBoundingBox();
  288. if (j == 0)
  289. bbox = buf->getBoundingBox();
  290. else
  291. bbox.addInternalBox(buf->getBoundingBox());
  292. }
  293. src_mesh->setBoundingBox(bbox);
  294. }
  295. bool checkMeshNormals(scene::IMesh *mesh)
  296. {
  297. u32 buffer_count = mesh->getMeshBufferCount();
  298. for (u32 i = 0; i < buffer_count; i++) {
  299. scene::IMeshBuffer *buffer = mesh->getMeshBuffer(i);
  300. // Here we intentionally check only first normal, assuming that if buffer
  301. // has it valid, then most likely all other ones are fine too. We can
  302. // check all of the normals to have length, but it seems like an overkill
  303. // hurting the performance and covering only really weird broken models.
  304. f32 length = buffer->getNormal(0).getLength();
  305. if (!std::isfinite(length) || length < 1e-10f)
  306. return false;
  307. }
  308. return true;
  309. }
  310. scene::IMeshBuffer* cloneMeshBuffer(scene::IMeshBuffer *mesh_buffer)
  311. {
  312. switch (mesh_buffer->getVertexType()) {
  313. case video::EVT_STANDARD: {
  314. video::S3DVertex *v = (video::S3DVertex *) mesh_buffer->getVertices();
  315. u16 *indices = mesh_buffer->getIndices();
  316. scene::SMeshBuffer *cloned_buffer = new scene::SMeshBuffer();
  317. cloned_buffer->append(v, mesh_buffer->getVertexCount(), indices,
  318. mesh_buffer->getIndexCount());
  319. return cloned_buffer;
  320. }
  321. case video::EVT_2TCOORDS: {
  322. video::S3DVertex2TCoords *v =
  323. (video::S3DVertex2TCoords *) mesh_buffer->getVertices();
  324. u16 *indices = mesh_buffer->getIndices();
  325. scene::SMeshBufferLightMap *cloned_buffer =
  326. new scene::SMeshBufferLightMap();
  327. cloned_buffer->append(v, mesh_buffer->getVertexCount(), indices,
  328. mesh_buffer->getIndexCount());
  329. return cloned_buffer;
  330. }
  331. case video::EVT_TANGENTS: {
  332. video::S3DVertexTangents *v =
  333. (video::S3DVertexTangents *) mesh_buffer->getVertices();
  334. u16 *indices = mesh_buffer->getIndices();
  335. scene::SMeshBufferTangents *cloned_buffer =
  336. new scene::SMeshBufferTangents();
  337. cloned_buffer->append(v, mesh_buffer->getVertexCount(), indices,
  338. mesh_buffer->getIndexCount());
  339. return cloned_buffer;
  340. }
  341. }
  342. // This should not happen.
  343. sanity_check(false);
  344. return NULL;
  345. }
  346. scene::SMesh* cloneMesh(scene::IMesh *src_mesh)
  347. {
  348. scene::SMesh* dst_mesh = new scene::SMesh();
  349. for (u16 j = 0; j < src_mesh->getMeshBufferCount(); j++) {
  350. scene::IMeshBuffer *temp_buf = cloneMeshBuffer(
  351. src_mesh->getMeshBuffer(j));
  352. dst_mesh->addMeshBuffer(temp_buf);
  353. temp_buf->drop();
  354. }
  355. return dst_mesh;
  356. }
  357. scene::IMesh* convertNodeboxesToMesh(const std::vector<aabb3f> &boxes,
  358. const f32 *uv_coords, float expand)
  359. {
  360. scene::SMesh* dst_mesh = new scene::SMesh();
  361. for (u16 j = 0; j < 6; j++)
  362. {
  363. scene::IMeshBuffer *buf = new scene::SMeshBuffer();
  364. buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
  365. buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
  366. dst_mesh->addMeshBuffer(buf);
  367. buf->drop();
  368. }
  369. video::SColor c(255,255,255,255);
  370. for (aabb3f box : boxes) {
  371. box.repair();
  372. box.MinEdge.X -= expand;
  373. box.MinEdge.Y -= expand;
  374. box.MinEdge.Z -= expand;
  375. box.MaxEdge.X += expand;
  376. box.MaxEdge.Y += expand;
  377. box.MaxEdge.Z += expand;
  378. // Compute texture UV coords
  379. f32 tx1 = (box.MinEdge.X / BS) + 0.5;
  380. f32 ty1 = (box.MinEdge.Y / BS) + 0.5;
  381. f32 tz1 = (box.MinEdge.Z / BS) + 0.5;
  382. f32 tx2 = (box.MaxEdge.X / BS) + 0.5;
  383. f32 ty2 = (box.MaxEdge.Y / BS) + 0.5;
  384. f32 tz2 = (box.MaxEdge.Z / BS) + 0.5;
  385. f32 txc_default[24] = {
  386. // up
  387. tx1, 1 - tz2, tx2, 1 - tz1,
  388. // down
  389. tx1, tz1, tx2, tz2,
  390. // right
  391. tz1, 1 - ty2, tz2, 1 - ty1,
  392. // left
  393. 1 - tz2, 1 - ty2, 1 - tz1, 1 - ty1,
  394. // back
  395. 1 - tx2, 1 - ty2, 1 - tx1, 1 - ty1,
  396. // front
  397. tx1, 1 - ty2, tx2, 1 - ty1,
  398. };
  399. // use default texture UV mapping if not provided
  400. const f32 *txc = uv_coords ? uv_coords : txc_default;
  401. v3f min = box.MinEdge;
  402. v3f max = box.MaxEdge;
  403. video::S3DVertex vertices[24] =
  404. {
  405. // up
  406. video::S3DVertex(min.X,max.Y,max.Z, 0,1,0, c, txc[0],txc[1]),
  407. video::S3DVertex(max.X,max.Y,max.Z, 0,1,0, c, txc[2],txc[1]),
  408. video::S3DVertex(max.X,max.Y,min.Z, 0,1,0, c, txc[2],txc[3]),
  409. video::S3DVertex(min.X,max.Y,min.Z, 0,1,0, c, txc[0],txc[3]),
  410. // down
  411. video::S3DVertex(min.X,min.Y,min.Z, 0,-1,0, c, txc[4],txc[5]),
  412. video::S3DVertex(max.X,min.Y,min.Z, 0,-1,0, c, txc[6],txc[5]),
  413. video::S3DVertex(max.X,min.Y,max.Z, 0,-1,0, c, txc[6],txc[7]),
  414. video::S3DVertex(min.X,min.Y,max.Z, 0,-1,0, c, txc[4],txc[7]),
  415. // right
  416. video::S3DVertex(max.X,max.Y,min.Z, 1,0,0, c, txc[ 8],txc[9]),
  417. video::S3DVertex(max.X,max.Y,max.Z, 1,0,0, c, txc[10],txc[9]),
  418. video::S3DVertex(max.X,min.Y,max.Z, 1,0,0, c, txc[10],txc[11]),
  419. video::S3DVertex(max.X,min.Y,min.Z, 1,0,0, c, txc[ 8],txc[11]),
  420. // left
  421. video::S3DVertex(min.X,max.Y,max.Z, -1,0,0, c, txc[12],txc[13]),
  422. video::S3DVertex(min.X,max.Y,min.Z, -1,0,0, c, txc[14],txc[13]),
  423. video::S3DVertex(min.X,min.Y,min.Z, -1,0,0, c, txc[14],txc[15]),
  424. video::S3DVertex(min.X,min.Y,max.Z, -1,0,0, c, txc[12],txc[15]),
  425. // back
  426. video::S3DVertex(max.X,max.Y,max.Z, 0,0,1, c, txc[16],txc[17]),
  427. video::S3DVertex(min.X,max.Y,max.Z, 0,0,1, c, txc[18],txc[17]),
  428. video::S3DVertex(min.X,min.Y,max.Z, 0,0,1, c, txc[18],txc[19]),
  429. video::S3DVertex(max.X,min.Y,max.Z, 0,0,1, c, txc[16],txc[19]),
  430. // front
  431. video::S3DVertex(min.X,max.Y,min.Z, 0,0,-1, c, txc[20],txc[21]),
  432. video::S3DVertex(max.X,max.Y,min.Z, 0,0,-1, c, txc[22],txc[21]),
  433. video::S3DVertex(max.X,min.Y,min.Z, 0,0,-1, c, txc[22],txc[23]),
  434. video::S3DVertex(min.X,min.Y,min.Z, 0,0,-1, c, txc[20],txc[23]),
  435. };
  436. u16 indices[] = {0,1,2,2,3,0};
  437. for(u16 j = 0; j < 24; j += 4)
  438. {
  439. scene::IMeshBuffer *buf = dst_mesh->getMeshBuffer(j / 4);
  440. buf->append(vertices + j, 4, indices, 6);
  441. }
  442. }
  443. return dst_mesh;
  444. }
  445. struct vcache
  446. {
  447. core::array<u32> tris;
  448. float score;
  449. s16 cachepos;
  450. u16 NumActiveTris;
  451. };
  452. struct tcache
  453. {
  454. u16 ind[3];
  455. float score;
  456. bool drawn;
  457. };
  458. const u16 cachesize = 32;
  459. float FindVertexScore(vcache *v)
  460. {
  461. const float CacheDecayPower = 1.5f;
  462. const float LastTriScore = 0.75f;
  463. const float ValenceBoostScale = 2.0f;
  464. const float ValenceBoostPower = 0.5f;
  465. const float MaxSizeVertexCache = 32.0f;
  466. if (v->NumActiveTris == 0)
  467. {
  468. // No tri needs this vertex!
  469. return -1.0f;
  470. }
  471. float Score = 0.0f;
  472. int CachePosition = v->cachepos;
  473. if (CachePosition < 0)
  474. {
  475. // Vertex is not in FIFO cache - no score.
  476. }
  477. else
  478. {
  479. if (CachePosition < 3)
  480. {
  481. // This vertex was used in the last triangle,
  482. // so it has a fixed score.
  483. Score = LastTriScore;
  484. }
  485. else
  486. {
  487. // Points for being high in the cache.
  488. const float Scaler = 1.0f / (MaxSizeVertexCache - 3);
  489. Score = 1.0f - (CachePosition - 3) * Scaler;
  490. Score = powf(Score, CacheDecayPower);
  491. }
  492. }
  493. // Bonus points for having a low number of tris still to
  494. // use the vert, so we get rid of lone verts quickly.
  495. float ValenceBoost = powf(v->NumActiveTris,
  496. -ValenceBoostPower);
  497. Score += ValenceBoostScale * ValenceBoost;
  498. return Score;
  499. }
  500. /*
  501. A specialized LRU cache for the Forsyth algorithm.
  502. */
  503. class f_lru
  504. {
  505. public:
  506. f_lru(vcache *v, tcache *t): vc(v), tc(t)
  507. {
  508. for (int &i : cache) {
  509. i = -1;
  510. }
  511. }
  512. // Adds this vertex index and returns the highest-scoring triangle index
  513. u32 add(u16 vert, bool updatetris = false)
  514. {
  515. bool found = false;
  516. // Mark existing pos as empty
  517. for (u16 i = 0; i < cachesize; i++)
  518. {
  519. if (cache[i] == vert)
  520. {
  521. // Move everything down
  522. for (u16 j = i; j; j--)
  523. {
  524. cache[j] = cache[j - 1];
  525. }
  526. found = true;
  527. break;
  528. }
  529. }
  530. if (!found)
  531. {
  532. if (cache[cachesize-1] != -1)
  533. vc[cache[cachesize-1]].cachepos = -1;
  534. // Move everything down
  535. for (u16 i = cachesize - 1; i; i--)
  536. {
  537. cache[i] = cache[i - 1];
  538. }
  539. }
  540. cache[0] = vert;
  541. u32 highest = 0;
  542. float hiscore = 0;
  543. if (updatetris)
  544. {
  545. // Update cache positions
  546. for (u16 i = 0; i < cachesize; i++)
  547. {
  548. if (cache[i] == -1)
  549. break;
  550. vc[cache[i]].cachepos = i;
  551. vc[cache[i]].score = FindVertexScore(&vc[cache[i]]);
  552. }
  553. // Update triangle scores
  554. for (int i : cache) {
  555. if (i == -1)
  556. break;
  557. const u16 trisize = vc[i].tris.size();
  558. for (u16 t = 0; t < trisize; t++)
  559. {
  560. tcache *tri = &tc[vc[i].tris[t]];
  561. tri->score =
  562. vc[tri->ind[0]].score +
  563. vc[tri->ind[1]].score +
  564. vc[tri->ind[2]].score;
  565. if (tri->score > hiscore)
  566. {
  567. hiscore = tri->score;
  568. highest = vc[i].tris[t];
  569. }
  570. }
  571. }
  572. }
  573. return highest;
  574. }
  575. private:
  576. s32 cache[cachesize];
  577. vcache *vc;
  578. tcache *tc;
  579. };
  580. /**
  581. Vertex cache optimization according to the Forsyth paper:
  582. http://home.comcast.net/~tom_forsyth/papers/fast_vert_cache_opt.html
  583. The function is thread-safe (read: you can optimize several meshes in different threads)
  584. \param mesh Source mesh for the operation. */
  585. scene::IMesh* createForsythOptimizedMesh(const scene::IMesh *mesh)
  586. {
  587. if (!mesh)
  588. return 0;
  589. scene::SMesh *newmesh = new scene::SMesh();
  590. newmesh->BoundingBox = mesh->getBoundingBox();
  591. const u32 mbcount = mesh->getMeshBufferCount();
  592. for (u32 b = 0; b < mbcount; ++b)
  593. {
  594. const scene::IMeshBuffer *mb = mesh->getMeshBuffer(b);
  595. if (mb->getIndexType() != video::EIT_16BIT)
  596. {
  597. //os::Printer::log("Cannot optimize a mesh with 32bit indices", ELL_ERROR);
  598. newmesh->drop();
  599. return 0;
  600. }
  601. const u32 icount = mb->getIndexCount();
  602. const u32 tcount = icount / 3;
  603. const u32 vcount = mb->getVertexCount();
  604. const u16 *ind = mb->getIndices();
  605. vcache *vc = new vcache[vcount];
  606. tcache *tc = new tcache[tcount];
  607. f_lru lru(vc, tc);
  608. // init
  609. for (u16 i = 0; i < vcount; i++)
  610. {
  611. vc[i].score = 0;
  612. vc[i].cachepos = -1;
  613. vc[i].NumActiveTris = 0;
  614. }
  615. // First pass: count how many times a vert is used
  616. for (u32 i = 0; i < icount; i += 3)
  617. {
  618. vc[ind[i]].NumActiveTris++;
  619. vc[ind[i + 1]].NumActiveTris++;
  620. vc[ind[i + 2]].NumActiveTris++;
  621. const u32 tri_ind = i/3;
  622. tc[tri_ind].ind[0] = ind[i];
  623. tc[tri_ind].ind[1] = ind[i + 1];
  624. tc[tri_ind].ind[2] = ind[i + 2];
  625. }
  626. // Second pass: list of each triangle
  627. for (u32 i = 0; i < tcount; i++)
  628. {
  629. vc[tc[i].ind[0]].tris.push_back(i);
  630. vc[tc[i].ind[1]].tris.push_back(i);
  631. vc[tc[i].ind[2]].tris.push_back(i);
  632. tc[i].drawn = false;
  633. }
  634. // Give initial scores
  635. for (u16 i = 0; i < vcount; i++)
  636. {
  637. vc[i].score = FindVertexScore(&vc[i]);
  638. }
  639. for (u32 i = 0; i < tcount; i++)
  640. {
  641. tc[i].score =
  642. vc[tc[i].ind[0]].score +
  643. vc[tc[i].ind[1]].score +
  644. vc[tc[i].ind[2]].score;
  645. }
  646. switch(mb->getVertexType())
  647. {
  648. case video::EVT_STANDARD:
  649. {
  650. video::S3DVertex *v = (video::S3DVertex *) mb->getVertices();
  651. scene::SMeshBuffer *buf = new scene::SMeshBuffer();
  652. buf->Material = mb->getMaterial();
  653. buf->Vertices.reallocate(vcount);
  654. buf->Indices.reallocate(icount);
  655. core::map<const video::S3DVertex, const u16> sind; // search index for fast operation
  656. typedef core::map<const video::S3DVertex, const u16>::Node snode;
  657. // Main algorithm
  658. u32 highest = 0;
  659. u32 drawcalls = 0;
  660. for (;;)
  661. {
  662. if (tc[highest].drawn)
  663. {
  664. bool found = false;
  665. float hiscore = 0;
  666. for (u32 t = 0; t < tcount; t++)
  667. {
  668. if (!tc[t].drawn)
  669. {
  670. if (tc[t].score > hiscore)
  671. {
  672. highest = t;
  673. hiscore = tc[t].score;
  674. found = true;
  675. }
  676. }
  677. }
  678. if (!found)
  679. break;
  680. }
  681. // Output the best triangle
  682. u16 newind = buf->Vertices.size();
  683. snode *s = sind.find(v[tc[highest].ind[0]]);
  684. if (!s)
  685. {
  686. buf->Vertices.push_back(v[tc[highest].ind[0]]);
  687. buf->Indices.push_back(newind);
  688. sind.insert(v[tc[highest].ind[0]], newind);
  689. newind++;
  690. }
  691. else
  692. {
  693. buf->Indices.push_back(s->getValue());
  694. }
  695. s = sind.find(v[tc[highest].ind[1]]);
  696. if (!s)
  697. {
  698. buf->Vertices.push_back(v[tc[highest].ind[1]]);
  699. buf->Indices.push_back(newind);
  700. sind.insert(v[tc[highest].ind[1]], newind);
  701. newind++;
  702. }
  703. else
  704. {
  705. buf->Indices.push_back(s->getValue());
  706. }
  707. s = sind.find(v[tc[highest].ind[2]]);
  708. if (!s)
  709. {
  710. buf->Vertices.push_back(v[tc[highest].ind[2]]);
  711. buf->Indices.push_back(newind);
  712. sind.insert(v[tc[highest].ind[2]], newind);
  713. }
  714. else
  715. {
  716. buf->Indices.push_back(s->getValue());
  717. }
  718. vc[tc[highest].ind[0]].NumActiveTris--;
  719. vc[tc[highest].ind[1]].NumActiveTris--;
  720. vc[tc[highest].ind[2]].NumActiveTris--;
  721. tc[highest].drawn = true;
  722. for (u16 j : tc[highest].ind) {
  723. vcache *vert = &vc[j];
  724. for (u16 t = 0; t < vert->tris.size(); t++)
  725. {
  726. if (highest == vert->tris[t])
  727. {
  728. vert->tris.erase(t);
  729. break;
  730. }
  731. }
  732. }
  733. lru.add(tc[highest].ind[0]);
  734. lru.add(tc[highest].ind[1]);
  735. highest = lru.add(tc[highest].ind[2], true);
  736. drawcalls++;
  737. }
  738. buf->setBoundingBox(mb->getBoundingBox());
  739. newmesh->addMeshBuffer(buf);
  740. buf->drop();
  741. }
  742. break;
  743. case video::EVT_2TCOORDS:
  744. {
  745. video::S3DVertex2TCoords *v = (video::S3DVertex2TCoords *) mb->getVertices();
  746. scene::SMeshBufferLightMap *buf = new scene::SMeshBufferLightMap();
  747. buf->Material = mb->getMaterial();
  748. buf->Vertices.reallocate(vcount);
  749. buf->Indices.reallocate(icount);
  750. core::map<const video::S3DVertex2TCoords, const u16> sind; // search index for fast operation
  751. typedef core::map<const video::S3DVertex2TCoords, const u16>::Node snode;
  752. // Main algorithm
  753. u32 highest = 0;
  754. u32 drawcalls = 0;
  755. for (;;)
  756. {
  757. if (tc[highest].drawn)
  758. {
  759. bool found = false;
  760. float hiscore = 0;
  761. for (u32 t = 0; t < tcount; t++)
  762. {
  763. if (!tc[t].drawn)
  764. {
  765. if (tc[t].score > hiscore)
  766. {
  767. highest = t;
  768. hiscore = tc[t].score;
  769. found = true;
  770. }
  771. }
  772. }
  773. if (!found)
  774. break;
  775. }
  776. // Output the best triangle
  777. u16 newind = buf->Vertices.size();
  778. snode *s = sind.find(v[tc[highest].ind[0]]);
  779. if (!s)
  780. {
  781. buf->Vertices.push_back(v[tc[highest].ind[0]]);
  782. buf->Indices.push_back(newind);
  783. sind.insert(v[tc[highest].ind[0]], newind);
  784. newind++;
  785. }
  786. else
  787. {
  788. buf->Indices.push_back(s->getValue());
  789. }
  790. s = sind.find(v[tc[highest].ind[1]]);
  791. if (!s)
  792. {
  793. buf->Vertices.push_back(v[tc[highest].ind[1]]);
  794. buf->Indices.push_back(newind);
  795. sind.insert(v[tc[highest].ind[1]], newind);
  796. newind++;
  797. }
  798. else
  799. {
  800. buf->Indices.push_back(s->getValue());
  801. }
  802. s = sind.find(v[tc[highest].ind[2]]);
  803. if (!s)
  804. {
  805. buf->Vertices.push_back(v[tc[highest].ind[2]]);
  806. buf->Indices.push_back(newind);
  807. sind.insert(v[tc[highest].ind[2]], newind);
  808. }
  809. else
  810. {
  811. buf->Indices.push_back(s->getValue());
  812. }
  813. vc[tc[highest].ind[0]].NumActiveTris--;
  814. vc[tc[highest].ind[1]].NumActiveTris--;
  815. vc[tc[highest].ind[2]].NumActiveTris--;
  816. tc[highest].drawn = true;
  817. for (u16 j : tc[highest].ind) {
  818. vcache *vert = &vc[j];
  819. for (u16 t = 0; t < vert->tris.size(); t++)
  820. {
  821. if (highest == vert->tris[t])
  822. {
  823. vert->tris.erase(t);
  824. break;
  825. }
  826. }
  827. }
  828. lru.add(tc[highest].ind[0]);
  829. lru.add(tc[highest].ind[1]);
  830. highest = lru.add(tc[highest].ind[2]);
  831. drawcalls++;
  832. }
  833. buf->setBoundingBox(mb->getBoundingBox());
  834. newmesh->addMeshBuffer(buf);
  835. buf->drop();
  836. }
  837. break;
  838. case video::EVT_TANGENTS:
  839. {
  840. video::S3DVertexTangents *v = (video::S3DVertexTangents *) mb->getVertices();
  841. scene::SMeshBufferTangents *buf = new scene::SMeshBufferTangents();
  842. buf->Material = mb->getMaterial();
  843. buf->Vertices.reallocate(vcount);
  844. buf->Indices.reallocate(icount);
  845. core::map<const video::S3DVertexTangents, const u16> sind; // search index for fast operation
  846. typedef core::map<const video::S3DVertexTangents, const u16>::Node snode;
  847. // Main algorithm
  848. u32 highest = 0;
  849. u32 drawcalls = 0;
  850. for (;;)
  851. {
  852. if (tc[highest].drawn)
  853. {
  854. bool found = false;
  855. float hiscore = 0;
  856. for (u32 t = 0; t < tcount; t++)
  857. {
  858. if (!tc[t].drawn)
  859. {
  860. if (tc[t].score > hiscore)
  861. {
  862. highest = t;
  863. hiscore = tc[t].score;
  864. found = true;
  865. }
  866. }
  867. }
  868. if (!found)
  869. break;
  870. }
  871. // Output the best triangle
  872. u16 newind = buf->Vertices.size();
  873. snode *s = sind.find(v[tc[highest].ind[0]]);
  874. if (!s)
  875. {
  876. buf->Vertices.push_back(v[tc[highest].ind[0]]);
  877. buf->Indices.push_back(newind);
  878. sind.insert(v[tc[highest].ind[0]], newind);
  879. newind++;
  880. }
  881. else
  882. {
  883. buf->Indices.push_back(s->getValue());
  884. }
  885. s = sind.find(v[tc[highest].ind[1]]);
  886. if (!s)
  887. {
  888. buf->Vertices.push_back(v[tc[highest].ind[1]]);
  889. buf->Indices.push_back(newind);
  890. sind.insert(v[tc[highest].ind[1]], newind);
  891. newind++;
  892. }
  893. else
  894. {
  895. buf->Indices.push_back(s->getValue());
  896. }
  897. s = sind.find(v[tc[highest].ind[2]]);
  898. if (!s)
  899. {
  900. buf->Vertices.push_back(v[tc[highest].ind[2]]);
  901. buf->Indices.push_back(newind);
  902. sind.insert(v[tc[highest].ind[2]], newind);
  903. }
  904. else
  905. {
  906. buf->Indices.push_back(s->getValue());
  907. }
  908. vc[tc[highest].ind[0]].NumActiveTris--;
  909. vc[tc[highest].ind[1]].NumActiveTris--;
  910. vc[tc[highest].ind[2]].NumActiveTris--;
  911. tc[highest].drawn = true;
  912. for (u16 j : tc[highest].ind) {
  913. vcache *vert = &vc[j];
  914. for (u16 t = 0; t < vert->tris.size(); t++)
  915. {
  916. if (highest == vert->tris[t])
  917. {
  918. vert->tris.erase(t);
  919. break;
  920. }
  921. }
  922. }
  923. lru.add(tc[highest].ind[0]);
  924. lru.add(tc[highest].ind[1]);
  925. highest = lru.add(tc[highest].ind[2]);
  926. drawcalls++;
  927. }
  928. buf->setBoundingBox(mb->getBoundingBox());
  929. newmesh->addMeshBuffer(buf);
  930. buf->drop();
  931. }
  932. break;
  933. }
  934. delete [] vc;
  935. delete [] tc;
  936. } // for each meshbuffer
  937. return newmesh;
  938. }