我正在尝试使用Three.js ShaderMaterial并尝试实现照明。 我有r70的工作代码,但相同的代码(稍作修改 - MAX_POINT_LIGHTS常量已重命名为NUM_POINT_LIGHTS)对r76不起作用。
查看WebGL Inspector中的跟踪,很明显没有光数据被发送到着色器。那么,照明是否已经破裂,或者我是否需要设置其他东西以使其发挥作用?
http://codepen.io/anon/pen/KzjXNr?editors=1010
片段着色器
uniform vec3 diffuse;
varying vec3 vPos;
varying vec3 vNormal;
uniform vec3 pointLightColor[MAX_POINT_LIGHTS];
uniform vec3 pointLightPosition[MAX_POINT_LIGHTS];
uniform float pointLightDistance[MAX_POINT_LIGHTS];
void main() {
vec4 addedLights = vec4(0.1, 0.1, 0.1, 1.0);
for(int l = 0; l < MAX_POINT_LIGHTS; l++) {
vec3 lightDirection = normalize(vPos - pointLightPosition[l]);
addedLights.rgb += clamp(dot(-lightDirection, vNormal), 0.0, 1.0) * pointLightColor[l];
}
gl_FragColor = addedLights;
}
JavaScript - 使用UniformsUtils和UniformsLib设置Shadermaterial
var uniforms = THREE.UniformsUtils.merge([
THREE.UniformsLib['lights'],
{ diffuse: { type: 'c', value: new THREE.Color(0xff00ff) } }
]);
var vertexShader = document.getElementById('vertexShader').text;
var fragmentShader = document.getElementById('fragmentShader').text;
material = new THREE.ShaderMaterial({
uniforms: uniforms,
vertexShader: vertexShader,
fragmentShader: fragmentShader,
lights: true
});
var geometry = new THREE.BoxGeometry(200, 200, 200);
mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
http://codepen.io/anon/pen/ZWdXLZ?editors=1010
片段着色器
uniform vec3 diffuse;
varying vec3 vPos;
varying vec3 vNormal;
uniform vec3 pointLightColor[NUM_POINT_LIGHTS];
uniform vec3 pointLightPosition[NUM_POINT_LIGHTS];
uniform float pointLightDistance[NUM_POINT_LIGHTS];
void main() {
vec4 addedLights = vec4(0.1, 0.1, 0.1, 1.0);
for(int l = 0; l < NUM_POINT_LIGHTS; l++) {
vec3 lightDirection = normalize(vPos - pointLightPosition[l]);
addedLights.rgb += clamp(dot(-lightDirection, vNormal), 0.0, 1.0) * pointLightColor[l];
}
gl_FragColor = addedLights;
}
的JavaScript
不变
答案 0 :(得分:6)
r74中的轻型制服已更改为struct
(具体在#7324)。请注意,虽然对struct
的更改发生在r74中,但以下内容适用于r75及更高版本。
为每种灯光类型提供单个struct
s数组。每个struct
都有您需要的position
和color
属性。
片段着色器
uniform vec3 diffuse;
varying vec3 vPos;
varying vec3 vNormal;
struct PointLight {
vec3 position;
vec3 color;
};
uniform PointLight pointLights[ NUM_POINT_LIGHTS ];
void main() {
vec4 addedLights = vec4(0.1, 0.1, 0.1, 1.0);
for(int l = 0; l < NUM_POINT_LIGHTS; l++) {
vec3 adjustedLight = pointLights[l].position + cameraPosition;
vec3 lightDirection = normalize(vPos - adjustedLight);
addedLights.rgb += clamp(dot(-lightDirection, vNormal), 0.0, 1.0) * pointLights[l].color;
}
gl_FragColor = addedLights;//mix(vec4(diffuse.x, diffuse.y, diffuse.z, 1.0), addedLights, addedLights);
}
请注意,灯光位置现在相对于相机,因此您可以使用相机位置偏移灯光位置。