three.js 多实例渲染 InstancedMesh提升性能
·
简介
InstancedMesh是R110之后出现
官网简介:
A special version of Mesh with instanced rendering support. Use InstancedMesh if you have to render a large number of objects with the same geometry and material but with different world transformations. The usage of InstancedMesh will help you to reduce the number of draw calls and thus improve the overall rendering performance in your application.
大量相同的几何,会减少绘图调用的次数,大量提高页面性能;
多实例需要三个参数 几何 材质 渲染的总数。
你需要的渲染总数如果超过了该数值不会被渲染
new THREE.InstancedMesh(geometry, material, count);
生成
例如生成 50的3次方
function createMeshs() {
// --
const amount = 50;
const geometry = new THREE.OctahedronBufferGeometry(2, 1);
const material = new THREE.MeshNormalMaterial({});
// --
mesh = new THREE.InstancedMesh(geometry, material, count);
let i = 0;
const gap = 5;
const size = amount * gap;
for (var x = 0; x < amount; x++) {
for (var y = 0; y < amount; y++) {
for (var z = 0; z < amount; z++) {
// 生成该图形
// localtion 当前的位置
group.position.set(x * gap - size / 2, y * gap - size / 2, z * gap - size / 2);
// matrix
group.updateMatrix();
// 根据当前索引更新
mesh.setMatrixAt(i++, group.matrix);
}
}
};
scene.add(mesh);
}
拾取
// move
function onMouseMove( event ) {
event.preventDefault();
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
}
// render
function render() {
raycaster.setFromCamera( mouse, camera );
var intersection = raycaster.intersectObject( mesh );
if ( intersection.length > 0 ) {
// 获取当前实例的ID 索引
var instanceId = intersection[ 0 ].instanceId;
// 根据当前的索引 获取当前的矩阵
mesh.getMatrixAt( instanceId, instanceMatrix );
// 更新矩阵
matrix.multiplyMatrices( instanceMatrix, rotationMatrix );
// 设置拾取当前几何的矩阵
mesh.setMatrixAt( instanceId, matrix );
// 更新矩阵
mesh.instanceMatrix.needsUpdate = true;
}
renderer.render( scene, camera );
}
更多推荐
已为社区贡献5条内容
所有评论(0)