Guest User

Matrices.java

a guest
Apr 12th, 2013
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.91 KB | None | 0 0
  1. package base;
  2.  
  3. import static org.lwjgl.opengl.GL20.glUniformMatrix4;
  4. import static org.lwjgl.opengl.GL20.glUseProgram;
  5.  
  6. import java.nio.FloatBuffer;
  7.  
  8. import org.lwjgl.BufferUtils;
  9. import org.lwjgl.util.vector.Matrix4f;
  10. import org.lwjgl.util.vector.Vector3f;
  11.  
  12. public class Matrices {
  13.     public static Matrix4f perspectiveMatrix, viewMatrix, modelMatrix;
  14.     public static int perspectiveMatrixLocation, viewMatrixLocation, modelMatrixLocation;
  15.     public static void setupPerspective(float fieldOfView, float WIDTH, float HEIGHT, float zNear, float zFar){
  16.         perspectiveMatrix = new Matrix4f();
  17.         perspectiveMatrix.setIdentity();
  18.        
  19.         float aspectRatio = WIDTH / HEIGHT;
  20.         float zRange = zNear - zFar;
  21.          
  22.         perspectiveMatrix.m00 = (float) (1.0f / (aspectRatio * Math.tan(degreesToRadians(fieldOfView / 2.0f))));
  23.         perspectiveMatrix.m11 =  (float) (1.0f / (Math.tan(degreesToRadians(fieldOfView / 2.0f))));
  24.         perspectiveMatrix.m22 = (-zNear - zFar) / zRange;
  25.         perspectiveMatrix.m23 = 1;
  26.         perspectiveMatrix.m32 = (2 * zFar * zNear) / zRange;
  27.     }
  28.    
  29.     public static void setupModel(){
  30.         modelMatrix = new Matrix4f();
  31.         modelMatrix.setIdentity();
  32.     }
  33.    
  34.     public static void uploadMatrices(int shaderProgramId, int perspectiveMatrixLocation, int viewMatrixLocation, int modelMatrixLocation){
  35.         FloatBuffer matrix44Buffer = BufferUtils.createFloatBuffer(16);
  36.         glUseProgram(shaderProgramId);
  37.             perspectiveMatrix.store(matrix44Buffer);
  38.             matrix44Buffer.flip();
  39.             glUniformMatrix4(perspectiveMatrixLocation, false, matrix44Buffer);
  40.            
  41.             viewMatrix.store(matrix44Buffer);
  42.             matrix44Buffer.flip();
  43.             glUniformMatrix4(viewMatrixLocation, false, matrix44Buffer);
  44.            
  45.             modelMatrix.store(matrix44Buffer);
  46.             matrix44Buffer.flip();
  47.             glUniformMatrix4(modelMatrixLocation, false, matrix44Buffer);
  48.         glUseProgram(0);
  49.     }
  50.    
  51.     public static float degreesToRadians(float angle){
  52.         return angle * (float)(Math.PI / 180d);
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment