Object3D.js 16 KB

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