babylon.meshSimplification.ts 32 KB

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