/*
 * Screens that show another's picture instead of their own part of the
 * layout: Duplicate (a mirror: the primary's frames, letterboxed) and the
 * glasses in XR.
 *
 * In XR the shell gets a screen of its own that isn't a display
 * at all: a headless output (the "virtual" one) that is the primary, so
 * Start, panels, toasts and the lock screen lay out on it as they always
 * have. Its frames are kept as the source picture. The glasses' real
 * output stays out of the layout; each of its frames is drawn here in GL:
 * the source as a slate in space, seen from where the tracker says the
 * head points, once per eye when the glasses are in side-by-side 3D
 * (3840x1080). Black is clear in the glasses, so the clear colour is.
 *
 * The GL is ours, issued inside a wlroots render pass on the glasses'
 * buffer: the pass makes the renderer's context current and binds the
 * buffer's framebuffer; wlroots sets the state it needs for each of its
 * own draws, so ours only has to leave the viewport and arrays as found.
 */
#define _GNU_SOURCE // memfd_create, pipe2
#include <cairo.h>
#include <EGL/egl.h>
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <drm_fourcc.h>
#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <wlr/backend/headless.h>
#include <wlr/backend/multi.h>
#include <wlr/interfaces/wlr_output.h>
#include <wlr/render/egl.h>
#include <wlr/render/gles2.h>
#include <wlr/render/pass.h>
#include <wlr/render/swapchain.h>
#include <wlr/types/wlr_buffer.h>
#include <wlr/types/wlr_output.h>
#include <wlr/types/wlr_output_layout.h>
#include <wlr/types/wlr_scene.h>
#include <wlr/util/log.h>
#include "server.h"


struct program {
	GLuint id;
	GLint mvp, mvp_end, tex, alpha, opaque, key, color, uv_rect, grow, edges;
	GLint pos, uv;
};

/* Soft edges: the quad grows by a few of its pixels each way, and the
 * sides that are a slate's edge fade over a screen pixel there (the rest
 * stay hard, so pieces of one window meet without a seam) */
struct aa {
	float grow[2]; // the quad's growth each way, in its own size
	float edges[4]; // left, top, right, bottom: 1 to fade
};
#define AA_MARGIN 3.0 // slate pixels: a screen pixel even at 3x the distance

struct c8_xr_gl {
	bool failed;
	struct program tex2d, external, solid, disc;
	/* The floor's grid: every line in one draw (see draw_floor) */
	GLuint lines;
	GLint lines_vp, lines_vp_end, lines_pos, lines_alpha;
	GLfloat *floor;
	int floor_count; // vertices
	/* How long the GPU took over a frame, asked without waiting for it:
	 * the answer comes a frame or two later (GL_EXT_disjoint_timer_query) */
	GLuint timer;
	bool timing; // a query is out, not yet answered
	void (*begin_query)(GLenum target, GLuint id);
	void (*end_query)(GLenum target);
	void (*query_uiv)(GLuint id, GLenum pname, GLuint *params);
	void (*query_ui64v)(GLuint id, GLenum pname, GLuint64 *params);
};

#define CURSOR_PX 7 // the pointer dot's radius, in slate pixels
#define FRAME_PX 2 // the focused window's accent frame
/* [glasses] outlines: the floor this far under the eyes, its grid of
 * metre squares out to GRID_M each way, fading out towards there */
#define FLOOR_M 1.2
#define GRID_M 8
#define LINE_M 0.01
#define DIM_UNDER_START 0.3f // windows' brightness while Start is up
#define DIM_RATE 0.2f // of the way there per frame
/* Windows going and coming back: closing, it shrinks to CLOSE_SCALE and
 * fades where it was; minimised, it shrinks to AWAY_SCALE and drops
 * AWAY_DROP_M towards the charms bar's row of them, and restored comes
 * back up the same way */
#define CLOSE_MS 200
#define CLOSE_SCALE 0.9
#define MINIMISE_MS 220
#define RESTORE_MS 280
#define AWAY_SCALE 0.6
#define AWAY_DROP_M 0.35
#define DIM_BY_THEATRE 0.25f // the other windows' while one plays fullscreen
#define BEACON_DIST 0.9 // m: a beacon, nearer than the windows

/* Setting up */

static void sink_schedule(struct c8_output *output) {
	output->sink_dirty = true;
	if (output->wlr_output->enabled) {
		wlr_output_schedule_frame(output->wlr_output);
	}
}

static void schedule_sinks(struct c8_server *server) {
	struct c8_output *output;
	wl_list_for_each(output, &server->outputs, link) {
		if (c8_output_is_sink(output)) {
			sink_schedule(output);
		}
	}
}

static void drop_picture(struct c8_server *server) {
	if (server->xr.picture_texture) {
		wlr_texture_destroy(server->xr.picture_texture);
		server->xr.picture_texture = NULL;
	}
	if (server->xr.picture) {
		wlr_buffer_unlock(server->xr.picture);
		server->xr.picture = NULL;
	}
}

static void eye_fov(double diagonal_deg, int w, int h, double *fov_x,
	double *fov_y);

void c8_xr_init(struct c8_server *server) {
	server->xr.centre = quat_identity();
	/* Until the first frame says otherwise: one 1080p eye, ahead */
	server->xr.head = (struct pose){ { 0, 0, 0 }, quat_identity() };
	server->xr.dim = 1;
	eye_fov(server->config.glasses.fov, 1920, 1080, &server->xr.fov_x,
		&server->xr.fov_y);
	server->xr.m_per_px = 2 * server->config.glasses.distance *
		tan(server->xr.fov_x / 2) / 1920;
	server->xr.tracker = c8_tracker_create(server);
	c8_xr_runtime_init(server);
	if (!wlr_backend_is_multi(server->backend)) {
		return;
	}
	server->xr.backend = wlr_headless_backend_create(server->loop);
	if (server->xr.backend == NULL ||
			!wlr_multi_backend_add(server->backend, server->xr.backend)) {
		wlr_log(WLR_ERROR, "XR: no headless backend");
		server->xr.backend = NULL;
	}
}

static void xr_audio(struct c8_server *server, bool on);
static void sky_cancel(void);
static void sky_drop(struct c8_server *server);

static void ghosts_drop(void);

void c8_xr_finish(struct c8_server *server) {
	sky_cancel();
	ghosts_drop();
	if (server->session) {
		xr_audio(server, false);
	}
	drop_picture(server);
	c8_slatebar_label_drop(server);
	c8_xr_runtime_finish(server); // before the tracker it sets poses in
	c8_tracker_destroy(server->xr.tracker);
	server->xr.tracker = NULL;
	if (server->xr.gl) {
		free(server->xr.gl->floor);
	}
	free(server->xr.gl);
	server->xr.gl = NULL;
}

/* XR can be drawn (a GLES2 renderer) */
static bool xr_possible(struct c8_server *server) {
	return server->xr.backend && wlr_renderer_is_gles2(server->renderer);
}

bool c8_xr_is_virtual(struct c8_server *server, struct wlr_output *output) {
	return server->xr.backend && output->backend == server->xr.backend;
}

bool c8_xr_is_view(struct c8_server *server, struct wlr_output *output) {
	return c8_xr_is_virtual(server, output) && (server->xr.view_coming ||
		output == server->xr.view_made);
}

/* What the runtime calls its headset, without Monado's "Monado: " in
 * front: shown under XR-VIEW when choosing what to share */
void c8_xr_headset_named(struct c8_server *server, const char *name) {
	const char *prefix = "Monado: ";
	if (strncmp(name, prefix, strlen(prefix)) == 0) {
		name += strlen(prefix);
	}
	snprintf(server->xr.headset, sizeof(server->xr.headset), "%s", name);
	if (server->xr.view && server->xr.headset[0]) {
		wlr_output_set_description(server->xr.view->wlr_output,
			server->xr.headset);
	}
}

/* Something wants a frame of the view. Not always a capture: every
 * wlr_output_schedule_frame says so too, and screencopy says it before
 * it takes its lock; so the frame (c8_xr_sink_frame) decides, by the
 * lock a capture holds until it has its picture */
void c8_xr_view_needs_frame(struct wl_listener *listener, void *data) {
	struct c8_output *output = wl_container_of(listener, output, needs_frame);
	output->sink_dirty = true;
	if (!output->server->xr.view_streaming) {
		wlr_output_schedule_frame(output->wlr_output);
	}
}

/* One of Monado's frames into the view, as its picture */
static void view_commit(struct c8_output *output, const uint8_t *pixels,
		int width, int height, int stride) {
	struct c8_server *server = output->server;
	struct wlr_output *wo = output->wlr_output;
	struct wlr_output_state state;
	wlr_output_state_init(&state);
	struct wlr_buffer *buffer = NULL;
	struct wlr_texture *texture = NULL;
	if (!wlr_output_configure_primary_swapchain(wo, &state, &wo->swapchain) ||
			(buffer = wlr_swapchain_acquire(wo->swapchain)) == NULL) {
		goto done;
	}
	/* R8G8B8X8 in memory: DRM's XBGR8888 */
	texture = wlr_texture_from_pixels(server->renderer, DRM_FORMAT_XBGR8888,
		stride, width, height, pixels);
	struct wlr_render_pass *pass = texture ?
		wlr_renderer_begin_buffer_pass(server->renderer, buffer, NULL) : NULL;
	if (pass == NULL) {
		goto done;
	}
	/* Fitted, not the view resized to it: a capture sizes its buffer by
	 * the mode, and one changed under it failed (nested, 2026-12-03).
	 * On the glasses both are one eye's 1920x1080 */
	double fit = MIN((double)buffer->width / width,
		(double)buffer->height / height);
	int w = (int)(width * fit + 0.5), h = (int)(height * fit + 0.5);
	wlr_render_pass_add_rect(pass, &(struct wlr_render_rect_options){
		.box = { 0, 0, buffer->width, buffer->height },
		.color = { 0, 0, 0, 1 },
	});
	wlr_render_pass_add_texture(pass, &(struct wlr_render_texture_options){
		.texture = texture,
		.dst_box = { (buffer->width - w) / 2, (buffer->height - h) / 2,
			w, h },
		.filter_mode = WLR_SCALE_FILTER_BILINEAR,
		.blend_mode = WLR_RENDER_BLEND_MODE_NONE,
	});
	if (wlr_render_pass_submit(pass)) {
		wlr_output_state_set_buffer(&state, buffer);
		if (wlr_output_commit_state(wo, &state)) {
			output->sink_dirty = false;
		}
	}
done:
	if (texture) {
		wlr_texture_destroy(texture);
	}
	if (buffer) {
		wlr_buffer_unlock(buffer);
	}
	wlr_output_state_finish(&state);
}

/* Monado's left eye, the layers put together: for a capture of the
 * view, and for Print in XR (screenshot.c asked for it) */
void c8_xr_share_frame(struct c8_server *server, const uint8_t *pixels,
		int width, int height, int stride) {
	if (server->xr.shot_action) {
		int action = server->xr.shot_action;
		server->xr.shot_action = 0;
		wl_event_source_timer_update(server->xr.shot_timer, 0);
		cairo_surface_t *image = cairo_image_surface_create(
			CAIRO_FORMAT_RGB24, width, height);
		if (cairo_surface_status(image) == CAIRO_STATUS_SUCCESS) {
			cairo_surface_flush(image);
			uint8_t *dst = cairo_image_surface_get_data(image);
			int dst_stride = cairo_image_surface_get_stride(image);
			for (int y = 0; y < height; y++) {
				const uint8_t *s = pixels + (size_t)y * stride;
				uint32_t *d = (uint32_t *)(dst + (size_t)y * dst_stride);
				for (int x = 0; x < width; x++, s += 4) {
					d[x] = (uint32_t)s[0] << 16 | (uint32_t)s[1] << 8 | s[2];
				}
			}
			cairo_surface_mark_dirty(image);
			c8_screenshot_finish(server, action, image, true);
		} else {
			cairo_surface_destroy(image);
		}
	}
	struct c8_output *view = server->xr.view;
	bool wanted = view && view->wlr_output->enabled &&
		view->wlr_output->attach_render_locks > 0;
	if (wanted) {
		server->xr.view_unwanted = 0;
		view_commit(view, pixels, width, height, stride);
	} else if (server->xr.view_streaming &&
			++server->xr.view_unwanted >= 10) {
		/* Nobody has captured it for a while (a portal stream lets go
		 * between its frames, so not on the first): Monado stops
		 * reading back */
		wlr_log(WLR_INFO, "XR: sharing ended");
		c8_xr_runtime_share(server, 's');
		server->xr.view_streaming = false;
	}
}

/* With Monado drawing the glasses nothing of ours shows what they do,
 * so screenshots came out blank and sharing had no screen to pick
 * (2026-12-02): a headless output of their one eye's size, out of the
 * layout and seen by the portal alone */
static void view_update(struct c8_server *server, bool monado,
		struct c8_output *glasses) {
	if (!monado) {
		if (server->xr.view_made) {
			struct wlr_output *wo = server->xr.view_made;
			server->xr.view_made = NULL;
			wlr_output_destroy(wo);
		}
		return;
	}
	if (server->xr.view_made) {
		return;
	}
	/* Monado's frames are fitted into it (view_commit) */
	int w = glasses ? glasses->wlr_output->width : 0;
	int h = glasses ? glasses->wlr_output->height : 0;
	if (w <= 0 || h <= 0) {
		w = 1920;
		h = 1080;
	} else if (w * 9 > h * 16 * 3 / 2) {
		w /= 2; // side by side: one eye
	}
	server->xr.view_coming = true;
	server->xr.view_made = wlr_headless_add_output(server->xr.backend, w, h);
	server->xr.view_coming = false;
	if (server->xr.view_made == NULL) {
		wlr_log(WLR_ERROR, "XR: no view for sharing");
	}
}

void c8_xr_recentre(struct c8_server *server) {
	struct pose head;
	c8_tracker_pose(server->xr.tracker, c8_now_ns(), &head);
	/* The world turns by the heading only, so it stays level: turning
	 * the head (about the real vertical) never tilts anything. Where
	 * you look up or down is where the slate goes instead, which also
	 * takes up the sensor sitting ~10 degrees tilted in the glasses */
	struct vec3 f = quat_rotate(head.orientation, (struct vec3){ 0, 0, -1 });
	server->xr.centre = quat_axis_angle((struct vec3){ 0, 1, 0 },
		quat_yaw(head.orientation));
	server->xr.centre_pitch = asin(fmax(-1, fmin(1, f.y)));
	c8_holo_recentred(server);
	schedule_sinks(server);
}

void c8_xr_tracking_changed(struct c8_server *server, bool settled) {
	if (settled) {
		c8_xr_recentre(server); // schedules
	} else {
		schedule_sinks(server);
	}
}

/* Sound goes with the picture: the glasses' own speakers (a USB sound
 * card, "XREAL…") become the default output while they're in mixed
 * reality, and the one before comes back after, unless something else
 * was chosen meanwhile. The card can show up a little after the display,
 * so it's waited for. */
static void xr_audio(struct c8_server *server, bool on) {
	if (on == server->xr.audio) {
		return;
	}
	server->xr.audio = on;
	c8_exec(on ?
		"f=\"$XDG_RUNTIME_DIR/c8-xr-sink\"; "
		"for i in 1 2 3 4 5 6 7 8 9 10; do "
		"s=$(pactl list sinks short | awk '$2 ~ /XREAL/ { print $2; exit }'); "
		"[ -n \"$s\" ] && break; sleep 1; done; "
		"[ -n \"$s\" ] || exit 0; "
		"d=$(pactl get-default-sink); "
		"[ \"$d\" = \"$s\" ] || echo \"$d\" > \"$f\"; "
		"pactl set-default-sink \"$s\"" :
		"f=\"$XDG_RUNTIME_DIR/c8-xr-sink\"; [ -f \"$f\" ] || exit 0; "
		"case $(pactl get-default-sink) in *XREAL*|'') "
		"pactl set-default-sink \"$(cat \"$f\")\";; esac; rm -f \"$f\"");
}

/* The duplicated screen: the built-in panel, else the first one on */
static struct c8_output *duplicate_source(struct c8_server *server) {
	struct c8_output *output, *first = NULL;
	wl_list_for_each(output, &server->outputs, link) {
		if (!output->wlr_output->enabled ||
				c8_output_is_virtual(output)) {
			continue;
		}
		if (output->builtin) {
			return output;
		}
		if (first == NULL) {
			first = output;
		}
	}
	return first;
}

static void xr_update_once(struct c8_server *server);

void c8_xr_update(struct c8_server *server) {
	if (server->xr.updating) {
		/* Stopping Monado ends its lease at once, and the glasses
		 * coming back has to be seen: dropping this left XR on with
		 * nothing to draw on and the laptop's screen off, 2026-12-02 */
		server->xr.update_again = true;
		return;
	}
	for (int i = 0; i < 4; i++) {
		server->xr.updating = true;
		server->xr.update_again = false;
		xr_update_once(server);
		server->xr.updating = false;
		if (!server->xr.update_again) {
			return;
		}
	}
	wlr_log(WLR_ERROR, "XR: the displays' roles keep changing");
}

static void xr_update_once(struct c8_server *server) {
	int now = c8_project_now(server);
	bool xr = now == C8_PROJECT_XR && xr_possible(server);
	bool dup = now == C8_PROJECT_DUPLICATE;

	if (xr && server->xr.shell_made == NULL) {
		/* new_output takes it as the virtual one, at once or (starting
		 * up) when the backend starts */
		server->xr.shell_made = wlr_headless_add_output(server->xr.backend,
			server->config.glasses.screen_w, server->config.glasses.screen_h);
		if (server->xr.shell_made == NULL) {
			wlr_log(WLR_ERROR, "XR: no virtual output");
			xr = false;
		}
	} else if (!xr && server->xr.shell_made) {
		struct wlr_output *wo = server->xr.shell_made;
		server->xr.shell_made = NULL;
		c8_holo_restore_all(server); // nothing is minimised flat
		ghosts_drop();
		wlr_output_destroy(wo);
		sky_drop(server); // a hundred MB or more, for nobody
	}

	struct c8_output *source = xr ? server->xr.shell :
		dup ? duplicate_source(server) : NULL;
	struct c8_output *output, *glasses = NULL;
	wl_list_for_each(output, &server->outputs, link) {
		if (c8_output_is_virtual(output)) {
			continue;
		}
		enum c8_output_role role = C8_OUTPUT_NORMAL;
		output->leasing = false;
		if (xr && output->glasses) {
			role = C8_OUTPUT_GLASSES;
			if (glasses == NULL) {
				glasses = output;
			}
		} else if (dup && source && output != source) {
			role = C8_OUTPUT_MIRROR;
		}
		if (role != output->role) {
			wlr_log(WLR_INFO, "Display %s: %s", output->wlr_output->name,
				role == C8_OUTPUT_GLASSES ? "XR" :
				role == C8_OUTPUT_MIRROR ? "duplicating" : "its own picture");
			if (output->capture_global) {
				/* Its own global was only for capturing (see
				 * c8_xr_sink_frame); back in the layout it gets an
				 * everyone's one again */
				wlr_output_destroy_global(output->wlr_output);
				output->capture_global = false;
			}
			output->role = role;
			if (role != C8_OUTPUT_NORMAL) {
				sink_schedule(output);
			}
		}
	}
	/* Monado drives them, when it's chosen and there (xrruntime.c) */
	bool monado = c8_xr_runtime_update(server, xr, glasses);
	if (monado && glasses) {
		glasses->leasing = true; // offered: we don't draw on them
	}
	/* Granting the lease destroys the glasses' output: Monado running
	 * is what counts (blank screenshots were XR-1's, 2026-12-02) */
	view_update(server, monado, glasses);
	bool tracking = xr && glasses && !monado;
	if (xr) {
		/* [glasses] screen, or Start up; the glasses' rate (their role
		 * is set now) */
		c8_xr_shell_size(server);
	} else {
		c8_stereo_shows(server, 0); // players take their frames apart
	}
	c8_tracker_set_wanted(server->xr.tracker, tracking);
	if (server->session) {
		xr_audio(server, tracking || monado); // not from a nested test
	}
	if (source != server->xr.source) {
		server->xr.source = source;
		drop_picture(server);
		if (source && source->wlr_output->enabled) {
			/* A first picture for the sinks without waiting for damage */
			wlr_output_update_needs_frame(source->wlr_output);
		}
	}
}

