vector3.vala 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * Copyright (c) 2012-2021 Daniele Bartolini et al.
  3. * License: https://github.com/dbartolini/crown/blob/master/LICENSE
  4. */
  5. using Gee;
  6. namespace Crown
  7. {
  8. [Compact]
  9. public struct Vector3
  10. {
  11. public double x;
  12. public double y;
  13. public double z;
  14. public Vector3(double x, double y, double z)
  15. {
  16. this.x = x;
  17. this.y = y;
  18. this.z = z;
  19. }
  20. public Vector3.from_array(ArrayList<Value?> arr)
  21. {
  22. this.x = (double)arr[0];
  23. this.y = (double)arr[1];
  24. this.z = (double)arr[2];
  25. }
  26. public ArrayList<Value?> to_array()
  27. {
  28. ArrayList<Value?> arr = new ArrayList<Value?>();
  29. arr.add(this.x);
  30. arr.add(this.y);
  31. arr.add(this.z);
  32. return arr;
  33. }
  34. public double dot(Vector3 b)
  35. {
  36. return this.x * b.x + this.y * b.y + this.z * b.z;
  37. }
  38. public double length_squared()
  39. {
  40. return dot(this);
  41. }
  42. public double length()
  43. {
  44. return Math.sqrt(length_squared());
  45. }
  46. public void normalize()
  47. {
  48. double len = length();
  49. double inv_len = 1.0 / len;
  50. this.x *= inv_len;
  51. this.y *= inv_len;
  52. this.z *= inv_len;
  53. }
  54. public void set_length(double len)
  55. {
  56. normalize();
  57. this.x *= len;
  58. this.y *= len;
  59. this.z *= len;
  60. }
  61. public string to_string()
  62. {
  63. return "%f, %f, %f".printf(x, y, z);
  64. }
  65. }
  66. public const Vector3 VECTOR3_ZERO = { 0.0, 0.0, 0.0 };
  67. public const Vector3 VECTOR3_ONE = { 1.0, 1.0, 1.0 };
  68. public const Vector3 VECTOR3_MIN = {-double.MAX, -double.MAX, -double.MAX };
  69. public const Vector3 VECTOR3_MAX = { double.MAX, double.MAX, double.MAX };
  70. }