PageRenderTime 50ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/SolarSystem/System.cs

https://bitbucket.org/efouts/solarsystem
C# | 65 lines | 52 code | 13 blank | 0 comment | 2 complexity | 575a26118f9fff1eba4fe5f927af9729 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. using MathNet.Numerics.LinearAlgebra.Double;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using MathNet.Numerics.LinearAlgebra.Generic;
  8. using MathNet.Numerics;
  9. namespace SolarSystem
  10. {
  11. public class System
  12. {
  13. private const Int32 X = 0;
  14. private const Int32 Y = 1;
  15. public IEnumerable<Body> Bodies { get; private set; }
  16. public System(IEnumerable<Body> bodies)
  17. {
  18. Bodies = bodies;
  19. }
  20. public void DoTicks(Double ticks)
  21. {
  22. foreach (var body in Bodies)
  23. DoTicks(body, ticks);
  24. }
  25. private void DoTicks(Body body, Double ticks)
  26. {
  27. var acceleration = GetTotalAccelerationActingOnBody(body);
  28. body.Velocity = body.Velocity.Add(acceleration * ticks);
  29. body.Position = body.Position.Add(body.Velocity * ticks);
  30. var bodyCircumference = 2 * Math.PI * body.Radius;
  31. var rotationPercentage = body.RotationVelocity * ticks / bodyCircumference;
  32. body.Rotation += (360 * rotationPercentage) % 360;
  33. }
  34. private Vector<Double> GetTotalAccelerationActingOnBody(Body body)
  35. {
  36. Vector<Double> totalAcceleration = new DenseVector(new[] { 0d, 0d });
  37. foreach (var otherBody in Bodies)
  38. if (body != otherBody)
  39. totalAcceleration = totalAcceleration + GetAccelerationDueToGravity(body, otherBody);
  40. return totalAcceleration;
  41. }
  42. private Vector<Double> GetAccelerationDueToGravity(Body body, Body otherBody)
  43. {
  44. var differenceVector = otherBody.Position.Subtract(body.Position);
  45. var differenceMagnitude = Math.Sqrt(Math.Pow(differenceVector[X], 2) + Math.Pow(differenceVector[Y], 2));
  46. var differenceUnit = new DenseVector(new[] { differenceVector[X] / differenceMagnitude, differenceVector[Y] / differenceMagnitude });
  47. var accelerationScalar = Constants.GravitationalConstant * otherBody.Mass / Math.Pow(differenceMagnitude, 2);
  48. var accelerationVector = differenceUnit * accelerationScalar;
  49. return accelerationVector;
  50. }
  51. }
  52. }