babylon.meshSimplification.ts 30 KB

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