跳到主要内容
← ShadowMap

ShadowMap

Shadow Map - Depth Buffer

shader-learning 自学第 3 课:Shadow Map - Depth Buffer

实时渲染 · 网格 GLSL

第 3 课:Shadow Map - Depth Buffer

实现

uniform vec2 iResolution;

attribute vec4 color;

varying vec3 vLightDir;
varying vec3 vNormal;
varying vec4 vColor;

mat4 getLightProjection() {
  float ratio = iResolution.x/iResolution.y;
  float left = -2.0 * ratio;
  float right = 2.0 * ratio;
  float top = 2.0;
  float bottom = -2.0;
  float far = 8.0;
  float near = 0.1;

  mat4 lightProjection = transpose(mat4(
    vec4(2.0/(right - left), 0.0, 0.0, 0.0),
    vec4(0.0, 2.0/(top - bottom), 0.0, 0.0),
    vec4(0.0, 0.0, 2.0/(near - far), 0.0),
    vec4(0.0, 0.0, 0.0, 1.0)
  ));

  mat4 translate = transpose(mat4(
    vec4(1.0, 0.0, 0.0, -(right + left)/2.0),
    vec4(0.0, 1.0, 0.0, -(top + bottom)/2.0),
    vec4(0.0, 0.0, 1.0, (near + far)/2.0),
    vec4(0.0, 0.0, 0.0, 1.0)
  ));

  lightProjection *= translate;

  return lightProjection;
}

void main() {

  vec3 lightDir = normalize(vec3(-0.5, -0.8, 0.0));
  vec3 lightPos = vec3(1.5, 2.4, 0.0);
  vec3 worldUp = vec3(0.0,1.0,0.0);
  vec3 vectorRight = normalize(cross(worldUp,-lightDir));
  vec3 vectorUp = normalize(cross(-lightDir, vectorRight));

  mat4 lightView = transpose(mat4(
    vec4(vectorRight, 0.0),
    vec4(vectorUp, 0.0),
    vec4(-lightDir, 0.0),
    vec4(vec3(0.0), 1.0)
  ));

  mat4 translate = transpose(mat4(
    vec4(1.0, 0.0, 0.0, -lightPos.x),
    vec4(0.0, 1.0, 0.0, -lightPos.y),
    vec4(0.0, 0.0, 1.0, -lightPos.z),
    vec4(vec3(0.0), 1.0)
  ));

  lightView *= translate;

  gl_Position = getLightProjection() * lightView * modelMatrix * vec4(position, 1.0);

  vLightDir = lightDir;
  vNormal = mat3(modelMatrix) * normal;
  vColor = color;
}