Threejs:使自定义着色器匹配标准渲染

Threejs: make custom shader match the standard rendering

出于性能原因,我需要在一个场景中显示数百个移动的四面体。我在那里使用需要自定义着色器的 instancedbuffergeometry。

场景还包含具有规则几何形状(非缓冲区)的对象和一些灯光(我准备了精简代码片段:https://jsfiddle.net/negan/xs3k1yz4/)。

我的问题是四面体没有着色,因此它们的光照似乎适合场景的其余部分。原因大概是我建的primitive shader:

<script id="vertexShader" type="x-shader/x-vertex">
attribute vec3 offset;
attribute vec4 color;
varying vec4 vColor;
varying vec3 vNormal;
void main() {
 vColor = color;
 vNormal = normalMatrix * vec3(normal);
 gl_Position = projectionMatrix *
    modelViewMatrix *
    vec4(position*1.0+offset,1.0);
}
</script>
<script id="fragmentShader" type="x-shader/x-fragment">
 varying vec4 vColor;
    varying vec3 vNormal;

 void main() {  
  float di = 0.4*dot(vNormal,normalize(vec3(1.,1.,0.)))+0.4*dot(vNormal,normalize(vec3(1.,0.,1.)));
  di = di+0.2;
  vec4 vColor2= vColor*vec4(1.0,1.,1.,0.2)*di;
  gl_FragColor = vColor2;// adjust the alpha
 }
</script>

有没有办法让自定义着色器适合我在场景中定义的灯光?着色器还以不产生定向光印象的方式渲染面孔。我宁愿让单个面均匀地照亮,而不是从顶点插值颜色,但我无法实现。

感谢任何指点或帮助。

Here's a gist of the full fragment and vertex shader source 对于 Three.js MeshPhongMaterial 着色器,从 r83 开始。

Three.js 使用字符串连接系统构建着色器,因此几乎不可能通过查看 Three.js 源来确定着色器的源。

以上 Gist 是通过安装 shader editor Chrome extension, going to a Three.js example page that has a MeshPhongMaterial like this one 并使用着色器编辑器检查 运行 着色器程序的完整源代码生成的:

Three.js 将所有默认制服(如光照数据)传递给所有着色器程序,因此如果您使用上述 Gist 代码创建自定义着色器,灯光、骨骼等都将自动工作。

我会获取完整的源代码并手动添加您的逻辑,将您的计算结果直接添加到现有的 gl_FragColor = ...

将来,我的工具 ShaderFrog 将允许您自动将任何 Three.js 着色器功能(灯光、骨骼、变形目标等)添加到任何自定义着色器。 ShaderFrog 已经可以自动将任何着色器组合在一起,但我还没有完成完全支持三个功能所需的手动工作。

有 three.js 的 InstancedMesh 模块。它允许在不使用着色器 materials 的情况下进行网格实例化。它修补了现有的 material。 https://github.com/pailhead/three-instanced-mesh