// MyRenderer.java
package opengl.tetrahedron1;

import android.content.Context;
//import android.graphics.Matrix; not the right one
import android.opengl.Matrix;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.view.MotionEvent;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public class MyRenderer implements GLSurfaceView.Renderer 
{
  // Model-view projection matrix
  private final float[] mvpMatrix = new float[16];
  private final float[] projectionMatrix = new float[16];
  private final float[] viewMatrix = new float[16];
  private final float[] rvMatrix = new float[16];  // view matrix with rotation
  private float angle = 0;  // angle of rotation
  
  private Tetrahedron tetrahedron;
  private Context context;

  public MyRenderer( Context context0 )
  {
     context = context0;
  }
  
  public void onSurfaceCreated(GL10 unused, EGLConfig config) {
    // Set the background frame color
    GLES20.glClearColor(0.9f, 0.9f, 0.9f, 1.0f);
    GLES20.glEnable(GLES20.GL_CULL_FACE);
    GLES20.glCullFace(GLES20.GL_BACK);
    GLES20.glFrontFace(GLES20.GL_CCW);
     
    GLES20.glEnable ( GLES20.GL_DEPTH_TEST );
    GLES20.glDepthFunc(GLES20.GL_GREATER);  //larger z values, nearer to viewpoint
    // Construct a Tetrahedron object 
    tetrahedron = new Tetrahedron ( context );
  }

  public void onDrawFrame ( GL10 unused ) {
    // Redraw background color
    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
    // Set the camera position (View matrix)
   Matrix.setLookAtM(viewMatrix, 0, 0.5f, 0.5f, 5, 0f, 0f, 0f, 0f, 1f, 0.0f);
   // Multiply view matrix by rotation matrix, result in rvMatrix
   Matrix.rotateM ( rvMatrix, 0, viewMatrix, 0, angle, 1f, 0.2f, 0.2f );
  // Matrix.setRotateM( rotateM, 0, angle, 1, 0.2f, 0.2f);

    // Calculate the projection and view transformation
    //Matrix.multiplyMM(mvpMatrix, 0, projectionMatrix, 0, viewMatrix, 0);
    Matrix.multiplyMM(mvpMatrix, 0, projectionMatrix, 0, rvMatrix, 0);
    // Draw the object with the transformation matrix
    tetrahedron.draw( mvpMatrix );
  }

  public void onSurfaceChanged(GL10 unused, int width, int height) {
     float ratio = (float) width / height;
     GLES20.glViewport(0,  0, width,  width  );
     Matrix.frustumM( projectionMatrix, 0, -1, 1, -1, 1, 3, 10);
  }
  
  // Get and set angle of rotation 
  public float getAngle() {
      return angle;
  }
 
  public void setAngle(float angle0) {
      angle = angle0;
  }

}
