【问题标题】:How to convert world coordinates to screen coordinates in OpenGL ES 2.0如何在 OpenGL ES 2.0 中将世界坐标转换为屏幕坐标
【发布时间】:2011-10-18 01:20:18
【问题描述】:

我正在使用以下 OpenGL ES 1.x 代码来设置我的投影坐标。

glMatrixMode(GL_PROJECTION); 

float width = 320;
float height = 480;

glOrthof(0.0,                  // Left
         1.0,                  // Right
         height / width,       // Bottom
         0.0,                  // Top
         -1.0,                 // Near
         1.0);                 // Far
glMatrixMode(GL_MODELVIEW);

在 OpenGL ES 2.0 中设置它的等效方法是什么? 我应该将什么投影矩阵传递给顶点着色器?

我尝试了以下函数来创建矩阵,但它不起作用:

void SetOrtho (Matrix4x4& m, float left, float right, float bottom, float top, float near, 
float far)
{
    const float tx = - (right + left)/(right - left);
    const float ty = - (top + bottom)/(top - bottom);
    const float tz = - (far + near)/(far - near);

    m.m[0] = 2.0f/(right-left);
    m.m[1] = 0;
    m.m[2] = 0;
    m.m[3] = tx;

    m.m[4] = 0;
    m.m[5] = 2.0f/(top-bottom);
    m.m[6] = 0;
    m.m[7] = ty;

    m.m[8] = 0;
    m.m[9] = 0;
    m.m[10] = -2.0/(far-near);
    m.m[11] = tz;

    m.m[12] = 0;
    m.m[13] = 0;
    m.m[14] = 0;
    m.m[15] = 1;
}

顶点着色器:

uniform mat4 u_mvpMatrix;

attribute vec4 a_position;
attribute vec4 a_color;

varying vec4 v_color;

void main()
{
   gl_Position = u_mvpMatrix * a_position;
   v_color = a_color;
}

客户端代码(顶点着色器的参数):

float min = 0.0f;
float max = 1.0f;
const GLfloat squareVertices[] = {
    min, min,
    min, max,
    max, min,
    max, max
};
const GLfloat squareColors[] = {
    1, 1, 0, 1,
    0, 1, 1, 1,
    0, 0, 0, 1,
    1, 0, 1, 1,
};
Matrix4x4 proj;
SetOrtho(proj, 0.0f, 1.0f, 480.0/320.0, 0.0f, -1.0f, 1.0f );

我在 iPhone 模拟器中得到的输出:

【问题讨论】:

  • 您更新了您的问题,但实际上已经看到并理解了汤米的回答?
  • @ChristianRau 是的,我已经尝试过转置标志,但它不起作用。除了上面提到的矩阵之外,我没有应用任何其他矩阵。我想正确地进行 Ortho 投影,但似乎我正在获得透视投影!

标签: opengl-es opengl-es-2.0


【解决方案1】:

您对glOrtho 公式的转录看起来正确。

您的 Matrix4x4 类是自定义的,但是 m.m 是否有可能最终被直接加载为 glUniformMatrix4fv?如果是这样,请检查您是否将转置标志设置为 GL_TRUE,因为您正在以行主要格式加载数据并且 OpenGL 期望列主要格式(即,标准规则是索引 [0] 是第一列的顶部,[3 ] 位于第一列的底部,[4] 位于第二列的顶部,依此类推)。

这可能还值得检查——假设你直接复制了旧世界的矩阵堆栈——你在顶点着色器中以正确的顺序应用模型视图和投影,或者在 CPU 上正确合成它们,无论哪种方式你在做。

【讨论】:

  • 它传递的转置标志是 GL_FALSE 但是当我将它设置为 GL_TRUE 时,四边形消失了!
  • 建议和代码是正确的。我在一个全新的程序中尝试了相同的方法,并且效果很好。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-19
  • 1970-01-01
  • 1970-01-01
  • 2013-04-14
  • 2017-02-25
  • 1970-01-01
相关资源
最近更新 更多