#define SHELL_MAX_W 8192 // GL's textures go that far everywhere

void c8_xr_shell_size(struct c8_server *server) {
	struct wlr_output *wo = server->xr.shell_made;
	if (wo == NULL || server->xr.shell == NULL) {
		return; // not made, or not announced yet: made at screen size
	}
	struct c8_config *c = &server->config;
	int w = c->glasses.screen_w, h = c->glasses.screen_h;
	/* Start up, or still sweeping away */
	bool wide = server->start_visible || server->layers.start->node.enabled;
	if (wide && server->xr.start_width > w) {
		w = server->xr.start_width < SHELL_MAX_W ?
			server->xr.start_width : SHELL_MAX_W;
	}
	/* At the glasses' rate: at headless's own 60 the shell's animations
	 * (Start closing, toasts) moved in uneven steps in the glasses' 90 */
	int refresh = 0;
	struct c8_output *output;
	wl_list_for_each(output, &server->outputs, link) {
		if (output->role == C8_OUTPUT_GLASSES && output->wlr_output->enabled) {
			refresh = output->wlr_output->refresh;
		}
	}
	if (wo->width == w && wo->height == h &&
			(refresh == 0 || wo->refresh == refresh)) {
		return;
	}
	/* Where it is: the shell lays out again, and the glasses draw the
	 * bigger or smaller picture from its corner */
	struct wlr_output_state state;
	wlr_output_state_init(&state);
	wlr_output_state_set_custom_mode(&state, w, h, refresh);
	if (!wlr_output_commit_state(wo, &state)) {
		wlr_log(WLR_ERROR, "XR: screen size %dx%d refused", w, h);
	}
	wlr_output_state_finish(&state);
	c8_layers_arrange(server);
	c8_views_arrange(server);
}

void c8_xr_output_gone(struct c8_output *output) {
	struct c8_server *server = output->server;
	c8_xr_runtime_output_gone(server, output->wlr_output);
	if (server->xr.source == output) {
		server->xr.source = NULL;
		drop_picture(server);
	}
	if (server->xr.shell == output) {
		server->xr.shell = NULL;
		server->xr.shell_made = NULL;
	}
	if (server->xr.view_made == output->wlr_output) {
		server->xr.view_made = NULL;
	}
	if (server->xr.view == output) {
		server->xr.view = NULL;
		if (server->xr.view_streaming) {
			c8_xr_runtime_share(server, 's');
			server->xr.view_streaming = false;
		}
	}
}

/* What of the scene shows on a screen: the box round every rect and
 * buffer there, in the layout. The shell's screen is mostly bare in XR
 * (nothing at all on it with Start closed), and drawing all of it keyed
 * over the windows every frame was the dearest thing the glasses drew. */
static void shown_box(struct wlr_scene_node *node, int x, int y,
		const struct wlr_box *within, struct wlr_box *out) {
	if (!node->enabled) {
		return;
	}
	x += node->x;
	y += node->y;
	struct wlr_box b = { x, y, 0, 0 };
	if (node->type == WLR_SCENE_NODE_TREE) {
		struct wlr_scene_tree *tree = wlr_scene_tree_from_node(node);
		struct wlr_scene_node *child;
		wl_list_for_each(child, &tree->children, link) {
			shown_box(child, x, y, within, out);
		}
		return;
	} else if (node->type == WLR_SCENE_NODE_RECT) {
		struct wlr_scene_rect *rect = wlr_scene_rect_from_node(node);
		if (rect->color[3] <= 0) {
			return;
		}
		b.width = rect->width;
		b.height = rect->height;
	} else {
		struct wlr_scene_buffer *sb = wlr_scene_buffer_from_node(node);
		b.width = sb->dst_width > 0 ? sb->dst_width :
			sb->buffer ? sb->buffer->width : 0;
		b.height = sb->dst_height > 0 ? sb->dst_height :
			sb->buffer ? sb->buffer->height : 0;
		if (b.width <= 0 || b.height <= 0) {
			b = *within; // of a size not known here: all of it, then
		}
	}
	if (!wlr_box_intersection(&b, &b, within)) {
		return;
	}
	if (wlr_box_empty(out)) {
		*out = b;
		return;
	}
	int x2 = out->x + out->width > b.x + b.width ? out->x + out->width :
		b.x + b.width;
	int y2 = out->y + out->height > b.y + b.height ? out->y + out->height :
		b.y + b.height;
	out->x = out->x < b.x ? out->x : b.x;
	out->y = out->y < b.y ? out->y : b.y;
	out->width = x2 - out->x;
	out->height = y2 - out->y;
}

/* The source: rendered as usual, and the frame kept */

void c8_xr_source_frame(struct c8_output *output) {
	struct c8_server *server = output->server;
	struct wlr_scene_output *so = output->scene_output;
	/* As wlr_scene_output_commit: nothing new, nothing to do */
	if (!wlr_scene_output_needs_frame(so)) {
		return;
	}
	struct wlr_output_state state;
	wlr_output_state_init(&state);
	if (!wlr_scene_output_build_state(so, &state, NULL)) {
		wlr_output_state_finish(&state);
		return;
	}
	if ((state.committed & WLR_OUTPUT_STATE_BUFFER) && state.buffer) {
		drop_picture(server);
		server->xr.picture = wlr_buffer_lock(state.buffer);
		server->xr.picture_seq++;
		struct wlr_output *wo = output->wlr_output;
		server->xr.picture_w = wo->width;
		server->xr.picture_h = wo->height;
		server->xr.picture_src = state.buffer_src_box;
		server->xr.picture_dst = wlr_box_empty(&state.buffer_dst_box) ?
			(struct wlr_box){ 0, 0, wo->width, wo->height } :
			state.buffer_dst_box;
		/* The part of it with anything on, in its pixels */
		struct wlr_box screen, shown = { 0 };
		wlr_output_layout_get_box(server->output_layout, wo, &screen);
		if (!wlr_box_empty(&screen)) {
			shown_box(&server->scene->tree.node, 0, 0, &screen, &shown);
			double sx = (double)wo->width / screen.width;
			double sy = (double)wo->height / screen.height;
			int x2 = (int)ceil((shown.x + shown.width - screen.x) * sx);
			int y2 = (int)ceil((shown.y + shown.height - screen.y) * sy);
			shown.x = (int)floor((shown.x - screen.x) * sx);
			shown.y = (int)floor((shown.y - screen.y) * sy);
			shown.width = x2 - shown.x;
			shown.height = y2 - shown.y;
			server->xr.picture_shown = shown;
		} else {
			server->xr.picture_shown = server->xr.picture_dst;
		}
		schedule_sinks(server);
	}
	wlr_output_commit_state(output->wlr_output, &state);
	wlr_output_state_finish(&state);
}

/* GL */

/* The glasses light their rows top down over a frame, so a row lower down
 * is seen later, the head turned further: mvp is where things are for the
 * top row, mvp_end for the bottom one, and each vertex goes where its row
 * puts it (asked twice, as moving it moves its row) */
static const char vertex_src[] =
	"uniform mat4 mvp;\n"
	"uniform mat4 mvp_end;\n"
	"uniform vec4 uv_rect;\n"
	"uniform vec2 grow;\n"
	"attribute vec2 pos;\n"
	"attribute vec2 uv;\n"
	"varying vec2 v_uv;\n"
	"varying vec2 v_q;\n"
	"varying vec4 v_rect;\n"
	"float row(vec4 p) {\n"
	"	return p.w > 0.0 ? clamp(p.y / p.w * 0.5 + 0.5, 0.0, 1.0) : 0.5;\n"
	"}\n"
	"void main() {\n"
	"	vec2 q = pos * (1.0 + 2.0 * grow) - grow;\n"
	"	v_q = q;\n"
	"	v_rect = uv_rect;\n"
	"	v_uv = uv_rect.xy + q * uv_rect.zw;\n"
	"	vec4 a = mvp * vec4(q, 0.0, 1.0);\n"
	"	vec4 b = mvp_end * vec4(q, 0.0, 1.0);\n"
	"	gl_Position = mix(a, b, row(mix(a, b, row(a))));\n"
	"}\n";

/* How much of a pixel is inside the quad: by its distance in screen
 * pixels from each side that fades, all or nothing at the others */
#define COVER_SRC \
	"uniform vec4 edges;\n" \
	"varying vec2 v_q;\n" \
	"varying vec4 v_rect;\n" \
	"float cover() {\n" \
	"	vec4 d = vec4(v_q, 1.0 - v_q);\n" \
	"#if AA\n" \
	"	vec2 w = max(fwidth(v_q), vec2(1e-4));\n" \
	"	d /= vec4(w, w);\n" \
	"	vec4 c = mix(step(0.0, d), clamp(d + 0.5, 0.0, 1.0), edges);\n" \
	"#else\n" \
	"	vec4 c = step(0.0, d);\n" \
	"#endif\n" \
	"	return c.x * c.y * c.z * c.w;\n" \
	"}\n" \
	"vec2 inside() {\n" \
	"	return v_rect.xy + clamp(v_q, 0.0, 1.0) * v_rect.zw;\n" \
	"}\n"

/* The same shader for both kinds of texture, so they can't drift apart. */
#define TEX_SRC(pre, sampler) \
	pre \
	"precision mediump float;\n" \
	"uniform " sampler " tex;\n" \
	"uniform float alpha;\n" \
	"uniform float opaque;\n" \
	"uniform float key;\n" \
	COVER_SRC \
	"void main() {\n" \
	"	vec4 c = texture2D(tex, inside());\n" \
	"	if (opaque > 0.5) c.a = 1.0;\n" \
	"	if (key > 0.5 && max(c.r, max(c.g, c.b)) < 0.004) c = vec4(0.0);\n" \
	"	gl_FragColor = c * alpha * cover();\n" \
	"}\n"

static const char tex2d_src[] = TEX_SRC("", "sampler2D");
static const char external_src[] = TEX_SRC(
	"#extension GL_OES_EGL_image_external : require\n", "samplerExternalOES");

static const char solid_src[] =
	"precision mediump float;\n"
	"uniform vec4 color;\n"
	COVER_SRC
	"void main() {\n"
	"	gl_FragColor = color * cover();\n"
	"}\n";

/* The pointer: a white dot ringed in black, so it shows on anything,
 * its rims soft over a screen pixel */
static const char disc_src[] =
	"precision mediump float;\n"
	"uniform vec4 color;\n"
	"varying vec2 v_uv;\n"
	"void main() {\n"
	"	float d = length(v_uv - vec2(0.5)) * 2.0;\n"
	"#if AA\n"
	"	float w = max(fwidth(d), 1e-4);\n"
	"	float a = clamp((1.0 - d) / w + 0.5, 0.0, 1.0);\n"
	"	float ring = clamp((d - 0.7) / w + 0.5, 0.0, 1.0);\n"
	"#else\n"
	"	float a = d > 1.0 ? 0.0 : 1.0;\n"
	"	float ring = d > 0.7 ? 1.0 : 0.0;\n"
	"#endif\n"
	"	gl_FragColor = mix(color, vec4(0.0, 0.0, 0.0, 1.0), ring) * a;\n"
	"}\n";

/* Put before each fragment shader: soft edges need screen derivatives */
static const char aa_on[] =
	"#extension GL_OES_standard_derivatives : enable\n#define AA 1\n";
static const char aa_off[] = "#define AA 0\n";

static GLuint compile(GLenum type, const char *head, const char *src) {
	GLuint shader = glCreateShader(type);
	const char *parts[2] = { head, src };
	glShaderSource(shader, 2, parts, NULL);
	glCompileShader(shader);
	GLint ok;
	glGetShaderiv(shader, GL_COMPILE_STATUS, &ok);
	if (!ok) {
		char log[512];
		glGetShaderInfoLog(shader, sizeof(log), NULL, log);
		wlr_log(WLR_ERROR, "XR: shader: %s", log);
		glDeleteShader(shader);
		return 0;
	}
	return shader;
}

static bool link_program(struct program *p, const char *frag_src,
		bool aa) {
	GLuint vs = compile(GL_VERTEX_SHADER, "", vertex_src);
	GLuint fs = compile(GL_FRAGMENT_SHADER, aa ? aa_on : aa_off, frag_src);
	if (!vs || !fs) {
		glDeleteShader(vs);
		glDeleteShader(fs);
		return false;
	}
	p->id = glCreateProgram();
	glAttachShader(p->id, vs);
	glAttachShader(p->id, fs);
	glLinkProgram(p->id);
	glDetachShader(p->id, vs);
	glDetachShader(p->id, fs);
	glDeleteShader(vs);
	glDeleteShader(fs);
	GLint ok;
	glGetProgramiv(p->id, GL_LINK_STATUS, &ok);
	if (!ok) {
		wlr_log(WLR_ERROR, "XR: a program didn't link");
		glDeleteProgram(p->id);
		p->id = 0;
		return false;
	}
	p->mvp = glGetUniformLocation(p->id, "mvp");
	p->mvp_end = glGetUniformLocation(p->id, "mvp_end");
	p->tex = glGetUniformLocation(p->id, "tex");
	p->alpha = glGetUniformLocation(p->id, "alpha");
	p->opaque = glGetUniformLocation(p->id, "opaque");
	p->key = glGetUniformLocation(p->id, "key");
	p->uv_rect = glGetUniformLocation(p->id, "uv_rect");
	p->color = glGetUniformLocation(p->id, "color");
	p->grow = glGetUniformLocation(p->id, "grow");
	p->edges = glGetUniformLocation(p->id, "edges");
	p->pos = glGetAttribLocation(p->id, "pos");
	p->uv = glGetAttribLocation(p->id, "uv");
	return true;
}

static const char lines_vertex_src[] =
	"uniform mat4 vp;\n"
	"uniform mat4 vp_end;\n"
	"attribute vec3 pos;\n"
	"attribute float alpha;\n"
	"varying float v_alpha;\n"
	"float row(vec4 p) {\n"
	"	return p.w > 0.0 ? clamp(p.y / p.w * 0.5 + 0.5, 0.0, 1.0) : 0.5;\n"
	"}\n"
	"void main() {\n"
	"	v_alpha = alpha;\n"
	"	vec4 a = vp * vec4(pos, 1.0);\n"
	"	vec4 b = vp_end * vec4(pos, 1.0);\n"
	"	gl_Position = mix(a, b, row(mix(a, b, row(a))));\n"
	"}\n";

static const char lines_src[] =
	"precision mediump float;\n"
	"varying float v_alpha;\n"
	"void main() {\n"
	"	gl_FragColor = vec4(v_alpha);\n" // premultiplied white
	"}\n";

/* The floor's grid: lines a metre apart both ways, in metre pieces so
 * they can fade with distance. It never moves in the world, so its
 * vertices (x, y, z, alpha) are made once and drawn in one go; a quad
 * each with uniforms of its own was 400 draws a frame */
static void make_floor(struct c8_xr_gl *gl) {
	GLuint vs = compile(GL_VERTEX_SHADER, "", lines_vertex_src);
	GLuint fs = compile(GL_FRAGMENT_SHADER, "", lines_src);
	if (!vs || !fs) {
		glDeleteShader(vs);
		glDeleteShader(fs);
		return;
	}
	gl->lines = glCreateProgram();
	glAttachShader(gl->lines, vs);
	glAttachShader(gl->lines, fs);
	glLinkProgram(gl->lines);
	glDeleteShader(vs);
	glDeleteShader(fs);
	GLint ok;
	glGetProgramiv(gl->lines, GL_LINK_STATUS, &ok);
	if (!ok) {
		glDeleteProgram(gl->lines);
		gl->lines = 0;
		return;
	}
	gl->lines_vp = glGetUniformLocation(gl->lines, "vp");
	gl->lines_vp_end = glGetUniformLocation(gl->lines, "vp_end");
	gl->lines_pos = glGetAttribLocation(gl->lines, "pos");
	gl->lines_alpha = glGetAttribLocation(gl->lines, "alpha");

	gl->floor = calloc((2 * GRID_M + 1) * 2 * GRID_M * 2 * 6 * 4,
		sizeof(GLfloat));
	GLfloat *v = gl->floor;
	const float y = -FLOOR_M, t = LINE_M / 2;
	for (int k = -GRID_M; k <= GRID_M; k++) {
		for (int j = -GRID_M; j < GRID_M; j++) {
			float mid = j + 0.5f;
			float a = 0.55f * fmaxf(0, 1 - hypotf(k, mid) / GRID_M);
			if (a <= 0.01f) {
				continue;
			}
			/* Along z at x = k, and along x at z = k */
			float box[2][4] = { // x0, z0, x1, z1
				{ k - t, j, k + t, j + 1 }, { j, k - t, j + 1, k + t },
			};
			for (int b = 0; b < 2; b++) {
				float corner[6][2] = {
					{ box[b][0], box[b][1] }, { box[b][2], box[b][1] },
					{ box[b][0], box[b][3] }, { box[b][2], box[b][1] },
					{ box[b][2], box[b][3] }, { box[b][0], box[b][3] },
				};
				for (int c = 0; c < 6; c++) {
					*v++ = corner[c][0];
					*v++ = y;
					*v++ = corner[c][1];
					*v++ = a;
				}
			}
		}
	}
	gl->floor_count = (int)(v - gl->floor) / 4;
}

/* Made the first time, with the context current */
static struct c8_xr_gl *gl_get(struct c8_server *server) {
	if (server->xr.gl == NULL) {
		struct c8_xr_gl *gl = calloc(1, sizeof(*gl));
		bool aa = wlr_gles2_renderer_check_ext(server->renderer,
			"GL_OES_standard_derivatives");
		gl->failed = !link_program(&gl->tex2d, tex2d_src, aa) ||
			!link_program(&gl->solid, solid_src, aa) ||
			!link_program(&gl->disc, disc_src, aa);
		if (!gl->failed && wlr_gles2_renderer_check_ext(server->renderer,
				"GL_OES_EGL_image_external")) {
			link_program(&gl->external, external_src, aa);
		}
		if (!gl->failed) {
			make_floor(gl);
		}
		if (!gl->failed && wlr_gles2_renderer_check_ext(server->renderer,
				"GL_EXT_disjoint_timer_query")) {
			void (*gen)(GLsizei, GLuint *) =
				(void (*)(GLsizei, GLuint *))eglGetProcAddress("glGenQueriesEXT");
			gl->begin_query = (void (*)(GLenum, GLuint))
				eglGetProcAddress("glBeginQueryEXT");
			gl->end_query = (void (*)(GLenum))
				eglGetProcAddress("glEndQueryEXT");
			gl->query_uiv = (void (*)(GLuint, GLenum, GLuint *))
				eglGetProcAddress("glGetQueryObjectuivEXT");
			gl->query_ui64v = (void (*)(GLuint, GLenum, GLuint64 *))
				eglGetProcAddress("glGetQueryObjectui64vEXT");
			if (gen && gl->begin_query && gl->end_query && gl->query_uiv &&
					gl->query_ui64v) {
				gen(1, &gl->timer);
			}
		}
		server->xr.gl = gl;
	}
	return server->xr.gl->failed ? NULL : server->xr.gl;
}

