[LAB] Squishies

Real-time soft-body gel physics in Rust/WebAssembly paired with per-pixel WebGPU ray-traced refraction across deforming surfaces, built because my daughter wanted NeeDoh squishies in the browser.

[LAB] Squishies

Launch Web Experience

My daughter is obsessed with squishies right now. NeeDohs, mostly. Some are firm, rounded-edge squares; others are like the one I was holding when I started this, a clear little jello cube that squashes flat under your thumb and springs right back.

She wanted one in the browser. Keep it simple, put a studio gradient behind it, and make it feel good to poke, stretch and throw around. The hard part was that two things had to work together at 60 frames a second. The physics had to behave like thick, nearly incompressible gel under violent pokes and throws without ever tangling or blowing up. And the light had to actually bend through surfaces that change shape every single frame, showing the backdrop and the other cubes warped inside them.

About three seconds into the film above, we freeze a mid-air collision and peel back the frame from the Rust physics cage up to the finished ray-traced gel. Here is how each layer works.

Two meshes from one distance field

You don't want to run soft-body physics directly on a high-resolution render mesh. Seven rounded cubes smooth enough to refract cleanly come to about 28,000 triangles, and solving elasticity on tiny surface triangles is both slow and prone to wrinkling. Instead, each squishy is built once from an exact rounded-box signed distance field (d < 0 inside the gel, d = 0 on the skin) and split into two representations that do different jobs.

Four-stage diagram of one squishy: signed distance field slice, shrink-wrapped 5-tet-per-voxel cage, Surface Nets mesh with barycentric weights, and graph-colored 4-lane SIMD batches
From distance field to SIMD batches, generated directly from the engine's geometry

First, Surface Nets steps across the field at 2.4 cm resolution to build the visible skin. Every vertex is pushed onto the exact d = 0 surface along the field's gradient so its normals come out smooth, and stores its rest position (aRest) so suspended glitter stays locked inside the gel as the cube stretches.

Second, a coarser voxel lattice (7 to 11 cm cells) covers every cell the solid touches and splits each cube into five tetrahedra. Across all seven squishies, that comes to 13,785 tetrahedra. A boxy lattice around a rounded cube would make collisions happen in mid-air before the visible surfaces touch, so the outer cage vertices are pulled inward along the distance field until they sit 8 mm outside the skin.

If you look closely at the cage views, the very outermost corner vertices stick out like little spikes. That's deliberate. Early on, pulling lone lattice corners (shared by two or fewer tetrahedra) onto a rounded bevel created paper-thin sliver elements that jittered at 5 to 8 m/s. Leaving valence-2 corners un-shrunk while rejecting any move that drops a tet below 6% of its lattice volume got rid of the jitter completely.

Finally, every vertex on the visible skin finds the cage tetrahedron that contains it and stores four barycentric weights. During play, the physics worker only solves the coarse cage; on the main thread, each skin vertex reconstructs its world position and smooth normal as a weighted sum of its parent tet's four corners.

The Rust soft-body solver

The simulation runs in squishy-core, a renderer-neutral Rust crate compiled to WebAssembly with 128-bit SIMD (wasm32 simd128, or ARM NEON natively) on a dedicated Web Worker. One 60 Hz tick runs 16 XPBD substeps, or 960 substeps a second, with zero heap allocations per tick in steady state.

Real gel barely changes volume when you mash it; it bulges sideways. Every tetrahedron solves Macklin and Müller's stable Neo-Hookean elasticity as a coupled 2×2 XPBD block:

  • Deviatoric (|F|_F): controlled by the shear modulus μ (30 kPa for the soft jello cube up to 160 kPa for the firm purple square). This sets how easily the shape bends and wobbles.
  • Hydrostatic (det F - γ): controlled by the bulk modulus κ (0.9 to 3.0 MPa), set roughly 30 times stiffer than shear so each tet fights hard to keep its rest volume.
