MatrixStack.java 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package me.hammerle.snuviengine.api;
  2. public class MatrixStack
  3. {
  4. private final int capacity;
  5. private final float[][] stack;
  6. private int index = 0;
  7. protected MatrixStack(int capacity)
  8. {
  9. this.capacity = capacity;
  10. stack = new float[capacity][16];
  11. stack[index][0] = 1.0f;
  12. stack[index][5] = 1.0f;
  13. stack[index][10] = 1.0f;
  14. stack[index][15] = 1.0f;
  15. }
  16. protected float[] getData()
  17. {
  18. return stack[index];
  19. }
  20. protected void push()
  21. {
  22. index++;
  23. if(index >= capacity)
  24. {
  25. throw new ShaderException("matrix stack overflow, max capacity is " + capacity);
  26. }
  27. System.arraycopy(stack[index - 1], 0, stack[index], 0, 16);
  28. }
  29. protected void pop()
  30. {
  31. if(index <= 0)
  32. {
  33. throw new ShaderException("matrix stack underflow");
  34. }
  35. index--;
  36. }
  37. protected void scale(float sx, float sy)
  38. {
  39. stack[index][0] *= sx;
  40. stack[index][1] *= sx;
  41. stack[index][4] *= sy;
  42. stack[index][5] *= sy;
  43. }
  44. protected void translate(float tx, float ty)
  45. {
  46. stack[index][12] += stack[index][0] * tx + stack[index][4] * ty;
  47. stack[index][13] += stack[index][1] * tx + stack[index][5] * ty;
  48. }
  49. protected void translateTo(float tx, float ty)
  50. {
  51. stack[index][0] = 1.0f;
  52. stack[index][1] = 0.0f;
  53. stack[index][4] = 0.0f;
  54. stack[index][5] = 1.0f;
  55. stack[index][12] = tx;
  56. stack[index][13] = ty;
  57. }
  58. protected void rotate(float angle)
  59. {
  60. angle = (float) Math.toRadians(angle);
  61. float cos = (float) Math.cos(angle);
  62. float sin = (float) Math.sin(angle);
  63. float a1 = stack[index][0];
  64. float a2 = stack[index][4];
  65. stack[index][0] = a1 * cos - a2 * sin;
  66. stack[index][4] = a1 * sin + a2 * cos;
  67. a1 = stack[index][1];
  68. a2 = stack[index][5];
  69. stack[index][1] = a1 * cos - a2 * sin;
  70. stack[index][5] = a1 * sin + a2 * cos;
  71. }
  72. }