Files
kinect/core/calibration/calibration.h
T

371 lines
14 KiB
C++

#ifndef NUI_CORE_CALIBRATION_H
#define NUI_CORE_CALIBRATION_H
#include <algorithm>
#include <array>
#include <cmath>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>
#include "mapping/mapping.h"
// The calibration module is header-only on purpose: the camera-agnostic cursor
// gains it resolves are consumed by three separate binaries that do NOT share a
// link unit - the OS-agnostic core test suite (Linux), the Windows NUI shim
// (`Kinect10.dll`), and the native Windows tracker. Keeping the logic inline
// here lets all three use the identical path/gain/derivation code by including
// this header, without adding `calibration.cpp` to each build.
namespace nui::calibration {
// --- Camera-agnostic cursor arm-reach gains -------------------------------
//
// The shim amplifies each arm outward from its shoulder so MediaPipe's
// compressed hand-relative reach spans the game's menu cursor range the way a
// real Kinect v1 does. These gains used to be hardcoded (3.2 / 2.6), tuned to
// one webcam/FOV; they are now resolvable (env > config file > default) and
// derivable per camera from a raised-arm hold.
constexpr float kDefaultArmGainX = 3.2f;
constexpr float kDefaultArmGainY = 2.6f;
constexpr float kArmGainMin = 1.0f;
constexpr float kArmGainMax = 6.0f;
// Target full-extension reach of HAND_R relative to the pivot shoulder, in
// post-L/R-swap post-mirror skeleton space (metres). Taken from real Kinect v1
// recordings, docs/game-internals.md section 3 (HAND_R - SHOULDER_CENTER x in
// [-0.35, +0.86], y reaching ~+0.5 above the shoulder).
constexpr float kTargetArmReachX = 0.86f;
constexpr float kTargetArmReachY = 0.5f;
struct ArmGains {
float x = kDefaultArmGainX;
float y = kDefaultArmGainY;
};
struct TposeObservation {
bool person_detected = false;
float root_depth_meters = 2.5f;
float normalized_shoulder_width = 0.0f;
std::array<float, 4> floor_plane{0.0f, 1.0f, 0.0f, 0.0f};
bool mirror = true;
};
struct RaiseRightArmObservation {
bool person_detected = false;
float right_shoulder_u = 0.0f;
float right_wrist_u = 0.0f;
float right_shoulder_v = 0.0f;
float right_wrist_v = 0.0f;
float left_shoulder_v = 0.0f;
float left_wrist_v = 0.0f;
// HAND_R relative to the amplification-pivot shoulder in post-L/R-swap,
// post-mirror skeleton space (metres) - exactly the excursion the shim's arm
// amplification scales. Populated during a cursor-reach calibration hold;
// zero on the mirror-confirm observations that do not measure reach.
float measured_reach_x = 0.0f;
float measured_reach_y = 0.0f;
};
struct CalibrationConfig {
mapping::MappingConfig mapping{};
mapping::SmoothingParameters smoothing{};
float player_scale = 1.0f;
std::array<float, 4> floor_plane{0.0f, 1.0f, 0.0f, 0.0f};
float arm_gain_x = kDefaultArmGainX;
float arm_gain_y = kDefaultArmGainY;
};
constexpr float kTargetShoulderWidthMeters = 0.40f;
namespace detail {
inline bool finite_value(float value) { return std::isfinite(value); }
// Strict full-token float parse for a gain field (env var or config token).
// Returns false (leaving `out` untouched) for an empty value, or one whose
// non-whitespace content is not entirely a finite float - so "2junk" is
// REJECTED rather than silently read as 2.0, and a garbled value falls through
// to the next source (config, then built-in default) instead of corrupting the
// gain.
inline bool parse_strict_float(const char* text, float& out) {
if (text == nullptr || *text == '\0') {
return false;
}
char* end = nullptr;
const double value = std::strtod(text, &end);
if (end == text) {
return false;
}
while (*end == ' ' || *end == '\t' || *end == '\r' || *end == '\n') {
++end;
}
if (*end != '\0' || !std::isfinite(value)) {
return false;
}
out = static_cast<float>(value);
return true;
}
} // namespace detail
// Canonical calibration config path shared by the tracker (writer) and the shim
// (reader): the KINECT_SHIM_CONFIG override when set, else
// `<LOCALAPPDATA>\VirtualKinect\calibration.cfg`. Pure - it takes the
// already-read environment strings so the identical path logic runs in both
// Windows binaries and is unit-testable off-Windows. A nullptr/empty argument
// means that variable is unset.
inline std::string calibration_config_path(const char* env_override,
const char* local_app_data) {
if (env_override != nullptr && *env_override != '\0') {
return std::string(env_override);
}
if (local_app_data != nullptr && *local_app_data != '\0') {
return std::string(local_app_data) + "\\VirtualKinect\\calibration.cfg";
}
return std::string("VirtualKinect\\calibration.cfg");
}
// Resolve the arm-reach gains with precedence
// env override (KINECT_SHIM_ARM_GAIN_X/_Y) > config-file value > built-in
// default (3.2 / 2.6).
// `base` supplies the file-or-default gains per axis; `env_x`/`env_y` are the
// raw environment strings (nullptr/empty = unset, unparseable = ignored).
inline ArmGains resolve_arm_gains(const ArmGains& base,
const char* env_x = nullptr,
const char* env_y = nullptr) {
ArmGains gains = base;
float parsed = 0.0f;
if (detail::parse_strict_float(env_x, parsed)) {
gains.x = parsed;
}
if (detail::parse_strict_float(env_y, parsed)) {
gains.y = parsed;
}
return gains;
}
// Convenience overload: take the file-or-default gains from a loaded config. A
// default-constructed CalibrationConfig (the fallback when no config file loads)
// already holds the built-in default, so a missing/malformed config resolves to
// 3.2 / 2.6 unless an env override is present.
inline ArmGains resolve_arm_gains(const CalibrationConfig& config,
const char* env_x = nullptr,
const char* env_y = nullptr) {
return resolve_arm_gains(ArmGains{config.arm_gain_x, config.arm_gain_y}, env_x,
env_y);
}
// The arm-reach amplification the shim's BuildSkeletonFrame applies: push each
// hand/elbow/wrist outward from its shoulder by the per-axis gain so MediaPipe's
// compressed reach spans the game's cursor range like a real Kinect. Templated
// on the position vector type so the production shim (NUI Vector4) and the host
// mechanism test (contract Vector4) run the IDENTICAL code - the single shipping
// definition of this transform. Only the six arm joints move; the hip, spine,
// head and the separate center-of-mass position are left untouched.
template <typename Vec>
inline void apply_arm_amplification(Vec* positions, const ArmGains& gains) {
const auto amplify = [&](int joint, int shoulder) {
positions[joint].x = positions[shoulder].x +
(positions[joint].x - positions[shoulder].x) * gains.x;
positions[joint].y = positions[shoulder].y +
(positions[joint].y - positions[shoulder].y) * gains.y;
};
amplify(9, 8); // ELBOW_RIGHT from SHOULDER_RIGHT
amplify(10, 8); // WRIST_RIGHT
amplify(11, 8); // HAND_RIGHT
amplify(5, 4); // ELBOW_LEFT from SHOULDER_LEFT
amplify(6, 4); // WRIST_LEFT
amplify(7, 4); // HAND_LEFT
}
// Derive camera-agnostic arm-reach gains from a raised/extended-right-arm hold.
// Each observation's measured_reach_{x,y} is HAND_R relative to the
// amplification-pivot shoulder in post-L/R-swap post-mirror skeleton space
// (metres). The gain per axis is target_reach / |mean measured_reach|, clamped
// to [kArmGainMin, kArmGainMax], averaged over the hold. Returns false (leaving
// `gains` unchanged) when no detected frame with a usable reach was observed.
inline bool derive_arm_gains(const std::vector<RaiseRightArmObservation>& hold,
ArmGains& gains,
std::string& error) {
double sum_x = 0.0;
double sum_y = 0.0;
int count = 0;
for (const RaiseRightArmObservation& observation : hold) {
if (!observation.person_detected) {
continue;
}
if (!detail::finite_value(observation.measured_reach_x) ||
!detail::finite_value(observation.measured_reach_y)) {
continue;
}
sum_x += std::fabs(observation.measured_reach_x);
sum_y += std::fabs(observation.measured_reach_y);
++count;
}
if (count == 0) {
error = "arm-gain calibration requires a detected raised-arm hold";
return false;
}
const float mean_x = static_cast<float>(sum_x / count);
const float mean_y = static_cast<float>(sum_y / count);
constexpr float kMinMeasuredReach = 1e-3f;
if (mean_x < kMinMeasuredReach || mean_y < kMinMeasuredReach) {
error = "arm-gain calibration reach too small - extend the arm fully";
return false;
}
gains.x = std::clamp(kTargetArmReachX / mean_x, kArmGainMin, kArmGainMax);
gains.y = std::clamp(kTargetArmReachY / mean_y, kArmGainMin, kArmGainMax);
error.clear();
return true;
}
// Mirror-confirm step: the subject raises only the anatomical right arm. A
// raw camera image places that arm on image-left, requiring the global mirror.
inline bool confirm_mirror_raise_right_arm(
const RaiseRightArmObservation& observation,
bool& mirror,
std::string& error) {
const bool right_raised =
observation.right_wrist_v < observation.right_shoulder_v;
const bool left_lowered =
observation.left_wrist_v >= observation.left_shoulder_v;
if (!observation.person_detected || !right_raised || !left_lowered) {
error = "mirror confirmation requires only the right arm raised";
return false;
}
mirror = observation.right_wrist_u < observation.right_shoulder_u;
error.clear();
return true;
}
// Produces the one-time T-pose calibration. The shoulder span establishes the
// player-space scale and Z0 preserves the observed root placement.
inline bool calibrate_tpose(
const TposeObservation& observation,
CalibrationConfig& output,
std::string& error) {
constexpr float kProjectionScale = 3.501e-3f;
constexpr float kMinZ = 0.8f;
constexpr float kMaxZ = 4.0f;
if (!observation.person_detected) {
error = "T-pose calibration requires one detected person";
return false;
}
if (!detail::finite_value(observation.root_depth_meters) ||
!detail::finite_value(observation.normalized_shoulder_width) ||
observation.normalized_shoulder_width <= 0.0f) {
error = "T-pose calibration observation is invalid";
return false;
}
CalibrationConfig candidate{};
candidate.mapping.z0_meters =
std::clamp(observation.root_depth_meters, kMinZ, kMaxZ);
candidate.mapping.depth_gain = 1.0f;
candidate.mapping.mirror = observation.mirror;
candidate.player_scale = kTargetShoulderWidthMeters /
(observation.normalized_shoulder_width * 320.0f *
kProjectionScale * candidate.mapping.z0_meters);
candidate.floor_plane = observation.floor_plane;
for (const float value : candidate.floor_plane) {
if (!detail::finite_value(value)) {
error = "T-pose floor plane is invalid";
return false;
}
}
output = candidate;
error.clear();
return true;
}
inline bool save_config(
const CalibrationConfig& config,
const std::string& path,
std::string& error) {
std::ofstream file(path, std::ios::trunc);
if (!file) {
error = "could not open calibration config for writing";
return false;
}
file << std::setprecision(9)
<< "depth_width " << config.mapping.depth_width << '\n'
<< "depth_height " << config.mapping.depth_height << '\n'
<< "z0_meters " << config.mapping.z0_meters << '\n'
<< "depth_gain " << config.mapping.depth_gain << '\n'
<< "mirror " << config.mapping.mirror << '\n'
<< "player_scale " << config.player_scale << '\n'
<< "smoothing " << config.smoothing.smoothing << ' '
<< config.smoothing.correction << ' ' << config.smoothing.prediction
<< ' ' << config.smoothing.jitter_radius << ' '
<< config.smoothing.max_deviation_radius << '\n'
<< "floor_plane " << config.floor_plane[0] << ' '
<< config.floor_plane[1] << ' ' << config.floor_plane[2] << ' '
<< config.floor_plane[3] << '\n'
<< "arm_gain_x " << config.arm_gain_x << '\n'
<< "arm_gain_y " << config.arm_gain_y << '\n';
if (!file) {
error = "could not write calibration config";
return false;
}
error.clear();
return true;
}
inline bool load_config(
const std::string& path,
CalibrationConfig& output,
std::string& error) {
std::ifstream file(path);
CalibrationConfig candidate{};
std::string key;
if (!file ||
!(file >> key >> candidate.mapping.depth_width) || key != "depth_width" ||
!(file >> key >> candidate.mapping.depth_height) || key != "depth_height" ||
!(file >> key >> candidate.mapping.z0_meters) || key != "z0_meters" ||
!(file >> key >> candidate.mapping.depth_gain) || key != "depth_gain" ||
!(file >> key >> candidate.mapping.mirror) || key != "mirror" ||
!(file >> key >> candidate.player_scale) || key != "player_scale" ||
!(file >> key >> candidate.smoothing.smoothing >>
candidate.smoothing.correction >> candidate.smoothing.prediction >>
candidate.smoothing.jitter_radius >>
candidate.smoothing.max_deviation_radius) || key != "smoothing" ||
!(file >> key >> candidate.floor_plane[0] >> candidate.floor_plane[1] >>
candidate.floor_plane[2] >> candidate.floor_plane[3]) ||
key != "floor_plane") {
error = "could not parse calibration config";
return false;
}
// arm_gain_{x,y} are an optional trailing pair: older configs predate them,
// so a missing key leaves the built-in default, and a malformed value is
// ignored rather than failing the whole load.
std::string extra;
while (file >> extra) {
if (extra != "arm_gain_x" && extra != "arm_gain_y") {
continue;
}
std::string token;
if (!(file >> token)) {
break;
}
float parsed = 0.0f;
if (!detail::parse_strict_float(token.c_str(), parsed)) {
continue;
}
if (extra == "arm_gain_x") {
candidate.arm_gain_x = parsed;
} else {
candidate.arm_gain_y = parsed;
}
}
output = candidate;
error.clear();
return true;
}
} // namespace nui::calibration
#endif // NUI_CORE_CALIBRATION_H