Octree.js 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139
  1. /*!
  2. *
  3. * threeoctree.js (r59) / https://github.com/collinhover/threeoctree
  4. * (sparse) dynamic 3D spatial representation structure for fast searches.
  5. *
  6. * @author Collin Hover / http://collinhover.com/
  7. * based on Dynamic Octree by Piko3D @ http://www.piko3d.com/ and Octree by Marek Pawlowski @ pawlowski.it
  8. *
  9. */
  10. ( function ( THREE ) { "use strict";
  11. /*===================================================
  12. utility
  13. =====================================================*/
  14. function isNumber ( n ) {
  15. return !isNaN( n ) && isFinite( n );
  16. }
  17. function isArray ( target ) {
  18. return Object.prototype.toString.call( target ) === '[object Array]';
  19. }
  20. function toArray ( target ) {
  21. return target ? ( isArray ( target ) !== true ? [ target ] : target ) : [];
  22. }
  23. function indexOfValue( array, value ) {
  24. for ( var i = 0, il = array.length; i < il; i++ ) {
  25. if ( array[ i ] === value ) {
  26. return i;
  27. }
  28. }
  29. return -1;
  30. }
  31. function indexOfPropertyWithValue( array, property, value ) {
  32. for ( var i = 0, il = array.length; i < il; i++ ) {
  33. if ( array[ i ][ property ] === value ) {
  34. return i;
  35. }
  36. }
  37. return -1;
  38. }
  39. /*===================================================
  40. octree
  41. =====================================================*/
  42. THREE.Octree = function ( parameters ) {
  43. // handle parameters
  44. parameters = parameters || {};
  45. parameters.tree = this;
  46. // static properties ( modification is not recommended )
  47. this.nodeCount = 0;
  48. this.INDEX_INSIDE_CROSS = -1;
  49. this.INDEX_OUTSIDE_OFFSET = 2;
  50. this.INDEX_OUTSIDE_POS_X = isNumber( parameters.INDEX_OUTSIDE_POS_X ) ? parameters.INDEX_OUTSIDE_POS_X : 0;
  51. this.INDEX_OUTSIDE_NEG_X = isNumber( parameters.INDEX_OUTSIDE_NEG_X ) ? parameters.INDEX_OUTSIDE_NEG_X : 1;
  52. this.INDEX_OUTSIDE_POS_Y = isNumber( parameters.INDEX_OUTSIDE_POS_Y ) ? parameters.INDEX_OUTSIDE_POS_Y : 2;
  53. this.INDEX_OUTSIDE_NEG_Y = isNumber( parameters.INDEX_OUTSIDE_NEG_Y ) ? parameters.INDEX_OUTSIDE_NEG_Y : 3;
  54. this.INDEX_OUTSIDE_POS_Z = isNumber( parameters.INDEX_OUTSIDE_POS_Z ) ? parameters.INDEX_OUTSIDE_POS_Z : 4;
  55. this.INDEX_OUTSIDE_NEG_Z = isNumber( parameters.INDEX_OUTSIDE_NEG_Z ) ? parameters.INDEX_OUTSIDE_NEG_Z : 5;
  56. this.INDEX_OUTSIDE_MAP = [];
  57. this.INDEX_OUTSIDE_MAP[ this.INDEX_OUTSIDE_POS_X ] = { index: this.INDEX_OUTSIDE_POS_X, count: 0, x: 1, y: 0, z: 0 };
  58. this.INDEX_OUTSIDE_MAP[ this.INDEX_OUTSIDE_NEG_X ] = { index: this.INDEX_OUTSIDE_NEG_X, count: 0, x: -1, y: 0, z: 0 };
  59. this.INDEX_OUTSIDE_MAP[ this.INDEX_OUTSIDE_POS_Y ] = { index: this.INDEX_OUTSIDE_POS_Y, count: 0, x: 0, y: 1, z: 0 };
  60. this.INDEX_OUTSIDE_MAP[ this.INDEX_OUTSIDE_NEG_Y ] = { index: this.INDEX_OUTSIDE_NEG_Y, count: 0, x: 0, y: -1, z: 0 };
  61. this.INDEX_OUTSIDE_MAP[ this.INDEX_OUTSIDE_POS_Z ] = { index: this.INDEX_OUTSIDE_POS_Z, count: 0, x: 0, y: 0, z: 1 };
  62. this.INDEX_OUTSIDE_MAP[ this.INDEX_OUTSIDE_NEG_Z ] = { index: this.INDEX_OUTSIDE_NEG_Z, count: 0, x: 0, y: 0, z: -1 };
  63. this.FLAG_POS_X = 1 << ( this.INDEX_OUTSIDE_POS_X + 1 );
  64. this.FLAG_NEG_X = 1 << ( this.INDEX_OUTSIDE_NEG_X + 1 );
  65. this.FLAG_POS_Y = 1 << ( this.INDEX_OUTSIDE_POS_Y + 1 );
  66. this.FLAG_NEG_Y = 1 << ( this.INDEX_OUTSIDE_NEG_Y + 1 );
  67. this.FLAG_POS_Z = 1 << ( this.INDEX_OUTSIDE_POS_Z + 1 );
  68. this.FLAG_NEG_Z = 1 << ( this.INDEX_OUTSIDE_NEG_Z + 1 );
  69. this.utilVec31Search = new THREE.Vector3();
  70. this.utilVec32Search = new THREE.Vector3();
  71. // pass scene to see octree structure
  72. this.scene = parameters.scene;
  73. if ( this.scene ) {
  74. this.visualGeometry = new THREE.CubeGeometry( 1, 1, 1 );
  75. this.visualMaterial = new THREE.MeshBasicMaterial( { color: 0xFF0066, wireframe: true, wireframeLinewidth: 1 } );
  76. }
  77. // properties
  78. this.objects = [];
  79. this.objectsMap = {};
  80. this.objectsData = [];
  81. this.objectsDeferred = [];
  82. this.depthMax = isNumber( parameters.depthMax ) ? parameters.depthMax : Infinity;
  83. this.objectsThreshold = isNumber( parameters.objectsThreshold ) ? parameters.objectsThreshold : 8;
  84. this.overlapPct = isNumber( parameters.overlapPct ) ? parameters.overlapPct : 0.15;
  85. this.undeferred = parameters.undeferred || false;
  86. this.root = parameters.root instanceof THREE.OctreeNode ? parameters.root : new THREE.OctreeNode( parameters );
  87. };
  88. THREE.Octree.prototype = {
  89. update: function () {
  90. // add any deferred objects that were waiting for render cycle
  91. if ( this.objectsDeferred.length > 0 ) {
  92. for ( var i = 0, il = this.objectsDeferred.length; i < il; i++ ) {
  93. var deferred = this.objectsDeferred[ i ];
  94. this.addDeferred( deferred.object, deferred.options );
  95. }
  96. this.objectsDeferred.length = 0;
  97. }
  98. },
  99. add: function ( object, options ) {
  100. // add immediately
  101. if ( this.undeferred ) {
  102. this.updateObject( object );
  103. this.addDeferred( object, options );
  104. } else {
  105. // defer add until update called
  106. this.objectsDeferred.push( { object: object, options: options } );
  107. }
  108. },
  109. addDeferred: function ( object, options ) {
  110. var i, l,
  111. geometry,
  112. faces,
  113. useFaces,
  114. vertices,
  115. useVertices,
  116. objectData;
  117. // ensure object is not object data
  118. if ( object instanceof THREE.OctreeObjectData ) {
  119. object = object.object;
  120. }
  121. // check uuid to avoid duplicates
  122. if ( !object.uuid ) {
  123. object.uuid = THREE.Math.generateUUID();
  124. }
  125. if ( !this.objectsMap[ object.uuid ] ) {
  126. // store
  127. this.objects.push( object );
  128. this.objectsMap[ object.uuid ] = object;
  129. // check options
  130. if ( options ) {
  131. useFaces = options.useFaces;
  132. useVertices = options.useVertices;
  133. }
  134. if ( useVertices === true ) {
  135. geometry = object.geometry;
  136. vertices = geometry.vertices;
  137. for ( i = 0, l = vertices.length; i < l; i++ ) {
  138. this.addObjectData( object, vertices[ i ] );
  139. }
  140. } else if ( useFaces === true ) {
  141. geometry = object.geometry;
  142. faces = geometry.faces;
  143. for ( i = 0, l = faces.length; i < l; i++ ) {
  144. this.addObjectData( object, faces[ i ] );
  145. }
  146. } else {
  147. this.addObjectData( object );
  148. }
  149. }
  150. },
  151. addObjectData: function ( object, part ) {
  152. var objectData = new THREE.OctreeObjectData( object, part );
  153. // add to tree objects data list
  154. this.objectsData.push( objectData );
  155. // add to nodes
  156. this.root.addObject( objectData );
  157. },
  158. remove: function ( object ) {
  159. var i, l,
  160. objectData = object,
  161. index,
  162. objectsDataRemoved;
  163. // ensure object is not object data for index search
  164. if ( object instanceof THREE.OctreeObjectData ) {
  165. object = object.object;
  166. }
  167. // check uuid
  168. if ( this.objectsMap[ object.uuid ] ) {
  169. this.objectsMap[ object.uuid ] = undefined;
  170. // check and remove from objects, nodes, and data lists
  171. index = indexOfValue( this.objects, object );
  172. if ( index !== -1 ) {
  173. this.objects.splice( index, 1 );
  174. // remove from nodes
  175. objectsDataRemoved = this.root.removeObject( objectData );
  176. // remove from objects data list
  177. for ( i = 0, l = objectsDataRemoved.length; i < l; i++ ) {
  178. objectData = objectsDataRemoved[ i ];
  179. index = indexOfValue( this.objectsData, objectData );
  180. if ( index !== -1 ) {
  181. this.objectsData.splice( index, 1 );
  182. }
  183. }
  184. }
  185. } else if ( this.objectsDeferred.length > 0 ) {
  186. // check and remove from deferred
  187. index = indexOfPropertyWithValue( this.objectsDeferred, 'object', object );
  188. if ( index !== -1 ) {
  189. this.objectsDeferred.splice( index, 1 );
  190. }
  191. }
  192. },
  193. extend: function ( octree ) {
  194. var i, l,
  195. objectsData,
  196. objectData;
  197. if ( octree instanceof THREE.Octree ) {
  198. // for each object data
  199. objectsData = octree.objectsData;
  200. for ( i = 0, l = objectsData.length; i < l; i++ ) {
  201. objectData = objectsData[ i ];
  202. this.add( objectData, { useFaces: objectData.faces, useVertices: objectData.vertices } );
  203. }
  204. }
  205. },
  206. rebuild: function () {
  207. var i, l,
  208. node,
  209. object,
  210. objectData,
  211. indexOctant,
  212. indexOctantLast,
  213. objectsUpdate = [];
  214. // check all object data for changes in position
  215. // assumes all object matrices are up to date
  216. for ( i = 0, l = this.objectsData.length; i < l; i++ ) {
  217. objectData = this.objectsData[ i ];
  218. node = objectData.node;
  219. // update object
  220. objectData.update();
  221. // if position has changed since last organization of object in tree
  222. if ( node instanceof THREE.OctreeNode && !objectData.positionLast.equals( objectData.position ) ) {
  223. // get octant index of object within current node
  224. indexOctantLast = objectData.indexOctant;
  225. indexOctant = node.getOctantIndex( objectData );
  226. // if object octant index has changed
  227. if ( indexOctant !== indexOctantLast ) {
  228. // add to update list
  229. objectsUpdate.push( objectData );
  230. }
  231. }
  232. }
  233. // update changed objects
  234. for ( i = 0, l = objectsUpdate.length; i < l; i++ ) {
  235. objectData = objectsUpdate[ i ];
  236. // remove object from current node
  237. objectData.node.removeObject( objectData );
  238. // add object to tree root
  239. this.root.addObject( objectData );
  240. }
  241. },
  242. updateObject: function ( object ) {
  243. var i, l,
  244. parentCascade = [ object ],
  245. parent,
  246. parentUpdate;
  247. // search all parents between object and root for world matrix update
  248. parent = object.parent;
  249. while( parent ) {
  250. parentCascade.push( parent );
  251. parent = parent.parent;
  252. }
  253. for ( i = 0, l = parentCascade.length; i < l; i++ ) {
  254. parent = parentCascade[ i ];
  255. if ( parent.matrixWorldNeedsUpdate === true ) {
  256. parentUpdate = parent;
  257. }
  258. }
  259. // update world matrix starting at uppermost parent that needs update
  260. if ( typeof parentUpdate !== 'undefined' ) {
  261. parentUpdate.updateMatrixWorld();
  262. }
  263. },
  264. search: function ( position, radius, organizeByObject, direction ) {
  265. var i, l,
  266. node,
  267. objects,
  268. objectData,
  269. object,
  270. results,
  271. resultData,
  272. resultsObjectsIndices,
  273. resultObjectIndex,
  274. directionPct;
  275. // add root objects
  276. objects = [].concat( this.root.objects );
  277. // ensure radius (i.e. distance of ray) is a number
  278. if ( !( radius > 0 ) ) {
  279. radius = Number.MAX_VALUE;
  280. }
  281. // if direction passed, normalize and find pct
  282. if ( direction instanceof THREE.Vector3 ) {
  283. direction = this.utilVec31Search.copy( direction ).normalize();
  284. directionPct = this.utilVec32Search.set( 1, 1, 1 ).divide( direction );
  285. }
  286. // search each node of root
  287. for ( i = 0, l = this.root.nodesIndices.length; i < l; i++ ) {
  288. node = this.root.nodesByIndex[ this.root.nodesIndices[ i ] ];
  289. objects = node.search( position, radius, objects, direction, directionPct );
  290. }
  291. // if should organize results by object
  292. if ( organizeByObject === true ) {
  293. results = [];
  294. resultsObjectsIndices = [];
  295. // for each object data found
  296. for ( i = 0, l = objects.length; i < l; i++ ) {
  297. objectData = objects[ i ];
  298. object = objectData.object;
  299. resultObjectIndex = indexOfValue( resultsObjectsIndices, object );
  300. // if needed, create new result data
  301. if ( resultObjectIndex === -1 ) {
  302. resultData = {
  303. object: object,
  304. faces: [],
  305. vertices: []
  306. };
  307. results.push( resultData );
  308. resultsObjectsIndices.push( object );
  309. } else {
  310. resultData = results[ resultObjectIndex ];
  311. }
  312. // object data has faces or vertices, add to list
  313. if ( objectData.faces ) {
  314. resultData.faces.push( objectData.faces );
  315. } else if ( objectData.vertices ) {
  316. resultData.vertices.push( objectData.vertices );
  317. }
  318. }
  319. } else {
  320. results = objects;
  321. }
  322. return results;
  323. },
  324. setRoot: function ( root ) {
  325. if ( root instanceof THREE.OctreeNode ) {
  326. // store new root
  327. this.root = root;
  328. // update properties
  329. this.root.updateProperties();
  330. }
  331. },
  332. getDepthEnd: function () {
  333. return this.root.getDepthEnd();
  334. },
  335. getNodeCountEnd: function () {
  336. return this.root.getNodeCountEnd();
  337. },
  338. getObjectCountEnd: function () {
  339. return this.root.getObjectCountEnd();
  340. },
  341. toConsole: function () {
  342. this.root.toConsole();
  343. }
  344. };
  345. /*===================================================
  346. object data
  347. =====================================================*/
  348. THREE.OctreeObjectData = function ( object, part ) {
  349. // properties
  350. this.object = object;
  351. // handle part by type
  352. if ( part instanceof THREE.Face3 ) {
  353. this.faces = part;
  354. this.face3 = true;
  355. this.utilVec31FaceBounds = new THREE.Vector3();
  356. } else if ( part instanceof THREE.Face4 ) {
  357. this.face4 = true;
  358. this.faces = part;
  359. this.utilVec31FaceBounds = new THREE.Vector3();
  360. } else if ( part instanceof THREE.Vector3 ) {
  361. this.vertices = part;
  362. }
  363. this.radius = 0;
  364. this.position = new THREE.Vector3();
  365. // initial update
  366. if ( this.object instanceof THREE.Object3D ) {
  367. this.update();
  368. }
  369. this.positionLast = this.position.clone();
  370. };
  371. THREE.OctreeObjectData.prototype = {
  372. update: function () {
  373. if ( this.face3 ) {
  374. this.radius = this.getFace3BoundingRadius( this.object, this.faces );
  375. this.position.copy( this.faces.centroid ).applyMatrix4( this.object.matrixWorld );
  376. } else if ( this.face4 ) {
  377. this.radius = this.getFace4BoundingRadius( this.object, this.faces );
  378. this.position.copy( this.faces.centroid ).applyMatrix4( this.object.matrixWorld );
  379. } else if ( this.vertices ) {
  380. this.radius = this.object.material.size || 1;
  381. this.position.copy( this.vertices ).applyMatrix4( this.object.matrixWorld );
  382. } else {
  383. if ( this.object.geometry ) {
  384. if ( this.object.geometry.boundingSphere === null ) {
  385. this.object.geometry.computeBoundingSphere();
  386. }
  387. this.radius = this.object.geometry.boundingSphere.radius;
  388. } else {
  389. this.radius = this.object.boundRadius;
  390. }
  391. this.position.getPositionFromMatrix( this.object.matrixWorld );
  392. }
  393. this.radius = this.radius * Math.max( this.object.scale.x, this.object.scale.y, this.object.scale.z );
  394. },
  395. getFace3BoundingRadius: function ( object, face ) {
  396. var geometry = object.geometry || object,
  397. vertices = geometry.vertices,
  398. centroid = face.centroid,
  399. va = vertices[ face.a ], vb = vertices[ face.b ], vc = vertices[ face.c ],
  400. centroidToVert = this.utilVec31FaceBounds,
  401. radius;
  402. centroid.addVectors( va, vb ).add( vc ).divideScalar( 3 );
  403. radius = Math.max( centroidToVert.subVectors( centroid, va ).length(), centroidToVert.subVectors( centroid, vb ).length(), centroidToVert.subVectors( centroid, vc ).length() );
  404. return radius;
  405. },
  406. getFace4BoundingRadius: function ( object, face ) {
  407. var geometry = object.geometry || object,
  408. vertices = geometry.vertices,
  409. centroid = face.centroid,
  410. va = vertices[ face.a ], vb = vertices[ face.b ], vc = vertices[ face.c ], vd = vertices[ face.d ],
  411. centroidToVert = this.utilVec31FaceBounds,
  412. radius;
  413. centroid.addVectors( va, vb ).add( vc ).add( vd ).divideScalar( 4 );
  414. radius = Math.max( centroidToVert.subVectors( centroid, va ).length(), centroidToVert.subVectors( centroid, vb ).length(), centroidToVert.subVectors( centroid, vc ).length(), centroidToVert.subVectors( centroid, vd ).length() );
  415. return radius;
  416. }
  417. };
  418. /*===================================================
  419. node
  420. =====================================================*/
  421. THREE.OctreeNode = function ( parameters ) {
  422. // utility
  423. this.utilVec31Branch = new THREE.Vector3();
  424. this.utilVec31Expand = new THREE.Vector3();
  425. this.utilVec31Ray = new THREE.Vector3();
  426. // handle parameters
  427. parameters = parameters || {};
  428. // store or create tree
  429. if ( parameters.tree instanceof THREE.Octree ) {
  430. this.tree = parameters.tree;
  431. } else if ( parameters.parent instanceof THREE.OctreeNode !== true ) {
  432. parameters.root = this;
  433. this.tree = new THREE.Octree( parameters );
  434. }
  435. // basic properties
  436. this.id = this.tree.nodeCount++;
  437. this.position = parameters.position instanceof THREE.Vector3 ? parameters.position : new THREE.Vector3();
  438. this.radius = parameters.radius > 0 ? parameters.radius : 1;
  439. this.indexOctant = parameters.indexOctant;
  440. this.depth = 0;
  441. // reset and assign parent
  442. this.reset();
  443. this.setParent( parameters.parent );
  444. // additional properties
  445. this.overlap = this.radius * this.tree.overlapPct;
  446. this.radiusOverlap = this.radius + this.overlap;
  447. this.left = this.position.x - this.radiusOverlap;
  448. this.right = this.position.x + this.radiusOverlap;
  449. this.bottom = this.position.y - this.radiusOverlap;
  450. this.top = this.position.y + this.radiusOverlap;
  451. this.back = this.position.z - this.radiusOverlap;
  452. this.front = this.position.z + this.radiusOverlap;
  453. // visual
  454. if ( this.tree.scene ) {
  455. this.visual = new THREE.Mesh( this.tree.visualGeometry, this.tree.visualMaterial );
  456. this.visual.scale.set( this.radiusOverlap * 2, this.radiusOverlap * 2, this.radiusOverlap * 2 );
  457. this.visual.position.copy( this.position );
  458. this.tree.scene.add( this.visual );
  459. }
  460. };
  461. THREE.OctreeNode.prototype = {
  462. setParent: function ( parent ) {
  463. // store new parent
  464. if ( parent !== this && this.parent !== parent ) {
  465. this.parent = parent;
  466. // update properties
  467. this.updateProperties();
  468. }
  469. },
  470. updateProperties: function () {
  471. var i, l;
  472. // properties
  473. if ( this.parent instanceof THREE.OctreeNode ) {
  474. this.tree = this.parent.tree;
  475. this.depth = this.parent.depth + 1;
  476. } else {
  477. this.depth = 0;
  478. }
  479. // cascade
  480. for ( i = 0, l = this.nodesIndices.length; i < l; i++ ) {
  481. this.nodesByIndex[ this.nodesIndices[ i ] ].updateProperties();
  482. }
  483. },
  484. reset: function ( cascade, removeVisual ) {
  485. var i, l,
  486. node,
  487. nodesIndices = this.nodesIndices || [],
  488. nodesByIndex = this.nodesByIndex;
  489. this.objects = [];
  490. this.nodesIndices = [];
  491. this.nodesByIndex = {};
  492. // unset parent in nodes
  493. for ( i = 0, l = nodesIndices.length; i < l; i++ ) {
  494. node = nodesByIndex[ nodesIndices[ i ] ];
  495. node.setParent( undefined );
  496. if ( cascade === true ) {
  497. node.reset( cascade, removeVisual );
  498. }
  499. }
  500. // visual
  501. if ( removeVisual === true && this.visual && this.visual.parent ) {
  502. this.visual.parent.remove( this.visual );
  503. }
  504. },
  505. addNode: function ( node, indexOctant ) {
  506. node.indexOctant = indexOctant;
  507. if ( indexOfValue( this.nodesIndices, indexOctant ) === -1 ) {
  508. this.nodesIndices.push( indexOctant );
  509. }
  510. this.nodesByIndex[ indexOctant ] = node;
  511. if ( node.parent !== this ) {
  512. node.setParent( this );
  513. }
  514. },
  515. removeNode: function ( indexOctant ) {
  516. var index,
  517. node;
  518. index = indexOfValue( this.nodesIndices, indexOctant );
  519. this.nodesIndices.splice( index, 1 );
  520. node = node || this.nodesByIndex[ indexOctant ];
  521. delete this.nodesByIndex[ indexOctant ];
  522. if ( node.parent === this ) {
  523. node.setParent( undefined );
  524. }
  525. },
  526. addObject: function ( object ) {
  527. var index,
  528. indexOctant,
  529. node;
  530. // get object octant index
  531. indexOctant = this.getOctantIndex( object );
  532. // if object fully contained by an octant, add to subtree
  533. if ( indexOctant > -1 && this.nodesIndices.length > 0 ) {
  534. node = this.branch( indexOctant );
  535. node.addObject( object );
  536. } else if ( indexOctant < -1 && this.parent instanceof THREE.OctreeNode ) {
  537. // if object lies outside bounds, add to parent node
  538. this.parent.addObject( object );
  539. } else {
  540. // add to this objects list
  541. index = indexOfValue( this.objects, object );
  542. if ( index === -1 ) {
  543. this.objects.push( object );
  544. }
  545. // node reference
  546. object.node = this;
  547. // check if need to expand, split, or both
  548. this.checkGrow();
  549. }
  550. },
  551. addObjectWithoutCheck: function ( objects ) {
  552. var i, l,
  553. object;
  554. for ( i = 0, l = objects.length; i < l; i++ ) {
  555. object = objects[ i ];
  556. this.objects.push( object );
  557. object.node = this;
  558. }
  559. },
  560. removeObject: function ( object ) {
  561. var i, l,
  562. nodesRemovedFrom,
  563. removeData;
  564. // cascade through tree to find and remove object
  565. removeData = this.removeObjectRecursive( object, { searchComplete: false, nodesRemovedFrom: [], objectsDataRemoved: [] } );
  566. // if object removed, try to shrink the nodes it was removed from
  567. nodesRemovedFrom = removeData.nodesRemovedFrom;
  568. if ( nodesRemovedFrom.length > 0 ) {
  569. for ( i = 0, l = nodesRemovedFrom.length; i < l; i++ ) {
  570. nodesRemovedFrom[ i ].shrink();
  571. }
  572. }
  573. return removeData.objectsDataRemoved;
  574. },
  575. removeObjectRecursive: function ( object, removeData ) {
  576. var i, l,
  577. index = -1,
  578. objectData,
  579. node,
  580. objectRemoved;
  581. // find index of object in objects list
  582. // search and remove object data (fast)
  583. if ( object instanceof THREE.OctreeObjectData ) {
  584. // remove from this objects list
  585. index = indexOfValue( this.objects, object );
  586. if ( index !== -1 ) {
  587. this.objects.splice( index, 1 );
  588. object.node = undefined;
  589. removeData.objectsDataRemoved.push( object );
  590. removeData.searchComplete = objectRemoved = true;
  591. }
  592. } else {
  593. // search each object data for object and remove (slow)
  594. for ( i = this.objects.length - 1; i >= 0; i-- ) {
  595. objectData = this.objects[ i ];
  596. if ( objectData.object === object ) {
  597. this.objects.splice( i, 1 );
  598. objectData.node = undefined;
  599. removeData.objectsDataRemoved.push( objectData );
  600. objectRemoved = true;
  601. if ( !objectData.faces && !objectData.vertices ) {
  602. removeData.searchComplete = true;
  603. break;
  604. }
  605. }
  606. }
  607. }
  608. // if object data removed and this is not on nodes removed from
  609. if ( objectRemoved === true ) {
  610. removeData.nodesRemovedFrom.push( this );
  611. }
  612. // if search not complete, search nodes
  613. if ( removeData.searchComplete !== true ) {
  614. for ( i = 0, l = this.nodesIndices.length; i < l; i++ ) {
  615. node = this.nodesByIndex[ this.nodesIndices[ i ] ];
  616. // try removing object from node
  617. removeData = node.removeObjectRecursive( object, removeData );
  618. if ( removeData.searchComplete === true ) {
  619. break;
  620. }
  621. }
  622. }
  623. return removeData;
  624. },
  625. checkGrow: function () {
  626. // if object count above max
  627. if ( this.objects.length > this.tree.objectsThreshold && this.tree.objectsThreshold > 0 ) {
  628. this.grow();
  629. }
  630. },
  631. grow: function () {
  632. var indexOctant,
  633. object,
  634. objectsExpand = [],
  635. objectsExpandOctants = [],
  636. objectsSplit = [],
  637. objectsSplitOctants = [],
  638. objectsRemaining = [],
  639. i, l;
  640. // for each object
  641. for ( i = 0, l = this.objects.length; i < l; i++ ) {
  642. object = this.objects[ i ];
  643. // get object octant index
  644. indexOctant = this.getOctantIndex( object );
  645. // if lies within octant
  646. if ( indexOctant > -1 ) {
  647. objectsSplit.push( object );
  648. objectsSplitOctants.push( indexOctant );
  649. } else if ( indexOctant < -1 ) {
  650. // lies outside radius
  651. objectsExpand.push( object );
  652. objectsExpandOctants.push( indexOctant );
  653. } else {
  654. // lies across bounds between octants
  655. objectsRemaining.push( object );
  656. }
  657. }
  658. // if has objects to split
  659. if ( objectsSplit.length > 0) {
  660. objectsRemaining = objectsRemaining.concat( this.split( objectsSplit, objectsSplitOctants ) );
  661. }
  662. // if has objects to expand
  663. if ( objectsExpand.length > 0) {
  664. objectsRemaining = objectsRemaining.concat( this.expand( objectsExpand, objectsExpandOctants ) );
  665. }
  666. // store remaining
  667. this.objects = objectsRemaining;
  668. // merge check
  669. this.checkMerge();
  670. },
  671. split: function ( objects, octants ) {
  672. var i, l,
  673. indexOctant,
  674. object,
  675. node,
  676. objectsRemaining;
  677. // if not at max depth
  678. if ( this.depth < this.tree.depthMax ) {
  679. objects = objects || this.objects;
  680. octants = octants || [];
  681. objectsRemaining = [];
  682. // for each object
  683. for ( i = 0, l = objects.length; i < l; i++ ) {
  684. object = objects[ i ];
  685. // get object octant index
  686. indexOctant = octants[ i ];
  687. // if object contained by octant, branch this tree
  688. if ( indexOctant > -1 ) {
  689. node = this.branch( indexOctant );
  690. node.addObject( object );
  691. } else {
  692. objectsRemaining.push( object );
  693. }
  694. }
  695. // if all objects, set remaining as new objects
  696. if ( objects === this.objects ) {
  697. this.objects = objectsRemaining;
  698. }
  699. } else {
  700. objectsRemaining = this.objects;
  701. }
  702. return objectsRemaining;
  703. },
  704. branch: function ( indexOctant ) {
  705. var node,
  706. overlap,
  707. radius,
  708. radiusOffset,
  709. offset,
  710. position;
  711. // node exists
  712. if ( this.nodesByIndex[ indexOctant ] instanceof THREE.OctreeNode ) {
  713. node = this.nodesByIndex[ indexOctant ];
  714. } else {
  715. // properties
  716. radius = ( this.radiusOverlap ) * 0.5;
  717. overlap = radius * this.tree.overlapPct;
  718. radiusOffset = radius - overlap;
  719. offset = this.utilVec31Branch.set( indexOctant & 1 ? radiusOffset : -radiusOffset, indexOctant & 2 ? radiusOffset : -radiusOffset, indexOctant & 4 ? radiusOffset : -radiusOffset );
  720. position = new THREE.Vector3().addVectors( this.position, offset );
  721. // node
  722. node = new THREE.OctreeNode( {
  723. tree: this.tree,
  724. parent: this,
  725. position: position,
  726. radius: radius,
  727. indexOctant: indexOctant
  728. } );
  729. // store
  730. this.addNode( node, indexOctant );
  731. }
  732. return node;
  733. },
  734. expand: function ( objects, octants ) {
  735. var i, l,
  736. object,
  737. objectsRemaining,
  738. objectsExpand,
  739. indexOctant,
  740. flagsOutside,
  741. indexOutside,
  742. indexOctantInverse,
  743. iom = this.tree.INDEX_OUTSIDE_MAP,
  744. indexOutsideCounts,
  745. infoIndexOutside1,
  746. infoIndexOutside2,
  747. infoIndexOutside3,
  748. indexOutsideBitwise1,
  749. indexOutsideBitwise2,
  750. infoPotential1,
  751. infoPotential2,
  752. infoPotential3,
  753. indexPotentialBitwise1,
  754. indexPotentialBitwise2,
  755. octantX, octantY, octantZ,
  756. overlap,
  757. radius,
  758. radiusOffset,
  759. radiusParent,
  760. overlapParent,
  761. offset = this.utilVec31Expand,
  762. position,
  763. parent;
  764. // handle max depth down tree
  765. if ( this.tree.root.getDepthEnd() < this.tree.depthMax ) {
  766. objects = objects || this.objects;
  767. octants = octants || [];
  768. objectsRemaining = [];
  769. objectsExpand = [];
  770. // reset counts
  771. for ( i = 0, l = iom.length; i < l; i++ ) {
  772. iom[ i ].count = 0;
  773. }
  774. // for all outside objects, find outside octants containing most objects
  775. for ( i = 0, l = objects.length; i < l; i++ ) {
  776. object = objects[ i ];
  777. // get object octant index
  778. indexOctant = octants[ i ] ;
  779. // if object outside this, include in calculations
  780. if ( indexOctant < -1 ) {
  781. // convert octant index to outside flags
  782. flagsOutside = -indexOctant - this.tree.INDEX_OUTSIDE_OFFSET;
  783. // check against bitwise flags
  784. // x
  785. if ( flagsOutside & this.tree.FLAG_POS_X ) {
  786. iom[ this.tree.INDEX_OUTSIDE_POS_X ].count++;
  787. } else if ( flagsOutside & this.tree.FLAG_NEG_X ) {
  788. iom[ this.tree.INDEX_OUTSIDE_NEG_X ].count++;
  789. }
  790. // y
  791. if ( flagsOutside & this.tree.FLAG_POS_Y ) {
  792. iom[ this.tree.INDEX_OUTSIDE_POS_Y ].count++;
  793. } else if ( flagsOutside & this.tree.FLAG_NEG_Y ) {
  794. iom[ this.tree.INDEX_OUTSIDE_NEG_Y ].count++;
  795. }
  796. // z
  797. if ( flagsOutside & this.tree.FLAG_POS_Z ) {
  798. iom[ this.tree.INDEX_OUTSIDE_POS_Z ].count++;
  799. } else if ( flagsOutside & this.tree.FLAG_NEG_Z ) {
  800. iom[ this.tree.INDEX_OUTSIDE_NEG_Z ].count++;
  801. }
  802. // store in expand list
  803. objectsExpand.push( object );
  804. } else {
  805. objectsRemaining.push( object );
  806. }
  807. }
  808. // if objects to expand
  809. if ( objectsExpand.length > 0 ) {
  810. // shallow copy index outside map
  811. indexOutsideCounts = iom.slice( 0 );
  812. // sort outside index count so highest is first
  813. indexOutsideCounts.sort( function ( a, b ) {
  814. return b.count - a.count;
  815. } );
  816. // get highest outside indices
  817. // first is first
  818. infoIndexOutside1 = indexOutsideCounts[ 0 ];
  819. indexOutsideBitwise1 = infoIndexOutside1.index | 1;
  820. // second is ( one of next two bitwise OR 1 ) that is not opposite of ( first bitwise OR 1 )
  821. infoPotential1 = indexOutsideCounts[ 1 ];
  822. infoPotential2 = indexOutsideCounts[ 2 ];
  823. infoIndexOutside2 = ( infoPotential1.index | 1 ) !== indexOutsideBitwise1 ? infoPotential1 : infoPotential2;
  824. indexOutsideBitwise2 = infoIndexOutside2.index | 1;
  825. // third is ( one of next three bitwise OR 1 ) that is not opposite of ( first or second bitwise OR 1 )
  826. infoPotential1 = indexOutsideCounts[ 2 ];
  827. infoPotential2 = indexOutsideCounts[ 3 ];
  828. infoPotential3 = indexOutsideCounts[ 4 ];
  829. indexPotentialBitwise1 = infoPotential1.index | 1;
  830. indexPotentialBitwise2 = infoPotential2.index | 1;
  831. infoIndexOutside3 = indexPotentialBitwise1 !== indexOutsideBitwise1 && indexPotentialBitwise1 !== indexOutsideBitwise2 ? infoPotential1 : indexPotentialBitwise2 !== indexOutsideBitwise1 && indexPotentialBitwise2 !== indexOutsideBitwise2 ? infoPotential2 : infoPotential3;
  832. // get this octant normal based on outside octant indices
  833. octantX = infoIndexOutside1.x + infoIndexOutside2.x + infoIndexOutside3.x;
  834. octantY = infoIndexOutside1.y + infoIndexOutside2.y + infoIndexOutside3.y;
  835. octantZ = infoIndexOutside1.z + infoIndexOutside2.z + infoIndexOutside3.z;
  836. // get this octant indices based on octant normal
  837. indexOctant = this.getOctantIndexFromPosition( octantX, octantY, octantZ );
  838. indexOctantInverse = this.getOctantIndexFromPosition( -octantX, -octantY, -octantZ );
  839. // properties
  840. overlap = this.overlap;
  841. radius = this.radius;
  842. // radius of parent comes from reversing overlap of this, unless overlap percent is 0
  843. radiusParent = this.tree.overlapPct > 0 ? overlap / ( ( 0.5 * this.tree.overlapPct ) * ( 1 + this.tree.overlapPct ) ) : radius * 2;
  844. overlapParent = radiusParent * this.tree.overlapPct;
  845. // parent offset is difference between radius + overlap of parent and child
  846. radiusOffset = ( radiusParent + overlapParent ) - ( radius + overlap );
  847. offset.set( indexOctant & 1 ? radiusOffset : -radiusOffset, indexOctant & 2 ? radiusOffset : -radiusOffset, indexOctant & 4 ? radiusOffset : -radiusOffset );
  848. position = new THREE.Vector3().addVectors( this.position, offset );
  849. // parent
  850. parent = new THREE.OctreeNode( {
  851. tree: this.tree,
  852. position: position,
  853. radius: radiusParent
  854. } );
  855. // set self as node of parent
  856. parent.addNode( this, indexOctantInverse );
  857. // set parent as root
  858. this.tree.setRoot( parent );
  859. // add all expand objects to parent
  860. for ( i = 0, l = objectsExpand.length; i < l; i++ ) {
  861. this.tree.root.addObject( objectsExpand[ i ] );
  862. }
  863. }
  864. // if all objects, set remaining as new objects
  865. if ( objects === this.objects ) {
  866. this.objects = objectsRemaining;
  867. }
  868. } else {
  869. objectsRemaining = objects;
  870. }
  871. return objectsRemaining;
  872. },
  873. shrink: function () {
  874. // merge check
  875. this.checkMerge();
  876. // contract check
  877. this.tree.root.checkContract();
  878. },
  879. checkMerge: function () {
  880. var nodeParent = this,
  881. nodeMerge;
  882. // traverse up tree as long as node + entire subtree's object count is under minimum
  883. while ( nodeParent.parent instanceof THREE.OctreeNode && nodeParent.getObjectCountEnd() < this.tree.objectsThreshold ) {
  884. nodeMerge = nodeParent;
  885. nodeParent = nodeParent.parent;
  886. }
  887. // if parent node is not this, merge entire subtree into merge node
  888. if ( nodeParent !== this ) {
  889. nodeParent.merge( nodeMerge );
  890. }
  891. },
  892. merge: function ( nodes ) {
  893. var i, l,
  894. j, k,
  895. node;
  896. // handle nodes
  897. nodes = toArray( nodes );
  898. for ( i = 0, l = nodes.length; i < l; i++ ) {
  899. node = nodes[ i ];
  900. // gather node + all subtree objects
  901. this.addObjectWithoutCheck( node.getObjectsEnd() );
  902. // reset node + entire subtree
  903. node.reset( true, true );
  904. // remove node
  905. this.removeNode( node.indexOctant, node );
  906. }
  907. // merge check
  908. this.checkMerge();
  909. },
  910. checkContract: function () {
  911. var i, l,
  912. node,
  913. nodeObjectsCount,
  914. nodeHeaviest,
  915. nodeHeaviestObjectsCount,
  916. outsideHeaviestObjectsCount;
  917. // find node with highest object count
  918. if ( this.nodesIndices.length > 0 ) {
  919. nodeHeaviestObjectsCount = 0;
  920. outsideHeaviestObjectsCount = this.objects.length;
  921. for ( i = 0, l = this.nodesIndices.length; i < l; i++ ) {
  922. node = this.nodesByIndex[ this.nodesIndices[ i ] ];
  923. nodeObjectsCount = node.getObjectCountEnd();
  924. outsideHeaviestObjectsCount += nodeObjectsCount;
  925. if ( nodeHeaviest instanceof THREE.OctreeNode === false || nodeObjectsCount > nodeHeaviestObjectsCount ) {
  926. nodeHeaviest = node;
  927. nodeHeaviestObjectsCount = nodeObjectsCount;
  928. }
  929. }
  930. // subtract heaviest count from outside count
  931. outsideHeaviestObjectsCount -= nodeHeaviestObjectsCount;
  932. // if should contract
  933. if ( outsideHeaviestObjectsCount < this.tree.objectsThreshold && nodeHeaviest instanceof THREE.OctreeNode ) {
  934. this.contract( nodeHeaviest );
  935. }
  936. }
  937. },
  938. contract: function ( nodeRoot ) {
  939. var i, l,
  940. node;
  941. // handle all nodes
  942. for ( i = 0, l = this.nodesIndices.length; i < l; i++ ) {
  943. node = this.nodesByIndex[ this.nodesIndices[ i ] ];
  944. // if node is not new root
  945. if ( node !== nodeRoot ) {
  946. // add node + all subtree objects to root
  947. nodeRoot.addObjectWithoutCheck( node.getObjectsEnd() );
  948. // reset node + entire subtree
  949. node.reset( true, true );
  950. }
  951. }
  952. // add own objects to root
  953. nodeRoot.addObjectWithoutCheck( this.objects );
  954. // reset self
  955. this.reset( false, true );
  956. // set new root
  957. this.tree.setRoot( nodeRoot );
  958. // contract check on new root
  959. nodeRoot.checkContract();
  960. },
  961. getOctantIndex: function ( objectData ) {
  962. var i, l,
  963. positionObj,
  964. radiusObj,
  965. position = this.position,
  966. radiusOverlap = this.radiusOverlap,
  967. overlap = this.overlap,
  968. deltaX, deltaY, deltaZ,
  969. distX, distY, distZ,
  970. distance,
  971. indexOctant = 0;
  972. // handle type
  973. if ( objectData instanceof THREE.OctreeObjectData ) {
  974. radiusObj = objectData.radius;
  975. positionObj = objectData.position;
  976. // update object data position last
  977. objectData.positionLast.copy( positionObj );
  978. } else if ( objectData instanceof THREE.OctreeNode ) {
  979. positionObj = objectData.position;
  980. radiusObj = 0;
  981. }
  982. // find delta and distance
  983. deltaX = positionObj.x - position.x;
  984. deltaY = positionObj.y - position.y;
  985. deltaZ = positionObj.z - position.z;
  986. distX = Math.abs( deltaX );
  987. distY = Math.abs( deltaY );
  988. distZ = Math.abs( deltaZ );
  989. distance = Math.max( distX, distY, distZ );
  990. // if outside, use bitwise flags to indicate on which sides object is outside of
  991. if ( distance + radiusObj > radiusOverlap ) {
  992. // x
  993. if ( distX + radiusObj > radiusOverlap ) {
  994. indexOctant = indexOctant ^ ( deltaX > 0 ? this.tree.FLAG_POS_X : this.tree.FLAG_NEG_X );
  995. }
  996. // y
  997. if ( distY + radiusObj > radiusOverlap ) {
  998. indexOctant = indexOctant ^ ( deltaY > 0 ? this.tree.FLAG_POS_Y : this.tree.FLAG_NEG_Y );
  999. }
  1000. // z
  1001. if ( distZ + radiusObj > radiusOverlap ) {
  1002. indexOctant = indexOctant ^ ( deltaZ > 0 ? this.tree.FLAG_POS_Z : this.tree.FLAG_NEG_Z );
  1003. }
  1004. objectData.indexOctant = -indexOctant - this.tree.INDEX_OUTSIDE_OFFSET;
  1005. return objectData.indexOctant;
  1006. }
  1007. // return octant index from delta xyz
  1008. if ( deltaX - radiusObj > -overlap ) {
  1009. // x right
  1010. indexOctant = indexOctant | 1;
  1011. } else if ( !( deltaX + radiusObj < overlap ) ) {
  1012. // x left
  1013. objectData.indexOctant = this.tree.INDEX_INSIDE_CROSS;
  1014. return objectData.indexOctant;
  1015. }
  1016. if ( deltaY - radiusObj > -overlap ) {
  1017. // y right
  1018. indexOctant = indexOctant | 2;
  1019. } else if ( !( deltaY + radiusObj < overlap ) ) {
  1020. // y left
  1021. objectData.indexOctant = this.tree.INDEX_INSIDE_CROSS;
  1022. return objectData.indexOctant;
  1023. }
  1024. if ( deltaZ - radiusObj > -overlap ) {
  1025. // z right
  1026. indexOctant = indexOctant | 4;
  1027. } else if ( !( deltaZ + radiusObj < overlap ) ) {
  1028. // z left
  1029. objectData.indexOctant = this.tree.INDEX_INSIDE_CROSS;
  1030. return objectData.indexOctant;
  1031. }
  1032. objectData.indexOctant = indexOctant;
  1033. return objectData.indexOctant;
  1034. },
  1035. getOctantIndexFromPosition: function ( x, y, z ) {
  1036. var indexOctant = 0;
  1037. if ( x > 0 ) {
  1038. indexOctant = indexOctant | 1;
  1039. }
  1040. if ( y > 0 ) {
  1041. indexOctant = indexOctant | 2;
  1042. }
  1043. if ( z > 0 ) {
  1044. indexOctant = indexOctant | 4;
  1045. }
  1046. return indexOctant;
  1047. },
  1048. search: function ( position, radius, objects, direction, directionPct ) {
  1049. var i, l,
  1050. node,
  1051. intersects;
  1052. // test intersects by parameters
  1053. if ( direction ) {
  1054. intersects = this.intersectRay( position, direction, radius, directionPct );
  1055. } else {
  1056. intersects = this.intersectSphere( position, radius );
  1057. }
  1058. // if intersects
  1059. if ( intersects === true ) {
  1060. // gather objects
  1061. objects = objects.concat( this.objects );
  1062. // search subtree
  1063. for ( i = 0, l = this.nodesIndices.length; i < l; i++ ) {
  1064. node = this.nodesByIndex[ this.nodesIndices[ i ] ];
  1065. objects = node.search( position, radius, objects, direction );
  1066. }
  1067. }
  1068. return objects;
  1069. },
  1070. intersectSphere: function ( position, radius ) {
  1071. var distance = radius * radius,
  1072. px = position.x,
  1073. py = position.y,
  1074. pz = position.z;
  1075. if ( px < this.left ) {
  1076. distance -= Math.pow( px - this.left, 2 );
  1077. } else if ( px > this.right ) {
  1078. distance -= Math.pow( px - this.right, 2 );
  1079. }
  1080. if ( py < this.bottom ) {
  1081. distance -= Math.pow( py - this.bottom, 2 );
  1082. } else if ( py > this.top ) {
  1083. distance -= Math.pow( py - this.top, 2 );
  1084. }
  1085. if ( pz < this.back ) {
  1086. distance -= Math.pow( pz - this.back, 2 );
  1087. } else if ( pz > this.front ) {
  1088. distance -= Math.pow( pz - this.front, 2 );
  1089. }
  1090. return distance >= 0;
  1091. },
  1092. intersectRay: function ( origin, direction, distance, directionPct ) {
  1093. if ( typeof directionPct === 'undefined' ) {
  1094. directionPct = this.utilVec31Ray.set( 1, 1, 1 ).divide( direction );
  1095. }
  1096. var t1 = ( this.left - origin.x ) * directionPct.x,
  1097. t2 = ( this.right - origin.x ) * directionPct.x,
  1098. t3 = ( this.bottom - origin.y ) * directionPct.y,
  1099. t4 = ( this.top - origin.y ) * directionPct.y,
  1100. t5 = ( this.back - origin.z ) * directionPct.z,
  1101. t6 = ( this.front - origin.z ) * directionPct.z,
  1102. tmax = Math.min( Math.min( Math.max( t1, t2), Math.max( t3, t4) ), Math.max( t5, t6) ),
  1103. tmin;
  1104. // ray would intersect in reverse direction, i.e. this is behind ray
  1105. if (tmax < 0)
  1106. {
  1107. return false;
  1108. }
  1109. tmin = Math.max( Math.max( Math.min( t1, t2), Math.min( t3, t4)), Math.min( t5, t6));
  1110. // if tmin > tmax or tmin > ray distance, ray doesn't intersect AABB
  1111. if( tmin > tmax || tmin > distance ) {
  1112. return false;
  1113. }
  1114. return true;
  1115. },
  1116. getDepthEnd: function ( depth ) {
  1117. var i, l,
  1118. node;
  1119. if ( this.nodesIndices.length > 0 ) {
  1120. for ( i = 0, l = this.nodesIndices.length; i < l; i++ ) {
  1121. node = this.nodesByIndex[ this.nodesIndices[ i ] ];
  1122. depth = node.getDepthEnd( depth );
  1123. }
  1124. } else {
  1125. depth = !depth || this.depth > depth ? this.depth : depth;
  1126. }
  1127. return depth;
  1128. },
  1129. getNodeCountEnd: function () {
  1130. return this.tree.root.getNodeCountRecursive() + 1;
  1131. },
  1132. getNodeCountRecursive: function () {
  1133. var i, l,
  1134. count = this.nodesIndices.length;
  1135. for ( i = 0, l = this.nodesIndices.length; i < l; i++ ) {
  1136. count += this.nodesByIndex[ this.nodesIndices[ i ] ].getNodeCountRecursive();
  1137. }
  1138. return count;
  1139. },
  1140. getObjectsEnd: function ( objects ) {
  1141. var i, l,
  1142. node;
  1143. objects = ( objects || [] ).concat( this.objects );
  1144. for ( i = 0, l = this.nodesIndices.length; i < l; i++ ) {
  1145. node = this.nodesByIndex[ this.nodesIndices[ i ] ];
  1146. objects = node.getObjectsEnd( objects );
  1147. }
  1148. return objects;
  1149. },
  1150. getObjectCountEnd: function () {
  1151. var i, l,
  1152. count = this.objects.length;
  1153. for ( i = 0, l = this.nodesIndices.length; i < l; i++ ) {
  1154. count += this.nodesByIndex[ this.nodesIndices[ i ] ].getObjectCountEnd();
  1155. }
  1156. return count;
  1157. },
  1158. getObjectCountStart: function () {
  1159. var count = this.objects.length,
  1160. parent = this.parent;
  1161. while( parent instanceof THREE.OctreeNode ) {
  1162. count += parent.objects.length;
  1163. parent = parent.parent;
  1164. }
  1165. return count;
  1166. },
  1167. toConsole: function ( space ) {
  1168. var i, l,
  1169. node,
  1170. spaceAddition = ' ';
  1171. space = typeof space === 'string' ? space : spaceAddition;
  1172. console.log( ( this.parent ? space + ' octree NODE > ' : ' octree ROOT > ' ), this, ' // id: ', this.id, ' // indexOctant: ', this.indexOctant, ' // position: ', this.position.x, this.position.y, this.position.z, ' // radius: ', this.radius, ' // depth: ', this.depth );
  1173. console.log( ( this.parent ? space + ' ' : ' ' ), '+ objects ( ', this.objects.length, ' ) ', this.objects );
  1174. console.log( ( this.parent ? space + ' ' : ' ' ), '+ children ( ', this.nodesIndices.length, ' )', this.nodesIndices, this.nodesByIndex );
  1175. for ( i = 0, l = this.nodesIndices.length; i < l; i++ ) {
  1176. node = this.nodesByIndex[ this.nodesIndices[ i ] ];
  1177. node.toConsole( space + spaceAddition );
  1178. }
  1179. }
  1180. };
  1181. /*===================================================
  1182. raycaster additional functionality
  1183. =====================================================*/
  1184. THREE.Raycaster.prototype.intersectOctreeObject = function ( object, recursive ) {
  1185. var intersects,
  1186. octreeObject,
  1187. facesAll,
  1188. facesSearch;
  1189. if ( object.object instanceof THREE.Object3D ) {
  1190. octreeObject = object;
  1191. object = octreeObject.object;
  1192. // temporarily replace object geometry's faces with octree object faces
  1193. facesSearch = octreeObject.faces;
  1194. facesAll = object.geometry.faces;
  1195. if ( facesSearch.length > 0 ) {
  1196. object.geometry.faces = facesSearch;
  1197. }
  1198. // intersect
  1199. intersects = this.intersectObject( object, recursive );
  1200. // revert object geometry's faces
  1201. if ( facesSearch.length > 0 ) {
  1202. object.geometry.faces = facesAll;
  1203. }
  1204. } else {
  1205. intersects = this.intersectObject( object, recursive );
  1206. }
  1207. return intersects;
  1208. };
  1209. THREE.Raycaster.prototype.intersectOctreeObjects = function ( objects, recursive ) {
  1210. var i, il,
  1211. intersects = [];
  1212. for ( i = 0, il = objects.length; i < il; i++ ) {
  1213. intersects = intersects.concat( this.intersectOctreeObject( objects[ i ], recursive ) );
  1214. }
  1215. return intersects;
  1216. };
  1217. }( THREE ) );