Octree.js 18 KB

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