Octree.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  1. import {
  2. Box3,
  3. Line3,
  4. Plane,
  5. Sphere,
  6. Triangle,
  7. Vector3,
  8. Layers
  9. } from 'three';
  10. import { Capsule } from '../math/Capsule.js';
  11. const _v1 = new Vector3();
  12. const _v2 = new Vector3();
  13. const _point1 = new Vector3();
  14. const _point2 = new Vector3();
  15. const _plane = new Plane();
  16. const _line1 = new Line3();
  17. const _line2 = new Line3();
  18. const _sphere = new Sphere();
  19. const _capsule = new Capsule();
  20. const _temp1 = new Vector3();
  21. const _temp2 = new Vector3();
  22. const _temp3 = new Vector3();
  23. const EPS = 1e-10;
  24. function lineToLineClosestPoints( line1, line2, target1 = null, target2 = null ) {
  25. const r = _temp1.copy( line1.end ).sub( line1.start );
  26. const s = _temp2.copy( line2.end ).sub( line2.start );
  27. const w = _temp3.copy( line2.start ).sub( line1.start );
  28. const a = r.dot( s ),
  29. b = r.dot( r ),
  30. c = s.dot( s ),
  31. d = s.dot( w ),
  32. e = r.dot( w );
  33. let t1, t2;
  34. const divisor = b * c - a * a;
  35. if ( Math.abs( divisor ) < EPS ) {
  36. const d1 = - d / c;
  37. const d2 = ( a - d ) / c;
  38. if ( Math.abs( d1 - 0.5 ) < Math.abs( d2 - 0.5 ) ) {
  39. t1 = 0;
  40. t2 = d1;
  41. } else {
  42. t1 = 1;
  43. t2 = d2;
  44. }
  45. } else {
  46. t1 = ( d * a + e * c ) / divisor;
  47. t2 = ( t1 * a - d ) / c;
  48. }
  49. t2 = Math.max( 0, Math.min( 1, t2 ) );
  50. t1 = Math.max( 0, Math.min( 1, t1 ) );
  51. if ( target1 ) {
  52. target1.copy( r ).multiplyScalar( t1 ).add( line1.start );
  53. }
  54. if ( target2 ) {
  55. target2.copy( s ).multiplyScalar( t2 ).add( line2.start );
  56. }
  57. }
  58. /**
  59. * An octree is a hierarchical tree data structure used to partition a three-dimensional
  60. * space by recursively subdividing it into eight octants.
  61. *
  62. * This particular implementation can have up to sixteen levels and stores up to eight triangles
  63. * in leaf nodes.
  64. *
  65. * `Octree` can be used in games to compute collision between the game world and colliders from
  66. * the player or other dynamic 3D objects.
  67. *
  68. *
  69. * ```js
  70. * const octree = new Octree().fromGraphNode( scene );
  71. * const result = octree.capsuleIntersect( playerCollider ); // collision detection
  72. * ```
  73. *
  74. * @three_import import { Octree } from 'three/addons/math/Octree.js';
  75. */
  76. class Octree {
  77. /**
  78. * Constructs a new Octree.
  79. *
  80. * @param {Box3} [box] - The base box with enclose the entire Octree.
  81. */
  82. constructor( box ) {
  83. /**
  84. * The base box with enclose the entire Octree.
  85. *
  86. * @type {Box3}
  87. */
  88. this.box = box;
  89. /**
  90. * The bounds of the Octree. Compared to {@link Octree#box}, no
  91. * margin is applied.
  92. *
  93. * @type {Box3}
  94. */
  95. this.bounds = new Box3();
  96. /**
  97. * Can by used for layers configuration for refine testing.
  98. *
  99. * @type {Layers}
  100. */
  101. this.layers = new Layers();
  102. /**
  103. * The number of triangles a leaf can store before it is split.
  104. *
  105. * @type {number}
  106. * @default 8
  107. */
  108. this.trianglesPerLeaf = 8;
  109. /**
  110. * The maximum level of the Octree. It defines the maximum
  111. * hierarchical depth of the data structure.
  112. *
  113. * @type {number}
  114. * @default 16
  115. */
  116. this.maxLevel = 16;
  117. // private
  118. this.subTrees = [];
  119. this.triangles = [];
  120. }
  121. /**
  122. * Adds the given triangle to the Octree. The triangle vertices are clamped if they exceed
  123. * the bounds of the Octree.
  124. *
  125. * @param {Triangle} triangle - The triangle to add.
  126. * @return {Octree} A reference to this Octree.
  127. */
  128. addTriangle( triangle ) {
  129. this.bounds.min.x = Math.min( this.bounds.min.x, triangle.a.x, triangle.b.x, triangle.c.x );
  130. this.bounds.min.y = Math.min( this.bounds.min.y, triangle.a.y, triangle.b.y, triangle.c.y );
  131. this.bounds.min.z = Math.min( this.bounds.min.z, triangle.a.z, triangle.b.z, triangle.c.z );
  132. this.bounds.max.x = Math.max( this.bounds.max.x, triangle.a.x, triangle.b.x, triangle.c.x );
  133. this.bounds.max.y = Math.max( this.bounds.max.y, triangle.a.y, triangle.b.y, triangle.c.y );
  134. this.bounds.max.z = Math.max( this.bounds.max.z, triangle.a.z, triangle.b.z, triangle.c.z );
  135. this.triangles.push( triangle );
  136. return this;
  137. }
  138. /**
  139. * Prepares {@link Octree#box} for the build.
  140. *
  141. * @return {Octree} A reference to this Octree.
  142. */
  143. calcBox() {
  144. this.box = this.bounds.clone();
  145. // offset small amount to account for regular grid
  146. this.box.min.x -= 0.01;
  147. this.box.min.y -= 0.01;
  148. this.box.min.z -= 0.01;
  149. return this;
  150. }
  151. /**
  152. * Splits the Octree. This method is used recursively when
  153. * building the Octree.
  154. *
  155. * @param {number} level - The current level.
  156. * @return {Octree} A reference to this Octree.
  157. */
  158. split( level ) {
  159. if ( ! this.box ) return;
  160. const subTrees = [];
  161. const halfsize = _v2.copy( this.box.max ).sub( this.box.min ).multiplyScalar( 0.5 );
  162. for ( let x = 0; x < 2; x ++ ) {
  163. for ( let y = 0; y < 2; y ++ ) {
  164. for ( let z = 0; z < 2; z ++ ) {
  165. const box = new Box3();
  166. const v = _v1.set( x, y, z );
  167. box.min.copy( this.box.min ).add( v.multiply( halfsize ) );
  168. box.max.copy( box.min ).add( halfsize );
  169. subTrees.push( new Octree( box ) );
  170. }
  171. }
  172. }
  173. let triangle;
  174. while ( triangle = this.triangles.pop() ) {
  175. for ( let i = 0; i < subTrees.length; i ++ ) {
  176. if ( subTrees[ i ].box.intersectsTriangle( triangle ) ) {
  177. subTrees[ i ].triangles.push( triangle );
  178. }
  179. }
  180. }
  181. for ( let i = 0; i < subTrees.length; i ++ ) {
  182. const len = subTrees[ i ].triangles.length;
  183. if ( len > this.trianglesPerLeaf && level < this.maxLevel ) {
  184. subTrees[ i ].split( level + 1 );
  185. }
  186. if ( len !== 0 ) {
  187. this.subTrees.push( subTrees[ i ] );
  188. }
  189. }
  190. return this;
  191. }
  192. /**
  193. * Builds the Octree.
  194. *
  195. * @return {Octree} A reference to this Octree.
  196. */
  197. build() {
  198. this.calcBox();
  199. this.split( 0 );
  200. return this;
  201. }
  202. /**
  203. * Computes the triangles that potentially intersect with the given ray.
  204. *
  205. * @param {Ray} ray - The ray to test.
  206. * @param {Array<Triangle>} triangles - The target array that holds the triangles.
  207. */
  208. getRayTriangles( ray, triangles ) {
  209. for ( let i = 0; i < this.subTrees.length; i ++ ) {
  210. const subTree = this.subTrees[ i ];
  211. if ( ! ray.intersectsBox( subTree.box ) ) continue;
  212. if ( subTree.triangles.length > 0 ) {
  213. for ( let j = 0; j < subTree.triangles.length; j ++ ) {
  214. if ( triangles.indexOf( subTree.triangles[ j ] ) === - 1 ) triangles.push( subTree.triangles[ j ] );
  215. }
  216. } else {
  217. subTree.getRayTriangles( ray, triangles );
  218. }
  219. }
  220. }
  221. /**
  222. * Computes the intersection between the given capsule and triangle.
  223. *
  224. * @param {Capsule} capsule - The capsule to test.
  225. * @param {Triangle} triangle - The triangle to test.
  226. * @return {Object|false} The intersection object. If no intersection
  227. * is detected, the method returns `false`.
  228. */
  229. triangleCapsuleIntersect( capsule, triangle ) {
  230. triangle.getPlane( _plane );
  231. const d1 = _plane.distanceToPoint( capsule.start ) - capsule.radius;
  232. const d2 = _plane.distanceToPoint( capsule.end ) - capsule.radius;
  233. if ( ( d1 > 0 && d2 > 0 ) || ( d1 < - capsule.radius && d2 < - capsule.radius ) ) {
  234. return false;
  235. }
  236. const delta = Math.abs( d1 / ( Math.abs( d1 ) + Math.abs( d2 ) ) );
  237. const intersectPoint = _v1.copy( capsule.start ).lerp( capsule.end, delta );
  238. if ( triangle.containsPoint( intersectPoint ) ) {
  239. return { normal: _plane.normal.clone(), point: intersectPoint.clone(), depth: Math.abs( Math.min( d1, d2 ) ) };
  240. }
  241. const r2 = capsule.radius * capsule.radius;
  242. const line1 = _line1.set( capsule.start, capsule.end );
  243. const lines = [
  244. [ triangle.a, triangle.b ],
  245. [ triangle.b, triangle.c ],
  246. [ triangle.c, triangle.a ]
  247. ];
  248. for ( let i = 0; i < lines.length; i ++ ) {
  249. const line2 = _line2.set( lines[ i ][ 0 ], lines[ i ][ 1 ] );
  250. lineToLineClosestPoints( line1, line2, _point1, _point2 );
  251. if ( _point1.distanceToSquared( _point2 ) < r2 ) {
  252. return {
  253. normal: _point1.clone().sub( _point2 ).normalize(),
  254. point: _point2.clone(),
  255. depth: capsule.radius - _point1.distanceTo( _point2 )
  256. };
  257. }
  258. }
  259. return false;
  260. }
  261. /**
  262. * Computes the intersection between the given sphere and triangle.
  263. *
  264. * @param {Sphere} sphere - The sphere to test.
  265. * @param {Triangle} triangle - The triangle to test.
  266. * @return {Object|false} The intersection object. If no intersection
  267. * is detected, the method returns `false`.
  268. */
  269. triangleSphereIntersect( sphere, triangle ) {
  270. triangle.getPlane( _plane );
  271. if ( ! sphere.intersectsPlane( _plane ) ) return false;
  272. const depth = Math.abs( _plane.distanceToSphere( sphere ) );
  273. const r2 = sphere.radius * sphere.radius - depth * depth;
  274. const plainPoint = _plane.projectPoint( sphere.center, _v1 );
  275. if ( triangle.containsPoint( sphere.center ) ) {
  276. return { normal: _plane.normal.clone(), point: plainPoint.clone(), depth: Math.abs( _plane.distanceToSphere( sphere ) ) };
  277. }
  278. const lines = [
  279. [ triangle.a, triangle.b ],
  280. [ triangle.b, triangle.c ],
  281. [ triangle.c, triangle.a ]
  282. ];
  283. for ( let i = 0; i < lines.length; i ++ ) {
  284. _line1.set( lines[ i ][ 0 ], lines[ i ][ 1 ] );
  285. _line1.closestPointToPoint( plainPoint, true, _v2 );
  286. const d = _v2.distanceToSquared( sphere.center );
  287. if ( d < r2 ) {
  288. return { normal: sphere.center.clone().sub( _v2 ).normalize(), point: _v2.clone(), depth: sphere.radius - Math.sqrt( d ) };
  289. }
  290. }
  291. return false;
  292. }
  293. /**
  294. * Computes the triangles that potentially intersect with the given bounding sphere.
  295. *
  296. * @param {Sphere} sphere - The sphere to test.
  297. * @param {Array<Triangle>} triangles - The target array that holds the triangles.
  298. */
  299. getSphereTriangles( sphere, triangles ) {
  300. for ( let i = 0; i < this.subTrees.length; i ++ ) {
  301. const subTree = this.subTrees[ i ];
  302. if ( ! sphere.intersectsBox( subTree.box ) ) continue;
  303. if ( subTree.triangles.length > 0 ) {
  304. for ( let j = 0; j < subTree.triangles.length; j ++ ) {
  305. if ( triangles.indexOf( subTree.triangles[ j ] ) === - 1 ) triangles.push( subTree.triangles[ j ] );
  306. }
  307. } else {
  308. subTree.getSphereTriangles( sphere, triangles );
  309. }
  310. }
  311. }
  312. /**
  313. * Computes the triangles that potentially intersect with the given capsule.
  314. *
  315. * @param {Capsule} capsule - The capsule to test.
  316. * @param {Array<Triangle>} triangles - The target array that holds the triangles.
  317. */
  318. getCapsuleTriangles( capsule, triangles ) {
  319. for ( let i = 0; i < this.subTrees.length; i ++ ) {
  320. const subTree = this.subTrees[ i ];
  321. if ( ! capsule.intersectsBox( subTree.box ) ) continue;
  322. if ( subTree.triangles.length > 0 ) {
  323. for ( let j = 0; j < subTree.triangles.length; j ++ ) {
  324. if ( triangles.indexOf( subTree.triangles[ j ] ) === - 1 ) triangles.push( subTree.triangles[ j ] );
  325. }
  326. } else {
  327. subTree.getCapsuleTriangles( capsule, triangles );
  328. }
  329. }
  330. }
  331. /**
  332. * Performs a bounding sphere intersection test with this Octree.
  333. *
  334. * @param {Sphere} sphere - The bounding sphere to test.
  335. * @return {Object|boolean} The intersection object. If no intersection
  336. * is detected, the method returns `false`.
  337. */
  338. sphereIntersect( sphere ) {
  339. _sphere.copy( sphere );
  340. const triangles = [];
  341. let result, hit = false;
  342. this.getSphereTriangles( sphere, triangles );
  343. for ( let i = 0; i < triangles.length; i ++ ) {
  344. if ( result = this.triangleSphereIntersect( _sphere, triangles[ i ] ) ) {
  345. hit = true;
  346. _sphere.center.add( result.normal.multiplyScalar( result.depth ) );
  347. }
  348. }
  349. if ( hit ) {
  350. const collisionVector = _sphere.center.clone().sub( sphere.center );
  351. const depth = collisionVector.length();
  352. return { normal: collisionVector.normalize(), depth: depth };
  353. }
  354. return false;
  355. }
  356. /**
  357. * Performs a capsule intersection test with this Octree.
  358. *
  359. * @param {Capsule} capsule - The capsule to test.
  360. * @return {Object|boolean} The intersection object. If no intersection
  361. * is detected, the method returns `false`.
  362. */
  363. capsuleIntersect( capsule ) {
  364. _capsule.copy( capsule );
  365. const triangles = [];
  366. let result, hit = false;
  367. this.getCapsuleTriangles( _capsule, triangles );
  368. for ( let i = 0; i < triangles.length; i ++ ) {
  369. if ( result = this.triangleCapsuleIntersect( _capsule, triangles[ i ] ) ) {
  370. hit = true;
  371. _capsule.translate( result.normal.multiplyScalar( result.depth ) );
  372. }
  373. }
  374. if ( hit ) {
  375. const collisionVector = _capsule.getCenter( new Vector3() ).sub( capsule.getCenter( _v1 ) );
  376. const depth = collisionVector.length();
  377. return { normal: collisionVector.normalize(), depth: depth };
  378. }
  379. return false;
  380. }
  381. /**
  382. * Performs a ray intersection test with this Octree.
  383. *
  384. * @param {Ray} ray - The ray to test.
  385. * @return {Object|boolean} The nearest intersection object. If no intersection
  386. * is detected, the method returns `false`.
  387. */
  388. rayIntersect( ray ) {
  389. const triangles = [];
  390. let triangle, position, distance = 1e100;
  391. this.getRayTriangles( ray, triangles );
  392. for ( let i = 0; i < triangles.length; i ++ ) {
  393. const result = ray.intersectTriangle( triangles[ i ].a, triangles[ i ].b, triangles[ i ].c, true, _v1 );
  394. if ( result ) {
  395. const newdistance = result.sub( ray.origin ).length();
  396. if ( distance > newdistance ) {
  397. position = result.clone().add( ray.origin );
  398. distance = newdistance;
  399. triangle = triangles[ i ];
  400. }
  401. }
  402. }
  403. return distance < 1e100 ? { distance: distance, triangle: triangle, position: position } : false;
  404. }
  405. /**
  406. * Constructs the Octree from the given 3D object.
  407. *
  408. * @param {Object3D} group - The scene graph node.
  409. * @return {Octree} A reference to this Octree.
  410. */
  411. fromGraphNode( group ) {
  412. group.updateWorldMatrix( true, true );
  413. group.traverse( ( obj ) => {
  414. if ( obj.isMesh === true ) {
  415. if ( this.layers.test( obj.layers ) ) {
  416. let geometry, isTemp = false;
  417. if ( obj.geometry.index !== null ) {
  418. isTemp = true;
  419. geometry = obj.geometry.toNonIndexed();
  420. } else {
  421. geometry = obj.geometry;
  422. }
  423. const positionAttribute = geometry.getAttribute( 'position' );
  424. for ( let i = 0; i < positionAttribute.count; i += 3 ) {
  425. const v1 = new Vector3().fromBufferAttribute( positionAttribute, i );
  426. const v2 = new Vector3().fromBufferAttribute( positionAttribute, i + 1 );
  427. const v3 = new Vector3().fromBufferAttribute( positionAttribute, i + 2 );
  428. v1.applyMatrix4( obj.matrixWorld );
  429. v2.applyMatrix4( obj.matrixWorld );
  430. v3.applyMatrix4( obj.matrixWorld );
  431. this.addTriangle( new Triangle( v1, v2, v3 ) );
  432. }
  433. if ( isTemp ) {
  434. geometry.dispose();
  435. }
  436. }
  437. }
  438. } );
  439. this.build();
  440. return this;
  441. }
  442. /**
  443. * Clears the Octree by making it empty.
  444. *
  445. * @return {Octree} A reference to this Octree.
  446. */
  447. clear() {
  448. this.box = null;
  449. this.bounds.makeEmpty();
  450. this.subTrees.length = 0;
  451. this.triangles.length = 0;
  452. return this;
  453. }
  454. }
  455. export { Octree };