ConvexHull.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695
  1. import {
  2. Line3,
  3. Plane,
  4. Triangle,
  5. Vector3
  6. } from 'three';
  7. const Visible = 0;
  8. const Deleted = 1;
  9. const _v1 = new Vector3();
  10. const _line3 = new Line3();
  11. const _plane = new Plane();
  12. const _closestPoint = new Vector3();
  13. const _triangle = new Triangle();
  14. /**
  15. * Can be used to compute the convex hull in 3D space for a given set of points. It
  16. * is primarily intended for {@link ConvexGeometry}.
  17. *
  18. * This Quickhull 3D implementation is a port of [quickhull3d]{@link https://github.com/maurizzzio/quickhull3d/}
  19. * by Mauricio Poppe.
  20. *
  21. * @three_import import { ConvexHull } from 'three/addons/math/ConvexHull.js';
  22. */
  23. class ConvexHull {
  24. /**
  25. * Constructs a new convex hull.
  26. */
  27. constructor() {
  28. this.tolerance = - 1;
  29. this.faces = []; // the generated faces of the convex hull
  30. this.newFaces = []; // this array holds the faces that are generated within a single iteration
  31. // the vertex lists work as follows:
  32. //
  33. // let 'a' and 'b' be 'Face' instances
  34. // let 'v' be points wrapped as instance of 'Vertex'
  35. //
  36. // [v, v, ..., v, v, v, ...]
  37. // ^ ^
  38. // | |
  39. // a.outside b.outside
  40. //
  41. this.assigned = new VertexList();
  42. this.unassigned = new VertexList();
  43. this.vertices = []; // vertices of the hull (internal representation of given geometry data)
  44. }
  45. /**
  46. * Computes to convex hull for the given array of points.
  47. *
  48. * @param {Array<Vector3>} points - The array of points in 3D space.
  49. * @return {ConvexHull} A reference to this convex hull.
  50. */
  51. setFromPoints( points ) {
  52. // The algorithm needs at least four points.
  53. if ( points.length >= 4 ) {
  54. this.makeEmpty();
  55. for ( let i = 0, l = points.length; i < l; i ++ ) {
  56. this.vertices.push( new VertexNode( points[ i ] ) );
  57. }
  58. this._compute();
  59. }
  60. return this;
  61. }
  62. /**
  63. * Computes the convex hull of the given 3D object (including its descendants),
  64. * accounting for the world transforms of both the 3D object and its descendants.
  65. *
  66. * @param {Object3D} object - The 3D object to compute the convex hull for.
  67. * @return {ConvexHull} A reference to this convex hull.
  68. */
  69. setFromObject( object ) {
  70. const points = [];
  71. object.updateMatrixWorld( true );
  72. object.traverse( function ( node ) {
  73. const geometry = node.geometry;
  74. if ( geometry !== undefined ) {
  75. const attribute = geometry.attributes.position;
  76. if ( attribute !== undefined ) {
  77. for ( let i = 0, l = attribute.count; i < l; i ++ ) {
  78. const point = new Vector3();
  79. point.fromBufferAttribute( attribute, i ).applyMatrix4( node.matrixWorld );
  80. points.push( point );
  81. }
  82. }
  83. }
  84. } );
  85. return this.setFromPoints( points );
  86. }
  87. /**
  88. * Returns `true` if the given point lies in the convex hull.
  89. *
  90. * @param {Vector3} point - The point to test.
  91. * @return {boolean} Whether the given point lies in the convex hull or not.
  92. */
  93. containsPoint( point ) {
  94. const faces = this.faces;
  95. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  96. const face = faces[ i ];
  97. // compute signed distance and check on what half space the point lies
  98. if ( face.distanceToPoint( point ) > this.tolerance ) return false;
  99. }
  100. return true;
  101. }
  102. /**
  103. * Computes the intersections point of the given ray and this convex hull.
  104. *
  105. * @param {Ray} ray - The ray to test.
  106. * @param {Vector3} target - The target vector that is used to store the method's result.
  107. * @return {Vector3|null} The intersection point. Returns `null` if not intersection was detected.
  108. */
  109. intersectRay( ray, target ) {
  110. // based on "Fast Ray-Convex Polyhedron Intersection" by Eric Haines, GRAPHICS GEMS II
  111. const faces = this.faces;
  112. let tNear = - Infinity;
  113. let tFar = Infinity;
  114. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  115. const face = faces[ i ];
  116. // interpret faces as planes for the further computation
  117. const vN = face.distanceToPoint( ray.origin );
  118. const vD = face.normal.dot( ray.direction );
  119. // if the origin is on the positive side of a plane (so the plane can "see" the origin) and
  120. // the ray is turned away or parallel to the plane, there is no intersection
  121. if ( vN > 0 && vD >= 0 ) return null;
  122. // compute the distance from the ray’s origin to the intersection with the plane
  123. const t = ( vD !== 0 ) ? ( - vN / vD ) : 0;
  124. // only proceed if the distance is positive. a negative distance means the intersection point
  125. // lies "behind" the origin
  126. if ( t <= 0 ) continue;
  127. // now categorized plane as front-facing or back-facing
  128. if ( vD > 0 ) {
  129. // plane faces away from the ray, so this plane is a back-face
  130. tFar = Math.min( t, tFar );
  131. } else {
  132. // front-face
  133. tNear = Math.max( t, tNear );
  134. }
  135. if ( tNear > tFar ) {
  136. // if tNear ever is greater than tFar, the ray must miss the convex hull
  137. return null;
  138. }
  139. }
  140. // evaluate intersection point
  141. // always try tNear first since its the closer intersection point
  142. if ( tNear !== - Infinity ) {
  143. ray.at( tNear, target );
  144. } else {
  145. ray.at( tFar, target );
  146. }
  147. return target;
  148. }
  149. /**
  150. * Returns `true` if the given ray intersects with this convex hull.
  151. *
  152. * @param {Ray} ray - The ray to test.
  153. * @return {boolean} Whether the given ray intersects with this convex hull or not.
  154. */
  155. intersectsRay( ray ) {
  156. return this.intersectRay( ray, _v1 ) !== null;
  157. }
  158. /**
  159. * Makes the convex hull empty.
  160. *
  161. * @return {ConvexHull} A reference to this convex hull.
  162. */
  163. makeEmpty() {
  164. this.faces = [];
  165. this.vertices = [];
  166. return this;
  167. }
  168. // private
  169. /**
  170. * Adds a vertex to the 'assigned' list of vertices and assigns it to the given face.
  171. *
  172. * @private
  173. * @param {VertexNode} vertex - The vertex to add.
  174. * @param {Face} face - The target face.
  175. * @return {ConvexHull} A reference to this convex hull.
  176. */
  177. _addVertexToFace( vertex, face ) {
  178. vertex.face = face;
  179. if ( face.outside === null ) {
  180. this.assigned.append( vertex );
  181. } else {
  182. this.assigned.insertBefore( face.outside, vertex );
  183. }
  184. face.outside = vertex;
  185. return this;
  186. }
  187. /**
  188. * Removes a vertex from the 'assigned' list of vertices and from the given face.
  189. * It also makes sure that the link from 'face' to the first vertex it sees in 'assigned'
  190. * is linked correctly after the removal.
  191. *
  192. * @private
  193. * @param {VertexNode} vertex - The vertex to remove.
  194. * @param {Face} face - The target face.
  195. * @return {ConvexHull} A reference to this convex hull.
  196. */
  197. _removeVertexFromFace( vertex, face ) {
  198. if ( vertex === face.outside ) {
  199. // fix face.outside link
  200. if ( vertex.next !== null && vertex.next.face === face ) {
  201. // face has at least 2 outside vertices, move the 'outside' reference
  202. face.outside = vertex.next;
  203. } else {
  204. // vertex was the only outside vertex that face had
  205. face.outside = null;
  206. }
  207. }
  208. this.assigned.remove( vertex );
  209. return this;
  210. }
  211. /**
  212. * Removes all the visible vertices that a given face is able to see which are stored in
  213. * the 'assigned' vertex list.
  214. *
  215. * @private
  216. * @param {Face} face - The target face.
  217. * @return {VertexNode|undefined} A reference to this convex hull.
  218. */
  219. _removeAllVerticesFromFace( face ) {
  220. if ( face.outside !== null ) {
  221. // reference to the first and last vertex of this face
  222. const start = face.outside;
  223. let end = face.outside;
  224. while ( end.next !== null && end.next.face === face ) {
  225. end = end.next;
  226. }
  227. this.assigned.removeSubList( start, end );
  228. // fix references
  229. start.prev = end.next = null;
  230. face.outside = null;
  231. return start;
  232. }
  233. }
  234. /**
  235. * Removes all the visible vertices that `face` is able to see.
  236. *
  237. * - If `absorbingFace` doesn't exist, then all the removed vertices will be added to the 'unassigned' vertex list.
  238. * - If `absorbingFace` exists, then this method will assign all the vertices of 'face' that can see 'absorbingFace'.
  239. * - If a vertex cannot see `absorbingFace`, it's added to the 'unassigned' vertex list.
  240. *
  241. * @private
  242. * @param {Face} face - The given face.
  243. * @param {Face} [absorbingFace] - An optional face that tries to absorb the vertices of the first face.
  244. * @return {ConvexHull} A reference to this convex hull.
  245. */
  246. _deleteFaceVertices( face, absorbingFace ) {
  247. const faceVertices = this._removeAllVerticesFromFace( face );
  248. if ( faceVertices !== undefined ) {
  249. if ( absorbingFace === undefined ) {
  250. // mark the vertices to be reassigned to some other face
  251. this.unassigned.appendChain( faceVertices );
  252. } else {
  253. // if there's an absorbing face try to assign as many vertices as possible to it
  254. let vertex = faceVertices;
  255. do {
  256. // we need to buffer the subsequent vertex at this point because the 'vertex.next' reference
  257. // will be changed by upcoming method calls
  258. const nextVertex = vertex.next;
  259. const distance = absorbingFace.distanceToPoint( vertex.point );
  260. // check if 'vertex' is able to see 'absorbingFace'
  261. if ( distance > this.tolerance ) {
  262. this._addVertexToFace( vertex, absorbingFace );
  263. } else {
  264. this.unassigned.append( vertex );
  265. }
  266. // now assign next vertex
  267. vertex = nextVertex;
  268. } while ( vertex !== null );
  269. }
  270. }
  271. return this;
  272. }
  273. /**
  274. * Reassigns as many vertices as possible from the unassigned list to the new faces.
  275. *
  276. * @private
  277. * @param {Array<Face>} newFaces - The new faces.
  278. * @return {ConvexHull} A reference to this convex hull.
  279. */
  280. _resolveUnassignedPoints( newFaces ) {
  281. if ( this.unassigned.isEmpty() === false ) {
  282. let vertex = this.unassigned.first();
  283. do {
  284. // buffer 'next' reference, see ._deleteFaceVertices()
  285. const nextVertex = vertex.next;
  286. let maxDistance = this.tolerance;
  287. let maxFace = null;
  288. for ( let i = 0; i < newFaces.length; i ++ ) {
  289. const face = newFaces[ i ];
  290. if ( face.mark === Visible ) {
  291. const distance = face.distanceToPoint( vertex.point );
  292. if ( distance > maxDistance ) {
  293. maxDistance = distance;
  294. maxFace = face;
  295. }
  296. if ( maxDistance > 1000 * this.tolerance ) break;
  297. }
  298. }
  299. // 'maxFace' can be null e.g. if there are identical vertices
  300. if ( maxFace !== null ) {
  301. this._addVertexToFace( vertex, maxFace );
  302. }
  303. vertex = nextVertex;
  304. } while ( vertex !== null );
  305. }
  306. return this;
  307. }
  308. /**
  309. * Computes the extremes values (min/max vectors) which will be used to
  310. * compute the initial hull.
  311. *
  312. * @private
  313. * @return {Object} The extremes.
  314. */
  315. _computeExtremes() {
  316. const min = new Vector3();
  317. const max = new Vector3();
  318. const minVertices = [];
  319. const maxVertices = [];
  320. // initially assume that the first vertex is the min/max
  321. for ( let i = 0; i < 3; i ++ ) {
  322. minVertices[ i ] = maxVertices[ i ] = this.vertices[ 0 ];
  323. }
  324. min.copy( this.vertices[ 0 ].point );
  325. max.copy( this.vertices[ 0 ].point );
  326. // compute the min/max vertex on all six directions
  327. for ( let i = 0, l = this.vertices.length; i < l; i ++ ) {
  328. const vertex = this.vertices[ i ];
  329. const point = vertex.point;
  330. // update the min coordinates
  331. for ( let j = 0; j < 3; j ++ ) {
  332. if ( point.getComponent( j ) < min.getComponent( j ) ) {
  333. min.setComponent( j, point.getComponent( j ) );
  334. minVertices[ j ] = vertex;
  335. }
  336. }
  337. // update the max coordinates
  338. for ( let j = 0; j < 3; j ++ ) {
  339. if ( point.getComponent( j ) > max.getComponent( j ) ) {
  340. max.setComponent( j, point.getComponent( j ) );
  341. maxVertices[ j ] = vertex;
  342. }
  343. }
  344. }
  345. // use min/max vectors to compute an optimal epsilon
  346. this.tolerance = 3 * Number.EPSILON * (
  347. Math.max( Math.abs( min.x ), Math.abs( max.x ) ) +
  348. Math.max( Math.abs( min.y ), Math.abs( max.y ) ) +
  349. Math.max( Math.abs( min.z ), Math.abs( max.z ) )
  350. );
  351. return { min: minVertices, max: maxVertices };
  352. }
  353. /**
  354. * Computes the initial simplex assigning to its faces all the points that are
  355. * candidates to form part of the hull.
  356. *
  357. * @private
  358. * @return {ConvexHull} A reference to this convex hull.
  359. */
  360. _computeInitialHull() {
  361. const vertices = this.vertices;
  362. const extremes = this._computeExtremes();
  363. const min = extremes.min;
  364. const max = extremes.max;
  365. // 1. Find the two vertices 'v0' and 'v1' with the greatest 1d separation
  366. // (max.x - min.x)
  367. // (max.y - min.y)
  368. // (max.z - min.z)
  369. let maxDistance = 0;
  370. let index = 0;
  371. for ( let i = 0; i < 3; i ++ ) {
  372. const distance = max[ i ].point.getComponent( i ) - min[ i ].point.getComponent( i );
  373. if ( distance > maxDistance ) {
  374. maxDistance = distance;
  375. index = i;
  376. }
  377. }
  378. const v0 = min[ index ];
  379. const v1 = max[ index ];
  380. let v2;
  381. let v3;
  382. // 2. The next vertex 'v2' is the one farthest to the line formed by 'v0' and 'v1'
  383. maxDistance = 0;
  384. _line3.set( v0.point, v1.point );
  385. for ( let i = 0, l = this.vertices.length; i < l; i ++ ) {
  386. const vertex = vertices[ i ];
  387. if ( vertex !== v0 && vertex !== v1 ) {
  388. _line3.closestPointToPoint( vertex.point, true, _closestPoint );
  389. const distance = _closestPoint.distanceToSquared( vertex.point );
  390. if ( distance > maxDistance ) {
  391. maxDistance = distance;
  392. v2 = vertex;
  393. }
  394. }
  395. }
  396. // 3. The next vertex 'v3' is the one farthest to the plane 'v0', 'v1', 'v2'
  397. maxDistance = - 1;
  398. _plane.setFromCoplanarPoints( v0.point, v1.point, v2.point );
  399. for ( let i = 0, l = this.vertices.length; i < l; i ++ ) {
  400. const vertex = vertices[ i ];
  401. if ( vertex !== v0 && vertex !== v1 && vertex !== v2 ) {
  402. const distance = Math.abs( _plane.distanceToPoint( vertex.point ) );
  403. if ( distance > maxDistance ) {
  404. maxDistance = distance;
  405. v3 = vertex;
  406. }
  407. }
  408. }
  409. const faces = [];
  410. if ( _plane.distanceToPoint( v3.point ) < 0 ) {
  411. // the face is not able to see the point so 'plane.normal' is pointing outside the tetrahedron
  412. faces.push(
  413. Face.create( v0, v1, v2 ),
  414. Face.create( v3, v1, v0 ),
  415. Face.create( v3, v2, v1 ),
  416. Face.create( v3, v0, v2 )
  417. );
  418. // set the twin edge
  419. for ( let i = 0; i < 3; i ++ ) {
  420. const j = ( i + 1 ) % 3;
  421. // join face[ i ] i > 0, with the first face
  422. faces[ i + 1 ].getEdge( 2 ).setTwin( faces[ 0 ].getEdge( j ) );
  423. // join face[ i ] with face[ i + 1 ], 1 <= i <= 3
  424. faces[ i + 1 ].getEdge( 1 ).setTwin( faces[ j + 1 ].getEdge( 0 ) );
  425. }
  426. } else {
  427. // the face is able to see the point so 'plane.normal' is pointing inside the tetrahedron
  428. faces.push(
  429. Face.create( v0, v2, v1 ),
  430. Face.create( v3, v0, v1 ),
  431. Face.create( v3, v1, v2 ),
  432. Face.create( v3, v2, v0 )
  433. );
  434. // set the twin edge
  435. for ( let i = 0; i < 3; i ++ ) {
  436. const j = ( i + 1 ) % 3;
  437. // join face[ i ] i > 0, with the first face
  438. faces[ i + 1 ].getEdge( 2 ).setTwin( faces[ 0 ].getEdge( ( 3 - i ) % 3 ) );
  439. // join face[ i ] with face[ i + 1 ]
  440. faces[ i + 1 ].getEdge( 0 ).setTwin( faces[ j + 1 ].getEdge( 1 ) );
  441. }
  442. }
  443. // the initial hull is the tetrahedron
  444. for ( let i = 0; i < 4; i ++ ) {
  445. this.faces.push( faces[ i ] );
  446. }
  447. // initial assignment of vertices to the faces of the tetrahedron
  448. for ( let i = 0, l = vertices.length; i < l; i ++ ) {
  449. const vertex = vertices[ i ];
  450. if ( vertex !== v0 && vertex !== v1 && vertex !== v2 && vertex !== v3 ) {
  451. maxDistance = this.tolerance;
  452. let maxFace = null;
  453. for ( let j = 0; j < 4; j ++ ) {
  454. const distance = this.faces[ j ].distanceToPoint( vertex.point );
  455. if ( distance > maxDistance ) {
  456. maxDistance = distance;
  457. maxFace = this.faces[ j ];
  458. }
  459. }
  460. if ( maxFace !== null ) {
  461. this._addVertexToFace( vertex, maxFace );
  462. }
  463. }
  464. }
  465. return this;
  466. }
  467. /**
  468. * Removes inactive (e.g. deleted) faces from the internal face list.
  469. *
  470. * @private
  471. * @return {ConvexHull} A reference to this convex hull.
  472. */
  473. _reindexFaces() {
  474. const activeFaces = [];
  475. for ( let i = 0; i < this.faces.length; i ++ ) {
  476. const face = this.faces[ i ];
  477. if ( face.mark === Visible ) {
  478. activeFaces.push( face );
  479. }
  480. }
  481. this.faces = activeFaces;
  482. return this;
  483. }
  484. /**
  485. * Finds the next vertex to create faces with the current hull.
  486. *
  487. * - Let the initial face be the first face existing in the 'assigned' vertex list.
  488. * - If a face doesn't exist then return since there're no vertices left.
  489. * - Otherwise for each vertex that face sees find the one furthest away from it.
  490. *
  491. * @private
  492. * @return {?VertexNode} The next vertex to add.
  493. */
  494. _nextVertexToAdd() {
  495. // if the 'assigned' list of vertices is empty, no vertices are left. return with 'undefined'
  496. if ( this.assigned.isEmpty() === false ) {
  497. let eyeVertex, maxDistance = 0;
  498. // grab the first available face and start with the first visible vertex of that face
  499. const eyeFace = this.assigned.first().face;
  500. let vertex = eyeFace.outside;
  501. // now calculate the farthest vertex that face can see
  502. do {
  503. const distance = eyeFace.distanceToPoint( vertex.point );
  504. if ( distance > maxDistance ) {
  505. maxDistance = distance;
  506. eyeVertex = vertex;
  507. }
  508. vertex = vertex.next;
  509. } while ( vertex !== null && vertex.face === eyeFace );
  510. return eyeVertex;
  511. }
  512. }
  513. /**
  514. * Computes a chain of half edges in CCW order called the 'horizon'. For an edge
  515. * to be part of the horizon it must join a face that can see 'eyePoint' and a face
  516. * that cannot see 'eyePoint'.
  517. *
  518. * @private
  519. * @param {Vector3} eyePoint - The 3D-coordinates of a point.
  520. * @param {HalfEdge} crossEdge - The edge used to jump to the current face.
  521. * @param {Face} face - The current face being tested.
  522. * @param {Array<HalfEdge>} horizon - The edges that form part of the horizon in CCW order.
  523. * @return {ConvexHull} A reference to this convex hull.
  524. */
  525. _computeHorizon( eyePoint, crossEdge, face, horizon ) {
  526. // moves face's vertices to the 'unassigned' vertex list
  527. this._deleteFaceVertices( face );
  528. face.mark = Deleted;
  529. let edge;
  530. if ( crossEdge === null ) {
  531. edge = crossEdge = face.getEdge( 0 );
  532. } else {
  533. // start from the next edge since 'crossEdge' was already analyzed
  534. // (actually 'crossEdge.twin' was the edge who called this method recursively)
  535. edge = crossEdge.next;
  536. }
  537. do {
  538. const twinEdge = edge.twin;
  539. const oppositeFace = twinEdge.face;
  540. if ( oppositeFace.mark === Visible ) {
  541. if ( oppositeFace.distanceToPoint( eyePoint ) > this.tolerance ) {
  542. // the opposite face can see the vertex, so proceed with next edge
  543. this._computeHorizon( eyePoint, twinEdge, oppositeFace, horizon );
  544. } else {
  545. // the opposite face can't see the vertex, so this edge is part of the horizon
  546. horizon.push( edge );
  547. }
  548. }
  549. edge = edge.next;
  550. } while ( edge !== crossEdge );
  551. return this;
  552. }
  553. /**
  554. * Creates a face with the vertices 'eyeVertex.point', 'horizonEdge.tail' and 'horizonEdge.head'
  555. * in CCW order. All the half edges are created in CCW order thus the face is always pointing
  556. * outside the hull.
  557. *
  558. * @private
  559. * @param {VertexNode} eyeVertex - The vertex that is added to the hull.
  560. * @param {HalfEdge} horizonEdge - A single edge of the horizon.
  561. * @return {HalfEdge} The half edge whose vertex is the eyeVertex.
  562. */
  563. _addAdjoiningFace( eyeVertex, horizonEdge ) {
  564. // all the half edges are created in ccw order thus the face is always pointing outside the hull
  565. const face = Face.create( eyeVertex, horizonEdge.tail(), horizonEdge.head() );
  566. this.faces.push( face );
  567. // join face.getEdge( - 1 ) with the horizon's opposite edge face.getEdge( - 1 ) = face.getEdge( 2 )
  568. face.getEdge( - 1 ).setTwin( horizonEdge.twin );
  569. return face.getEdge( 0 ); // the half edge whose vertex is the eyeVertex
  570. }
  571. /**
  572. * Adds 'horizon.length' faces to the hull, each face will be linked with the horizon
  573. * opposite face and the face on the left/right.
  574. *
  575. * @private
  576. * @param {VertexNode} eyeVertex - The vertex that is added to the hull.
  577. * @param {Array<HalfEdge>} horizon - The horizon.
  578. * @return {ConvexHull} A reference to this convex hull.
  579. */
  580. _addNewFaces( eyeVertex, horizon ) {
  581. this.newFaces = [];
  582. let firstSideEdge = null;
  583. let previousSideEdge = null;
  584. for ( let i = 0; i < horizon.length; i ++ ) {
  585. const horizonEdge = horizon[ i ];
  586. // returns the right side edge
  587. const sideEdge = this._addAdjoiningFace( eyeVertex, horizonEdge );
  588. if ( firstSideEdge === null ) {
  589. firstSideEdge = sideEdge;
  590. } else {
  591. // joins face.getEdge( 1 ) with previousFace.getEdge( 0 )
  592. sideEdge.next.setTwin( previousSideEdge );
  593. }
  594. this.newFaces.push( sideEdge.face );
  595. previousSideEdge = sideEdge;
  596. }
  597. // perform final join of new faces
  598. firstSideEdge.next.setTwin( previousSideEdge );
  599. return this;
  600. }
  601. /**
  602. * Adds a vertex to the hull with the following algorithm:
  603. *
  604. * - Compute the 'horizon' which is a chain of half edges. For an edge to belong to this group
  605. * it must be the edge connecting a face that can see 'eyeVertex' and a face which cannot see 'eyeVertex'.
  606. * - All the faces that can see 'eyeVertex' have its visible vertices removed from the assigned vertex list.
  607. * - A new set of faces is created with each edge of the 'horizon' and 'eyeVertex'. Each face is connected
  608. * with the opposite horizon face and the face on the left/right.
  609. * - The vertices removed from all the visible faces are assigned to the new faces if possible.
  610. *
  611. * @private
  612. * @param {VertexNode} eyeVertex - The vertex to add.
  613. * @return {ConvexHull} A reference to this convex hull.
  614. */
  615. _addVertexToHull( eyeVertex ) {
  616. const horizon = [];
  617. this.unassigned.clear();
  618. // remove 'eyeVertex' from 'eyeVertex.face' so that it can't be added to the 'unassigned' vertex list
  619. this._removeVertexFromFace( eyeVertex, eyeVertex.face );
  620. this._computeHorizon( eyeVertex.point, null, eyeVertex.face, horizon );
  621. this._addNewFaces( eyeVertex, horizon );
  622. // reassign 'unassigned' vertices to the new faces
  623. this._resolveUnassignedPoints( this.newFaces );
  624. return this;
  625. }
  626. /**
  627. * Cleans up internal properties after computing the convex hull.
  628. *
  629. * @private
  630. * @return {ConvexHull} A reference to this convex hull.
  631. */
  632. _cleanup() {
  633. this.assigned.clear();
  634. this.unassigned.clear();
  635. this.newFaces = [];
  636. return this;
  637. }
  638. /**
  639. * Starts the execution of the quick hull algorithm.
  640. *
  641. * @private
  642. * @return {ConvexHull} A reference to this convex hull.
  643. */
  644. _compute() {
  645. let vertex;
  646. this._computeInitialHull();
  647. // add all available vertices gradually to the hull
  648. while ( ( vertex = this._nextVertexToAdd() ) !== undefined ) {
  649. this._addVertexToHull( vertex );
  650. }
  651. this._reindexFaces();
  652. this._cleanup();
  653. return this;
  654. }
  655. }
  656. /**
  657. * Represents a section bounded by a specific amount of half-edges.
  658. * The current implementation assumes that a face always consist of three edges.
  659. *
  660. * @private
  661. */
  662. class Face {
  663. /**
  664. * Constructs a new face.
  665. */
  666. constructor() {
  667. /**
  668. * The normal vector of the face.
  669. *
  670. * @private
  671. * @type {Vector3}
  672. */
  673. this.normal = new Vector3();
  674. /**
  675. * The midpoint or centroid of the face.
  676. *
  677. * @private
  678. * @type {Vector3}
  679. */
  680. this.midpoint = new Vector3();
  681. /**
  682. * The area of the face.
  683. *
  684. * @private
  685. * @type {number}
  686. * @default 0
  687. */
  688. this.area = 0;
  689. /**
  690. * Signed distance from face to the origin.
  691. *
  692. * @private
  693. * @type {number}
  694. * @default 0
  695. */
  696. this.constant = 0;
  697. /**
  698. * Reference to a vertex in a vertex list this face can see.
  699. *
  700. * @private
  701. * @type {?VertexNode}
  702. * @default null
  703. */
  704. this.outside = null; // reference to a vertex in a vertex list this face can see
  705. this.mark = Visible;
  706. /**
  707. * Reference to the base edge of a face. To retrieve all edges, you can use the
  708. * `next` reference of the current edge.
  709. *
  710. * @private
  711. * @type {?HalfEdge}
  712. * @default null
  713. */
  714. this.edge = null;
  715. }
  716. /**
  717. * Creates a face from the given vertex nodes.
  718. *
  719. * @private
  720. * @param {VertexNode} a - The first vertex node.
  721. * @param {VertexNode} b - The second vertex node.
  722. * @param {VertexNode} c - The third vertex node.
  723. * @return {Face} The created face.
  724. */
  725. static create( a, b, c ) {
  726. const face = new Face();
  727. const e0 = new HalfEdge( a, face );
  728. const e1 = new HalfEdge( b, face );
  729. const e2 = new HalfEdge( c, face );
  730. // join edges
  731. e0.next = e2.prev = e1;
  732. e1.next = e0.prev = e2;
  733. e2.next = e1.prev = e0;
  734. // main half edge reference
  735. face.edge = e0;
  736. return face.compute();
  737. }
  738. /**
  739. * Returns an edge by the given index.
  740. *
  741. * @private
  742. * @param {number} i - The edge index.
  743. * @return {HalfEdge} The edge.
  744. */
  745. getEdge( i ) {
  746. let edge = this.edge;
  747. while ( i > 0 ) {
  748. edge = edge.next;
  749. i --;
  750. }
  751. while ( i < 0 ) {
  752. edge = edge.prev;
  753. i ++;
  754. }
  755. return edge;
  756. }
  757. /**
  758. * Computes all properties of the face.
  759. *
  760. * @private
  761. * @return {Face} A reference to this face.
  762. */
  763. compute() {
  764. const a = this.edge.tail();
  765. const b = this.edge.head();
  766. const c = this.edge.next.head();
  767. _triangle.set( a.point, b.point, c.point );
  768. _triangle.getNormal( this.normal );
  769. _triangle.getMidpoint( this.midpoint );
  770. this.area = _triangle.getArea();
  771. this.constant = this.normal.dot( this.midpoint );
  772. return this;
  773. }
  774. /**
  775. * Returns the signed distance from a given point to the plane representation of this face.
  776. *
  777. * @private
  778. * @param {Vector3} point - The point to compute the distance to.
  779. * @return {number} The distance.
  780. */
  781. distanceToPoint( point ) {
  782. return this.normal.dot( point ) - this.constant;
  783. }
  784. }
  785. /**
  786. * The basis for a half-edge data structure, also known as doubly
  787. * connected edge list (DCEL).
  788. *
  789. * @private
  790. */
  791. class HalfEdge {
  792. /**
  793. * Constructs a new half edge.
  794. *
  795. * @param {VertexNode} vertex - A reference to its destination vertex.
  796. * @param {Face} face - A reference to its face.
  797. */
  798. constructor( vertex, face ) {
  799. /**
  800. * A reference to its destination vertex.
  801. *
  802. * @private
  803. * @type {VertexNode}
  804. */
  805. this.vertex = vertex;
  806. /**
  807. * Reference to the previous half-edge of the same face.
  808. *
  809. * @private
  810. * @type {?HalfEdge}
  811. * @default null
  812. */
  813. this.prev = null;
  814. /**
  815. * Reference to the next half-edge of the same face.
  816. *
  817. * @private
  818. * @type {?HalfEdge}
  819. * @default null
  820. */
  821. this.next = null;
  822. /**
  823. * Reference to the twin half-edge to reach the opposite face.
  824. *
  825. * @private
  826. * @type {?HalfEdge}
  827. * @default null
  828. */
  829. this.twin = null;
  830. /**
  831. * A reference to its face.
  832. *
  833. * @private
  834. * @type {Face}
  835. */
  836. this.face = face;
  837. }
  838. /**
  839. * Returns the destination vertex.
  840. *
  841. * @private
  842. * @return {VertexNode} The destination vertex.
  843. */
  844. head() {
  845. return this.vertex;
  846. }
  847. /**
  848. * Returns the origin vertex.
  849. *
  850. * @private
  851. * @return {VertexNode} The destination vertex.
  852. */
  853. tail() {
  854. return this.prev ? this.prev.vertex : null;
  855. }
  856. /**
  857. * Returns the Euclidean length (straight-line length) of the edge.
  858. *
  859. * @private
  860. * @return {number} The edge's length.
  861. */
  862. length() {
  863. const head = this.head();
  864. const tail = this.tail();
  865. if ( tail !== null ) {
  866. return tail.point.distanceTo( head.point );
  867. }
  868. return - 1;
  869. }
  870. /**
  871. * Returns the square of the Euclidean length (straight-line length) of the edge.
  872. *
  873. * @private
  874. * @return {number} The square of the edge's length.
  875. */
  876. lengthSquared() {
  877. const head = this.head();
  878. const tail = this.tail();
  879. if ( tail !== null ) {
  880. return tail.point.distanceToSquared( head.point );
  881. }
  882. return - 1;
  883. }
  884. /**
  885. * Sets the twin edge of this half-edge. It also ensures that the twin reference
  886. * of the given half-edge is correctly set.
  887. *
  888. * @private
  889. * @param {HalfEdge} edge - The twin edge to set.
  890. * @return {HalfEdge} A reference to this edge.
  891. */
  892. setTwin( edge ) {
  893. this.twin = edge;
  894. edge.twin = this;
  895. return this;
  896. }
  897. }
  898. /**
  899. * A vertex as a double linked list node.
  900. *
  901. * @private
  902. */
  903. class VertexNode {
  904. /**
  905. * Constructs a new vertex node.
  906. *
  907. * @param {Vector3} point - A point in 3D space.
  908. */
  909. constructor( point ) {
  910. /**
  911. * A point in 3D space.
  912. *
  913. * @private
  914. * @type {Vector3}
  915. */
  916. this.point = point;
  917. /**
  918. * Reference to the previous vertex in the double linked list.
  919. *
  920. * @private
  921. * @type {?VertexNode}
  922. * @default null
  923. */
  924. this.prev = null;
  925. /**
  926. * Reference to the next vertex in the double linked list.
  927. *
  928. * @private
  929. * @type {?VertexNode}
  930. * @default null
  931. */
  932. this.next = null;
  933. /**
  934. * Reference to the face that is able to see this vertex.
  935. *
  936. * @private
  937. * @type {?Face}
  938. * @default null
  939. */
  940. this.face = null;
  941. }
  942. }
  943. /**
  944. * A doubly linked list of vertices.
  945. *
  946. * @private
  947. */
  948. class VertexList {
  949. /**
  950. * Constructs a new vertex list.
  951. */
  952. constructor() {
  953. /**
  954. * Reference to the first vertex of the linked list.
  955. *
  956. * @private
  957. * @type {?VertexNode}
  958. * @default null
  959. */
  960. this.head = null;
  961. /**
  962. * Reference to the last vertex of the linked list.
  963. *
  964. * @private
  965. * @type {?VertexNode}
  966. * @default null
  967. */
  968. this.tail = null;
  969. }
  970. /**
  971. * Returns the head reference.
  972. *
  973. * @private
  974. * @return {VertexNode} The head reference.
  975. */
  976. first() {
  977. return this.head;
  978. }
  979. /**
  980. * Returns the tail reference.
  981. *
  982. * @private
  983. * @return {VertexNode} The tail reference.
  984. */
  985. last() {
  986. return this.tail;
  987. }
  988. /**
  989. * Clears the linked list.
  990. *
  991. * @private
  992. * @return {VertexList} A reference to this vertex list.
  993. */
  994. clear() {
  995. this.head = this.tail = null;
  996. return this;
  997. }
  998. /**
  999. * Inserts a vertex before a target vertex.
  1000. *
  1001. * @private
  1002. * @param {VertexNode} target - The target.
  1003. * @param {VertexNode} vertex - The vertex to insert.
  1004. * @return {VertexList} A reference to this vertex list.
  1005. */
  1006. insertBefore( target, vertex ) {
  1007. vertex.prev = target.prev;
  1008. vertex.next = target;
  1009. if ( vertex.prev === null ) {
  1010. this.head = vertex;
  1011. } else {
  1012. vertex.prev.next = vertex;
  1013. }
  1014. target.prev = vertex;
  1015. return this;
  1016. }
  1017. /**
  1018. * Inserts a vertex after a target vertex.
  1019. *
  1020. * @private
  1021. * @param {VertexNode} target - The target.
  1022. * @param {VertexNode} vertex - The vertex to insert.
  1023. * @return {VertexList} A reference to this vertex list.
  1024. */
  1025. insertAfter( target, vertex ) {
  1026. vertex.prev = target;
  1027. vertex.next = target.next;
  1028. if ( vertex.next === null ) {
  1029. this.tail = vertex;
  1030. } else {
  1031. vertex.next.prev = vertex;
  1032. }
  1033. target.next = vertex;
  1034. return this;
  1035. }
  1036. /**
  1037. * Appends a vertex to this vertex list.
  1038. *
  1039. * @private
  1040. * @param {VertexNode} vertex - The vertex to append.
  1041. * @return {VertexList} A reference to this vertex list.
  1042. */
  1043. append( vertex ) {
  1044. if ( this.head === null ) {
  1045. this.head = vertex;
  1046. } else {
  1047. this.tail.next = vertex;
  1048. }
  1049. vertex.prev = this.tail;
  1050. vertex.next = null; // the tail has no subsequent vertex
  1051. this.tail = vertex;
  1052. return this;
  1053. }
  1054. /**
  1055. * Appends a chain of vertices where the given vertex is the head.
  1056. *
  1057. * @private
  1058. * @param {VertexNode} vertex - The head vertex of a chain of vertices.
  1059. * @return {VertexList} A reference to this vertex list.
  1060. */
  1061. appendChain( vertex ) {
  1062. if ( this.head === null ) {
  1063. this.head = vertex;
  1064. } else {
  1065. this.tail.next = vertex;
  1066. }
  1067. vertex.prev = this.tail;
  1068. // ensure that the 'tail' reference points to the last vertex of the chain
  1069. while ( vertex.next !== null ) {
  1070. vertex = vertex.next;
  1071. }
  1072. this.tail = vertex;
  1073. return this;
  1074. }
  1075. /**
  1076. * Removes a vertex from the linked list.
  1077. *
  1078. * @private
  1079. * @param {VertexNode} vertex - The vertex to remove.
  1080. * @return {VertexList} A reference to this vertex list.
  1081. */
  1082. remove( vertex ) {
  1083. if ( vertex.prev === null ) {
  1084. this.head = vertex.next;
  1085. } else {
  1086. vertex.prev.next = vertex.next;
  1087. }
  1088. if ( vertex.next === null ) {
  1089. this.tail = vertex.prev;
  1090. } else {
  1091. vertex.next.prev = vertex.prev;
  1092. }
  1093. return this;
  1094. }
  1095. /**
  1096. * Removes a sublist of vertices from the linked list.
  1097. *
  1098. * @private
  1099. * @param {VertexNode} a - The head of the sublist.
  1100. * @param {VertexNode} b - The tail of the sublist.
  1101. * @return {VertexList} A reference to this vertex list.
  1102. */
  1103. removeSubList( a, b ) {
  1104. if ( a.prev === null ) {
  1105. this.head = b.next;
  1106. } else {
  1107. a.prev.next = b.next;
  1108. }
  1109. if ( b.next === null ) {
  1110. this.tail = a.prev;
  1111. } else {
  1112. b.next.prev = a.prev;
  1113. }
  1114. return this;
  1115. }
  1116. /**
  1117. * Returns `true` if the linked list is empty.
  1118. *
  1119. * @private
  1120. * @return {boolean} Whether the linked list is empty or not.
  1121. */
  1122. isEmpty() {
  1123. return this.head === null;
  1124. }
  1125. }
  1126. export { ConvexHull, Face, HalfEdge, VertexNode, VertexList };