【发布时间】:2017-04-05 23:29:25
【问题描述】:
我目前正在实现一个模拟 OpenGL 的软件渲染器,作为基于 these lessons 的学习体验。我的项目代码可以是found here.
我在处理顶点法线时遇到了一些困难。我想用模型矩阵转换它们,我知道当矩阵不正交时我应该使用模型矩阵的逆转置。光照方向应在世界空间中指定,因此应转换法线,然后使用世界空间光照方向的点积来计算光照强度。
这就是问题所在。它在这里工作正常,请注意相机在向上轴旋转 45 度查看模型。
如果我在任何轴上将模型旋转 90 度,现在取向上轴,光线方向会翻转指向另一个方向。正如您在此处看到的那样,光线来自背面。
如果我旋转到 180 度,又可以了。
如果我旋转到 45 度,那么光点就会变成 90 度,如此处所示。注意尖峰以查看光的来源。
这让我困惑了好几个小时。我无法弄清楚出了什么问题。就好像在灯光下旋转加倍。光的矢量并没有改变,看这里:
vec4 SmoothShader::Vertex(int iFace, int nthVert)
{
vec3 vposition = model->vert(iFace, nthVert);
vec4 projectionSpace = MVP * embed<4>(vposition);
vec3 light = vec3(0, 0, 1);
mat4 normTrans = M.invert_transpose();
vec4 normal = normTrans * embed<4>(model->normal(iFace, nthVert), 0.f);
vec3 norm = proj<3>(normal);
intensity[nthVert] = std::max(0.0f, norm.normalise() * light.normalise());
return projectionSpace;
}
bool SmoothShader::Fragment(vec3 barycentric, vec3 &Colour)
{
float pixelIntensity = intensity * barycentric;
Colour = vec3(255, 122, 122) * pixelIntensity;
return true;
}
MVP(模型、视图、投影)和 M(模型)矩阵的计算如下:
// Model Matrix, converts to world space
mat4 scale = MakeScale(o->scale);
mat4 translate = MakeTranslate(o->position);
mat4 rotate = MakeRotate(o->rotation);
// Move objects backward from the camera's position
mat4 cameraTranslate = MakeTranslate(vec3(-cameraPosition.x, -cameraPosition.y, -cameraPosition.z));
// Get the camera's rotated basis vectors to rotate everything to camera space.
vec3 Forward;
vec3 Right;
vec3 Up;
GetAxesFromRotation(cameraRotation, Forward, Right, Up);
mat4 cameraRotate = MakeLookAt(Forward, Up);
// Convert from camera space to perspective projection space
mat4 projection = MakePerspective(surf->w, surf->h, 1, 10, cameraFOV);
// Convert from projection space (-1, 1) to viewport space
mat4 viewport = MakeViewport(surf->w, surf->h);
mat4 M = translate * rotate * scale;
mat4 MVP = viewport * projection * cameraRotate * cameraTranslate * M;
知道我做错了什么吗?
【问题讨论】:
标签: c++ matrix graphics 3d rotation