0
我想在Lua中實現GLM的項目和unproject函數,但結果是...值得懷疑。據我所知,我的代碼(如下所示)與GLM幾乎相同,但是如下面的視頻所示,文本不會按預期顯示。當我將相機帶到0,0,0時,文字會形成菱形圖案,這很有趣。mat4項目/ unproject不工作
這裏應該顯示的是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
在unproject我看到position.x分配給兩次,而不是它是第二次。 – 2014-10-29 00:59:23
謝謝你發現,我現在就去改變它。我們還沒有實際測試過項目,因爲項目導致我們有這麼多問題。 :) – Karai17 2014-10-29 01:00:19