/*
 * Where the head points, for the glasses. Everything that draws or aims
 * in XR asks this, never a sensor itself, so 6DoF tracking
 * (or another pair of glasses) is one more source here and nothing else
 * changes. With none the head stays still, looking straight ahead.
 */
#include <stdlib.h>
#include "imu.h"
#include "server.h"

struct c8_tracker {
	struct c8_server *server;
	struct c8_imu *imu; // 3DoF from the glasses' own sensors
	/* or the runtime's pose, while Monado has the glasses */
	bool external;
	struct pose pose;
};

/* Tracking came, went or settled: frames start or stop, and a fresh
 * fix puts forward where the head points */
static void imu_changed(void *data, bool settled) {
	struct c8_tracker *tracker = data;
	c8_xr_tracking_changed(tracker->server, settled);
}

static void imu_settings(void *data, double *tilt_deg, bool *steady) {
	struct c8_tracker *tracker = data;
	*tilt_deg = tracker->server->config.glasses.tilt;
	*steady = tracker->server->config.glasses.steady;
}

static void imu_silent(void *data) {
	c8_exec("notify-send -a cont8nuum -i input-gaming "
		"'Head tracking isn’t working' "
		"'The glasses aren’t sending their motion. Check that their "
		"network shows up, and turn off their own Anchor or "
		"Stabiliser mode.'");
}

struct c8_tracker *c8_tracker_create(struct c8_server *server) {
	struct c8_tracker *tracker = calloc(1, sizeof(*tracker));
	tracker->server = server;
	struct c8_imu_host host = {
		.loop = server->loop,
		.changed = imu_changed,
		.settings = imu_settings,
		.silent = imu_silent,
		.data = tracker,
	};
	tracker->imu = c8_imu_create(&host);
	return tracker;
}

void c8_tracker_destroy(struct c8_tracker *tracker) {
	if (tracker) {
		c8_imu_destroy(tracker->imu);
	}
	free(tracker);
}

void c8_tracker_set_wanted(struct c8_tracker *tracker, bool wanted) {
	if (tracker) {
		c8_imu_set_wanted(tracker->imu, wanted);
	}
}

void c8_tracker_update(struct c8_tracker *tracker) {
	if (tracker) {
		c8_imu_read(tracker->imu);
	}
}

void c8_tracker_set_external(struct c8_tracker *tracker,
		const struct pose *pose) {
	if (tracker) {
		tracker->external = pose != NULL;
		if (pose) {
			tracker->pose = *pose;
		}
	}
}

bool c8_tracker_pose(struct c8_tracker *tracker, int64_t when_ns,
		struct pose *out) {
	*out = (struct pose){ { 0, 0, 0 }, quat_identity() };
	if (tracker && tracker->external) {
		/* Already for the frame's moment, neck and all */
		*out = tracker->pose;
		return true;
	}
	if (!tracker || !c8_imu_orientation(tracker->imu, when_ns,
			&out->orientation)) {
		return false;
	}
	/* Neck model: the head turns about the neck, not the eyes, so a turn
	 * or a tilt carries the eyes a few cm (a tilt left moves them left).
	 * Without it the slate swims against the room. */
	struct c8_config *c = &tracker->server->config;
	struct vec3 eyes = { 0, c->glasses.neck_up, -c->glasses.neck_ahead };
	out->position = vec3_sub(quat_rotate(out->orientation, eyes), eyes);
	return true;
}