/* Where the head is at a moment, turned so recentring's forward is
 * ahead */
static struct pose head_at(struct c8_server *server, int64_t when_ns) {
	struct pose head;
	c8_tracker_pose(server->xr.tracker, when_ns, &head);
	head.orientation = quat_mul(quat_conjugate(server->xr.centre),
		head.orientation);
	head.position = quat_rotate(quat_conjugate(server->xr.centre),
		head.position);
	return head;
}

/* How long the glasses take to light a frame top to bottom: by default
 * all of one refresh */
static double scan_ms(struct c8_output *output) {
	double ms = output->server->config.glasses.scanout;
	if (ms >= 0) {
		return ms;
	}
	int mhz = output->wlr_output->refresh;
	return mhz > 0 ? 1e6 / mhz : 1000.0 / 60;
}

/* What one eye sees with: as the top row lights up and as the bottom one
 * does */
struct eye {
	struct mat4 view_proj[2];
	int x, width, height; // its viewport
};

/* A quad's matrices for those two moments */
struct mvp {
	struct mat4 m[2];
};

/* A rectangle of a slate's pixels, as a quad: px is the rectangle in the
 * slate's pixels (size w x h), the slate pose_m is its centre in the
 * world and m_per_px its pixel size there */
static struct mvp quad_matrix(const struct eye *eye, struct pose slate,
		double m_per_px, int w, int h, double px, double py, double pw,
		double ph) {
	double sx = pw * m_per_px, sy = -ph * m_per_px;
	double tx = (px - w / 2.0) * m_per_px, ty = (h / 2.0 - py) * m_per_px;
	struct mat4 model = mat4_mul(mat4_from_pose(slate),
		mat4_scale_translate(sx, sy, tx, ty));
	return (struct mvp){ { mat4_mul(eye->view_proj[0], model),
		mat4_mul(eye->view_proj[1], model) } };
}

static void set_mvp(struct program *p, const struct mvp *mvp) {
	glUniformMatrix4fv(p->mvp, 1, GL_FALSE, mvp->m[0].m);
	glUniformMatrix4fv(p->mvp_end, 1, GL_FALSE, mvp->m[1].m);
}

static const GLfloat unit_quad[] = { 0, 0, 1, 0, 0, 1, 1, 1 };

/* A quad of one colour (or the pointer's dot) */
/* Which sides of a quad pw x ph (slate pixels) fade */
static struct aa aa_sides(double pw, double ph, bool l, bool t, bool r,
		bool b) {
	struct aa a = { { 0, 0 }, { l, t, r, b } };
	if (l || t || r || b) {
		a.grow[0] = AA_MARGIN / fmax(pw, 1);
		a.grow[1] = AA_MARGIN / fmax(ph, 1);
	}
	return a;
}

static void set_aa(struct program *p, const struct aa *a) {
	static const struct aa hard = { { 0, 0 }, { 0, 0, 0, 0 } };
	if (a == NULL) {
		a = &hard;
	}
	glUniform2fv(p->grow, 1, a->grow);
	glUniform4fv(p->edges, 1, a->edges);
}

/* Draw calls so far: none into the overlay's projection, and it isn't
 * given to the runtime at all (xrclient.c) */
static unsigned draw_count;

/* The quad itself, with the program's uniforms set */
static void draw_unit_quad(const struct program *p) {
	glVertexAttribPointer(p->pos, 2, GL_FLOAT, GL_FALSE, 0, unit_quad);
	glEnableVertexAttribArray(p->pos);
	/* The shader may work uv out from pos, and the compiler then drops
	 * the input: -1 here, and an error for every quad if passed */
	if (p->uv >= 0) {
		glVertexAttribPointer(p->uv, 2, GL_FLOAT, GL_FALSE, 0, unit_quad);
		glEnableVertexAttribArray(p->uv);
	}
	glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
	draw_count++;
	glDisableVertexAttribArray(p->pos);
	if (p->uv >= 0) {
		glDisableVertexAttribArray(p->uv);
	}
}

static void draw_solid(struct program *p, const struct mvp *mvp,
		const float color[4], const struct aa *aa) {
	glUseProgram(p->id);
	set_mvp(p, mvp);
	set_aa(p, aa);
	glUniform4f(p->uv_rect, 0, 0, 1, 1);
	glUniform4fv(p->color, 1, color);
	draw_unit_quad(p);
}

/* src is the part of the texture drawn, as fractions of it; key makes
 * black clear (the shell's screen has no alpha where nothing is) */
