# Limp Ninja – "Ersatz" (party version, 2008) — WebGL reconstruction

A browser re-implementation of the 2008 PC demo, rebuilt from the release's executable and data files.
The YouTube capture was used only to check the result. Run it from a local web server:

    python3 reconstruction/tools/serve.py 8765        # then http://localhost:8765

(`python3 -m http.server 8765 -d reconstruction` works too; `serve.py` adds no-cache headers.)

Keys: space pauses, ←/→ seeks 5 s (with shift: one frame), R restarts, F full screen, N toggles native 1280×720.
`?t=52.1` starts at a time; `&freeze` starts paused without the click-to-start overlay.

Two explorers sit next to the player:

- **`exe/`**: executable explorer. PE header and rich header, a section map with entropy, all 459 functions with
  annotated disassembly (imports, strings, float constants and globals named inline), callers and callees, a call graph,
  imports with their callers, strings with cross-references, RTTI classes and vtables, the scene timeline, and a hex view.
- **`assets/`**: asset explorer.
  - Every image, shown both as the file holds it and as the exe's texture loader turns it, with the pixels the loader wraps marked.
  - The models in a viewer, with an `explode.vert` slider.
  - Every shader's original GLSL next to its WebGL 2 port, including the four inline shaders and the editor backups (`*~`) that shipped with the release.
  - The song, with the spectrum values the demo reads.

## What was recovered, and from where

| Source | Contents | How it's used |
|---|---|---|
| `schuifkaas.exe` | MSVC 2008 Win32, 104 KB, linked 2008‑08‑26, `c:\code\ersatz\Release\ersatz.pdb`. SDL + SDL_image, OpenGL 2.0 / GLSL, GLU, FMOD Ex | Disassembled with capstone (`tools/disasm.py`). Every scene's constructor and draw function were decompiled by hand into `notes/*.md`, then ported to `js/scenes.js` |
| `shaders/*.vert, *.frag` | 16 GLSL 1.10 files, plus 13 editor backups | Ported to GLSL ES 3.00 in `js/shaders.js`. Fixed-function built-ins are supplied by `js/glx.js` |
| inline shader strings in the exe | The love scene's blob vertex and fragment shaders, and the Circle Cluster's vertex, fragment and geometry shaders | Blob shaders ported; the cluster is never drawn |
| `images/*.png`, `limpninja-ersatz-colored.png` | 14 images (2048×1024 photos, 1024² sprites) | Passed through the exe's loader transform by `tools/build.py` → `data/img` |
| `models/*.raw` | Text meshes: one quad per line, 12 position floats then 12 normal floats | Parsed in the browser, as the exe does |
| `song.ogg` | Lackluster's soundtrack, 44.1 kHz, 119.07 s | `music.mp3`. The clock, and the source of the per-frame spectrum |

`tools/gen_exe.py` writes `exe/data.json` and `exe/disasm.json` from the exe and `tools/labels.json` (the function names and
descriptions, which come from the decompilation). `tools/build.py` writes `data/` and `music.mp3`.

## How the exe works

**Clock.** `main` opens a 1280×720 window (4× MSAA, 8-bit alpha), starts `song.ogg` in FMOD, constructs every scene, and loops:
`t = Channel::getPosition(ms) / 1000`, `Channel::getSpectrum(256 floats, channel 0, triangle window)`, draw, swap.
There is no frame counter and no delta time: everything is a function of `t`, apart from the love scene's grid, which is rebuilt every frame.

**Running order.** `DrawFrame(t)` clears, sets `gluPerspective(90°, 16:9, 0.1, 1000)` and a gently swaying
`gluLookAt(0.5 sin 0.4t, 0.2 cos 0.2t, 1.5)`, then calls each scene whose window contains `t`:

| Scene | Window (s) | Draw | What it is |
|---|---|---|---|
| intro | t < 8.33 | `sub_405bc0` | A dotted stripe square drawn as points, through the glow2 pass |
| logo | 6.511 – 9 | `sub_405610` | The Limp Ninja logo |
| discs | 9 – 25.514 | `sub_4027b0` | 44 DesignRings in three groups, a spectrum-lit sky, streaking lines |
| city | 25.514 – 36.5 | `sub_40b7a0` + `sub_4092a0` | City photo, 10,000 lit dots, 30 space creatures |
| mackerel | 36.25 – 52.093 | `sub_40a9d0` | The mackerel photo, an exploding sphere, orbiting workers, a ring |
| points | 52.093 – 66.974 | `sub_407890` | 5000 sphere imposters, shaded from screen-space normals and an envmap |
| cubes | 66.974 – 81.8 | `sub_401e10` | 9000 lit cubes on a twisting column, edge-detected, plus black pickles |
| shore | 81.8 – 98.603 | `sub_4087e0` | An exploding space creature on the shore, through splitcolors |
| love | 98.603 – 104.171 | `sub_403bf0` | A 150,000-point blob grid drawn as lines, "my love can kill you" |
| tunnel | t > 104.171 | `sub_40bcb0` | The space creature turned into a bass-driven tunnel, then the credits |

**Randomness.** The exe never calls `srand`, so MSVC's `rand()` starts from seed 1 every run and the demo is
deterministic. Constructors share one global stream, in construction order: mackerel ring 176 calls, points 5000,
the unused points scene 5000, discs 44 rings × 3, cluster 400 … 18,568 calls before the first frame. `js/common.js` has
the same LCG (`s = s·214013 + 2531011`, `(s >> 16) & 0x7fff`), and `buildScenes` constructs in the exe's order. That
is why the disc layout and the creature positions match the capture exactly. The logo and the shore each call `rand()`
once per frame and discard the result.

