【问题标题】:OpenGL Light moving with moving object even though its not supposed toOpenGL Light随着移动对象移动,即使它不应该
【发布时间】:2021-12-25 13:04:33
【问题描述】:

C++、OpenGL、Glad ->
我有一个灯应该会在场景中引起一些漫射照明。
问题是当我旋转在 Y 上渲染的对象时(UP ) 轴,似乎光线也随着物体移动。 灯光的运动与物体的旋转不同步。
为什么会发生这种情况,我该如何解决? 这是着色器。
顶点着色器

#version 330 core

layout (location = 0) in vec3 pos;
layout (location = 1) in vec2 coords;
layout (location = 2) in vec3 normals;

out vec2 Texture_Coords;
out vec3 normal;
out vec3 toLightVector;

uniform mat4 p;
uniform mat4 m;
uniform mat4 v;
uniform vec3 light_position;

void main(){
    vec4 world_position = m * vec4(pos,1.0);
    gl_Position = p * v * world_position;

    Texture_Coords = coords;
    normal = (vec4(normals,1.0) * m).xyz;

    toLightVector = light_position - world_position.xyz;
}

片段着色器

#version 330 core

out vec4 Pixel;

in vec2 Texture_Coords;
in vec3 normal;
in vec3 toLightVector;

uniform vec4 color;
uniform sampler2D Texture;
uniform float ambient;
uniform vec3 light_color;

void main(){

    vec3 unitNormal = normalize(normal);
    vec3 unitToLightVector = normalize(toLightVector);

    float light_factor = dot(unitNormal, unitToLightVector);
    float brightness = max(light_factor, ambient);
    vec3 diffuse = brightness * light_color;

    Pixel = vec4(diffuse,1.0) * texture(Texture, Texture_Coords);
}

【问题讨论】:

  • 试试normal = mat3(m) * normals;
  • @Rabbid76 它有效,但是为什么,这改变了什么?
  • m * normalsnormals * m 不同

标签: opengl glsl lighting


【解决方案1】:

矩阵乘法不可交换v * mm * v不一样:

normal = (vec4(normals,1.0) * m).xyz;

normal = mat3(m) * normals;

我也推荐阅读Why is the transposed inverse of the model view matrix used to transform the normal vectors?Why transforming normals with the transpose of the inverse of the modelview matrix?

normal = transpose(inverse(mat3(m))) * normals;

【讨论】:

    猜你喜欢
    • 2018-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多