static void draw_texture_part(struct c8_xr_gl *gl, const struct mvp *mvp,
		struct wlr_texture *texture, float alpha, const float src[4],
		bool key, const struct aa *aa) {
	struct wlr_gles2_texture_attribs attribs;
	wlr_gles2_texture_get_attribs(texture, &attribs);
	struct program *p = attribs.target == GL_TEXTURE_EXTERNAL_OES ?
		&gl->external : &gl->tex2d;
	if (p->id == 0) {
		return;
	}
	glUseProgram(p->id);
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(attribs.target, attribs.tex);
	glTexParameteri(attribs.target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(attribs.target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	set_mvp(p, mvp);
	set_aa(p, aa);
	glUniform1i(p->tex, 0);
	glUniform1f(p->alpha, alpha);
	glUniform1f(p->opaque, attribs.has_alpha ? 0 : 1);
	glUniform1f(p->key, key ? 1 : 0);
	glUniform4fv(p->uv_rect, 1, src);
	draw_unit_quad(p);
	glBindTexture(attribs.target, 0);
}

/* Field of view per eye from the diagonal one, for the viewport's shape */
static void eye_fov(double diagonal_deg, int w, int h, double *fov_x,
		double *fov_y) {
	double t = tan(diagonal_deg * M_PI / 360);
	double d = sqrt((double)w * w + (double)h * h);
	*fov_x = 2 * atan(t * w / d);
	*fov_y = 2 * atan(t * h / d);
}

/* The eyes for a frame: one, or two side by side. head is recentred. */
static int eyes_for(struct c8_server *server, int width, int height,
		const struct pose heads[2], struct eye eyes[2], double *m_per_px,
		double *fov_x, double *fov_y) {
	struct c8_config *c = &server->config;
	/* Side-by-side 3D doubles the width: 32:9 */
	int count = width * 9 > height * 16 * 3 / 2 ? 2 : 1;
	int ew = width / count;
	eye_fov(c->glasses.fov, ew, height, fov_x, fov_y);
	/* The shell's screen at its distance, one of its pixels to one of the
	 * glasses' straight ahead: sharp, and as big as the glasses show */
	*m_per_px = 2 * c->glasses.distance * tan(*fov_x / 2) / ew;

	struct mat4 proj = mat4_perspective(*fov_y, (double)ew / height, 0.05,
		100);
	/* Rows of the buffer run top down; GL's clip space bottom up */
	struct mat4 flip = mat4_scale_translate(1, -1, 0, 0);
	proj = mat4_mul(flip, proj);
	for (int i = 0; i < count; i++) {
		for (int k = 0; k < 2; k++) {
			struct pose eye = heads[k];
			if (count == 2) {
				double half = c->glasses.ipd / 2000 * (i == 0 ? -1 : 1);
				eye.position = pose_point(eye, half, 0, 0);
			}
			eyes[i].view_proj[k] = mat4_mul(proj, mat4_view(eye));
		}
		eyes[i].x = i * ew;
		eyes[i].width = ew;
		eyes[i].height = height;
	}
	return count;
}

/* One window's slate: each of its surfaces (popups and subsurfaces too)
 * from its texture, where the scene has it relative to the window */

struct slate_draw {
	struct c8_xr_gl *gl;
	const struct eye *eye;
	struct pose pose;
	double m;
	struct wlr_box geo; // the window, in the layout
	struct timespec *now; // set on the last eye: frames are done
	float alpha; // under Start they're dimmed
	double curve; // m: bent round you on a cylinder this wide; 0 flat
	/* For windows: 3D surfaces give this eye its picture (0 the left,
	 * 1 the right), and the one that is round you isn't drawn here */
	struct c8_server *server;
	int which;
	struct wlr_surface *around;
	/* Show as 3D, chosen on its slate bar (view->holo.stereo): the
	 * window's own surface, unless the app tags it itself */
	struct wlr_surface *main;
	int main_layout;
};

/* The part of a 3D surface's buffer that is one eye's picture, half a
 * texel in from the other's so they don't run into each other */
static void stereo_src(uint32_t layout, bool right_first, int which,
		struct wlr_texture *texture, float src[4]) {
	int half = (which != 0) != right_first;
	if (layout == 1) {
		float in = 0.5f / texture->width;
		src[2] = src[2] / 2 - in;
		src[0] += half ? src[2] + 2 * in : 0;
	} else if (layout == 2) {
		float in = 0.5f / texture->height;
		src[3] = src[3] / 2 - in;
		src[1] += half ? src[3] + 2 * in : 0;
	}
}

#define CURVE_STRIP_PX 32 // a curved slate is drawn in strips this wide

/* A strip of a curved slate, its middle `x` slate pixels from the
 * slate's: on the cylinder (its axis the slate's up, `r` in front of
 * it), turned to face the axis */
static struct pose curve_strip(struct pose slate, double r, double m,
		double x) {
	if (r <= 0) {
		/* Unrolled: the cylinder's drawn flat for a runtime to bend */
		return (struct pose){ pose_point(slate, x * m, 0, 0),
			slate.orientation };
	}
	double a = x * m / r;
	return (struct pose){
		pose_point(slate, r * sin(a), 0, r * (1 - cos(a))),
		quat_mul(slate.orientation,
			quat_axis_angle((struct vec3){ 0, 1, 0 }, -a)),
	};
}

static void draw_surface(struct wlr_scene_buffer *buffer, int lx, int ly,
		void *data) {
	struct slate_draw *sd = data;
	struct wlr_scene_surface *ss = wlr_scene_surface_try_from_buffer(buffer);
	if (ss == NULL) {
		return;
	}
	struct wlr_surface *surface = ss->surface;
	struct wlr_texture *texture = wlr_surface_get_texture(surface);
	if (sd->now) {
		/* No output shows it, so nobody else tells it to draw again */
		wlr_surface_send_frame_done(surface, sd->now);
	}
	if (texture == NULL || surface->current.width <= 0) {
		return;
	}
	struct wlr_fbox box;
	wlr_surface_get_buffer_source_box(surface, &box);
	float src[4] = {
		box.x / texture->width, box.y / texture->height,
		box.width / texture->width, box.height / texture->height,
	};
	if (sd->server) {
		if (surface == sd->around) {
			return; // a sphere: round you, not on the window
		}
		struct c8_stereo_surface *st = c8_stereo_for(sd->server, surface);
		if (st && (st->layout || sd->main != surface)) {
			stereo_src(st->layout, st->right_first, sd->which, texture, src);
		} else if (surface == sd->main && sd->main_layout) {
			stereo_src(sd->main_layout, false, sd->which, texture, src);
		}
	}
	int x = lx - sd->geo.x, y = ly - sd->geo.y;
	int w = surface->current.width, h = surface->current.height;
	if (sd->curve > 0) {
		for (int sx = 0; sx < w; sx += CURVE_STRIP_PX) {
			int sw = w - sx < CURVE_STRIP_PX ? w - sx : CURVE_STRIP_PX;
			struct pose p = curve_strip(sd->pose, sd->curve, sd->m,
				x + sx + sw / 2.0 - sd->geo.width / 2.0);
			float part[4] = { src[0] + src[2] * sx / w, src[1],
				src[2] * sw / w, src[3] };
			struct mvp mvp = quad_matrix(sd->eye, p, sd->m, sw,
				sd->geo.height, 0, y, sw, h);
			struct aa aa = aa_sides(sw, h, x + sx <= 0, y <= 0,
				x + sx + sw >= sd->geo.width, y + h >= sd->geo.height);
			draw_texture_part(sd->gl, &mvp, texture, sd->alpha, part, false,
				&aa);
		}
		return;
	}
	struct mvp mvp = quad_matrix(sd->eye, sd->pose, sd->m, sd->geo.width,
		sd->geo.height, x, y, w, h);
	/* Soft where it's the window's edge (or past it: a popup), hard
	 * where it meets more of the window */
	struct aa aa = aa_sides(w, h, x <= 0, y <= 0, x + w >= sd->geo.width,
		y + h >= sd->geo.height);
	draw_texture_part(sd->gl, &mvp, texture, sd->alpha, src, false, &aa);
}

/* Closed windows, fading: each surface's last buffer, locked so it
 * outlives the surface, and where it was on the slate */
#define GHOSTS 8
#define GHOST_PARTS 16
static struct ghost {
	int64_t at; // ms it closed, 0: free
	struct pose pose;
	struct wlr_box geo;
	int count;
	struct ghost_part {
		struct wlr_buffer *buffer;
		struct wlr_texture *texture;
		bool own; // made here, not the client buffer's own
		int x, y, w, h;
		float src[4];
	} part[GHOST_PARTS];
} ghosts[GHOSTS];

static void ghost_free(struct ghost *g) {
	for (int i = 0; i < g->count; i++) {
		if (g->part[i].own) {
			wlr_texture_destroy(g->part[i].texture);
		}
		wlr_buffer_unlock(g->part[i].buffer);
	}
	g->count = 0;
	g->at = 0;
}

static void ghosts_drop(void) {
	for (int i = 0; i < GHOSTS; i++) {
		ghost_free(&ghosts[i]);
	}
}

struct ghost_take {
	struct ghost *g;
	struct c8_server *server;
};

static void ghost_part(struct wlr_scene_buffer *sb, int lx, int ly,
		void *data) {
	struct ghost_take *gt = data;
	struct ghost *g = gt->g;
	if (g->count == GHOST_PARTS || sb->buffer == NULL) {
		return;
	}
	struct ghost_part *p = &g->part[g->count];
	struct wlr_client_buffer *client = wlr_client_buffer_get(sb->buffer);
	p->own = !(client && client->texture);
	p->texture = p->own ? wlr_texture_from_buffer(gt->server->renderer,
		sb->buffer) : client->texture;
	if (p->texture == NULL) {
		return;
	}
	p->buffer = wlr_buffer_lock(sb->buffer);
	p->x = lx - g->geo.x;
	p->y = ly - g->geo.y;
	p->w = sb->dst_width > 0 ? sb->dst_width : sb->buffer->width;
	p->h = sb->dst_height > 0 ? sb->dst_height : sb->buffer->height;
	struct wlr_fbox b = sb->src_box;
	if (wlr_fbox_empty(&b)) {
		b = (struct wlr_fbox){ 0, 0, p->texture->width, p->texture->height };
	}
	p->src[0] = b.x / p->texture->width;
	p->src[1] = b.y / p->texture->height;
	p->src[2] = b.width / p->texture->width;
	p->src[3] = b.height / p->texture->height;
	g->count++;
}

/* As wlr_scene_node_for_each_buffer, but into disabled nodes too: by
 * the time the unmap reaches us the surface's own tree is switched off */
static void ghost_walk(struct wlr_scene_node *node, int lx, int ly,
		struct ghost_take *gt) {
	if (node->type == WLR_SCENE_NODE_BUFFER) {
		ghost_part(wlr_scene_buffer_from_node(node), lx, ly, gt);
	} else if (node->type == WLR_SCENE_NODE_TREE) {
		struct wlr_scene_tree *tree = wlr_scene_tree_from_node(node);
		struct wlr_scene_node *child;
		wl_list_for_each(child, &tree->children, link) {
			ghost_walk(child, lx + child->x, ly + child->y, gt);
		}
	}
}

void c8_xr_window_closing(struct c8_view *view) {
	struct c8_server *server = view->server;
	if (!c8_xr_active(server) || !view->mapped || !view->holo.slot ||
			view->geo.width <= 0 || c8_holo_minimised(view) ||
			!view->tree->node.enabled || c8_locked(server)) {
		return;
	}
	struct ghost *g = &ghosts[0];
	for (int i = 0; i < GHOSTS; i++) { // a free one, else the oldest
		if (ghosts[i].at == 0) {
			g = &ghosts[i];
			break;
		}
		if (ghosts[i].at < g->at) {
			g = &ghosts[i];
		}
	}
	ghost_free(g);
	g->pose = c8_holo_pose(view);
	g->geo = view->geo;
	struct ghost_take gt = { g, server };
	int lx, ly;
	wlr_scene_node_coords(&view->tree->node, &lx, &ly);
	ghost_walk(&view->tree->node, lx, ly, &gt);
	g->at = g->count > 0 ? c8_now_ms() : 0;
}

/* Whether a window just closed is still going */
static bool ghosts_shown(void) {
	for (int i = 0; i < GHOSTS; i++) {
		if (ghosts[i].at != 0) {
			return true;
		}
	}
	return false;
}

static void draw_ghosts(struct c8_xr_gl *gl, const struct eye *eye,
		double m, float dim, int64_t now) {
	for (int i = 0; i < GHOSTS; i++) {
		struct ghost *g = &ghosts[i];
		if (g->at == 0) {
			continue;
		}
		double t = (now - g->at) / (double)CLOSE_MS;
		if (t >= 1) {
			ghost_free(g);
			continue;
		}
		double e = t * t; // easing in: it sets off slowly
		double gm = m * (1 - (1 - CLOSE_SCALE) * e);
		for (int k = 0; k < g->count; k++) {
			struct ghost_part *p = &g->part[k];
			struct mvp mvp = quad_matrix(eye, g->pose, gm, g->geo.width,
				g->geo.height, p->x, p->y, p->w, p->h);
			struct aa aa = aa_sides(p->w, p->h, p->x <= 0, p->y <= 0,
				p->x + p->w >= g->geo.width, p->y + p->h >= g->geo.height);
			draw_texture_part(gl, &mvp, p->texture, (1 - e) * dim, p->src,
				false, &aa);
		}
	}
}

/* Minimised or restored: 0 in place, 1 wholly away */
static double away(struct c8_view *view, int64_t now) {
	struct c8_view *root = c8_view_root(view);
	if (root->holo.minimised) {
		double t = (now - root->holo.minimised_at) / (double)MINIMISE_MS;
		return t >= 1 || t < 0 ? 1 : t * t;
	}
	double t = (now - root->holo.restored_at) / (double)RESTORE_MS;
	if (root->holo.restored_at == 0 || t >= 1 || t < 0) {
		return 0;
	}
	return pow(1 - t, 3); // easing out as it arrives
}

static void draw_frame(struct c8_xr_gl *gl, const struct eye *eye,
		struct pose pose, double m, int w, int h, const float color[4]) {
	/* Each side reaches a pixel under the window, which is drawn over it
	 * with soft edges: no dark seam between them */
	int f = FRAME_PX;
	double sides[4][4] = {
		{ -f, -f, w + 2 * f, f + 1 }, { -f, h - 1, w + 2 * f, f + 1 },
		{ -f, 0, f + 1, h }, { w - 1, 0, f + 1, h },
	};
	bool soft[4][4] = { // left, top, right, bottom
		{ 1, 1, 1, 0 }, { 1, 0, 1, 1 }, { 1, 0, 0, 0 }, { 0, 0, 1, 0 },
	};
	for (int i = 0; i < 4; i++) {
		struct mvp mvp = quad_matrix(eye, pose, m, w, h, sides[i][0],
			sides[i][1], sides[i][2], sides[i][3]);
		struct aa aa = aa_sides(sides[i][2], sides[i][3], soft[i][0],
			soft[i][1], soft[i][2], soft[i][3]);
		draw_solid(&gl->solid, &mvp, color, &aa);
	}
}

/* A window's controls under it and the resize handle round its bottom
 * right corner, on its plane (slatebar.c, hologram.c) */
static void draw_chrome(struct c8_xr_gl *gl, const struct eye *eye,
		struct pose pose, double m, struct c8_view *view, float alpha,
		const float accent[4]) {
	struct c8_slatebar_look look = c8_holo_chrome_look(view);
	struct wlr_texture *texture = c8_slatebar_texture(view, &look);
	int w = view->geo.width, h = view->geo.height;
	if (texture) {
		/* The row of tiles under it */
		static const float all[4] = { 0, 0, 1, 1 };
		int bw = c8_slatebar_width(w);
		struct mvp mvp = quad_matrix(eye, pose, m, w, h, 0,
			h + C8_SLATEBAR_GAP, bw, C8_SLATEBAR_H);
		struct aa aa = aa_sides(bw, C8_SLATEBAR_H, 1, 1, 1, 1);
		draw_texture_part(gl, &mvp, texture, alpha, all, false, &aa);
	}
	bool hot = look.hover == C8_SLATEBAR_CORNER ||
		view->server->xr.size_view == view;
	float c[4];
	for (int i = 0; i < 4; i++) {
		c[i] = (hot ? 1 : accent[i]) * alpha;
	}
	/* An L just outside the corner */
	const int gap = 4, len = 22, thick = 4;
	double sides[2][4] = {
		{ w + gap, h + gap - len, thick, len + thick },
		{ w + gap - len, h + gap, len, thick },
	};
	for (int i = 0; i < 2; i++) {
		struct mvp mvp = quad_matrix(eye, pose, m, w, h, sides[i][0],
			sides[i][1], sides[i][2], sides[i][3]);
		struct aa aa = aa_sides(sides[i][2], sides[i][3], 1, 1, 1, 1);
		draw_solid(&gl->solid, &mvp, c, &aa);
	}
}

/* Outlines of the space ([glasses] outlines), for showing it in a
 * recording: black is clear in the glasses, so on a capture the slates
 * float in nothing without them */

static const float outline_rgba = 0.55f;

/* A flat rectangle in the world, w x h metres round pose */
static void draw_world_rect(struct c8_xr_gl *gl, const struct eye *eye,
		struct pose pose, double w, double h, float alpha) {
	struct mvp mvp = quad_matrix(eye, pose, 0.001, 0, 0, -w * 500,
		-h * 500, w * 1000, h * 1000);
	float c[4] = { alpha, alpha, alpha, alpha }; // premultiplied white
	draw_solid(&gl->solid, &mvp, c, NULL);
}

static struct quat floor_facing(void) {
	return quat_axis_angle((struct vec3){ 1, 0, 0 }, -M_PI / 2);
}

static void draw_floor(struct c8_xr_gl *gl, const struct eye *eye) {
	if (gl->lines == 0 || gl->floor_count == 0) {
		return;
	}
	glUseProgram(gl->lines);
	glUniformMatrix4fv(gl->lines_vp, 1, GL_FALSE, eye->view_proj[0].m);
	glUniformMatrix4fv(gl->lines_vp_end, 1, GL_FALSE, eye->view_proj[1].m);
	glVertexAttribPointer(gl->lines_pos, 3, GL_FLOAT, GL_FALSE,
		4 * sizeof(GLfloat), gl->floor);
	glVertexAttribPointer(gl->lines_alpha, 1, GL_FLOAT, GL_FALSE,
		4 * sizeof(GLfloat), gl->floor + 3);
	glEnableVertexAttribArray(gl->lines_pos);
	glEnableVertexAttribArray(gl->lines_alpha);
	glDrawArrays(GL_TRIANGLES, 0, gl->floor_count);
	draw_count++;
	glDisableVertexAttribArray(gl->lines_pos);
	glDisableVertexAttribArray(gl->lines_alpha);
}

/* A window's slate: a line from its bottom down to the floor, and a dot
 * where it lands, facing the head so it never goes edge-on */
static void draw_drop(struct c8_xr_gl *gl, const struct eye *eye,
		struct pose head, struct pose slate, double m, int h) {
	struct vec3 foot = pose_point(slate, 0, -h * m / 2, 0);
	double drop = foot.y + FLOOR_M;
	if (drop <= 0) {
		return; // at or under the floor
	}
	double yaw = atan2(head.position.x - foot.x, head.position.z - foot.z);
	struct pose line = {
		{ foot.x, foot.y - drop / 2, foot.z },
		quat_axis_angle((struct vec3){ 0, 1, 0 }, yaw),
	};
	draw_world_rect(gl, eye, line, LINE_M, drop, outline_rgba);
	struct pose spot = { { foot.x, -FLOOR_M, foot.z }, floor_facing() };
	struct mvp mvp = quad_matrix(eye, spot, 0.001, 0, 0, -60, -60, 120, 120);
	float c[4] = { outline_rgba, outline_rgba, outline_rgba, outline_rgba };
	draw_solid(&gl->disc, &mvp, c, NULL);
}

/* A stick len x thick px, its middle at x, y (px, up) on the slate pose,
 * turned by angle */
static void draw_stick(struct c8_xr_gl *gl, const struct eye *eye,
		struct pose pose, double m, double x, double y, double len,
		double thick, double angle, const float color[4]) {
	struct pose p = {
		pose_point(pose, x * m, y * m, 0),
		quat_mul(pose.orientation,
			quat_axis_angle((struct vec3){ 0, 0, 1 }, angle)),
	};
	struct mvp mvp = quad_matrix(eye, p, m, 0, 0, -len / 2, -thick / 2, len,
		thick);
	struct aa aa = aa_sides(len, thick, 1, 1, 1, 1);
	draw_solid(&gl->solid, &mvp, color, &aa);
}

/* A window that opened out of view: its icon at the view's edge on its
 * side, a chevron beside it pointing the way */
static void draw_beacon(struct c8_xr_gl *gl, const struct eye *eye,
		struct pose head, double m, struct c8_view *view) {
	struct c8_server *server = view->server;
	double yaw, pitch;
	float alpha;
	if (!c8_holo_beacon(view, &yaw, &pitch, &alpha) || alpha <= 0) {
		return;
	}
	struct wlr_texture *texture = c8_slatebar_beacon(view);
	if (texture == NULL) {
		return;
	}
	/* Nearer than everything but the charms bar, as big as at the
	 * windows' distance */
	double d = BEACON_DIST, bm = m * d / server->config.glasses.distance;
	struct quat q = quat_mul(head.orientation, quat_yaw_pitch(yaw, pitch));
	struct pose p = {
		vec3_add(head.position, quat_rotate(q, (struct vec3){ 0, 0, -d })),
		q,
	};
	int px = C8_BEACON_PX;
	static const float all[4] = { 0, 0, 1, 1 };
	struct mvp mvp = quad_matrix(eye, p, bm, 0, 0, -px / 2.0, -px / 2.0, px,
		px);
	struct aa aa = aa_sides(px, px, 1, 1, 1, 1);
	draw_texture_part(gl, &mvp, texture, alpha, all, false, &aa);
	/* Out from the middle of the view: right is less yaw */
	double out = atan2(pitch, -yaw);
	double tip = px / 2.0 + 22, len = 16, th = 4;
	double c = cos(out), sn = sin(out), back = len / 2 * sqrt(0.5);
	float white[4] = { alpha, alpha, alpha, alpha };
	for (int k = -1; k <= 1; k += 2) {
		/* Each arm from the tip back at 45 degrees */
		double lx = tip - back, ly = k * back;
		draw_stick(gl, eye, p, bm, lx * c - ly * sn, lx * sn + ly * c, len,
			th, out - k * M_PI / 4, white);
	}
}

/* Minimised windows: each its icon on its tile's colour, in a row over
 * the charms bar and round its cylinder; the one the ray is on has a
 * white frame and its title above it (hologram.c takes the clicks) */
static void draw_minimised(struct c8_xr_gl *gl, const struct eye *eye,
		struct c8_server *server, double m, int bar_h, double r) {
	struct c8_view *views[C8_MINI_MAX];
	int n = c8_holo_minimised_views(server, views, C8_MINI_MAX);
	float alpha = server->xr.bar_fade;
	static const float all[4] = { 0, 0, 1, 1 };
	int px = C8_MINI_PX;
	for (int i = 0; i < n; i++) {
		struct wlr_texture *texture = c8_slatebar_beacon(views[i]);
		if (texture == NULL) {
			continue;
		}
		struct pose p = curve_strip(server->xr.bar_drawn, r, m,
			c8_mini_x(i, n));
		p.position = pose_point(p, 0,
			(bar_h / 2.0 + C8_MINI_ABOVE + px / 2.0) * m, 0);
		bool hot = server->xr.aim_mini == views[i];
		if (hot) {
			float white[4] = { alpha, alpha, alpha, alpha };
			draw_frame(gl, eye, p, m, px, px, white);
		}
		struct mvp mvp = quad_matrix(eye, p, m, px, px, 0, 0, px, px);
		struct aa aa = aa_sides(px, px, 1, 1, 1, 1);
		draw_texture_part(gl, &mvp, texture, alpha, all, false, &aa);
		struct wlr_texture *label = hot ? c8_slatebar_label(server,
			c8_view_label(views[i])) : NULL;
		if (label) {
			int lw = label->width, lh = label->height;
			mvp = quad_matrix(eye, p, m, px, px, (px - lw) / 2.0,
				-(C8_MINI_GAP + lh), lw, lh);
			aa = aa_sides(lw, lh, 1, 1, 1, 1);
			draw_texture_part(gl, &mvp, label, alpha, all, false, &aa);
		}
	}
}

/* How far the minimised windows' row reaches round the bar's middle
 * (half its width) and over its top (top, < 0), in the bar's pixels */
static void minimised_extent(struct c8_server *server, double *half,
		double *top) {
	struct c8_view *views[C8_MINI_MAX];
	int n = c8_holo_minimised_views(server, views, C8_MINI_MAX);
	int px = C8_MINI_PX;
	for (int i = 0; i < n; i++) {
		double x = fabs(c8_mini_x(i, n)) + px / 2.0 + FRAME_PX;
		double y = -(C8_MINI_ABOVE + px + FRAME_PX);
		struct wlr_texture *label = server->xr.aim_mini == views[i] ?
			c8_slatebar_label(server, c8_view_label(views[i])) : NULL;
		if (label) {
			x = fmax(x, fabs(c8_mini_x(i, n)) + label->width / 2.0);
			y = -(C8_MINI_ABOVE + px + C8_MINI_GAP + label->height);
		}
		*half = fmax(*half, x);
		*top = fmin(*top, y);
	}
}

/* A window to draw: where it is this frame (its pose walks up to its
 * root, so it's worked out once, not per compare and per eye) */
struct ranked {
	struct c8_view *view;
	int mru;
	struct pose pose;
	double dist;
	bool unseen; // wholly out of view: not drawn
	double away; // minimising or restoring (`away`)
	bool layered; // the runtime shows it, as a layer of its own
};

#define OUT_OF_VIEW_MS 200 // how often an unseen window is told to draw
#define VIEW_MARGIN_PX 512 // round a window: its frame, bar and popups
#define VIEW_MARGIN_RAD 0.1 // round the view: the eyes apart, the scan

/* Whether none of a window's slate (and the room round it) can be in
 * the view: all its corners behind the head, or all off the same side.
 * The other way round wouldn't do, a near window fills the view with
 * every corner outside it. */
static bool out_of_view(struct pose head, struct pose slate, double m,
		int w, int h, double fov_x, double fov_y) {
	double tx = tan(fmin(fov_x / 2 + VIEW_MARGIN_RAD, 1.5));
	double ty = tan(fmin(fov_y / 2 + VIEW_MARGIN_RAD, 1.5));
	double hw = (w / 2.0 + VIEW_MARGIN_PX) * m;
	double hh = (h / 2.0 + VIEW_MARGIN_PX) * m;
	int behind = 0, left = 0, right = 0, above = 0, below = 0;
	struct quat to_head = quat_conjugate(head.orientation);
	for (int i = 0; i < 4; i++) {
		struct vec3 p = quat_rotate(to_head, vec3_sub(pose_point(slate,
			i & 1 ? hw : -hw, i & 2 ? hh : -hh, 0), head.position));
		double ahead = -p.z;
		behind += ahead <= 0;
		left += p.x < -ahead * tx;
		right += p.x > ahead * tx;
		below += p.y < -ahead * ty;
		above += p.y > ahead * ty;
	}
	return behind == 4 || left == 4 || right == 4 || above == 4 ||
		below == 4;
}

/* A window out of view still has to draw now and then (its picture in
 * the switcher, a capture), only not at the glasses' rate */
static void frame_done_only(struct wlr_scene_buffer *buffer, int lx, int ly,
		void *data) {
	struct wlr_scene_surface *ss = wlr_scene_surface_try_from_buffer(buffer);
	if (ss) {
		wlr_surface_send_frame_done(ss->surface, data);
	}
}

/* Every window told its frame is done, while no frame is being drawn
 * (xrclient.c, while the runtime makes swapchains): Monado's own window
 * in a nested c8 must go on showing frames for it to answer */
void c8_xr_windows_done(struct c8_server *server) {
	struct timespec now;
	clock_gettime(CLOCK_MONOTONIC, &now);
	struct c8_view *view;
	wl_list_for_each(view, &server->views, link) {
		if (view->mapped) {
			wlr_scene_node_for_each_buffer(&view->tree->node,
				frame_done_only, &now);
		}
	}
}

/* For testing nested (C8_XR_DUMP_RUNTIME=/path/r%d.png): the runtime's
 * own window, which is what it shows the glasses, saved once every
 * C8_XR_DUMP_MS (1000) ms. grim can't see it: it's a slate in a space
 * only the runtime draws. */
static void dump_runtime_buffer(struct wlr_scene_buffer *buffer, int lx,
		int ly, void *data) {
	struct c8_server *server = data;
	struct wlr_scene_surface *ss = wlr_scene_surface_try_from_buffer(buffer);
	if (ss == NULL || ss->surface->buffer == NULL ||
			ss->surface->buffer->texture == NULL ||
			!c8_xr_runtime_is_client(server,
				wl_resource_get_client(ss->surface->resource))) {
		return;
	}
	struct wlr_texture *tex = ss->surface->buffer->texture;
	cairo_surface_t *image = cairo_image_surface_create(
		CAIRO_FORMAT_ARGB32, tex->width, tex->height);
	cairo_surface_flush(image);
	if (wlr_texture_read_pixels(tex, &(struct wlr_texture_read_pixels_options){
			.data = cairo_image_surface_get_data(image),
			.format = DRM_FORMAT_ARGB8888,
			.stride = cairo_image_surface_get_stride(image),
		})) {
		cairo_surface_mark_dirty(image);
		static int n;
		char path[512];
		snprintf(path, sizeof(path), getenv("C8_XR_DUMP_RUNTIME"), n++);
		cairo_surface_write_to_png(image, path);
	}
	cairo_surface_destroy(image);
}

void c8_xr_dump_runtime(struct c8_server *server) {
	static int64_t last;
	const char *path = getenv("C8_XR_DUMP_RUNTIME");
	const char *every = getenv("C8_XR_DUMP_MS");
	int64_t now = c8_now_ms();
	if (path == NULL || !*path || strstr(path, "%d") == NULL ||
			now - last < (every ? atoi(every) : 1000)) {
		return;
	}
	last = now;
	struct c8_view *view;
	wl_list_for_each(view, &server->views, link) {
		if (view->mapped) {
			wlr_scene_node_for_each_buffer(&view->tree->node,
				dump_runtime_buffer, server);
		}
	}
}

/* Furthest first, so nearer ones cover them; at the same distance the
 * most recently used on top (qsort isn't stable: the MRU index breaks
 * ties, the older, with the larger index, first) */
static int ranked_cmp(const void *a, const void *b) {
	const struct ranked *ra = a, *rb = b;
	if (fabs(ra->dist - rb->dist) > 0.005) {
		return ra->dist > rb->dist ? -1 : 1;
	}
	return rb->mru - ra->mru;
}

/* The picture as a texture, kept with it: it only changes with a new
 * frame of the source, and the glasses draw far more often than that */
static struct wlr_texture *picture_texture(struct c8_server *server) {
	if (server->xr.picture == NULL) {
		return NULL;
	}
	/* A scanned-out frame is the client's buffer itself (Start alone on
	 * the shell's screen, with no cursor image to keep it from being
	 * scanned out). An shm one is only a texture by then, which
	 * wlr_texture_from_buffer can't import: those frames had no
	 * picture, and Start flickered. Its own texture, then (not ours). */
	struct wlr_client_buffer *client = wlr_client_buffer_get(server->xr.picture);
	if (client && client->texture) {
		return client->texture;
	}
	if (server->xr.picture_texture == NULL) {
		server->xr.picture_texture =
			wlr_texture_from_buffer(server->renderer, server->xr.picture);
	}
	return server->xr.picture_texture;
}

/* The picture's part to draw, as fractions of it */
static void picture_src(struct c8_server *server, struct wlr_texture *t,
		float src[4]) {
	struct wlr_fbox b = server->xr.picture_src;
	if (wlr_fbox_empty(&b)) {
		b = (struct wlr_fbox){ 0, 0, t->width, t->height };
	}
	src[0] = b.x / t->width;
	src[1] = b.y / t->height;
	src[2] = b.width / t->width;
	src[3] = b.height / t->height;
}

/* How the glasses' frames are doing, a line every PACE_FRAMES to the
 * log beside tracking's: how many a second and how many came a refresh
 * or more late; then where a frame's time went, each as average/most:
 * from the refresh to our turn (the loop busy with something else), the
 * sensors, drawing (ours: the GL calls), handing it to the display, and
 * the GPU's own time over it (asked for without waiting, so not of every
 * frame) */
#define PACE_FRAMES 1000
static struct {
	int64_t since, last, drawn;
	int frames, late, gpu_n;
	double sum[4], max[4]; // wait, sensors, drawing, handing over
	double gpu_sum, gpu_max;
} pace;

static void pace_frame(struct c8_output *output, int64_t started,
		int64_t sensed) {
	int64_t now = c8_now_ns();
	int64_t wait = started - output->presented_ns;
	if (output->presented_ns <= 0 || wait < 0 || wait > 1000000000) {
		wait = 0;
	}
	int64_t drawn = pace.drawn > sensed ? pace.drawn : sensed;
	double ms[4] = { wait / 1e6, (sensed - started) / 1e6,
		(drawn - sensed) / 1e6, (now - drawn) / 1e6 };
	for (int i = 0; i < 4; i++) {
		pace.sum[i] += ms[i];
		pace.max[i] = fmax(pace.max[i], ms[i]);
	}
	if (pace.frames == 0) {
		pace.since = started;
	} else if (output->refresh_ns > 0 &&
			started - pace.last > output->refresh_ns * 3 / 2) {
		pace.late++;
	}
	pace.last = started;
	pace.drawn = 0;
	if (++pace.frames < PACE_FRAMES) {
		return;
	}
	int n = pace.frames, g = pace.gpu_n > 0 ? pace.gpu_n : 1;
	wlr_log(WLR_INFO, "Glasses: frames: %.1f a second of %.1f, %d late; "
		"wait %.1f/%.1f, sensors %.1f/%.1f, drawing %.1f/%.1f, "
		"handing over %.1f/%.1f, GPU %.1f/%.1f ms",
		n * 1e9 / (now - pace.since),
		output->refresh_ns > 0 ? 1e9 / output->refresh_ns : 0, pace.late,
		pace.sum[0] / n, pace.max[0], pace.sum[1] / n, pace.max[1],
		pace.sum[2] / n, pace.max[2], pace.sum[3] / n, pace.max[3],
		pace.gpu_sum / g, pace.gpu_max);
	memset(&pace, 0, sizeof(pace));
}

/* The background ([glasses] background): a 360 picture all round you,
 * behind everything. An equirectangular one (2:1) is the whole sphere;
 * a wider one is taken as a strip all the way round, as high as its
 * shape says (20000x5389 is 97 degrees), the horizon where [glasses]
 * background_horizon says it is in it (a rover's panorama has it near
 * the top and its own deck at the bottom). What a strip leaves of the
 * sphere above and below is filled from its edge: the edge's colours
 * round you, averaged (SKY_EDGE of them, so no streaks), going to their
 * mean at the pole, and the picture fades into that.
 *
 * c8-panorama decodes it into a memfd, shrunk to what the glasses can
 * show (their pixels per degree, all the way round) or the GPU can
 * hold; its rows then go into the texture a few MB a frame, so no frame
 * waits for all of it, and it fades in when whole. Drawn as a piece of
 * a sphere round the head: no fragment shader arithmetic, and the
 * vertex shader's rows (see vertex_src) work as for a slate. */

#define SKY_M 50.0 // the sphere's radius: within the far plane
#define SKY_MAX_W 16384
#define SKY_COLS 128 // quads round; under 3 degrees each, flat enough
#define SKY_UPLOAD (8 << 20) // bytes of the picture a frame
#define SKY_FADE_DEG 5.0 // a strip's top and bottom fade over this
#define SKY_EDGE 64 // colours round a strip's edge, for what's beyond it
#define SKY_RATE 0.04f // of the way to shown, a frame

static struct {
	char *path; // [glasses] background as shown or loading; NULL: none
	/* c8-panorama at work: its pipe closes when it's done */
	pid_t pid;
	int out, pipe;
	struct wl_event_source *source;
	/* Its picture, while rows of it have yet to go to the GPU */
	uint8_t *map;
	size_t map_size;
	int w, h, rows; // rows: how many the texture has
	GLuint tex;
	/* Beyond a strip's edges: four rows of SKY_EDGE + 1 colours (the
	 * top's mean, the top edge, the bottom edge, the bottom's mean; the
	 * last column is the first again, for the seam) */
	GLuint edge;
	bool whole;
	float shown; // eased to 1 once whole
	double horizon; // [glasses] background_horizon the mesh was made for
	/* The picture's pitches, top and bottom, and whether the edge's
	 * colours fill above and below it */
	double top, bottom;
	bool above, below;
	unsigned serial; // a new one with each mesh, for xrclient.c's layers
	/* flat: the same mesh unrolled, x -1 to 1 round, y the pitch in
	 * radians, for drawing it as an equirectangular picture */
	GLuint program, vbo, flat, ibo;
	GLint vp, vp_end, pos, uv, sampler, alpha, fade;
	/* Indices: the picture, then what's above it and below it */
	int first[3], count[3];
	float fade_v[2]; // the fades, as fractions of the picture's height
} sky = { .out = -1, .pipe = -1 };

static const char sky_vertex_src[] =
	"uniform mat4 vp;\n"
	"uniform mat4 vp_end;\n"
	"attribute vec3 pos;\n"
	"attribute vec2 uv;\n"
	"varying vec2 v_uv;\n"
	"float row(vec4 p) {\n"
	"	return p.w > 0.0 ? clamp(p.y / p.w * 0.5 + 0.5, 0.0, 1.0) : 0.5;\n"
	"}\n"
	"void main() {\n"
	"	v_uv = uv;\n"
	"	vec4 a = vp * vec4(pos, 1.0);\n"
	"	vec4 b = vp_end * vec4(pos, 1.0);\n"
	"	gl_Position = mix(a, b, row(mix(a, b, row(a))));\n"
	"}\n";

/* highp where there is any: the picture can be 16384 texels across */
static const char sky_src[] =
	"#ifdef GL_FRAGMENT_PRECISION_HIGH\n"
	"precision highp float;\n"
	"#else\n"
	"precision mediump float;\n"
	"#endif\n"
	"uniform sampler2D tex;\n"
	"uniform float alpha;\n"
	"uniform vec2 fade;\n" // at the top, at the bottom
	"varying vec2 v_uv;\n"
	"void main() {\n"
	"	float a = alpha;\n"
	"	if (fade.x > 0.0) a *= smoothstep(0.0, fade.x, v_uv.y);\n"
	"	if (fade.y > 0.0) a *= smoothstep(0.0, fade.y, 1.0 - v_uv.y);\n"
	"	gl_FragColor = vec4(texture2D(tex, v_uv).rgb * a, a);\n"
	"}\n";

/* The loader, if one is at work, and what it made so far */
static void sky_cancel(void) {
	if (sky.source) {
		wl_event_source_remove(sky.source);
		sky.source = NULL;
	}
	if (sky.pid > 0) {
		kill(sky.pid, SIGKILL);
		waitpid(sky.pid, NULL, 0);
		sky.pid = 0;
	}
	if (sky.pipe >= 0) {
		close(sky.pipe);
		sky.pipe = -1;
	}
	if (sky.out >= 0) {
		close(sky.out);
		sky.out = -1;
	}
	if (sky.map) {
		munmap(sky.map, sky.map_size);
		sky.map = NULL;
	}
}

/* With the renderer's context current */
static void sky_delete_mesh(void) {
	if (sky.vbo) {
		glDeleteBuffers(1, &sky.vbo);
		glDeleteBuffers(1, &sky.flat);
		glDeleteBuffers(1, &sky.ibo);
	}
	sky.vbo = sky.flat = sky.ibo = 0;
}

static void sky_delete(void) {
	if (sky.tex) {
		glDeleteTextures(1, &sky.tex);
		glDeleteTextures(1, &sky.edge);
	}
	sky_delete_mesh();
	sky.tex = sky.edge = 0;
	sky.whole = false;
	sky.shown = 0;
}

/* All of it, from anywhere: leaving XR, no frame of ours comes again to
 * do it in */
static void sky_drop(struct c8_server *server) {
	sky_cancel();
	free(sky.path);
	sky.path = NULL;
	if (sky.tex == 0 && sky.vbo == 0) {
		return;
	}
	struct wlr_egl *egl = wlr_gles2_renderer_get_egl(server->renderer);
	EGLDisplay display = wlr_egl_get_display(egl);
	EGLContext ours = wlr_egl_get_context(egl), was = eglGetCurrentContext();
	EGLSurface draw = eglGetCurrentSurface(EGL_DRAW);
	EGLSurface read = eglGetCurrentSurface(EGL_READ);
	if (was != ours && !eglMakeCurrent(display, EGL_NO_SURFACE,
			EGL_NO_SURFACE, ours)) {
		return; // kept for the next time in XR: sky_update deletes it
	}
	sky_delete();
	if (was != ours) {
		eglMakeCurrent(display, draw, read, was);
	}
}

/* c8-panorama's pipe closed: it's done, or it died */
static int sky_loaded(int fd, uint32_t mask, void *data) {
	struct c8_server *server = data;
	wl_event_source_remove(sky.source);
	sky.source = NULL;
	close(sky.pipe);
	sky.pipe = -1;
	waitpid(sky.pid, NULL, 0);
	sky.pid = 0;
	uint32_t size[2] = { 0 };
	struct stat st;
	if (pread(sky.out, size, sizeof(size), 0) == sizeof(size) &&
			size[0] >= 1 && size[1] >= 1 && size[0] <= SKY_MAX_W &&
			size[1] <= SKY_MAX_W && fstat(sky.out, &st) == 0 &&
			(uint64_t)st.st_size >= 8 + (uint64_t)size[0] * size[1] * 3) {
		sky.map_size = 8 + (size_t)size[0] * size[1] * 3;
		sky.map = mmap(NULL, sky.map_size, PROT_READ, MAP_PRIVATE, sky.out,
			0);
		if (sky.map == MAP_FAILED) {
			sky.map = NULL;
		}
	}
	close(sky.out);
	sky.out = -1;
	if (sky.map) {
		sky.w = size[0];
		sky.h = size[1];
		sky.rows = 0;
		wlr_log(WLR_INFO, "XR: background %s: %dx%d", sky.path, sky.w,
			sky.h);
		schedule_sinks(server);
	} else {
		wlr_log(WLR_ERROR, "XR: background %s can't be shown", sky.path);
	}
	return 0;
}

/* Starts c8-panorama on sky.path, for a picture max_w wide at most */
static void sky_load(struct c8_server *server, int max_w) {
	char *file = NULL;
	const char *home = getenv("HOME");
	if (sky.path[0] == '~' && sky.path[1] == '/' && home) {
		size_t len = strlen(home) + strlen(sky.path);
		file = malloc(len);
		snprintf(file, len, "%s%s", home, sky.path + 1);
	} else {
		file = strdup(sky.path);
	}
	int out = memfd_create("c8-panorama", MFD_CLOEXEC);
	int ends[2] = { -1, -1 };
	if (file == NULL || out < 0 || pipe2(ends, O_CLOEXEC) < 0) {
		wlr_log_errno(WLR_ERROR, "XR: background");
		if (out >= 0) {
			close(out);
		}
		free(file);
		return;
	}
	char w[16], h[16];
	snprintf(w, sizeof(w), "%d", max_w);
	snprintf(h, sizeof(h), "%d", max_w / 2);
	pid_t pid = fork();
	if (pid == 0) {
		sigset_t set;
		sigemptyset(&set);
		sigprocmask(SIG_SETMASK, &set, NULL);
		/* Its picture to stdout, the pipe as fd 3 (see panorama.c) */
		int end = fcntl(ends[1], F_DUPFD, 4);
		if (dup2(out, STDOUT_FILENO) < 0 || dup2(end, 3) < 0) {
			_exit(127);
		}
		execl(C8_LIBEXECDIR "/c8-panorama", "c8-panorama", file, w, h,
			(char *)NULL);
		_exit(127);
	}
	close(ends[1]);
	free(file);
	if (pid < 0) {
		wlr_log_errno(WLR_ERROR, "XR: background: fork");
		close(ends[0]);
		close(out);
		return;
	}
	sky.pid = pid;
	sky.out = out;
	sky.pipe = ends[0];
	sky.source = wl_event_loop_add_fd(server->loop, sky.pipe,
		WL_EVENT_READABLE, sky_loaded, server);
}

static bool sky_program(void) {
	if (sky.program) {
		return true;
	}
	GLuint vs = compile(GL_VERTEX_SHADER, "", sky_vertex_src);
	GLuint fs = compile(GL_FRAGMENT_SHADER, "", sky_src);
	if (!vs || !fs) {
		glDeleteShader(vs);
		glDeleteShader(fs);
		return false;
	}
	GLuint p = glCreateProgram();
	glAttachShader(p, vs);
	glAttachShader(p, fs);
	glLinkProgram(p);
	glDeleteShader(vs);
	glDeleteShader(fs);
	GLint ok;
	glGetProgramiv(p, GL_LINK_STATUS, &ok);
	if (!ok) {
		glDeleteProgram(p);
		return false;
	}
	sky.program = p;
	sky.vp = glGetUniformLocation(p, "vp");
	sky.vp_end = glGetUniformLocation(p, "vp_end");
	sky.sampler = glGetUniformLocation(p, "tex");
	sky.alpha = glGetUniformLocation(p, "alpha");
	sky.fade = glGetUniformLocation(p, "fade");
	sky.pos = glGetAttribLocation(p, "pos");
	sky.uv = glGetAttribLocation(p, "uv");
	return true;
}

/* A ring of the unit sphere at a pitch: all the way round, the middle
 * of the picture ahead (-z). u runs 0 to 1 round it, or for the edge
 * colours from the first one's middle to the last one's. The same ring
 * unrolled into flat, if given (see sky.flat). */
static GLfloat *sky_ring(GLfloat *p, GLfloat *flat, double pitch, double v,
		bool edge) {
	for (int c = 0; c <= SKY_COLS; c++) {
		double u = (double)c / SKY_COLS, turn = (u - 0.5) * 2 * M_PI;
		*p++ = sin(turn) * cos(pitch);
		*p++ = sin(pitch);
		*p++ = -cos(turn) * cos(pitch);
		*p++ = edge ? (0.5 + u * SKY_EDGE) / (SKY_EDGE + 1) : u;
		*p++ = v;
		if (flat) {
			*flat++ = u * 2 - 1;
			*flat++ = pitch;
			*flat++ = 0;
			*flat++ = p[-2];
			*flat++ = v;
		}
	}
	return p;
}

/* The sphere: the piece the picture covers, as high as its shape says
 * with its horizon level with the eyes, and what's left above and below */
static void sky_mesh(struct c8_server *server) {
	sky_delete_mesh();
	sky.horizon = server->config.glasses.background_horizon;
	double high = fmin(M_PI, 2 * M_PI * sky.h / sky.w);
	/* Never over a pole: a picture too high for where its horizon is
	 * said to be slides until it fits */
	double top = fmax(high - M_PI / 2,
		fmin(M_PI / 2, sky.horizon / 100 * high));
	double bottom = top - high;
	double fade = fmin(SKY_FADE_DEG * M_PI / 180, high / 4);
	bool above = top < M_PI / 2 - 0.01, below = bottom > -M_PI / 2 + 0.01;
	sky.top = top;
	sky.bottom = bottom;
	sky.above = above;
	sky.below = below;
	sky.fade_v[0] = above ? fade / high : 0;
	sky.fade_v[1] = below ? fade / high : 0;

	const double step = 2 * M_PI / SKY_COLS;
	/* Each part's rings: from, to (pitch), and how many rows between */
	double from[3] = { top, M_PI / 2, bottom + fade };
	double to[3] = { bottom, top - fade, -M_PI / 2 };
	int rows[3], rings = 0;
	for (int k = 0; k < 3; k++) {
		bool there = k == 0 || (k == 1 ? above : below);
		rows[k] = there ? (int)ceil((from[k] - to[k]) / step) : 0;
		rows[k] = there && rows[k] < 1 ? 1 : rows[k];
		rings += there ? rows[k] + 1 : 0;
	}
	int across = SKY_COLS + 1; // the seam's vertices twice: u 0 and 1
	GLfloat *v = calloc((size_t)across * rings * 5, sizeof(GLfloat));
	GLfloat *flat = calloc((size_t)across * rings * 5, sizeof(GLfloat));
	GLushort *ix = calloc((size_t)SKY_COLS * rings * 6, sizeof(GLushort));
	if (v == NULL || flat == NULL || ix == NULL) {
		free(v);
		free(flat);
		free(ix);
		return;
	}
	GLfloat *p = v;
	GLushort *q = ix;
	int ring = 0;
	for (int k = 0; k < 3; k++) {
		sky.first[k] = (int)(q - ix);
		for (int r = 0; rows[k] > 0 && r <= rows[k]; r++) {
			double t = (double)r / rows[k];
			double pitch = from[k] + (to[k] - from[k]) * t;
			double tv = t;
			if (k == 1) {
				/* The edge texture's first two rows: the mean at the
				 * pole, the edge's colours from the edge on down, under
				 * the picture's fade */
				tv = 0.125 + 0.25 * fmin(1,
					(M_PI / 2 - pitch) / (M_PI / 2 - top));
			} else if (k == 2) {
				tv = 0.625 + 0.25 * fmax(0,
					(bottom - pitch) / (bottom + M_PI / 2));
			}
			p = sky_ring(p, flat + (p - v), pitch, tv, k != 0);
			for (int c = 0; r < rows[k] && c < SKY_COLS; c++) {
				GLushort a = (ring + r) * across + c, b = a + across;
				*q++ = a;
				*q++ = b;
				*q++ = a + 1;
				*q++ = a + 1;
				*q++ = b;
				*q++ = b + 1;
			}
		}
		ring += rows[k] > 0 ? rows[k] + 1 : 0;
		sky.count[k] = (int)(q - ix) - sky.first[k];
	}
	glGenBuffers(1, &sky.vbo);
	glGenBuffers(1, &sky.flat);
	glGenBuffers(1, &sky.ibo);
	glBindBuffer(GL_ARRAY_BUFFER, sky.vbo);
	glBufferData(GL_ARRAY_BUFFER, (p - v) * sizeof(GLfloat), v,
		GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, sky.flat);
	glBufferData(GL_ARRAY_BUFFER, (p - v) * sizeof(GLfloat), flat,
		GL_STATIC_DRAW);
	sky.serial++;
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sky.ibo);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, (q - ix) * sizeof(GLushort), ix,
		GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
	free(v);
	free(flat);
	free(ix);
}

/* The edge colours, from the picture while it's mapped: each the
 * average of its stretch of the top (or bottom) couple of degrees */
static void sky_edges(void) {
	static uint8_t px[4][SKY_EDGE + 1][3];
	int deep = sky.h / 90 < 1 ? 1 : sky.h / 90;
	const uint8_t *rgb = sky.map + 8;
	for (int side = 0; side < 2; side++) {
		int y0 = side == 0 ? 0 : sky.h - deep;
		uint64_t all[3] = { 0 };
		for (int b = 0; b < SKY_EDGE; b++) {
			int x0 = (int)((int64_t)b * sky.w / SKY_EDGE);
			int x1 = (int)((int64_t)(b + 1) * sky.w / SKY_EDGE);
			x1 = x1 <= x0 ? x0 + 1 : x1;
			uint64_t sum[3] = { 0 }, n = 0;
			for (int y = y0; y < y0 + deep; y++) {
				const uint8_t *row = rgb + ((size_t)y * sky.w + x0) * 3;
				for (int x = x0; x < x1 && x < sky.w; x++, row += 3, n++) {
					sum[0] += row[0];
					sum[1] += row[1];
					sum[2] += row[2];
				}
			}
			for (int c = 0; c < 3; c++) {
				px[1 + side][b][c] = n ? sum[c] / n : 0;
				all[c] += px[1 + side][b][c];
			}
		}
		memcpy(px[1 + side][SKY_EDGE], px[1 + side][0], 3);
		for (int b = 0; b <= SKY_EDGE; b++) {
			for (int c = 0; c < 3; c++) {
				px[side * 3][b][c] = all[c] / SKY_EDGE;
			}
		}
	}
	glGenTextures(1, &sky.edge);
	glBindTexture(GL_TEXTURE_2D, sky.edge);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, SKY_EDGE + 1, 4, 0, GL_RGB,
		GL_UNSIGNED_BYTE, px);
	glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
}

