"the cursor scaling is still wrong, make it like the windows one" - the Linux tracker had no way to calibrate at all. The in-game cursor's arm-reach gains (default 3.2/2.6) were tuned specifically for the native Windows tracker's camera/pose characteristics via its "Calibrate cursor" button (core/calibration.h's derive_arm_gains); Linux users were stuck on that default regardless of their own camera/body, with no equivalent tool. tracker/calibration.py is a byte-for-byte port of core/calibration.h's arm-gain derivation (mean(|reach|) -> target/mean, clamped [1,6]) and the calibration.cfg text format load_config()/save_config() share, so a config written by either side is read identically by the shim - not a reimplementation that happens to produce similar numbers, the same formula and the same wire format, verified against tests/test_calibration.cpp's own cases (averaging, diagonal-gesture success, horizontal-only rejection, clamp-to-min, save/reload round-trip) ported 1:1 into tests/test_calibration_py.py - 6/6 passing, plus the existing tracker suite still 11/11. tracker.py gets a --calibrate mode (calibrate_cursor()): mirrors each frame for pose inference exactly like the main loop, computes Kinect joints with mirror=False, and reads HAND_LEFT (index 7) minus SHOULDER_LEFT (index 4) - the slots the player's actual right arm lands in post-mirror, pre-shim-swap, matching exactly where win_main.cpp's CalibrateCursor() reads skeleton.joints[7]/[4] (verified by reading that function directly). Usage: nix run .#tracker -- --calibrate --source 0. docs/calibration.md and docs/linux-wine.md document the Linux flow, the Linux default config path (no %LOCALAPPDATA% equivalent - XDG config dir), and that KINECT_SHIM_CONFIG must be set explicitly in both the calibration tool's environment and the game's launch options (Wine or Proton) so they agree on one file - the same pattern already established for KINECT_SHIM_SHM_FILE. Co-authored-by: sisyphus-dev-ai <sisyphus-dev-ai@users.noreply.github.com>
219 lines
8.0 KiB
Python
219 lines
8.0 KiB
Python
"""Camera-agnostic cursor arm-reach calibration, ported from core/calibration.h.
|
|
|
|
This is a byte-for-byte port of the arm-gain derivation and the shared
|
|
calibration.cfg text format the shim's load_config()/save_config() (C++,
|
|
core/calibration.h) read and write, so a config written here is read
|
|
identically by the shim regardless of which side wrote it. Only the arm-gain
|
|
calibration flow is ported (the "Calibrate cursor" button on the native
|
|
tracker); the T-pose scale/floor-plane calibration is not, since the shim
|
|
works fine on the CalibrationConfig{} defaults for those fields - only the
|
|
arm-reach gains need a per-camera value.
|
|
|
|
Formula and defaults are copied exactly from core/calibration.h (not
|
|
reimplemented independently): see kTargetArmReachX/Y, kArmGainMin/Max, and
|
|
derive_arm_gains's mean-of-abs-reach clamp-and-divide.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
from dataclasses import dataclass, field
|
|
from typing import Optional
|
|
|
|
# --- core/calibration.h constants (copied exactly) -------------------------
|
|
|
|
DEFAULT_ARM_GAIN_X = 3.2
|
|
DEFAULT_ARM_GAIN_Y = 2.6
|
|
ARM_GAIN_MIN = 1.0
|
|
ARM_GAIN_MAX = 6.0
|
|
TARGET_ARM_REACH_X = 0.86
|
|
TARGET_ARM_REACH_Y = 0.5
|
|
MIN_MEASURED_REACH = 1e-3
|
|
|
|
# --- core/mapping.h MappingConfig{} / SmoothingParameters{} defaults -------
|
|
# (the CalibrationConfig{} fields this module does not calibrate; written
|
|
# verbatim so a config written here, loaded by the shim, behaves exactly like
|
|
# one the native tracker would produce before ever running T-pose calibration)
|
|
|
|
DEFAULT_DEPTH_WIDTH = 640
|
|
DEFAULT_DEPTH_HEIGHT = 480
|
|
DEFAULT_Z0_METERS = 2.5
|
|
DEFAULT_DEPTH_GAIN = 0.0
|
|
DEFAULT_MIRROR = True
|
|
DEFAULT_PLAYER_SCALE = 1.0
|
|
DEFAULT_SMOOTHING = (0.6, 0.4, 0.4, 0.04, 0.07)
|
|
DEFAULT_FLOOR_PLANE = (0.0, 1.0, 0.0, 0.0)
|
|
|
|
|
|
@dataclass
|
|
class ArmGains:
|
|
x: float = DEFAULT_ARM_GAIN_X
|
|
y: float = DEFAULT_ARM_GAIN_Y
|
|
|
|
|
|
@dataclass
|
|
class CalibrationConfig:
|
|
depth_width: int = DEFAULT_DEPTH_WIDTH
|
|
depth_height: int = DEFAULT_DEPTH_HEIGHT
|
|
z0_meters: float = DEFAULT_Z0_METERS
|
|
depth_gain: float = DEFAULT_DEPTH_GAIN
|
|
mirror: bool = DEFAULT_MIRROR
|
|
player_scale: float = DEFAULT_PLAYER_SCALE
|
|
smoothing: tuple[float, float, float, float, float] = field(
|
|
default_factory=lambda: DEFAULT_SMOOTHING
|
|
)
|
|
floor_plane: tuple[float, float, float, float] = field(
|
|
default_factory=lambda: DEFAULT_FLOOR_PLANE
|
|
)
|
|
arm_gain_x: float = DEFAULT_ARM_GAIN_X
|
|
arm_gain_y: float = DEFAULT_ARM_GAIN_Y
|
|
|
|
|
|
def derive_arm_gains(
|
|
samples: list[tuple[float, float]],
|
|
) -> tuple[Optional[ArmGains], str]:
|
|
"""Exactly core/calibration.h's derive_arm_gains: gain = target_reach /
|
|
mean(|measured_reach|), clamped to [1.0, 6.0]. `samples` are
|
|
(measured_reach_x, measured_reach_y) pairs already filtered to
|
|
person-detected frames. Returns (None, error) on failure, matching the
|
|
C++ function's (false, error) contract."""
|
|
if not samples:
|
|
return None, "arm-gain calibration requires a detected raised-arm hold"
|
|
mean_x = sum(abs(x) for x, _ in samples) / len(samples)
|
|
mean_y = sum(abs(y) for _, y in samples) / len(samples)
|
|
if mean_x < MIN_MEASURED_REACH or mean_y < MIN_MEASURED_REACH:
|
|
return None, "arm-gain calibration reach too small - extend the arm fully"
|
|
gains = ArmGains(
|
|
x=min(max(TARGET_ARM_REACH_X / mean_x, ARM_GAIN_MIN), ARM_GAIN_MAX),
|
|
y=min(max(TARGET_ARM_REACH_Y / mean_y, ARM_GAIN_MIN), ARM_GAIN_MAX),
|
|
)
|
|
return gains, ""
|
|
|
|
|
|
def calibration_config_path(env_override: Optional[str] = None) -> str:
|
|
"""Linux equivalent of core/calibration.h's calibration_config_path: the
|
|
KINECT_SHIM_CONFIG override (shared with the shim - set it to the same
|
|
path, reachable from Wine via its Z: drive, in the game's launch options)
|
|
when set, else a Linux XDG-style default. There is no %LOCALAPPDATA% on
|
|
Linux, so this does not reuse the Windows-side default path string - set
|
|
KINECT_SHIM_CONFIG explicitly to share one file with the shim."""
|
|
override = env_override if env_override is not None else os.environ.get("KINECT_SHIM_CONFIG")
|
|
if override:
|
|
return override
|
|
xdg_config = os.environ.get("XDG_CONFIG_HOME") or os.path.join(
|
|
os.path.expanduser("~"), ".config"
|
|
)
|
|
return os.path.join(xdg_config, "VirtualKinect", "calibration.cfg")
|
|
|
|
|
|
def save_config(config: CalibrationConfig, path: str) -> None:
|
|
"""Writes the exact whitespace-delimited token format core/calibration.h's
|
|
save_config()/load_config() share - key, then its value(s), one line per
|
|
key. The shim's loader reads tokens via operator>>, so exact whitespace
|
|
layout does not matter, but the key names, order, and count of tokens
|
|
per key do."""
|
|
parent = os.path.dirname(path)
|
|
if parent:
|
|
os.makedirs(parent, exist_ok=True)
|
|
with open(path, "w") as f:
|
|
f.write(f"depth_width {config.depth_width}\n")
|
|
f.write(f"depth_height {config.depth_height}\n")
|
|
f.write(f"z0_meters {config.z0_meters!r}\n")
|
|
f.write(f"depth_gain {config.depth_gain!r}\n")
|
|
f.write(f"mirror {1 if config.mirror else 0}\n")
|
|
f.write(f"player_scale {config.player_scale!r}\n")
|
|
f.write("smoothing " + " ".join(repr(v) for v in config.smoothing) + "\n")
|
|
f.write("floor_plane " + " ".join(repr(v) for v in config.floor_plane) + "\n")
|
|
f.write(f"arm_gain_x {config.arm_gain_x!r}\n")
|
|
f.write(f"arm_gain_y {config.arm_gain_y!r}\n")
|
|
|
|
|
|
def load_config(path: str) -> Optional[CalibrationConfig]:
|
|
"""Mirrors core/calibration.h's load_config: strict token-by-token parse
|
|
of the required depth_width..floor_plane fields (None on any failure, so
|
|
a missing/corrupt file falls back to CalibrationConfig() defaults exactly
|
|
like the C++ side), then scans optional trailing arm_gain_x/arm_gain_y
|
|
tokens."""
|
|
try:
|
|
with open(path) as f:
|
|
tokens = f.read().split()
|
|
except OSError:
|
|
return None
|
|
|
|
def take(expected_key: str, count: int, pos: int):
|
|
if pos >= len(tokens) or tokens[pos] != expected_key:
|
|
return None, pos
|
|
pos += 1
|
|
if pos + count > len(tokens):
|
|
return None, pos
|
|
values = tokens[pos : pos + count]
|
|
return values, pos + count
|
|
|
|
pos = 0
|
|
values, pos = take("depth_width", 1, pos)
|
|
if values is None:
|
|
return None
|
|
depth_width = int(values[0])
|
|
values, pos = take("depth_height", 1, pos)
|
|
if values is None:
|
|
return None
|
|
depth_height = int(values[0])
|
|
values, pos = take("z0_meters", 1, pos)
|
|
if values is None:
|
|
return None
|
|
z0_meters = float(values[0])
|
|
values, pos = take("depth_gain", 1, pos)
|
|
if values is None:
|
|
return None
|
|
depth_gain = float(values[0])
|
|
values, pos = take("mirror", 1, pos)
|
|
if values is None:
|
|
return None
|
|
mirror = values[0] not in ("0", "0.0")
|
|
values, pos = take("player_scale", 1, pos)
|
|
if values is None:
|
|
return None
|
|
player_scale = float(values[0])
|
|
values, pos = take("smoothing", 5, pos)
|
|
if values is None:
|
|
return None
|
|
smoothing = tuple(float(v) for v in values)
|
|
values, pos = take("floor_plane", 4, pos)
|
|
if values is None:
|
|
return None
|
|
floor_plane = tuple(float(v) for v in values)
|
|
|
|
config = CalibrationConfig(
|
|
depth_width=depth_width,
|
|
depth_height=depth_height,
|
|
z0_meters=z0_meters,
|
|
depth_gain=depth_gain,
|
|
mirror=mirror,
|
|
player_scale=player_scale,
|
|
smoothing=smoothing,
|
|
floor_plane=floor_plane,
|
|
)
|
|
|
|
# Optional trailing arm_gain_x/arm_gain_y pair, in any order, mirroring
|
|
# the C++ loader's "while (file >> extra)" scan.
|
|
i = pos
|
|
while i < len(tokens):
|
|
key = tokens[i]
|
|
if key not in ("arm_gain_x", "arm_gain_y"):
|
|
i += 1
|
|
continue
|
|
if i + 1 >= len(tokens):
|
|
break
|
|
try:
|
|
value = float(tokens[i + 1])
|
|
except ValueError:
|
|
i += 2
|
|
continue
|
|
if key == "arm_gain_x":
|
|
config.arm_gain_x = value
|
|
else:
|
|
config.arm_gain_y = value
|
|
i += 2
|
|
|
|
return config
|