SimplifyModifier.js 10 KB

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