Object3D.js 16 KB

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