babylon.meshSimplification.ts 26 KB

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