OpenGL ES Android Matrix Transformations

前端 未结 3 1179
再見小時候
再見小時候 2020-12-08 23:17

I have a renderer implementing GLSurfaceView.Renderer interface; a subclass of GLSurfaceView and some classes representing my objects I want to draw. I have the code from ht

3条回答
  •  春和景丽
    2020-12-09 00:17

    I´ve been working with the example from the Android Training, the following approach finally works for me. (Based on Android Training > Displaying Graphics with OpenGL ES > Adding Motion)

    1. Use the correct vertex shader:

      private final String vertexShaderCode =
      // This matrix member variable provides a hook to manipulate
      // the coordinates of the objects that use this vertex shader
      "uniform mat4 uMVPMatrix;" +
      "attribute vec4 vPosition;" +
      "void main() {" +
      // the matrix must be included as a modifier of gl_Position
      "  gl_Position = uMVPMatrix * vPosition;" +
      "}";
      
    2. In the renderer class:

      public class MyGL20Renderer implements GLSurfaceView.Renderer {
      [...]
      // create a model matrix for the triangle
      private final float[] mModelMatrix = new float[16];
      // create a temporary matrix for calculation purposes,
      // to avoid the same matrix on the right and left side of multiplyMM later
      // see https://stackoverflow.com/questions/13480043/opengl-es-android-matrix-transformations#comment18443759_13480364
      private float[] mTempMatrix = new float[16];
      [...]
      
    3. Apply transformations in onDrawFrame, start with translation:

      public void onDrawFrame(GL10 unused) {
      [...]
      Matrix.setIdentityM(mModelMatrix, 0); // initialize to identity matrix
      Matrix.translateM(mModelMatrix, 0, -0.5f, 0, 0); // translation to the left
      
    4. Then rotation:

      // Create a rotation transformation for the triangle
      long time = SystemClock.uptimeMillis() % 4000L;
      float mAngle = 0.090f * ((int) time);
      Matrix.setRotateM(mRotationMatrix, 0, mAngle, 0, 0, -1.0f);
      
    5. Combine rotation and translation, avoid using mModelMatrix

      "as the same matrix on the right and left side of multiplyMM" (see 2)

      // Combine Rotation and Translation matrices 
      mTempMatrix = mModelMatrix.clone();
      Matrix.multiplyMM(mModelMatrix, 0, mTempMatrix, 0, mRotationMatrix, 0);
      
    6. Combine the model matrix with the projection and camera view; again avoid using mModelMatrix

      "as the same matrix on the right and left side of multiplyMM" (see 2)

      // Combine the model matrix with the projection and camera view
      mTempMatrix = mMVPMatrix.clone();
      Matrix.multiplyMM(mMVPMatrix, 0, mTempMatrix, 0, mModelMatrix, 0);
      
    7. Draw the shape

      // Draw shape
      mTriangle.draw(mMVPMatrix);
      

    Thank you all, for all the useful input I could draw from this thread.

提交回复
热议问题