mat4项目/非项目无法正常工作

时间:2014-10-29 00:35:39

标签: opengl math lua projection glm-math

我正在尝试在Lua中实现GLM的项目和非项目功能,但结果是......值得怀疑。据我所知,我的代码(如下所示)几乎与GLM相同,但正如下面的视频所示,文本没有按预期显示。当我将相机带到0,0,0时,文本形成一个菱形图案,这很有趣。

这里应该显示的是,无论相机在哪里移动,应该在各自的立方体上绘制cube.001到cube.009。 cube.001是TL,cube.009是BR。

要全面了解我们的mat4库(以及其他垃圾),请访问here

-- https://github.com/g-truc/glm/blob/master/glm/gtc/matrix_transform.inl#L317
function mat4.project(obj, view, projection, viewport)
    local position = { obj.x, obj.y, obj.z, 1 }
    position = view * position
    position = projection * position

    position[1] = position[1] / position[4] * 0.5 + 0.5
    position[2] = position[2] / position[4] * 0.5 + 0.5
    position[3] = position[3] / position[4] * 0.5 + 0.5
    position[4] = position[4] / position[4] * 0.5 + 0.5

    position[1] = position[1] * viewport[3] + viewport[1]
    position[2] = position[2] * viewport[4] + viewport[2]

    return vec3(position[1], position[2], position[3])
end

-- https://github.com/g-truc/glm/blob/master/glm/gtc/matrix_transform.inl#L338
function mat4.unproject(win, view, projection, viewport)
    local inverse = (projection * view):inverse()
    local position = { win.x, win.y, win.z, 1 }
    position.x = (position.x - viewport[1]) / viewport[3]
    position.y = (position.y - viewport[2]) / viewport[4]

    position[1] = position[1] * 2 - 1
    position[2] = position[2] * 2 - 1
    position[3] = position[3] * 2 - 1
    position[4] = position[4] * 2 - 1

    position = inverse * position

    position[1] = position[1] / position[4]
    position[2] = position[2] / position[4]
    position[3] = position[3] / position[4]
    position[4] = position[4] / position[4]

    return vec3(position[1], position[2], position[3])
end

-- Get projection from cubes
local viewport = { 0, 0, 1280, 720 }
for _, cube in ipairs(self.cubes) do
    local model = cpml.mat4()
        :translate(cube.position)
        :rotate(cube.orientation.x, { 1, 0, 0 })
        :rotate(cube.orientation.y, { 0, 1, 0 })
        :rotate(cube.orientation.z, { 0, 0, 1 })
        :scale(cube.scale)

    local projection = cpml.mat4.project(
        cube.position,
        self.camera.view:transpose(),
        self.camera.projection:transpose(),
        viewport
    )
end

1 个答案:

答案 0 :(得分:0)

事实证明有两件事是错的:

1)因为我有一个错误...我的代码中的其他地方需要转换矩阵。

2)GLM使用" model"当提到相机视图时,我一直在使用错误的矩阵。

我已更新代码以反映这些更正。