diff --git a/src/game/box_distance.cpp b/src/game/box_distance.cpp new file mode 100644 index 0000000..c132962 --- /dev/null +++ b/src/game/box_distance.cpp @@ -0,0 +1,28 @@ +#include "validity.h" + +namespace gk::game { + +// rva=0x101ab6d0 (orig FUN_101ab6d0) +float GK_CDECL BoxDistanceSquared(const ValidityBox& box, const Vec3& point) { + // T7's field names are misleading: the instructions use center +/- extent, + // not minimum/maximum corners. Preserve its verified binary layout. + const float center[] = {box.minimum.x, box.minimum.y, box.minimum.z}; + const float extent[] = {box.maximum.x, box.maximum.y, box.maximum.z}; + const float position[] = {point.x, point.y, point.z}; + float delta[3]; + for (unsigned axis = 0; axis < 3; ++axis) { + // Match the DWORD spills before the two original clamp helpers. + volatile float lower = center[axis] - extent[axis]; + volatile float upper = center[axis] + extent[axis]; + const float above_lower = + lower >= position[axis] ? lower : position[axis]; + const float clamped = above_lower < upper ? above_lower : upper; + volatile float difference = position[axis] - clamped; + delta[axis] = difference; + } + const long double x = delta[0], y = delta[1], z = delta[2]; + volatile float distance = (x * x + y * y) + z * z; + return distance; +} + +} // namespace gk::game diff --git a/src/game/nui_elevation.cpp b/src/game/nui_elevation.cpp new file mode 100644 index 0000000..82540f2 --- /dev/null +++ b/src/game/nui_elevation.cpp @@ -0,0 +1,25 @@ +#include "nui_elevation.h" + +namespace gk::game { + +// rva=0x1000f510 (orig FUN_1000f510) +void GK_CDECL UpdateCameraElevation(ElevationThread& thread) { + std::int32_t current = 0; + const std::int32_t status = thread.sensor->GetAngle(¤t); + if (status >= 0) { + if (thread.accumulator == kAccumulatorSentinel) { + thread.accumulator = current; + } + // (current + 2*prev)/3: the imul 0x55555556 + shr 31 at 0x1000f53c is a + // signed divide-by-three truncating toward zero, which C++ int / 3 matches. + const std::int32_t averaged = (current + thread.accumulator * 2) / 3; + thread.smoothed_angle = averaged; + thread.accumulator = averaged; + } + if (thread.applied_angle != thread.desired_angle) { + thread.sensor->SetAngle(thread.desired_angle); + thread.applied_angle = thread.desired_angle; + } +} + +} // namespace gk::game diff --git a/src/game/nui_elevation.h b/src/game/nui_elevation.h new file mode 100644 index 0000000..46246b0 --- /dev/null +++ b/src/game/nui_elevation.h @@ -0,0 +1,36 @@ +#pragma once + +#include "gk/types.h" + +namespace gk::game { + +// Camera-elevation control surface the NuiThread drives through the live +// INuiSensor. Declared as a C++ interface so MinGW emits the Itanium vtable +// (never copy MSVC vtable bytes, per docs/conventions.md). The two slots used +// here mirror INuiSensor::NuiCameraElevationGetAngle and +// ::NuiCameraElevationSetAngle (kinect/fallback/windows-nui/nui_interfaces.h), +// the methods the original dispatches at vtable offsets 0x3c and 0x38. +class ICameraElevation { + public: + virtual std::int32_t GK_STDCALL GetAngle(std::int32_t* out_degrees) = 0; + virtual std::int32_t GK_STDCALL SetAngle(std::int32_t degrees) = 0; +}; + +// NuiThread elevation-smoothing state. Offsets pinned to the original +// FUN_1000f510 frame: the object arrives in ESI and the function touches +// +0x38/+0x3c/+0x40/+0x44 and the sensor pointer at +0x15fc. +struct ElevationThread { + std::int32_t desired_angle; // +0x38, caller-requested elevation + std::int32_t applied_angle; // +0x3c, last angle pushed to the sensor + std::int32_t smoothed_angle; // +0x40, published smoothed estimate + std::int32_t accumulator; // +0x44, IIR state, sentinel -0x168 + ICameraElevation* sensor; // +0x15fc, live INuiSensor +}; + +// cmp DWORD PTR [esi+0x44],0xfffffe98 at 0x1000f527. +constexpr std::int32_t kAccumulatorSentinel = -0x168; + +// rva=0x1000f510 (orig FUN_1000f510) +void GK_CDECL UpdateCameraElevation(ElevationThread& thread); + +} // namespace gk::game diff --git a/src/game/validity.cpp b/src/game/validity.cpp new file mode 100644 index 0000000..0dd294c --- /dev/null +++ b/src/game/validity.cpp @@ -0,0 +1,65 @@ +#include "validity.h" + +#include + +namespace gk::game { +namespace { + +Vec3 GK_CDECL TransformPosition(const Matrix4x4& m, const Vec3& p) { + // The original uses SSE2 binary64 products/sums, then binary32 stores. + // Positions multiply columns in the T7 row-major storage layout. + return { + static_cast(((double(m.m10) * p.y + double(m.m00) * p.x) + + double(m.m20) * p.z) + m.m30), + static_cast(((double(m.m11) * p.y + double(m.m01) * p.x) + + double(m.m21) * p.z) + m.m31), + static_cast(((double(m.m12) * p.y + double(m.m02) * p.x) + + double(m.m22) * p.z) + m.m32)}; +} + +} // namespace + +// rva=0x100e4140 (orig FUN_100e4140) +void GK_CDECL UpdateValidityCandidates(const LiveManager& manager, + ValidityState& state) { + const Matrix4x4 transform = state.transform; + for (std::size_t index = 0; index < kSkeletonCount; ++index) { + const SkeletonData& skeleton = manager.skeleton_frame.skeletons[index]; + ValidityCandidate& candidate = state.candidates[index]; + const std::uint32_t tracking_id = manager.synthetic_tracking_mode + ? (index < 2 ? static_cast(index + 1) : 0) + : skeleton.tracking_id; + // The ID is integer bits, despite T7's float field declaration. + std::uint32_t previous_id; + std::memcpy(&previous_id, &candidate.tracking_id, sizeof(previous_id)); + if (previous_id != tracking_id) { + std::memcpy(&candidate.tracking_id, &tracking_id, sizeof(tracking_id)); + candidate.valid = 0; + } + Vec3 source = state.missing_position; + if (!manager.synthetic_tracking_mode && + skeleton.tracking_state != SkeletonTrackingState::not_tracked) { + source = {skeleton.position.x, skeleton.position.y, skeleton.position.z}; + } + const Vec3 transformed = TransformPosition(transform, source); + if (source.x != state.missing_position.x || + source.y != state.missing_position.y || + source.z != state.missing_position.z) { + const float tolerance = candidate.valid + ? state.retained_tolerance : state.entry_tolerance; + const float squared_tolerance = + static_cast(double(tolerance) * tolerance); + candidate.valid = BoxDistanceSquared(state.box, transformed) <= + squared_tolerance; + if (candidate.valid) { + candidate.source_position = source; + // The original deliberately applies the matrix a second time. + candidate.transformed_position = TransformPosition(transform, transformed); + } + } else { + candidate.valid = 0; + } + } +} + +} // namespace gk::game diff --git a/src/game/validity.h b/src/game/validity.h new file mode 100644 index 0000000..5b6a02b --- /dev/null +++ b/src/game/validity.h @@ -0,0 +1,24 @@ +#pragma once + +#include "gk/offsets_assert.h" + +namespace gk::game { + +// The original globals are explicit state here; no calls back into the DLL. +struct ValidityState { + Matrix4x4 transform; // DAT_103d4a80 + ValidityBox box; // DAT_103d3230 + Vec3 missing_position; // DAT_103d32c4 + float entry_tolerance; // DAT_10299294 + float retained_tolerance; // DAT_10299298 + ValidityCandidate candidates[kSkeletonCount]; // DAT_103e29b0 +}; + +// rva=0x101ab6d0 (orig FUN_101ab6d0); original inputs EAX=box, EDI=point. +float GK_CDECL BoxDistanceSquared(const ValidityBox& box, const Vec3& point); + +// rva=0x100e4140 (orig FUN_100e4140); original inputs were globals. +void GK_CDECL UpdateValidityCandidates(const LiveManager& manager, + ValidityState& state); + +} // namespace gk::game diff --git a/tools/unicorn_diff/prove_t11.py b/tools/unicorn_diff/prove_t11.py new file mode 100644 index 0000000..1f1b29f --- /dev/null +++ b/tools/unicorn_diff/prove_t11.py @@ -0,0 +1,263 @@ +"""T11 keystone proof: original gamekdm.dll vs compiled MinGW reconstruction. + +For each reconstructed function this emulates the real routine in the shipping +binary (Unicorn) and runs the compiled C++ reconstruction under wine on the +same inputs, then asserts behavioural equality through the T8 differ. Run: + + tools/unicorn_diff/.venv/bin/python tools/unicorn_diff/prove_t11.py +""" +from __future__ import annotations + +import os +import shutil +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +from unicorn.x86_const import UC_X86_REG_EIP, UC_X86_REG_ESI, UC_X86_REG_ESP + +from udiff import ( + Buffer, CallSpec, FloatTolerance, PeImage, RegValue, + ReturnKind, RunResult, UnicornRunner, Verdict, diff, +) +from udiff.image import CODE_SCRATCH, SCRATCH_BASE, STACK_BASE, STACK_SIZE +from udiff.metadata import load_calling_convention +from udiff.runner import RETURN_SENTINEL + +ROOT = Path(__file__).resolve().parents[2] +DLL = Path("/home/athapa/ghidra/gamekdm.dll") +RECON = ROOT / "tools" / "unicorn_diff" / "recon.exe" +TOL = FloatTolerance(absolute=1e-6, relative=1e-6) + + +def run_recon(exe: Path, mode: str, payload: bytes) -> bytes: + env = dict(os.environ) + env["WINEDEBUG"] = "-all" + out = subprocess.run( + ["wine", str(exe), mode], + input=payload.hex().encode(), + capture_output=True, + env=env, + check=True, + ) + return bytes.fromhex(out.stdout.decode().strip()) + + +def prove_box(image: PeImage, log: list[str]) -> None: + runner = UnicornRunner(image) + conv = load_calling_convention(0x1AB6D0) + cases = ((6.0, 9.0, 7.0), (-4.0, -5.0, 3.0), (1.0, 2.0, 3.0), (1.3, 0.0, 2.5)) + center, extent = (1.0, 2.0, 3.0), (2.0, 3.0, 4.0) + box = struct.pack("<6f", *center, *extent) + for point in cases: + spec = CallSpec( + rva=0x1AB6D0, conv=conv, ret=ReturnKind.FLOAT_ST0, + regs=(RegValue("eax", buffer=Buffer("box", box)), + RegValue("edi", buffer=Buffer("pt", struct.pack("<3f", *point)))), + ) + original = runner.run(spec) + recon_bits = run_recon(RECON, "box", box + struct.pack("<3f", *point)) + recon = struct.unpack(" {report.verdict.value}") + log.append(f"FUN_101ab6d0: PASS ({len(cases)} cases, differential original==reconstructed)") + + +def emulate_elev(image: PeImage, thread: dict[str, int]) -> dict[str, int]: + uc = image.new_emulator() + manager = SCRATCH_BASE + 0x1000 + sensor = SCRATCH_BASE + 0x2000 + vtable = SCRATCH_BASE + 0x3000 + rec = SCRATCH_BASE + 0x4000 + stub_get = CODE_SCRATCH + 0x100 + stub_set = CODE_SCRATCH + 0x200 + uc.mem_write(manager + 0x38, struct.pack(" None: + cases = ( + {"desired": 10, "applied": -5, "smoothed": 0, "accum": -0x168, "angle": 7, "status": 0}, + {"desired": -5, "applied": -5, "smoothed": 0, "accum": 4, "angle": 19, "status": 0}, + {"desired": 27, "applied": 27, "smoothed": 0, "accum": 0, "angle": -40, "status": -1}, + {"desired": 3, "applied": 1, "smoothed": 9, "accum": -0x168, "angle": -12, "status": 0}, + ) + for case in cases: + original = emulate_elev(image, case) + payload = struct.pack("= 1, ("GetAngle never dispatched", case) + assert recon == original, (case, original, recon) + log.append(f" elev in={case} orig={original} recon(set_called={set_called}," + f"get_called={get_called}) -> EQUAL") + log.append(f"FUN_1000f510: PASS ({len(cases)} cases, vtable GetAngle/SetAngle dispatch " + "+ object state original==reconstructed)") + + +def emulate_gate(image: PeImage, case: dict) -> bytes: + uc = image.new_emulator() + manager = SCRATCH_BASE + 0x8000 + base = image.image_base + uc.mem_write(image.va(0x102E54B8 - base), struct.pack(" bytes: + buf = struct.pack("<16f", *case["matrix"]) + struct.pack("<6f", *case["box"]) + buf += struct.pack("<3f", *case["missing"]) + buf += struct.pack(" dict: + identity = (1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0) + return { + "matrix": identity, + "box": (0.0, 1.0, 0.0, 1.22, 1.0, 0.675), + "missing": (-3131.0, -3131.0, -3131.0), + "entry": 0.05, "retained": 0.08, "synthetic": synthetic, + "skeletons": [{"state": states[i], "id": ids[i], "pos": positions[i]} for i in range(6)], + "candidates": seeds, + } + + +def prove_gate(image: PeImage, log: list[str]) -> None: + far = (99.0, 99.0, 99.0) + seeds = [{"id": 0, "valid": 0} for _ in range(6)] + cases = [ + gate_case(0, [2, 2, 0, 0, 0, 0], [11, 22, 0, 0, 0, 0], + [(0.0, 1.0, 0.0), (2.0, 1.0, 0.0), far, far, far, far], seeds), + gate_case(0, [2, 0, 0, 0, 0, 0], [7, 0, 0, 0, 0, 0], + [(1.2, 1.0, 0.0), far, far, far, far, far], seeds), + gate_case(1, [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], + [far, far, far, far, far, far], seeds), + ] + for idx, case in enumerate(cases): + original = emulate_gate(image, case) + recon = run_recon(RECON, "gate", gate_payload(case)) + assert len(recon) == len(original) == 0x20 * 6, (len(recon), len(original)) + valid_bytes = [recon[i * 0x20 + 0x1C] for i in range(6)] + assert recon == original, (idx, original.hex(), recon.hex()) + log.append(f" gate case{idx} synthetic={case['synthetic']} valid={valid_bytes} " + f"candidates[192B] original==reconstructed") + log.append(f"FUN_100e4140: PASS ({len(cases)} cases, 6-candidate validity array " + "original==reconstructed)") + + +def prove_injected_bug(image: PeImage, log: list[str]) -> None: + src = (ROOT / "src" / "game" / "box_distance.cpp").read_text() + bug = src.replace("volatile float difference = position[axis] - clamped;", + "volatile float difference = position[axis] - clamped + 0.01f;") + assert bug != src, "injection anchor not found" + with tempfile.TemporaryDirectory() as td: + bug_cpp = Path(td) / "box_distance_bug.cpp" + bug_cpp.write_text(bug) + bug_exe = Path(td) / "recon_bug.exe" + subprocess.run( + ["i686-w64-mingw32-g++", "-std=c++20", "-O2", "-mfpmath=sse", "-msse2", + "-ffp-contract=off", "-fno-fast-math", f"-I{ROOT}/include", f"-I{ROOT}/src", + f"-I{ROOT}/src/game", + "-L/nix/store/g72bh3mrbh6gkh59axd2199js9kccxfs-mcfgthread-i686-w64-mingw32-2.5.1/lib", + str(ROOT / "tools/unicorn_diff/recon_harness.cpp"), str(bug_cpp), + str(ROOT / "src/game/validity.cpp"), str(ROOT / "src/game/nui_elevation.cpp"), + "-o", str(bug_exe), "-static", "-static-libgcc", "-static-libstdc++"], + check=True, + ) + runner = UnicornRunner(image) + conv = load_calling_convention(0x1AB6D0) + box = struct.pack("<6f", 1.0, 2.0, 3.0, 2.0, 3.0, 4.0) + point = (1.3, 0.0, 2.5) + original = runner.run(CallSpec( + rva=0x1AB6D0, conv=conv, ret=ReturnKind.FLOAT_ST0, + regs=(RegValue("eax", buffer=Buffer("box", box)), + RegValue("edi", buffer=Buffer("pt", struct.pack("<3f", *point)))), + )) + recon = struct.unpack(" {report.verdict.value} {report.differences[0]}") + log.append("NON-VACUITY: PASS (injected reconstruction bug caught by the differential)") + + +def main() -> int: + if not RECON.is_file(): + print(f"missing {RECON}", file=sys.stderr) + return 2 + if shutil.which("wine") is None: + print("wine not on PATH", file=sys.stderr) + return 2 + image = PeImage(DLL) + log: list[str] = [f"DLL={DLL} base={image.image_base:#x} tol abs={TOL.absolute} rel={TOL.relative}"] + prove_box(image, log) + prove_elev(image, log) + prove_gate(image, log) + prove_injected_bug(image, log) + log.append("ALL DIFFERENTIALS PASS") + print("\n".join(log)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/unicorn_diff/recon_harness.cpp b/tools/unicorn_diff/recon_harness.cpp new file mode 100644 index 0000000..b363582 --- /dev/null +++ b/tools/unicorn_diff/recon_harness.cpp @@ -0,0 +1,189 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "gk/structs/manager.h" +#include "gk/structs/validity.h" +#include "game/validity.h" +#include "game/nui_elevation.h" + +using gk::LiveManager; +using gk::SkeletonData; +using gk::SkeletonTrackingState; +using gk::Vec3; +using gk::game::BoxDistanceSquared; +using gk::game::ElevationThread; +using gk::game::ICameraElevation; +using gk::game::UpdateCameraElevation; +using gk::game::UpdateValidityCandidates; +using gk::game::ValidityState; + +namespace { + +std::vector ReadHex() { + std::vector out; + std::string digits; + int c = 0; + while ((c = std::getchar()) != EOF) { + if (std::isxdigit(c) != 0) { + digits.push_back(static_cast(c)); + } + } + for (std::size_t i = 0; i + 1 < digits.size(); i += 2) { + out.push_back(static_cast( + std::strtol(digits.substr(i, 2).c_str(), nullptr, 16))); + } + return out; +} + +void PutHex(const void* data, std::size_t size) { + const auto* bytes = static_cast(data); + for (std::size_t i = 0; i < size; ++i) { + std::printf("%02x", bytes[i]); + } + std::printf("\n"); +} + +class ScriptedSensor final : public ICameraElevation { + public: + ScriptedSensor(std::int32_t angle, std::int32_t status) + : angle_(angle), status_(status) {} + + std::int32_t GK_STDCALL GetAngle(std::int32_t* out_degrees) override { + ++get_calls_; + *out_degrees = angle_; + return status_; + } + + std::int32_t GK_STDCALL SetAngle(std::int32_t degrees) override { + ++set_calls_; + set_arg_ = degrees; + return 0; + } + + std::int32_t get_calls_ = 0; + std::int32_t set_calls_ = 0; + std::int32_t set_arg_ = 0; + + private: + std::int32_t angle_; + std::int32_t status_; +}; + +float ReadFloat(const std::uint8_t* p) { + float v = 0.0F; + std::memcpy(&v, p, 4); + return v; +} + +std::uint32_t ReadU32(const std::uint8_t* p) { + std::uint32_t v = 0; + std::memcpy(&v, p, 4); + return v; +} + +int RunBox(const std::vector& in) { + gk::ValidityBox box{}; + Vec3 point{}; + std::memcpy(&box, in.data(), sizeof(box)); + std::memcpy(&point, in.data() + sizeof(box), sizeof(point)); + const float result = BoxDistanceSquared(box, point); + PutHex(&result, sizeof(result)); + return 0; +} + +int RunElev(const std::vector& in) { + const auto* p = in.data(); + ElevationThread thread{}; + thread.desired_angle = static_cast(ReadU32(p + 0)); + thread.applied_angle = static_cast(ReadU32(p + 4)); + thread.smoothed_angle = static_cast(ReadU32(p + 8)); + thread.accumulator = static_cast(ReadU32(p + 12)); + const auto angle = static_cast(ReadU32(p + 16)); + const auto status = static_cast(ReadU32(p + 20)); + ScriptedSensor sensor(angle, status); + thread.sensor = &sensor; + UpdateCameraElevation(thread); + std::uint8_t out[28]; + std::memcpy(out + 0, &thread.desired_angle, 4); + std::memcpy(out + 4, &thread.applied_angle, 4); + std::memcpy(out + 8, &thread.smoothed_angle, 4); + std::memcpy(out + 12, &thread.accumulator, 4); + std::memcpy(out + 16, &sensor.set_calls_, 4); + std::memcpy(out + 20, &sensor.set_arg_, 4); + std::memcpy(out + 24, &sensor.get_calls_, 4); + PutHex(out, sizeof(out)); + return 0; +} + +int RunGate(const std::vector& in) { + const auto* p = in.data(); + std::size_t off = 0; + ValidityState state{}; + std::memcpy(&state.transform, p + off, sizeof(state.transform)); + off += sizeof(state.transform); + std::memcpy(&state.box, p + off, sizeof(state.box)); + off += sizeof(state.box); + std::memcpy(&state.missing_position, p + off, sizeof(state.missing_position)); + off += sizeof(state.missing_position); + state.entry_tolerance = ReadFloat(p + off); + off += 4; + state.retained_tolerance = ReadFloat(p + off); + off += 4; + const std::uint8_t synthetic = p[off]; + off += 1; + + LiveManager manager{}; + std::memset(&manager, 0, sizeof(LiveManager)); + manager.synthetic_tracking_mode = synthetic; + for (std::size_t i = 0; i < gk::kSkeletonCount; ++i) { + SkeletonData& skel = manager.skeleton_frame.skeletons[i]; + skel.tracking_state = static_cast(ReadU32(p + off)); + off += 4; + skel.tracking_id = ReadU32(p + off); + off += 4; + skel.position.x = ReadFloat(p + off); + off += 4; + skel.position.y = ReadFloat(p + off); + off += 4; + skel.position.z = ReadFloat(p + off); + off += 4; + } + for (std::size_t i = 0; i < gk::kSkeletonCount; ++i) { + std::uint32_t id = ReadU32(p + off); + off += 4; + std::memcpy(&state.candidates[i].tracking_id, &id, 4); + state.candidates[i].valid = p[off]; + off += 1; + } + + UpdateValidityCandidates(manager, state); + PutHex(state.candidates, sizeof(state.candidates)); + return 0; +} + +} + +int main(int argc, char** argv) { + if (argc < 2) { + std::fprintf(stderr, "usage: recon \n"); + return 2; + } + const std::vector in = ReadHex(); + const std::string mode = argv[1]; + if (mode == "box") { + return RunBox(in); + } + if (mode == "elev") { + return RunElev(in); + } + if (mode == "gate") { + return RunGate(in); + } + std::fprintf(stderr, "unknown mode %s\n", argv[1]); + return 2; +}