babylon.meshSimplification.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var SimplificationSettings = (function () {
  4. function SimplificationSettings(quality, distance) {
  5. this.quality = quality;
  6. this.distance = distance;
  7. }
  8. return SimplificationSettings;
  9. })();
  10. BABYLON.SimplificationSettings = SimplificationSettings;
  11. var SimplificationQueue = (function () {
  12. function SimplificationQueue() {
  13. this.running = false;
  14. this._simplificationArray = [];
  15. }
  16. SimplificationQueue.prototype.addTask = function (task) {
  17. this._simplificationArray.push(task);
  18. };
  19. SimplificationQueue.prototype.executeNext = function () {
  20. var task = this._simplificationArray.pop();
  21. if (task) {
  22. this.running = true;
  23. this.runSimplification(task);
  24. }
  25. else {
  26. this.running = false;
  27. }
  28. };
  29. SimplificationQueue.prototype.runSimplification = function (task) {
  30. var _this = this;
  31. function setLODLevel(distance, mesh) {
  32. }
  33. if (task.parallelProcessing) {
  34. //parallel simplifier
  35. task.settings.forEach(function (setting) {
  36. var simplifier = _this.getSimplifier(task);
  37. simplifier.simplify(setting, function (newMesh) {
  38. task.mesh.addLODLevel(setting.distance, newMesh);
  39. //check if it is the last
  40. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  41. //all done, run the success callback.
  42. task.successCallback();
  43. }
  44. _this.executeNext();
  45. });
  46. });
  47. }
  48. else {
  49. //single simplifier.
  50. var simplifier = this.getSimplifier(task);
  51. var runDecimation = function (setting, callback) {
  52. simplifier.simplify(setting, function (newMesh) {
  53. task.mesh.addLODLevel(setting.distance, newMesh);
  54. //run the next quality level
  55. callback();
  56. });
  57. };
  58. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  59. runDecimation(task.settings[loop.index], function () {
  60. loop.executeNext();
  61. });
  62. }, function () {
  63. //execution ended, run the success callback.
  64. if (task.successCallback) {
  65. task.successCallback();
  66. }
  67. _this.executeNext();
  68. });
  69. }
  70. };
  71. SimplificationQueue.prototype.getSimplifier = function (task) {
  72. switch (task.simplificationType) {
  73. case 0 /* QUADRATIC */:
  74. default:
  75. return new QuadraticErrorSimplification(task.mesh);
  76. }
  77. };
  78. return SimplificationQueue;
  79. })();
  80. BABYLON.SimplificationQueue = SimplificationQueue;
  81. /**
  82. * The implemented types of simplification.
  83. * At the moment only Quadratic Error Decimation is implemented.
  84. */
  85. (function (SimplificationType) {
  86. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  87. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  88. var SimplificationType = BABYLON.SimplificationType;
  89. var DecimationTriangle = (function () {
  90. function DecimationTriangle(vertices) {
  91. this.vertices = vertices;
  92. this.error = new Array(4);
  93. this.deleted = false;
  94. this.isDirty = false;
  95. this.deletePending = false;
  96. this.borderFactor = 0;
  97. }
  98. return DecimationTriangle;
  99. })();
  100. BABYLON.DecimationTriangle = DecimationTriangle;
  101. var DecimationVertex = (function () {
  102. function DecimationVertex(position, normal, uv, id) {
  103. this.position = position;
  104. this.normal = normal;
  105. this.uv = uv;
  106. this.id = id;
  107. this.isBorder = true;
  108. this.q = new QuadraticMatrix();
  109. this.triangleCount = 0;
  110. this.triangleStart = 0;
  111. }
  112. return DecimationVertex;
  113. })();
  114. BABYLON.DecimationVertex = DecimationVertex;
  115. var QuadraticMatrix = (function () {
  116. function QuadraticMatrix(data) {
  117. this.data = new Array(10);
  118. for (var i = 0; i < 10; ++i) {
  119. if (data && data[i]) {
  120. this.data[i] = data[i];
  121. }
  122. else {
  123. this.data[i] = 0;
  124. }
  125. }
  126. }
  127. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  128. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] + this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] - this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  129. return det;
  130. };
  131. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  132. for (var i = 0; i < 10; ++i) {
  133. this.data[i] += matrix.data[i];
  134. }
  135. };
  136. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  137. for (var i = 0; i < 10; ++i) {
  138. this.data[i] += data[i];
  139. }
  140. };
  141. QuadraticMatrix.prototype.add = function (matrix) {
  142. var m = new QuadraticMatrix();
  143. for (var i = 0; i < 10; ++i) {
  144. m.data[i] = this.data[i] + matrix.data[i];
  145. }
  146. return m;
  147. };
  148. QuadraticMatrix.FromData = function (a, b, c, d) {
  149. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  150. };
  151. //returning an array to avoid garbage collection
  152. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  153. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  154. };
  155. return QuadraticMatrix;
  156. })();
  157. BABYLON.QuadraticMatrix = QuadraticMatrix;
  158. var Reference = (function () {
  159. function Reference(vertexId, triangleId) {
  160. this.vertexId = vertexId;
  161. this.triangleId = triangleId;
  162. }
  163. return Reference;
  164. })();
  165. BABYLON.Reference = Reference;
  166. /**
  167. * An implementation of the Quadratic Error simplification algorithm.
  168. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  169. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  170. * @author RaananW
  171. */
  172. var QuadraticErrorSimplification = (function () {
  173. function QuadraticErrorSimplification(_mesh) {
  174. this._mesh = _mesh;
  175. this.initialised = false;
  176. this.syncIterations = 5000;
  177. this.aggressiveness = 7;
  178. this.decimationIterations = 100;
  179. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  180. }
  181. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  182. var _this = this;
  183. this.initDecimatedMesh();
  184. //iterating through the submeshes array, one after the other.
  185. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  186. _this.initWithMesh(_this._mesh, loop.index, function () {
  187. _this.runDecimation(settings, loop.index, function () {
  188. loop.executeNext();
  189. });
  190. });
  191. }, function () {
  192. setTimeout(function () {
  193. _this._reconstructedMesh.isVisible = true;
  194. successCallback(_this._reconstructedMesh);
  195. }, 0);
  196. });
  197. };
  198. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  199. var _this = this;
  200. var gCount = 0;
  201. triangle.vertices.forEach(function (vId) {
  202. var count = 0;
  203. var vPos = _this.vertices[vId].position;
  204. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  205. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  206. ++count;
  207. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  208. ++count;
  209. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  210. ++count;
  211. if (count > 1) {
  212. ++gCount;
  213. }
  214. ;
  215. });
  216. if (gCount > 1) {
  217. console.log(triangle, gCount);
  218. }
  219. return gCount > 1;
  220. };
  221. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  222. var _this = this;
  223. var targetCount = ~~(this.triangles.length * settings.quality);
  224. var deletedTriangles = 0;
  225. var triangleCount = this.triangles.length;
  226. var iterationFunction = function (iteration, callback) {
  227. setTimeout(function () {
  228. if (iteration % 5 === 0) {
  229. _this.updateMesh(iteration === 0);
  230. }
  231. for (var i = 0; i < _this.triangles.length; ++i) {
  232. _this.triangles[i].isDirty = false;
  233. }
  234. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  235. var trianglesIterator = function (i) {
  236. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  237. var t = _this.triangles[tIdx];
  238. if (!t)
  239. return;
  240. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  241. return;
  242. }
  243. for (var j = 0; j < 3; ++j) {
  244. if (t.error[j] < threshold) {
  245. var deleted0 = [];
  246. var deleted1 = [];
  247. var i0 = t.vertices[j];
  248. var i1 = t.vertices[(j + 1) % 3];
  249. var v0 = _this.vertices[i0];
  250. var v1 = _this.vertices[i1];
  251. if (v0.isBorder !== v1.isBorder)
  252. continue;
  253. var p = BABYLON.Vector3.Zero();
  254. var n = BABYLON.Vector3.Zero();
  255. var uv = BABYLON.Vector2.Zero();
  256. var color = new BABYLON.Color4(0, 0, 0, 1);
  257. _this.calculateError(v0, v1, p, n, uv, color);
  258. var delTr = [];
  259. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor, delTr))
  260. continue;
  261. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor, delTr))
  262. continue;
  263. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  264. continue;
  265. var uniqueArray = [];
  266. delTr.forEach(function (deletedT) {
  267. if (uniqueArray.indexOf(deletedT) === -1) {
  268. deletedT.deletePending = true;
  269. uniqueArray.push(deletedT);
  270. }
  271. });
  272. if (uniqueArray.length % 2 != 0) {
  273. continue;
  274. }
  275. v0.normal = n;
  276. if (v0.uv)
  277. v0.uv = uv;
  278. else if (v0.color)
  279. v0.color = color;
  280. v0.q = v1.q.add(v0.q);
  281. v0.position = p;
  282. var tStart = _this.references.length;
  283. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  284. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  285. var tCount = _this.references.length - tStart;
  286. if (tCount <= v0.triangleCount) {
  287. if (tCount) {
  288. for (var c = 0; c < tCount; c++) {
  289. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  290. }
  291. }
  292. }
  293. else {
  294. v0.triangleStart = tStart;
  295. }
  296. v0.triangleCount = tCount;
  297. break;
  298. }
  299. }
  300. };
  301. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  302. return (triangleCount - deletedTriangles <= targetCount);
  303. });
  304. }, 0);
  305. };
  306. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  307. if (triangleCount - deletedTriangles <= targetCount)
  308. loop.breakLoop();
  309. else {
  310. iterationFunction(loop.index, function () {
  311. loop.executeNext();
  312. });
  313. }
  314. }, function () {
  315. setTimeout(function () {
  316. //reconstruct this part of the mesh
  317. _this.reconstructMesh(submeshIndex);
  318. successCallback();
  319. }, 0);
  320. });
  321. };
  322. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, submeshIndex, callback) {
  323. var _this = this;
  324. if (!mesh)
  325. return;
  326. this.vertices = [];
  327. this.triangles = [];
  328. this._mesh = mesh;
  329. //It is assumed that a mesh has positions, normals and either uvs or colors.
  330. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  331. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  332. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  333. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  334. var indices = mesh.getIndices();
  335. var submesh = mesh.subMeshes[submeshIndex];
  336. var vertexInit = function (i) {
  337. var offset = i + submesh.verticesStart;
  338. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, offset * 3), BABYLON.Vector3.FromArray(normalData, offset * 3), null, i);
  339. if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  340. vertex.uv = BABYLON.Vector2.FromArray(uvs, offset * 2);
  341. }
  342. else if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  343. vertex.color = BABYLON.Color4.FromArray(colorsData, offset * 4);
  344. }
  345. _this.vertices.push(vertex);
  346. };
  347. //var totalVertices = mesh.getTotalVertices();
  348. var totalVertices = submesh.verticesCount;
  349. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  350. var indicesInit = function (i) {
  351. var offset = (submesh.indexStart / 3) + i;
  352. var pos = (offset * 3);
  353. var i0 = indices[pos + 0] - submesh.verticesStart;
  354. var i1 = indices[pos + 1] - submesh.verticesStart;
  355. var i2 = indices[pos + 2] - submesh.verticesStart;
  356. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  357. _this.triangles.push(triangle);
  358. };
  359. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  360. _this.init(callback);
  361. });
  362. });
  363. };
  364. QuadraticErrorSimplification.prototype.init = function (callback) {
  365. var _this = this;
  366. var triangleInit1 = function (i) {
  367. var t = _this.triangles[i];
  368. t.normal = BABYLON.Vector3.Cross(_this.vertices[t.vertices[1]].position.subtract(_this.vertices[t.vertices[0]].position), _this.vertices[t.vertices[2]].position.subtract(_this.vertices[t.vertices[0]].position)).normalize();
  369. for (var j = 0; j < 3; j++) {
  370. _this.vertices[t.vertices[j]].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, _this.vertices[t.vertices[0]].position))));
  371. }
  372. };
  373. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  374. var triangleInit2 = function (i) {
  375. var t = _this.triangles[i];
  376. for (var j = 0; j < 3; ++j) {
  377. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  378. }
  379. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  380. };
  381. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  382. _this.initialised = true;
  383. callback();
  384. });
  385. });
  386. };
  387. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  388. var newTriangles = [];
  389. var i;
  390. for (i = 0; i < this.vertices.length; ++i) {
  391. this.vertices[i].triangleCount = 0;
  392. }
  393. var t;
  394. var j;
  395. for (i = 0; i < this.triangles.length; ++i) {
  396. if (!this.triangles[i].deleted) {
  397. t = this.triangles[i];
  398. for (j = 0; j < 3; ++j) {
  399. this.vertices[t.vertices[j]].triangleCount = 1;
  400. }
  401. newTriangles.push(t);
  402. }
  403. }
  404. var newVerticesOrder = [];
  405. //compact vertices, get the IDs of the vertices used.
  406. var dst = 0;
  407. for (i = 0; i < this.vertices.length; ++i) {
  408. if (this.vertices[i].triangleCount) {
  409. this.vertices[i].triangleStart = dst;
  410. this.vertices[dst].position = this.vertices[i].position;
  411. this.vertices[dst].normal = this.vertices[i].normal;
  412. this.vertices[dst].uv = this.vertices[i].uv;
  413. this.vertices[dst].color = this.vertices[i].color;
  414. newVerticesOrder.push(dst);
  415. dst++;
  416. }
  417. }
  418. for (i = 0; i < newTriangles.length; ++i) {
  419. t = newTriangles[i];
  420. for (j = 0; j < 3; ++j) {
  421. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  422. }
  423. }
  424. this.vertices = this.vertices.slice(0, dst);
  425. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  426. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  427. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  428. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  429. for (i = 0; i < newVerticesOrder.length; ++i) {
  430. newPositionData.push(this.vertices[i].position.x);
  431. newPositionData.push(this.vertices[i].position.y);
  432. newPositionData.push(this.vertices[i].position.z);
  433. newNormalData.push(this.vertices[i].normal.x);
  434. newNormalData.push(this.vertices[i].normal.y);
  435. newNormalData.push(this.vertices[i].normal.z);
  436. if (this.vertices[i].uv) {
  437. newUVsData.push(this.vertices[i].uv.x);
  438. newUVsData.push(this.vertices[i].uv.y);
  439. }
  440. else if (this.vertices[i].color) {
  441. newColorsData.push(this.vertices[i].color.r);
  442. newColorsData.push(this.vertices[i].color.g);
  443. newColorsData.push(this.vertices[i].color.b);
  444. newColorsData.push(this.vertices[i].color.a);
  445. }
  446. }
  447. var startingIndex = this._reconstructedMesh.getTotalIndices();
  448. var startingVertex = this._reconstructedMesh.getTotalVertices();
  449. var submeshesArray = this._reconstructedMesh.subMeshes;
  450. this._reconstructedMesh.subMeshes = [];
  451. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  452. for (i = 0; i < newTriangles.length; ++i) {
  453. newIndicesArray.push(newTriangles[i].vertices[0] + startingVertex);
  454. newIndicesArray.push(newTriangles[i].vertices[1] + startingVertex);
  455. newIndicesArray.push(newTriangles[i].vertices[2] + startingVertex);
  456. }
  457. //overwriting the old vertex buffers and indices.
  458. this._reconstructedMesh.setIndices(newIndicesArray);
  459. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  460. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  461. if (newUVsData.length > 0)
  462. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  463. if (newColorsData.length > 0)
  464. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  465. //create submesh
  466. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  467. if (submeshIndex > 0) {
  468. this._reconstructedMesh.subMeshes = [];
  469. submeshesArray.forEach(function (submesh) {
  470. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  471. });
  472. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, newVerticesOrder.length, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  473. }
  474. };
  475. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  476. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  477. this._reconstructedMesh.material = this._mesh.material;
  478. this._reconstructedMesh.parent = this._mesh.parent;
  479. this._reconstructedMesh.isVisible = false;
  480. };
  481. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor, delTr) {
  482. for (var i = 0; i < vertex1.triangleCount; ++i) {
  483. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  484. if (t.deleted)
  485. continue;
  486. var s = this.references[vertex1.triangleStart + i].vertexId;
  487. var id1 = t.vertices[(s + 1) % 3];
  488. var id2 = t.vertices[(s + 2) % 3];
  489. if ((id1 === index2 || id2 === index2)) {
  490. deletedArray[i] = true;
  491. delTr.push(t);
  492. continue;
  493. }
  494. var d1 = this.vertices[id1].position.subtract(point);
  495. d1 = d1.normalize();
  496. var d2 = this.vertices[id2].position.subtract(point);
  497. d2 = d2.normalize();
  498. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  499. return true;
  500. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  501. deletedArray[i] = false;
  502. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  503. return true;
  504. }
  505. return false;
  506. };
  507. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  508. var newDeleted = deletedTriangles;
  509. for (var i = 0; i < vertex.triangleCount; ++i) {
  510. var ref = this.references[vertex.triangleStart + i];
  511. var t = this.triangles[ref.triangleId];
  512. if (t.deleted)
  513. continue;
  514. if (deletedArray[i] && t.deletePending) {
  515. t.deleted = true;
  516. newDeleted++;
  517. continue;
  518. }
  519. t.vertices[ref.vertexId] = vertexId;
  520. t.isDirty = true;
  521. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  522. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  523. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  524. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  525. this.references.push(ref);
  526. }
  527. return newDeleted;
  528. };
  529. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  530. for (var i = 0; i < this.vertices.length; ++i) {
  531. var vCount = [];
  532. var vId = [];
  533. var v = this.vertices[i];
  534. var j;
  535. for (j = 0; j < v.triangleCount; ++j) {
  536. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  537. for (var ii = 0; ii < 3; ii++) {
  538. var ofs = 0;
  539. var id = triangle.vertices[ii];
  540. while (ofs < vCount.length) {
  541. if (vId[ofs] === id)
  542. break;
  543. ++ofs;
  544. }
  545. if (ofs === vCount.length) {
  546. vCount.push(1);
  547. vId.push(id);
  548. }
  549. else {
  550. vCount[ofs]++;
  551. }
  552. }
  553. }
  554. for (j = 0; j < vCount.length; ++j) {
  555. if (vCount[j] === 1) {
  556. this.vertices[vId[j]].isBorder = true;
  557. }
  558. else {
  559. this.vertices[vId[j]].isBorder = false;
  560. }
  561. }
  562. }
  563. };
  564. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  565. if (identifyBorders === void 0) { identifyBorders = false; }
  566. var i;
  567. if (!identifyBorders) {
  568. var newTrianglesVector = [];
  569. for (i = 0; i < this.triangles.length; ++i) {
  570. if (!this.triangles[i].deleted) {
  571. newTrianglesVector.push(this.triangles[i]);
  572. }
  573. }
  574. this.triangles = newTrianglesVector;
  575. }
  576. for (i = 0; i < this.vertices.length; ++i) {
  577. this.vertices[i].triangleCount = 0;
  578. this.vertices[i].triangleStart = 0;
  579. }
  580. var t;
  581. var j;
  582. var v;
  583. for (i = 0; i < this.triangles.length; ++i) {
  584. t = this.triangles[i];
  585. for (j = 0; j < 3; ++j) {
  586. v = this.vertices[t.vertices[j]];
  587. v.triangleCount++;
  588. }
  589. }
  590. var tStart = 0;
  591. for (i = 0; i < this.vertices.length; ++i) {
  592. this.vertices[i].triangleStart = tStart;
  593. tStart += this.vertices[i].triangleCount;
  594. this.vertices[i].triangleCount = 0;
  595. }
  596. var newReferences = new Array(this.triangles.length * 3);
  597. for (i = 0; i < this.triangles.length; ++i) {
  598. t = this.triangles[i];
  599. for (j = 0; j < 3; ++j) {
  600. v = this.vertices[t.vertices[j]];
  601. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  602. v.triangleCount++;
  603. }
  604. }
  605. this.references = newReferences;
  606. if (identifyBorders) {
  607. this.identifyBorder();
  608. }
  609. };
  610. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  611. var x = point.x;
  612. var y = point.y;
  613. var z = point.z;
  614. return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  615. };
  616. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  617. var q = vertex1.q.add(vertex2.q);
  618. var border = vertex1.isBorder && vertex2.isBorder;
  619. var error = 0;
  620. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  621. if (qDet !== 0 && !border) {
  622. if (!pointResult) {
  623. pointResult = BABYLON.Vector3.Zero();
  624. }
  625. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  626. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  627. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  628. error = this.vertexError(q, pointResult);
  629. //TODO this should be correctly calculated
  630. if (normalResult) {
  631. normalResult.copyFrom(vertex1.normal);
  632. if (vertex1.uv)
  633. uvResult.copyFrom(vertex1.uv);
  634. else if (vertex1.color)
  635. colorResult.copyFrom(vertex1.color);
  636. }
  637. }
  638. else {
  639. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  640. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  641. var error1 = this.vertexError(q, vertex1.position);
  642. var error2 = this.vertexError(q, vertex2.position);
  643. var error3 = this.vertexError(q, p3);
  644. error = Math.min(error1, error2, error3);
  645. if (error === error1) {
  646. if (pointResult) {
  647. pointResult.copyFrom(vertex1.position);
  648. normalResult.copyFrom(vertex1.normal);
  649. if (vertex1.uv)
  650. uvResult.copyFrom(vertex1.uv);
  651. else if (vertex1.color)
  652. colorResult.copyFrom(vertex1.color);
  653. }
  654. }
  655. else if (error === error2) {
  656. if (pointResult) {
  657. pointResult.copyFrom(vertex2.position);
  658. normalResult.copyFrom(vertex2.normal);
  659. if (vertex2.uv)
  660. uvResult.copyFrom(vertex2.uv);
  661. else if (vertex2.color)
  662. colorResult.copyFrom(vertex2.color);
  663. }
  664. }
  665. else {
  666. if (pointResult) {
  667. pointResult.copyFrom(p3);
  668. normalResult.copyFrom(vertex1.normal);
  669. if (vertex1.uv)
  670. uvResult.copyFrom(vertex1.uv);
  671. else if (vertex1.color)
  672. colorResult.copyFrom(vertex1.color);
  673. }
  674. }
  675. }
  676. return error;
  677. };
  678. return QuadraticErrorSimplification;
  679. })();
  680. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  681. })(BABYLON || (BABYLON = {}));
  682. //# sourceMappingURL=babylon.meshSimplification.js.map