/* Once a glasses frame, before drawing: follows the setting, and takes
 * the next rows of a picture that came. eye_w and fov_x are one eye's. */
static void sky_update(struct c8_server *server, int eye_w, double fov_x) {
	const char *want = server->config.glasses.background;
	if (want && want[0] == '\0') {
		want = NULL;
	}
	if ((want == NULL) != (sky.path == NULL) ||
			(want && strcmp(want, sky.path) != 0)) {
		sky_cancel();
		sky_delete();
		free(sky.path);
		sky.path = want ? strdup(want) : NULL;
		if (sky.path && sky_program()) {
			/* No more of it than the glasses have pixels for */
			GLint most = 0;
			glGetIntegerv(GL_MAX_TEXTURE_SIZE, &most);
			int w = (int)ceil(eye_w * 2 * M_PI / fov_x);
			w = w > most ? most : w;
			sky_load(server, w > SKY_MAX_W ? SKY_MAX_W : w);
		}
	}
	if (sky.whole &&
			sky.horizon != server->config.glasses.background_horizon) {
		sky_mesh(server);
	}
	if (sky.map == NULL) {
		return;
	}
	if (sky.rows == 0) {
		sky_delete(); // one left by a sky_drop that couldn't
		sky_edges();
		glGenTextures(1, &sky.tex);
	}
	glBindTexture(GL_TEXTURE_2D, sky.tex);
	if (sky.rows == 0) {
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, sky.w, sky.h, 0, GL_RGB,
			GL_UNSIGNED_BYTE, NULL);
	}
	int n = SKY_UPLOAD / (sky.w * 3);
	n = n < 1 ? 1 : n;
	n = n > sky.h - sky.rows ? sky.h - sky.rows : n;
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
	glTexSubImage2D(GL_TEXTURE_2D, 0, 0, sky.rows, sky.w, n, GL_RGB,
		GL_UNSIGNED_BYTE, sky.map + 8 + (size_t)sky.rows * sky.w * 3);
	glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
	glBindTexture(GL_TEXTURE_2D, 0);
	sky.rows += n;
	if (sky.rows == sky.h) {
		munmap(sky.map, sky.map_size);
		sky.map = NULL;
		sky_mesh(server);
		sky.whole = sky.vbo != 0;
	}
}