Three views of the clear cube crushed to half height: ray-traced gel, outer cage over skin, and full 5-tet internal lattice bulging sideways
Crushed to half its height on the floor, the clear cube doubles in width against its neighbours while every tet stays well-formed

Using the stable Neo-Hookean form matters whenever you whip-throw a cube into a wall or smack two together mid-air. In classical finite elements, a tetrahedron that flattens or flips inside out (det F ≤ 0) produces singular forces and NaN velocities. Here, the cofactor of the deformation gradient keeps pushing det F smoothly back above zero, so even a completely pancaked element pops right back out on the next substep.

Because Gauss-Seidel XPBD updates vertex positions in place, two tetrahedra that share a corner cannot be solved at the same time. When bodies are added to the world, the schedule graph-colors all 13,785 tetrahedra so no two elements of the same color share a vertex, merges matching colors across all seven bodies, and packs them Structure-of-Arrays style into 32-byte-aligned 4-lane SIMD batches. LLVM doesn't reliably auto-vectorize the coupled element kernel, so the simd128 and NEON lanes are written out by hand. That keeps a full 16-substep tick around 4 to 7.5 ms on a single worker thread.

Order inside each substep is what keeps interactions solid:

  1. Predict: integrate velocity plus either -9.81 m/s² gravity or, in zero gravity, a spring-damper attractor at the centre of the stage (stiffness 3.0, damping 1.2) that pulls all seven cubes into a floating heap.
  2. Elasticity: one Gauss-Seidel pass across all colored SIMD tet batches.
  3. Compliant grabs: up to 48 cage vertices around the pointer attached by critically damped XPBD springs (maxAcceleration = 165 m/s²).
  4. Contacts: soft-on-soft vertex-against-triangle contacts between squishies, then the invisible stage walls, then the floor.
  5. Velocities: v = (x - prev) / h, restitution, deformation damping, and a light settle damper below 0.06 m/s.

Because contacts run after grabs, later passes win. You cannot drag one squishy through another or push it through the floor. Instead, the grab's force cap yields as the local elements lose volume (det F), so pressing down squashes the gel flat and shoves neighbouring cubes out of the way.

Ray tracing through moving gel

Ray-traced glass normally assumes a static acceleration structure, or rigid objects whose bounding boxes move by a matrix. Here, every triangle on every glass surface bends and stretches on every frame.

Six-panel breakdown of one frozen mid-air collision: deformed tet cage, surface normals, 10 cm GPU voxel grid, ray traversal heatmap, pure 6-surface refraction, and floor shadows with coloured gel caustics
One paused GPU tick mid-collision, taken apart across six passes

On WebGPU, RTGrid places a fixed 14 × 6.7 × 8.6 m uniform grid of 10 cm voxels over the stage and rebuilds it from scratch on the GPU every frame before the scene draws (beforeScene passes 20 to 31):

  1. Re-upload the deformed positions and smooth vertex normals of all seven squishies.
  2. Gather world-space triangles inside the box, one GPU thread per triangle, compacted a workgroup at a time.
  3. Count how many triangles overlap each 10 cm cell (with separate wide and big lists for large backdrop triangles), run a parallel prefix scan across the cell counts, and fill the flat triangle reference list.

During the main scene pass, the gel draws opaque into the depth buffer and tags itself as refractive in the G-buffer by writing a negative reflectivity equal to -IOR (-1.34 to -1.40) alongside its linear tint colour (uTint). Non-glass pixels take a single normal-buffer read and exit early.

