InstancedMesh.js 1.8 KB
Newer Older
M
Mr.doob 已提交
1 2 3 4 5
/**
 * @author mrdoob / http://mrdoob.com/
 */
import { BufferAttribute } from '../core/BufferAttribute.js';
import { Mesh } from './Mesh.js';
W
webglzhang 已提交
6
import { Matrix4 } from '../math/Matrix4.js';
M
Mr.doob 已提交
7

W
webglzhang 已提交
8 9 10 11 12
var _instanceLocalMatrix = new Matrix4();
var _instanceWorldMatrix = new Matrix4();

var _instanceIntersects = [];

13
var _mesh = new Mesh();
W
webglzhang 已提交
14

M
Mr.doob 已提交
15 16 17 18 19 20
function InstancedMesh( geometry, material, count ) {

	Mesh.call( this, geometry, material );

	this.instanceMatrix = new BufferAttribute( new Float32Array( count * 16 ), 16 );

M
Mr.doob 已提交
21 22
	this.count = count;

M
Mr.doob 已提交
23 24 25 26 27 28 29 30
}

InstancedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {

	constructor: InstancedMesh,

	isInstancedMesh: true,

31
	getMatrixAt: function ( index, matrix ) {
W
webglzhang 已提交
32 33 34

		matrix.fromArray( this.instanceMatrix.array, index * 16 );

W
webglzhang 已提交
35 36 37 38 39 40 41
	},

	raycast: function ( raycaster, intersects ) {

		var matrixWorld = this.matrixWorld;
		var raycastTimes = this.count;

42 43
		_mesh.geometry = this.geometry;
		_mesh.material = this.material;
W
webglzhang 已提交
44

45
		if ( _mesh.material === undefined ) return;
W
webglzhang 已提交
46 47 48 49 50 51 52 53 54 55

		for ( var instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {

			//Calculate the world matrix for each instance

			this.getMatrixAt( instanceId, _instanceLocalMatrix );

			_instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );


W
webglzhang 已提交
56
			//The mesh represents this single instance
W
webglzhang 已提交
57

58
			_mesh.matrixWorld = _instanceWorldMatrix;
W
webglzhang 已提交
59

60
			_mesh.raycast( raycaster, _instanceIntersects );
W
webglzhang 已提交
61 62 63 64 65 66 67 68 69 70 71


			//Process the result of raycast

			if ( _instanceIntersects.length > 0 ) {

				_instanceIntersects[ 0 ].instanceId = instanceId;
				_instanceIntersects[ 0 ].object = this;

				intersects.push( _instanceIntersects[ 0 ] );

W
webglzhang 已提交
72
				_instanceIntersects.length = 0;
W
webglzhang 已提交
73 74 75 76

			}

		}
W
webglzhang 已提交
77 78

	},
M
Mr.doob 已提交
79

80
	setMatrixAt: function ( index, matrix ) {
M
Mr.doob 已提交
81

82
		matrix.toArray( this.instanceMatrix.array, index * 16 );
M
Mr.doob 已提交
83 84 85

	},

W
webglzhang 已提交
86 87 88
	updateMorphTargets: function () {

	}
M
Mr.doob 已提交
89 90 91 92

} );

export { InstancedMesh };