SimplifyModifier.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. ( function () {
  2. /**
  3. * Simplification Geometry Modifier
  4. * - based on code and technique
  5. * - by Stan Melax in 1998
  6. * - Progressive Mesh type Polygon Reduction Algorithm
  7. * - http://www.melax.com/polychop/
  8. */
  9. const _cb = new THREE.Vector3(),
  10. _ab = new THREE.Vector3();
  11. class SimplifyModifier {
  12. modify( geometry, count ) {
  13. if ( geometry.isGeometry === true ) {
  14. console.error( 'THREE.SimplifyModifier no longer supports Geometry. Use THREE.BufferGeometry instead.' );
  15. return;
  16. }
  17. geometry = geometry.clone();
  18. const attributes = geometry.attributes; // this modifier can only process indexed and non-indexed geomtries with a position attribute
  19. for ( const name in attributes ) {
  20. if ( name !== 'position' ) geometry.deleteAttribute( name );
  21. }
  22. geometry = THREE.BufferGeometryUtils.mergeVertices( geometry ); //
  23. // put data of original geometry in different data structures
  24. //
  25. const vertices = [];
  26. const faces = []; // add vertices
  27. const positionAttribute = geometry.getAttribute( 'position' );
  28. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  29. const v = new THREE.Vector3().fromBufferAttribute( positionAttribute, i );
  30. const vertex = new Vertex( v );
  31. vertices.push( vertex );
  32. } // add faces
  33. let index = geometry.getIndex();
  34. if ( index !== null ) {
  35. for ( let i = 0; i < index.count; i += 3 ) {
  36. const a = index.getX( i );
  37. const b = index.getX( i + 1 );
  38. const c = index.getX( i + 2 );
  39. const triangle = new Triangle( vertices[ a ], vertices[ b ], vertices[ c ], a, b, c );
  40. faces.push( triangle );
  41. }
  42. } else {
  43. for ( let i = 0; i < positionAttribute.count; i += 3 ) {
  44. const a = i;
  45. const b = i + 1;
  46. const c = i + 2;
  47. const triangle = new Triangle( vertices[ a ], vertices[ b ], vertices[ c ], a, b, c );
  48. faces.push( triangle );
  49. }
  50. } // compute all edge collapse costs
  51. for ( let i = 0, il = vertices.length; i < il; i ++ ) {
  52. computeEdgeCostAtVertex( vertices[ i ] );
  53. }
  54. let nextVertex;
  55. let z = count;
  56. while ( z -- ) {
  57. nextVertex = minimumCostEdge( vertices );
  58. if ( ! nextVertex ) {
  59. console.log( 'THREE.SimplifyModifier: No next vertex' );
  60. break;
  61. }
  62. collapse( vertices, faces, nextVertex, nextVertex.collapseNeighbor );
  63. } //
  64. const simplifiedGeometry = new THREE.BufferGeometry();
  65. const position = [];
  66. index = []; //
  67. for ( let i = 0; i < vertices.length; i ++ ) {
  68. const vertex = vertices[ i ].position;
  69. position.push( vertex.x, vertex.y, vertex.z ); // cache final index to GREATLY speed up faces reconstruction
  70. vertices[ i ].id = i;
  71. } //
  72. for ( let i = 0; i < faces.length; i ++ ) {
  73. const face = faces[ i ];
  74. index.push( face.v1.id, face.v2.id, face.v3.id );
  75. } //
  76. simplifiedGeometry.setAttribute( 'position', new THREE.Float32BufferAttribute( position, 3 ) );
  77. simplifiedGeometry.setIndex( index );
  78. return simplifiedGeometry;
  79. }
  80. }
  81. function pushIfUnique( array, object ) {
  82. if ( array.indexOf( object ) === - 1 ) array.push( object );
  83. }
  84. function removeFromArray( array, object ) {
  85. const k = array.indexOf( object );
  86. if ( k > - 1 ) array.splice( k, 1 );
  87. }
  88. function computeEdgeCollapseCost( u, v ) {
  89. // if we collapse edge uv by moving u to v then how
  90. // much different will the model change, i.e. the "error".
  91. const edgelength = v.position.distanceTo( u.position );
  92. let curvature = 0;
  93. const sideFaces = []; // find the "sides" triangles that are on the edge uv
  94. for ( let i = 0, il = u.faces.length; i < il; i ++ ) {
  95. const face = u.faces[ i ];
  96. if ( face.hasVertex( v ) ) {
  97. sideFaces.push( face );
  98. }
  99. } // use the triangle facing most away from the sides
  100. // to determine our curvature term
  101. for ( let i = 0, il = u.faces.length; i < il; i ++ ) {
  102. let minCurvature = 1;
  103. const face = u.faces[ i ];
  104. for ( let j = 0; j < sideFaces.length; j ++ ) {
  105. const sideFace = sideFaces[ j ]; // use dot product of face normals.
  106. const dotProd = face.normal.dot( sideFace.normal );
  107. minCurvature = Math.min( minCurvature, ( 1.001 - dotProd ) / 2 );
  108. }
  109. curvature = Math.max( curvature, minCurvature );
  110. } // crude approach in attempt to preserve borders
  111. // though it seems not to be totally correct
  112. const borders = 0;
  113. if ( sideFaces.length < 2 ) {
  114. // we add some arbitrary cost for borders,
  115. // borders += 10;
  116. curvature = 1;
  117. }
  118. const amt = edgelength * curvature + borders;
  119. return amt;
  120. }
  121. function computeEdgeCostAtVertex( v ) {
  122. // compute the edge collapse cost for all edges that start
  123. // from vertex v. Since we are only interested in reducing
  124. // the object by selecting the min cost edge at each step, we
  125. // only cache the cost of the least cost edge at this vertex
  126. // (in member variable collapse) as well as the value of the
  127. // cost (in member variable collapseCost).
  128. if ( v.neighbors.length === 0 ) {
  129. // collapse if no neighbors.
  130. v.collapseNeighbor = null;
  131. v.collapseCost = - 0.01;
  132. return;
  133. }
  134. v.collapseCost = 100000;
  135. v.collapseNeighbor = null; // search all neighboring edges for "least cost" edge
  136. for ( let i = 0; i < v.neighbors.length; i ++ ) {
  137. const collapseCost = computeEdgeCollapseCost( v, v.neighbors[ i ] );
  138. if ( ! v.collapseNeighbor ) {
  139. v.collapseNeighbor = v.neighbors[ i ];
  140. v.collapseCost = collapseCost;
  141. v.minCost = collapseCost;
  142. v.totalCost = 0;
  143. v.costCount = 0;
  144. }
  145. v.costCount ++;
  146. v.totalCost += collapseCost;
  147. if ( collapseCost < v.minCost ) {
  148. v.collapseNeighbor = v.neighbors[ i ];
  149. v.minCost = collapseCost;
  150. }
  151. } // we average the cost of collapsing at this vertex
  152. v.collapseCost = v.totalCost / v.costCount; // v.collapseCost = v.minCost;
  153. }
  154. function removeVertex( v, vertices ) {
  155. console.assert( v.faces.length === 0 );
  156. while ( v.neighbors.length ) {
  157. const n = v.neighbors.pop();
  158. removeFromArray( n.neighbors, v );
  159. }
  160. removeFromArray( vertices, v );
  161. }
  162. function removeFace( f, faces ) {
  163. removeFromArray( faces, f );
  164. if ( f.v1 ) removeFromArray( f.v1.faces, f );
  165. if ( f.v2 ) removeFromArray( f.v2.faces, f );
  166. if ( f.v3 ) removeFromArray( f.v3.faces, f ); // TODO optimize this!
  167. const vs = [ f.v1, f.v2, f.v3 ];
  168. for ( let i = 0; i < 3; i ++ ) {
  169. const v1 = vs[ i ];
  170. const v2 = vs[ ( i + 1 ) % 3 ];
  171. if ( ! v1 || ! v2 ) continue;
  172. v1.removeIfNonNeighbor( v2 );
  173. v2.removeIfNonNeighbor( v1 );
  174. }
  175. }
  176. function collapse( vertices, faces, u, v ) {
  177. // u and v are pointers to vertices of an edge
  178. // Collapse the edge uv by moving vertex u onto v
  179. if ( ! v ) {
  180. // u is a vertex all by itself so just delete it..
  181. removeVertex( u, vertices );
  182. return;
  183. }
  184. const tmpVertices = [];
  185. for ( let i = 0; i < u.neighbors.length; i ++ ) {
  186. tmpVertices.push( u.neighbors[ i ] );
  187. } // delete triangles on edge uv:
  188. for ( let i = u.faces.length - 1; i >= 0; i -- ) {
  189. if ( u.faces[ i ].hasVertex( v ) ) {
  190. removeFace( u.faces[ i ], faces );
  191. }
  192. } // update remaining triangles to have v instead of u
  193. for ( let i = u.faces.length - 1; i >= 0; i -- ) {
  194. u.faces[ i ].replaceVertex( u, v );
  195. }
  196. removeVertex( u, vertices ); // recompute the edge collapse costs in neighborhood
  197. for ( let i = 0; i < tmpVertices.length; i ++ ) {
  198. computeEdgeCostAtVertex( tmpVertices[ i ] );
  199. }
  200. }
  201. function minimumCostEdge( vertices ) {
  202. // O(n * n) approach. TODO optimize this
  203. let least = vertices[ 0 ];
  204. for ( let i = 0; i < vertices.length; i ++ ) {
  205. if ( vertices[ i ].collapseCost < least.collapseCost ) {
  206. least = vertices[ i ];
  207. }
  208. }
  209. return least;
  210. } // we use a triangle class to represent structure of face slightly differently
  211. class Triangle {
  212. constructor( v1, v2, v3, a, b, c ) {
  213. this.a = a;
  214. this.b = b;
  215. this.c = c;
  216. this.v1 = v1;
  217. this.v2 = v2;
  218. this.v3 = v3;
  219. this.normal = new THREE.Vector3();
  220. this.computeNormal();
  221. v1.faces.push( this );
  222. v1.addUniqueNeighbor( v2 );
  223. v1.addUniqueNeighbor( v3 );
  224. v2.faces.push( this );
  225. v2.addUniqueNeighbor( v1 );
  226. v2.addUniqueNeighbor( v3 );
  227. v3.faces.push( this );
  228. v3.addUniqueNeighbor( v1 );
  229. v3.addUniqueNeighbor( v2 );
  230. }
  231. computeNormal() {
  232. const vA = this.v1.position;
  233. const vB = this.v2.position;
  234. const vC = this.v3.position;
  235. _cb.subVectors( vC, vB );
  236. _ab.subVectors( vA, vB );
  237. _cb.cross( _ab ).normalize();
  238. this.normal.copy( _cb );
  239. }
  240. hasVertex( v ) {
  241. return v === this.v1 || v === this.v2 || v === this.v3;
  242. }
  243. replaceVertex( oldv, newv ) {
  244. if ( oldv === this.v1 ) this.v1 = newv; else if ( oldv === this.v2 ) this.v2 = newv; else if ( oldv === this.v3 ) this.v3 = newv;
  245. removeFromArray( oldv.faces, this );
  246. newv.faces.push( this );
  247. oldv.removeIfNonNeighbor( this.v1 );
  248. this.v1.removeIfNonNeighbor( oldv );
  249. oldv.removeIfNonNeighbor( this.v2 );
  250. this.v2.removeIfNonNeighbor( oldv );
  251. oldv.removeIfNonNeighbor( this.v3 );
  252. this.v3.removeIfNonNeighbor( oldv );
  253. this.v1.addUniqueNeighbor( this.v2 );
  254. this.v1.addUniqueNeighbor( this.v3 );
  255. this.v2.addUniqueNeighbor( this.v1 );
  256. this.v2.addUniqueNeighbor( this.v3 );
  257. this.v3.addUniqueNeighbor( this.v1 );
  258. this.v3.addUniqueNeighbor( this.v2 );
  259. this.computeNormal();
  260. }
  261. }
  262. class Vertex {
  263. constructor( v ) {
  264. this.position = v;
  265. this.id = - 1; // external use position in vertices list (for e.g. face generation)
  266. this.faces = []; // faces vertex is connected
  267. this.neighbors = []; // neighbouring vertices aka "adjacentVertices"
  268. // these will be computed in computeEdgeCostAtVertex()
  269. this.collapseCost = 0; // cost of collapsing this vertex, the less the better. aka objdist
  270. this.collapseNeighbor = null; // best candinate for collapsing
  271. }
  272. addUniqueNeighbor( vertex ) {
  273. pushIfUnique( this.neighbors, vertex );
  274. }
  275. removeIfNonNeighbor( n ) {
  276. const neighbors = this.neighbors;
  277. const faces = this.faces;
  278. const offset = neighbors.indexOf( n );
  279. if ( offset === - 1 ) return;
  280. for ( let i = 0; i < faces.length; i ++ ) {
  281. if ( faces[ i ].hasVertex( n ) ) return;
  282. }
  283. neighbors.splice( offset, 1 );
  284. }
  285. }
  286. THREE.SimplifyModifier = SimplifyModifier;
  287. } )();