Right after the scene pass (afterScene), rtgrid.glass runs on every negative-reflectivity pixel. A ray enters the front face with exact dielectric Fresnel (F0 from the cube's index of refraction) and bends by Snell's law (refract(-V, N, 1.0 / IOR)). Inside the grid, it steps through the 10 cm cells to find the exit face on the far side of the deformed cube. Along that interior path, Beer-Lambert absorption (pow(uTint, distance)) deepens the colour by distance, so thin bevels stay water-clear and thick centres go deep ruby, sapphire or lime. At grazing exit angles where refract has no solution, the ray reflects off the inside wall. Otherwise it bends back out into air and keeps marching across up to six glass surfaces per pixel, so you see one squishy bent through a second and a third, with the curved studio sweep warped behind them all.

Three cheaper layers finish the look on top of that traced glass:

  • Subsurface milkiness: thick gel scatters a little light inside itself (1 - exp(-thick * milk)), wrapped around the key light plus a back-lit rim term so backlit cubes glow without turning opaque.
  • Studio specular and 3D glitter: a sharp key softbox (shine = 900, softened on the slightly frosted purple and pink cubes), a secondary fill strip, and procedural flakes hashed in rest space (uCenter-relative cells) that catch glints along the refracted ray.
  • Shadows and coloured caustic cores: tracing full photon caustics onto the sweep every frame wasn't worth the milliseconds, so SquishyGelCommon.glsl pairs each cube's soft directional shadow and contact ring with an analytical caustic focus pool, a bright core of the cube's glow colour shifted slightly toward the key light underneath it.

Estimated vs. ray traced, and keeping 60 fps

Not every screen wants to spend GPU milliseconds marching six bounces per pixel, and WebGL2 has no compute grid at all. So RT starts off by default, and the fragment shader carries a fast analytic stand-in that shares the exact same backdrop lighting code (SquishyGelCommon.glsl).

Side-by-side comparison on the same mid-air tick: RT on with 6-surface ray-traced glass on the left, RT off with the analytic ellipsoid estimate on the right
Same instant: ray-traced multi-surface refraction on the left, the single-pass analytic ellipsoid estimate on the right

Each frame on the CPU, we fit an axis-aligned ellipsoid (uCenter, uHalf) to each deformed mesh's world bounding box. With RT off, the fragment shader refracts the view ray at the real deformed surface normal, solves the far crossing of that fitted ellipsoid in closed form (gelExit), reflects the studio off the inner wall, bends the exiting ray once more, and intersects the curved sweep analytically (sweepHit). You lose seeing one squishy refracted inside another, and it reads a bit softer, closer to gummy candy than wet jello, but it runs locked at 60 fps on phones, WebGL2, and huge monitors.

Turning RT on spins up RTGrid and RTReflections on demand. At 3000 × 1636, the default high preset originally cost 48 ms a frame on the glass pass alone because it traced multiple rough-lobe samples per pixel through eight interfaces. Clear gel doesn't need frosted jitter, so dropping to one path per pixel and six interfaces cut the pass nearly three-fold to 17 ms (4 to 5 ms at 1080p). If a window still holds below 50 fps, the adaptive governor steps down to quarter-resolution tracing with temporal accumulation (6 ms), and large 4K/5K windows cap internal render resolution at a 5.2-megapixel budget and scale cleanly up.

Cubes airborne over the green-gold Soda studio sweep after a double-click floor launch
Gravity on, Soda palette: launching the pile off the floor

Getting the feel right

Physics and refraction only get you halfway if the mouse and touch input fight what your hand meant to do. In the first pass, holding a press for 170 ms turned it into a downward squeeze, and a squeeze could never become a drag. Anyone clicking and hesitating for a tenth of a second before dragging got stuck squashing the cube instead of pulling it.

Now pointerDown attaches the XPBD grab immediately so the squishy follows within 4 pixels of movement. Holding still for 360 ms turns that grab into a deep squeeze toward the cube's centre (and into the floor when gravity is on), while moving past 12 pixels mid-squeeze hands it straight back to a drag. Releasing a fast drag samples the last 95 ms of pointer motion and fires an extra linear and angular kick, so you can whip-flick a cube across the room or hurl it high into the air and watch it crash back into the pile. A quick tap under 280 ms skips the grab and drives a concentrated impulse across up to 64 nearby cage vertices plus an off-centre spin kick, denting the face and sending the cube tumbling. Double-clicking anywhere, or tapping empty background, fires a staggered burst across all seven cubes and cross-fades the studio sweep to the next palette.