Object3D.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  1. import { Quaternion } from '../math/Quaternion.js';
  2. import { Vector3 } from '../math/Vector3.js';
  3. import { Matrix4 } from '../math/Matrix4.js';
  4. import { EventDispatcher } from './EventDispatcher.js';
  5. import { Euler } from '../math/Euler.js';
  6. import { Layers } from './Layers.js';
  7. import { Matrix3 } from '../math/Matrix3.js';
  8. import { MathUtils } from '../math/MathUtils.js';
  9. let _object3DId = 0;
  10. const _v1 = new Vector3();
  11. const _q1 = new Quaternion();
  12. const _m1 = new Matrix4();
  13. const _target = new Vector3();
  14. const _position = new Vector3();
  15. const _scale = new Vector3();
  16. const _quaternion = new Quaternion();
  17. const _xAxis = new Vector3( 1, 0, 0 );
  18. const _yAxis = new Vector3( 0, 1, 0 );
  19. const _zAxis = new Vector3( 0, 0, 1 );
  20. const _addedEvent = { type: 'added' };
  21. const _removedEvent = { type: 'removed' };
  22. function Object3D() {
  23. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  24. this.uuid = MathUtils.generateUUID();
  25. this.name = '';
  26. this.type = 'Object3D';
  27. this.parent = null;
  28. this.children = [];
  29. this.up = Object3D.DefaultUp.clone();
  30. const position = new Vector3();
  31. const rotation = new Euler();
  32. const quaternion = new Quaternion();
  33. const scale = new Vector3( 1, 1, 1 );
  34. function onRotationChange() {
  35. quaternion.setFromEuler( rotation, false );
  36. }
  37. function onQuaternionChange() {
  38. rotation.setFromQuaternion( quaternion, undefined, false );
  39. }
  40. rotation._onChange( onRotationChange );
  41. quaternion._onChange( onQuaternionChange );
  42. Object.defineProperties( this, {
  43. position: {
  44. configurable: true,
  45. enumerable: true,
  46. value: position
  47. },
  48. rotation: {
  49. configurable: true,
  50. enumerable: true,
  51. value: rotation
  52. },
  53. quaternion: {
  54. configurable: true,
  55. enumerable: true,
  56. value: quaternion
  57. },
  58. scale: {
  59. configurable: true,
  60. enumerable: true,
  61. value: scale
  62. },
  63. modelViewMatrix: {
  64. value: new Matrix4()
  65. },
  66. normalMatrix: {
  67. value: new Matrix3()
  68. }
  69. } );
  70. this.matrix = new Matrix4();
  71. this.matrixWorld = new Matrix4();
  72. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  73. this.matrixWorldNeedsUpdate = false;
  74. this.layers = new Layers();
  75. this.visible = true;
  76. this.castShadow = false;
  77. this.receiveShadow = false;
  78. this.frustumCulled = true;
  79. this.renderOrder = 0;
  80. this.userData = {};
  81. }
  82. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  83. Object3D.DefaultMatrixAutoUpdate = true;
  84. Object3D.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  85. constructor: Object3D,
  86. isObject3D: true,
  87. onBeforeRender: function () {},
  88. onAfterRender: function () {},
  89. applyMatrix4: function ( matrix ) {
  90. if ( this.matrixAutoUpdate ) this.updateMatrix();
  91. this.matrix.premultiply( matrix );
  92. this.matrix.decompose( this.position, this.quaternion, this.scale );
  93. },
  94. applyQuaternion: function ( q ) {
  95. this.quaternion.premultiply( q );
  96. return this;
  97. },
  98. setRotationFromAxisAngle: function ( axis, angle ) {
  99. // assumes axis is normalized
  100. this.quaternion.setFromAxisAngle( axis, angle );
  101. },
  102. setRotationFromEuler: function ( euler ) {
  103. this.quaternion.setFromEuler( euler, true );
  104. },
  105. setRotationFromMatrix: function ( m ) {
  106. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  107. this.quaternion.setFromRotationMatrix( m );
  108. },
  109. setRotationFromQuaternion: function ( q ) {
  110. // assumes q is normalized
  111. this.quaternion.copy( q );
  112. },
  113. rotateOnAxis: function ( axis, angle ) {
  114. // rotate object on axis in object space
  115. // axis is assumed to be normalized
  116. _q1.setFromAxisAngle( axis, angle );
  117. this.quaternion.multiply( _q1 );
  118. return this;
  119. },
  120. rotateOnWorldAxis: function ( axis, angle ) {
  121. // rotate object on axis in world space
  122. // axis is assumed to be normalized
  123. // method assumes no rotated parent
  124. _q1.setFromAxisAngle( axis, angle );
  125. this.quaternion.premultiply( _q1 );
  126. return this;
  127. },
  128. rotateX: function ( angle ) {
  129. return this.rotateOnAxis( _xAxis, angle );
  130. },
  131. rotateY: function ( angle ) {
  132. return this.rotateOnAxis( _yAxis, angle );
  133. },
  134. rotateZ: function ( angle ) {
  135. return this.rotateOnAxis( _zAxis, angle );
  136. },
  137. translateOnAxis: function ( axis, distance ) {
  138. // translate object by distance along axis in object space
  139. // axis is assumed to be normalized
  140. _v1.copy( axis ).applyQuaternion( this.quaternion );
  141. this.position.add( _v1.multiplyScalar( distance ) );
  142. return this;
  143. },
  144. translateX: function ( distance ) {
  145. return this.translateOnAxis( _xAxis, distance );
  146. },
  147. translateY: function ( distance ) {
  148. return this.translateOnAxis( _yAxis, distance );
  149. },
  150. translateZ: function ( distance ) {
  151. return this.translateOnAxis( _zAxis, distance );
  152. },
  153. localToWorld: function ( vector ) {
  154. return vector.applyMatrix4( this.matrixWorld );
  155. },
  156. worldToLocal: function ( vector ) {
  157. return vector.applyMatrix4( _m1.getInverse( this.matrixWorld ) );
  158. },
  159. lookAt: function ( x, y, z ) {
  160. // This method does not support objects having non-uniformly-scaled parent(s)
  161. if ( x.isVector3 ) {
  162. _target.copy( x );
  163. } else {
  164. _target.set( x, y, z );
  165. }
  166. const parent = this.parent;
  167. this.updateWorldMatrix( true, false );
  168. _position.setFromMatrixPosition( this.matrixWorld );
  169. if ( this.isCamera || this.isLight ) {
  170. _m1.lookAt( _position, _target, this.up );
  171. } else {
  172. _m1.lookAt( _target, _position, this.up );
  173. }
  174. this.quaternion.setFromRotationMatrix( _m1 );
  175. if ( parent ) {
  176. _m1.extractRotation( parent.matrixWorld );
  177. _q1.setFromRotationMatrix( _m1 );
  178. this.quaternion.premultiply( _q1.inverse() );
  179. }
  180. },
  181. add: function ( object ) {
  182. if ( arguments.length > 1 ) {
  183. for ( let i = 0; i < arguments.length; i ++ ) {
  184. this.add( arguments[ i ] );
  185. }
  186. return this;
  187. }
  188. if ( object === this ) {
  189. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  190. return this;
  191. }
  192. if ( ( object && object.isObject3D ) ) {
  193. if ( object.parent !== null ) {
  194. object.parent.remove( object );
  195. }
  196. object.parent = this;
  197. this.children.push( object );
  198. object.dispatchEvent( _addedEvent );
  199. } else {
  200. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  201. }
  202. return this;
  203. },
  204. remove: function ( object ) {
  205. if ( arguments.length > 1 ) {
  206. for ( let i = 0; i < arguments.length; i ++ ) {
  207. this.remove( arguments[ i ] );
  208. }
  209. return this;
  210. }
  211. const index = this.children.indexOf( object );
  212. if ( index !== - 1 ) {
  213. object.parent = null;
  214. this.children.splice( index, 1 );
  215. object.dispatchEvent( _removedEvent );
  216. }
  217. return this;
  218. },
  219. attach: function ( object ) {
  220. // adds object as a child of this, while maintaining the object's world transform
  221. this.updateWorldMatrix( true, false );
  222. _m1.getInverse( this.matrixWorld );
  223. if ( object.parent !== null ) {
  224. object.parent.updateWorldMatrix( true, false );
  225. _m1.multiply( object.parent.matrixWorld );
  226. }
  227. object.applyMatrix4( _m1 );
  228. object.updateWorldMatrix( false, false );
  229. this.add( object );
  230. return this;
  231. },
  232. getObjectById: function ( id ) {
  233. return this.getObjectByProperty( 'id', id );
  234. },
  235. getObjectByName: function ( name ) {
  236. return this.getObjectByProperty( 'name', name );
  237. },
  238. getObjectByProperty: function ( name, value ) {
  239. if ( this[ name ] === value ) return this;
  240. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  241. const child = this.children[ i ];
  242. const object = child.getObjectByProperty( name, value );
  243. if ( object !== undefined ) {
  244. return object;
  245. }
  246. }
  247. return undefined;
  248. },
  249. getWorldPosition: function ( target ) {
  250. if ( target === undefined ) {
  251. console.warn( 'THREE.Object3D: .getWorldPosition() target is now required' );
  252. target = new Vector3();
  253. }
  254. this.updateWorldMatrix( true, false );
  255. return target.setFromMatrixPosition( this.matrixWorld );
  256. },
  257. getWorldQuaternion: function ( target ) {
  258. if ( target === undefined ) {
  259. console.warn( 'THREE.Object3D: .getWorldQuaternion() target is now required' );
  260. target = new Quaternion();
  261. }
  262. this.updateWorldMatrix( true, false );
  263. this.matrixWorld.decompose( _position, target, _scale );
  264. return target;
  265. },
  266. getWorldScale: function ( target ) {
  267. if ( target === undefined ) {
  268. console.warn( 'THREE.Object3D: .getWorldScale() target is now required' );
  269. target = new Vector3();
  270. }
  271. this.updateWorldMatrix( true, false );
  272. this.matrixWorld.decompose( _position, _quaternion, target );
  273. return target;
  274. },
  275. getWorldDirection: function ( target ) {
  276. if ( target === undefined ) {
  277. console.warn( 'THREE.Object3D: .getWorldDirection() target is now required' );
  278. target = new Vector3();
  279. }
  280. this.updateWorldMatrix( true, false );
  281. const e = this.matrixWorld.elements;
  282. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  283. },
  284. raycast: function () {},
  285. traverse: function ( callback ) {
  286. callback( this );
  287. const children = this.children;
  288. for ( let i = 0, l = children.length; i < l; i ++ ) {
  289. children[ i ].traverse( callback );
  290. }
  291. },
  292. traverseVisible: function ( callback ) {
  293. if ( this.visible === false ) return;
  294. callback( this );
  295. const children = this.children;
  296. for ( let i = 0, l = children.length; i < l; i ++ ) {
  297. children[ i ].traverseVisible( callback );
  298. }
  299. },
  300. traverseAncestors: function ( callback ) {
  301. const parent = this.parent;
  302. if ( parent !== null ) {
  303. callback( parent );
  304. parent.traverseAncestors( callback );
  305. }
  306. },
  307. updateMatrix: function () {
  308. this.matrix.compose( this.position, this.quaternion, this.scale );
  309. this.matrixWorldNeedsUpdate = true;
  310. },
  311. updateMatrixWorld: function ( force ) {
  312. if ( this.matrixAutoUpdate ) this.updateMatrix();
  313. if ( this.matrixWorldNeedsUpdate || force ) {
  314. if ( this.parent === null ) {
  315. this.matrixWorld.copy( this.matrix );
  316. } else {
  317. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  318. }
  319. this.matrixWorldNeedsUpdate = false;
  320. force = true;
  321. }
  322. // update children
  323. const children = this.children;
  324. for ( let i = 0, l = children.length; i < l; i ++ ) {
  325. children[ i ].updateMatrixWorld( force );
  326. }
  327. },
  328. updateWorldMatrix: function ( updateParents, updateChildren ) {
  329. const parent = this.parent;
  330. if ( updateParents === true && parent !== null ) {
  331. parent.updateWorldMatrix( true, false );
  332. }
  333. if ( this.matrixAutoUpdate ) this.updateMatrix();
  334. if ( this.parent === null ) {
  335. this.matrixWorld.copy( this.matrix );
  336. } else {
  337. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  338. }
  339. // update children
  340. if ( updateChildren === true ) {
  341. const children = this.children;
  342. for ( let i = 0, l = children.length; i < l; i ++ ) {
  343. children[ i ].updateWorldMatrix( false, true );
  344. }
  345. }
  346. },
  347. toJSON: function ( meta ) {
  348. // meta is a string when called from JSON.stringify
  349. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  350. const output = {};
  351. // meta is a hash used to collect geometries, materials.
  352. // not providing it implies that this is the root object
  353. // being serialized.
  354. if ( isRootObject ) {
  355. // initialize meta obj
  356. meta = {
  357. geometries: {},
  358. materials: {},
  359. textures: {},
  360. images: {},
  361. shapes: {}
  362. };
  363. output.metadata = {
  364. version: 4.5,
  365. type: 'Object',
  366. generator: 'Object3D.toJSON'
  367. };
  368. }
  369. // standard Object3D serialization
  370. const object = {};
  371. object.uuid = this.uuid;
  372. object.type = this.type;
  373. if ( this.name !== '' ) object.name = this.name;
  374. if ( this.castShadow === true ) object.castShadow = true;
  375. if ( this.receiveShadow === true ) object.receiveShadow = true;
  376. if ( this.visible === false ) object.visible = false;
  377. if ( this.frustumCulled === false ) object.frustumCulled = false;
  378. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  379. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  380. object.layers = this.layers.mask;
  381. object.matrix = this.matrix.toArray();
  382. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  383. // object specific properties
  384. if ( this.isInstancedMesh ) {
  385. object.type = 'InstancedMesh';
  386. object.count = this.count;
  387. object.instanceMatrix = this.instanceMatrix.toJSON();
  388. }
  389. //
  390. function serialize( library, element ) {
  391. if ( library[ element.uuid ] === undefined ) {
  392. library[ element.uuid ] = element.toJSON( meta );
  393. }
  394. return element.uuid;
  395. }
  396. if ( this.isMesh || this.isLine || this.isPoints ) {
  397. object.geometry = serialize( meta.geometries, this.geometry );
  398. const parameters = this.geometry.parameters;
  399. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  400. const shapes = parameters.shapes;
  401. if ( Array.isArray( shapes ) ) {
  402. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  403. const shape = shapes[ i ];
  404. serialize( meta.shapes, shape );
  405. }
  406. } else {
  407. serialize( meta.shapes, shapes );
  408. }
  409. }
  410. }
  411. if ( this.material !== undefined ) {
  412. if ( Array.isArray( this.material ) ) {
  413. const uuids = [];
  414. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  415. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  416. }
  417. object.material = uuids;
  418. } else {
  419. object.material = serialize( meta.materials, this.material );
  420. }
  421. }
  422. //
  423. if ( this.children.length > 0 ) {
  424. object.children = [];
  425. for ( let i = 0; i < this.children.length; i ++ ) {
  426. object.children.push( this.children[ i ].toJSON( meta ).object );
  427. }
  428. }
  429. if ( isRootObject ) {
  430. const geometries = extractFromCache( meta.geometries );
  431. const materials = extractFromCache( meta.materials );
  432. const textures = extractFromCache( meta.textures );
  433. const images = extractFromCache( meta.images );
  434. const shapes = extractFromCache( meta.shapes );
  435. if ( geometries.length > 0 ) output.geometries = geometries;
  436. if ( materials.length > 0 ) output.materials = materials;
  437. if ( textures.length > 0 ) output.textures = textures;
  438. if ( images.length > 0 ) output.images = images;
  439. if ( shapes.length > 0 ) output.shapes = shapes;
  440. }
  441. output.object = object;
  442. return output;
  443. // extract data from the cache hash
  444. // remove metadata on each item
  445. // and return as array
  446. function extractFromCache( cache ) {
  447. const values = [];
  448. for ( const key in cache ) {
  449. const data = cache[ key ];
  450. delete data.metadata;
  451. values.push( data );
  452. }
  453. return values;
  454. }
  455. },
  456. clone: function ( recursive ) {
  457. return new this.constructor().copy( this, recursive );
  458. },
  459. copy: function ( source, recursive ) {
  460. if ( recursive === undefined ) recursive = true;
  461. this.name = source.name;
  462. this.up.copy( source.up );
  463. this.position.copy( source.position );
  464. this.rotation.order = source.rotation.order;
  465. this.quaternion.copy( source.quaternion );
  466. this.scale.copy( source.scale );
  467. this.matrix.copy( source.matrix );
  468. this.matrixWorld.copy( source.matrixWorld );
  469. this.matrixAutoUpdate = source.matrixAutoUpdate;
  470. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  471. this.layers.mask = source.layers.mask;
  472. this.visible = source.visible;
  473. this.castShadow = source.castShadow;
  474. this.receiveShadow = source.receiveShadow;
  475. this.frustumCulled = source.frustumCulled;
  476. this.renderOrder = source.renderOrder;
  477. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  478. if ( recursive === true ) {
  479. for ( let i = 0; i < source.children.length; i ++ ) {
  480. const child = source.children[ i ];
  481. this.add( child.clone() );
  482. }
  483. }
  484. return this;
  485. }
  486. } );
  487. export { Object3D };