diff --git a/README.md b/README.md index f68c349..e476436 100644 --- a/README.md +++ b/README.md @@ -15,11 +15,19 @@ Linux) computes the skeleton from webcam-derived synthetic depth. - **Calibrate once:** **[docs/calibration.md](docs/calibration.md)**. - **Something broken:** **[docs/troubleshooting.md](docs/troubleshooting.md)**. - **Build details / toolchain:** **[docs/build.md](docs/build.md)**. +- **Native Windows tracker (current path):** **[docs/native-tracker.md](docs/native-tracker.md)**. +- **How DEA works inside + RE jump-start:** **[docs/game-internals.md](docs/game-internals.md)**. ## Architecture +The current Windows path uses the self-contained **native tracker** +(`tracker-native/`, C++ Media Foundation capture + Win32 GUI + ONNX BlazePose), +so no Python runtime is needed on the play machine. The original Python tracker +(`tracker/`) remains the reference/Linux path. Both publish the same contract. + ``` - webcam ─► tracker (Python, MediaPipe pose + segmentation) + webcam ─► tracker (native tracker-native/ on Windows, or Python tracker/) + │ MediaPipe/BlazePose pose + segmentation │ publishes to the frozen shared-memory IPC contract ▼ core/ (OS-agnostic engine, libnui_core) @@ -56,7 +64,8 @@ OS this environment lacks (no Windows, no WDK, no `usbip` userspace, no loaded ` | Linux skeleton tracking (NiTE2) | OpenNI2 + NiTE2 | out of scope: NiTE2 is non-redistributable; supply it yourself | | Windows device-attach (IS-1 enumerate, IS-2 MS NUI skeletonizes synthetic depth) | `attach/windows/` | `[~]` blocked: no Windows/WDK. Scripts + topology + signing fully specified | | Windows `Kinect10.dll` NUI shim (IS-3/IS-4 playability only) | `fallback/windows-nui/` | **built + export-audited** (real PE32/PE32+, 21 exports, 0 missing); runtime load `[~]` unverified | -| DEA in-game playability proof | Windows | `[~]` blocked: human-assisted on the user's Windows box (plan F5) | +| Native Windows tracker (MF capture + Win32 GUI + ONNX BlazePose, remembers last camera/resolution) | `tracker-native/` | **verified** on the user's Windows box | +| DEA in-game skeleton rendering + menu hand-cursor | Windows + `fallback/windows-nui/` | **verified** on the user's Windows box (skeleton renders; one-arm cursor covers the screen). See [docs/game-internals.md](docs/game-internals.md) | The authoritative skeleton/fidelity proof is DEA on Windows; the Linux OpenNI2 path proves the depth/synthesis fidelity. The `Kinect10.dll` shim proves playability only and does **not** satisfy @@ -78,7 +87,8 @@ NiTE2, and any game assets are never bundled; the docs link to their official so | `core/synth/` | Packed depth + player-index + color rasterizer | | `core/protocol/` | Kinect v1 virtual USB device emitter | | `core/calibration/` | One-time T-pose + mirror calibration | -| `tracker/` | Python webcam -> MediaPipe pose/segmentation -> IPC | +| `tracker/` | Python webcam -> MediaPipe pose/segmentation -> IPC (reference/Linux path) | +| `tracker-native/` | Native Windows tracker: MF capture + Win32 GUI + ONNX BlazePose -> IPC | | `attach/linux/` | Linux USB attach via usbip/vhci | | `attach/windows/` | Windows virtual USB bus attach + signing scripts | | `fallback/linux-openni2/` | OpenNI2 virtual device / Linux general emulator | @@ -87,7 +97,7 @@ NiTE2, and any game assets are never bundled; the docs link to their official so | `tools/record-replay/`, `tools/mock-nui-host/` | Deterministic record/replay + mock NUI host | | `packaging/` | Per-OS runnable-bundle assembly script | | `tests/` | Cross-cutting C++ (CTest) + Python (pytest) tests | -| `docs/` | Setup, calibration, troubleshooting, build, spike reports | +| `docs/` | Setup, calibration, troubleshooting, build, native tracker, DEA game internals + RE jump-start | ## Packaging diff --git a/docs/game-internals.md b/docs/game-internals.md new file mode 100644 index 0000000..90292c0 --- /dev/null +++ b/docs/game-internals.md @@ -0,0 +1,169 @@ +# DanceEvolution Arcade (DEA / `gamekdm.dll`) — game internals & RE jumpstart + +Everything reverse-engineered about how DEA consumes the emulated Kinect, plus a +jump‑start so another agent can continue a full RE/decompilation **without +redoing this work**. All gamekdm addresses use image base `0x10000000`. + +The emulator presents an ordinary webcam as a Kinect v1: the native tracker +(`tracker-native/`, MediaPipe/BlazePose + ONNX) publishes a synthetic +depth/color/skeleton frame over a shared‑memory contract, and the Windows NUI +shim (`fallback/windows-nui/`, a drop‑in `Kinect10.dll`) serves it to the game. +We never modify any game file. + +--- + +## 1. How DEA consumes the Kinect + +- DEA loads `Kinect10.dll` (MS NUI v1 API). Our shim implements that ABI and + feeds the game our frames. The game's own NUI stack computes nothing extra for + the skeleton — we publish the 20‑joint skeleton directly; the game *does* run + its own selection/validation and a Flash menu cursor on top (below). +- Resolution: the game only accepts a **4:3** image. The tracker enforces 4:3 + (`PopulateResolutions` filters to 4:3; depth/color are 640×480). +- The in‑process introspection tool (section 5) reads the game's live manager at + `*(gamekdm+0x3cf1b4)` — this is how everything below was discovered. + +## 2. Skeleton rendering & the selection/validity gate *(solved)* + +For the in‑game skeleton to render, our candidate skeleton must pass the game's +orientation/validity gate, decoded from `gamekdm`: + +- `FUN_10018570` builds a gravity/floor‑relative transform `M`. If the gravity + vector at `manager+0x2c` is the sentinel, `M` is derived from the skeleton's + TRACKED joints (weighted ratio of tracked joints must exceed `0.85`, weights + `DAT_102a49e8`; then 5 limb‑direction dot‑products must each exceed `0.9`). + Feeding `vNormalToGravity = (0,1,0)` populates `manager+0x2c` and takes the + simpler gravity branch instead. +- `FUN_100e4140 → FUN_101ab6d0` is the candidate‑validity filter: it computes + `P1 = (-px, py + m13, -pz + m14)` (no perspective divide) and accepts only if + `P1` is within `0.05` of the box `[A-B, A+B]` where `A = DAT_103d3230 = + (0,1,0)`, `B = (1.22, 1, 0.675)` → box x∈[-1.22,1.22], y∈[0,2], z∈[-0.675, + 0.675]. `m14 = 2.5` matches our published `z0`; `m13` is taken straight from + the skeleton frame's `vFloorClipPlane.w`. +- **The fix** (`sensor.cpp BuildSkeletonFrame`): publish all 20 joints as + `TRACKED`, `vNormalToGravity = {0,1,0,0}`, and **`vFloorClipPlane = {0,1,0, + 1.0 - hip.y}`** so `P1.y = hip.y + (1 - hip.y) = 1.0` (box centre) every frame. + This auto‑centres the candidate and the skeleton renders. (Commit `36035cc`.) + +## 3. The menu hand‑cursor (Flash/`afp` PhIZ) *(solved)* + +This one is *not* in any DLL — it lives in the game's Flash runtime: + +- `afp` is a **Flash/ActionScript runtime** (`libafp-win32.dll` exports + `flash.display.InteractiveObject`, `flash.ui.MouseCursor`, `useHandCursor`). + Menu UI (incl. the cursor sprite) is compiled Flash packed in the `.ifs` + archives under `contents/data/bm2d/*.ifs`. +- The moving cursor is the controller's own movie clip. gamekdm global + **`DAT_103d2bb8`** is the cursor‑controller object pointer; the live 1P cursor + is at `(*DAT_103d2bb8)+0x108/+0x10c` and 2P at `+0x110/+0x114`, in **screen + pixels (1280×720)**. `FUN_1007fbf0` reads it via `afp_mc_get_param(ctrl+8, + 0x1008)` and snaps to the OK buttons (`_but_ok_1p/2p_usr`) when `dist² < + 0x1fa4` (~90 UI units). The `_icon_1p/2p/only_usr` strings are the **OK‑button + icons**, *not* the cursor. +- **No gamekdm code writes the cursor from the hand** (no `afp_mc_set_param` + with `0x1008`; 53 decompiled menu AS scripts reference no hand/cursor/natal). + The hand→cursor PhIZ is inside the Flash/Natal runtime — a body‑relative, + reach‑normalised mapping we can't modify. The only lever is **our skeleton**. +- **Root causes & fixes** (all shim‑side, `BuildSkeletonFrame`; no tracker + rebuild needed): + 1. **Handedness.** Our projection is byte‑identical to a real Kinect's + `NuiTransformDepthImageToSkeleton` (`kDepthProjectionScale = 3.501e-3 = + NUI_CAMERA_DEPTH_NOMINAL_INVERSE_FOCAL_LENGTH_IN_PIXELS`). But the tracker + mirrors the camera (selfie view, like a real Kinect's mirrored depth + image), and **mirroring swaps MediaPipe's L/R labels** (verified: a + mirrored frame's `RIGHT_WRIST.x ≈ 1 - LEFT_WRIST.x` of the normal frame). + So the shim swaps L/R joints back (`kSwap[]`) → the player's right hand + lands in `HAND_RIGHT` with +x relative to `SHOULDER_CENTER`, matching real + Kinect recordings (`HAND_R - SHOULDER_CENTER.x ∈ [-0.35, +0.86]`). + 2. **Reach compression.** Measured against real Kinect v1 recordings (UTKinect + `waveHands` + MSR arm‑waves; see section 6), MediaPipe reports the hand + ~**1.6× (x) / 1.3× (y)** *closer* to the shoulder than a real Kinect does + (scale‑invariant, shoulder‑width‑normalised — a genuine joint‑placement + difference), so one arm only covered part of the screen. The shim amplifies + each arm outward from its shoulder by `kArmGainX / kArmGainY` (tuned to + **3.2 / 2.6** empirically for full coverage without over‑sensitivity). The + hip/center‑of‑mass is left untouched, so the validity box stays centred. + +## 4. Two‑player + +- **The game supports 2P**: dual cursor slots (`CUR1`/`CUR2` above), + `NuiSkeletonSetTrackedSkeletons([id0, id1])`, and NUI's 6 skeleton slots. +- **The emulator does not** (yet): it's single‑person end‑to‑end — the contract + carries one `SkeletonFrame`, the shim fills only `SkeletonData[0]`, and the + tracker runs single‑person BlazePose (verified: it returns exactly one pose on + a 2‑person image). Enabling 2P needs: a multi‑person pose stage, a 2‑skeleton + contract, and the shim filling `SkeletonData[0]`+`[1]` with distinct + `dwTrackingID`s. + +## 5. Debug tooling: in‑process game introspection + +Because the shim runs inside `gamekdm.dll`, it can read the game's live memory. +`sensor.cpp DumpGameDisplayState()` dumps the manager, the skeleton‑selection +state, the validity matrix/box, and the live cursor; the per‑frame `handcur:` +log pairs our published joints with the live cursor value. Both are gated behind +`constexpr bool kShimDebug` (`sensor.cpp`, default **false**). Flip it true, +rebuild, and watch `kinect_shim.log` (`game-introspect` / `game-skel[1-4]` / +`game-cursor` / `handcur` lines). This is the method that cracked §2 and §3 — +reimplement the game's math in Python from a single dump, don't guess. + +## 6. RE / decompilation jump‑start (for a fresh agent) + +Everything you need to continue without redoing the groundwork: + +### Ghidra (gamekdm.dll) +- Analyse **once** into a persistent project, then reuse it (re‑analysing per run + wasted 3–5 min each): + ``` + analyzeHeadless /home/athapa/ghidra gkproj -import gamekdm.dll # once, NO -deleteProject + analyzeHeadless /home/athapa/ghidra gkproj -process gamekdm.dll -noanalysis -postScript + ``` + JDK21 at `/home/athapa/jdk`; scripts in `/home/athapa/ghidra/scripts/` + (`getFunctionContaining` + `decompileFunction`). Full objdump at `/tmp/gk.asm`. +- Key functions/globals (base `0x10000000`): cursor controller global + `DAT_103d2bb8`; cursor read `FUN_101d84c0`→`afp_mc_get_param(_,0x1008)`; + button‑hit `FUN_1007fbf0`; cursor state machine `FUN_1007e330`; icon‑reader + `FUN_10080360`; validity transform `FUN_10018570`; candidate filter + `FUN_100e4140`/`FUN_101ab6d0`; validity box `DAT_103d3230`, matrix + `DAT_103d4a80`; manager pointer `*(gamekdm+0x3cf1b4)`. + +### afp / Flash data (the cursor PhIZ lives here) +- `ifstools` (pip, pure‑Python) extracts `data/bm2d/*.ifs` → `afp/` (Flash) + + `afp/bsi/` (bytecode) + `geo/` + `tex/`. +- **bemaniutils** has the AFP ActionScript decompiler, but it is **not on PyPI** + and needs **Python 3.12** (not 3.14) — install from git and import only the afp + parser (its `mysqlclient`/server deps fail but aren't needed): + ``` + git clone --depth 1 https://github.com/DragonMinded/bemaniutils /tmp/bemaniutils + python3.12 -m pip install --break-system-packages Pillow pycryptodome cython + PYTHONPATH=/tmp/bemaniutils python3.12 -c "from bemani.format.afp import SWF, ByteCodeDecompiler" + ``` + Decompile a clip: `SWF("", open(afp,'rb').read(), open(bsi,'rb').read())`, + `.parse()`, then walk `AP2DoActionTag.bytecode.decompile()` (see + `bemani/utils/afputils.py decompile_and_write_bytecode`). The menu scripts do + **not** contain the hand→cursor map — it's in the Flash/Natal runtime — + so next step is `libafp-win32.dll` (Ghidra project `afpproj`, already analysed) + around its `flash.ui.MouseCursor` / pointer handling. + +### Real‑Kinect reference data (for calibrating our skeleton) +- UTKinect‑Action3D: RGB (1.79G) + synced 20‑joint skeletons (3.3M) + + `actionLabel.txt`, `https://cvrc.ece.utexas.edu/KinectDatasets/` (`RGB.zip`, + `joints.zip`). Joint order = NUI (HIP_CENTER=0 … HAND_R=11 … FOOT_R=19); + real‑world metres. `waveHands` frames are a clean hand sweep. +- MSR‑Action3D `MSRAction3DSkeletonReal3D` (github `Mabdou11/Activity- + Recognition-skeleton-datasets`): `a01`=high‑arm‑wave, `a02`=horizontal‑arm‑ + wave. Compare `HAND_R - SHOULDER_CENTER` (shoulder‑width‑normalised) against + our published joints to re‑derive the reach gains. + +### Can't run the game here +Wine is not installed and the build is an 8.2 GB spice2x arcade build needing +DirectX + a real camera — iterate with the build→deploy→playtest loop, not an +emulator. Deep‑low RE subagents repeatedly failed on this (armed a monitor and +exited, then hit a 429 at ~2.1M tokens) — do the game RE directly with the local +Ghidra setup. + +## 7. Top remaining latency lever +Inference is now multi‑threaded (ONNX intra‑op, `pose_estimator.cpp`). The +biggest further win is a **GPU execution provider (DirectML)**: swap the +`onnxruntime-win-x64` CPU binary for `onnxruntime-directml` and +`so.AppendExecutionProvider_DML(0)`. Also optional: a short fixed camera +exposure (cuts sensor lag + motion blur, needs good lighting). diff --git a/docs/native-tracker.md b/docs/native-tracker.md index 910ea13..cb050cf 100644 --- a/docs/native-tracker.md +++ b/docs/native-tracker.md @@ -1,8 +1,9 @@ # Native tracker (zero-Python) — architecture -Status: in progress. Replaces the Python/MediaPipe tracker (`tracker/`) with a -single native Windows application. Goal from the user: pick the camera, pick the -resolution, see a live preview, and no Python anywhere. +Status: **working** (verified on the user's Windows box; DEA renders the skeleton +and the menu hand-cursor covers the screen). Replaces the Python/MediaPipe +tracker (`tracker/`) with a single native Windows application. Goal from the +user: pick the camera, pick the resolution, see a live preview, no Python. ## Why / scope @@ -12,10 +13,19 @@ and drags a MediaPipe/OpenCV venv behind it. The new tracker is one native - enumerates webcams and their native resolutions, lets you pick both in a GUI, - shows a live preview with a mask/skeleton overlay so you can frame yourself, -- runs pose + person segmentation natively, +- runs pose + person segmentation natively (ONNX BlazePose; inference is + multi-threaded across ~half the cores for lower latency), +- **remembers the last camera + resolution** (`kinect_tracker_last.txt` next to + the exe) and defaults the dropdowns to it on the next launch, +- mirrors the camera at the source (selfie view, matching a real Kinect's + mirrored depth image), - publishes the frozen IPC contract into the `kinect_virtual_frames` shared memory the `Kinect10.dll` shim already reads. +The skeleton-selection/validity gate and the menu hand-cursor mapping (L/R swap + +reach amplification, applied shim-side) are documented in +[game-internals.md](game-internals.md). + ## What is reused (already C++) `core/` is the whole non-ML spine and already builds in the shim: