SimplifyModifier.js 10 KB

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