SimplifyModifier.js 13 KB

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