Object3D.js 16 KB

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