SimplifyModifier.js 10 KB

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