Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android OpenGL weirdness with the setLookAtM method

As a beginner to android and openGL 2.0 es, I'm testing simple things and see how it goes.

I downloaded the sample at http://developer.android.com/training/graphics/opengl/touch.html .

I changed the code to check if I could animate a rotation of the camera around the (0,0,0) point, the center of the square.

So i did this:

public void onDrawFrame(GL10 unused) {
    // Draw background color
    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);

    // Set the camera position (View matrix)
    long time = SystemClock.uptimeMillis() % 4000L;
    float angle = ((float) (2*Math.PI)/ (float) 4000) * ((int) time);
    Matrix.setLookAtM(mVMatrix, 0, (float) (3*Math.sin(angle)), 0, (float) (3.0f*Math.cos(angle)),     0 ,0, 0,     0f, 1.0f, 0.0f);

    // Calculate the projection and view transformation
    Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mVMatrix, 0);

    // Draw square
    mSquare.draw(mMVPMatrix);
}

I expected the camera to look always to the center of the square (the (0,0,0) point) but that's not what happens. The camera is indeed rotating around the square but the square does not stay in the center of the screen.. instead it is moving along the X axis...: enter image description hereenter image description here

I also expected that if we gave the eyeX and eyeY the same values as centerX and centerY,like this:

Matrix.setLookAtM(mVMatrix, 0, 1, 1, -3,     1 ,1, 0,     0f, 1.0f, 0.0f);

the square would keep it's shape (I mean, your field of vision would be dragged but along a plane which would be paralel to the square), but that's also not what happens:

enter image description here

This is my projection matrix:

float ratio = (float) width / height;

// this projection matrix is applied to object coordinates
// in the onDrawFrame() method
Matrix.frustumM(mProjMatrix, 0, -ratio, ratio, -1, 1, 2, 7);

What is going on here?

like image 592
jmacedo Avatar asked Jan 16 '23 20:01

jmacedo


1 Answers

Looking at the source code to the example you downloaded, I can see why you're having that problem, it has to do with the order of the matrix multiplication.

Typically in OpenGL source you see matrices set up such that

transformed vertex = projMatrix * viewMatrix * modelMatrix * input vertex

However in the source example program that you downloaded, their shader is setup like this:

" gl_Position = vPosition * uMVPMatrix;"

With the position on the other side of the matrix. You can work with OpenGL in this way, but it requires that you reverse the lhs/rhs of your matrix multiplications.

Long story short, in your case, you should change your shader to read:

" gl_Position = uMVPMatrix * vPosition;"

and then I believe you will get the expected behavior.

like image 147
Tim Avatar answered Jan 18 '23 23:01

Tim