为什么我的 WebGL 3D 到 2D 投影会给出错误的结果?

问题描述

我正在编写一个 WebGL 应用程序,该应用程序需要能够将 3D 点投影到相机的视野(在视野内时在 [-1 .. 1] 范围内)。

大部分时间我的代码都可以正常工作,但似乎我必须管理一些边缘情况,因为有时我会得到错误的值。下面是重现问题的示例代码(使用 https://glmatrix.net 进行数学运算):

// Get canvas size:
const width = this.gl.canvas.clientWidth; // 814
const height = this.gl.canvas.clientHeight; // 944

// Create the projection matrix:
const zNear = 0.1;
const zFar = 1.5;
const fov = 45.0 * Math.PI / 180;
const ratio = width / height;
const cameradistance = 0.625;

const projectionMatrix = mat4.perspective(mat4.create(),fov,ratio,zNear,zFar);

// Create the view matrix:
const viewMatrix = mat4.create();
mat4.rotateX(viewMatrix,viewMatrix,-40 * Math.PI / 180);
mat4.translate(viewMatrix,[0,-cameradistance]);

// Create the view projection matrix:
const vpMatrix = mat4.multiply(mat4.create(),projectionMatrix,viewMatrix);

// Test:
const point = [-0.29009878635406494,-0.4102616608142853,0.29009878635406494];
const projected = vec3.transformMat4(vec3.create(),point,vpMatrix);
console.log(projected[0] + "," + projected[1]);

JSfiddlehttps://jsfiddle.net/0rhyz2xk/2

这里是场景(测试点是黄色方块,相机的视野是灰色的平截头体):

enter image description here

上面代码在控制台打印113.40699005126953,178.50587463378906,说明投影点应该在视野外,在其右上角。这是错误的,我应该得到负值,因为我的观点在左下角。如果我将相机倾斜到 -39 而不是 -40,我会得到 -390.28143310546875、-614.3656616210938,这似乎更好。

怎么了?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)