Activity

grumpymarie

ADDED FIGURE-8, FIXED BARNES-HUT & VERLET INTEGRATION!!

0
grumpymarie

ADDED BARNES-HUT ALGORITHM AND VELOCITY VERLET INTEGRATION!!

THE PROBLEM:

  • before this update, every body in the simulation would calculate the gravitational pull from every other body, which is force evaluations per step.
  • I am thinking of adding galaxy collisions next, and for a galaxy with a 100 stars, O(n²) isnt great, it would lag a lot and would even more on a higher timescale.

    THE SOLUTION: BARNES-HUT
  • good news tho! this problem has already been solved cuz its really well known in astrophysics.
  • the solution is to treat distant groups of stars as a single mass. a cluster of stars about 50 AU away pulls on an object almost the same way whether you calculate each one individually or use the entire cluster’s total mass at its centre of mass (COM). the error is miniscule. and it becomes O(n log n).

    BARNES HUT ALGORITHM:
  • barnes-hut requires building a quadtree over all the bodies at the start of each step. then the tree sub-divides into quadrants until each cell contains at most one body. then for each body, you walk the tree. if a cell is far enough that its angular size is below a threshold θ (0.5 in this case), you stop recursively calling and treat the whole cell as a point mass. if its too close, you continue. the approximation error is a great deal under 1% and its O(n log n) from O(n^2). a great deal faster!

    THE PROBLEM:
  • energy conservation using RK4 integration is very accurate but not symplectic. in a conservative system you want an integrator that preserves the geometric structure of the physics. without that, the errors leak energy in and out of the system, which means if you run a two-body orbit for a long time, with a non-symplectic integrator and it would spiral or drift because of floating point errors adding up over time.

    THE SOLUTION: VELOCITY VERLET is symplectic.
  • velocity verlet is a lot simpler than RK4, half-kick the velocity with the old accelaration, drift the position, recalc. acceleration, and then half kick again.
  • its called “symplectic” because it conserves energy for a long time which means orbits stay stable which is important for galaxy collisions.
  • toggles for both barnes-hut and velocity verlet are independent and you can run any combo of integrator and force method. RK4 and direct force calculation stay the same, but you do get the option to switch! (velocity verlet and barnes-hut will be auto-toggled on for some presets, but you can toggle it off, at your own risk ofc- your browser will lag).
  • minor bug fixes- the velocity vectors were a bit too small, so I scaled them a tiny bit up, there was also a bug in the energy panel readout, so I fixed that aswl.
Attachment
Attachment
0
grumpymarie

Shipped this project!

Hours: 10.39
Cookies: 🍪 359
Multiplier: 28.79 cookies/hr

ADDED LAGRANGE POINTS

What are lagrange points?
The n-body problem asks how N objects move under gravitational forces, but what about a point where an object stays still?

In the rotating reference frame of a two body system (consider Sun-Earth), there are five points where gravity from both bodies and the centrifugal force (psuedo-force) of the frame all cancel out.

This simualation visualises these five lagrange points for five systems (Sun-Earth, Earth-Moon, Sun-Jupiter, Sun-Mars, Sun-Venus) and shows a heatmap for effective potential in the background as well. The secondary body is also animated, and orbits around the primary body.

I learnt a lot building this, like the pseudo forces (centrifugal forces) acting on the frame and how it plays a role in the effective potential calculation (didnt know about this)

One challenge I faced that took a lot of time to fix, was the potential heatmap not rendering and the canvas zooming in infinitely.

grumpymarie

UPDATED README, REPLACED PLACEHOLDER TEXT, AND FIXED CSS BADGES

  • updated readme to reflect new simulation “Lagrange Points” being added.
  • replaced all mentions of placeholder text or lorem ipsum dorem with appropriate text.
  • changed nbody, hohmann and index to include lagrange points page in the nav-bar.
  • fixed orbit and stability of L4/L5 not being shown in the system panel readout.

    UPDATE: I removed the animation toggle, because the animation playing or not can be paused or played using the speed slider. I couldn’t devlog this change as it was less than 15 mins. (images do not reflect this change, but it is a minor one, so you can test it in the demo)
