c - View (lookat)和投影(perspective)矩阵无法正常工作

标签 c opengl math glsl vertex-shader

由于原因(固执和 C),我一直在关注 open.gl 教程,但没有使用 GLM 库。 我无法使 View 和投影矩阵正常工作。

这是相关的顶点着色器代码,

#version 150 core

in vec3 size;
in vec3 color;
in vec2 texcoord;

out vec3 Color;
out vec2 Texcoord;

uniform vec3 pos;
uniform float angle;

uniform vec3 camPos;
uniform vec3 camTarget;

const float fov=90, ratio=4.0/3.0, near=1.0, far=10.0;

mat4 projection ()
{
    float t = tan(radians(fov)),
          l = ratio * t;
    return mat4(
        vec4(near/l, 0.0,    0.0,                    0.0),
        vec4(0.0,    near/t, 0.0,                    0.0),
        vec4(0.0,    0.0,    -(far+near)/(far-near), -(2*far*near)/(far-near)),
        vec4(0.0,    0.0,    -1.0,                   0.0)
    );
}

mat4 rotZ(float theta)
{
    return mat4(
        vec4(cos(theta), -sin(theta),  0.0, 0.0),
        vec4(sin(theta),  cos(theta),  0.0, 0.0),
        vec4(0.0,         0.0,         1.0, 0.0),
        vec4(0.0,         0.0,         0.0, 1.0)
    );
}

mat4 translate(vec3 translation)
{
    return mat4(
        vec4(1.0,            0.0,            0.0,            0.0),
        vec4(0.0,            1.0,            0.0,            0.0),
        vec4(0.0,            0.0,            1.0,            0.0),
        vec4(translation.x, translation.y, translation.z, 1.0)
    );
}

mat4 lookAtRH(vec3 eye, vec3 target)
{
    vec3 zaxis = normalize(target - eye);    // The "forward" vector.
    vec3 xaxis = normalize(cross(vec3(0.0,0.0,1.0), zaxis));// The "right" vector.
    vec3 yaxis = normalize(cross(zaxis, xaxis));     // The "up" vector.

    mat4 axis = {
        vec4(xaxis.x, yaxis.x, zaxis.x, 0),
        vec4(xaxis.y, yaxis.y, zaxis.y, 0),
        vec4(xaxis.z, yaxis.z, zaxis.z, 0),
        vec4(dot(xaxis,-eye),       dot(yaxis,-eye),       dot(zaxis,-eye),     1)
    };

    return axis;
}

void main()
{
    Color = color;
    Texcoord = texcoord;

    mat4 model = translate(pos) * rotZ(angle);
    mat4 view = lookAtRH(camPos, camTarget);

    gl_Position = projection() * view * model * vec4(size, 1.0);
}

从周围的调整看来, View 矩阵似乎是正确的,但投影矩阵导致了狡猾。

最佳答案

首先,我必须指出,直接在着色器中执行此操作是一个非常糟糕的主意。

但是,如果您确实愿意,也可以这样做。您应该知道 GLSL 矩阵构造函数使用列 vector 。您的投影矩阵因此被指定转置(但是,您的平移矩阵是正确的)。

关于c - View (lookat)和投影(perspective)矩阵无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20776918/

相关文章:

c - 编写一个测量缓存 block 大小的 C 程序

c++ - OpenGL Alpha 与错误的颜色混合

python - 算术运算中的暴力搜索算法

c++ - 计算 ackermann 函数的较大值

c - 链表不打印所有值

c - 如何从 .t​​xt C 中的数组中删除项目

c - 如何使用 scanf() 获取任意数量的整数?

opengl - 绘制抗锯齿粗镶嵌曲线

c++ - 为什么我们选择 "bounding box"方法来填充一个三角形呢?

c++ - 字符串编码问题?