InstancedMesh.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. */
  4. import { BufferAttribute } from '../core/BufferAttribute.js';
  5. import { Mesh } from './Mesh.js';
  6. import { Matrix4 } from '../math/Matrix4.js';
  7. var _instanceLocalMatrix = new Matrix4();
  8. var _instanceWorldMatrix = new Matrix4();
  9. var _instanceIntersects = [];
  10. var _mesh = new Mesh();
  11. function InstancedMesh( geometry, material, count ) {
  12. Mesh.call( this, geometry, material );
  13. this.instanceMatrix = new BufferAttribute( new Float32Array( count * 16 ), 16 );
  14. this.count = count;
  15. this.frustumCulled = false;
  16. }
  17. InstancedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  18. constructor: InstancedMesh,
  19. isInstancedMesh: true,
  20. getMatrixAt: function ( index, matrix ) {
  21. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  22. },
  23. raycast: function ( raycaster, intersects ) {
  24. var matrixWorld = this.matrixWorld;
  25. var raycastTimes = this.count;
  26. _mesh.geometry = this.geometry;
  27. _mesh.material = this.material;
  28. if ( _mesh.material === undefined ) return;
  29. for ( var instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  30. // calculate the world matrix for each instance
  31. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  32. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  33. // the mesh represents this single instance
  34. _mesh.matrixWorld = _instanceWorldMatrix;
  35. _mesh.raycast( raycaster, _instanceIntersects );
  36. // process the result of raycast
  37. for ( var i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  38. var intersect = _instanceIntersects[ i ];
  39. intersect.instanceId = instanceId;
  40. intersect.object = this;
  41. intersects.push( intersect );
  42. }
  43. _instanceIntersects.length = 0;
  44. }
  45. },
  46. setMatrixAt: function ( index, matrix ) {
  47. matrix.toArray( this.instanceMatrix.array, index * 16 );
  48. },
  49. updateMorphTargets: function () {
  50. }
  51. } );
  52. export { InstancedMesh };