【问题标题】:rendering 1 million boxes in react-three/fiber在 react-three/fiber 中渲染 100 万个盒子
【发布时间】:2021-07-15 16:17:24
【问题描述】:

我正在 react-three/fiber 中测试渲染 1 mil 的盒子。性能很慢。

function App() {
  const boxes = [];

  for (let i = 0; i < 1000; i++) {
    const x = Math.random();
    const y = Math.random();
    const z = Math.random();

    const box = (
      <mesh position={[x, y, z]}>
        <boxGeometry args={[0.01, 0.01, 0.01]} />
        <meshLambertMaterial color={"red"} />
      </mesh>
    );

    boxes.push(box);
  }

  return (
    <MBox style={{ height: "100vh", width: "100vw" }}>
      <Canvas camera={{ position: [10, 10, 10] }}>
        <pointLight position={[15, 15, 15]} />
        {boxes}
        <OrbitControls />
        <Stats />
      </Canvas>
    </MBox>
  );
}

渲染响应性为 1000 个框 (60 FPS)。有 10000 个盒子,它会下降到 7 FPS,有点缺乏。浏览器死了 100000 个盒子。

完全没有使用计算机专用 GPU NVIDIA。

请问有什么提高性能的想法吗?

【问题讨论】:

  • 你应该考虑用InstancedMesh渲染你的盒子。
  • 不确定是否仍然可以使用 InstancedMesh,如果每个框在我的情况下具有不同的宽度、高度、深度。
  • 这可以通过不同的尺度来实现。

标签: reactjs three.js webgl react-three-fiber


【解决方案1】:

通过@Mugen87 的建议让它工作。

function Boxes() {
  const meshRef = useRef<InstancedMesh>();
  const tempObject = new Object3D();

  useEffect(() => {
    if (meshRef == null) return;
    if (meshRef.current == null) return;

    let i = 0;
    for (let x = 0; x < 100; x++)
      for (let y = 0; y < 100; y++)
        for (let z = 0; z < 100; z++) {
          const id = i++;
          tempObject.position.set(x, y, z);
          tempObject.scale.set(1, 0.5, 1.5);
          tempObject.updateMatrix();
          meshRef.current.setMatrixAt(id, tempObject.matrix);
        }
    meshRef.current.instanceMatrix.needsUpdate = true;
  }, []);

  return (
    <instancedMesh ref={meshRef} args={[null as any, null as any, 1000000]}>
      <boxGeometry args={[0.1, 0.1, 0.1]}></boxGeometry>
      <meshBasicMaterial />
    </instancedMesh>
  );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    • 2020-10-31
    • 2022-01-04
    • 1970-01-01
    • 2021-11-27
    • 2021-08-20
    • 2021-03-09
    相关资源
    最近更新 更多