How do you implement glOrtho for opengles 2.0? Wit

2019-06-22 09:23发布

问题:

Im trying to implement my own glOtho function from the opengles docs http://www.khronos.org/opengles/documentation/opengles1_0/html/glOrtho.html
to modify a Projection matrix in my vertex shader. It's currently not working properly as I see my simple triangles vertices out of place. Can you please check the code below and see if i'm doing things wrong.

I've tried setting tx,ty and tz to 0 and that seems to make it render properly. Any ideas why would this be so?

void ES2Renderer::_applyOrtho(float left, float right,float bottom, float top,float near, float far) const{ 

        float a = 2.0f / (right - left);
        float b = 2.0f / (top - bottom);
        float c = -2.0f / (far - near);

        float tx = - (right + left)/(right - left);
        float ty = - (top + bottom)/(top - bottom);
        float tz = - (far + near)/(far - near);

        float ortho[16] = {
            a, 0, 0, tx,
            0, b, 0, ty,
            0, 0, c, tz,
            0, 0, 0, 1
        };


        GLint projectionUniform = glGetUniformLocation(_shaderProgram, "Projection");
        glUniformMatrix4fv(projectionUniform, 1, 0, &ortho[0]);

}

void ES2Renderer::_renderScene()const{
    GLfloat vVertices[] = {
        0.0f,  5.0f, 0.0f,  
        -5.0f, -5.0f, 0.0f,
        5.0f, -5.0f,  0.0f};

    GLuint positionAttribute = glGetAttribLocation(_shaderProgram, "Position");

    glEnableVertexAttribArray(positionAttribute);


    glVertexAttribPointer(positionAttribute, 3, GL_FLOAT, GL_FALSE, 0, vVertices);  
    glDrawArrays(GL_TRIANGLES, 0, 3);       


    glDisableVertexAttribArray(positionAttribute);

}

Vert shader

attribute vec4 Position;
uniform mat4 Projection;
void main(void){
    gl_Position = Projection*Position;
}

Solution From Nicols answer below I modifed my matrix as so and it seemed render properly

float ortho[16] = {
    a, 0, 0, 0,
    0, b, 0, 0,
    0, 0, c, 0,
    tx, ty, tz, 1
};

Important note You cannot use GL_TRUE for transpose argument for glUniform as below. opengles does not support it. it must be GL_FALSE

glUniformMatrix4fv(projectionUniform, 1, GL_TRUE, &ortho[0]);

From http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml

transpose Specifies whether to transpose the matrix as the values are loaded into the uniform variable. Must be GL_FALSE.

回答1:

Matrices in OpenGL are column major. Unless you pass GL_TRUE as the third parameter to glUniformMatrix4fv, the matrix will effectively be transposed relative to what you would intend.