Skip to content

渲染 instancedMesh 边线

官方文档并没有提供渲染 instancedMesh 边线的方法。翻阅官方论坛,找不到现成的解决方案。能找到的代码要么因为年代久远失效了,要么过于复杂难以复用。

最终,答案很简单:

js
const eGeom = new THREE.InstancedBufferGeometry();
eGeom.setAttribute("position", geom.getAttribute("position"));
// 将 instancedMesh 的矩阵属性绑定到边线元素
eGeom.setAttribute("matrix", iMesh.instanceMatrix);
eGeom.instanceCount = iMesh.instanceMatrix.array.length / 16;
const eMat = new THREE.LineBasicMaterial({
  color: "#fff",
  onBeforeCompile: (shader) => {
    // shader 按绑定的矩阵属性计算顶点坐标,让边线与 instancedMesh 保持一致
    shader.vertexShader = `
    attribute mat4 matrix;
    void main() {
      gl_Position = projectionMatrix * modelViewMatrix * matrix * vec4( position, 1.0 );
    }`;
  },
});

const edges = new THREE.LineSegments(eGeom, eMat);
scene.add(edges);

渲染效果:

在线预览作品 《instancedEdges》,作者(@周狮虎)创作于 笔.COOL