**Spectrum.** FMOD Ex is never given an output format, so it mixes at its default 48 kHz, and `getSpectrum` analyses the
song resampled to 48 kHz. The player decodes the song at 48 kHz on purpose and computes the same 512-point,
triangle-windowed magnitudes (scaled 2|X|/N) for the 512 samples before `t`. Two scenes read it: the disc sky's top
brightness is `0.7 + 0.3 · Σ bins 80–99`, and the tunnel's swell is `1 + Σ bins 0–129`.

**Lighting.** There is no `glLight*`, `glMaterial` or `GL_COLOR_MATERIAL` call anywhere in the exe. Fixed-function
lighting therefore runs on OpenGL's defaults: light 0 is white and points along (0,0,1) in eye space, the material is
0.8 grey diffuse with 0.2 ambient, and the global ambient is 0.2. The result is `0.04 + 0.8 · N·L`, and `glColor` has no
effect while lighting is on.

**Textures.** The loader (`sub_409e30`) un-premultiplies colour by alpha: `c = (byte)(int)(c / (a/255))`. Where a
semi-transparent pixel's colour exceeds its alpha, the value passes 255 and wraps to a dark one. city-1, credits,
mackerel, love2 and others have thousands of such pixels. `build.py` applies the same transform, so the browser
receives the bytes the GL texture held. Textures are mipmapped, linear and clamped. Sprites use `LINEAR_MIPMAP_NEAREST`.

**Render targets.** Effects render into rectangle-texture FBOs and composite them with a one-fragment-shader program
(`sub_407c80` / `sub_407dc0`). The shore and cubes targets are 1440×900 (an earlier screen size) drawn into a
1280×720 screen, and the port keeps those sizes.

## Bugs in the original, kept

- **points.vert** has `m_vertex += gl_Position = MVP * m_vertex;`, which adds the clip-space position to the vertex before the billboard offset.
- **edges.frag**: the exe sets a uniform named `blender`, but the shader declares `blend`, so the edge mix is always 0.
- **Mackerel workers**: the explosion uniform comes from a stale stack temporary. Each worker gets `fmod(P[i−1], 0.9)`
  of the previous worker before its own value is computed, which is visible as staggered explosions.
- **The ring draw** leaves blending enabled, and later geometry in the same scene inherits it.
- **splitcolors.frag** sums 9×9 taps and divides by 8×8, adding 27% more light than an average.
- **ssnormals.frag** addresses the envmap with a hard-coded 1440×900 size.
- **disc.frag** has operator-precedence slips in two of its patterns.

## Built but never shown

- `factory.png` is shipped, but no string in the exe refers to it.
- `city-2.png` is loaded by the city scene and never drawn. `dirt.png` is also loaded by the disc scene, which never draws it.
- The logo builds a glow2 render target and doesn't use it. The cubes build an ssnormals target and don't use it.
- A second points scene (`g_419a9c`) with front and back passes and `sstnormals.frag` is constructed, which costs 5000
  `rand()` calls, and never drawn.
- The "Circle Cluster" (`sub_4013e0`) is the demo's only geometry shader, and it is never drawn either.
- `lightpoints.vert` is not loaded by anything.

The asset explorer marks all of these.

## Checked against a capture of the original

The player can render any `t` to a PNG (`__ersatz.snap(t)` in the console; with `SNAP_DIR` set, `serve.py` saves
`POST /__snap` uploads there). 119 frames, one per second, were compared with the capture. Cross-correlation puts the
capture at offset 0 s, and the mean per-frame correlation of 64×36 luminance is 0.84. From the intro to the points
scene, most frames score above 0.9; the discs dip to 0.6 where a ring sweeps past the camera, since a capture frame
and a render at the same nominal second can differ by a fraction of a frame. Shore, love and tunnel score 0.1–0.8
because they move fast and the capture is heavily compressed, but side by side they match: the same cubes, the same
debris, the same tunnel spokes.

![reconstruction (left) and capture (right) at 4, 8, 15, 30, 44, 58, 75, 90, 101 and 110 s](data/compare.jpg)

## Known approximations

- **points.frag** takes the square root of a negative number at the billboard corners. That gives NaN depth, which the
  GeForce 8 rejected. The port discards those fragments instead.
- **The disc cue table** is read past its end for 25.48 < t ≤ 25.514. The port clamps the index; that is one or two frames.
- **City point size** is whatever the last intro frame left behind (≈2.7). The port uses 3 px.
- **The current normal** for the city dots is the last `glNormal` seen; the port uses (0,0,1).
- **3 px smooth lines** (the love grid) are drawn as GPU quads, because WebGL has no wide lines.
- **Mesh::Draw** passes the float count to `glDrawArrays`, three times the vertex count, so the driver drew whatever
  followed in memory. The port draws only the real vertices.
- **MSAA** is the browser's 4× instead of the driver's, and line and point smoothing are emulated.

## Files

    index.html            player and overview
    js/glx.js             fixed-function OpenGL emulation on WebGL 2 (matrix stacks, immediate mode, quads,
                          lighting, alpha test, rectangle textures, wide lines, polygon offset for lines)
    js/shaders.js         the ported GLSL, with notes on each quirk
    js/common.js          MSVC rand(), .raw parser, FMOD-style spectrum, shared helpers (gradient, sprite, photo, post pass)
    js/scenes.js          the ten scenes and DrawFrame
    js/main.js            loading, clock, controls, timeline
    exe/                  executable explorer (index.html, app.js, data.json, disasm.json, schuifkaas.exe.bin)
    assets/               asset explorer
    notes/                the decompilation notes per scene, with addresses
    data/                 transformed images (img/), originals of non-opaque images (orig/), models, shaders, compare.jpg
    tools/                disasm.py, gen_exe.py, labels.json, build.py, serve.py
