SimplifyModifier.js 10 KB

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