babylon.meshSimplification.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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. /**
  12. * The implemented types of simplification.
  13. * At the moment only Quadratic Error Decimation is implemented.
  14. */
  15. (function (SimplificationType) {
  16. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  17. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  18. var SimplificationType = BABYLON.SimplificationType;
  19. var DecimationTriangle = (function () {
  20. function DecimationTriangle(vertices) {
  21. this.vertices = vertices;
  22. this.error = new Array(4);
  23. this.deleted = false;
  24. this.isDirty = false;
  25. this.borderFactor = 0;
  26. }
  27. return DecimationTriangle;
  28. })();
  29. BABYLON.DecimationTriangle = DecimationTriangle;
  30. var DecimationVertex = (function () {
  31. function DecimationVertex(position, normal, uv, id) {
  32. this.position = position;
  33. this.normal = normal;
  34. this.uv = uv;
  35. this.id = id;
  36. this.isBorder = true;
  37. this.q = new QuadraticMatrix();
  38. this.triangleCount = 0;
  39. this.triangleStart = 0;
  40. }
  41. return DecimationVertex;
  42. })();
  43. BABYLON.DecimationVertex = DecimationVertex;
  44. var QuadraticMatrix = (function () {
  45. function QuadraticMatrix(data) {
  46. this.data = new Array(10);
  47. for (var i = 0; i < 10; ++i) {
  48. if (data && data[i]) {
  49. this.data[i] = data[i];
  50. } else {
  51. this.data[i] = 0;
  52. }
  53. }
  54. }
  55. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  56. 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];
  57. return det;
  58. };
  59. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  60. for (var i = 0; i < 10; ++i) {
  61. this.data[i] += matrix.data[i];
  62. }
  63. };
  64. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  65. for (var i = 0; i < 10; ++i) {
  66. this.data[i] += data[i];
  67. }
  68. };
  69. QuadraticMatrix.prototype.add = function (matrix) {
  70. var m = new QuadraticMatrix();
  71. for (var i = 0; i < 10; ++i) {
  72. m.data[i] = this.data[i] + matrix.data[i];
  73. }
  74. return m;
  75. };
  76. QuadraticMatrix.FromData = function (a, b, c, d) {
  77. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  78. };
  79. //returning an array to avoid garbage collection
  80. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  81. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  82. };
  83. return QuadraticMatrix;
  84. })();
  85. BABYLON.QuadraticMatrix = QuadraticMatrix;
  86. var Reference = (function () {
  87. function Reference(vertexId, triangleId) {
  88. this.vertexId = vertexId;
  89. this.triangleId = triangleId;
  90. }
  91. return Reference;
  92. })();
  93. BABYLON.Reference = Reference;
  94. /**
  95. * An implementation of the Quadratic Error simplification algorithm.
  96. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  97. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  98. * @author RaananW
  99. */
  100. var QuadraticErrorSimplification = (function () {
  101. function QuadraticErrorSimplification(_mesh) {
  102. this._mesh = _mesh;
  103. this.initialised = false;
  104. this.syncIterations = 5000;
  105. this.agressiveness = 7;
  106. this.decimationIterations = 100;
  107. }
  108. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  109. var _this = this;
  110. this.initWithMesh(this._mesh, function () {
  111. _this.runDecimation(settings, successCallback);
  112. });
  113. };
  114. QuadraticErrorSimplification.prototype.runDecimation = function (settings, successCallback) {
  115. var _this = this;
  116. var targetCount = ~~(this.triangles.length * settings.quality);
  117. var deletedTriangles = 0;
  118. var triangleCount = this.triangles.length;
  119. var iterationFunction = function (iteration, callback) {
  120. setTimeout(function () {
  121. if (iteration % 5 === 0) {
  122. _this.updateMesh(iteration === 0);
  123. }
  124. for (var i = 0; i < _this.triangles.length; ++i) {
  125. _this.triangles[i].isDirty = false;
  126. }
  127. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.agressiveness);
  128. var trianglesIterator = function (i) {
  129. var t = _this.triangles[i];
  130. if (!t)
  131. return;
  132. if (t.error[3] > threshold) {
  133. return;
  134. }
  135. if (t.deleted) {
  136. return;
  137. }
  138. if (t.isDirty) {
  139. return;
  140. }
  141. for (var j = 0; j < 3; ++j) {
  142. if (t.error[j] < threshold) {
  143. var deleted0 = [];
  144. var deleted1 = [];
  145. var i0 = t.vertices[j];
  146. var i1 = t.vertices[(j + 1) % 3];
  147. var v0 = _this.vertices[i0];
  148. var v1 = _this.vertices[i1];
  149. if (v0.isBorder !== v1.isBorder)
  150. continue;
  151. var p = BABYLON.Vector3.Zero();
  152. var n = BABYLON.Vector3.Zero();
  153. var uv = BABYLON.Vector2.Zero();
  154. _this.calculateError(v0, v1, p, n, uv);
  155. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor))
  156. continue;
  157. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor))
  158. continue;
  159. v0.position = p;
  160. v0.normal = n;
  161. v0.uv = uv;
  162. v0.q = v1.q.add(v0.q);
  163. var tStart = _this.references.length;
  164. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  165. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  166. var tCount = _this.references.length - tStart;
  167. if (tCount <= v0.triangleCount) {
  168. if (tCount) {
  169. for (var c = 0; c < tCount; c++) {
  170. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  171. }
  172. }
  173. } else {
  174. v0.triangleStart = tStart;
  175. }
  176. v0.triangleCount = tCount;
  177. break;
  178. }
  179. }
  180. };
  181. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  182. return (triangleCount - deletedTriangles <= targetCount);
  183. });
  184. }, 0);
  185. };
  186. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  187. if (triangleCount - deletedTriangles <= targetCount)
  188. loop.breakLoop();
  189. else {
  190. iterationFunction(loop.index, function () {
  191. loop.executeNext();
  192. });
  193. }
  194. }, function () {
  195. setTimeout(function () {
  196. successCallback(_this.reconstructMesh());
  197. }, 0);
  198. });
  199. };
  200. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, callback) {
  201. var _this = this;
  202. if (!mesh)
  203. return;
  204. this.vertices = [];
  205. this.triangles = [];
  206. this._mesh = mesh;
  207. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  208. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  209. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  210. var indices = mesh.getIndices();
  211. var vertexInit = function (i) {
  212. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, i * 3), BABYLON.Vector3.FromArray(normalData, i * 3), BABYLON.Vector2.FromArray(uvs, i * 2), i);
  213. _this.vertices.push(vertex);
  214. };
  215. var totalVertices = mesh.getTotalVertices();
  216. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  217. var indicesInit = function (i) {
  218. var pos = i * 3;
  219. var i0 = indices[pos + 0];
  220. var i1 = indices[pos + 1];
  221. var i2 = indices[pos + 2];
  222. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  223. _this.triangles.push(triangle);
  224. };
  225. BABYLON.AsyncLoop.SyncAsyncForLoop(indices.length / 3, _this.syncIterations, indicesInit, function () {
  226. _this.init(callback);
  227. });
  228. });
  229. };
  230. QuadraticErrorSimplification.prototype.init = function (callback) {
  231. var _this = this;
  232. var triangleInit1 = function (i) {
  233. var t = _this.triangles[i];
  234. 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();
  235. for (var j = 0; j < 3; j++) {
  236. _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))));
  237. }
  238. };
  239. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  240. var triangleInit2 = function (i) {
  241. var t = _this.triangles[i];
  242. for (var j = 0; j < 3; ++j) {
  243. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  244. }
  245. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  246. };
  247. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  248. _this.initialised = true;
  249. callback();
  250. });
  251. });
  252. };
  253. QuadraticErrorSimplification.prototype.reconstructMesh = function () {
  254. var newTriangles = [];
  255. var i;
  256. for (i = 0; i < this.vertices.length; ++i) {
  257. this.vertices[i].triangleCount = 0;
  258. }
  259. var t;
  260. var j;
  261. for (i = 0; i < this.triangles.length; ++i) {
  262. if (!this.triangles[i].deleted) {
  263. t = this.triangles[i];
  264. for (j = 0; j < 3; ++j) {
  265. this.vertices[t.vertices[j]].triangleCount = 1;
  266. }
  267. newTriangles.push(t);
  268. }
  269. }
  270. var newVerticesOrder = [];
  271. //compact vertices, get the IDs of the vertices used.
  272. var dst = 0;
  273. for (i = 0; i < this.vertices.length; ++i) {
  274. if (this.vertices[i].triangleCount) {
  275. this.vertices[i].triangleStart = dst;
  276. this.vertices[dst].position = this.vertices[i].position;
  277. this.vertices[dst].normal = this.vertices[i].normal;
  278. this.vertices[dst].uv = this.vertices[i].uv;
  279. newVerticesOrder.push(i);
  280. dst++;
  281. }
  282. }
  283. for (i = 0; i < newTriangles.length; ++i) {
  284. t = newTriangles[i];
  285. for (j = 0; j < 3; ++j) {
  286. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  287. }
  288. }
  289. this.vertices = this.vertices.slice(0, dst);
  290. var newPositionData = [];
  291. var newNormalData = [];
  292. var newUVsData = [];
  293. for (i = 0; i < newVerticesOrder.length; ++i) {
  294. newPositionData.push(this.vertices[i].position.x);
  295. newPositionData.push(this.vertices[i].position.y);
  296. newPositionData.push(this.vertices[i].position.z);
  297. newNormalData.push(this.vertices[i].normal.x);
  298. newNormalData.push(this.vertices[i].normal.y);
  299. newNormalData.push(this.vertices[i].normal.z);
  300. newUVsData.push(this.vertices[i].uv.x);
  301. newUVsData.push(this.vertices[i].uv.y);
  302. }
  303. var newIndicesArray = [];
  304. for (i = 0; i < newTriangles.length; ++i) {
  305. newIndicesArray.push(newTriangles[i].vertices[0]);
  306. newIndicesArray.push(newTriangles[i].vertices[1]);
  307. newIndicesArray.push(newTriangles[i].vertices[2]);
  308. }
  309. var newMesh = new BABYLON.Mesh(this._mesh + "Decimated", this._mesh.getScene());
  310. newMesh.material = this._mesh.material;
  311. newMesh.parent = this._mesh.parent;
  312. newMesh.setIndices(newIndicesArray);
  313. newMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  314. newMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  315. newMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  316. //preparing the skeleton support
  317. if (this._mesh.skeleton) {
  318. //newMesh.skeleton = this._mesh.skeleton.clone("", "");
  319. //newMesh.getScene().beginAnimation(newMesh.skeleton, 0, 100, true, 1.0);
  320. }
  321. return newMesh;
  322. };
  323. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor) {
  324. for (var i = 0; i < vertex1.triangleCount; ++i) {
  325. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  326. if (t.deleted)
  327. continue;
  328. var s = this.references[vertex1.triangleStart + i].vertexId;
  329. var id1 = t.vertices[(s + 1) % 3];
  330. var id2 = t.vertices[(s + 2) % 3];
  331. if ((id1 === index2 || id2 === index2) && borderFactor < 2) {
  332. deletedArray[i] = true;
  333. continue;
  334. }
  335. var d1 = this.vertices[id1].position.subtract(point);
  336. d1 = d1.normalize();
  337. var d2 = this.vertices[id2].position.subtract(point);
  338. d2 = d2.normalize();
  339. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  340. return true;
  341. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  342. deletedArray[i] = false;
  343. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  344. return true;
  345. }
  346. return false;
  347. };
  348. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  349. var newDeleted = deletedTriangles;
  350. for (var i = 0; i < vertex.triangleCount; ++i) {
  351. var ref = this.references[vertex.triangleStart + i];
  352. var t = this.triangles[ref.triangleId];
  353. if (t.deleted)
  354. continue;
  355. if (deletedArray[i]) {
  356. t.deleted = true;
  357. newDeleted++;
  358. continue;
  359. }
  360. t.vertices[ref.vertexId] = vertexId;
  361. t.isDirty = true;
  362. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  363. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  364. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  365. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  366. this.references.push(ref);
  367. }
  368. return newDeleted;
  369. };
  370. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  371. for (var i = 0; i < this.vertices.length; ++i) {
  372. var vCount = [];
  373. var vId = [];
  374. var v = this.vertices[i];
  375. var j;
  376. for (j = 0; j < v.triangleCount; ++j) {
  377. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  378. for (var ii = 0; ii < 3; ii++) {
  379. var ofs = 0;
  380. var id = triangle.vertices[ii];
  381. while (ofs < vCount.length) {
  382. if (vId[ofs] === id)
  383. break;
  384. ++ofs;
  385. }
  386. if (ofs === vCount.length) {
  387. vCount.push(1);
  388. vId.push(id);
  389. } else {
  390. vCount[ofs]++;
  391. }
  392. }
  393. }
  394. for (j = 0; j < vCount.length; ++j) {
  395. if (vCount[j] === 1) {
  396. this.vertices[vId[j]].isBorder = true;
  397. } else {
  398. this.vertices[vId[j]].isBorder = false;
  399. }
  400. }
  401. }
  402. };
  403. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  404. if (typeof identifyBorders === "undefined") { identifyBorders = false; }
  405. var i;
  406. if (!identifyBorders) {
  407. var newTrianglesVector = [];
  408. for (i = 0; i < this.triangles.length; ++i) {
  409. if (!this.triangles[i].deleted) {
  410. newTrianglesVector.push(this.triangles[i]);
  411. }
  412. }
  413. this.triangles = newTrianglesVector;
  414. }
  415. for (i = 0; i < this.vertices.length; ++i) {
  416. this.vertices[i].triangleCount = 0;
  417. this.vertices[i].triangleStart = 0;
  418. }
  419. var t;
  420. var j;
  421. var v;
  422. for (i = 0; i < this.triangles.length; ++i) {
  423. t = this.triangles[i];
  424. for (j = 0; j < 3; ++j) {
  425. v = this.vertices[t.vertices[j]];
  426. v.triangleCount++;
  427. }
  428. }
  429. var tStart = 0;
  430. for (i = 0; i < this.vertices.length; ++i) {
  431. this.vertices[i].triangleStart = tStart;
  432. tStart += this.vertices[i].triangleCount;
  433. this.vertices[i].triangleCount = 0;
  434. }
  435. var newReferences = new Array(this.triangles.length * 3);
  436. for (i = 0; i < this.triangles.length; ++i) {
  437. t = this.triangles[i];
  438. for (j = 0; j < 3; ++j) {
  439. v = this.vertices[t.vertices[j]];
  440. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  441. v.triangleCount++;
  442. }
  443. }
  444. this.references = newReferences;
  445. if (identifyBorders) {
  446. this.identifyBorder();
  447. }
  448. };
  449. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  450. var x = point.x;
  451. var y = point.y;
  452. var z = point.z;
  453. 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];
  454. };
  455. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult) {
  456. var q = vertex1.q.add(vertex2.q);
  457. var border = vertex1.isBorder && vertex2.isBorder;
  458. var error = 0;
  459. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  460. if (qDet !== 0 && !border) {
  461. if (!pointResult) {
  462. pointResult = BABYLON.Vector3.Zero();
  463. }
  464. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  465. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  466. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  467. error = this.vertexError(q, pointResult);
  468. //TODO this should be correctly calculated
  469. if (normalResult) {
  470. normalResult.copyFrom(vertex1.normal);
  471. uvResult.copyFrom(vertex1.uv);
  472. }
  473. } else {
  474. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  475. var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new BABYLON.Vector3(2, 2, 2)).normalize();
  476. var error1 = this.vertexError(q, vertex1.position);
  477. var error2 = this.vertexError(q, vertex2.position);
  478. var error3 = this.vertexError(q, p3);
  479. error = Math.min(error1, error2, error3);
  480. if (error === error1) {
  481. if (pointResult) {
  482. pointResult.copyFrom(vertex1.position);
  483. normalResult.copyFrom(vertex1.normal);
  484. uvResult.copyFrom(vertex1.uv);
  485. }
  486. } else if (error === error2) {
  487. if (pointResult) {
  488. pointResult.copyFrom(vertex2.position);
  489. normalResult.copyFrom(vertex2.normal);
  490. uvResult.copyFrom(vertex2.uv);
  491. }
  492. } else {
  493. if (pointResult) {
  494. pointResult.copyFrom(p3);
  495. normalResult.copyFrom(norm3);
  496. uvResult.copyFrom(vertex1.uv);
  497. }
  498. }
  499. }
  500. return error;
  501. };
  502. return QuadraticErrorSimplification;
  503. })();
  504. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  505. })(BABYLON || (BABYLON = {}));
  506. //# sourceMappingURL=babylon.meshSimplification.js.map