static void sky_parts(struct mat4 a, struct mat4 b, GLuint vbo, float alpha,
	int from, int to);

static void draw_sky(const struct eye *eye, struct pose head, float alpha) {
	/* Round the head, wherever the neck has carried it */
	struct mat4 model = { {
		SKY_M, 0, 0, 0, 0, SKY_M, 0, 0, 0, 0, SKY_M, 0,
		head.position.x, head.position.y, head.position.z, 1,
	} };
	struct mat4 a = mat4_mul(eye->view_proj[0], model);
	struct mat4 b = mat4_mul(eye->view_proj[1], model);
	sky_parts(a, b, sky.vbo, alpha, 2, 0);
}

/* The mesh's parts from one to another (0 the picture, 1 above it, 2
 * below), drawn from vbo with a and b as vp and vp_end */
static void sky_parts(struct mat4 a, struct mat4 b, GLuint vbo, float alpha,
		int from, int to) {
	glUseProgram(sky.program);
	glActiveTexture(GL_TEXTURE0);
	glUniformMatrix4fv(sky.vp, 1, GL_FALSE, a.m);
	glUniformMatrix4fv(sky.vp_end, 1, GL_FALSE, b.m);
	glUniform1i(sky.sampler, 0);
	glUniform1f(sky.alpha, alpha);
	glBindBuffer(GL_ARRAY_BUFFER, vbo);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sky.ibo);
	glVertexAttribPointer(sky.pos, 3, GL_FLOAT, GL_FALSE,
		5 * sizeof(GLfloat), (void *)0);
	glVertexAttribPointer(sky.uv, 2, GL_FLOAT, GL_FALSE,
		5 * sizeof(GLfloat), (void *)(3 * sizeof(GLfloat)));
	glEnableVertexAttribArray(sky.pos);
	glEnableVertexAttribArray(sky.uv);
	/* What's beyond the picture first: it fades in over that */
	for (int k = from; to <= from ? k >= to : k <= to;
			k += to <= from ? -1 : 1) {
		if (sky.count[k] == 0) {
			continue;
		}
		glBindTexture(GL_TEXTURE_2D, k == 0 ? sky.tex : sky.edge);
		glUniform2f(sky.fade, k == 0 ? sky.fade_v[0] : 0,
			k == 0 ? sky.fade_v[1] : 0);
		glDrawElements(GL_TRIANGLES, sky.count[k], GL_UNSIGNED_SHORT,
			(void *)(sky.first[k] * sizeof(GLushort)));
		draw_count++;
	}
	glDisableVertexAttribArray(sky.pos);
	glDisableVertexAttribArray(sky.uv);
	/* The rest draw from arrays of their own, wlroots too */
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
	glBindTexture(GL_TEXTURE_2D, 0);
}

/* The background for an OpenXR runtime (xrclient.c), which shows it as
 * equirectangular layers behind ours: sharp, and turned with the head
 * at the last moment. The picture is a band as high above the horizon
 * as below (Monado v25.1.0 counts the angles from straight up, so an
 * uneven one comes out upside down: an even one is right either way),
 * what isn't in it clear; the edge's colours are a whole sphere of
 * their own behind it. */
bool c8_xr_sky(struct c8_server *server, struct c8_xr_sky *out) {
	if (!sky.whole || sky.flat == 0) {
		return false;
	}
	double half = fmax(fabs(sky.top), fabs(sky.bottom));
	*out = (struct c8_xr_sky){
		.serial = sky.serial,
		.w = sky.w,
		.h = (int)ceil(half / M_PI * sky.w),
		.half = half,
		.fill = sky.above || sky.below,
	};
	return out->h > 0;
}

/* How much black goes over the background's layers: it fades in, and
 * dims under Start with the windows. The runtime blends in linear
 * light, ours as the sRGB numbers are: as dark as ours looks, the
 * multiplier goes to the power 2.2 (Monado, nested: 0.3 came out as
 * 0.56 of the sky's sRGB value). */
float c8_xr_sky_veil(struct c8_server *server) {
	return 1 - powf(sky.shown * server->xr.dim, 2.2f);
}

/* Into the framebuffer bound, w by h: the picture's band, or the fill */
void c8_xr_sky_draw(struct c8_server *server, bool fill, int w, int h) {
	glViewport(0, 0, w, h);
	glDisable(GL_SCISSOR_TEST);
	glClearColor(0, 0, 0, 0);
	glClear(GL_COLOR_BUFFER_BIT);
	glEnable(GL_BLEND);
	glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
	/* x is -1 to 1 already; y, the pitch, to -1 to 1 */
	double half = fill ? M_PI / 2 : fmax(fabs(sky.top), fabs(sky.bottom));
	struct mat4 m = { {
		1, 0, 0, 0, 0, 1 / half, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1,
	} };
	if (fill) {
		sky_parts(m, m, sky.flat, 1, 2, 1);
	} else {
		sky_parts(m, m, sky.flat, 1, 0, 0);
	}
	glUseProgram(0);
}

/* An all-round video (stereo.c): a surface's picture on a sphere round
 * the head, as the background is, its middle straight ahead. Each eye
 * gets its part of the buffer if it is 3D too. The half sphere is the
 * same mesh with the picture over its front half and nothing behind. */

#define DOME_ROWS (SKY_COLS / 2)

#define DOME_SRC(pre, sampler) \
	pre \
	"#ifdef GL_FRAGMENT_PRECISION_HIGH\n" \
	"precision highp float;\n" \
	"#else\n" \
	"precision mediump float;\n" \
	"#endif\n" \
	"uniform " sampler " tex;\n" \
	"uniform float alpha;\n" \
	"uniform float half_sphere;\n" \
	"uniform vec4 uv_rect;\n" \
	"varying vec2 v_uv;\n" \
	"void main() {\n" \
	"	float u = v_uv.x;\n" \
	"	if (half_sphere > 0.5) {\n" \
	"		u = (u - 0.5) * 2.0 + 0.5;\n" \
	"		if (u < 0.0 || u > 1.0) discard;\n" \
	"	}\n" \
	"	vec2 t = uv_rect.xy + vec2(u, v_uv.y) * uv_rect.zw;\n" \
	"	gl_FragColor = vec4(texture2D(tex, t).rgb * alpha, alpha);\n" \
	"}\n"

static const char dome_2d_src[] = DOME_SRC("", "sampler2D");
static const char dome_external_src[] = DOME_SRC(
	"#extension GL_OES_EGL_image_external : require\n", "samplerExternalOES");

struct dome_program {
	GLuint id;
	GLint vp, vp_end, pos, uv, sampler, alpha, half, uv_rect;
	bool failed;
};

static struct {
	struct dome_program flat, external;
	GLuint vbo, ibo;
	int count;
} dome;

static struct dome_program *dome_program(bool external) {
	struct dome_program *p = external ? &dome.external : &dome.flat;
	if (p->id || p->failed) {
		return p->id ? p : NULL;
	}
	GLuint vs = compile(GL_VERTEX_SHADER, "", sky_vertex_src);
	GLuint fs = compile(GL_FRAGMENT_SHADER, "",
		external ? dome_external_src : dome_2d_src);
	GLuint id = vs && fs ? glCreateProgram() : 0;
	if (id) {
		glAttachShader(id, vs);
		glAttachShader(id, fs);
		glLinkProgram(id);
		GLint ok = 0;
		glGetProgramiv(id, GL_LINK_STATUS, &ok);
		if (!ok) {
			glDeleteProgram(id);
			id = 0;
		}
	}
	glDeleteShader(vs);
	glDeleteShader(fs);
	if (id == 0) {
		p->failed = true;
		return NULL;
	}
	p->id = id;
	p->vp = glGetUniformLocation(id, "vp");
	p->vp_end = glGetUniformLocation(id, "vp_end");
	p->sampler = glGetUniformLocation(id, "tex");
	p->alpha = glGetUniformLocation(id, "alpha");
	p->half = glGetUniformLocation(id, "half_sphere");
	p->uv_rect = glGetUniformLocation(id, "uv_rect");
	p->pos = glGetAttribLocation(id, "pos");
	p->uv = glGetAttribLocation(id, "uv");
	return p;
}

static bool dome_mesh(void) {
	if (dome.vbo) {
		return true;
	}
	int across = SKY_COLS + 1, rings = DOME_ROWS + 1;
	GLfloat *v = calloc((size_t)across * rings * 5, sizeof(GLfloat));
	GLushort *ix = calloc((size_t)SKY_COLS * DOME_ROWS * 6, sizeof(GLushort));
	if (v == NULL || ix == NULL) {
		free(v);
		free(ix);
		return false;
	}
	GLfloat *p = v;
	GLushort *q = ix;
	for (int r = 0; r <= DOME_ROWS; r++) {
		double t = (double)r / DOME_ROWS;
		p = sky_ring(p, NULL, M_PI / 2 - t * M_PI, t, false);
		for (int c = 0; r < DOME_ROWS && c < SKY_COLS; c++) {
			GLushort a = r * across + c, b = a + across;
			*q++ = a;
			*q++ = b;
			*q++ = a + 1;
			*q++ = a + 1;
			*q++ = b;
			*q++ = b + 1;
		}
	}
	dome.count = (int)(q - ix);
	glGenBuffers(1, &dome.vbo);
	glGenBuffers(1, &dome.ibo);
	glBindBuffer(GL_ARRAY_BUFFER, dome.vbo);
	glBufferData(GL_ARRAY_BUFFER, (p - v) * sizeof(GLfloat), v,
		GL_STATIC_DRAW);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, dome.ibo);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, (q - ix) * sizeof(GLushort), ix,
		GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
	free(v);
	free(ix);
	return true;
}

