SimplifyModifier.js 10.0 KB

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