BabylonVector3.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. namespace BabylonExport.Entities
  3. {
  4. public class BabylonVector3
  5. {
  6. public float X { get; set; }
  7. public float Y { get; set; }
  8. public float Z { get; set; }
  9. public float[] ToArray()
  10. {
  11. return new [] {X, Y, Z};
  12. }
  13. public float Length()
  14. {
  15. return (float)Math.Sqrt(X * X + Y * Y + Z * Z);
  16. }
  17. public static BabylonVector3 operator +(BabylonVector3 a, BabylonVector3 b)
  18. {
  19. return new BabylonVector3 {X = a.X + b.X, Y = a.Y + b.Y, Z = a.Z + b.Z};
  20. }
  21. public static BabylonVector3 operator -(BabylonVector3 a, BabylonVector3 b)
  22. {
  23. return new BabylonVector3 { X = a.X - b.X, Y = a.Y - b.Y, Z = a.Z - b.Z };
  24. }
  25. public static BabylonVector3 operator /(BabylonVector3 a, float b)
  26. {
  27. return new BabylonVector3 { X = a.X / b, Y = a.Y / b, Z = a.Z / b };
  28. }
  29. public static BabylonVector3 operator *(BabylonVector3 a, float b)
  30. {
  31. return new BabylonVector3 { X = a.X * b, Y = a.Y * b, Z = a.Z * b };
  32. }
  33. public BabylonQuaternion toQuaternionGltf()
  34. {
  35. BabylonQuaternion babylonQuaternion = RotationYawPitchRollToRefBabylon(X, -Y, -Z);
  36. // Doing following computation is ugly but works
  37. // The goal is to switch from left to right handed coordinate system
  38. // Swap X and Y
  39. var tmp = babylonQuaternion.X;
  40. babylonQuaternion.X = babylonQuaternion.Y;
  41. babylonQuaternion.Y = tmp;
  42. return babylonQuaternion;
  43. }
  44. /**
  45. * (Copy pasted from babylon)
  46. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  47. */
  48. private BabylonQuaternion RotationYawPitchRollToRefBabylon(float yaw, float pitch, float roll)
  49. {
  50. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  51. var halfRoll = roll * 0.5;
  52. var halfPitch = pitch * 0.5;
  53. var halfYaw = yaw * 0.5;
  54. var sinRoll = Math.Sin(halfRoll);
  55. var cosRoll = Math.Cos(halfRoll);
  56. var sinPitch = Math.Sin(halfPitch);
  57. var cosPitch = Math.Cos(halfPitch);
  58. var sinYaw = Math.Sin(halfYaw);
  59. var cosYaw = Math.Cos(halfYaw);
  60. var result = new BabylonQuaternion();
  61. result.X = (float)((cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll));
  62. result.Y = (float)((sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll));
  63. result.Z = (float)((cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll));
  64. result.W = (float)((cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll));
  65. return result;
  66. }
  67. }
  68. }