2D & 3D Physics Solvers & Numerical Integration

โš™๏ธ 2D & 3D Physics Solvers & Numerical Integration

In custom game engines (built with Odin and Vulkan), physics engines simulate motion, collisions, and constraints through Numerical Integration.

Understanding the trade-offs between Euler Integration, Verlet Integration, and Runge-Kutta (RK4) allows you to choose the right solver for rigid bodies, cloth, particles, and vehicles.


๐Ÿงฎ 1. Numerical Integration Methods

Integration computes an entity's new position xt+dt from its current velocity vt and acceleration at:

+-------------------------------------------------------------+
| 1. Explicit / Forward Euler (Fastest, Highly Unstable)      |
|    v += a * dt;   x += v * dt;                              |
+-------------------------------------------------------------+
                              โ”‚  (Accumulates energy / explodes)
                              โ–ผ
+-------------------------------------------------------------+
| 2. Semi-Implicit / Symplectic Euler (Standard for Game Dev) |
|    v += a * dt;   x += v_new * dt;                          |
+-------------------------------------------------------------+
                              โ”‚  (Preserves energy over time)
                              โ–ผ
+-------------------------------------------------------------+
| 3. Verlet Integration (Ideal for Cloth, Ropes, Ragdolls)    |
|    x_new = 2*x - x_old + a * dt^2;                          |
+-------------------------------------------------------------+

Semi-Implicit Euler Implementation in Odin

integrate_body :: proc(body: ^Rigid_Body, gravity: [3]f32, dt: f32) {
    if body.is_static do return

    // 1. Calculate acceleration from forces
    inv_mass := 1.0 / body.mass
    acceleration := (body.force * inv_mass) + gravity

    // 2. Update velocity first
    body.velocity += acceleration * dt
    body.velocity *= (1.0 - body.linear_drag * dt) // Simple damping

    // 3. Update position using the NEW velocity
    body.position += body.velocity * dt

    // Reset accumulated forces for next tick
    body.force = {0, 0, 0}
}

๐Ÿงต 2. Verlet Integration & Position-Based Dynamics (PBD)

Verlet integration does not store velocity explicitly. Instead, velocity is implicitly derived from the difference between the current position and the previous position:

xt+ฮ”t=2xtโˆ’xtโˆ’ฮ”t+atฮ”t2

Why Verlet Excels for Constraints (Cloth & Ropes)

When simulating distance constraints (e.g. rope links or cloth springs), Verlet allows you to simply project positions directly to satisfy distance limits without modifying velocity states:

solve_distance_constraint :: proc(p1, p2: ^Particle, target_distance: f32) {
    delta := p2.position - p1.position
    current_dist := linalg.length(delta)
    if current_dist == 0.0 do return

    // Percentage error
    diff := (current_dist - target_distance) / current_dist
    
    // Push particles apart or pull together
    p1.position += delta * 0.5 * diff
    p2.position -= delta * 0.5 * diff
}

๐Ÿ“ฆ 3. Broad-Phase vs Narrow-Phase Collision Detection

Simulating 1,000 entities naively requires O(N2)=1,000,000 collision checks per frame. Real-time physics engines split detection into two phases:

[ All Scene Entities ] โ”€โ”€> [ Broad-Phase: Spatial Hash / BVH / AABB ]
                                           โ”‚ (Prunes 99% of pairs)
                                           โ–ผ
                               [ Narrow-Phase: SAT / GJK / EPA ]
                                           โ”‚ (Exact contact points & normals)
                                           โ–ผ
                               [ Impulse Solver / Manifold Resolution ]
  1. Broad-Phase (Fast & Rough):
    • Uses AABB (Axis-Aligned Bounding Boxes) organized in a Dynamic Bounding Volume Hierarchy (BVH) or Spatial Grid/Hash.
    • Quickly rejects objects that are nowhere near each other.
  2. Narrow-Phase (Exact & Geometric):
    • SAT (Separating Axis Theorem): Tests whether a separating plane exists between convex 2D/3D polyhedra.
    • GJK (Gilbert-Johnson-Keerthi): Finds the minimum distance between arbitrary convex shapes in 3D using Minkowski differences.
    • EPA (Expanding Polytope Algorithm): Computes penetration depth and contact normal when GJK detects overlap.

โšก 4. Sequential Impulse Resolution (Penetration & Restitution)

Once a collision manifold with normal n and penetration depth d is detected, the solver applies an instantaneous Impulse (J):

J=โˆ’(1+e)(vrelโ‹…n)1m1+1m2