vector3.vala 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. * Copyright (c) 2012-2026 Daniele Bartolini et al.
  3. * SPDX-License-Identifier: GPL-3.0-or-later
  4. */
  5. namespace Crown
  6. {
  7. [Compact]
  8. public struct Vector3
  9. {
  10. public double x;
  11. public double y;
  12. public double z;
  13. public Vector3(double x, double y, double z)
  14. {
  15. this.x = x;
  16. this.y = y;
  17. this.z = z;
  18. }
  19. public Vector3.from_array(Gee.ArrayList<Value?> arr)
  20. {
  21. this.x = (double)arr[0];
  22. this.y = (double)arr[1];
  23. this.z = (double)arr[2];
  24. }
  25. public Gee.ArrayList<Value?> to_array()
  26. {
  27. Gee.ArrayList<Value?> arr = new Gee.ArrayList<Value?>();
  28. arr.add(this.x);
  29. arr.add(this.y);
  30. arr.add(this.z);
  31. return arr;
  32. }
  33. public double dot(Vector3 b)
  34. {
  35. return this.x * b.x + this.y * b.y + this.z * b.z;
  36. }
  37. public Vector3 cross(Vector3 b)
  38. {
  39. return Vector3(this.y * b.z - this.z * b.y
  40. , this.z * b.x - this.x * b.z
  41. , this.x * b.y - this.y * b.x
  42. );
  43. }
  44. public double length_squared()
  45. {
  46. return dot(this);
  47. }
  48. public double length()
  49. {
  50. return Math.sqrt(length_squared());
  51. }
  52. public Vector3 normalize()
  53. {
  54. double len = length();
  55. double inv_len = 1.0 / len;
  56. this.x *= inv_len;
  57. this.y *= inv_len;
  58. this.z *= inv_len;
  59. return this;
  60. }
  61. public void set_length(double len)
  62. {
  63. normalize();
  64. this.x *= len;
  65. this.y *= len;
  66. this.z *= len;
  67. }
  68. public string to_string()
  69. {
  70. return "%f, %f, %f".printf(x, y, z);
  71. }
  72. public static bool equal_func(Vector3? a, Vector3? b)
  73. {
  74. return a.x == b.x
  75. && a.y == b.y
  76. && a.z == b.z
  77. ;
  78. }
  79. }
  80. public const Vector3 VECTOR3_ZERO = { 0.0, 0.0, 0.0 };
  81. public const Vector3 VECTOR3_ONE = { 1.0, 1.0, 1.0 };
  82. public const Vector3 VECTOR3_MIN = {-double.MAX, -double.MAX, -double.MAX };
  83. public const Vector3 VECTOR3_MAX = { double.MAX, double.MAX, double.MAX };
  84. } /* namespace Crown */