vector4.vala 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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 Vector4
  9. {
  10. public double x;
  11. public double y;
  12. public double z;
  13. public double w;
  14. public Vector4(double x, double y, double z, double w)
  15. {
  16. this.x = x;
  17. this.y = y;
  18. this.z = z;
  19. this.w = w;
  20. }
  21. public Vector4.from_array(Gee.ArrayList<Value?> arr)
  22. {
  23. this.x = (double)arr[0];
  24. this.y = (double)arr[1];
  25. this.z = (double)arr[2];
  26. this.w = (double)arr[3];
  27. }
  28. public Gee.ArrayList<Value?> to_array()
  29. {
  30. Gee.ArrayList<Value?> arr = new Gee.ArrayList<Value?>();
  31. arr.add(this.x);
  32. arr.add(this.y);
  33. arr.add(this.z);
  34. arr.add(this.w);
  35. return arr;
  36. }
  37. public double dot(Vector4 b)
  38. {
  39. return this.x * b.x + this.y * b.y + this.z * b.z + this.w * b.w;
  40. }
  41. public double length_squared()
  42. {
  43. return dot(this);
  44. }
  45. public double length()
  46. {
  47. return Math.sqrt(length_squared());
  48. }
  49. public void normalize()
  50. {
  51. double len = length();
  52. double inv_len = 1.0 / len;
  53. this.x *= inv_len;
  54. this.y *= inv_len;
  55. this.z *= inv_len;
  56. this.w *= inv_len;
  57. }
  58. public void set_length(double len)
  59. {
  60. normalize();
  61. this.x *= len;
  62. this.y *= len;
  63. this.z *= len;
  64. this.w *= len;
  65. }
  66. public Vector3 to_vector3()
  67. {
  68. return Vector3(this.x, this.y, this.z);
  69. }
  70. public string to_string()
  71. {
  72. return "%f, %f, %f, %f".printf(x, y, z, w);
  73. }
  74. }
  75. public const Vector4 VECTOR4_ZERO = { 0.0, 0.0, 0.0, 0.0 };
  76. public const Vector4 VECTOR4_ONE = { 1.0, 1.0, 1.0, 1.0 };
  77. } /* namespace Crown */