2011-10-17 161 views
2

我正在使用以下OpenGL ES 1.x代碼來設置我的投影座標。如何將世界座標轉換爲OpenGL ES 2.0中的屏幕座標

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模擬器中獲得的輸出:

enter image description here

+0

你已經更新了你的問題,但實際上已經看到並理解了湯米的回答? –

+0

@ChristianRau是的,我試過轉置標誌,但它不起作用。除了上面提到的那個之外,我沒有應用任何其他矩陣。我想要得到Ortho投影的權利,但是好像我獲得了透視投影! – kal21

回答

1

你的glOrtho公式的轉錄看起來是正確的。

您的Matrix4x4類是自定義的,但有可能m.m最終直接作爲glUniformMatrix4fv加載?如果是這樣,請檢查您是否將轉置標誌設置爲GL_TRUE,因爲您要以行主格式加載數據,並且OpenGL期望列主要(即標準規則是index [0]是第一列的頂部,[3 ]位於第一列的底部,[4]位於第二列的頂部等)。

也許值得一提的是,假設你直接複製舊世界矩陣堆棧,你將在頂點着色器中以正確的順序應用模型視圖和投影,或者在CPU上正確地合成它們,無論哪種方式你正在做這件事。

+0

正在傳遞轉置標誌是GL_FALSE,但是當我將它設置爲GL_TRUE時,四方消失了! – kal21

+0

建議和代碼是正確的。我在一個新的新程序中嘗試了相同的方法,它工作正常。謝謝。 – kal21

相關問題