透视投影,坐标系转换的问题。
大家好,
我在做3d正方体。
步骤是将正方体在世界坐标的顶点转换成相机坐标系内顶点,我已完成。
然后将相机坐标系内的顶点通过透视投影转换到规则观察体中(Canonical View Volume)
问题来了。
我的正方体在世界坐标系内的顶点为:
- C/C++ code
Vertex v1(5.0, 5.0, 10.0, 1.0, 5.0, 5.0, 5.0,1.0);//001 Vertex v2(10.0, 5.0, 10.0, 1.0, 5.0, 5.0, 5.0,1.0);//101 Vertex v3(5.0, 10.0, 10.0, 1.0, 5.0, 5.0, 5.0,1.0);//011 Vertex v4(10.0, 10.0, 10.0, 1.0, 5.0, 5.0, 5.0,1.0);//111 Vertex v5(5.0, 10.0, 5.0, 1.0, 5.0, 5.0, 5.0,1.0);//010 Vertex v6(10.0, 10.0, 5.0, 1.0, 5.0, 5.0, 5.0,1.0);//110 Vertex v7(5.0, 5.0, 5.0, 1.0, 5.0, 5.0, 5.0,1.0);//000 Vertex v8(10.0, 5.0, 5.0, 1.0, 5.0, 5.0, 5.0,1.0);//100
经过转换,现在在相机坐标系中的位置为:
-3.53553, -2.04124, -14.4338
0, -4.08248, -11.547
-3.53553, 2.04124, -11.547
0, 0, -8.66025
0, 4.08248, -14.4338
3.53553, 2.04124, -11.547
0, 0, -17.3205
3.53553, -2.04124, -14.4338
现在我要定义一个视锥体:
- C/C++ code
void CameraCoord::frustum(int l, int r, int b, int t, int n, int f){ //这是投影矩阵。 double perspective[] = { 2*n/(r-l), 0, (r+l)/(r-1), 0, 0, 2*n/(t - b), (t+b)/(t-b), 0, 0, 0, -(n+f)/(n-f), -2*n*f/(n-f), 0, 0, -1, 0 }; for(int i = 0; i < 16; i++) perspectiveMatrix.push_back(perspective[i]);//投影矩阵}然后我把我的相机坐标系内的正方体的点也就是
-3.53553, -2.04124, -14.4338|
0, -4.08248, -11.547 |
-3.53553, 2.04124, -11.547 |
0, 0, -8.66025| 乘以perspectiveMatrix应该得到透视除法(perspective division)之前的点。
0, 4.08248, -14.4338|
3.53553, 2.04124, -11.547 |
0, 0, -17.3205|
3.53553, -2.04124, -14.4338|
代码如下:
- C/C++ code
void RGBCube::projectionTransformation(Vertex *v){ CameraCoord camera; camera.frustum(-5,5,-5,5,-5,-25); double vx = v->x; double vy = v->y; double vz = v->z; double vw = v->w; v->x = vx * camera.perspectiveMatrix[0] + vy * camera.perspectiveMatrix[1] + vz * camera.perspectiveMatrix[2] + vw * camera.perspectiveMatrix[3]; v->y = vx * camera.perspectiveMatrix[4] + vy * camera.perspectiveMatrix[5] + vz * camera.perspectiveMatrix[6] + vw * camera.perspectiveMatrix[7]; v->z = vx * camera.perspectiveMatrix[8] + vy * camera.perspectiveMatrix[9] + vz * camera.perspectiveMatrix[10] + vw * camera.perspectiveMatrix[11]; v->w = vx * camera.perspectiveMatrix[12] + vy * camera.perspectiveMatrix[13] + vz * camera.perspectiveMatrix[14] + vw * camera.perspectiveMatrix[15]; cout<<v->x<<","<<v->y<<","<<v->z<<endl;}最后的输出竟然所有点的x,y都是0.请问这是为什么?是哪里出错了?
谢谢大伙!
[解决办法]
经过转换后点 v 已经不在 homogeneous space 了,你得将 v.xyz /= v.w 将点 v 变回来,再比较才有意义。
[解决办法]
我看楼主的代码不象 OpenGL 代码,干嘛还非得要模拟 OpenGL 那套摄影变换的体系呢,这不是自找麻烦又得不到 GL 渲染加速的好处吗。
[解决办法]
超出你的视景体了吧
[解决办法]