static void draw_dome(const struct eye *eye, struct pose head,
		const struct c8_stereo_surface *st, int which, float alpha) {
	struct wlr_texture *texture = wlr_surface_get_texture(st->surface);
	if (texture == NULL || !dome_mesh()) {
		return;
	}
	struct wlr_gles2_texture_attribs attribs;
	wlr_gles2_texture_get_attribs(texture, &attribs);
	struct dome_program *p =
		dome_program(attribs.target == GL_TEXTURE_EXTERNAL_OES);
	if (p == NULL) {
		return;
	}
	struct wlr_fbox box;
	wlr_surface_get_buffer_source_box(st->surface, &box);
	float src[4] = {
		box.x / texture->width, box.y / texture->height,
		box.width / texture->width, box.height / texture->height,
	};
	stereo_src(st->layout, st->right_first, which, texture, src);
	struct mat4 model = { {
		SKY_M, 0, 0, 0, 0, SKY_M, 0, 0, 0, 0, SKY_M, 0,
		head.position.x, head.position.y, head.position.z, 1,
	} };
	struct mat4 a = mat4_mul(eye->view_proj[0], model);
	struct mat4 b = mat4_mul(eye->view_proj[1], model);
	glUseProgram(p->id);
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(attribs.target, attribs.tex);
	glTexParameteri(attribs.target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(attribs.target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glUniformMatrix4fv(p->vp, 1, GL_FALSE, a.m);
	glUniformMatrix4fv(p->vp_end, 1, GL_FALSE, b.m);
	glUniform1i(p->sampler, 0);
	glUniform1f(p->alpha, alpha);
	glUniform1f(p->half, st->projection == 2 ? 1 : 0);
	glUniform4fv(p->uv_rect, 1, src);
	glBindBuffer(GL_ARRAY_BUFFER, dome.vbo);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, dome.ibo);
	glVertexAttribPointer(p->pos, 3, GL_FLOAT, GL_FALSE,
		5 * sizeof(GLfloat), (void *)0);
	glVertexAttribPointer(p->uv, 2, GL_FLOAT, GL_FALSE,
		5 * sizeof(GLfloat), (void *)(3 * sizeof(GLfloat)));
	glEnableVertexAttribArray(p->pos);
	glEnableVertexAttribArray(p->uv);
	glDrawElements(GL_TRIANGLES, dome.count, GL_UNSIGNED_SHORT, (void *)0);
	draw_count++;
	glDisableVertexAttribArray(p->pos);
	glDisableVertexAttribArray(p->uv);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
	glBindTexture(attribs.target, 0);
}

/* The refresh a frame drawn now starts from: the last one shown, on the
 * display's own beat. Drawing starts a varying while after it (whatever
 * else the loop had to do first), but the frame still lights at the
 * next one; timed from now, every late start was a pose too far ahead,
 * and turning the head the picture shook by as much */
static int64_t frame_start(struct c8_output *output) {
	int64_t now = c8_now_ns();
	int64_t r = output->refresh_ns, at = output->presented_ns;
	if (r <= 0 || at <= 0 || now < at || now - at > 4 * r) {
		return now; // not shown lately: nothing better to go by
	}
	return at + (now - at) / r * r;
}

#define LATENCY_AT_MS (1000.0 / 90) // the refresh [glasses] latency is for

/* One frame's eyes, however they were found: from our own tracking for
 * the glasses' output, from the runtime's views through OpenXR */
struct space_frame {
	struct pose head; // recentred
	struct eye eyes[2];
	int count;
	double m, fov_x, fov_y;
	int width, height; // what is drawn into
	bool backdrop; // the sky or a dome behind; not over a VR game
	bool sky_layer; // the runtime can show the background behind
	const struct c8_xr_slates *slates; // windows as layers of their own
	bool *drawn; // set: anything drawn into the views
};

static bool draw_space_frame(struct c8_server *server, struct c8_xr_gl *gl,
	const struct space_frame *f, struct wlr_texture *picture);

/* The glasses' frame: the windows' slates and the shell's screen in front */
static bool draw_space(struct c8_output *output, struct wlr_buffer *buffer,
		struct wlr_texture *picture) {
	struct c8_server *server = output->server;
	struct wlr_render_pass *pass =
		wlr_renderer_begin_buffer_pass(server->renderer, buffer, NULL);
	if (pass == NULL) {
		return false;
	}
	struct c8_xr_gl *gl = gl_get(server);
	if (gl == NULL) {
		/* No shaders: at least a flat picture */
		wlr_render_pass_add_rect(pass, &(struct wlr_render_rect_options){
			.box = { 0, 0, buffer->width, buffer->height },
			.color = { 0, 0, 0, 1 },
		});
		if (picture) {
			wlr_render_pass_add_texture(pass,
				&(struct wlr_render_texture_options){
					.texture = picture,
					.dst_box = { 0, 0, buffer->width, buffer->height },
				});
		}
		return wlr_render_pass_submit(pass);
	}

	/* latency is from the refresh this frame starts in to the middle row
	 * being seen; the top row lights half a scan before it, the bottom
	 * one half a scan after. It is a refresh and a half (the frame is
	 * taken at the next refresh and its middle lit half of one later)
	 * and a little, so the setting, found at 90 Hz, grows with the
	 * refresh: the glasses' 3D mode runs at 60, and with 90's look ahead
	 * the windows trailed every turn by 8 ms of it. */
	double refresh_ms = output->refresh_ns > 0 ? output->refresh_ns / 1e6 :
		output->wlr_output->refresh > 0 ?
		1e6 / output->wlr_output->refresh : LATENCY_AT_MS;
	int64_t mid = frame_start(output) + (int64_t)(
		server->config.glasses.latency * refresh_ms / LATENCY_AT_MS * 1e6);
	int64_t half = (int64_t)(scan_ms(output) * 500000);
	struct pose head = head_at(server, mid);
	struct pose heads[2] = {
		head_at(server, mid - half), head_at(server, mid + half),
	};
	struct space_frame f = {
		.head = head, .width = buffer->width, .height = buffer->height,
		.backdrop = true,
	};
	f.count = eyes_for(server, buffer->width, buffer->height, heads, f.eyes,
		&f.m, &f.fov_x, &f.fov_y);
	draw_space_frame(server, gl, &f, picture);
	pace.drawn = c8_now_ns();
	return wlr_render_pass_submit(pass);
}

/* A window drawn flat for a runtime's quad layer (xrclient.c): its
 * surfaces, popups, frame and chrome, at a pixel of the image to a pixel
 * of the slate, through an eye that looks straight at the slate's plane.
 * The image is what's on the slate round the window; the layer's pose
 * is that image's middle. */
struct slate_look {
	struct c8_view *view;
	struct pose pose;
	double m;
	float alpha;
	const float *frame; // its colour, or NULL: none
	bool chrome;
	const float *accent;
	struct timespec *now;
};

static void slate_extent(struct wlr_scene_buffer *buffer, int lx, int ly,
		void *data) {
	struct wlr_box *b = data;
	struct wlr_scene_surface *ss = wlr_scene_surface_try_from_buffer(buffer);
	if (ss == NULL) {
		return;
	}
	int x1 = lx + ss->surface->current.width;
	int y1 = ly + ss->surface->current.height;
	x1 = x1 > b->x + b->width ? x1 : b->x + b->width;
	y1 = y1 > b->y + b->height ? y1 : b->y + b->height;
	b->x = lx < b->x ? lx : b->x;
	b->y = ly < b->y ? ly : b->y;
	b->width = x1 - b->x;
	b->height = y1 - b->y;
}

/* What a window's layer shows, as one number: when it's the same as last
 * frame's the runtime shows the image it has (most windows, most of the
 * time: a window moved round you is the same image elsewhere) */
static uint64_t sig_mix(uint64_t h, uint64_t v) {
	h ^= v + 0x9e3779b97f4a7c15ull + (h << 6) + (h >> 2);
	return h ? h : 1;
}

static uint64_t sig_float(uint64_t h, float f) {
	uint32_t u;
	memcpy(&u, &f, sizeof(u));
	return sig_mix(h, u);
}

/* Each surface's commits (a client's every new picture) and place */
static void sig_surface(struct wlr_scene_buffer *buffer, int lx, int ly,
		void *data) {
	uint64_t *h = data;
	struct wlr_scene_surface *ss = wlr_scene_surface_try_from_buffer(buffer);
	if (ss == NULL) {
		return;
	}
	*h = sig_mix(*h, (uintptr_t)ss->surface);
	*h = sig_mix(*h, ss->surface->current.seq);
	*h = sig_mix(*h, (uint64_t)(uint32_t)lx << 32 | (uint32_t)ly);
	*h = sig_mix(*h, (uintptr_t)wlr_surface_get_texture(ss->surface));
}

/* A tree's surfaces (the toasts', a splash's) */
static uint64_t tree_sig(struct wlr_scene_node *node) {
	uint64_t h = 1;
	wlr_scene_node_for_each_buffer(node, sig_surface, &h);
	return h;
}

static uint64_t slate_sig(struct c8_view *view, const struct slate_look *l) {
	uint64_t h = sig_mix(0, (uint64_t)view->geo.width << 32 |
		(uint32_t)view->geo.height);
	wlr_scene_node_for_each_buffer(&view->tree->node, sig_surface, &h);
	h = sig_float(h, l->alpha);
	h = sig_mix(h, l->frame != NULL);
	for (int i = 0; l->frame && i < 4; i++) {
		h = sig_float(h, l->frame[i]);
	}
	h = sig_mix(h, l->chrome);
	if (l->chrome) {
		struct c8_slatebar_look look = c8_holo_chrome_look(view);
		h = sig_mix(h, (uintptr_t)c8_slatebar_texture(view, &look));
		h = sig_mix(h, (uint64_t)(uint32_t)look.width << 32 |
			(uint32_t)look.hover);
		h = sig_mix(h, (uint64_t)(uint32_t)look.pressed << 32 |
			(uint32_t)look.stereo);
		h = sig_mix(h, look.focused | look.follow << 1 | look.icon << 2 |
			look.theatre << 3);
		h = sig_mix(h, look.accent);
		for (const char *t = look.title; t && *t; t++) {
			h = sig_mix(h, (unsigned char)*t);
		}
		h = sig_mix(h, view->server->xr.size_view == view);
		for (int i = 0; i < 4; i++) {
			h = sig_float(h, l->accent[i]);
		}
	}
	return h;
}

/* A slate's plane drawn into a layer of its own: the eye looks straight
 * at it, a pixel of the image to a pixel of the slate (w x h, m metres
 * each, its middle at pose), the image covering (x0, y0)..(x1, y1) of
 * its pixels with room round them for the soft edges */
struct plane {
	const struct c8_xr_slates *slates;
	const void *key;
	struct pose pose;
	double curve;
	bool same; // nothing to draw: the last image stands
	double lx0, lx1, ly0, ly1;
	struct eye eye;
	GLint fbo, vp[4];
};

static enum c8_xr_slate_begin plane_begin(struct plane *p,
		const struct c8_xr_slates *slates, const void *key, struct pose pose,
		double m, int w, int h, double x0, double y0, double x1, double y1,
		double curve, uint64_t sig) {
	x0 = floor(x0 - AA_MARGIN - 1);
	y0 = floor(y0 - AA_MARGIN - 1);
	x1 = ceil(x1 + AA_MARGIN + 1);
	y1 = ceil(y1 + AA_MARGIN + 1);
	int iw = (int)(x1 - x0), ih = (int)(y1 - y0);
	if (iw <= 0 || ih <= 0) {
		return C8_XR_NONE;
	}
	glGetIntegerv(GL_FRAMEBUFFER_BINDING, &p->fbo);
	glGetIntegerv(GL_VIEWPORT, p->vp);
	/* The image's place goes in its sig: the same picture placed
	 * otherwise in it is another image */
	if (sig) {
		sig = sig_mix(sig, (uint64_t)(int64_t)x0 << 32 ^ (uint32_t)y0);
		sig = sig_mix(sig, (uint64_t)iw << 32 | (uint32_t)ih);
	}
	enum c8_xr_slate_begin got = slates->begin(slates->data, key, iw, ih,
		curve, sig);
	if (got == C8_XR_NONE) {
		return C8_XR_NONE;
	}
	p->slates = slates;
	p->key = key;
	p->pose = pose;
	p->curve = curve;
	/* x right, y up, in metres round the slate's middle */
	p->lx0 = (x0 - w / 2.0) * m;
	p->lx1 = (x1 - w / 2.0) * m;
	p->ly0 = (h / 2.0 - y1) * m;
	p->ly1 = (h / 2.0 - y0) * m;
	p->same = got == C8_XR_SAME;
	if (p->same) {
		return C8_XR_SAME;
	}
	struct mat4 ortho = { {
		2 / (p->lx1 - p->lx0), 0, 0, 0,
		0, 2 / (p->ly1 - p->ly0), 0, 0,
		0, 0, 0, 0,
		-(p->lx1 + p->lx0) / (p->lx1 - p->lx0),
		-(p->ly1 + p->ly0) / (p->ly1 - p->ly0), 0, 1,
	} };
	struct mat4 vpm = mat4_mul(ortho, mat4_view(pose));
	p->eye = (struct eye){ { vpm, vpm }, 0, iw, ih };
	glViewport(0, 0, iw, ih);
	glDisable(GL_SCISSOR_TEST);
	glClearColor(0, 0, 0, 0);
	glClear(GL_COLOR_BUFFER_BIT);
	glEnable(GL_BLEND);
	glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
	return C8_XR_DRAW;
}

static void plane_end(struct plane *p) {
	struct pose middle = {
		pose_point(p->pose, (p->lx0 + p->lx1) / 2,
			(p->ly0 + p->ly1) / 2, 0),
		p->pose.orientation,
	};
	p->slates->end(p->slates->data, p->key, middle, p->lx1 - p->lx0,
		p->ly1 - p->ly0, p->curve);
	if (p->same) {
		return;
	}
	glBindFramebuffer(GL_FRAMEBUFFER, p->fbo);
	glViewport(p->vp[0], p->vp[1], p->vp[2], p->vp[3]);
}

static bool draw_slate_layer(struct c8_server *server, struct c8_xr_gl *gl,
		const struct c8_xr_slates *slates, const struct slate_look *l) {
	struct c8_view *view = l->view;
	int w = view->geo.width, h = view->geo.height;
	/* What's on the slate, in its pixels: the surfaces (popups go past
	 * the window), the frame round it, the chrome under it */
	struct wlr_box b = view->geo;
	wlr_scene_node_for_each_buffer(&view->tree->node, slate_extent, &b);
	double x0 = b.x - view->geo.x, y0 = b.y - view->geo.y;
	double x1 = x0 + b.width, y1 = y0 + b.height;
	x0 = fmin(x0, -FRAME_PX);
	y0 = fmin(y0, -FRAME_PX);
	x1 = fmax(x1, w + FRAME_PX);
	y1 = fmax(y1, h + FRAME_PX);
	/* Room for the chrome whether it shows or not: the layer keeps its
	 * size and middle when it comes and goes, and its swapchain (a
	 * bigger one took frames to come, the window meanwhile in our
	 * projection, which moved on the glasses, 2026-12-02) */
	x1 = fmax(x1, fmax(c8_slatebar_width(w), w + 30));
	y1 = fmax(y1, h + C8_SLATEBAR_GAP + C8_SLATEBAR_H);
	struct plane p;
	enum c8_xr_slate_begin got = plane_begin(&p, slates, view, l->pose,
		l->m, w, h, x0, y0, x1, y1, 0, slate_sig(view, l));
	if (got == C8_XR_NONE) {
		return false;
	}
	if (got == C8_XR_SAME) {
		plane_end(&p);
		return true;
	}
	if (l->frame) {
		draw_frame(gl, &p.eye, l->pose, l->m, w, h, l->frame);
	}
	struct slate_draw sd = {
		gl, &p.eye, l->pose, l->m, view->geo, l->now, l->alpha,
		.server = server, .which = 0,
		.main = view->impl->get_surface(view),
	};
	wlr_scene_node_for_each_buffer(&view->tree->node, draw_surface, &sd);
	if (l->chrome) {
		draw_chrome(gl, &p.eye, l->pose, l->m, view, l->alpha, l->accent);
	}
	plane_end(&p);
	return true;
}

/* A window that can be a layer: flat (a 3D one gives each eye its own
 * picture, which one quad can't), and not the all-round video's */
static bool slate_flat(struct c8_server *server, struct c8_view *view,
		struct c8_view *around_view) {
	if (view->holo.stereo || view == around_view) {
		return false;
	}
	struct wlr_surface *main = view->impl->get_surface(view);
	return main == NULL || c8_stereo_for(server, main) == NULL;
}

/* The windows' slates and the shell's screen in front, into whatever
 * framebuffer is bound: the glasses' buffer or an OpenXR runtime's
 * swapchain image (xrclient.c) */
static bool draw_space_frame(struct c8_server *server, struct c8_xr_gl *gl,
		const struct space_frame *f, struct wlr_texture *picture) {
	struct pose head = f->head;
	const struct eye *eyes = f->eyes;
	int count = f->count;
	double m = f->m, fov_x = f->fov_x, fov_y = f->fov_y;
	/* The ray follows the head; this may move the cursor */
	c8_holo_frame(server, head, m, fov_x, fov_y);
	/* 3D surfaces get an eye each when there are two; a sphere goes
	 * round you either way */
	c8_stereo_shows(server, C8_STEREO_SHOWS_SURROUND |
		(count == 2 ? C8_STEREO_SHOWS_STEREO : 0));
	struct c8_view *around_view = NULL;
	struct c8_stereo_surface *around = c8_locked(server) ? NULL :
		c8_stereo_surround(server, &around_view);

	struct ranked ranked[64];
	int n = 0;
	struct c8_view *view;
	int mru = 0;
	wl_list_for_each(view, &server->views, link) {
		if (n < 64 && view->mapped && view->holo.slot &&
				view->tree->node.enabled && !c8_locked(server)) {
			struct pose pose = c8_holo_pose(view);
			ranked[n++] = (struct ranked){ view, mru, pose,
				vec3_length(pose.position) };
		}
		mru++;
	}
	qsort(ranked, n, sizeof(ranked[0]), ranked_cmp);
	struct c8_view *focused = c8_top_view(server);
	/* What can't be seen isn't drawn, and isn't asked for a new frame
	 * every time: an app behind you would go on drawing at the glasses'
	 * rate for nobody. Not the one in front (it has the keyboard), nor
	 * one being shared, which someone else is watching. */
	int64_t now_ms = c8_now_ms();
	/* Over a VR game the desktop keeps out of the way until it's called
	 * for: Start (Super) or the charms bar bring the windows over it */
	bool game_only = !f->backdrop && !server->start_visible &&
		!server->xr.bar_shown;
	for (int k = 0; k < n; k++) {
		view = ranked[k].view;
		/* A minimised one neither, whoever is watching */
		ranked[k].away = away(view, now_ms);
		ranked[k].unseen = ranked[k].away >= 1 || game_only ||
			(view != focused &&
			view->listed.capture == NULL && view != around_view &&
			out_of_view(head, ranked[k].pose, m, view->geo.width,
			view->geo.height, fov_x, fov_y));
	}
	/* Under Start the windows dim (the glasses add light, so less of it
	 * is darker and more see-through), eased so it doesn't blink */
	struct c8_view *theatre = c8_holo_theatre(server);
	float dim_goal = server->start_visible ? DIM_UNDER_START :
		theatre ? DIM_BY_THEATRE : 1;
	server->xr.dim += (dim_goal - server->xr.dim) * DIM_RATE;
	if (fabsf(dim_goal - server->xr.dim) < 0.01f) {
		server->xr.dim = dim_goal;
	}
	struct c8_shell_surface *splash = c8_shell_splash(server);
	struct wlr_box splash_box;
	if (splash && !c8_holo_splash_box(server, &splash_box)) {
		splash = NULL;
	}
	struct c8_shell_surface *bar = c8_shell_bar(server);
	struct wlr_box bar_box;
	if (bar && (server->xr.bar_fade <= 0 || c8_locked(server) ||
			!c8_holo_bar_box(server, &bar_box))) {
		bar = NULL;
	}
	struct wlr_box hud_box;
	bool hud = server->xr.hud_placed && c8_holo_hud_box(server, &hud_box);
	float accent[4];
	c8_color_to_float(server->config.accent, 1, accent);
	struct timespec now;
	clock_gettime(CLOCK_MONOTONIC, &now);
	/* The same for both eyes */
	bool outlines = server->config.glasses.outlines && !c8_locked(server);
	float shell_src[4];
	double shell_m = 0, hud_m = 0;
	struct pose shell_pose = { 0 }, hud_pose = { 0 };
	struct wlr_box shell_box = { 0 };
	if (picture && !wlr_box_intersection(&shell_box, &server->xr.picture_dst,
			&server->xr.picture_shown)) {
		picture = NULL; // nothing on the shell's screen
	}
	if (picture) {
		/* Only the part of it with something on */
		struct wlr_box *d = &server->xr.picture_dst;
		float all[4];
		picture_src(server, picture, all);
		shell_src[0] = all[0] + all[2] * (shell_box.x - d->x) / d->width;
		shell_src[1] = all[1] + all[3] * (shell_box.y - d->y) / d->height;
		shell_src[2] = all[2] * shell_box.width / d->width;
		shell_src[3] = all[3] * shell_box.height / d->height;
		shell_pose = c8_holo_shell_pose(server, &shell_m);
	}
	if (hud) {
		hud_pose = c8_holo_hud_pose(server, &hud_m);
	}
	double bar_m = c8_holo_bar_m(server);
	/* Where the ray lands (the shell's screen draws its own) */
	double dot_yaw, dot_pitch;
	vec3_yaw_pitch(server->xr.aim, &dot_yaw, &dot_pitch);
	struct pose dot = { vec3_add(head.position, vec3_scale(server->xr.aim,
		server->xr.aim_t * 0.999)), quat_yaw_pitch(dot_yaw, dot_pitch) };
	double dot_r = CURSOR_PX * server->xr.aim_t /
		server->config.glasses.distance;

	bool timed = false;
	if (gl->timer) {
		GLuint ready = 0;
		if (gl->timing) {
			gl->query_uiv(gl->timer, GL_QUERY_RESULT_AVAILABLE_EXT, &ready);
			if (ready) {
				GLuint64 ns = 0;
				gl->query_ui64v(gl->timer, GL_QUERY_RESULT_EXT, &ns);
				pace.gpu_sum += ns / 1e6;
				pace.gpu_max = fmax(pace.gpu_max, ns / 1e6);
				pace.gpu_n++;
				gl->timing = false;
			}
		}
		if (!gl->timing) {
			gl->begin_query(GL_TIME_ELAPSED_EXT, gl->timer);
			timed = true;
		}
	}
	sky_update(server, eyes[0].width, fov_x);
	bool backdrop = f->backdrop && !c8_locked(server);
	if (sky.whole && backdrop) {
		sky.shown += (1 - sky.shown) * SKY_RATE;
	}
	/* The background behind, as the runtime's: what is clear here shows
	 * it, dimmed and faded in by a layer between it and the windows
	 * (c8_xr_sky_veil) */
	bool layered = f->sky_layer && sky.whole && backdrop && !around;
	/* Windows the runtime shows as layers of their own, under ours:
	 * drawn once each here, and left out of the eyes below. Not while
	 * something solid is behind them in ours (the background drawn
	 * here, a video all round): it would cover them. */
	const struct c8_xr_slates *slates = f->slates;
	if ((around && f->backdrop) || (sky.whole && backdrop && !layered)) {
		slates = NULL;
	}
	for (int k = 0; slates && k < n; k++) {
		view = ranked[k].view;
		if (ranked[k].unseen || ranked[k].away > 0 ||
				!slate_flat(server, view, around_view)) {
			continue;
		}
		bool playing = theatre && c8_view_root(view) == theatre;
		static const float white[4] = {
			outline_rgba, outline_rgba, outline_rgba, outline_rgba,
		};
		struct slate_look look = {
			view, ranked[k].pose, m, playing ? 1 : server->xr.dim,
			view == focused && !server->start_visible && !playing ?
				accent : outlines ? white : NULL,
			c8_holo_chrome_shown(view), accent, &now,
		};
		ranked[k].layered = draw_slate_layer(server, gl, slates, &look);
	}
	/* The shell's in front of the windows: layers too, as long as all
	 * under them are (layers have no depth: one drawn in ours would be
	 * over them) */
	bool shell_layers = slates != NULL && !ghosts_shown();
	for (int k = 0; k < n; k++) {
		if (!ranked[k].unseen && !ranked[k].layered) {
			shell_layers = false;
		}
	}
	bool picture_layered = false, splash_layered = false,
		hud_layered = false;
	struct plane p;
	if (shell_layers && picture) {
		struct wlr_box *d = &shell_box;
		picture_layered = plane_begin(&p, slates, &server->xr.picture_dst,
			shell_pose, shell_m, server->xr.picture_w,
			server->xr.picture_h, d->x, d->y, d->x + d->width,
			d->y + d->height, 0, sig_float(sig_float(sig_float(sig_float(
			sig_mix(1, server->xr.picture_seq), shell_src[0]),
			shell_src[1]), shell_src[2]), shell_src[3])) != C8_XR_NONE;
		if (picture_layered && p.same) {
			plane_end(&p);
		} else if (picture_layered) {
			struct mvp mvp = quad_matrix(&p.eye, shell_pose, shell_m,
				server->xr.picture_w, server->xr.picture_h, d->x, d->y,
				d->width, d->height);
			struct aa aa = aa_sides(d->width, d->height, 1, 1, 1, 1);
			draw_texture_part(gl, &mvp, picture, 1, shell_src, true, &aa);
			plane_end(&p);
		}
		shell_layers = picture_layered;
	}
	if (shell_layers && splash && !c8_locked(server)) {
		splash_layered = plane_begin(&p, slates, splash,
			server->xr.splash_pose, m, splash_box.width,
			splash_box.height, 0, 0, splash_box.width, splash_box.height,
			0, tree_sig(&splash->tree->node)) != C8_XR_NONE;
		if (splash_layered && p.same) {
			plane_end(&p);
		} else if (splash_layered) {
			struct slate_draw sd = {
				gl, &p.eye, server->xr.splash_pose, m, splash_box, &now, 1,
			};
			wlr_scene_node_for_each_buffer(&splash->tree->node,
				draw_surface, &sd);
			plane_end(&p);
		}
		shell_layers = splash_layered;
	}
	if (shell_layers && hud) {
		uint64_t sig = 1;
		struct c8_shell_surface *ss;
		wl_list_for_each(ss, &server->shell.surfaces, link) {
			if (c8_shell_osd_shown(ss)) {
				sig = sig_mix(sig, tree_sig(&ss->tree->node));
			}
		}
		hud_layered = plane_begin(&p, slates, &server->xr.hud_placed,
			hud_pose, hud_m, hud_box.width, hud_box.height, 0, 0,
			hud_box.width, hud_box.height, 0, sig) != C8_XR_NONE;
		if (hud_layered && p.same) {
			plane_end(&p);
		} else if (hud_layered) {
			struct slate_draw sd = {
				gl, &p.eye, hud_pose, hud_m, hud_box, &now, 1,
			};
			wl_list_for_each(ss, &server->shell.surfaces, link) {
				if (c8_shell_osd_shown(ss)) {
					wlr_scene_node_for_each_buffer(&ss->tree->node,
						draw_surface, &sd);
				}
			}
			plane_end(&p);
		}
		shell_layers = hud_layered;
	}
	bool bar_layered = false;
	if (shell_layers && bar) {
		/* Bent round you by the runtime (a cylinder layer), drawn
		 * here flat: along it a pixel is as long as on ours. Its
		 * middle is the image's, so it reaches as far either side;
		 * the minimised windows' row and titles stand over it. */
		int w = bar_box.width, h = bar_box.height;
		double half = w / 2.0, top = 0;
		minimised_extent(server, &half, &top);
		bar_layered = plane_begin(&p, slates, bar, server->xr.bar_drawn,
			bar_m, w, h, w / 2.0 - half, top, w / 2.0 + half, h,
			C8_BAR_CURVE_R, 0) != C8_XR_NONE;
		if (bar_layered) {
			struct slate_draw sd = {
				gl, &p.eye, server->xr.bar_drawn, bar_m, bar_box, &now,
				server->xr.bar_fade,
			};
			wlr_scene_node_for_each_buffer(&bar->tree->node, draw_surface,
				&sd);
			draw_minimised(gl, &p.eye, server, bar_m, h, 0);
			plane_end(&p);
		}
		shell_layers = bar_layered;
	}
	/* The pointer's dot last, a layer too: in ours Monado turned it to
	 * the head on its own time and the windows on its, so on the
	 * glasses it swam against them (2026-12-02). Drawn once, a disc
	 * DOT_PX round in its image, sized by the layer. */
	bool dot_layered = false;
	if (shell_layers && !game_only) {
		static const char dot_key;
		enum { DOT_PX = 64, DOT_R = 28 };
		double dot_m = dot_r * m / DOT_R;
		enum c8_xr_slate_begin got = plane_begin(&p, slates, &dot_key,
			dot, dot_m, DOT_PX, DOT_PX, 0, 0, DOT_PX, DOT_PX, 0, 0xd07);
		dot_layered = got != C8_XR_NONE;
		if (got == C8_XR_DRAW) {
			struct mvp mvp = quad_matrix(&p.eye, dot, dot_m, DOT_PX, DOT_PX,
				DOT_PX / 2 - DOT_R, DOT_PX / 2 - DOT_R, 2 * DOT_R,
				2 * DOT_R);
			static const float white[4] = { 1, 1, 1, 1 };
			struct aa aa = { { 1.0f / DOT_R, 1.0f / DOT_R },
				{ 0, 0, 0, 0 } };
			draw_solid(&gl->disc, &mvp, white, &aa);
		}
		if (dot_layered) {
			plane_end(&p);
		}
	}
	glDisable(GL_SCISSOR_TEST);
	/* Over a VR game what isn't drawn shows it; so do the layers under
	 * ours */
	bool black = f->backdrop && !layered && !slates;
	glClearColor(0, 0, 0, black ? 1 : 0);
	glClear(GL_COLOR_BUFFER_BIT);
	glEnable(GL_BLEND);
	glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
	unsigned draws_before = draw_count;
	for (int i = 0; i < count; i++) {
		const struct eye *eye = &eyes[i];
		glViewport(eye->x, 0, eye->width, eye->height);
		/* Frames are done once the last eye has them */
		struct timespec *done = i == count - 1 ? &now : NULL;
		if (around && f->backdrop) {
			/* A video all round, in the background's place; under
			 * Start it dims as the windows do */
			draw_dome(eye, head, around, i,
				server->start_visible ? server->xr.dim : 1);
		} else if (sky.whole && backdrop && !layered) {
			/* Behind everything, dimming with the windows */
			draw_sky(eye, head, sky.shown * server->xr.dim);
		}
		if (outlines) {
			/* Under everything: there's no depth buffer, so what's
			 * drawn later covers it */
			if (f->backdrop) {
				draw_floor(gl, eye);
			}
			for (int k = 0; k < n; k++) {
				view = ranked[k].view;
				if (c8_holo_minimised(view)) {
					continue;
				}
				draw_drop(gl, eye, head, ranked[k].pose, m,
					view->geo.height);
			}
		}
		for (int k = 0; k < n; k++) {
			view = ranked[k].view;
			if (ranked[k].layered) {
				continue;
			}
			if (ranked[k].unseen) {
				/* A minimised window isn't asked to draw at all, as
				 * one hidden on the desktop isn't: the switcher shows
				 * what it last drew. One being shared still is. */
				if (c8_holo_minimised(view) &&
						view->listed.capture == NULL) {
					continue;
				}
				if (done && now_ms - view->holo.unseen_frame >=
						OUT_OF_VIEW_MS) {
					view->holo.unseen_frame = now_ms;
					wlr_scene_node_for_each_buffer(&view->tree->node,
						frame_done_only, done);
				}
				continue;
			}
			struct slate_draw sd = {
				gl, eye, ranked[k].pose, m, view->geo, done, server->xr.dim,
				.server = server, .which = i,
				.around = around ? around->surface : NULL,
				.main = view->impl->get_surface(view),
				.main_layout = view->holo.stereo,
			};
			bool playing = theatre && c8_view_root(view) == theatre;
			if (playing) {
				sd.alpha = 1; // the rest dim round it
			}
			double a = ranked[k].away;
			if (a > 0) {
				/* Smaller, lower and fainter: going to the bar's row
				 * or coming back from it; no frame or bar meanwhile */
				sd.pose.position = pose_point(sd.pose, 0,
					-AWAY_DROP_M * a, 0);
				sd.m = m * (1 - (1 - AWAY_SCALE) * a);
				sd.alpha *= 1 - a;
				wlr_scene_node_for_each_buffer(&view->tree->node,
					draw_surface, &sd);
				continue;
			}
			if (view == focused && !server->start_visible && !playing) {
				draw_frame(gl, eye, sd.pose, m, view->geo.width,
					view->geo.height, accent);
			} else if (outlines) {
				static const float white[4] = {
					outline_rgba, outline_rgba, outline_rgba,
					outline_rgba,
				};
				draw_frame(gl, eye, sd.pose, m, view->geo.width,
					view->geo.height, white);
			}
			wlr_scene_node_for_each_buffer(&view->tree->node, draw_surface,
				&sd);
			if (c8_holo_chrome_shown(view)) {
				draw_chrome(gl, eye, sd.pose, m, view, sd.alpha, accent);
			}
		}
		draw_ghosts(gl, eye, m, server->xr.dim, now_ms);
		if (picture && !picture_layered) {
			/* In front of them all, where nothing is clear */
			struct wlr_box *d = &shell_box;
			struct mvp mvp = quad_matrix(eye, shell_pose, shell_m,
				server->xr.picture_w, server->xr.picture_h, d->x, d->y,
				d->width, d->height);
			struct aa aa = aa_sides(d->width, d->height, 1, 1, 1, 1);
			draw_texture_part(gl, &mvp, picture, 1, shell_src, true, &aa);
		}
		if (splash && !splash_layered && !c8_locked(server)) {
			/* A launch: where its window will open, in front of everything (Start
			 * has just gone; without apps it stays) */
			struct slate_draw sd = {
				gl, eye, server->xr.splash_pose, m, splash_box, done, 1,
			};
			wlr_scene_node_for_each_buffer(&splash->tree->node,
				draw_surface, &sd);
		}
		if (hud && !hud_layered) {
			/* Toasts and the level box, along the bottom of the view */
			struct slate_draw sd = {
				gl, eye, hud_pose, hud_m, hud_box, done, 1,
			};
			struct c8_shell_surface *ss;
			wl_list_for_each(ss, &server->shell.surfaces, link) {
				if (c8_shell_osd_shown(ss)) {
					wlr_scene_node_for_each_buffer(&ss->tree->node,
						draw_surface, &sd);
				}
			}
		}
		for (int k = 0; k < n && !game_only; k++) {
			draw_beacon(gl, eye, head, m, ranked[k].view);
		}
		if (bar && !bar_layered) {
			/* The charms bar, below you and nearest of all */
			struct slate_draw sd = {
				gl, eye, server->xr.bar_drawn, bar_m, bar_box, done,
				server->xr.bar_fade, C8_BAR_CURVE_R,
			};
			wlr_scene_node_for_each_buffer(&bar->tree->node, draw_surface,
				&sd);
			draw_minimised(gl, eye, server, bar_m, bar_box.height,
				C8_BAR_CURVE_R);
		}
		if (game_only || dot_layered) {
			continue; // the game has the pointer, or it's a layer
		}
		/* The pointer, nearest of all */
		struct mvp mvp = quad_matrix(eye, dot, m, 0, 0, -dot_r, -dot_r,
			2 * dot_r, 2 * dot_r);
		static const float white[4] = { 1, 1, 1, 1 };
		/* Room round it for its soft rim: a screen pixel or two */
		struct aa aa = { { 1.0f / CURSOR_PX, 1.0f / CURSOR_PX },
			{ 0, 0, 0, 0 } };
		draw_solid(&gl->disc, &mvp, white, &aa);
	}
	if (f->drawn) {
		*f->drawn = black || draw_count != draws_before;
	}
	glViewport(0, 0, f->width, f->height);
	glUseProgram(0);
	if (timed) {
		gl->end_query(GL_TIME_ELAPSED_EXT);
		gl->timing = true;
	}
	return layered;
}

static bool dump_due(void);
static void dump_image(cairo_surface_t *image);

/* A frame for an OpenXR runtime (xrclient.c): its views, recentred,
 * drawn into the framebuffer bound, the eyes side by side. Its images
 * are GL's way up, so nothing is flipped. */
bool c8_xr_draw_views(struct c8_server *server,
		const struct c8_xr_view views[2], int view_w, int view_h, int gap,
		double overscan, bool over_game, bool sky_layer,
		const struct c8_xr_slates *slates, bool *drawn) {
	*drawn = true;
	struct c8_xr_gl *gl = gl_get(server);
	if (gl == NULL) {
		return false;
	}
	struct quat back = quat_conjugate(server->xr.centre);
	struct space_frame f = {
		.count = 2, .width = 2 * view_w + gap, .height = view_h,
		.backdrop = !over_game, .sky_layer = sky_layer, .slates = slates,
		.drawn = drawn,
	};
	struct vec3 mid = { 0, 0, 0 };
	for (int i = 0; i < 2; i++) {
		struct pose eye = {
			quat_rotate(back, views[i].pose.position),
			quat_mul(back, views[i].pose.orientation),
		};
		mid = vec3_add(mid, vec3_scale(eye.position, 0.5));
		struct mat4 proj = mat4_frustum(tan(views[i].left),
			tan(views[i].right), tan(views[i].down), tan(views[i].up),
			0.05, 100);
		struct mat4 vp = mat4_mul(proj, mat4_view(eye));
		/* No rolling scanout to make up for: the runtime reprojects */
		f.eyes[i] = (struct eye){ { vp, vp }, i * (view_w + gap), view_w,
			view_h };
	}
	f.head = (struct pose){ mid,
		quat_mul(back, views[0].pose.orientation) };
	/* Their sizes as one eye sees: the left's, from its angles, less
	 * what's drawn beyond the glasses' edges for the runtime's turning */
	double tx = tan(views[0].right) - tan(views[0].left);
	double ty = tan(views[0].up) - tan(views[0].down);
	f.fov_x = 2 * atan(tx / overscan / 2);
	f.fov_y = 2 * atan(ty / overscan / 2);
	f.m = server->config.glasses.distance * tx / view_w;
	bool layered = draw_space_frame(server, gl, &f, picture_texture(server));
	if (dump_due()) {
		/* GL's rows run bottom up */
		cairo_surface_t *image = cairo_image_surface_create(
			CAIRO_FORMAT_ARGB32, f.width, f.height);
		unsigned char *data = cairo_image_surface_get_data(image);
		int stride = cairo_image_surface_get_stride(image);
		uint32_t *row = malloc((size_t)f.width * 4);
		for (int y = 0; y < f.height; y++) {
			glReadPixels(0, f.height - 1 - y, f.width, 1, GL_RGBA,
				GL_UNSIGNED_BYTE, row);
			uint32_t *out = (uint32_t *)(data + (size_t)y * stride);
			for (int x = 0; x < f.width; x++) {
				uint8_t *p = (uint8_t *)&row[x];
				out[x] = (uint32_t)p[3] << 24 | (uint32_t)p[0] << 16 |
					(uint32_t)p[1] << 8 | p[2];
			}
		}
		free(row);
		cairo_surface_mark_dirty(image);
		dump_image(image);
		cairo_surface_destroy(image);
	}
	return layered;
}

/* A mirror's frame: the picture as big as fits, centred */
static bool draw_flat(struct c8_output *output, struct wlr_buffer *buffer,
		struct wlr_texture *picture) {
	struct wlr_render_pass *pass = wlr_renderer_begin_buffer_pass(
		output->server->renderer, buffer, NULL);
	if (pass == NULL) {
		return false;
	}
	wlr_render_pass_add_rect(pass, &(struct wlr_render_rect_options){
		.box = { 0, 0, buffer->width, buffer->height },
		.color = { 0, 0, 0, 1 },
	});
	struct c8_server *server = output->server;
	if (picture && server->xr.picture_w > 0) {
		/* The source as big as fits, and the picture where it was on it */
		int pw = server->xr.picture_w, ph = server->xr.picture_h;
		double s = fmin((double)buffer->width / pw,
			(double)buffer->height / ph);
		double ox = (buffer->width - pw * s) / 2;
		double oy = (buffer->height - ph * s) / 2;
		struct wlr_box *d = &server->xr.picture_dst;
		int x0 = (int)lround(ox + d->x * s), y0 = (int)lround(oy + d->y * s);
		wlr_render_pass_add_texture(pass, &(struct wlr_render_texture_options){
			.texture = picture,
			.src_box = server->xr.picture_src,
			.dst_box = { x0, y0,
				(int)lround(ox + (d->x + d->width) * s) - x0,
				(int)lround(oy + (d->y + d->height) * s) - y0 },
			.filter_mode = WLR_SCALE_FILTER_BILINEAR,
		});
	}
	return wlr_render_pass_submit(pass);
}

/* For testing headless, where nothing can read a display that isn't in
 * the layout: C8_XR_DUMP=FILE.png gets the glasses' frames, one a second
 * or every C8_XR_DUMP_MS; a %d in FILE numbers them (to see an animation) */
static bool dump_due(void) {
	static int64_t last;
	const char *path = getenv("C8_XR_DUMP");
	const char *every = getenv("C8_XR_DUMP_MS");
	int64_t now = c8_now_ms();
	if (path == NULL || !*path ||
			now - last < (every ? atoi(every) : 1000)) {
		return false;
	}
	last = now;
	return true;
}

static void dump_image(cairo_surface_t *image) {
	static int n;
	const char *path = getenv("C8_XR_DUMP");
	char name[PATH_MAX];
	if (strstr(path, "%d")) {
		snprintf(name, sizeof(name), "%s", path);
		char *at = strstr(name, "%d");
		snprintf(at, sizeof(name) - (size_t)(at - name), "%05d%s", n++,
			strstr(path, "%d") + 2);
		path = name;
	}
	/* Written aside and renamed, so a reader never gets half */
	char tmp[PATH_MAX + 8]; // room for .part
	snprintf(tmp, sizeof(tmp), "%s.part", path);
	if (cairo_surface_write_to_png(image, tmp) == CAIRO_STATUS_SUCCESS) {
		rename(tmp, path);
	}
}

static void dump(struct c8_server *server, struct wlr_buffer *buffer) {
	if (!dump_due()) {
		return;
	}
	cairo_surface_t *image = c8_buffer_read(server, buffer, 0, 0);
	if (image) {
		dump_image(image);
		cairo_surface_destroy(image);
	}
}

void c8_xr_sink_frame(struct c8_output *output) {
	struct c8_server *server = output->server;
	struct wlr_output *wo = output->wlr_output;
	/* The glasses draw every frame: the head moves, and windows only get
	 * their frame callbacks from here */
	bool live = output->role == C8_OUTPUT_GLASSES;
	if (!wo->enabled || (!output->sink_dirty && !live) || output->leasing) {
		return; // no commit: frames stop until there's something new
	}
	if (output->role == C8_OUTPUT_VIEW && (server->xr.view_streaming ||
			(wo->attach_render_locks > 0 &&
			c8_xr_runtime_share(server, 'S')))) {
		/* A capture waits: Monado's frames, games and all, are its
		 * pictures (c8_xr_share_frame). Ours draw only what we do */
		if (!server->xr.view_streaming) {
			wlr_log(WLR_INFO, "XR: sharing what the glasses show, "
				"from Monado");
			server->xr.view_streaming = true;
			server->xr.view_unwanted = 0;
		}
		return;
	}
	output->sink_dirty = false;
	int64_t started = c8_now_ns();
	if (live) {
		/* The head's motion since the last frame, before its poses */
		c8_tracker_update(server->xr.tracker);
	}
	int64_t sensed = c8_now_ns();
	if (live && wo->global == NULL) {
		/* Out of the layout the glasses have no wl_output, and then
		 * nothing can capture them (OBS, through the portal, would get
		 * only XR-1: the shell's screen without the windows). With one,
		 * wlroots' output capture copies these frames, what the
		 * glasses show. Made here, after XR-1's, because portal-wlr
		 * without a picker shares the newest screen. */
		output->capture_global = true; // before: making it announces it
		wlr_output_create_global(wo, server->display);
	}

	struct wlr_output_state state;
	wlr_output_state_init(&state);
	if (!wlr_output_configure_primary_swapchain(wo, &state, &wo->swapchain)) {
		wlr_output_state_finish(&state);
		return;
	}
	struct wlr_buffer *buffer = wlr_swapchain_acquire(wo->swapchain);
	if (buffer == NULL) {
		wlr_output_state_finish(&state);
		return;
	}
	struct wlr_texture *picture = picture_texture(server);
	bool ok = output->role == C8_OUTPUT_GLASSES ||
			output->role == C8_OUTPUT_VIEW ?
		draw_space(output, buffer, picture) :
		draw_flat(output, buffer, picture);
	if (ok) {
		dump(server, buffer);
		wlr_output_state_set_buffer(&state, buffer);
		if (!wlr_output_commit_state(wo, &state)) {
			/* Busy (a flip still pending): no frame event follows a
			 * refusal, so ask for one or tracking would freeze */
			wlr_log(WLR_DEBUG, "Display %s: frame refused", wo->name);
			output->sink_dirty = true;
			wlr_output_schedule_frame(wo);
		}
	}
	wlr_buffer_unlock(buffer);
	wlr_output_state_finish(&state);
	if (live) {
		pace_frame(output, started, sensed);
	}
}

/* A screenshot in XR: what the glasses show (the left eye's
 * half in 3D), drawn once more into a buffer of their swapchain */
cairo_surface_t *c8_xr_screenshot(struct c8_server *server) {
	struct c8_output *output, *glasses = NULL;
	wl_list_for_each(output, &server->outputs, link) {
		if (output->role == C8_OUTPUT_GLASSES && output->wlr_output->enabled) {
			glasses = output;
			break;
		}
	}
	/* Leased, the glasses have no output: the view times it */
	bool own = glasses == NULL || glasses->leasing;
	if (glasses == NULL) {
		glasses = server->xr.view;
	}
	if (glasses == NULL) {
		return NULL;
	}
	struct wlr_output *wo = glasses->wlr_output;
	struct wlr_buffer *buffer = NULL;
	if (own) {
		/* Monado has them: their swapchain is nobody's, and drawing in
		 * it gave blank pictures (2026-12-02). One eye, in our own */
		int w = wo->width > 0 ? wo->width : 1920;
		int h = wo->height > 0 ? wo->height : 1080;
		if (w * 9 > h * 16 * 3 / 2) {
			w /= 2;
		}
		buffer = c8_capture_buffer(server, w, h);
	} else {
		struct wlr_output_state state;
		wlr_output_state_init(&state);
		bool have = wlr_output_configure_primary_swapchain(wo, &state,
			&wo->swapchain);
		wlr_output_state_finish(&state);
		buffer = have ? wlr_swapchain_acquire(wo->swapchain) : NULL;
	}
	if (buffer == NULL) {
		return NULL;
	}
	struct wlr_texture *picture = picture_texture(server);
	bool ok = draw_space(glasses, buffer, picture);
	int w = buffer->width, h = buffer->height;
	if (w * 9 > h * 16 * 3 / 2) {
		w /= 2; // side by side
	}
	cairo_surface_t *image = ok ? c8_buffer_read(server, buffer, w, h) : NULL;
	if (own) {
		wlr_buffer_drop(buffer); // ours alone
	} else {
		wlr_buffer_unlock(buffer); // back to the swapchain
	}
	return image;
}
