SimplifyModifier.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. import {
  2. BufferGeometry,
  3. Color,
  4. Float32BufferAttribute,
  5. Vector2,
  6. Vector3,
  7. Vector4
  8. } from 'three';
  9. import * as BufferGeometryUtils from '../utils/BufferGeometryUtils.js';
  10. const _cb = new Vector3(), _ab = new Vector3();
  11. /**
  12. * This class can be used to modify a geometry by simplifying it. A typical use
  13. * case for such a modifier is automatic LOD generation.
  14. *
  15. * The implementation is based on [Progressive Mesh type Polygon Reduction Algorithm]{@link https://web.archive.org/web/20230610044040/http://www.melax.com/polychop/}
  16. * by Stan Melax in 1998.
  17. *
  18. * ```js
  19. * const modifier = new SimplifyModifier();
  20. * geometry = modifier.modify( geometry );
  21. * ```
  22. */
  23. class SimplifyModifier {
  24. /**
  25. * Returns a new, modified version of the given geometry by applying a simplification.
  26. * Please note that the resulting geometry is always non-indexed.
  27. *
  28. * @param {BufferGeometry} geometry - The geometry to modify.
  29. * @param {number} count - The number of vertices to remove.
  30. * @return {BufferGeometry} A new, modified geometry.
  31. */
  32. modify( geometry, count ) {
  33. geometry = geometry.clone();
  34. // currently morphAttributes are not supported
  35. delete geometry.morphAttributes.position;
  36. delete geometry.morphAttributes.normal;
  37. const attributes = geometry.attributes;
  38. // this modifier can only process indexed and non-indexed geometries with at least a position attribute
  39. for ( const name in attributes ) {
  40. if ( name !== 'position' && name !== 'uv' && name !== 'normal' && name !== 'tangent' && name !== 'color' ) geometry.deleteAttribute( name );
  41. }
  42. geometry = BufferGeometryUtils.mergeVertices( geometry );
  43. //
  44. // put data of original geometry in different data structures
  45. //
  46. const vertices = [];
  47. const faces = [];
  48. // add vertices
  49. const positionAttribute = geometry.getAttribute( 'position' );
  50. const uvAttribute = geometry.getAttribute( 'uv' );
  51. const normalAttribute = geometry.getAttribute( 'normal' );
  52. const tangentAttribute = geometry.getAttribute( 'tangent' );
  53. const colorAttribute = geometry.getAttribute( 'color' );
  54. let t = null;
  55. let v2 = null;
  56. let nor = null;
  57. let col = null;
  58. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  59. const v = new Vector3().fromBufferAttribute( positionAttribute, i );
  60. if ( uvAttribute ) {
  61. v2 = new Vector2().fromBufferAttribute( uvAttribute, i );
  62. }
  63. if ( normalAttribute ) {
  64. nor = new Vector3().fromBufferAttribute( normalAttribute, i );
  65. }
  66. if ( tangentAttribute ) {
  67. t = new Vector4().fromBufferAttribute( tangentAttribute, i );
  68. }
  69. if ( colorAttribute ) {
  70. col = new Color().fromBufferAttribute( colorAttribute, i );
  71. }
  72. const vertex = new Vertex( v, v2, nor, t, col );
  73. vertices.push( vertex );
  74. }
  75. // add faces
  76. let index = geometry.getIndex();
  77. if ( index !== null ) {
  78. for ( let i = 0; i < index.count; i += 3 ) {
  79. const a = index.getX( i );
  80. const b = index.getX( i + 1 );
  81. const c = index.getX( i + 2 );
  82. const triangle = new Triangle( vertices[ a ], vertices[ b ], vertices[ c ], a, b, c );
  83. faces.push( triangle );
  84. }
  85. } else {
  86. for ( let i = 0; i < positionAttribute.count; i += 3 ) {
  87. const a = i;
  88. const b = i + 1;
  89. const c = i + 2;
  90. const triangle = new Triangle( vertices[ a ], vertices[ b ], vertices[ c ], a, b, c );
  91. faces.push( triangle );
  92. }
  93. }
  94. // compute all edge collapse costs
  95. for ( let i = 0, il = vertices.length; i < il; i ++ ) {
  96. computeEdgeCostAtVertex( vertices[ i ] );
  97. }
  98. let nextVertex;
  99. let z = count;
  100. while ( z -- ) {
  101. nextVertex = minimumCostEdge( vertices );
  102. if ( ! nextVertex ) {
  103. console.log( 'THREE.SimplifyModifier: No next vertex' );
  104. break;
  105. }
  106. collapse( vertices, faces, nextVertex, nextVertex.collapseNeighbor );
  107. }
  108. //
  109. const simplifiedGeometry = new BufferGeometry();
  110. const position = [];
  111. const uv = [];
  112. const normal = [];
  113. const tangent = [];
  114. const color = [];
  115. index = [];
  116. //
  117. for ( let i = 0; i < vertices.length; i ++ ) {
  118. const vertex = vertices[ i ];
  119. position.push( vertex.position.x, vertex.position.y, vertex.position.z );
  120. if ( vertex.uv ) {
  121. uv.push( vertex.uv.x, vertex.uv.y );
  122. }
  123. if ( vertex.normal ) {
  124. normal.push( vertex.normal.x, vertex.normal.y, vertex.normal.z );
  125. }
  126. if ( vertex.tangent ) {
  127. tangent.push( vertex.tangent.x, vertex.tangent.y, vertex.tangent.z, vertex.tangent.w );
  128. }
  129. if ( vertex.color ) {
  130. color.push( vertex.color.r, vertex.color.g, vertex.color.b );
  131. }
  132. // cache final index to GREATLY speed up faces reconstruction
  133. vertex.id = i;
  134. }
  135. //
  136. for ( let i = 0; i < faces.length; i ++ ) {
  137. const face = faces[ i ];
  138. index.push( face.v1.id, face.v2.id, face.v3.id );
  139. }
  140. simplifiedGeometry.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  141. if ( uv.length > 0 ) simplifiedGeometry.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  142. if ( normal.length > 0 ) simplifiedGeometry.setAttribute( 'normal', new Float32BufferAttribute( normal, 3 ) );
  143. if ( tangent.length > 0 ) simplifiedGeometry.setAttribute( 'tangent', new Float32BufferAttribute( tangent, 4 ) );
  144. if ( color.length > 0 ) simplifiedGeometry.setAttribute( 'color', new Float32BufferAttribute( color, 3 ) );
  145. simplifiedGeometry.setIndex( index );
  146. return simplifiedGeometry;
  147. }
  148. }
  149. function pushIfUnique( array, object ) {
  150. if ( array.indexOf( object ) === - 1 ) array.push( object );
  151. }
  152. function removeFromArray( array, object ) {
  153. const k = array.indexOf( object );
  154. if ( k > - 1 ) array.splice( k, 1 );
  155. }
  156. function computeEdgeCollapseCost( u, v ) {
  157. // if we collapse edge uv by moving u to v then how
  158. // much different will the model change, i.e. the "error".
  159. const edgelength = v.position.distanceTo( u.position );
  160. let curvature = 0;
  161. const sideFaces = [];
  162. // find the "sides" triangles that are on the edge uv
  163. for ( let i = 0, il = u.faces.length; i < il; i ++ ) {
  164. const face = u.faces[ i ];
  165. if ( face.hasVertex( v ) ) {
  166. sideFaces.push( face );
  167. }
  168. }
  169. // use the triangle facing most away from the sides
  170. // to determine our curvature term
  171. for ( let i = 0, il = u.faces.length; i < il; i ++ ) {
  172. let minCurvature = 1;
  173. const face = u.faces[ i ];
  174. for ( let j = 0; j < sideFaces.length; j ++ ) {
  175. const sideFace = sideFaces[ j ];
  176. // use dot product of face normals.
  177. const dotProd = face.normal.dot( sideFace.normal );
  178. minCurvature = Math.min( minCurvature, ( 1.001 - dotProd ) / 2 );
  179. }
  180. curvature = Math.max( curvature, minCurvature );
  181. }
  182. // crude approach in attempt to preserve borders
  183. // though it seems not to be totally correct
  184. const borders = 0;
  185. if ( sideFaces.length < 2 ) {
  186. // we add some arbitrary cost for borders,
  187. // borders += 10;
  188. curvature = 1;
  189. }
  190. const amt = edgelength * curvature + borders;
  191. return amt;
  192. }
  193. function computeEdgeCostAtVertex( v ) {
  194. // compute the edge collapse cost for all edges that start
  195. // from vertex v. Since we are only interested in reducing
  196. // the object by selecting the min cost edge at each step, we
  197. // only cache the cost of the least cost edge at this vertex
  198. // (in member variable collapse) as well as the value of the
  199. // cost (in member variable collapseCost).
  200. if ( v.neighbors.length === 0 ) {
  201. // collapse if no neighbors.
  202. v.collapseNeighbor = null;
  203. v.collapseCost = - 0.01;
  204. return;
  205. }
  206. v.collapseCost = 100000;
  207. v.collapseNeighbor = null;
  208. // search all neighboring edges for "least cost" edge
  209. for ( let i = 0; i < v.neighbors.length; i ++ ) {
  210. const collapseCost = computeEdgeCollapseCost( v, v.neighbors[ i ] );
  211. if ( ! v.collapseNeighbor ) {
  212. v.collapseNeighbor = v.neighbors[ i ];
  213. v.collapseCost = collapseCost;
  214. v.minCost = collapseCost;
  215. v.totalCost = 0;
  216. v.costCount = 0;
  217. }
  218. v.costCount ++;
  219. v.totalCost += collapseCost;
  220. if ( collapseCost < v.minCost ) {
  221. v.collapseNeighbor = v.neighbors[ i ];
  222. v.minCost = collapseCost;
  223. }
  224. }
  225. // we average the cost of collapsing at this vertex
  226. v.collapseCost = v.totalCost / v.costCount;
  227. // v.collapseCost = v.minCost;
  228. }
  229. function removeVertex( v, vertices ) {
  230. console.assert( v.faces.length === 0 );
  231. while ( v.neighbors.length ) {
  232. const n = v.neighbors.pop();
  233. removeFromArray( n.neighbors, v );
  234. }
  235. removeFromArray( vertices, v );
  236. }
  237. function removeFace( f, faces ) {
  238. removeFromArray( faces, f );
  239. if ( f.v1 ) removeFromArray( f.v1.faces, f );
  240. if ( f.v2 ) removeFromArray( f.v2.faces, f );
  241. if ( f.v3 ) removeFromArray( f.v3.faces, f );
  242. // TODO optimize this!
  243. const vs = [ f.v1, f.v2, f.v3 ];
  244. for ( let i = 0; i < 3; i ++ ) {
  245. const v1 = vs[ i ];
  246. const v2 = vs[ ( i + 1 ) % 3 ];
  247. if ( ! v1 || ! v2 ) continue;
  248. v1.removeIfNonNeighbor( v2 );
  249. v2.removeIfNonNeighbor( v1 );
  250. }
  251. }
  252. function collapse( vertices, faces, u, v ) {
  253. // Collapse the edge uv by moving vertex u onto v
  254. if ( ! v ) {
  255. // u is a vertex all by itself so just delete it..
  256. removeVertex( u, vertices );
  257. return;
  258. }
  259. if ( v.uv ) {
  260. u.uv.copy( v.uv );
  261. }
  262. if ( v.normal ) {
  263. v.normal.add( u.normal ).normalize();
  264. }
  265. if ( v.tangent ) {
  266. v.tangent.add( u.tangent ).normalize();
  267. }
  268. const tmpVertices = [];
  269. for ( let i = 0; i < u.neighbors.length; i ++ ) {
  270. tmpVertices.push( u.neighbors[ i ] );
  271. }
  272. // delete triangles on edge uv:
  273. for ( let i = u.faces.length - 1; i >= 0; i -- ) {
  274. if ( u.faces[ i ] && u.faces[ i ].hasVertex( v ) ) {
  275. removeFace( u.faces[ i ], faces );
  276. }
  277. }
  278. // update remaining triangles to have v instead of u
  279. for ( let i = u.faces.length - 1; i >= 0; i -- ) {
  280. u.faces[ i ].replaceVertex( u, v );
  281. }
  282. removeVertex( u, vertices );
  283. // recompute the edge collapse costs in neighborhood
  284. for ( let i = 0; i < tmpVertices.length; i ++ ) {
  285. computeEdgeCostAtVertex( tmpVertices[ i ] );
  286. }
  287. }
  288. function minimumCostEdge( vertices ) {
  289. // O(n * n) approach. TODO optimize this
  290. let least = vertices[ 0 ];
  291. for ( let i = 0; i < vertices.length; i ++ ) {
  292. if ( vertices[ i ].collapseCost < least.collapseCost ) {
  293. least = vertices[ i ];
  294. }
  295. }
  296. return least;
  297. }
  298. // we use a triangle class to represent structure of face slightly differently
  299. class Triangle {
  300. constructor( v1, v2, v3, a, b, c ) {
  301. this.a = a;
  302. this.b = b;
  303. this.c = c;
  304. this.v1 = v1;
  305. this.v2 = v2;
  306. this.v3 = v3;
  307. this.normal = new Vector3();
  308. this.computeNormal();
  309. v1.faces.push( this );
  310. v1.addUniqueNeighbor( v2 );
  311. v1.addUniqueNeighbor( v3 );
  312. v2.faces.push( this );
  313. v2.addUniqueNeighbor( v1 );
  314. v2.addUniqueNeighbor( v3 );
  315. v3.faces.push( this );
  316. v3.addUniqueNeighbor( v1 );
  317. v3.addUniqueNeighbor( v2 );
  318. }
  319. computeNormal() {
  320. const vA = this.v1.position;
  321. const vB = this.v2.position;
  322. const vC = this.v3.position;
  323. _cb.subVectors( vC, vB );
  324. _ab.subVectors( vA, vB );
  325. _cb.cross( _ab ).normalize();
  326. this.normal.copy( _cb );
  327. }
  328. hasVertex( v ) {
  329. return v === this.v1 || v === this.v2 || v === this.v3;
  330. }
  331. replaceVertex( oldv, newv ) {
  332. if ( oldv === this.v1 ) this.v1 = newv;
  333. else if ( oldv === this.v2 ) this.v2 = newv;
  334. else if ( oldv === this.v3 ) this.v3 = newv;
  335. removeFromArray( oldv.faces, this );
  336. newv.faces.push( this );
  337. oldv.removeIfNonNeighbor( this.v1 );
  338. this.v1.removeIfNonNeighbor( oldv );
  339. oldv.removeIfNonNeighbor( this.v2 );
  340. this.v2.removeIfNonNeighbor( oldv );
  341. oldv.removeIfNonNeighbor( this.v3 );
  342. this.v3.removeIfNonNeighbor( oldv );
  343. this.v1.addUniqueNeighbor( this.v2 );
  344. this.v1.addUniqueNeighbor( this.v3 );
  345. this.v2.addUniqueNeighbor( this.v1 );
  346. this.v2.addUniqueNeighbor( this.v3 );
  347. this.v3.addUniqueNeighbor( this.v1 );
  348. this.v3.addUniqueNeighbor( this.v2 );
  349. this.computeNormal();
  350. }
  351. }
  352. class Vertex {
  353. constructor( v, uv, normal, tangent, color ) {
  354. this.position = v;
  355. this.uv = uv;
  356. this.normal = normal;
  357. this.tangent = tangent;
  358. this.color = color;
  359. this.id = - 1; // external use position in vertices list (for e.g. face generation)
  360. this.faces = []; // faces vertex is connected
  361. this.neighbors = []; // neighbouring vertices aka "adjacentVertices"
  362. // these will be computed in computeEdgeCostAtVertex()
  363. this.collapseCost = 0; // cost of collapsing this vertex, the less the better. aka objdist
  364. this.collapseNeighbor = null; // best candidate for collapsing
  365. }
  366. addUniqueNeighbor( vertex ) {
  367. pushIfUnique( this.neighbors, vertex );
  368. }
  369. removeIfNonNeighbor( n ) {
  370. const neighbors = this.neighbors;
  371. const faces = this.faces;
  372. const offset = neighbors.indexOf( n );
  373. if ( offset === - 1 ) return;
  374. for ( let i = 0; i < faces.length; i ++ ) {
  375. if ( faces[ i ].hasVertex( n ) ) return;
  376. }
  377. neighbors.splice( offset, 1 );
  378. }
  379. }
  380. export { SimplifyModifier };
粤ICP备19079148号