0
0

SimplifyModifier.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. import {
  2. BufferGeometry,
  3. Float32BufferAttribute,
  4. Vector3
  5. } from '../../../build/three.module.js';
  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. 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 );
  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. // cache final index to GREATLY speed up faces reconstruction
  87. vertices[ i ].id = i;
  88. }
  89. //
  90. for ( let i = 0; i < faces.length; i ++ ) {
  91. const face = faces[ i ];
  92. index.push( face.v1.id, face.v2.id, face.v3.id );
  93. }
  94. //
  95. simplifiedGeometry.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  96. simplifiedGeometry.setIndex( index );
  97. return simplifiedGeometry;
  98. }
  99. }
  100. function pushIfUnique( array, object ) {
  101. if ( array.indexOf( object ) === - 1 ) array.push( object );
  102. }
  103. function removeFromArray( array, object ) {
  104. var k = array.indexOf( object );
  105. if ( k > - 1 ) array.splice( k, 1 );
  106. }
  107. function computeEdgeCollapseCost( u, v ) {
  108. // if we collapse edge uv by moving u to v then how
  109. // much different will the model change, i.e. the "error".
  110. const edgelength = v.position.distanceTo( u.position );
  111. let curvature = 0;
  112. const sideFaces = [];
  113. // find the "sides" triangles that are on the edge uv
  114. for ( let i = 0, il = u.faces.length; i < il; i ++ ) {
  115. const face = u.faces[ i ];
  116. if ( face.hasVertex( v ) ) {
  117. sideFaces.push( face );
  118. }
  119. }
  120. // use the triangle facing most away from the sides
  121. // to determine our curvature term
  122. for ( let i = 0, il = u.faces.length; i < il; i ++ ) {
  123. let minCurvature = 1;
  124. const face = u.faces[ i ];
  125. for ( let j = 0; j < sideFaces.length; j ++ ) {
  126. const sideFace = sideFaces[ j ];
  127. // use dot product of face normals.
  128. const dotProd = face.normal.dot( sideFace.normal );
  129. minCurvature = Math.min( minCurvature, ( 1.001 - dotProd ) / 2 );
  130. }
  131. curvature = Math.max( curvature, minCurvature );
  132. }
  133. // crude approach in attempt to preserve borders
  134. // though it seems not to be totally correct
  135. const borders = 0;
  136. if ( sideFaces.length < 2 ) {
  137. // we add some arbitrary cost for borders,
  138. // borders += 10;
  139. curvature = 1;
  140. }
  141. const amt = edgelength * curvature + borders;
  142. return amt;
  143. }
  144. function computeEdgeCostAtVertex( v ) {
  145. // compute the edge collapse cost for all edges that start
  146. // from vertex v. Since we are only interested in reducing
  147. // the object by selecting the min cost edge at each step, we
  148. // only cache the cost of the least cost edge at this vertex
  149. // (in member variable collapse) as well as the value of the
  150. // cost (in member variable collapseCost).
  151. if ( v.neighbors.length === 0 ) {
  152. // collapse if no neighbors.
  153. v.collapseNeighbor = null;
  154. v.collapseCost = - 0.01;
  155. return;
  156. }
  157. v.collapseCost = 100000;
  158. v.collapseNeighbor = null;
  159. // search all neighboring edges for "least cost" edge
  160. for ( let i = 0; i < v.neighbors.length; i ++ ) {
  161. const collapseCost = computeEdgeCollapseCost( v, v.neighbors[ i ] );
  162. if ( ! v.collapseNeighbor ) {
  163. v.collapseNeighbor = v.neighbors[ i ];
  164. v.collapseCost = collapseCost;
  165. v.minCost = collapseCost;
  166. v.totalCost = 0;
  167. v.costCount = 0;
  168. }
  169. v.costCount ++;
  170. v.totalCost += collapseCost;
  171. if ( collapseCost < v.minCost ) {
  172. v.collapseNeighbor = v.neighbors[ i ];
  173. v.minCost = collapseCost;
  174. }
  175. }
  176. // we average the cost of collapsing at this vertex
  177. v.collapseCost = v.totalCost / v.costCount;
  178. // v.collapseCost = v.minCost;
  179. }
  180. function removeVertex( v, vertices ) {
  181. console.assert( v.faces.length === 0 );
  182. while ( v.neighbors.length ) {
  183. const n = v.neighbors.pop();
  184. removeFromArray( n.neighbors, v );
  185. }
  186. removeFromArray( vertices, v );
  187. }
  188. function removeFace( f, faces ) {
  189. removeFromArray( faces, f );
  190. if ( f.v1 ) removeFromArray( f.v1.faces, f );
  191. if ( f.v2 ) removeFromArray( f.v2.faces, f );
  192. if ( f.v3 ) removeFromArray( f.v3.faces, f );
  193. // TODO optimize this!
  194. const vs = [ f.v1, f.v2, f.v3 ];
  195. for ( let i = 0; i < 3; i ++ ) {
  196. const v1 = vs[ i ];
  197. const v2 = vs[ ( i + 1 ) % 3 ];
  198. if ( ! v1 || ! v2 ) continue;
  199. v1.removeIfNonNeighbor( v2 );
  200. v2.removeIfNonNeighbor( v1 );
  201. }
  202. }
  203. function collapse( vertices, faces, u, v ) { // u and v are pointers to vertices of an edge
  204. // Collapse the edge uv by moving vertex u onto v
  205. if ( ! v ) {
  206. // u is a vertex all by itself so just delete it..
  207. removeVertex( u, vertices );
  208. return;
  209. }
  210. const tmpVertices = [];
  211. for ( let i = 0; i < u.neighbors.length; i ++ ) {
  212. tmpVertices.push( u.neighbors[ i ] );
  213. }
  214. // delete triangles on edge uv:
  215. for ( let i = u.faces.length - 1; i >= 0; i -- ) {
  216. if ( u.faces[ i ].hasVertex( v ) ) {
  217. removeFace( u.faces[ i ], faces );
  218. }
  219. }
  220. // update remaining triangles to have v instead of u
  221. for ( let i = u.faces.length - 1; i >= 0; i -- ) {
  222. u.faces[ i ].replaceVertex( u, v );
  223. }
  224. removeVertex( u, vertices );
  225. // recompute the edge collapse costs in neighborhood
  226. for ( let i = 0; i < tmpVertices.length; i ++ ) {
  227. computeEdgeCostAtVertex( tmpVertices[ i ] );
  228. }
  229. }
  230. function minimumCostEdge( vertices ) {
  231. // O(n * n) approach. TODO optimize this
  232. let least = vertices[ 0 ];
  233. for ( let i = 0; i < vertices.length; i ++ ) {
  234. if ( vertices[ i ].collapseCost < least.collapseCost ) {
  235. least = vertices[ i ];
  236. }
  237. }
  238. return least;
  239. }
  240. // we use a triangle class to represent structure of face slightly differently
  241. class Triangle {
  242. constructor( v1, v2, v3, a, b, c ) {
  243. this.a = a;
  244. this.b = b;
  245. this.c = c;
  246. this.v1 = v1;
  247. this.v2 = v2;
  248. this.v3 = v3;
  249. this.normal = new Vector3();
  250. this.computeNormal();
  251. v1.faces.push( this );
  252. v1.addUniqueNeighbor( v2 );
  253. v1.addUniqueNeighbor( v3 );
  254. v2.faces.push( this );
  255. v2.addUniqueNeighbor( v1 );
  256. v2.addUniqueNeighbor( v3 );
  257. v3.faces.push( this );
  258. v3.addUniqueNeighbor( v1 );
  259. v3.addUniqueNeighbor( v2 );
  260. }
  261. computeNormal() {
  262. const vA = this.v1.position;
  263. const vB = this.v2.position;
  264. const vC = this.v3.position;
  265. _cb.subVectors( vC, vB );
  266. _ab.subVectors( vA, vB );
  267. _cb.cross( _ab ).normalize();
  268. this.normal.copy( _cb );
  269. }
  270. hasVertex( v ) {
  271. return v === this.v1 || v === this.v2 || v === this.v3;
  272. }
  273. replaceVertex( oldv, newv ) {
  274. if ( oldv === this.v1 ) this.v1 = newv;
  275. else if ( oldv === this.v2 ) this.v2 = newv;
  276. else if ( oldv === this.v3 ) this.v3 = newv;
  277. removeFromArray( oldv.faces, this );
  278. newv.faces.push( this );
  279. oldv.removeIfNonNeighbor( this.v1 );
  280. this.v1.removeIfNonNeighbor( oldv );
  281. oldv.removeIfNonNeighbor( this.v2 );
  282. this.v2.removeIfNonNeighbor( oldv );
  283. oldv.removeIfNonNeighbor( this.v3 );
  284. this.v3.removeIfNonNeighbor( oldv );
  285. this.v1.addUniqueNeighbor( this.v2 );
  286. this.v1.addUniqueNeighbor( this.v3 );
  287. this.v2.addUniqueNeighbor( this.v1 );
  288. this.v2.addUniqueNeighbor( this.v3 );
  289. this.v3.addUniqueNeighbor( this.v1 );
  290. this.v3.addUniqueNeighbor( this.v2 );
  291. this.computeNormal();
  292. }
  293. }
  294. class Vertex {
  295. constructor( v ) {
  296. this.position = v;
  297. this.id = - 1; // external use position in vertices list (for e.g. face generation)
  298. this.faces = []; // faces vertex is connected
  299. this.neighbors = []; // neighbouring vertices aka "adjacentVertices"
  300. // these will be computed in computeEdgeCostAtVertex()
  301. this.collapseCost = 0; // cost of collapsing this vertex, the less the better. aka objdist
  302. this.collapseNeighbor = null; // best candinate for collapsing
  303. }
  304. addUniqueNeighbor( vertex ) {
  305. pushIfUnique( this.neighbors, vertex );
  306. }
  307. removeIfNonNeighbor( n ) {
  308. const neighbors = this.neighbors;
  309. const faces = this.faces;
  310. const offset = neighbors.indexOf( n );
  311. if ( offset === - 1 ) return;
  312. for ( let i = 0; i < faces.length; i ++ ) {
  313. if ( faces[ i ].hasVertex( n ) ) return;
  314. }
  315. neighbors.splice( offset, 1 );
  316. }
  317. }
  318. export { SimplifyModifier };