babylon.meshSimplification.ts 31 KB

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