babylon.meshSimplification.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  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. if (task.parallelProcessing) {
  32. //parallel simplifier
  33. task.settings.forEach(function (setting) {
  34. var simplifier = _this.getSimplifier(task);
  35. simplifier.simplify(setting, function (newMesh) {
  36. task.mesh.addLODLevel(setting.distance, newMesh);
  37. newMesh.isVisible = true;
  38. //check if it is the last
  39. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  40. //all done, run the success callback.
  41. task.successCallback();
  42. }
  43. _this.executeNext();
  44. });
  45. });
  46. }
  47. else {
  48. //single simplifier.
  49. var simplifier = this.getSimplifier(task);
  50. var runDecimation = function (setting, callback) {
  51. simplifier.simplify(setting, function (newMesh) {
  52. task.mesh.addLODLevel(setting.distance, newMesh);
  53. newMesh.isVisible = true;
  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. successCallback(_this._reconstructedMesh);
  194. }, 0);
  195. });
  196. };
  197. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  198. var _this = this;
  199. var gCount = 0;
  200. triangle.vertices.forEach(function (vId) {
  201. var count = 0;
  202. var vPos = _this.vertices[vId].position;
  203. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  204. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  205. ++count;
  206. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  207. ++count;
  208. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  209. ++count;
  210. if (count > 1) {
  211. ++gCount;
  212. }
  213. ;
  214. });
  215. if (gCount > 1) {
  216. console.log(triangle, gCount);
  217. }
  218. return gCount > 1;
  219. };
  220. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  221. var _this = this;
  222. var targetCount = ~~(this.triangles.length * settings.quality);
  223. var deletedTriangles = 0;
  224. var triangleCount = this.triangles.length;
  225. var iterationFunction = function (iteration, callback) {
  226. setTimeout(function () {
  227. if (iteration % 5 === 0) {
  228. _this.updateMesh(iteration === 0);
  229. }
  230. for (var i = 0; i < _this.triangles.length; ++i) {
  231. _this.triangles[i].isDirty = false;
  232. }
  233. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  234. var trianglesIterator = function (i) {
  235. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  236. var t = _this.triangles[tIdx];
  237. if (!t)
  238. return;
  239. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  240. return;
  241. }
  242. for (var j = 0; j < 3; ++j) {
  243. if (t.error[j] < threshold) {
  244. var deleted0 = [];
  245. var deleted1 = [];
  246. var i0 = t.vertices[j];
  247. var i1 = t.vertices[(j + 1) % 3];
  248. var v0 = _this.vertices[i0];
  249. var v1 = _this.vertices[i1];
  250. if (v0.isBorder !== v1.isBorder)
  251. continue;
  252. var p = BABYLON.Vector3.Zero();
  253. var n = BABYLON.Vector3.Zero();
  254. var uv = BABYLON.Vector2.Zero();
  255. var color = new BABYLON.Color4(0, 0, 0, 1);
  256. _this.calculateError(v0, v1, p, n, uv, color);
  257. var delTr = [];
  258. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor, delTr))
  259. continue;
  260. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor, delTr))
  261. continue;
  262. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  263. continue;
  264. var uniqueArray = [];
  265. delTr.forEach(function (deletedT) {
  266. if (uniqueArray.indexOf(deletedT) === -1) {
  267. deletedT.deletePending = true;
  268. uniqueArray.push(deletedT);
  269. }
  270. });
  271. if (uniqueArray.length % 2 != 0) {
  272. continue;
  273. }
  274. v0.normal = n;
  275. if (v0.uv)
  276. v0.uv = uv;
  277. else if (v0.color)
  278. v0.color = color;
  279. v0.q = v1.q.add(v0.q);
  280. v0.position = p;
  281. var tStart = _this.references.length;
  282. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  283. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  284. var tCount = _this.references.length - tStart;
  285. if (tCount <= v0.triangleCount) {
  286. if (tCount) {
  287. for (var c = 0; c < tCount; c++) {
  288. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  289. }
  290. }
  291. }
  292. else {
  293. v0.triangleStart = tStart;
  294. }
  295. v0.triangleCount = tCount;
  296. break;
  297. }
  298. }
  299. };
  300. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  301. return (triangleCount - deletedTriangles <= targetCount);
  302. });
  303. }, 0);
  304. };
  305. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  306. if (triangleCount - deletedTriangles <= targetCount)
  307. loop.breakLoop();
  308. else {
  309. iterationFunction(loop.index, function () {
  310. loop.executeNext();
  311. });
  312. }
  313. }, function () {
  314. setTimeout(function () {
  315. //reconstruct this part of the mesh
  316. _this.reconstructMesh(submeshIndex);
  317. successCallback();
  318. }, 0);
  319. });
  320. };
  321. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, submeshIndex, callback) {
  322. var _this = this;
  323. if (!mesh)
  324. return;
  325. this.vertices = [];
  326. this.triangles = [];
  327. this._mesh = mesh;
  328. //It is assumed that a mesh has positions, normals and either uvs or colors.
  329. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  330. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  331. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  332. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  333. var indices = mesh.getIndices();
  334. var submesh = mesh.subMeshes[submeshIndex];
  335. var vertexInit = function (i) {
  336. var offset = i + submesh.verticesStart;
  337. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, offset * 3), BABYLON.Vector3.FromArray(normalData, offset * 3), null, i);
  338. if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  339. vertex.uv = BABYLON.Vector2.FromArray(uvs, offset * 2);
  340. }
  341. else if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  342. vertex.color = BABYLON.Color4.FromArray(colorsData, offset * 4);
  343. }
  344. _this.vertices.push(vertex);
  345. };
  346. //var totalVertices = mesh.getTotalVertices();
  347. var totalVertices = submesh.verticesCount;
  348. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  349. var indicesInit = function (i) {
  350. var offset = (submesh.indexStart / 3) + i;
  351. var pos = (offset * 3);
  352. var i0 = indices[pos + 0] - submesh.verticesStart;
  353. var i1 = indices[pos + 1] - submesh.verticesStart;
  354. var i2 = indices[pos + 2] - submesh.verticesStart;
  355. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  356. _this.triangles.push(triangle);
  357. };
  358. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  359. _this.init(callback);
  360. });
  361. });
  362. };
  363. QuadraticErrorSimplification.prototype.init = function (callback) {
  364. var _this = this;
  365. var triangleInit1 = function (i) {
  366. var t = _this.triangles[i];
  367. 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();
  368. for (var j = 0; j < 3; j++) {
  369. _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))));
  370. }
  371. };
  372. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  373. var triangleInit2 = function (i) {
  374. var t = _this.triangles[i];
  375. for (var j = 0; j < 3; ++j) {
  376. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  377. }
  378. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  379. };
  380. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  381. _this.initialised = true;
  382. callback();
  383. });
  384. });
  385. };
  386. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  387. var newTriangles = [];
  388. var i;
  389. for (i = 0; i < this.vertices.length; ++i) {
  390. this.vertices[i].triangleCount = 0;
  391. }
  392. var t;
  393. var j;
  394. for (i = 0; i < this.triangles.length; ++i) {
  395. if (!this.triangles[i].deleted) {
  396. t = this.triangles[i];
  397. for (j = 0; j < 3; ++j) {
  398. this.vertices[t.vertices[j]].triangleCount = 1;
  399. }
  400. newTriangles.push(t);
  401. }
  402. }
  403. var newVerticesOrder = [];
  404. //compact vertices, get the IDs of the vertices used.
  405. var dst = 0;
  406. for (i = 0; i < this.vertices.length; ++i) {
  407. if (this.vertices[i].triangleCount) {
  408. this.vertices[i].triangleStart = dst;
  409. this.vertices[dst].position = this.vertices[i].position;
  410. this.vertices[dst].normal = this.vertices[i].normal;
  411. this.vertices[dst].uv = this.vertices[i].uv;
  412. this.vertices[dst].color = this.vertices[i].color;
  413. newVerticesOrder.push(dst);
  414. dst++;
  415. }
  416. }
  417. for (i = 0; i < newTriangles.length; ++i) {
  418. t = newTriangles[i];
  419. for (j = 0; j < 3; ++j) {
  420. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  421. }
  422. }
  423. this.vertices = this.vertices.slice(0, dst);
  424. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  425. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  426. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  427. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  428. for (i = 0; i < newVerticesOrder.length; ++i) {
  429. newPositionData.push(this.vertices[i].position.x);
  430. newPositionData.push(this.vertices[i].position.y);
  431. newPositionData.push(this.vertices[i].position.z);
  432. newNormalData.push(this.vertices[i].normal.x);
  433. newNormalData.push(this.vertices[i].normal.y);
  434. newNormalData.push(this.vertices[i].normal.z);
  435. if (this.vertices[i].uv) {
  436. newUVsData.push(this.vertices[i].uv.x);
  437. newUVsData.push(this.vertices[i].uv.y);
  438. }
  439. else if (this.vertices[i].color) {
  440. newColorsData.push(this.vertices[i].color.r);
  441. newColorsData.push(this.vertices[i].color.g);
  442. newColorsData.push(this.vertices[i].color.b);
  443. newColorsData.push(this.vertices[i].color.a);
  444. }
  445. }
  446. var startingIndex = this._reconstructedMesh.getTotalIndices();
  447. var startingVertex = this._reconstructedMesh.getTotalVertices();
  448. var submeshesArray = this._reconstructedMesh.subMeshes;
  449. this._reconstructedMesh.subMeshes = [];
  450. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  451. for (i = 0; i < newTriangles.length; ++i) {
  452. newIndicesArray.push(newTriangles[i].vertices[0] + startingVertex);
  453. newIndicesArray.push(newTriangles[i].vertices[1] + startingVertex);
  454. newIndicesArray.push(newTriangles[i].vertices[2] + startingVertex);
  455. }
  456. //overwriting the old vertex buffers and indices.
  457. this._reconstructedMesh.setIndices(newIndicesArray);
  458. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  459. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  460. if (newUVsData.length > 0)
  461. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  462. if (newColorsData.length > 0)
  463. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  464. //create submesh
  465. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  466. if (submeshIndex > 0) {
  467. this._reconstructedMesh.subMeshes = [];
  468. submeshesArray.forEach(function (submesh) {
  469. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  470. });
  471. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, newVerticesOrder.length, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  472. }
  473. };
  474. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  475. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  476. this._reconstructedMesh.material = this._mesh.material;
  477. this._reconstructedMesh.parent = this._mesh.parent;
  478. this._reconstructedMesh.isVisible = false;
  479. };
  480. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor, delTr) {
  481. for (var i = 0; i < vertex1.triangleCount; ++i) {
  482. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  483. if (t.deleted)
  484. continue;
  485. var s = this.references[vertex1.triangleStart + i].vertexId;
  486. var id1 = t.vertices[(s + 1) % 3];
  487. var id2 = t.vertices[(s + 2) % 3];
  488. if ((id1 === index2 || id2 === index2)) {
  489. deletedArray[i] = true;
  490. delTr.push(t);
  491. continue;
  492. }
  493. var d1 = this.vertices[id1].position.subtract(point);
  494. d1 = d1.normalize();
  495. var d2 = this.vertices[id2].position.subtract(point);
  496. d2 = d2.normalize();
  497. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  498. return true;
  499. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  500. deletedArray[i] = false;
  501. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  502. return true;
  503. }
  504. return false;
  505. };
  506. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  507. var newDeleted = deletedTriangles;
  508. for (var i = 0; i < vertex.triangleCount; ++i) {
  509. var ref = this.references[vertex.triangleStart + i];
  510. var t = this.triangles[ref.triangleId];
  511. if (t.deleted)
  512. continue;
  513. if (deletedArray[i] && t.deletePending) {
  514. t.deleted = true;
  515. newDeleted++;
  516. continue;
  517. }
  518. t.vertices[ref.vertexId] = vertexId;
  519. t.isDirty = true;
  520. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  521. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  522. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  523. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  524. this.references.push(ref);
  525. }
  526. return newDeleted;
  527. };
  528. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  529. for (var i = 0; i < this.vertices.length; ++i) {
  530. var vCount = [];
  531. var vId = [];
  532. var v = this.vertices[i];
  533. var j;
  534. for (j = 0; j < v.triangleCount; ++j) {
  535. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  536. for (var ii = 0; ii < 3; ii++) {
  537. var ofs = 0;
  538. var id = triangle.vertices[ii];
  539. while (ofs < vCount.length) {
  540. if (vId[ofs] === id)
  541. break;
  542. ++ofs;
  543. }
  544. if (ofs === vCount.length) {
  545. vCount.push(1);
  546. vId.push(id);
  547. }
  548. else {
  549. vCount[ofs]++;
  550. }
  551. }
  552. }
  553. for (j = 0; j < vCount.length; ++j) {
  554. if (vCount[j] === 1) {
  555. this.vertices[vId[j]].isBorder = true;
  556. }
  557. else {
  558. this.vertices[vId[j]].isBorder = false;
  559. }
  560. }
  561. }
  562. };
  563. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  564. if (identifyBorders === void 0) { identifyBorders = false; }
  565. var i;
  566. if (!identifyBorders) {
  567. var newTrianglesVector = [];
  568. for (i = 0; i < this.triangles.length; ++i) {
  569. if (!this.triangles[i].deleted) {
  570. newTrianglesVector.push(this.triangles[i]);
  571. }
  572. }
  573. this.triangles = newTrianglesVector;
  574. }
  575. for (i = 0; i < this.vertices.length; ++i) {
  576. this.vertices[i].triangleCount = 0;
  577. this.vertices[i].triangleStart = 0;
  578. }
  579. var t;
  580. var j;
  581. var v;
  582. for (i = 0; i < this.triangles.length; ++i) {
  583. t = this.triangles[i];
  584. for (j = 0; j < 3; ++j) {
  585. v = this.vertices[t.vertices[j]];
  586. v.triangleCount++;
  587. }
  588. }
  589. var tStart = 0;
  590. for (i = 0; i < this.vertices.length; ++i) {
  591. this.vertices[i].triangleStart = tStart;
  592. tStart += this.vertices[i].triangleCount;
  593. this.vertices[i].triangleCount = 0;
  594. }
  595. var newReferences = new Array(this.triangles.length * 3);
  596. for (i = 0; i < this.triangles.length; ++i) {
  597. t = this.triangles[i];
  598. for (j = 0; j < 3; ++j) {
  599. v = this.vertices[t.vertices[j]];
  600. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  601. v.triangleCount++;
  602. }
  603. }
  604. this.references = newReferences;
  605. if (identifyBorders) {
  606. this.identifyBorder();
  607. }
  608. };
  609. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  610. var x = point.x;
  611. var y = point.y;
  612. var z = point.z;
  613. 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];
  614. };
  615. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  616. var q = vertex1.q.add(vertex2.q);
  617. var border = vertex1.isBorder && vertex2.isBorder;
  618. var error = 0;
  619. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  620. if (qDet !== 0 && !border) {
  621. if (!pointResult) {
  622. pointResult = BABYLON.Vector3.Zero();
  623. }
  624. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  625. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  626. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  627. error = this.vertexError(q, pointResult);
  628. //TODO this should be correctly calculated
  629. if (normalResult) {
  630. normalResult.copyFrom(vertex1.normal);
  631. if (vertex1.uv)
  632. uvResult.copyFrom(vertex1.uv);
  633. else if (vertex1.color)
  634. colorResult.copyFrom(vertex1.color);
  635. }
  636. }
  637. else {
  638. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  639. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  640. var error1 = this.vertexError(q, vertex1.position);
  641. var error2 = this.vertexError(q, vertex2.position);
  642. var error3 = this.vertexError(q, p3);
  643. error = Math.min(error1, error2, error3);
  644. if (error === error1) {
  645. if (pointResult) {
  646. pointResult.copyFrom(vertex1.position);
  647. normalResult.copyFrom(vertex1.normal);
  648. if (vertex1.uv)
  649. uvResult.copyFrom(vertex1.uv);
  650. else if (vertex1.color)
  651. colorResult.copyFrom(vertex1.color);
  652. }
  653. }
  654. else if (error === error2) {
  655. if (pointResult) {
  656. pointResult.copyFrom(vertex2.position);
  657. normalResult.copyFrom(vertex2.normal);
  658. if (vertex2.uv)
  659. uvResult.copyFrom(vertex2.uv);
  660. else if (vertex2.color)
  661. colorResult.copyFrom(vertex2.color);
  662. }
  663. }
  664. else {
  665. if (pointResult) {
  666. pointResult.copyFrom(p3);
  667. normalResult.copyFrom(vertex1.normal);
  668. if (vertex1.uv)
  669. uvResult.copyFrom(vertex1.uv);
  670. else if (vertex1.color)
  671. colorResult.copyFrom(vertex1.color);
  672. }
  673. }
  674. }
  675. return error;
  676. };
  677. return QuadraticErrorSimplification;
  678. })();
  679. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  680. })(BABYLON || (BABYLON = {}));
  681. //# sourceMappingURL=babylon.meshSimplification.js.map