Attachment
Attachment
Attachment
Attachment
Attachment
Attachment
0
grumpymarie

SOME POLISHING AND CSS CHANGES:

  • the newton() function defined inside solveLP() got redefined on every call, so I moved it out. I also added a condition to avoid singularities.
  • fixed the canvas zooming in infinitely on refresh - that took maybe an hour :(
Attachment
0
grumpymarie

ADDED ORBIT ANIMATION, POTENTIAL HEATMAP AND MORE SYSTEMS!!

EFFECTIVE POTENTIAL HEATMAP:

  • in the rotating reference frame, you can define an effective potential, a scalar field that adds the gravity from both bodies with the centrifugal term (Ω(x,y) = -½(x² + y²) - (1-μ)/r₁ - μ/r₂). the five Lagrange points, as stated in the prev. devlog, are the saddle points of this field.
  • this allows to visualise why the points exist, cuz bfr I was only showing their positions.
  • the potential is sampled at every pixel on the grid and mapped to a blue color ramp and then written to an offscreen canvas usingImageDAta, pixel by pixel (doing it using shapes takes too long)
      
    ORBIT ANIMATION:
  • added orbit animation!!! now m2 moves around m1. the lagrange points also move since theyre relative to both bodies.
  • also added a stability indicator, L4 and L5 are only stable if the mass ratio is > 25. below thats the equilateral points are also unstable. the panel shows green or red if the system selected satisfies this.

    ADDED 4 SYSTEMS:
  • added Earth-Moon, Sun- Jupiter Sun-Mars and Sun-Venus systems as well. the sidebar also shows examples and a bit about each lagrange point in the system as well!
1

Comments

Slayer
Slayer 14 days ago

seems nice

grumpymarie

ADDED LAGRANGE POINTS!!

WHAT ARE LAGRANGE POINTS?
yet again, im so happy you asked this!

  • in a two body system, lets consider the sun and earth there are five special positions where a third smaller body (think asteroids, satellites) can sit in a stable (or semi-stable) position relative to the system. this basically means it doesnt move, without requiring constant engine burns.
  • eg: at L2:- James Webb Telescope, L4/L5- Trojan asteroids.

    ROTATING REFERENCE FRAME:
  • Lagrange points only exist in a rotating reference frame, this means that if you look at the sun-earth system from a frame that rotates with the Earth’s orbit, both bodies appear at rest.
  • in this frame, you get pseudo-forces, centrifugal force and the coriolis force, and when they are added to gravity, the resulting effective potential has five saddle points. those are Lagrange points.

    L1, L2, L3:
  • L1, L2, L3 lay on the line connecting the two bodies. there positions come from the variations of the equation of effective potential, again, there is no closed form solution for these equations so I solved them numerically using Newton-Raphson method (see devlog for Hohmann transfer, its used for Kepler eq.).
  • for L1 and L2 the initial guess uses Hill sphere radius (∛(μ/3)), which is the approx radius of the sphere where m2’s gravity is dominating. this allows for a starting point for the iteration to converge.

    L4/L5
  • L4 and L5 sit at the vertices of equilateral triangles formed with the two masses, so their positions are (0.5 - μ, ±√3/2). there is no further solving required for these.

    MU PARAMETER:
  • everything in the frame is normalised using one parameter, mu (reduced mass ratio- μ = m₂ / (m₁ + m₂))
  • for the sun-earth system, mu will be very small as the sun is so much bigger in comparison.
  • all five langrange points are then functions of mu which means the same thing works for any two body by changing the mass ratio.
Attachment
0
grumpymarie

Shipped this project!

Hours: 22.55
Cookies: 🍪 605
Multiplier: 26.82 cookies/hr

I built Gravitas, an orbital mechanics simulator. it includes two simulations, n-body gravity and hohmann transfer.

N-BODY SIM.:
the n-body problem is: given N objects that all gravitationally attract each other at the same time, how do they move?
there is no closed form solution for N>=3 bodies, so you have to simulate it step by step. This simulation aims to do this.

There are two presets, a solar system and a binary stars preset, and using the simulation you can add bodies to these presets and watch them intereact with each other (merge, collide, eject out of threshold)

HOHMANN TRANSFER CALC. and VISUALISATION:
this is the 2nd sim, a hohmann trasfer is the most efficient way to move a spacecraft b/w two orbits. i tried to simulate this for two modes: planet to planet transfer and satellite transfer. you can read more about this in the devlogs.
NOTES: this took a lot of time and effort, please vote fairly!!

What did i learn?

  • i learnt rk4 order integration , newton-raphson method, vis-viva equation, in short a lot of physics and EVEN MORE MATH. but i truly did enjoy making it and all’s well that ends well, right?

IMP NOTE!!: if you toggle on track COM for the n-body sim. you will not be able to pan cuz you are tracking the centre of mass.
NOTES: this took a lot of time and effort, please vote fairly!!

grumpymarie

SMALL FIXES, FAVICON AND README!! FINAL DEVLOG BEFORE SHIPPING

  • replaced placeholder text
  • fixed minor css bugs (gravitas, written on the navbar of the Hohmann page, was grey instead of intended green)
  • added favicon
  • added README
Attachment
Attachment
Attachment
Attachment
Attachment
0
grumpymarie

ADDED ANIMATIONSS KEPLER SOLVER AND BADGES!!

ANIMATIONS:

  • finally added the canvas animation!! now you can see the bodies involved in the transfer moveee

    KEPLER SOLVER:
  • PROBLEM: I was moving the spacecraft at a const. angular speed along the ellipse. because of that, it was moving too fast near the sun, and too slow at the far end.
  • ideally, the spacecraft should move fast at periapsis and slower at apoapsis (Kepler’s 2nd law: equal areas swept in equal times)
  • FIX: I needed to convert mean anomaly to true anomaly, because mean anomly increases linearly with time, which is what I had. true anomaly is the actual angle.
  • the relationship between them goes thru eccentric anomaly thru Kepler’s eq. (M = E - e·sin(E)). but you cant solve directly for E so I had to implement Newton-Raphson Iteration.
  • also added a trail, which draws the last N steps of the path with increasing opacity.

    BADGES:
  • also added a phase badge that shows current state of the mission (WAITING, BURN 1, BURN 2, ARRIVED.)

    SLIDER:
  • added animation speed slider to control the speed of the animation.
  • I had to scale the the real elapsed time by speedMult × (transferDays / 20) so a slow transfer and a fast one would take about the same time real life time (at normal speed). otherwise, earth to mercury wld barely be visible and earth to Neptune would take FOREVER.

    BUG FIXES:
  • fixed the scaling bug which was causing the centre body become massive and eat the inner orbit. clamped the body radius to 35% of the inner orbit radius.
0
grumpymarie

SATELLITE MODE!!!!

PROBLEM: the planet to planet tab works in AU and yrs which is fine for interplanetary transfers but not for satellites cuz then AU doesnt work and you need km. so I added another mode.

THE FIX:

  • planet to planet remains the same but I added another tab: Satellite mode.
  • added buttons to pick the central body
  • add type in field to enter both altitudes and angle
  • the vis-viva eq we discussed before remains the same but now uses μ instead of the AU version.

    INCLINATION:
  • PROBLEM: the planet tab assumes that all orbits are coplanar , satellite manoeuvres however also require a plane change
  • FIX: combined the plane change with the second burn. this can be done using the law of cosines √(vt² + vc² - 2·vt·vc·cos(Δi)) - vc

    DEFAULTS:
  • each body has its default values when you select it.

    BUG FIXES:
  • If you call offsetWidth on a panel that was just visible, it read zero. requestAnimationFrame delay fixed that.
Attachment
0
grumpymarie

HOHMANN TRANSFER!!

What even is a Hohmann transfer?
THANK GOD YOU ASKED CUZ I HAVE A BUNCH OF UNTRACKED RESEARCH TIME TO SHOWCASE

  • its the MOST efficient way to move a spacecraft b/w two circular orbits. you fire the engine twice, once to leave the first orbit and enter an elliptical transfer orbit, and once when you arrive at the second orbit to circularise.
  • missions you know and have heard about use this. the mars transfer windows and stuff… this is it.

    MATH:
  • the eq is the vis-viva eq. v = √(GM(2/r - 1/a)). it gives you the speed for the object at any point in the orbit. because for a circular orbit r = a, the equation can be simplified to v = √(GM/r).
  • a Hohmann transfer has one focus at the sun, periapsis touching the inner orbit and apoapsis touching the outer one. so, on the canvas the sun is the centre, and the ellipse isnt centred but offset by a focal distance (c = ecc * a). so, to account for that we docx - c before drawing the ellipse.⠀

    PLANET BUTTONS:
  • added buttons to pick the arrival and departure planet
  • you cant pick the same arrival and departure planet (added classList.toggle('disabled'))

    CANVAS:
  • started drawing the orbits for the transfer
  • the two delta-v burn points are marked with points, amber for departure and blue for arrival (labelled).
  • the arrival planet is placed at the phase angle (the angle is needs to be at so it arrives at the right spot)
  • the stars on the canvas are seeded deterministically rather than than Math.random(), so they stop flickering every time the canvas redraws.
Attachment
Attachment
0
grumpymarie

ADDED LANDING PAGE + BUG FIXES!!

LANDING PAGE:

  • added a landing page (finallyy!!)
  • the background is a live canvas animation (see attached video)
  • a twinkling stars background aswl
  • a card list listing all the sims available (nbody, and Hohmann -to come)

    CUSTOM CURSOR:
  • added a custom cursor, a small green dot
  • on hover, it becomes bigger with a glow

    BUG FIXES:
  • fixed the font in nbody + some other small fixes

for now, all the text is just placeholder text, but I plan on changing that right bfr shipping

0
grumpymarie

CSS UPDATES, BINARY STAR PRESET, VELOCITY VECTORS… AND MORE

CSS:

  • rewrote the css with a sticky navbar, blinking status, diff button types, panel components, badges, a scanline overlay, etc.
  • also restructured nbody.html

    ENERGY PANEL:
  • PROBLEM: now how would YOU know the simulation is working right?
  • FIX: YOU TRACK ENERGY CONSERVATION! if the energy drifts too far from its initial value, then the integrator is accumulating error.
  • added energy panel to show kinetic energy, potential energy, total energy and angular momentum.
  • also added a little bar at the bottom of the panel that shows how much the total energy has drifted from its initial value

    BINARY STARS PRESET:
  • added the binary stars preset
  • this took A LOT of UNTRACKED time. It took so much research but I’ll try to summarise why this took me so much time.

    basically for this preset, two stars need to orbit their shared centre of mass, not the origin . so, you have to calculate where the star sits relative to its barycentre.
    the orbital velocities were also headache inducing to get right. you need the relative velocity of the circular orbit and then each star gets a fraction of that.

    VELOCITY VECTORS:
  • each body gets an arrow showing the direction and the magnitude of its velocity.

    GRID:
  • add a grid toggle because it gives a sense of scale, each square is one AU. (I got lost on the canvas and each body I placed was outside 50 AU and so I had to reset the sim.)

    COM Tracking:
  • added centre of mass tracking. the camera follows the system,’s barycentre (barycentre: mass weighed av. position)
  • I kept getting the sign wrong because of the flipped y-axis.

    ADAPTIVE SUBSTEPS:
  • when bodies get close to each other the integrator auto. takes smaller and smaller step to maintain accuracy.

    CONTROLS?
  • added play, pause, step, and a timescale slider.
0
grumpymarie

COLLISIONS, SOFTENING, CLICK-TO-ADD BODIES AND TRAILS
‎⠀
COLLISIONS:

  • PROBLEM: bodies were just passing through each other, so COLLISIONS.
  • FIX: added inelastic merging for collisions. when a bigger body gets closer to the smaller one it swallows it and gets bigger (radius is capped however)

    BODY ESCAPING:
  • also added a body ejection threshold and notification, so when a body escapes beyond 50AU, it disappears and you get a notification for the same.

    SOFTENING:
  • PROBLEM: when two bodies got close to each other the force calculation would tend to infinity (dividing by distance approaching zero, causes acceleration to tend to infinity and bodies go ZOOMINGGG)
  • FIX: add a ε² term (0.001) to the denominator of the force eq. , so it never reaches 0 (or tends to 0).

    CLICK-TO-ADD BODIES:
  • when you click anywhere on the canvas (not beyond 50AU tho), a new body is added over there.
  • I also added option for the size of the body (try adding a star, a lot of things happen then… OOOH GRAVITY)
  • also added a dropbox to pick HOW the body is added. basically, most of the time a body with Zero Velocity will fall into the nearest star. so I added Random and Circular Orbit. The default mode, Circular Orbit computes circular orbital velocity at that point, relative to the nearest massive body. Orbit eccentricity can also be adjusted, which leads to more keplerian orbits.

    TRAILS:
  • each body keeps a history of its prev. 500 positions and I connect them using a using a line. the trail also fades gradually as it is tied to how old the point is.
0
grumpymarie

ADDED RK4 INTEGRATION AND CAMERA CONTROLS
‎‎‎‎

  • Euler was causing energy drift so added replaced with fixed step RK4.
  • getDerivs() temporarily overwrites positions so accel() can be evaluated at intermediate stages, then it restores them. (this took me so long to figure out… the bodies were teleporting because I forgot to restore.)
  • you couldnt see outer planets before, so I added cursor anchored zoom and pan
    ‎‎
    so now…, you can see all the planets (and bodies in the future) cuz I added zoom and pan.
    orbits are now stable long term!!
    ‎‎‎
    TODO:
  • add gravitational softening
  • add new bodies on click
  • add trails behind bodies
Attachment
Attachment
0
grumpymarie

WE NOW HAVE 5 BODIES!!! AND THEY MOSTLY OBEY THE LAWS OF PHYSICS!!

  • added Sun, Mercury, Venus, Mars and Earth.
  • labeled bodies
  • gravity calculated b.w every pair of bodies
  • set G = 4π², stable orbits.
  • added integration using Euler method, so velocity and position update by (dt).
  • real time to sim. time scaling (1 sec = 0.05yrs in sim. time)
  • background changes (stars)
  • sim. time in corner

    basically we got more planets, stable orbits, with gravity working for multiple bodies anddd speeds look realistic relative to each planet.

    TODO:
  • SWITCH TO BETTER INTEGRATION METHOD FOR ENERGY STABILITY (RK4.. or velocity verlet)
  • add trails behind bodies
  • update and add back the navbar that I removed in this version

    ramblings..
    I have a rough idea on how to add the bodies (like the user adds the bodies… the actual point of this sim). ive also kinda figured out how to implement binary stars, so in theory, at least, I know what to do!!
Attachment
0
grumpymarie

MADE BLUE DOT GO WHEE AROUND YELLOW DOT
‎‎‎‎‎‎‎‎‎‎‎‎
set up canvas and render loop now works!!
then added two bodies:

  • sun in the middle
  • small blue body orbiting it with sideways velocity.
Attachment
0