Files

898 lines
34 KiB
C++

// GCC 13 mingw-w64 (x86_64-w64-mingw32-g++-win32, this toolchain) has a real
// -O2 -finline-functions codegen bug that silently truncates/corrupts string
// literals in this translation unit (reproduced on pre-existing code too, not
// just new additions - e.g. CalibrateCursor's "Start capture first, then
// raise your right arm up and out to calibrate" truncates to "Start caH" without this).
// Disabling just this one pass for the file keeps -O2 everywhere else in the
// build while avoiding the bug; no build-script change needed.
#pragma GCC optimize ("no-inline-functions")
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <mfapi.h>
#include <commdlg.h>
#include <wincodec.h>
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <fstream>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
#include "calibration/calibration.h"
#include "frame_pipeline.h"
#include "pose_estimator.h"
#include "shm_publisher.h"
#include "trace_log.h"
#include "win_camera.h"
using namespace kinect_tracker;
namespace {
constexpr int kIdDevice = 1001;
constexpr int kIdResolution = 1002;
constexpr int kIdStart = 1003;
constexpr int kIdStatus = 1004;
constexpr int kIdCalibrate = 1005;
constexpr wchar_t kShmName[] = L"kinect_virtual_frames";
constexpr wchar_t kModelName[] = L"pose_landmarks_detector.onnx";
struct App {
HWND main = nullptr;
HWND device_combo = nullptr;
HWND res_combo = nullptr;
HWND start_btn = nullptr;
HWND calibrate_btn = nullptr;
HWND status = nullptr;
std::vector<CameraDevice> devices;
std::vector<CameraResolution> resolutions;
std::thread worker;
std::atomic<bool> running{false};
HANDLE mapping = nullptr;
uint8_t* shm_base = nullptr;
std::mutex preview_mutex;
std::vector<uint8_t> preview_bgra;
int preview_w = 0;
int preview_h = 0;
std::vector<uint8_t> test_bgra; // decoded test image (BGRA), used in image mode
int test_w = 0;
int test_h = 0;
std::string status_text = "Idle";
// Cursor-reach calibration: while cal_active, the worker samples the live
// post-L/R-swap arm reach into cal_samples for derive_arm_gains.
std::atomic<bool> cal_active{false};
std::mutex cal_mutex;
std::vector<nui::calibration::RaiseRightArmObservation> cal_samples;
};
App g_app;
std::wstring ExeDir() {
wchar_t path[MAX_PATH];
GetModuleFileNameW(nullptr, path, MAX_PATH);
std::wstring p(path);
const size_t slash = p.find_last_of(L"\\/");
return slash == std::wstring::npos ? L"." : p.substr(0, slash);
}
// Remember the camera + resolution the user last started, in a small text file
// next to the exe, so the dropdowns default to it on the next launch.
std::wstring LastSelectionPath() { return ExeDir() + L"\\kinect_tracker_last.txt"; }
void SaveLastSelection(const std::string& device_name, int width, int height) {
std::ofstream f(LastSelectionPath().c_str());
if (f) f << device_name << '\n' << width << ' ' << height << '\n';
}
bool LoadLastSelection(std::string& device_name, int& width, int& height) {
std::ifstream f(LastSelectionPath().c_str());
return f && std::getline(f, device_name) && (f >> width >> height) &&
!device_name.empty();
}
// Read a wide environment variable as a UTF-8 narrow string (empty = unset).
std::string EnvNarrow(const wchar_t* name) {
wchar_t buffer[1024];
const DWORD n = GetEnvironmentVariableW(name, buffer, 1024);
if (n == 0 || n >= 1024) return std::string();
const int len = WideCharToMultiByte(CP_UTF8, 0, buffer, static_cast<int>(n),
nullptr, 0, nullptr, nullptr);
std::string out(static_cast<size_t>(len), '\0');
WideCharToMultiByte(CP_UTF8, 0, buffer, static_cast<int>(n), out.data(), len,
nullptr, nullptr);
return out;
}
// Canonical calibration config path, shared byte-for-byte with the shim reader.
std::string CalibrationConfigPath() {
const std::string override_path = EnvNarrow(L"KINECT_SHIM_CONFIG");
const std::string local_app_data = EnvNarrow(L"LOCALAPPDATA");
return nui::calibration::calibration_config_path(
override_path.empty() ? nullptr : override_path.c_str(),
local_app_data.empty() ? nullptr : local_app_data.c_str());
}
// Create the config file's parent directory (e.g. %LOCALAPPDATA%\VirtualKinect)
// before writing; its own parent always exists.
void EnsureParentDir(const std::string& path) {
const size_t slash = path.find_last_of("\\/");
if (slash != std::string::npos) {
CreateDirectoryA(path.substr(0, slash).c_str(), nullptr);
}
}
std::string ModelPath() {
const std::wstring dir = ExeDir();
const wchar_t* candidates[] = {L"\\", L"\\models\\"};
for (const wchar_t* mid : candidates) {
std::wstring w = dir + mid + kModelName;
if (GetFileAttributesW(w.c_str()) != INVALID_FILE_ATTRIBUTES) {
std::string s(w.begin(), w.end());
return s;
}
}
std::wstring w = dir + L"\\" + kModelName;
return std::string(w.begin(), w.end());
}
void SetStatus(const std::string& text) {
{
std::lock_guard<std::mutex> lock(g_app.preview_mutex);
g_app.status_text = text;
}
SetWindowTextA(g_app.status, text.c_str());
}
// The tracker exe is a standalone x64 process - it never loads into DEA's
// (32-bit gamekdm.dll) address space and talks to the virtual-kinect shim
// only through shared memory, so there is no bitness coupling between them.
// Surfaced once at startup (status line + log) so a "wrong bitness" report
// can be ruled out without reasoning about the build.
void LogBitnessNote() {
const std::string msg =
std::string("Ready: ") + (sizeof(void*) == 8 ? "x64" : "x86") +
" build, a standalone process - no bitness dependency on DEA/gamekdm.dll "
"(32-bit) or the virtual-kinect shim DLL; they communicate only via "
"shared memory";
TraceLog("preflight: %s", msg.c_str());
SetStatus(msg);
}
void DrawOverlay(std::vector<uint8_t>& bgra, int w, int h, const PoseResult& pose) {
auto plot = [&](int x, int y, uint8_t b, uint8_t g, uint8_t r) {
for (int dy = -2; dy <= 2; ++dy) {
for (int dx = -2; dx <= 2; ++dx) {
const int px = x + dx, py = y + dy;
if (px < 0 || py < 0 || px >= w || py >= h) continue;
uint8_t* p = &bgra[(static_cast<size_t>(py) * w + px) * 4];
p[0] = b;
p[1] = g;
p[2] = r;
}
}
};
auto draw_line = [&](int x0, int y0, int x1, int y1, uint8_t b, uint8_t g,
uint8_t r) {
const int dx = x1 > x0 ? x1 - x0 : x0 - x1;
const int sx = x0 < x1 ? 1 : -1;
const int dy = -(y1 > y0 ? y1 - y0 : y0 - y1);
const int sy = y0 < y1 ? 1 : -1;
int err = dx + dy;
for (;;) {
for (int oy = -1; oy <= 1; ++oy)
for (int ox = -1; ox <= 1; ++ox) {
const int px = x0 + ox, py = y0 + oy;
if (px < 0 || py < 0 || px >= w || py >= h) continue;
uint8_t* p = &bgra[(static_cast<size_t>(py) * w + px) * 4];
p[0] = b;
p[1] = g;
p[2] = r;
}
if (x0 == x1 && y0 == y1) break;
const int e2 = 2 * err;
if (e2 >= dy) {
err += dy;
x0 += sx;
}
if (e2 <= dx) {
err += dx;
y0 += sy;
}
}
};
if (!pose.image_mask.empty() && pose.image_mask_width == w &&
pose.image_mask_height == h) {
for (size_t i = 0; i < static_cast<size_t>(w) * h; ++i) {
if (pose.image_mask[i] > 0.5f) {
uint8_t* p = &bgra[i * 4];
p[2] = static_cast<uint8_t>((p[2] + 255) / 2);
}
}
}
// Skeleton bones (MediaPipe-33 body connections): torso, arms, legs, neck.
static const int kBones[][2] = {
{11, 12}, {11, 13}, {13, 15}, {12, 14}, {14, 16}, {11, 23}, {12, 24},
{23, 24}, {23, 25}, {25, 27}, {27, 29}, {29, 31}, {24, 26}, {26, 28},
{28, 30}, {30, 32}, {0, 11}, {0, 12}};
for (const auto& bone : kBones) {
const int a = bone[0], c = bone[1];
const bool vis = pose.visibility[a] > 0.5f && pose.visibility[c] > 0.5f;
draw_line(static_cast<int>(pose.image_xy[a * 2]),
static_cast<int>(pose.image_xy[a * 2 + 1]),
static_cast<int>(pose.image_xy[c * 2]),
static_cast<int>(pose.image_xy[c * 2 + 1]),
vis ? 0 : 150, vis ? 255 : 150, vis ? 0 : 150);
}
for (int i = 0; i < kBodyLandmarks; ++i) {
const int x = static_cast<int>(pose.image_xy[i * 2]);
const int y = static_cast<int>(pose.image_xy[i * 2 + 1]);
if (pose.visibility[i] > 0.5f) {
plot(x, y, 0, 255, 0);
} else {
plot(x, y, 0, 160, 255);
}
}
}
// Decode an image file (jpg/png/bmp) to top-down BGRA via WIC.
bool LoadImageBGRA(const wchar_t* path, std::vector<uint8_t>& bgra, int& width,
int& height) {
IWICImagingFactory* factory = nullptr;
if (FAILED(CoCreateInstance(CLSID_WICImagingFactory, nullptr,
CLSCTX_INPROC_SERVER, IID_IWICImagingFactory,
reinterpret_cast<void**>(&factory)))) {
return false;
}
bool ok = false;
IWICBitmapDecoder* decoder = nullptr;
if (SUCCEEDED(factory->CreateDecoderFromFilename(
path, nullptr, GENERIC_READ, WICDecodeMetadataCacheOnDemand,
&decoder))) {
IWICBitmapFrameDecode* frame = nullptr;
if (SUCCEEDED(decoder->GetFrame(0, &frame))) {
IWICFormatConverter* converter = nullptr;
if (SUCCEEDED(factory->CreateFormatConverter(&converter))) {
if (SUCCEEDED(converter->Initialize(
frame, GUID_WICPixelFormat32bppBGRA, WICBitmapDitherTypeNone,
nullptr, 0.0, WICBitmapPaletteTypeCustom))) {
UINT uw = 0, uh = 0;
converter->GetSize(&uw, &uh);
width = static_cast<int>(uw);
height = static_cast<int>(uh);
bgra.resize(static_cast<size_t>(width) * height * 4);
if (SUCCEEDED(converter->CopyPixels(nullptr, width * 4,
static_cast<UINT>(bgra.size()),
bgra.data()))) {
ok = true;
}
}
converter->Release();
}
frame->Release();
}
decoder->Release();
}
factory->Release();
return ok;
}
void WorkerLoop(bool image_mode, std::wstring symlink, int req_w, int req_h) {
CoInitializeEx(nullptr, COINIT_MULTITHREADED);
// Preflight: fail fast with a distinct, actionable message (status line +
// log) for the one independently-diagnosable, runtime-reachable cause of
// "nothing happens after Start" at this point: the .onnx model file, which
// we open ourselves below. onnxruntime.dll is NOT checked here - it is an
// implicit (load-time) PE import of this exe, so if it were missing the
// Windows loader would already have failed to start the process before any
// of our code (including this preflight) could run; that failure is the
// OS's own "<exe> - This application was unable to start correctly" style
// dialog, not ours to duplicate or improve on here.
const std::string model_path = ModelPath();
if (GetFileAttributesA(model_path.c_str()) == INVALID_FILE_ATTRIBUTES) {
const std::string msg = "ERROR: pose model not found at '" + model_path +
"' - run scripts/setup_models.sh or reinstall the tracker bundle";
TraceLog("WorkerLoop preflight: %s", msg.c_str());
SetStatus(msg);
g_app.running = false;
return;
}
Camera camera;
std::vector<uint8_t> source_bgra;
int src_w = 0, src_h = 0;
if (image_mode) {
source_bgra = g_app.test_bgra;
src_w = g_app.test_w;
src_h = g_app.test_h;
TraceLog("WorkerLoop: test-image mode %dx%d", src_w, src_h);
} else if (!camera.open(symlink, req_w, req_h)) {
TraceLog("WorkerLoop: camera.open(%dx%d) FAILED", req_w, req_h);
SetStatus("ERROR: could not open camera - it may be disconnected or in use by another app");
g_app.running = false;
return;
}
TraceLog("WorkerLoop: camera open, loading model '%s'", model_path.c_str());
PoseEstimator estimator(model_path.c_str());
TraceLog("WorkerLoop: model loaded, entering capture loop");
PipelineConfig cfg;
FramePipeline pipeline(g_app.shm_base, cfg);
// A second mapper, configured identically to the pipeline's, lets the cursor
// calibration measure the live arm reach in the same skeleton space the shim
// amplifies (pipeline's own mapped skeleton is internal and not returned).
nui::mapping::MappingConfig cal_mapping_cfg;
cal_mapping_cfg.depth_width = static_cast<int>(cfg.depth_width);
cal_mapping_cfg.depth_height = static_cast<int>(cfg.depth_height);
cal_mapping_cfg.z0_meters = 2.5f;
cal_mapping_cfg.depth_gain = 1.0f;
cal_mapping_cfg.mirror = false;
nui::mapping::SkeletonMapper cal_mapper(cal_mapping_cfg);
Roi roi{};
bool have_lock = false;
std::vector<uint8_t> bgra;
std::vector<uint8_t> rgb;
int w = 0, h = 0;
uint32_t frame_number = 0;
const LARGE_INTEGER t0_now = [] {
LARGE_INTEGER x;
QueryPerformanceCounter(&x);
return x;
}();
LARGE_INTEGER freq;
QueryPerformanceFrequency(&freq);
// Capture thread: continuously pull frames and keep only the LATEST one, so
// the inference loop never processes a stale queued frame. This bounds
// end-to-end latency to a single inference instead of a growing FIFO backlog
// (the source reader queues frames when inference is slower than the camera).
std::mutex cap_mutex;
std::condition_variable cap_cv;
std::vector<uint8_t> cap_bgra;
int cap_w = 0, cap_h = 0;
std::atomic<uint64_t> cap_seq{0};
std::atomic<bool> cap_running{true};
std::thread cap_thread;
if (!image_mode) {
cap_thread = std::thread([&] {
CoInitializeEx(nullptr, COINIT_MULTITHREADED);
std::vector<uint8_t> tmp;
int tw = 0, th = 0;
while (cap_running.load() && g_app.running) {
if (camera.read_frame(tmp, tw, th)) {
{
std::lock_guard<std::mutex> lk(cap_mutex);
cap_bgra.swap(tmp);
cap_w = tw;
cap_h = th;
cap_seq.fetch_add(1, std::memory_order_release);
}
cap_cv.notify_one();
}
}
CoUninitialize();
});
}
uint64_t last_seq = 0;
while (g_app.running) {
if (image_mode) {
bgra = source_bgra;
w = src_w;
h = src_h;
Sleep(33);
} else {
// Block until the capture thread delivers a fresher frame (woken by the
// condition variable, so there's no fixed poll latency), then take
// ownership of its buffer by swapping instead of copying.
std::unique_lock<std::mutex> lk(cap_mutex);
cap_cv.wait_for(lk, std::chrono::milliseconds(100), [&] {
return cap_seq.load(std::memory_order_acquire) != last_seq ||
!g_app.running;
});
if (!g_app.running) break;
if (cap_seq.load(std::memory_order_acquire) == last_seq) continue;
bgra.swap(cap_bgra);
w = cap_w;
h = cap_h;
last_seq = cap_seq.load(std::memory_order_acquire);
}
// Mirror horizontally. Verified against real Kinect v1 recordings (UTKinect
// waveHands + MSR arm-waves): on a real Kinect the right hand reads as
// POSITIVE x relative to SHOULDER_CENTER (x in [-0.35,+0.86]). Running pose
// on the raw (un-mirrored) camera put our right hand at NEGATIVE x (our live
// log: [-0.5,0]) - the opposite handedness - which pinned the menu cursor.
// Mirroring the source makes the player's right hand land on the image right
// -> +x, matching real hardware, and also gives the natural selfie preview.
rgb.resize(static_cast<size_t>(w) * h * 3);
for (int y = 0; y < h; ++y) {
for (int x = 0; x < w; ++x) {
const size_t src = (static_cast<size_t>(y) * w + (w - 1 - x)) * 4;
const size_t dst = (static_cast<size_t>(y) * w + x) * 3;
rgb[dst + 0] = bgra[src + 2];
rgb[dst + 1] = bgra[src + 1];
rgb[dst + 2] = bgra[src + 0];
}
}
PoseResult pose = have_lock ? estimator.run(rgb.data(), w, h, roi)
: estimator.acquire(rgb.data(), w, h);
const bool tracked = pose.valid && pose.presence >= cfg.presence_threshold;
have_lock = tracked;
if (tracked) roi = pose.next_roi;
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
const int64_t ts_us = (now.QuadPart - t0_now.QuadPart) * 1000000 / freq.QuadPart;
pipeline.publish(++frame_number, ts_us, tracked ? &pose : nullptr, bgra.data(), w, h);
if (frame_number <= 3 || frame_number % 150u == 0) {
TraceLog("frame#%u %dx%d presence=%.3f tracked=%d",
frame_number, w, h, pose.presence, tracked ? 1 : 0);
}
if (tracked && g_app.cal_active.load()) {
std::array<nui::mapping::MediaPipeLandmark,
nui::mapping::kMediaPipeLandmarkCount>
landmarks{};
for (size_t i = 0; i < nui::mapping::kMediaPipeLandmarkCount; ++i) {
landmarks[i].u = pose.image_xy[i * 2] / static_cast<float>(w);
landmarks[i].v = pose.image_xy[i * 2 + 1] / static_cast<float>(h);
landmarks[i].visibility = pose.visibility[i];
landmarks[i].world_z = pose.world_z[i];
}
const auto skeleton = cal_mapper.map(landmarks);
// Shim post-L/R-swap HAND_RIGHT = source HAND_LEFT (NUI idx 7); pivot
// SHOULDER_RIGHT = source SHOULDER_LEFT (NUI idx 4). The source mirror
// already routed the player's right arm into the left joints.
const auto& hand = skeleton.joints[7].position;
const auto& shoulder = skeleton.joints[4].position;
nui::calibration::RaiseRightArmObservation obs;
obs.person_detected = true;
obs.measured_reach_x = hand.x - shoulder.x;
obs.measured_reach_y = hand.y - shoulder.y;
std::lock_guard<std::mutex> lock(g_app.cal_mutex);
g_app.cal_samples.push_back(obs);
}
std::vector<uint8_t> overlay = bgra;
if (tracked) DrawOverlay(overlay, w, h, pose);
{
std::lock_guard<std::mutex> lock(g_app.preview_mutex);
g_app.preview_bgra.swap(overlay);
g_app.preview_w = w;
g_app.preview_h = h;
g_app.status_text = tracked ? "Tracking (player detected)" : "No player detected";
}
}
if (!image_mode) {
cap_running = false;
if (cap_thread.joinable()) cap_thread.join();
camera.close();
}
CoUninitialize();
}
bool StartShm() {
PipelineConfig cfg;
const size_t region = ShmPublisher::region_size(cfg.depth_width, cfg.depth_height,
cfg.color_width, cfg.color_height);
g_app.mapping = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE,
static_cast<DWORD>((region >> 32) & 0xffffffffu),
static_cast<DWORD>(region & 0xffffffffu), kShmName);
// Both failure modes below share the same recovery instruction (the only
// realistic cause of either is another tracker instance already holding the
// mapping, or - rarely - a system out of resources) and both go to the
// status line AND the log verbatim, so there's exactly one message text to
// read regardless of which surface you're looking at. Each branch spells
// the full literal out (rather than sharing a concatenated constant) since
// this toolchain's string-section codegen has shown itself unreliable for
// literals built by concatenating a shared fragment at this optimization
// level - see the pragma note at the top of this file.
const DWORD create_err = GetLastError();
if (!g_app.mapping) {
const std::string msg =
"ERROR: shared memory create failed (err=" + std::to_string(create_err) +
") - close any other running tracker instance and retry";
TraceLog("%s", msg.c_str());
SetStatus(msg);
return false;
}
g_app.shm_base = static_cast<uint8_t*>(
MapViewOfFile(g_app.mapping, FILE_MAP_ALL_ACCESS, 0, 0, region));
if (!g_app.shm_base) {
const DWORD map_err = GetLastError();
const std::string msg =
"ERROR: shared memory map failed (err=" + std::to_string(map_err) +
") - close any other running tracker instance and retry";
TraceLog("%s", msg.c_str());
SetStatus(msg);
CloseHandle(g_app.mapping);
g_app.mapping = nullptr;
return false;
}
TraceLog("shm '%ls' region=%zu mapped=1 already_existed=%d", kShmName, region,
create_err == ERROR_ALREADY_EXISTS ? 1 : 0);
return true;
}
void StopShm() {
if (g_app.shm_base) {
UnmapViewOfFile(g_app.shm_base);
g_app.shm_base = nullptr;
}
if (g_app.mapping) {
CloseHandle(g_app.mapping);
g_app.mapping = nullptr;
}
}
void PopulateResolutions() {
SendMessage(g_app.res_combo, CB_RESETCONTENT, 0, 0);
const int sel = static_cast<int>(SendMessage(g_app.device_combo, CB_GETCURSEL, 0, 0));
if (sel < 0 || sel >= static_cast<int>(g_app.devices.size())) return;
// Only expose 4:3 resolutions: the emulated Kinect is natively 4:3, so a 16:9
// source would have to be stretched or letterboxed into the 4:3 depth/color
// frame, which misaligns the silhouette and skeleton in the game.
const auto all = enumerate_resolutions(g_app.devices[sel].symbolic_link);
g_app.resolutions.clear();
for (const auto& r : all) {
if (r.height > 0 && r.width * 3 == r.height * 4) {
g_app.resolutions.push_back(r);
}
}
if (g_app.resolutions.empty()) {
g_app.resolutions = all; // camera offers no 4:3 mode; show all rather than nothing
const std::string msg =
all.empty() ? "ERROR: camera reports no usable resolutions"
: "WARNING: no native 4:3 mode on this camera - picture will be "
"stretched/letterboxed in-game";
TraceLog("preflight: %s", msg.c_str());
SetStatus(msg);
}
for (const auto& r : g_app.resolutions) {
wchar_t buf[64];
wsprintfW(buf, L"%d x %d", r.width, r.height);
SendMessageW(g_app.res_combo, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(buf));
}
if (!g_app.resolutions.empty()) SendMessage(g_app.res_combo, CB_SETCURSEL, 0, 0);
}
void StartCapture() {
const int dsel = static_cast<int>(SendMessage(g_app.device_combo, CB_GETCURSEL, 0, 0));
if (dsel < 0) {
SetStatus("Pick a camera or test image first");
return;
}
// The entry after the real cameras is the test-image option.
if (dsel == static_cast<int>(g_app.devices.size())) {
wchar_t path[MAX_PATH] = L"";
OPENFILENAMEW ofn{};
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = g_app.main;
ofn.lpstrFilter = L"Images\0*.jpg;*.jpeg;*.png;*.bmp\0All files\0*.*\0";
ofn.lpstrFile = path;
ofn.nMaxFile = MAX_PATH;
ofn.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
if (!GetOpenFileNameW(&ofn)) {
SetStatus("No test image selected");
return;
}
if (!LoadImageBGRA(path, g_app.test_bgra, g_app.test_w, g_app.test_h)) {
SetStatus("ERROR: could not load image");
return;
}
if (!StartShm()) return;
g_app.running = true;
TraceLog("Start: test image %dx%d", g_app.test_w, g_app.test_h);
g_app.worker = std::thread(WorkerLoop, true, std::wstring(), 0, 0);
SetWindowTextA(g_app.start_btn, "Stop");
SetStatus("Starting (test image)...");
return;
}
const int rsel = static_cast<int>(SendMessage(g_app.res_combo, CB_GETCURSEL, 0, 0));
if (rsel < 0 || rsel >= static_cast<int>(g_app.resolutions.size())) {
SetStatus("Pick a camera and resolution first");
return;
}
if (!StartShm()) return;
g_app.running = true;
const CameraResolution res = g_app.resolutions[rsel];
TraceLog("Start: device[%d]='%s' %dx%d", dsel, g_app.devices[dsel].name.c_str(),
res.width, res.height);
g_app.worker = std::thread(WorkerLoop, false, g_app.devices[dsel].symbolic_link,
res.width, res.height);
SaveLastSelection(g_app.devices[dsel].name, res.width, res.height);
SetWindowTextA(g_app.start_btn, "Stop");
SetStatus("Starting...");
}
void StopCapture() {
g_app.running = false;
if (g_app.worker.joinable()) g_app.worker.join();
StopShm();
SetWindowTextA(g_app.start_btn, "Start");
SetStatus("Stopped");
}
// Run a short raised-arm hold, derive camera-specific cursor gains from it, and
// write them to the shared config the shim reads. Runs on a detached thread so
// the hold does not block the UI message loop.
void CalibrateCursor() {
if (!g_app.running) {
SetStatus("Start capture first, then raise your right arm up and out to calibrate");
return;
}
{
std::lock_guard<std::mutex> lock(g_app.cal_mutex);
g_app.cal_samples.clear();
}
g_app.cal_active = true;
SetStatus("Calibrating cursor: raise your right arm up and out toward the top corner of the screen - hand clearly above your shoulder and out to the side...");
std::thread([] {
std::this_thread::sleep_for(std::chrono::milliseconds(1800));
g_app.cal_active = false;
std::vector<nui::calibration::RaiseRightArmObservation> samples;
{
std::lock_guard<std::mutex> lock(g_app.cal_mutex);
samples.swap(g_app.cal_samples);
}
nui::calibration::ArmGains gains;
std::string error;
if (!nui::calibration::derive_arm_gains(samples, gains, error)) {
SetStatus("Calibration failed: " + error);
return;
}
const std::string path = CalibrationConfigPath();
nui::calibration::CalibrationConfig config;
std::string io_error;
nui::calibration::load_config(path, config, io_error);
config.arm_gain_x = gains.x;
config.arm_gain_y = gains.y;
EnsureParentDir(path);
if (nui::calibration::save_config(config, path, io_error)) {
SetStatus("Calibrated cursor gains X=" + std::to_string(gains.x) +
" Y=" + std::to_string(gains.y) + " (saved)");
} else {
SetStatus("Calibration save failed: " + io_error);
}
}).detach();
}
void PaintPreview(HWND hwnd, HDC hdc) {
RECT rc;
GetClientRect(hwnd, &rc);
const int top = 44;
const int avail_w = rc.right;
const int avail_h = rc.bottom - top;
if (avail_w <= 0 || avail_h <= 0) return;
// Compose the whole preview area in an off-screen bitmap, then blit it once.
// Painting the black fill and the image straight to the window produced a
// visible flash each frame; double-buffering removes it.
HDC mem = CreateCompatibleDC(hdc);
HBITMAP bmp = CreateCompatibleBitmap(hdc, avail_w, avail_h);
HBITMAP old_bmp = static_cast<HBITMAP>(SelectObject(mem, bmp));
const RECT full{0, 0, avail_w, avail_h};
FillRect(mem, &full, reinterpret_cast<HBRUSH>(GetStockObject(BLACK_BRUSH)));
{
std::lock_guard<std::mutex> lock(g_app.preview_mutex);
if (!g_app.preview_bgra.empty() && g_app.preview_w > 0 &&
g_app.preview_h > 0) {
// Scale to fit the box while preserving the frame's aspect ratio, centered.
const double src_ar =
static_cast<double>(g_app.preview_w) / g_app.preview_h;
const double dst_ar = static_cast<double>(avail_w) / avail_h;
int draw_w, draw_h;
if (src_ar > dst_ar) {
draw_w = avail_w;
draw_h = static_cast<int>(avail_w / src_ar + 0.5);
} else {
draw_h = avail_h;
draw_w = static_cast<int>(avail_h * src_ar + 0.5);
}
const int off_x = (avail_w - draw_w) / 2;
const int off_y = (avail_h - draw_h) / 2;
BITMAPINFO bmi{};
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = g_app.preview_w;
bmi.bmiHeader.biHeight = -g_app.preview_h;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB;
SetStretchBltMode(mem, HALFTONE);
StretchDIBits(mem, off_x, off_y, draw_w, draw_h, 0, 0, g_app.preview_w,
g_app.preview_h, g_app.preview_bgra.data(), &bmi,
DIB_RGB_COLORS, SRCCOPY);
}
}
BitBlt(hdc, 0, top, avail_w, avail_h, mem, 0, 0, SRCCOPY);
SelectObject(mem, old_bmp);
DeleteObject(bmp);
DeleteDC(mem);
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) {
switch (msg) {
case WM_CREATE: {
HINSTANCE inst = reinterpret_cast<LPCREATESTRUCT>(lparam)->hInstance;
g_app.device_combo = CreateWindowW(L"COMBOBOX", nullptr,
WS_CHILD | WS_VISIBLE | CBS_DROPDOWNLIST,
8, 8, 260, 300, hwnd,
reinterpret_cast<HMENU>(kIdDevice), inst, nullptr);
g_app.res_combo = CreateWindowW(L"COMBOBOX", nullptr,
WS_CHILD | WS_VISIBLE | CBS_DROPDOWNLIST,
276, 8, 150, 300, hwnd,
reinterpret_cast<HMENU>(kIdResolution), inst, nullptr);
g_app.start_btn = CreateWindowA("BUTTON", "Start", WS_CHILD | WS_VISIBLE,
434, 8, 70, 26, hwnd,
reinterpret_cast<HMENU>(kIdStart), inst, nullptr);
g_app.calibrate_btn = CreateWindowA("BUTTON", "Calibrate cursor",
WS_CHILD | WS_VISIBLE, 512, 8, 130, 26,
hwnd,
reinterpret_cast<HMENU>(kIdCalibrate),
inst, nullptr);
g_app.status = CreateWindowA("STATIC", "Idle", WS_CHILD | WS_VISIBLE,
650, 12, 300, 20, hwnd,
reinterpret_cast<HMENU>(kIdStatus), inst, nullptr);
g_app.devices = enumerate_cameras();
TraceLog("enumerated %zu camera(s)", g_app.devices.size());
for (const auto& d : g_app.devices) {
TraceLog(" camera: %s", d.name.c_str());
}
for (const auto& d : g_app.devices) {
SendMessageA(g_app.device_combo, CB_ADDSTRING, 0,
reinterpret_cast<LPARAM>(d.name.c_str()));
}
SendMessageA(g_app.device_combo, CB_ADDSTRING, 0,
reinterpret_cast<LPARAM>("[ Test image file... ]"));
LogBitnessNote();
// Default the dropdowns to whatever was selected last time, if that
// camera is still present; otherwise fall back to the first camera.
std::string last_name;
int last_w = 0, last_h = 0;
const bool has_last = LoadLastSelection(last_name, last_w, last_h);
int dev_sel = 0;
bool last_found = !has_last;
if (has_last) {
for (size_t i = 0; i < g_app.devices.size(); ++i) {
if (g_app.devices[i].name == last_name) {
dev_sel = static_cast<int>(i);
last_found = true;
break;
}
}
}
if (g_app.devices.empty()) {
const std::string msg = "No camera detected - plug in a webcam and restart the tracker";
TraceLog("preflight: %s", msg.c_str());
SetStatus(msg);
} else if (has_last && !last_found) {
const std::string msg = "Previously used camera '" + last_name +
"' not found - defaulting to the first available camera";
TraceLog("preflight: %s", msg.c_str());
SetStatus(msg);
}
if (!g_app.devices.empty()) {
SendMessage(g_app.device_combo, CB_SETCURSEL, dev_sel, 0);
PopulateResolutions();
if (has_last) {
for (size_t i = 0; i < g_app.resolutions.size(); ++i) {
if (g_app.resolutions[i].width == last_w &&
g_app.resolutions[i].height == last_h) {
SendMessage(g_app.res_combo, CB_SETCURSEL, i, 0);
break;
}
}
}
}
SetTimer(hwnd, 1, 33, nullptr);
return 0;
}
case WM_COMMAND: {
const int id = LOWORD(wparam);
const int code = HIWORD(wparam);
if (id == kIdDevice && code == CBN_SELCHANGE) {
PopulateResolutions();
} else if (id == kIdStart && code == BN_CLICKED) {
if (g_app.running) {
StopCapture();
} else {
StartCapture();
}
} else if (id == kIdCalibrate && code == BN_CLICKED) {
CalibrateCursor();
}
return 0;
}
case WM_TIMER: {
std::string st;
{
std::lock_guard<std::mutex> lock(g_app.preview_mutex);
st = g_app.status_text;
}
SetWindowTextA(g_app.status, st.c_str());
InvalidateRect(hwnd, nullptr, FALSE);
return 0;
}
case WM_ERASEBKGND: {
// Erase only the top control strip; the preview area below is fully
// repainted (double-buffered) in WM_PAINT, so erasing it here only
// causes flicker.
HDC hdc = reinterpret_cast<HDC>(wparam);
RECT rc;
GetClientRect(hwnd, &rc);
RECT strip{0, 0, rc.right, 44};
FillRect(hdc, &strip, reinterpret_cast<HBRUSH>(COLOR_WINDOW + 1));
return 1;
}
case WM_PAINT: {
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
PaintPreview(hwnd, hdc);
EndPaint(hwnd, &ps);
return 0;
}
case WM_DESTROY:
StopCapture();
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, msg, wparam, lparam);
}
}
int WINAPI wWinMain(HINSTANCE inst, HINSTANCE, PWSTR, int show) {
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
MFStartup(MF_VERSION);
TraceLog("==== kinect-tracker starting ====");
WNDCLASSW wc{};
wc.lpfnWndProc = WndProc;
wc.hInstance = inst;
wc.lpszClassName = L"KinectTrackerWnd";
wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
wc.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_WINDOW + 1);
RegisterClassW(&wc);
// Size the client so the preview area (below the 44px control strip) is a
// 4:3 box: with 4:3-only capture the image fills it edge to edge, no bars.
const int kStripH = 44;
const int kPreviewW = 820;
RECT wr{0, 0, kPreviewW, kStripH + kPreviewW * 3 / 4};
AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
g_app.main = CreateWindowW(L"KinectTrackerWnd", L"Kinect Tracker (native)",
WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,
wr.right - wr.left, wr.bottom - wr.top,
nullptr, nullptr, inst, nullptr);
ShowWindow(g_app.main, show);
UpdateWindow(g_app.main);
MSG msg;
while (GetMessage(&msg, nullptr, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
MFShutdown();
CoUninitialize();
return 0;
}