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 );
}

快速搭建工具-持续开发中

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

菜鸡饶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值