feat: Cardboard VR mode with ARM64 SteamVR (#704)

* feat: add Cardboard mode with side-by-side lens-distorted eyes and 3DoF head tracking

* fix: derive the Cardboard field of view from the panel and recentre fully when far from upright

* feat: share the Cardboard head pose with the guest and add a SteamVR driver for it

* feat: run SteamVR's compositor on Turnip/KGSL with a display-extension layer and a driver-direct HMD

* feat: show SteamVR frames in Cardboard mode through a driver-side presenter and a fake direct-mode display

* feat: install and start SteamVR for Cardboard mode from the session drawer

* docs: describe Cardboard mode and the SteamVR path

* feat: drive SteamVR hands from the game pad and keep the Cardboard headset out of standby

* docs: record where the SteamVR dashboard stops

* fix: map Cardboard head tracking to the screen's axes and keep turns about the real vertical as yaw

* fix: give Cardboard its previous picture back when SteamVR stops

* fix: report sem_otime from emulated SysV semaphores so SteamVR's web helper can start

* fix: bridge SteamVR's shared semaphores across processes and keep Steam alive while SteamVR runs

* feat: present SteamVR straight to DroidDeck's compositor at panel resolution

* docs: update Cardboard VR notes for the dashboard, semaphore bridge and direct presenter

* fix: keep Wine and FEX signal handlers in the VR layer; add semaphore tracing

* fix: clear a stale SteamVR active marker on status

* fix: clear only an old SteamVR active marker

* fix: unblock SteamVR clients on Turnip and keep Steam's web helper alive across SteamVR runs

* fix: judge shared waits before a submit's own signals and on Vulkan 1.0 devices

* docs: record VR games, SteamVR Home and OpenXR results on the Thor

* docs: add Cardboard VR learnings from the Thor bring-up

* docs: add Cardboard VR screenshots from the Thor

* fix: keep the VR layer's display stand-in to SteamVR runs and clear a leftover marker at session start

* fix: report SteamVR start and stop failures from the helper's exit code
This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-10-13 14:36:56 +00:00
1 parent 92d038b428
commit f4b0ab6867
57 files changed
+17799 -15

No files matched your search

+3
View File
@@ -131,6 +131,9 @@ docker run --rm --platform linux/amd64 \
chown -R '"$(id -u):$(id -g)"' app/src/main/assets/linuxfs
'
# Cardboard mode's SteamVR driver and Vulkan layer (tools/vr, docs/cardboard-vr.md).
DROIDDECK_BUILD_IMAGE="${image_name}" "${repo_root}/tools/vr/build.sh" "${linuxfs_dir}/usr/local/lib/droiddeck-vr"
github_repo=${DROIDDECK_GITHUB_REPOSITORY:-}
if [[ -z "${github_repo}" ]]; then
origin_url=$(git -C "${repo_root}" remote get-url origin)
+51
View File
@@ -0,0 +1,51 @@
/* Host test for the cardboard pass's pure helpers (waylandcomp/src/cardboard.c, built with
* CARDBOARD_HOST_TEST): clamping and the push-constant layout cardboard.frag reads. */
#include "cardboard.h"
#include <math.h>
#include <stdio.h>
static int failures;
#define CHECK(c) do { if (!(c)) { printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); failures++; } } while (0)
static int near(float a, float b) { return fabsf(a - b) < 1e-4f; }
int main(void) {
struct cardboard_params p = {.enabled = 7, .source = 9, .ipd_m = 1.0f, .screen_dist_m = 0.0f,
.screen_width_m = 100.0f, .k1 = 5.0f, .k2 = -5.0f, .fov_deg = 500.0f,
.lens_inset = 1.0f, .chroma = -1.0f};
cardboard_clamp(&p);
CHECK(p.enabled == 1);
CHECK(p.source == CARDBOARD_SOURCE_SCREEN);
CHECK(near(p.ipd_m, 0.1f));
CHECK(near(p.screen_dist_m, 0.5f));
CHECK(near(p.screen_width_m, 60.0f));
CHECK(near(p.k1, 2.0f) && near(p.k2, -1.0f));
CHECK(near(p.fov_deg, 140.0f));
CHECK(near(p.lens_inset, 0.25f) && near(p.chroma, 0.0f));
struct cardboard_params q = {.enabled = 1, .source = CARDBOARD_SOURCE_SCREEN, .ipd_m = 0.064f, .screen_dist_m = 3.0f,
.screen_width_m = 4.0f, .k1 = 0.34f, .k2 = 0.55f, .fov_deg = 90.0f,
.lens_inset = 0.05f, .chroma = 0.006f};
const float pose[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
float pc[24];
cardboard_push_constants(&q, pose, 1920, 1080, 2400, 1080, pc);
/* rot rows with the scalars in w */
CHECK(near(pc[0], 1) && near(pc[1], 2) && near(pc[2], 3) && near(pc[3], 0.032f));
CHECK(near(pc[4], 4) && near(pc[5], 5) && near(pc[6], 6) && near(pc[7], 3.0f));
CHECK(near(pc[8], 7) && near(pc[9], 8) && near(pc[10], 9) && near(pc[11], 2.0f));
/* lens: k1, k2, tan(fov/2), chroma */
CHECK(near(pc[12], 0.34f) && near(pc[13], 0.55f) && near(pc[14], 1.0f) && near(pc[15], 0.006f));
/* view: inset, source aspect, mode, eye viewport aspect (half the panel) */
CHECK(near(pc[16], 0.05f) && near(pc[17], 1920.0f / 1080.0f) && near(pc[18], 0.0f) && near(pc[19], 1200.0f / 1080.0f));
/* A side-by-side source: each eye's aspect is half the frame's. */
q.source = CARDBOARD_SOURCE_SBS;
cardboard_push_constants(&q, pose, 3840, 1080, 2400, 1080, pc);
CHECK(near(pc[17], 1920.0f / 1080.0f) && near(pc[18], 1.0f));
/* Unknown sizes fall back instead of dividing by zero. */
cardboard_push_constants(&q, pose, 0, 0, 0, 0, pc);
CHECK(isfinite(pc[17]) && isfinite(pc[19]));
if (failures) return 1;
printf("PASS: cardboard params\n");
return 0;
}
@@ -540,6 +540,38 @@ def quit_game(agent_dir, app_id, timeout):
# --- Requests ------------------------------------------------------------------------------------
VR_HELPER = "/usr/local/bin/droiddeck-steamvr"
VR_ACTIONS = ("status", "install", "start", "stop")
def steamvr(req):
"""Cardboard mode's SteamVR: a fixed helper with four actions, unlike exec (no command line from
the request). install downloads 571 MB, so it runs detached and status reports it."""
action = req.get("action", "status")
if action not in VR_ACTIONS:
raise AgentError("INVALID_REQUEST", "vr action must be one of " + ", ".join(VR_ACTIONS))
helper = os.environ.get("DROIDDECK_VR_HELPER", VR_HELPER)
if not os.path.isfile(helper):
raise AgentError("UNAVAILABLE", "this runtime has no " + helper)
if action == "install":
state = Path(os.environ.get("XDG_RUNTIME_DIR", "/tmp")) / "droiddeck-steamvr"
state.mkdir(parents=True, exist_ok=True)
with open(state / "install.log", "ab") as log_file:
subprocess.Popen(["sh", helper, "install"], stdin=subprocess.DEVNULL, stdout=log_file,
stderr=subprocess.STDOUT, start_new_session=True)
return {"action": action, "started": True}
done = subprocess.run(["sh", helper, action], stdin=subprocess.DEVNULL, capture_output=True,
timeout=request_timeout(req, 30))
out = done.stdout.decode("utf-8", "replace").strip()
result = {"action": action, "exitCode": done.returncode, "output": out[-2000:]}
if action == "status":
for part in out.split():
key, _, value = part.partition("=")
if key in ("installed", "running", "installing", "driver"):
result[key] = value == "1"
return result
def run_exec(req):
argv = req.get("argv")
if not isinstance(argv, list) or not argv or not all(isinstance(a, str) and "\0" not in a for a in argv):
@@ -656,6 +688,8 @@ def handle(agent_dir, req):
return steam_selection(agent_dir, request_timeout(req, 5))
if kind == "quit":
return quit_game(agent_dir, req.get("appId"), request_timeout(req, 15))
if kind == "vr":
return steamvr(req)
raise AgentError("UNKNOWN_REQUEST", "Unknown agent request '%s'" % kind)
@@ -165,6 +165,9 @@ export XDG_DATA_HOME=${XDG_DATA_HOME:-$HOME/.local/share}
export XDG_CONFIG_HOME=${XDG_CONFIG_HOME:-$HOME/.config}
export XDG_CACHE_HOME=${XDG_CACHE_HOME:-$HOME/.cache}
mkdir -p "$XDG_DATA_HOME" "$XDG_CONFIG_HOME" "$XDG_CACHE_HOME"
# No SteamVR runs at session start. A marker left by a session that died with SteamVR up would put
# the Cardboard VR layer's display stand-in into this one (docs/cardboard-vr.md).
rm -f "${XDG_RUNTIME_DIR:-/run/droiddeck}/droiddeck-steamvr/active"
if [ "$mode" = lxqt ] || [ "$mode" = desktop ]; then
/usr/local/bin/droiddeck-desktop-bookmarks || true
fi
@@ -0,0 +1,117 @@
#!/bin/sh
# SteamVR for Cardboard mode (docs/cardboard-vr.md). Experimental.
#
# droiddeck-steamvr status one line: installed=0|1 running=0|1 installing=0|1 driver=0|1
# droiddeck-steamvr install fetch Valve's ARM64 SteamVR (the Steam Frame's package) into /opt/steamvr
# droiddeck-steamvr start start SteamVR with the DroidDeck Cardboard driver
# droiddeck-steamvr stop stop it
#
# SteamVR renders through the driver (tools/vr/src/driver_droiddeck.cpp) into an overlay window that
# gamescope shows over everything; the app's Cardboard pass, with a side-by-side source, puts the lens
# on it. vrcompositor needs the Vulkan layer (tools/vr/src/vk_layer_droiddeck_vr.c) on Turnip/KGSL.
set -u
steamvr=${STEAMVR:-/opt/steamvr}
vrdir=${DROIDDECK_VR_DIR:-/usr/local/lib/droiddeck-vr}
driver=$vrdir/droiddeck
layer=$vrdir/layer
logs=$HOME/.local/share/Steam/logs
state=${XDG_RUNTIME_DIR:-/tmp}/droiddeck-steamvr
mkdir -p "$state"
# The Steam Frame's SteamVR, from Valve's package server; the same build the Frame's SteamOS ships.
PKG_URL=https://steamdeck-packages.steamos.cloud/archlinux-deckard-hotfixes/release/0.3.x/deckard-steamvr-rel-r25358740%2B28b72a4f-1-aarch64.pkg.tar.zst
PKG_SHA256=90a600775eb3e8856dc475f83166a93a290a0b1f3b4e82a69c8e2a8f06b9ddc9
running() { pgrep -x vrserver >/dev/null 2>&1; }
installed() { [ -x "$steamvr/bin/linuxarm64/vrstartup" ]; }
stop() {
rm -f "$state/active"
for n in vrcompositor vrserver vrmonitor vrdashboard vrstartup vrwebhelper; do
for p in $(pgrep -x "$n"); do kill "$p" 2>/dev/null; done
done
# pgrep -x matches 15 characters of the name at most.
for p in $(pgrep -f "$steamvr/bin/linuxarm64/vrcompositor-launcher"); do kill "$p" 2>/dev/null; done
# A process that exited on its own meanwhile is not a failure: the app reads this exit code.
return 0
}
case "${1:-status}" in
status)
i=0; installed && i=1
r=0; running && r=1
# A session that died with SteamVR up leaves the marker behind; it would keep the layer active.
# Only an old one: vrserver takes a while to appear after start, and Steam's web helper needs the
# marker from the start.
if [ "$r" = 0 ] && [ -n "$(find "$state/active" -mmin +2 2>/dev/null)" ]; then rm -f "$state/active"; fi
n=0; [ -f "$state/installing" ] && n=1
d=0; [ -f "$driver/bin/linuxarm64/driver_droiddeck.so" ] && [ -f "$layer/libVkLayer_droiddeck_vr.so" ] && d=1
echo "installed=$i running=$r installing=$n driver=$d"
;;
install)
installed && { echo "SteamVR is already in $steamvr"; exit 0; }
[ -f "$state/installing" ] && { echo "already installing"; exit 0; }
: > "$state/installing"
trap 'rm -f "$state/installing"' EXIT
cache=$HOME/.cache/droiddeck-vr
mkdir -p "$cache"
pkg=$cache/steamvr.pkg.tar.zst
echo "downloading SteamVR (571 MB) from Valve's package server"
curl -fsSL --retry 5 -C - -o "$pkg" "$PKG_URL" || { echo "download failed"; exit 1; }
echo "$PKG_SHA256 $pkg" | sha256sum -c - >/dev/null 2>&1 || { echo "checksum mismatch: removing the download"; rm -f "$pkg"; exit 1; }
tmp=$cache/extract
rm -rf "$tmp" && mkdir -p "$tmp"
zstd -dc "$pkg" | tar -x -C "$tmp" opt/steamvr || { echo "extract failed"; rm -rf "$tmp"; exit 1; }
mkdir -p "$(dirname "$steamvr")"
rm -rf "$steamvr" && mv "$tmp/opt/steamvr" "$steamvr" && rm -rf "$tmp" "$pkg"
echo "SteamVR installed in $steamvr"
;;
stop)
stop
;;
start)
installed || { echo "SteamVR is not installed (droiddeck-steamvr install)"; exit 1; }
[ -f "$driver/bin/linuxarm64/driver_droiddeck.so" ] || { echo "the Cardboard driver is missing from $driver"; exit 1; }
stop
sleep 1
mkdir -p "$HOME/.config/openvr" "$HOME/.config/openxr/1" "$logs" "$HOME/.local/share/Steam/config"
cat > "$HOME/.config/openvr/openvrpaths.vrpath" <<JSON
{
"config": ["$HOME/.local/share/Steam/config"],
"external_drivers": ["$driver"],
"jsonid": "vrpathreg",
"log": ["$logs"],
"runtime": ["$steamvr"],
"version": 1
}
JSON
ln -sf "$steamvr/steamxr_linuxarm64.json" "$HOME/.config/openxr/1/active_runtime.json"
# vrcompositor asks for VK_KHR_display, which makes Turnip/KGSL report no GPU at all; the layer stands
# in for a display. gamescope's implicit WSI layer stays out of SteamVR's processes.
export VK_LAYER_PATH="$layer${VK_LAYER_PATH:+:$VK_LAYER_PATH}"
export VK_INSTANCE_LAYERS="VK_LAYER_DROIDDECK_vr${VK_INSTANCE_LAYERS:+:$VK_INSTANCE_LAYERS}"
export VK_LOADER_LAYERS_DISABLE="${VK_LOADER_LAYERS_DISABLE:-~implicit~}"
# SteamVR's web helper (the dashboard) checks the X server with xset, which the runtime lacks.
shims=$state/shims
mkdir -p "$shims"
if ! command -v xset >/dev/null 2>&1; then
printf '#!/bin/sh\n# xset stand-in for vrwebhelper.sh: "q" only checks the display answers.\nexec xprop -root -display "${DISPLAY:-:0}" _NET_SUPPORTED >/dev/null 2>&1\n' > "$shims/xset"
chmod +x "$shims/xset"
export PATH="$shims:$PATH"
fi
# While this file exists, the layer is active in every Vulkan instance of the session, not only
# SteamVR's: Steam's web helper shares its in-VR overlay with SteamVR and needs it too.
: > "$state/active"
cd "$steamvr/bin/linuxarm64" || exit 1
setsid ./vrstartup > "$state/vrstartup.log" 2>&1 < /dev/null &
echo "SteamVR starting; logs in $logs and $state/vrstartup.log"
;;
*)
echo "usage: droiddeck-steamvr status|install|start|stop" >&2
exit 2
;;
esac
+15 -3
View File
@@ -43,8 +43,14 @@ struct sem_header {
uint32_t key;
uint32_t mode;
int32_t creator_pid;
int32_t pad[11];
/* What IPC_STAT reports as sem_otime / sem_ctime (seconds). The usual race-free init has the
* creator semop the new set once, and every other process wait until sem_otime is non-zero;
* SteamVR's web helper spins on exactly that. */
_Atomic uint32_t otime;
_Atomic uint32_t ctime;
int32_t pad[9];
};
_Static_assert(sizeof(struct sem_header) == 64, "semaphore files written by older sessions keep their layout");
/* The counters follow the header, one 32-bit word each (a futex word). */
struct sem_map { int id; struct sem_header *hdr; size_t len; };
@@ -176,7 +182,8 @@ int semget(key_t key, int nsems, int semflg) {
size_t len = sizeof(struct sem_header) + (size_t)nsems * sizeof(int32_t);
if (ftruncate(fd, (off_t)len) != 0) { close(fd); return -1; }
struct sem_header h = {.magic = SEM_MAGIC, .nsems = (uint32_t)nsems, .key = (uint32_t)key,
.mode = (uint32_t)(semflg & 0777), .creator_pid = (int32_t)getpid()};
.mode = (uint32_t)(semflg & 0777), .creator_pid = (int32_t)getpid(),
.ctime = (uint32_t)time(NULL)};
if (pwrite(fd, &h, sizeof(h), 0) != (ssize_t)sizeof(h)) { close(fd); return -1; }
} else {
struct sem_header h;
@@ -222,6 +229,7 @@ int semtimedop(int semid, struct sembuf *sops, size_t nsops, const struct timesp
}
if (sops[i].sem_op < 0) futex(w, FUTEX_WAKE, INT_MAX, NULL); /* zero-waiters see the change */
}
atomic_store(&h->otime, (uint32_t)time(NULL));
return 0;
}
@@ -256,6 +264,7 @@ int semctl(int semid, int semnum, int cmd, ...) {
if (semnum < 0 || (uint32_t)semnum >= h->nsems) { errno = EINVAL; return -1; }
atomic_store(&words[semnum], (int32_t)(intptr_t)arg.buf);
futex(&words[semnum], FUTEX_WAKE, INT_MAX, NULL);
atomic_store(&h->ctime, (uint32_t)time(NULL));
return 0;
case GETALL:
for (uint32_t i = 0; i < h->nsems; i++) arg.array[i] = (unsigned short)atomic_load(&words[i]);
@@ -265,6 +274,7 @@ int semctl(int semid, int semnum, int cmd, ...) {
atomic_store(&words[i], arg.array[i]);
futex(&words[i], FUTEX_WAKE, INT_MAX, NULL);
}
atomic_store(&h->ctime, (uint32_t)time(NULL));
return 0;
case GETPID: return h->creator_pid;
case GETNCNT: case GETZCNT: return 0;
@@ -275,8 +285,10 @@ int semctl(int semid, int semnum, int cmd, ...) {
arg.buf->sem_perm.gid = arg.buf->sem_perm.cgid = getgid();
arg.buf->sem_perm.mode = (unsigned short)h->mode;
arg.buf->sem_nsems = h->nsems;
arg.buf->sem_otime = (time_t)atomic_load(&h->otime);
arg.buf->sem_ctime = (time_t)atomic_load(&h->ctime);
return 0;
case IPC_SET: return 0;
case IPC_SET: atomic_store(&h->ctime, (uint32_t)time(NULL)); return 0;
default: errno = EINVAL; return -1;
}
}
+4 -2
View File
@@ -47,9 +47,11 @@ static int is_status_path(const char *path) {
}
/* Chromium stands its hang watchdogs down when it sees a tracer, and the client's web helper does
* not come up within their patience here: it is left reading the truth. */
* not come up within their patience here: it is left reading the truth. SteamVR's web helper (the
* dashboard, Cardboard mode's SteamVR) is the same Chromium and stalls the same way. */
static int is_web_helper(void) {
return strcmp(program_invocation_short_name, "steamwebhelper") == 0;
return strcmp(program_invocation_short_name, "steamwebhelper") == 0 ||
strcmp(program_invocation_short_name, "vrwebhelper") == 0;
}
static int write_all(int fd, const char *data, size_t len) {
+6 -1
View File
@@ -17,7 +17,8 @@ SOURCE_PATHS = ['app/build.gradle', 'app/src/main/cpp/fakeinput_steam.cpp', 'app
'tools/gamescope/release.env', 'tools/droiddeck-esync/release.env',
'tools/mangoapp', 'tools/msitools', 'tools/comet', 'tools/build_local.sh',
'tools/release/runtime_inputs.py', 'app/src/main/assets/desktop-removal',
'tools/quest', 'app/src/main/cpp/adrenotools/src/hook/kgsl.h',
'tools/quest', 'tools/vr/src', 'tools/vr/driver_droiddeck', 'tools/vr/layer', 'tools/vr/build.sh',
'app/src/main/cpp/adrenotools/src/hook/kgsl.h',
'app/src/main/assets/graphics_driver/adrenotools-turnip25.1.0.tzst']
@@ -67,6 +68,10 @@ def required():
paths += ['assets/linuxfs/i386/libfaultreport.so']
paths += ['assets/linuxfs/usr/local/lib/droiddeck-msitools/' + name for name in
['msiinfo', 'cabextract', '7z', '7z.so', 'libmsi-1.0.so.0', 'libgsf-1.so.114', 'libgcab-1.0.so.0']]
paths += ['assets/linuxfs/usr/local/lib/droiddeck-vr/' + name for name in
['droiddeck/bin/linuxarm64/driver_droiddeck.so', 'droiddeck/driver.vrdrivermanifest',
'droiddeck/resources/settings/default.vrsettings', 'layer/libVkLayer_droiddeck_vr.so',
'layer/VK_LAYER_DROIDDECK_vr.json', 'layer/VK_LAYER_DROIDDECK_vr_implicit.json']]
paths += ['assets/linuxfs/usr/local/lib/mangoapp/' + name for name in
['mangoapp', 'libfmt.so.10', 'libspdlog.so.1.13', 'libglfw.so.3', 'libtraceevent.so.1', 'libtracefs.so.1']]
paths += ['assets/linuxfs/usr/local/lib/droiddeck-comet/' + name for name in
+28
View File
@@ -0,0 +1,28 @@
/* Host test for sysv.c: IPC_STAT's sem_otime turns non-zero with the first semop, which the usual
* race-free init (and SteamVR's web helper) waits for. Linked with sysv.c, whose semget/semop/semctl
* replace libc's. */
#define _GNU_SOURCE
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/sem.h>
int main(void) {
int creator = semget(0x5eed0001, 1, IPC_CREAT | IPC_EXCL | 0600);
if (creator < 0) { perror("semget"); return 1; }
struct semid_ds ds;
if (semctl(creator, 0, IPC_STAT, &ds) != 0 || ds.sem_otime != 0 || ds.sem_ctime == 0) {
printf("FAIL: a new set has otime %ld ctime %ld\n", (long)ds.sem_otime, (long)ds.sem_ctime);
return 1;
}
struct sembuf up = {0, 1, 0};
if (semop(creator, &up, 1) != 0) { perror("semop"); return 1; }
int other = semget(0x5eed0001, 1, 0600);
if (other < 0 || semctl(other, 0, IPC_STAT, &ds) != 0 || ds.sem_otime == 0) {
printf("FAIL: otime still 0 after semop\n");
return 1;
}
if (semctl(other, 0, GETVAL) != 1) { printf("FAIL: value\n"); return 1; }
semctl(creator, 0, IPC_RMID);
printf("PASS: sysv otime\n");
return 0;
}
+60
View File
@@ -0,0 +1,60 @@
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
SRC = ROOT / 'app' / 'src' / 'main' / 'cpp' / 'waylandcomp' / 'src'
TOOLS = ROOT / 'tools' / 'cardboard'
def spirv_words(header: str) -> list[str]:
return re.findall(r'0x[0-9a-fA-F]{8}', header)
@unittest.skipUnless(shutil.which('cc'), 'needs a C compiler')
class CardboardParamsTest(unittest.TestCase):
def test_clamp_and_push_constant_layout(self):
with tempfile.TemporaryDirectory() as folder:
binary = str(Path(folder) / 'test-cardboard')
subprocess.run(['cc', '-std=c11', '-Wall', '-Wextra', '-Werror', '-O2', '-DCARDBOARD_HOST_TEST',
'-D_DEFAULT_SOURCE', f'-I{SRC}', f'-I{Path(folder)}', '-o', binary,
str(TOOLS / 'test_cardboard_params.c'), str(SRC / 'cardboard.c'), '-lm'],
check=True, cwd=folder, env=self._env(folder))
result = subprocess.run([binary], capture_output=True, text=True, check=True, timeout=10)
self.assertIn('PASS: cardboard params', result.stdout)
@staticmethod
def _env(folder):
# cardboard.h includes <vulkan/vulkan.h>; the host test only needs the types, so a stub
# header stands in when the Vulkan SDK is not installed.
import os
stub = Path(folder) / 'vulkan'
stub.mkdir(exist_ok=True)
(stub / 'vulkan.h').write_text('typedef struct VkDevice_T *VkDevice; typedef struct VkImage_T *VkImage;\n'
'typedef struct VkCommandBuffer_T *VkCommandBuffer;\n'
'typedef struct { int unused; } VkPhysicalDeviceMemoryProperties;\n')
return dict(os.environ)
@unittest.skipUnless(shutil.which('glslangValidator'), 'needs glslangValidator')
class CardboardShaderTest(unittest.TestCase):
def test_committed_spirv_matches_the_glsl(self):
with tempfile.TemporaryDirectory() as folder:
out = Path(folder) / 'cardboard_frag.h'
subprocess.run(['glslangValidator', '-V', '--vn', 'cardboard_frag_code', '-o', str(out),
str(SRC / 'cardboard.frag')], check=True, capture_output=True)
self.assertEqual(spirv_words(out.read_text()), spirv_words((SRC / 'cardboard_frag.h').read_text()),
'cardboard_frag.h is stale: regenerate it from cardboard.frag (see cardboard.c)')
def test_push_constants_fit_the_guaranteed_range(self):
# 7 vec4 = 112 bytes in the shader; Vulkan guarantees 128.
glsl = (SRC / 'cardboard.frag').read_text()
block = glsl[glsl.index('uniform PC {'):glsl.index('} pc;')]
self.assertLessEqual(16 * len(re.findall(r'\bvec4\b', block)), 128)
if __name__ == '__main__':
unittest.main()
+31
View File
@@ -91,6 +91,37 @@ class AgentTest(unittest.TestCase):
self.assertFalse(path.exists(), "the request file is consumed")
return json.loads((self.dir / "resp" / "req.json").read_text())
def vr_helper(self, body):
helper = self.dir / "droiddeck-steamvr"
helper.write_text("#!/bin/sh\n" + body)
old = os.environ.get("DROIDDECK_VR_HELPER")
os.environ["DROIDDECK_VR_HELPER"] = str(helper)
self.addCleanup(lambda: os.environ.pop("DROIDDECK_VR_HELPER") if old is None
else os.environ.__setitem__("DROIDDECK_VR_HELPER", old))
return helper
def test_vr_status_is_parsed(self):
self.vr_helper('echo "installed=1 running=0 installing=0 driver=1"\n')
answer = self.ask({"kind": "vr", "action": "status"})
self.assertTrue(answer["ok"])
self.assertEqual((True, False, False, True),
(answer["installed"], answer["running"], answer["installing"], answer["driver"]))
def test_vr_runs_only_its_own_actions(self):
log = self.dir / "args"
self.vr_helper('echo "$@" > %s\n' % log)
self.assertTrue(self.ask({"kind": "vr", "action": "start"})["ok"])
self.assertEqual("start", log.read_text().strip())
answer = self.ask({"kind": "vr", "action": "rm -rf /"})
self.assertFalse(answer["ok"])
self.assertEqual("INVALID_REQUEST", answer["error"]["code"])
def test_vr_without_a_helper_is_unavailable(self):
os.environ["DROIDDECK_VR_HELPER"] = str(self.dir / "missing")
self.addCleanup(os.environ.pop, "DROIDDECK_VR_HELPER")
answer = self.ask({"kind": "vr", "action": "status"})
self.assertEqual("UNAVAILABLE", answer["error"]["code"])
def test_exec_output_and_status(self):
answer = self.ask({"kind": "exec", "argv": ["sh", "-c", "echo out; echo err >&2; exit 3"], "env": {"X": "1"}})
self.assertTrue(answer["ok"])
+25
View File
@@ -0,0 +1,25 @@
from pathlib import Path
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
PRELOAD = Path(__file__).resolve().parents[1] / 'linuxfs' / 'preload'
@unittest.skipUnless(sys.platform == 'linux' and shutil.which('gcc'), 'needs Linux and gcc')
class SysvPreloadTest(unittest.TestCase):
def test_semop_sets_otime_for_waiters(self):
with tempfile.TemporaryDirectory() as folder:
binary = str(Path(folder) / 'test-sysv')
subprocess.run(['gcc', '-Wall', '-Wextra', '-O2', '-pthread', '-o', binary,
str(Path(__file__).resolve().parent / 'sysv_otime_harness.c'), str(PRELOAD / 'sysv.c')], check=True)
env = dict(os.environ, BL_SYSV_DIR=folder)
result = subprocess.run([binary], capture_output=True, text=True, timeout=10, env=env)
self.assertIn('PASS: sysv otime', result.stdout, result.stdout + result.stderr)
if __name__ == '__main__':
unittest.main()
+72
View File
@@ -0,0 +1,72 @@
#!/usr/bin/env bash
# Builds Cardboard mode's SteamVR pieces for the guest (glibc aarch64):
# <out>/droiddeck the SteamVR driver: driver_droiddeck.so, its manifest and default settings
# <out>/layer VK_LAYER_DROIDDECK_vr, the Vulkan layer SteamVR's compositor needs on Turnip/KGSL
#
# tools/vr/build.sh [OUT] in the local cross image (default OUT: tools/vr/out)
# tools/vr/build.sh --native OUT with aarch64-linux-gnu-gcc/g++ on PATH (CI, or inside the image)
#
# Vulkan headers: VK_INCLUDE (a directory holding vulkan/), else the NDK's (ANDROID_NDK_HOME, the
# runner's latest NDK, or the newest under ANDROID_HOME). Only vulkan/ is copied out of it: the rest of
# the NDK sysroot is Android's libc, not the guest's.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
repo=$(cd "$here/../.." && pwd)
native=0
if [ "${1:-}" = --native ]; then native=1; shift; fi
out=${1:-$here/out}
case "$out" in /*) ;; *) out="$PWD/$out" ;; esac
vkinc=${VK_INCLUDE:-}
if [ -z "$vkinc" ]; then
for ndk in "${ANDROID_NDK_HOME:-}" "${ANDROID_NDK_LATEST_HOME:-}" \
$(ls -d "${ANDROID_HOME:-$HOME/Library/Android/sdk}"/ndk/* 2>/dev/null | sort -r); do
[ -n "$ndk" ] || continue
cand=$(ls -d "$ndk"/toolchains/llvm/prebuilt/*/sysroot/usr/include 2>/dev/null | head -1)
if [ -n "$cand" ] && [ -f "$cand/vulkan/vk_layer.h" ]; then vkinc=$cand; break; fi
done
fi
[ -n "$vkinc" ] && [ -f "$vkinc/vulkan/vulkan_core.h" ] || { echo "tools/vr/build.sh: no Vulkan headers (set VK_INCLUDE)" >&2; exit 1; }
# Everything the compilers read sits under the repo, so the cross image (which mounts only the repo)
# sees it too.
work="$repo/build/vr"
rm -rf "$work" && mkdir -p "$work/include"
cp -R "$vkinc/vulkan" "$work/include/"
if [ -d "$vkinc/vk_video" ]; then cp -R "$vkinc/vk_video" "$work/include/"; fi
mkdir -p "$work/out/droiddeck/bin/linuxarm64" "$work/out/layer"
compile() {
local cmd=(sh -c '
set -e
# libwayland-client: linked against a stub with its soname (the guest has the real one).
mkdir -p build/vr/stub
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wl,-soname,libwayland-client.so.0 -Itools/vr/third_party/wayland \
-o build/vr/stub/libwayland-client.so tools/vr/src/wayland_client_stub.c
aarch64-linux-gnu-gcc -c -fPIC -O2 -Itools/vr/third_party/wayland -o build/vr/xdg-shell-protocol.o \
app/src/main/cpp/waylandcomp/generated/xdg-shell-protocol.c
aarch64-linux-gnu-g++ -std=c++17 -shared -fPIC -O2 -Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers \
-fvisibility=hidden -static-libstdc++ -static-libgcc -pthread -Wl,-z,defs -Ibuild/vr/include \
-Itools/vr/third_party/wayland -Iapp/src/main/cpp/waylandcomp/generated \
-o build/vr/out/droiddeck/bin/linuxarm64/driver_droiddeck.so tools/vr/src/driver_droiddeck.cpp tools/vr/src/presenter.cpp \
build/vr/xdg-shell-protocol.o -Lbuild/vr/stub -lwayland-client -ldl
aarch64-linux-gnu-gcc -std=c11 -shared -fPIC -O2 -Wall -Wextra -Wno-unused-parameter -fvisibility=hidden -pthread \
-Wl,-z,defs -Ibuild/vr/include -o build/vr/out/layer/libVkLayer_droiddeck_vr.so tools/vr/src/vk_layer_droiddeck_vr.c -ldl
aarch64-linux-gnu-strip --strip-unneeded build/vr/out/droiddeck/bin/linuxarm64/driver_droiddeck.so \
build/vr/out/layer/libVkLayer_droiddeck_vr.so')
if [ "$native" = 1 ]; then
(cd "$repo" && "${cmd[@]}")
else
docker run --rm --platform linux/amd64 --user "$(id -u):$(id -g)" -v "$repo:/src" -w /src \
"${DROIDDECK_BUILD_IMAGE:-droiddeck-local-cross:24.04-v3}" "${cmd[@]}"
fi
}
compile
cp -R "$here/driver_droiddeck/." "$work/out/droiddeck/"
cp "$here/layer/VK_LAYER_DROIDDECK_vr.json" "$here/layer/VK_LAYER_DROIDDECK_vr_implicit.json" "$work/out/layer/"
rm -rf "$out/droiddeck" "$out/layer"
mkdir -p "$out"
cp -R "$work/out/droiddeck" "$work/out/layer" "$out/"
echo "built $out/droiddeck and $out/layer"
@@ -0,0 +1,7 @@
{
"alwaysActivate": true,
"name": "droiddeck",
"directory": "",
"resourceOnly": false,
"hmd_presence": ["*.*"]
}
@@ -0,0 +1,11 @@
{
"driver_droiddeck": {
"enable": true,
"windowWidth": 1920,
"windowHeight": 1080,
"displayFrequency": 60.0,
"virtualDisplay": false,
"directMode": true,
"gamepadControllers": true
}
}
+14
View File
@@ -0,0 +1,14 @@
{
"file_format_version": "1.2.0",
"layer": {
"name": "VK_LAYER_DROIDDECK_vr",
"type": "GLOBAL",
"library_path": "./libVkLayer_droiddeck_vr.so",
"api_version": "1.3.0",
"implementation_version": "1",
"description": "Lets SteamVR's compositor start on Turnip/KGSL: stands in for the display extensions",
"functions": {
"vkNegotiateLoaderLayerInterfaceVersion": "DroidDeckVr_NegotiateLoaderLayerInterfaceVersion"
}
}
}
@@ -0,0 +1,17 @@
{
"file_format_version": "1.2.0",
"layer": {
"name": "VK_LAYER_DROIDDECK_vr",
"type": "GLOBAL",
"library_path": "/usr/local/lib/droiddeck-vr/layer/libVkLayer_droiddeck_vr.so",
"api_version": "1.3.0",
"implementation_version": "1",
"description": "Cardboard SteamVR: shared-texture semaphores and a stand-in display on Turnip/KGSL; passes through unless SteamVR runs",
"functions": {
"vkNegotiateLoaderLayerInterfaceVersion": "DroidDeckVr_NegotiateLoaderLayerInterfaceVersion"
},
"disable_environment": {
"DROIDDECK_VR_LAYER_DISABLE": "1"
}
}
}
+27
View File
@@ -0,0 +1,27 @@
Copyright (c) 2015, Valve Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+666
View File
@@ -0,0 +1,666 @@
// SteamVR driver for DroidDeck's Cardboard mode: one 3DoF HMD whose pose is the phone's rotation
// sensor, read from the head pose file the app shares with the guest
// (app/src/main/cpp/waylandcomp/src/headpose_shm.h, /run/droiddeck/droiddeck-headpose).
//
// The HMD renders an undistorted side-by-side pair: the app's Cardboard pass, in its side-by-side
// mode, does the lens distortion for the viewer the user picked. So the projection here is exactly
// the frustum that pass samples (tan_half_fov, eye_aspect from the pose file), and the distortion is
// the identity.
//
// How the frames reach the screen is the open question this driver is for: see docs/cardboard-vr.md.
// It exposes IVRDisplayComponent with the display "on the desktop" (extended mode) at the session's
// size, and logs what vrserver / vrcompositor ask of it.
#include "openvr_driver.h"
#include <algorithm>
#include <string>
#include <atomic>
#include <cstdarg>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <fcntl.h>
#include <sys/mman.h>
#include <mutex>
#include <thread>
#include <vector>
#include <unistd.h>
#include "../../../app/src/main/cpp/waylandcomp/src/headpose_shm.h"
#include "presenter.h"
#define DD_EXPORT extern "C" __attribute__((visibility("default")))
using namespace vr;
namespace {
const char *const kSettingsSection = "driver_droiddeck";
const char *const kPosePath = "/run/droiddeck/" DROIDDECK_HEADPOSE_FILE;
void Log(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
void Log(const char *fmt, ...) {
char buf[1024];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
if (VRDriverLog()) VRDriverLog()->Log(buf);
fprintf(stderr, "[droiddeck] %s\n", buf);
}
// The shared pose file, mapped read-only; reads follow the seqlock in headpose_shm.h.
class PoseFile {
public:
bool Read(droiddeck_headpose *out) {
if (!map_ && !Open()) return false;
for (int tries = 0; tries < 8; tries++) {
uint32_t a = __atomic_load_n(&map_->seq, __ATOMIC_ACQUIRE);
if (a & 1u) continue;
memcpy(out, (const void *)map_, sizeof(*out));
__atomic_thread_fence(__ATOMIC_ACQUIRE);
if (__atomic_load_n(&map_->seq, __ATOMIC_RELAXED) == a)
return out->magic == DROIDDECK_HEADPOSE_MAGIC && out->version == DROIDDECK_HEADPOSE_VERSION;
}
return false;
}
~PoseFile() { if (map_) munmap((void *)map_, sizeof(*map_)); }
private:
bool Open() {
int fd = open(kPosePath, O_RDONLY | O_CLOEXEC);
if (fd < 0) return false;
void *p = mmap(nullptr, sizeof(droiddeck_headpose), PROT_READ, MAP_SHARED, fd, 0);
close(fd);
if (p == MAP_FAILED) return false;
map_ = (volatile droiddeck_headpose *)p;
Log("head pose file mapped: %s", kPosePath);
return true;
}
volatile droiddeck_headpose *map_ = nullptr;
};
HmdQuaternion_t QuatFromMatrix(const float m[9]) {
// Row-major rotation -> quaternion (Shepperd's method).
HmdQuaternion_t q;
float tr = m[0] + m[4] + m[8];
if (tr > 0.0f) {
float s = sqrtf(tr + 1.0f) * 2.0f;
q.w = 0.25f * s; q.x = (m[7] - m[5]) / s; q.y = (m[2] - m[6]) / s; q.z = (m[3] - m[1]) / s;
} else if (m[0] > m[4] && m[0] > m[8]) {
float s = sqrtf(1.0f + m[0] - m[4] - m[8]) * 2.0f;
q.w = (m[7] - m[5]) / s; q.x = 0.25f * s; q.y = (m[1] + m[3]) / s; q.z = (m[2] + m[6]) / s;
} else if (m[4] > m[8]) {
float s = sqrtf(1.0f + m[4] - m[0] - m[8]) * 2.0f;
q.w = (m[2] - m[6]) / s; q.x = (m[1] + m[3]) / s; q.y = 0.25f * s; q.z = (m[5] + m[7]) / s;
} else {
float s = sqrtf(1.0f + m[8] - m[0] - m[4]) * 2.0f;
q.w = (m[3] - m[1]) / s; q.x = (m[2] + m[6]) / s; q.y = (m[5] + m[7]) / s; q.z = 0.25f * s;
}
return q;
}
// IVRVirtualDisplay: the compositor renders the final frame into its own backbuffer and hands it
// here instead of scanning it out. What the handle is on Linux is what this logs (experiment).
class VirtualDisplay : public IVRVirtualDisplay {
public:
void Present(const PresentInfo_t *info, uint32_t size) override {
frames_++;
if (frames_ <= 5 || frames_ % 600 == 0)
Log("virtual display Present #%llu: handle 0x%llx vsync %d frame %llu (info %u bytes)",
(unsigned long long)frames_, (unsigned long long)info->backbufferTextureHandle, (int)info->vsync,
(unsigned long long)info->nFrameId, size);
last_ = std::chrono::steady_clock::now();
}
void WaitForPresent() override {}
bool GetTimeSinceLastVsync(float *seconds, uint64_t *counter) override {
// A free-running 60 Hz vsync.
using namespace std::chrono;
double t = duration<double>(steady_clock::now().time_since_epoch()).count();
double period = 1.0 / 60.0;
*seconds = (float)fmod(t, period);
*counter = (uint64_t)(t / period);
return true;
}
private:
uint64_t frames_ = 0;
std::chrono::steady_clock::time_point last_;
};
// The vsync grid SteamVR paces against in driver-direct mode (Prop_DriverDirectModeSendsVsyncEvents):
// a free-running 60 Hz tick, declared a little ahead of time (ALVR's announcer, alvr/server_openvr/src/vsync.rs).
class Vsync {
public:
static constexpr std::chrono::nanoseconds kInterval{16666667};
static constexpr std::chrono::microseconds kLead{2000};
static void Start() {
if (running_.exchange(true)) return;
thread_ = std::thread([] {
auto next = std::chrono::steady_clock::now() + kInterval;
while (running_) {
auto announce = next - kLead;
std::this_thread::sleep_until(announce);
auto now = std::chrono::steady_clock::now();
double offset = std::chrono::duration<double>(announce - now).count();
VRServerDriverHost()->VsyncEvent(offset);
{
std::lock_guard<std::mutex> lock(mutex_);
last_ = next;
}
next += kInterval;
now = std::chrono::steady_clock::now();
while (next <= now) next += kInterval;
}
});
}
static void Stop() {
running_ = false;
if (thread_.joinable()) thread_.join();
}
static std::chrono::steady_clock::time_point LastTick() {
std::lock_guard<std::mutex> lock(mutex_);
return last_;
}
private:
static inline std::atomic<bool> running_{false};
static inline std::thread thread_;
static inline std::mutex mutex_;
static inline std::chrono::steady_clock::time_point last_{};
};
// IVRDriverDirectModeComponent: SteamVR renders each eye into textures this driver allocates
// (shared Vulkan images from SteamVR's IPC resource manager, dmabufs on Linux) and hands them
// over per frame. This is how ALVR gets frames on Linux; it avoids the compositor's own direct mode,
// which needs VK_KHR_display - something Turnip on KGSL refuses outright.
class DirectMode : public IVRDriverDirectModeComponent {
public:
struct Set {
SharedTextureHandle_t handles[3] = {};
int fds[3] = {-1, -1, -1};
uint32_t pid = 0, index = 0;
SwapTextureSetDesc_t desc = {};
};
void CreateSwapTextureSet(uint32_t pid, const SwapTextureSetDesc_t *d, SwapTextureSet_t *out) override {
Log("CreateSwapTextureSet pid %u: format %u, %ux%u, %u samples", pid, d->nFormat, d->nWidth, d->nHeight, d->nSampleCount);
Set set;
set.pid = pid;
set.desc = *d;
const uint32_t usage = 0x1 /* TRANSFER_SRC */ | 0x4 /* SAMPLED */ | 0x80 /* INPUT_ATTACHMENT */;
const uint32_t create = 0x8 /* MUTABLE_FORMAT */;
for (int i = 0; i < 3; i++) {
SharedTextureHandle_t h = 0;
if (!VRIPCResourceManager()->NewSharedVulkanImage(d->nFormat, d->nWidth, d->nHeight, true, false, true, 1, 1,
create, usage, &h)) {
Log("NewSharedVulkanImage failed");
return;
}
uint64_t ipc = 0;
VRIPCResourceManager()->RefResource(h, &ipc);
int fd = -1;
if (!VRIPCResourceManager()->ReceiveSharedFd(ipc, &fd)) Log("ReceiveSharedFd failed");
set.handles[i] = h;
set.fds[i] = fd;
out->rSharedTextureHandles[i] = h;
}
out->unTextureFlags = 0;
Log(" -> handles 0x%llx 0x%llx 0x%llx, fds %d %d %d", (unsigned long long)set.handles[0],
(unsigned long long)set.handles[1], (unsigned long long)set.handles[2], set.fds[0], set.fds[1], set.fds[2]);
droiddeck::Presenter::AddTextures(set.handles, set.fds, d->nFormat, d->nWidth, d->nHeight);
std::lock_guard<std::mutex> lock(mutex_);
sets_.push_back(set);
}
void DestroySwapTextureSet(SharedTextureHandle_t h) override {
std::lock_guard<std::mutex> lock(mutex_);
for (auto it = sets_.begin(); it != sets_.end(); ++it) {
if (it->handles[0] == h || it->handles[1] == h || it->handles[2] == h) {
Release(*it);
sets_.erase(it);
return;
}
}
}
void DestroyAllSwapTextureSets(uint32_t pid) override {
std::lock_guard<std::mutex> lock(mutex_);
for (auto it = sets_.begin(); it != sets_.end();) {
if (it->pid == pid) { Release(*it); it = sets_.erase(it); } else ++it;
}
}
void GetNextSwapTextureSetIndex(SharedTextureHandle_t handles[2], uint32_t (*indices)[2]) override {
std::lock_guard<std::mutex> lock(mutex_);
for (int e = 0; e < 2; e++) {
Set *s = Find(handles[e]);
if (!s) { (*indices)[e] = 0; continue; }
s->index = (s->index + 1) % 3;
(*indices)[e] = s->index;
}
}
void SubmitLayer(const SubmitLayerPerEye_t (&eyes)[2]) override {
layers_++;
// The first layer of a frame is the compositor's own picture; overlays after it are not drawn yet.
if (layerInFrame_++ == 0) {
for (int e = 0; e < 2; e++) {
frame_.texture[e] = eyes[e].hTexture;
frame_.bounds[e][0] = eyes[e].bounds.uMin; frame_.bounds[e][1] = eyes[e].bounds.vMin;
frame_.bounds[e][2] = eyes[e].bounds.uMax; frame_.bounds[e][3] = eyes[e].bounds.vMax;
}
}
if (frames_ < 3)
Log("SubmitLayer: textures 0x%llx / 0x%llx, bounds %.2f,%.2f-%.2f,%.2f",
(unsigned long long)eyes[0].hTexture, (unsigned long long)eyes[1].hTexture,
eyes[0].bounds.uMin, eyes[0].bounds.vMin, eyes[0].bounds.uMax, eyes[0].bounds.vMax);
}
void Present(SharedTextureHandle_t sync) override {
frames_++;
if (layerInFrame_) droiddeck::Presenter::Submit(frame_);
if (layerInFrame_ != lastLayerCount_) {
static int said;
if (said++ < 20) Log("frame %llu: %d layer(s) (was %d)", (unsigned long long)frames_, layerInFrame_, lastLayerCount_);
lastLayerCount_ = layerInFrame_;
}
layerInFrame_ = 0;
if (frames_ <= 3 || frames_ % 600 == 0)
Log("Present #%llu (%llu layers so far), sync 0x%llx", (unsigned long long)frames_,
(unsigned long long)layers_, (unsigned long long)sync);
}
void PostPresent(const Throttling_t *t) override {
// Hold until the tick after the last one declared (ALVR's pacing): a slow frame costs one frame.
auto last = Vsync::LastTick();
auto until = last + Vsync::kInterval * (1 + (t ? t->nFramesToThrottle : 0));
if (until > std::chrono::steady_clock::now()) std::this_thread::sleep_until(until);
}
void GetFrameTiming(DriverDirectMode_FrameTiming *t) override { t->m_nReprojectionFlags = 0; }
private:
Set *Find(SharedTextureHandle_t h) {
for (auto &s : sets_)
for (int i = 0; i < 3; i++)
if (s.handles[i] == h) return &s;
return nullptr;
}
static void Release(Set &s) {
for (int i = 0; i < 3; i++) {
if (s.handles[i]) droiddeck::Presenter::RemoveTexture(s.handles[i]);
if (s.fds[i] >= 0) close(s.fds[i]);
if (s.handles[i]) VRIPCResourceManager()->UnrefResource(s.handles[i]);
}
}
std::mutex mutex_;
std::vector<Set> sets_;
uint64_t frames_ = 0, layers_ = 0;
int layerInFrame_ = 0, lastLayerCount_ = -1;
droiddeck::EyeFrame frame_{};
};
// The session's game pad, as the app publishes it for the guest: the absolute-state snapshot at the
// head of fake input ring 0 (app/src/main/cpp/fakeinput_steam.cpp, FakeInputRingHeader), under a
// seqlock. FAKE_EVDEV_MEMFD_PATHS names the rings in every session process's environment.
struct PadState {
uint32_t buttons = 0; // bit order of FakeInputWriter.BUTTON_MAP; bit 11 = the QAM button
int16_t axes[8] = {}; // X, Y, RX, RY (+-32767), GAS = right trigger, BRAKE = left (0..255), HAT0X, HAT0Y
};
enum : uint32_t {
PAD_A = 1u << 0, PAD_B = 1u << 1, PAD_X = 1u << 2, PAD_Y = 1u << 3, PAD_LB = 1u << 4, PAD_RB = 1u << 5,
PAD_SELECT = 1u << 6, PAD_START = 1u << 7, PAD_L3 = 1u << 8, PAD_R3 = 1u << 9, PAD_GUIDE = 1u << 10,
};
class PadRing {
public:
bool Read(PadState *out) {
if (!map_ && !Open()) return false;
for (int tries = 0; tries < 8; tries++) {
uint64_t a = __atomic_load_n((const uint64_t *)(map_ + 32), __ATOMIC_ACQUIRE);
if (a & 1u) continue;
memcpy(&out->buttons, (const void *)(map_ + 40), 4);
memcpy(out->axes, (const void *)(map_ + 44), 16);
__atomic_thread_fence(__ATOMIC_ACQUIRE);
if (__atomic_load_n((const uint64_t *)(map_ + 32), __ATOMIC_RELAXED) == a) return true;
}
return false;
}
~PadRing() { if (map_) munmap((void *)map_, 64); }
private:
bool Open() {
auto now = std::chrono::steady_clock::now();
if (now < retry_) return false;
retry_ = now + std::chrono::seconds(2);
std::string path;
if (const char *env = getenv("DROIDDECK_VR_PAD_RING")) path = env;
if (path.empty()) {
const char *paths = getenv("FAKE_EVDEV_MEMFD_PATHS"); // "0=/path;1=/path;..."
if (paths && !strncmp(paths, "0=", 2)) path.assign(paths + 2, strcspn(paths + 2, ";"));
}
if (path.empty()) {
if (const char *dir = getenv("BL_LAUNCH_DIR")) path = std::string(dir) + "/dev/fakeinput-rings/ring0";
}
if (path.empty()) return false;
int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
if (fd < 0) return false;
void *p = mmap(nullptr, 64, PROT_READ, MAP_SHARED, fd, 0);
close(fd);
if (p == MAP_FAILED) return false;
uint32_t magic;
memcpy(&magic, p, 4);
if (magic != 0x46494252u) { munmap(p, 64); return false; }
map_ = (const volatile uint8_t *)p;
Log("game pad ring mapped: %s", path.c_str());
return true;
}
const volatile uint8_t *map_ = nullptr;
std::chrono::steady_clock::time_point retry_{};
};
// One hand: a Vive-profile controller driven by the game pad. 3DoF, so it is a gaze pointer: it sits
// low in front of its side of the body and points where the head looks, and SteamVR's laser follows the
// view. Right hand: right stick = trackpad, A = trackpad click, RT = trigger, RB = grip, Start = menu,
// the Steam/guide button = system. Left: left stick, X, LT, LB, Select.
class CardboardController : public ITrackedDeviceServerDriver {
public:
explicit CardboardController(bool right) : right_(right) {}
EVRInitError Activate(uint32_t id) override {
id_ = id;
PropertyContainerHandle_t c = VRProperties()->TrackedDeviceToPropertyContainer(id_);
VRProperties()->SetStringProperty(c, Prop_ModelNumber_String, "DroidDeck Pad Hand");
VRProperties()->SetStringProperty(c, Prop_ManufacturerName_String, "DroidDeck");
VRProperties()->SetStringProperty(c, Prop_TrackingSystemName_String, "droiddeck");
VRProperties()->SetStringProperty(c, Prop_RenderModelName_String, "generic_controller");
VRProperties()->SetStringProperty(c, Prop_ControllerType_String, "vive_controller");
VRProperties()->SetStringProperty(c, Prop_InputProfilePath_String, "{htc}/input/vive_controller_profile.json");
VRProperties()->SetInt32Property(c, Prop_ControllerRoleHint_Int32,
right_ ? TrackedControllerRole_RightHand : TrackedControllerRole_LeftHand);
VRProperties()->SetInt32Property(c, Prop_DeviceClass_Int32, TrackedDeviceClass_Controller);
auto in = VRDriverInput();
in->CreateBooleanComponent(c, "/input/system/click", &system_);
in->CreateBooleanComponent(c, "/input/application_menu/click", &menu_);
in->CreateBooleanComponent(c, "/input/grip/click", &grip_);
in->CreateBooleanComponent(c, "/input/trigger/click", &triggerClick_);
in->CreateScalarComponent(c, "/input/trigger/value", &trigger_, VRScalarType_Absolute, VRScalarUnits_NormalizedOneSided);
in->CreateScalarComponent(c, "/input/trackpad/x", &padX_, VRScalarType_Absolute, VRScalarUnits_NormalizedTwoSided);
in->CreateScalarComponent(c, "/input/trackpad/y", &padY_, VRScalarType_Absolute, VRScalarUnits_NormalizedTwoSided);
in->CreateBooleanComponent(c, "/input/trackpad/click", &padClick_);
in->CreateBooleanComponent(c, "/input/trackpad/touch", &padTouch_);
in->CreateHapticComponent(c, "/output/haptic", &haptic_);
Log("%s hand activated (game pad)", right_ ? "right" : "left");
return VRInitError_None;
}
void Deactivate() override { id_ = k_unTrackedDeviceIndexInvalid; }
void EnterStandby() override {}
void *GetComponent(const char *) override { return nullptr; }
void DebugRequest(const char *, char *resp, uint32_t size) override { if (size) resp[0] = 0; }
DriverPose_t GetPose() override { return pose_; }
// From the driver's pose thread: the head's orientation and the pad.
void Update(const HmdQuaternion_t &head, const PadState *pad) {
if (id_ == k_unTrackedDeviceIndexInvalid) return;
DriverPose_t p = {};
p.qWorldFromDriverRotation.w = 1;
p.qDriverFromHeadRotation.w = 1;
p.qRotation = head;
// Low and in front of its side, in head space, then into the room with the head's rotation.
const double off[3] = {right_ ? 0.18 : -0.18, -0.35, -0.30};
double m[3][3];
const double w = head.w, x = head.x, y = head.y, z = head.z;
m[0][0] = 1 - 2 * (y * y + z * z); m[0][1] = 2 * (x * y - z * w); m[0][2] = 2 * (x * z + y * w);
m[1][0] = 2 * (x * y + z * w); m[1][1] = 1 - 2 * (x * x + z * z); m[1][2] = 2 * (y * z - x * w);
m[2][0] = 2 * (x * z - y * w); m[2][1] = 2 * (y * z + x * w); m[2][2] = 1 - 2 * (x * x + y * y);
for (int i = 0; i < 3; i++) p.vecPosition[i] = (i == 1 ? 1.6 : 0.0) + m[i][0] * off[0] + m[i][1] * off[1] + m[i][2] * off[2];
p.poseIsValid = true;
p.result = TrackingResult_Running_OK;
p.deviceIsConnected = true;
pose_ = p;
VRServerDriverHost()->TrackedDevicePoseUpdated(id_, p, sizeof(p));
if (!pad) return;
auto in = VRDriverInput();
const uint32_t b = pad->buttons;
const float stickX = pad->axes[right_ ? 2 : 0] / 32767.0f, stickY = -pad->axes[right_ ? 3 : 1] / 32767.0f;
const float trig = pad->axes[right_ ? 4 : 5] / 255.0f;
const bool touch = stickX * stickX + stickY * stickY > 0.01f;
in->UpdateBooleanComponent(system_, right_ && (b & PAD_GUIDE), 0);
in->UpdateBooleanComponent(menu_, (b & (right_ ? PAD_START : PAD_SELECT)) != 0, 0);
in->UpdateBooleanComponent(grip_, (b & (right_ ? PAD_RB : PAD_LB)) != 0, 0);
in->UpdateScalarComponent(trigger_, trig, 0);
in->UpdateBooleanComponent(triggerClick_, trig > 0.6f, 0);
in->UpdateScalarComponent(padX_, touch ? stickX : 0.0f, 0);
in->UpdateScalarComponent(padY_, touch ? stickY : 0.0f, 0);
in->UpdateBooleanComponent(padTouch_, touch || (b & (right_ ? PAD_A : PAD_X)), 0);
in->UpdateBooleanComponent(padClick_, (b & (right_ ? (PAD_A | PAD_R3) : (PAD_X | PAD_L3))) != 0, 0);
}
private:
bool right_;
uint32_t id_ = k_unTrackedDeviceIndexInvalid;
DriverPose_t pose_ = {};
VRInputComponentHandle_t system_ = 0, menu_ = 0, grip_ = 0, triggerClick_ = 0, trigger_ = 0, padX_ = 0, padY_ = 0,
padClick_ = 0, padTouch_ = 0, haptic_ = 0;
};
class CardboardHmd : public ITrackedDeviceServerDriver, public IVRDisplayComponent {
public:
EVRInitError Activate(uint32_t unObjectId) override {
id_ = unObjectId;
PropertyContainerHandle_t c = VRProperties()->TrackedDeviceToPropertyContainer(id_);
width_ = VRSettings()->GetInt32(kSettingsSection, "windowWidth");
height_ = VRSettings()->GetInt32(kSettingsSection, "windowHeight");
if (width_ <= 0) width_ = 1920;
if (height_ <= 0) height_ = 1080;
float hz = VRSettings()->GetFloat(kSettingsSection, "displayFrequency");
if (hz <= 0.0f) hz = 60.0f;
// Until the app has drawn an eye: the Cardboard pass's defaults for a 1920x1080 panel.
tanHalf_ = 1.0f;
eyeAspect_ = (width_ * 0.5f) / height_;
droiddeck_headpose hp;
if (pose_.Read(&hp) && hp.tan_half_fov > 0.0f) {
tanHalf_ = hp.tan_half_fov;
if (hp.eye_aspect > 0.0f) eyeAspect_ = hp.eye_aspect;
}
VRProperties()->SetStringProperty(c, Prop_ModelNumber_String, "DroidDeck Cardboard");
VRProperties()->SetStringProperty(c, Prop_ManufacturerName_String, "DroidDeck");
VRProperties()->SetStringProperty(c, Prop_TrackingSystemName_String, "droiddeck");
VRProperties()->SetFloatProperty(c, Prop_UserIpdMeters_Float, 0.064f);
VRProperties()->SetFloatProperty(c, Prop_UserHeadToEyeDepthMeters_Float, 0.0f);
VRProperties()->SetFloatProperty(c, Prop_DisplayFrequency_Float, hz);
VRProperties()->SetFloatProperty(c, Prop_SecondsFromVsyncToPhotons_Float, 0.011f);
VRProperties()->SetUint64Property(c, Prop_CurrentUniverseId_Uint64, 2);
// Off the desktop: with a direct mode component that sends SteamVR's compositor down the
// driver-direct path; on it, the compositor opens its own direct mode window (VK_KHR_display).
VRProperties()->SetBoolProperty(c, Prop_IsOnDesktop_Bool, false);
VRProperties()->SetBoolProperty(c, Prop_DisplayDebugMode_Bool, false);
directMode_ = VRSettings()->GetBool(kSettingsSection, "directMode");
VRProperties()->SetBoolProperty(c, Prop_HasDriverDirectModeComponent_Bool, directMode_);
if (directMode_) {
VRProperties()->SetBoolProperty(c, Prop_DriverDirectModeSendsVsyncEvents_Bool, true);
VRProperties()->SetBoolProperty(c, Prop_Hmd_AllowsClientToControlTextureIndex, true);
}
VRProperties()->SetBoolProperty(c, Prop_HasDisplayComponent_Bool, true);
virtualDisplay_ = VRSettings()->GetBool(kSettingsSection, "virtualDisplay");
VRProperties()->SetBoolProperty(c, Prop_HasVirtualDisplayComponent_Bool, virtualDisplay_);
// A proximity sensor that reads "worn" while Cardboard mode is on: otherwise SteamVR sees a headset
// lying still (a phone on a table between sessions) and puts the display in standby, after which
// the compositor submits no layers at all.
VRProperties()->SetBoolProperty(c, Prop_ContainsProximitySensor_Bool, true);
VRDriverInput()->CreateBooleanComponent(c, "/proximity", &proximity_);
VRDriverInput()->UpdateBooleanComponent(proximity_, true, 0);
Log("HMD activated: %dx%d at %.0f Hz, eye tan(half fov) %.3f, eye aspect %.3f", width_, height_, hz, tanHalf_, eyeAspect_);
running_ = true;
thread_ = std::thread([this] { PoseLoop(); });
if (directMode_) Vsync::Start();
return VRInitError_None;
}
void Deactivate() override {
Vsync::Stop();
droiddeck::Presenter::Shutdown();
running_ = false;
if (thread_.joinable()) thread_.join();
id_ = k_unTrackedDeviceIndexInvalid;
}
void EnterStandby() override {}
void *GetComponent(const char *name) override {
Log("component asked for: %s", name);
if (!strncmp(name, "IVRDisplayComponent_", 20)) return static_cast<IVRDisplayComponent *>(this);
if (virtualDisplay_ && !strcmp(name, IVRVirtualDisplay_Version)) return static_cast<IVRVirtualDisplay *>(&vd_);
if (directMode_ && !strncmp(name, "IVRDriverDirectModeComponent_", 29)) return static_cast<IVRDriverDirectModeComponent *>(&dm_);
return nullptr;
}
void DebugRequest(const char *, char *resp, uint32_t size) override { if (size) resp[0] = 0; }
DriverPose_t GetPose() override {
DriverPose_t p = {};
p.qWorldFromDriverRotation.w = 1;
p.qDriverFromHeadRotation.w = 1;
p.qRotation.w = 1;
p.vecPosition[1] = 1.6; // standing eye height: 3DoF, the head never moves
droiddeck_headpose hp;
bool ok = pose_.Read(&hp);
if (ok) {
p.qRotation = QuatFromMatrix(hp.rot);
p.poseTimeOffset = 0;
if (hp.tan_half_fov > 0.0f) tanHalf_ = hp.tan_half_fov;
if (hp.eye_aspect > 0.0f) eyeAspect_ = hp.eye_aspect;
}
p.poseIsValid = true;
p.result = TrackingResult_Running_OK;
p.deviceIsConnected = true;
return p;
}
// ---- IVRDisplayComponent
void GetWindowBounds(int32_t *x, int32_t *y, uint32_t *w, uint32_t *h) override {
*x = 0; *y = 0; *w = (uint32_t)width_; *h = (uint32_t)height_;
}
bool IsDisplayOnDesktop() override { return !directMode_; }
bool IsDisplayRealDisplay() override { return false; }
void GetRecommendedRenderTargetSize(uint32_t *w, uint32_t *h) override {
// Rendered a little larger than the panel: the lens pass magnifies the middle.
*w = (uint32_t)(width_ / 2 * 1.4f);
*h = (uint32_t)(height_ * 1.4f);
}
void GetEyeOutputViewport(EVREye eye, uint32_t *x, uint32_t *y, uint32_t *w, uint32_t *h) override {
*y = 0; *w = (uint32_t)width_ / 2; *h = (uint32_t)height_;
*x = eye == Eye_Left ? 0 : (uint32_t)width_ / 2;
}
void GetProjectionRaw(EVREye, float *left, float *right, float *top, float *bottom) override {
// Exactly what the Cardboard pass samples from each half of a side-by-side frame.
*left = -tanHalf_ * eyeAspect_; *right = tanHalf_ * eyeAspect_;
*top = -tanHalf_; *bottom = tanHalf_;
}
DistortionCoordinates_t ComputeDistortion(EVREye, float u, float v) override {
DistortionCoordinates_t d;
d.rfRed[0] = d.rfGreen[0] = d.rfBlue[0] = u;
d.rfRed[1] = d.rfGreen[1] = d.rfBlue[1] = v;
return d;
}
bool ComputeInverseDistortion(HmdVector2_t *result, EVREye, uint32_t, float u, float v) override {
result->v[0] = u; result->v[1] = v;
return true;
}
private:
void PoseLoop() {
uint32_t lastSeq = 0;
auto lastSent = std::chrono::steady_clock::now();
while (running_) {
droiddeck_headpose hp;
bool fresh = pose_.Read(&hp) && hp.seq != lastSeq;
auto now = std::chrono::steady_clock::now();
// A new sample, or a heartbeat so SteamVR never thinks the HMD went away.
PadState pad;
const bool havePad = pad_.Read(&pad);
const bool padChanged = havePad && (pad.buttons != lastPad_.buttons || memcmp(pad.axes, lastPad_.axes, sizeof(pad.axes)));
if ((fresh || padChanged || now - lastSent > std::chrono::milliseconds(100)) && id_ != k_unTrackedDeviceIndexInvalid) {
if (fresh) {
lastSeq = hp.seq;
const bool worn = (hp.flags & DROIDDECK_HEADPOSE_ENABLED) != 0;
if (worn != worn_) {
worn_ = worn;
VRDriverInput()->UpdateBooleanComponent(proximity_, worn, 0);
Log("headset %s (Cardboard mode %s)", worn ? "worn" : "taken off", worn ? "on" : "off");
}
}
DriverPose_t head = GetPose();
VRServerDriverHost()->TrackedDevicePoseUpdated(id_, head, sizeof(DriverPose_t));
for (CardboardController *hand : hands_) if (hand) hand->Update(head.qRotation, havePad ? &pad : nullptr);
if (havePad) lastPad_ = pad;
lastSent = now;
}
std::this_thread::sleep_for(std::chrono::milliseconds(2));
}
}
uint32_t id_ = k_unTrackedDeviceIndexInvalid;
int32_t width_ = 1920, height_ = 1080;
float tanHalf_ = 1.0f, eyeAspect_ = 0.889f;
public:
void SetHands(CardboardController *left, CardboardController *right) { hands_[0] = left; hands_[1] = right; }
private:
PoseFile pose_;
PadRing pad_;
PadState lastPad_;
VRInputComponentHandle_t proximity_ = 0;
bool worn_ = true;
CardboardController *hands_[2] = {nullptr, nullptr};
bool virtualDisplay_ = false, directMode_ = false;
VirtualDisplay vd_;
DirectMode dm_;
std::atomic<bool> running_{false};
std::thread thread_;
};
class Provider : public IServerTrackedDeviceProvider {
public:
EVRInitError Init(IVRDriverContext *ctx) override {
VR_INIT_SERVER_DRIVER_CONTEXT(ctx);
Log("DroidDeck Cardboard driver loaded");
if (!VRServerDriverHost()->TrackedDeviceAdded("droiddeck-cardboard-hmd", TrackedDeviceClass_HMD, &hmd_))
Log("TrackedDeviceAdded failed");
if (VRSettings()->GetBool(kSettingsSection, "gamepadControllers")) {
VRServerDriverHost()->TrackedDeviceAdded("droiddeck-pad-left", TrackedDeviceClass_Controller, &left_);
VRServerDriverHost()->TrackedDeviceAdded("droiddeck-pad-right", TrackedDeviceClass_Controller, &right_);
hmd_.SetHands(&left_, &right_);
}
return VRInitError_None;
}
void Cleanup() override { VR_CLEANUP_SERVER_DRIVER_CONTEXT(); }
const char *const *GetInterfaceVersions() override { return k_InterfaceVersions; }
void RunFrame() override {
VREvent_t e;
while (VRServerDriverHost()->PollNextEvent(&e, sizeof(e))) {}
}
bool ShouldBlockStandbyMode() override { return false; }
void EnterStandby() override {}
void LeaveStandby() override {}
private:
CardboardHmd hmd_;
CardboardController left_{false}, right_{true};
};
Provider g_provider;
} // namespace
DD_EXPORT void *HmdDriverFactory(const char *interfaceName, int *returnCode) {
if (!strcmp(interfaceName, IServerTrackedDeviceProvider_Version)) return &g_provider;
if (returnCode) *returnCode = VRInitError_Init_InterfaceNotFound;
return nullptr;
}
File diff suppressed because it is too large. Load diff
+607
View File
@@ -0,0 +1,607 @@
// See presenter.h.
#define VK_NO_PROTOTYPES
#include <vulkan/vulkan_core.h>
typedef struct _XDisplay Display;
typedef unsigned long Window;
typedef unsigned long VisualID;
#include <vulkan/vulkan_xlib.h>
#include <wayland-client.h>
#include <vulkan/vulkan_wayland.h>
#include "xdg-shell-client-protocol.h"
#include "presenter.h"
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <dlfcn.h>
#include <fcntl.h>
#include <mutex>
#include <thread>
#include <unistd.h>
#include <vector>
#include "openvr_driver.h"
namespace droiddeck {
namespace {
void Log(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
void Log(const char *fmt, ...) {
char buf[1024];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
if (vr::VRDriverLog()) vr::VRDriverLog()->Log(buf);
fprintf(stderr, "[droiddeck] %s\n", buf);
}
// ---------------------------------------------------------------- Xlib, loaded at runtime
struct X11 {
void *lib = nullptr;
Display *(*OpenDisplay)(const char *);
Window (*DefaultRootWindow)(Display *);
int (*DefaultScreen)(Display *);
int (*DisplayWidth)(Display *, int);
int (*DisplayHeight)(Display *, int);
Window (*CreateSimpleWindow)(Display *, Window, int, int, unsigned, unsigned, unsigned, unsigned long, unsigned long);
unsigned long (*InternAtom)(Display *, const char *, int);
int (*ChangeProperty)(Display *, Window, unsigned long, unsigned long, int, int, const unsigned char *, int);
int (*MapWindow)(Display *, Window);
int (*StoreName)(Display *, Window, const char *);
int (*Flush)(Display *);
bool Load() {
lib = dlopen("libX11.so.6", RTLD_NOW | RTLD_LOCAL);
if (!lib) return false;
#define X(name) if (!(*(void **)&name = dlsym(lib, "X" #name))) return false;
X(OpenDisplay) X(DefaultRootWindow) X(DefaultScreen) X(DisplayWidth) X(DisplayHeight)
X(CreateSimpleWindow) X(InternAtom) X(ChangeProperty) X(MapWindow) X(StoreName) X(Flush)
#undef X
return true;
}
};
// ---------------------------------------------------------------- Vulkan, loaded at runtime
#define VK_GLOBAL(X) X(CreateInstance)
#define VK_INSTANCE(X) \
X(DestroyInstance) X(EnumeratePhysicalDevices) X(GetPhysicalDeviceQueueFamilyProperties) \
X(GetPhysicalDeviceMemoryProperties) X(CreateDevice) X(GetDeviceProcAddr) X(CreateXlibSurfaceKHR) \
X(CreateWaylandSurfaceKHR) \
X(GetPhysicalDeviceSurfaceSupportKHR) X(GetPhysicalDeviceSurfaceCapabilitiesKHR) \
X(GetPhysicalDeviceSurfaceFormatsKHR) X(GetPhysicalDeviceSurfacePresentModesKHR) X(GetPhysicalDeviceProperties)
#define VK_DEVICE(X) \
X(GetDeviceQueue) X(CreateSwapchainKHR) X(DestroySwapchainKHR) X(GetSwapchainImagesKHR) X(AcquireNextImageKHR) \
X(QueuePresentKHR) X(CreateCommandPool) X(AllocateCommandBuffers) X(BeginCommandBuffer) X(EndCommandBuffer) \
X(ResetCommandBuffer) X(CmdPipelineBarrier) X(CmdBlitImage) X(CmdClearColorImage) X(QueueSubmit) X(CreateFence) \
X(WaitForFences) X(ResetFences) X(CreateSemaphore) X(CreateImage) X(DestroyImage) X(GetImageMemoryRequirements) \
X(AllocateMemory) X(FreeMemory) X(BindImageMemory) X(DeviceWaitIdle)
struct Vk {
void *lib = nullptr;
PFN_vkGetInstanceProcAddr GetInstanceProcAddr = nullptr;
#define X(n) PFN_vk##n n = nullptr;
VK_GLOBAL(X) VK_INSTANCE(X) VK_DEVICE(X)
#undef X
};
struct Imported {
uint64_t handle;
VkImage image = VK_NULL_HANDLE;
VkDeviceMemory memory = VK_NULL_HANDLE;
uint32_t width = 0, height = 0;
};
struct PendingImport {
uint64_t handle;
int fd;
uint32_t format, width, height;
};
VkFormat UnormOf(uint32_t f) {
switch (f) {
case VK_FORMAT_R8G8B8A8_SRGB: return VK_FORMAT_R8G8B8A8_UNORM;
case VK_FORMAT_B8G8R8A8_SRGB: return VK_FORMAT_B8G8R8A8_UNORM;
default: return (VkFormat)f;
}
}
class Impl {
public:
static Impl &Get() {
static Impl impl;
return impl;
}
void Add(const uint64_t handles[3], const int fds[3], uint32_t format, uint32_t w, uint32_t h) {
std::lock_guard<std::mutex> lock(mutex_);
for (int i = 0; i < 3; i++) {
if (fds[i] < 0) continue;
int fd = dup(fds[i]); // the import owns its fd; the driver keeps its own
if (fd >= 0) pending_.push_back({handles[i], fd, format, w, h});
}
EnsureThread();
cv_.notify_one();
}
void Remove(uint64_t handle) {
std::lock_guard<std::mutex> lock(mutex_);
removals_.push_back(handle);
cv_.notify_one();
}
void Submit(const EyeFrame &f) {
std::lock_guard<std::mutex> lock(mutex_);
frame_ = f;
frameAt_ = std::chrono::steady_clock::now();
haveFrame_ = true;
submitted_++;
cv_.notify_one();
}
void Shutdown() {
{
std::lock_guard<std::mutex> lock(mutex_);
exit_ = true;
cv_.notify_one();
}
if (thread_.joinable()) thread_.join();
}
private:
void EnsureThread() {
if (!started_) {
started_ = true;
thread_ = std::thread([this] { Run(); });
}
}
// ------------------------------------------------------------ the presenting thread
void Run() {
const char *mode = getenv("DROIDDECK_VR_PRESENT");
wayland_ = !(mode && !strcmp(mode, "x11")) && InitWayland();
if (!wayland_ && !InitWindow()) {
Log("presenter: unavailable, frames are not shown");
return;
}
if (!InitVulkan()) {
Log("presenter: unavailable, frames are not shown");
return;
}
uint64_t shown = 0;
auto lastLog = std::chrono::steady_clock::now();
while (true) {
EyeFrame f;
std::chrono::steady_clock::time_point at;
std::vector<PendingImport> imports;
std::vector<uint64_t> removals;
{
std::unique_lock<std::mutex> lock(mutex_);
cv_.wait(lock, [this] { return exit_ || haveFrame_ || !pending_.empty() || !removals_.empty(); });
if (exit_) break;
imports.swap(pending_);
removals.swap(removals_);
f = frame_;
at = frameAt_;
bool draw = haveFrame_;
haveFrame_ = false;
if (!draw) f.texture[0] = f.texture[1] = 0;
}
if (wl_) { wl_display_dispatch_pending(wl_); wl_display_flush(wl_); }
for (auto &p : imports) Import(p);
for (auto h : removals) Forget(h);
// SteamVR hands the textures over at Present with no fence the driver can wait on: give the
// compositor's GPU work a moment to land before copying, as ALVR does (a torn or half-drawn
// frame otherwise).
if (f.texture[0]) std::this_thread::sleep_until(at + guard_);
if (f.texture[0] && Draw(f)) shown++;
auto now = std::chrono::steady_clock::now();
if (now - lastLog > std::chrono::seconds(10)) {
Log("presenter: %llu frames shown, %llu submitted (last 10 s)", (unsigned long long)shown,
(unsigned long long)submitted_.exchange(0));
shown = 0;
lastLog = now;
}
}
if (dev_) vk_.DeviceWaitIdle(dev_);
}
std::chrono::microseconds guard_{4000};
// ------------------------------------------------------------ Wayland: straight to DroidDeck's compositor
// The compositor the app runs (wayland-0 in the session's runtime dir, beside gamescope's socket)
// takes a fullscreen toplevel at the panel's size: one hop and one scale fewer than the X11 overlay
// through gamescope, whose output is the session's (often smaller) resolution.
struct wl_display *wl_ = nullptr;
struct wl_compositor *wlComp_ = nullptr;
struct xdg_wm_base *wm_ = nullptr;
struct wl_surface *wlSurf_ = nullptr;
struct xdg_surface *xdgSurf_ = nullptr;
struct xdg_toplevel *toplevel_ = nullptr;
bool wayland_ = false, configured_ = false;
int32_t cfgW_ = 0, cfgH_ = 0;
static void OnGlobal(void *data, struct wl_registry *reg, uint32_t name, const char *iface, uint32_t version) {
Impl *self = (Impl *)data;
if (!strcmp(iface, wl_compositor_interface.name))
self->wlComp_ = (struct wl_compositor *)wl_registry_bind(reg, name, &wl_compositor_interface, version < 4 ? version : 4);
else if (!strcmp(iface, xdg_wm_base_interface.name))
self->wm_ = (struct xdg_wm_base *)wl_registry_bind(reg, name, &xdg_wm_base_interface, 1);
}
static void OnGlobalRemove(void *, struct wl_registry *, uint32_t) {}
static void OnPing(void *, struct xdg_wm_base *wm, uint32_t serial) { xdg_wm_base_pong(wm, serial); }
static void OnSurfaceConfigure(void *data, struct xdg_surface *xs, uint32_t serial) {
xdg_surface_ack_configure(xs, serial);
((Impl *)data)->configured_ = true;
}
static void OnToplevelConfigure(void *data, struct xdg_toplevel *, int32_t w, int32_t h, struct wl_array *) {
Impl *self = (Impl *)data;
if (w > 0 && h > 0) { self->cfgW_ = w; self->cfgH_ = h; }
}
static void OnToplevelClose(void *, struct xdg_toplevel *) {}
bool InitWayland() {
const char *name = getenv("DROIDDECK_VR_WAYLAND_DISPLAY");
if (!name || !*name) name = "wayland-0";
wl_ = wl_display_connect(name);
if (!wl_) { Log("presenter: no Wayland display %s; using the X11 overlay", name); return false; }
static const struct wl_registry_listener regListener = {OnGlobal, OnGlobalRemove};
struct wl_registry *reg = wl_display_get_registry(wl_);
wl_registry_add_listener(reg, &regListener, this);
wl_display_roundtrip(wl_);
if (!wlComp_ || !wm_) { Log("presenter: %s lacks wl_compositor or xdg_wm_base", name); return false; }
static const struct xdg_wm_base_listener wmListener = {OnPing};
xdg_wm_base_add_listener(wm_, &wmListener, this);
wlSurf_ = wl_compositor_create_surface(wlComp_);
xdgSurf_ = xdg_wm_base_get_xdg_surface(wm_, wlSurf_);
static const struct xdg_surface_listener xsListener = {OnSurfaceConfigure};
xdg_surface_add_listener(xdgSurf_, &xsListener, this);
toplevel_ = xdg_surface_get_toplevel(xdgSurf_);
static const struct xdg_toplevel_listener tlListener = {OnToplevelConfigure, OnToplevelClose, nullptr, nullptr};
xdg_toplevel_add_listener(toplevel_, &tlListener, this);
xdg_toplevel_set_title(toplevel_, "DroidDeck Cardboard VR");
xdg_toplevel_set_app_id(toplevel_, "droiddeck-cardboard-vr");
xdg_toplevel_set_fullscreen(toplevel_, nullptr);
wl_surface_commit(wlSurf_);
for (int i = 0; i < 20 && !configured_; i++) wl_display_roundtrip(wl_);
// The size: the panel the Cardboard pass draws (two eyes, from the shared pose file), so nothing
// scales the picture down on the way. The compositor's configure carries the session's output
// size, which is often smaller; it is the fallback.
width_ = height_ = 0;
int fd = open("/run/droiddeck/droiddeck-headpose", O_RDONLY | O_CLOEXEC);
if (fd >= 0) {
uint32_t eye[2] = {0, 0};
if (pread(fd, eye, sizeof(eye), 72) == (ssize_t)sizeof(eye) && eye[0] && eye[1]) { width_ = eye[0] * 2; height_ = eye[1]; }
close(fd);
}
if (!width_ && cfgW_ > 0 && cfgH_ > 0) { width_ = (uint32_t)cfgW_; height_ = (uint32_t)cfgH_; }
if (!width_) { width_ = 1920; height_ = 1080; }
Log("presenter: %ux%u fullscreen window on Wayland display %s (configured %s)", width_, height_, name, configured_ ? "yes" : "no");
return true;
}
bool InitWindow() {
if (const char *g = getenv("DROIDDECK_VR_PRESENT_GUARD_MS")) guard_ = std::chrono::microseconds((long)(atof(g) * 1000));
if (!x_.Load()) { Log("presenter: no libX11"); return false; }
// gamescope's first Xwayland (:0) is where its overlays (mangoapp, Steam's) live; SteamVR's
// processes inherit the games' display (:1), so it is not taken from DISPLAY.
const char *name = getenv("DROIDDECK_VR_DISPLAY");
if (!name || !*name) name = ":0";
dpy_ = x_.OpenDisplay(name);
if (!dpy_) { Log("presenter: cannot open X display %s", name); return false; }
int scr = x_.DefaultScreen(dpy_);
width_ = (uint32_t)x_.DisplayWidth(dpy_, scr);
height_ = (uint32_t)x_.DisplayHeight(dpy_, scr);
win_ = x_.CreateSimpleWindow(dpy_, x_.DefaultRootWindow(dpy_), 0, 0, width_, height_, 0, 0, 0);
x_.StoreName(dpy_, win_, "DroidDeck Cardboard VR");
// gamescope shows an external overlay above whatever has focus (mangoapp is one).
// gamescope composites one external overlay (mangoapp, the perf HUD, usually holds it) and one Steam
// overlay; the Steam overlay slot is free while nothing is shown over a game.
const char *atom = getenv("DROIDDECK_VR_OVERLAY_ATOM");
if (!atom || !*atom) atom = "STEAM_OVERLAY";
unsigned long cardinal = 6; // XA_CARDINAL
unsigned long one = 1; // format 32 properties are longs in Xlib
x_.ChangeProperty(dpy_, win_, x_.InternAtom(dpy_, atom, 0), cardinal, 32, 0 /* PropModeReplace */,
(const unsigned char *)&one, 1);
x_.MapWindow(dpy_, win_);
x_.Flush(dpy_);
Log("presenter: %ux%u overlay window (%s) on X display %s", width_, height_, atom, name);
return true;
}
bool InitVulkan() {
vk_.lib = dlopen("libvulkan.so.1", RTLD_NOW | RTLD_LOCAL);
if (!vk_.lib) { Log("presenter: no libvulkan"); return false; }
vk_.GetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)dlsym(vk_.lib, "vkGetInstanceProcAddr");
#define X(n) vk_.n = (PFN_vk##n)vk_.GetInstanceProcAddr(VK_NULL_HANDLE, "vk" #n);
VK_GLOBAL(X)
#undef X
const char *iexts[] = {"VK_KHR_surface", wayland_ ? "VK_KHR_wayland_surface" : "VK_KHR_xlib_surface"};
VkApplicationInfo app = {VK_STRUCTURE_TYPE_APPLICATION_INFO, nullptr, "droiddeck-vr-presenter", 1, nullptr, 0, VK_API_VERSION_1_1};
VkInstanceCreateInfo ici = {VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, nullptr, 0, &app, 0, nullptr, 2, iexts};
VkResult r = vk_.CreateInstance(&ici, nullptr, &inst_);
if (r != VK_SUCCESS) { Log("presenter: vkCreateInstance %d", r); return false; }
#define X(n) vk_.n = (PFN_vk##n)vk_.GetInstanceProcAddr(inst_, "vk" #n);
VK_INSTANCE(X)
#undef X
uint32_t n = 1;
VkPhysicalDevice pds[4];
n = 4;
if (vk_.EnumeratePhysicalDevices(inst_, &n, pds) < 0 || n == 0) { Log("presenter: no GPU"); return false; }
pd_ = pds[0];
VkPhysicalDeviceProperties props;
vk_.GetPhysicalDeviceProperties(pd_, &props);
vk_.GetPhysicalDeviceMemoryProperties(pd_, &mem_);
if (wayland_) {
VkWaylandSurfaceCreateInfoKHR wci = {VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR, nullptr, 0, wl_, wlSurf_};
if ((r = vk_.CreateWaylandSurfaceKHR(inst_, &wci, nullptr, &surface_)) != VK_SUCCESS) { Log("presenter: wayland surface %d", r); return false; }
} else {
VkXlibSurfaceCreateInfoKHR sci = {VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR, nullptr, 0, dpy_, win_};
if ((r = vk_.CreateXlibSurfaceKHR(inst_, &sci, nullptr, &surface_)) != VK_SUCCESS) { Log("presenter: xlib surface %d", r); return false; }
}
uint32_t nq = 0;
vk_.GetPhysicalDeviceQueueFamilyProperties(pd_, &nq, nullptr);
std::vector<VkQueueFamilyProperties> qf(nq);
vk_.GetPhysicalDeviceQueueFamilyProperties(pd_, &nq, qf.data());
qfam_ = UINT32_MAX;
for (uint32_t i = 0; i < nq; i++) {
VkBool32 present = VK_FALSE;
vk_.GetPhysicalDeviceSurfaceSupportKHR(pd_, i, surface_, &present);
if ((qf[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) && present) { qfam_ = i; break; }
}
if (qfam_ == UINT32_MAX) { Log("presenter: no queue can present"); return false; }
float prio = 1.0f;
VkDeviceQueueCreateInfo qci = {VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, nullptr, 0, qfam_, 1, &prio};
const char *dexts[] = {"VK_KHR_swapchain", "VK_KHR_external_memory_fd"};
VkDeviceCreateInfo dci = {VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, nullptr, 0, 1, &qci, 0, nullptr, 2, dexts, nullptr};
if ((r = vk_.CreateDevice(pd_, &dci, nullptr, &dev_)) != VK_SUCCESS) { Log("presenter: vkCreateDevice %d", r); return false; }
#define X(n) vk_.n = (PFN_vk##n)vk_.GetDeviceProcAddr(dev_, "vk" #n);
VK_DEVICE(X)
#undef X
vk_.GetDeviceQueue(dev_, qfam_, 0, &queue_);
VkCommandPoolCreateInfo pci = {VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, nullptr,
VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, qfam_};
vk_.CreateCommandPool(dev_, &pci, nullptr, &pool_);
VkCommandBufferAllocateInfo cai = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, nullptr, pool_, VK_COMMAND_BUFFER_LEVEL_PRIMARY, 1};
vk_.AllocateCommandBuffers(dev_, &cai, &cmd_);
VkFenceCreateInfo fci = {VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, nullptr, VK_FENCE_CREATE_SIGNALED_BIT};
vk_.CreateFence(dev_, &fci, nullptr, &fence_);
VkSemaphoreCreateInfo semci = {VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, nullptr, 0};
vk_.CreateSemaphore(dev_, &semci, nullptr, &acquired_);
vk_.CreateSemaphore(dev_, &semci, nullptr, &rendered_);
if (!CreateSwapchain()) return false;
Log("presenter: Vulkan on %s, queue family %u", props.deviceName, qfam_);
return true;
}
bool CreateSwapchain() {
VkSurfaceCapabilitiesKHR caps;
vk_.GetPhysicalDeviceSurfaceCapabilitiesKHR(pd_, surface_, &caps);
uint32_t nf = 0;
vk_.GetPhysicalDeviceSurfaceFormatsKHR(pd_, surface_, &nf, nullptr);
std::vector<VkSurfaceFormatKHR> fmts(nf);
vk_.GetPhysicalDeviceSurfaceFormatsKHR(pd_, surface_, &nf, fmts.data());
VkSurfaceFormatKHR fmt = fmts.empty() ? VkSurfaceFormatKHR{VK_FORMAT_B8G8R8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR} : fmts[0];
for (auto &f : fmts)
if (f.format == VK_FORMAT_B8G8R8A8_UNORM || f.format == VK_FORMAT_R8G8B8A8_UNORM) { fmt = f; break; }
uint32_t npm = 0;
vk_.GetPhysicalDeviceSurfacePresentModesKHR(pd_, surface_, &npm, nullptr);
std::vector<VkPresentModeKHR> pms(npm);
vk_.GetPhysicalDeviceSurfacePresentModesKHR(pd_, surface_, &npm, pms.data());
VkPresentModeKHR pm = VK_PRESENT_MODE_FIFO_KHR;
for (auto m : pms) if (m == VK_PRESENT_MODE_MAILBOX_KHR) pm = m;
VkExtent2D ext = caps.currentExtent.width != UINT32_MAX ? caps.currentExtent : VkExtent2D{width_, height_};
extent_ = ext;
uint32_t count = caps.minImageCount + 1;
if (caps.maxImageCount && count > caps.maxImageCount) count = caps.maxImageCount;
VkCompositeAlphaFlagBitsKHR alpha = (caps.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR)
? VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR : (VkCompositeAlphaFlagBitsKHR)(caps.supportedCompositeAlpha & -caps.supportedCompositeAlpha);
VkSwapchainCreateInfoKHR sci = {VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR};
sci.surface = surface_;
sci.minImageCount = count;
sci.imageFormat = fmt.format;
sci.imageColorSpace = fmt.colorSpace;
sci.imageExtent = ext;
sci.imageArrayLayers = 1;
sci.imageUsage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
sci.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
sci.preTransform = caps.currentTransform;
sci.compositeAlpha = alpha;
sci.presentMode = pm;
sci.clipped = VK_TRUE;
VkResult r = vk_.CreateSwapchainKHR(dev_, &sci, nullptr, &swapchain_);
if (r != VK_SUCCESS) { Log("presenter: vkCreateSwapchainKHR %d", r); return false; }
uint32_t ni = 0;
vk_.GetSwapchainImagesKHR(dev_, swapchain_, &ni, nullptr);
images_.resize(ni);
vk_.GetSwapchainImagesKHR(dev_, swapchain_, &ni, images_.data());
Log("presenter: swapchain %ux%u, format %d, %u images, %s", ext.width, ext.height, fmt.format, ni,
pm == VK_PRESENT_MODE_MAILBOX_KHR ? "mailbox" : "fifo");
return true;
}
int MemoryType(uint32_t bits) {
for (uint32_t i = 0; i < mem_.memoryTypeCount; i++)
if ((bits & (1u << i)) && (mem_.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) return (int)i;
for (uint32_t i = 0; i < mem_.memoryTypeCount; i++) if (bits & (1u << i)) return (int)i;
return -1;
}
// Imports one of SteamVR's shared images with the parameters it was made with (ALVR's recipe):
// optimal tiling, mutable format (which keeps it uncompressed), opaque fd, dedicated memory. UNORM so a
// blit copies the bytes rather than decoding sRGB.
void Import(const PendingImport &p) {
Imported im{p.handle};
im.width = p.width;
im.height = p.height;
// The same format list SteamVR's mutable sRGB images carry: with it Turnip keeps UBWC compression on,
// and the import has to agree on that or it reads compressed data as plain pixels.
const char *fl = getenv("DROIDDECK_VR_IMPORT_FORMAT_LIST");
const bool formatList = !fl || strcmp(fl, "0") != 0;
VkFormat formats[2] = {(VkFormat)p.format, UnormOf(p.format)};
VkImageFormatListCreateInfo list = {VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO, nullptr, 2, formats};
VkExternalMemoryImageCreateInfo ext = {VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO, formatList ? &list : nullptr,
VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT};
VkImageCreateInfo ici = {VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, &ext, VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, VK_IMAGE_TYPE_2D,
UnormOf(p.format), {p.width, p.height, 1}, 1, 1, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_TILING_OPTIMAL,
VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT,
VK_SHARING_MODE_EXCLUSIVE, 0, nullptr, VK_IMAGE_LAYOUT_UNDEFINED};
VkResult r = vk_.CreateImage(dev_, &ici, nullptr, &im.image);
if (r != VK_SUCCESS) { Log("presenter: import image %d", r); close(p.fd); return; }
VkMemoryRequirements req;
vk_.GetImageMemoryRequirements(dev_, im.image, &req);
VkImportMemoryFdInfoKHR imp = {VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR, nullptr, VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT, p.fd};
VkMemoryDedicatedAllocateInfo ded = {VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO, &imp, im.image, VK_NULL_HANDLE};
VkMemoryAllocateInfo mai = {VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &ded, req.size, (uint32_t)MemoryType(req.memoryTypeBits)};
r = vk_.AllocateMemory(dev_, &mai, nullptr, &im.memory);
if (r != VK_SUCCESS) {
Log("presenter: import memory (fd %d, %llu bytes) %d", p.fd, (unsigned long long)req.size, r);
close(p.fd);
vk_.DestroyImage(dev_, im.image, nullptr);
return;
}
vk_.BindImageMemory(dev_, im.image, im.memory, 0);
textures_.push_back(im);
Log("presenter: imported texture 0x%llx (%ux%u, format %u)", (unsigned long long)p.handle, p.width, p.height, p.format);
}
void Forget(uint64_t handle) {
for (auto it = textures_.begin(); it != textures_.end(); ++it) {
if (it->handle == handle) {
vk_.DeviceWaitIdle(dev_);
vk_.DestroyImage(dev_, it->image, nullptr);
vk_.FreeMemory(dev_, it->memory, nullptr);
textures_.erase(it);
return;
}
}
}
const Imported *Find(uint64_t h) const {
for (auto &t : textures_) if (t.handle == h) return &t;
return nullptr;
}
static VkImageMemoryBarrier Barrier(VkImage img, VkImageLayout from, VkImageLayout to, VkAccessFlags src, VkAccessFlags dst,
uint32_t srcQ = VK_QUEUE_FAMILY_IGNORED, uint32_t dstQ = VK_QUEUE_FAMILY_IGNORED) {
VkImageMemoryBarrier b = {VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, nullptr, src, dst, from, to, srcQ, dstQ, img,
{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
return b;
}
bool Draw(const EyeFrame &f) {
const Imported *eye[2] = {Find(f.texture[0]), Find(f.texture[1])};
if (!eye[0] || !eye[1]) return false;
vk_.WaitForFences(dev_, 1, &fence_, VK_TRUE, UINT64_MAX);
uint32_t idx = 0;
VkResult r = vk_.AcquireNextImageKHR(dev_, swapchain_, 100000000ull, acquired_, VK_NULL_HANDLE, &idx);
if (r != VK_SUCCESS && r != VK_SUBOPTIMAL_KHR) {
static int said;
if (said++ < 3) Log("presenter: acquire %d", r);
return false;
}
vk_.ResetFences(dev_, 1, &fence_);
vk_.ResetCommandBuffer(cmd_, 0);
VkCommandBufferBeginInfo bi = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, nullptr, VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
vk_.BeginCommandBuffer(cmd_, &bi);
VkImage dst = images_[idx];
// The eye textures come from SteamVR's compositor (another process): take them from the external
// queue family as they are (GENERAL keeps the contents; they are uncompressed).
VkImageMemoryBarrier pre[3] = {
Barrier(dst, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0, VK_ACCESS_TRANSFER_WRITE_BIT),
Barrier(eye[0]->image, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL, 0, VK_ACCESS_TRANSFER_READ_BIT,
VK_QUEUE_FAMILY_EXTERNAL, qfam_),
Barrier(eye[1]->image, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL, 0, VK_ACCESS_TRANSFER_READ_BIT,
VK_QUEUE_FAMILY_EXTERNAL, qfam_)};
vk_.CmdPipelineBarrier(cmd_, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr,
eye[0] == eye[1] ? 2 : 3, pre);
VkClearColorValue black = {{0, 0, 0, 1}};
VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
vk_.CmdClearColorImage(cmd_, dst, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &black, 1, &range);
VkMemoryBarrier mb = {VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT};
vk_.CmdPipelineBarrier(cmd_, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &mb, 0, nullptr, 0, nullptr);
const int32_t half = (int32_t)extent_.width / 2;
for (int e = 0; e < 2; e++) {
const float *b = f.bounds[e];
VkImageBlit blit = {};
blit.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
blit.srcOffsets[0] = {(int32_t)(b[0] * eye[e]->width), (int32_t)(b[1] * eye[e]->height), 0};
blit.srcOffsets[1] = {(int32_t)(b[2] * eye[e]->width), (int32_t)(b[3] * eye[e]->height), 1};
blit.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
blit.dstOffsets[0] = {e * half, 0, 0};
blit.dstOffsets[1] = {e * half + half, (int32_t)extent_.height, 1};
vk_.CmdBlitImage(cmd_, eye[e]->image, VK_IMAGE_LAYOUT_GENERAL, dst, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit,
VK_FILTER_LINEAR);
}
VkImageMemoryBarrier post[3] = {
Barrier(dst, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, VK_ACCESS_TRANSFER_WRITE_BIT, 0),
Barrier(eye[0]->image, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL, VK_ACCESS_TRANSFER_READ_BIT, 0, qfam_,
VK_QUEUE_FAMILY_EXTERNAL),
Barrier(eye[1]->image, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL, VK_ACCESS_TRANSFER_READ_BIT, 0, qfam_,
VK_QUEUE_FAMILY_EXTERNAL)};
vk_.CmdPipelineBarrier(cmd_, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, nullptr, 0, nullptr,
eye[0] == eye[1] ? 2 : 3, post);
vk_.EndCommandBuffer(cmd_);
VkPipelineStageFlags wait = VK_PIPELINE_STAGE_TRANSFER_BIT;
VkSubmitInfo si = {VK_STRUCTURE_TYPE_SUBMIT_INFO, nullptr, 1, &acquired_, &wait, 1, &cmd_, 1, &rendered_};
if ((r = vk_.QueueSubmit(queue_, 1, &si, fence_)) != VK_SUCCESS) { Log("presenter: submit %d", r); return false; }
VkPresentInfoKHR pi = {VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, nullptr, 1, &rendered_, 1, &swapchain_, &idx, nullptr};
r = vk_.QueuePresentKHR(queue_, &pi);
if (r != VK_SUCCESS && r != VK_SUBOPTIMAL_KHR) {
static int said;
if (said++ < 3) Log("presenter: present %d", r);
}
return true;
}
std::mutex mutex_;
std::condition_variable cv_;
std::vector<PendingImport> pending_;
std::vector<uint64_t> removals_;
EyeFrame frame_{};
std::chrono::steady_clock::time_point frameAt_{};
bool haveFrame_ = false, exit_ = false, started_ = false;
std::atomic<uint64_t> submitted_{0};
std::thread thread_;
X11 x_;
Display *dpy_ = nullptr;
Window win_ = 0;
uint32_t width_ = 0, height_ = 0;
Vk vk_;
VkInstance inst_ = VK_NULL_HANDLE;
VkPhysicalDevice pd_ = VK_NULL_HANDLE;
VkPhysicalDeviceMemoryProperties mem_{};
VkSurfaceKHR surface_ = VK_NULL_HANDLE;
uint32_t qfam_ = 0;
VkDevice dev_ = VK_NULL_HANDLE;
VkQueue queue_ = VK_NULL_HANDLE;
VkCommandPool pool_ = VK_NULL_HANDLE;
VkCommandBuffer cmd_ = VK_NULL_HANDLE;
VkFence fence_ = VK_NULL_HANDLE;
VkSemaphore acquired_ = VK_NULL_HANDLE, rendered_ = VK_NULL_HANDLE;
VkSwapchainKHR swapchain_ = VK_NULL_HANDLE;
VkExtent2D extent_{};
std::vector<VkImage> images_;
std::vector<Imported> textures_;
};
} // namespace
void Presenter::AddTextures(const uint64_t h[3], const int fds[3], uint32_t f, uint32_t w, uint32_t hh) { Impl::Get().Add(h, fds, f, w, hh); }
void Presenter::RemoveTexture(uint64_t h) { Impl::Get().Remove(h); }
void Presenter::Submit(const EyeFrame &f) { Impl::Get().Submit(f); }
void Presenter::Shutdown() { Impl::Get().Shutdown(); }
} // namespace droiddeck
+34
View File
@@ -0,0 +1,34 @@
// Puts SteamVR's eye textures on the screen for the Cardboard driver (driver_droiddeck.cpp).
//
// The driver-direct component hands each frame over as two eye textures: shared Vulkan images,
// dmabufs on Linux. The presenter imports them into a Vulkan device of its own and draws them side by
// side into a fullscreen X11 window on gamescope's Xwayland, marked as an external overlay so gamescope
// shows it above whatever app has focus. DroidDeck's compositor, in Cardboard mode with a
// side-by-side source, then puts the lens distortion on it for the viewer.
//
// SteamVR compositor -> eye textures -> [presenter: blit L|R] -> X11 overlay -> gamescope
// -> DroidDeck compositor -> Cardboard lens pass -> panel
//
// Everything is loaded at runtime (libvulkan.so.1, libX11.so.6): the driver links against nothing
// the cross build image lacks.
#pragma once
#include <cstdint>
namespace droiddeck {
struct EyeFrame {
uint64_t texture[2]; // SharedTextureHandle_t per eye
float bounds[2][4]; // uMin, vMin, uMax, vMax per eye
};
class Presenter {
public:
// Called from CreateSwapTextureSet: the three images of one set, as SteamVR made them.
static void AddTextures(const uint64_t handles[3], const int fds[3], uint32_t vkFormat, uint32_t width, uint32_t height);
static void RemoveTexture(uint64_t handle);
// Called from Present: the frame's eye textures; returns at once (a thread of its own presents).
static void Submit(const EyeFrame &frame);
static void Shutdown();
};
} // namespace droiddeck
File diff suppressed because it is too large. Load diff
+34
View File
@@ -0,0 +1,34 @@
/* Link-time stand-in for libwayland-client.so.0 (tools/vr/build.sh): the symbols the presenter uses, so
* the driver links with -z defs against a library the build machine does not have. Never loaded: the
* runtime's real libwayland-client.so.0 satisfies the dependency on the device. */
#include <stdint.h>
#include <stddef.h>
#include "wayland-util.h"
struct wl_display;
struct wl_proxy;
struct wl_event_queue;
struct wl_display *wl_display_connect(const char *name) { return NULL; }
void wl_display_disconnect(struct wl_display *d) {}
int wl_display_roundtrip(struct wl_display *d) { return -1; }
int wl_display_dispatch(struct wl_display *d) { return -1; }
int wl_display_dispatch_pending(struct wl_display *d) { return -1; }
int wl_display_flush(struct wl_display *d) { return -1; }
int wl_display_get_error(struct wl_display *d) { return 0; }
struct wl_proxy *wl_proxy_marshal_flags(struct wl_proxy *p, uint32_t opcode, const struct wl_interface *i, uint32_t v,
uint32_t flags, ...) { return NULL; }
int wl_proxy_add_listener(struct wl_proxy *p, void (**impl)(void), void *data) { return -1; }
uint32_t wl_proxy_get_version(struct wl_proxy *p) { return 0; }
void wl_proxy_destroy(struct wl_proxy *p) {}
void wl_proxy_set_user_data(struct wl_proxy *p, void *d) {}
void *wl_proxy_get_user_data(struct wl_proxy *p) { return NULL; }
const struct wl_interface wl_registry_interface;
const struct wl_interface wl_compositor_interface;
const struct wl_interface wl_surface_interface;
const struct wl_interface wl_output_interface;
const struct wl_interface wl_seat_interface;
const struct wl_interface wl_callback_interface;
const struct wl_interface wl_region_interface;
const struct wl_interface wl_buffer_interface;
+4
View File
@@ -0,0 +1,4 @@
Wayland client headers (MIT, wayland 1.26.0, from the runtime's Arch Linux ARM package) for the SteamVR
driver's presenter (tools/vr/src/presenter.cpp). `src/wayland_client_stub.c` is only linked against at
build time, so the driver gets a `libwayland-client.so.0` dependency without the build needing the guest's
library; the runtime's real one is used on the device.
+330
View File
@@ -0,0 +1,330 @@
/*
* Copyright © 2008 Kristian Høgsberg
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef WAYLAND_CLIENT_CORE_H
#define WAYLAND_CLIENT_CORE_H
#include <stdint.h>
#include "wayland-util.h"
#include "wayland-version.h"
#ifdef __cplusplus
extern "C" {
#endif
struct timespec;
/** \class wl_proxy
*
* \brief Represents a protocol object on the client side.
*
* A wl_proxy acts as a client side proxy to an object existing in the
* compositor. The proxy is responsible for converting requests made by the
* clients with \ref wl_proxy_marshal() into Wayland's wire format. Events
* coming from the compositor are also handled by the proxy, which will in
* turn call the handler set with \ref wl_proxy_add_listener().
*
* \note With the exception of function \ref wl_proxy_set_queue(), functions
* accessing a wl_proxy are not normally used by client code. Clients
* should normally use the higher level interface generated by the scanner to
* interact with compositor objects.
*
*/
struct wl_proxy;
/** \class wl_display
*
* \brief Represents a connection to the compositor and acts as a proxy to
* the wl_display singleton object.
*
* A wl_display object represents a client connection to a Wayland
* compositor. It is created with either \ref wl_display_connect() or
* \ref wl_display_connect_to_fd(). A connection is terminated using
* \ref wl_display_disconnect().
*
* A wl_display is also used as the \ref wl_proxy for the wl_display
* singleton object on the compositor side.
*
* A wl_display object handles all the data sent from and to the
* compositor. When a \ref wl_proxy marshals a request, it will write its wire
* representation to the display's write buffer. The data is sent to the
* compositor when the client calls \ref wl_display_flush().
*
* Incoming data is handled in two steps: queueing and dispatching. In the
* queue step, the data coming from the display fd is interpreted and
* added to a queue. On the dispatch step, the handler for the incoming
* event set by the client on the corresponding \ref wl_proxy is called.
*
* A wl_display has at least one event queue, called the <em>default
* queue</em>. Clients can create additional event queues with \ref
* wl_display_create_queue() and assign \ref wl_proxy's to it. Events
* occurring in a particular proxy are always queued in its assigned queue.
* A client can ensure that a certain assumption, such as holding a lock
* or running from a given thread, is true when a proxy event handler is
* called by assigning that proxy to an event queue and making sure that
* this queue is only dispatched when the assumption holds.
*
* The default queue is dispatched by calling \ref wl_display_dispatch().
* This will dispatch any events queued on the default queue and attempt
* to read from the display fd if it's empty. Events read are then queued
* on the appropriate queues according to the proxy assignment.
*
* A user created queue is dispatched with \ref wl_display_dispatch_queue().
* This function behaves exactly the same as wl_display_dispatch()
* but it dispatches given queue instead of the default queue.
*
* A real world example of event queue usage is Mesa's implementation of
* eglSwapBuffers() for the Wayland platform. This function might need
* to block until a frame callback is received, but dispatching the default
* queue could cause an event handler on the client to start drawing
* again. This problem is solved using another event queue, so that only
* the events handled by the EGL code are dispatched during the block.
*
* This creates a problem where a thread dispatches a non-default
* queue, reading all the data from the display fd. If the application
* would call \em poll(2) after that it would block, even though there
* might be events queued on the default queue. Those events should be
* dispatched with \ref wl_display_dispatch_pending() or \ref
* wl_display_dispatch_queue_pending() before flushing and blocking.
*/
struct wl_display;
/** \class wl_event_queue
*
* \brief A queue for \ref wl_proxy object events.
*
* Event queues allows the events on a display to be handled in a thread-safe
* manner. See \ref wl_display for details.
*
*/
struct wl_event_queue;
/** Destroy proxy after marshalling
* \relates wl_proxy
*/
#define WL_MARSHAL_FLAG_DESTROY (1 << 0)
void
wl_event_queue_destroy(struct wl_event_queue *queue);
struct wl_proxy *
wl_proxy_marshal_flags(struct wl_proxy *proxy, uint32_t opcode,
const struct wl_interface *interface,
uint32_t version,
uint32_t flags, ...);
struct wl_proxy *
wl_proxy_marshal_array_flags(struct wl_proxy *proxy, uint32_t opcode,
const struct wl_interface *interface,
uint32_t version,
uint32_t flags,
union wl_argument *args);
void
wl_proxy_marshal(struct wl_proxy *p, uint32_t opcode, ...);
void
wl_proxy_marshal_array(struct wl_proxy *p, uint32_t opcode,
union wl_argument *args);
struct wl_proxy *
wl_proxy_create(struct wl_proxy *factory,
const struct wl_interface *interface);
void *
wl_proxy_create_wrapper(void *proxy);
void
wl_proxy_wrapper_destroy(void *proxy_wrapper);
struct wl_proxy *
wl_proxy_marshal_constructor(struct wl_proxy *proxy,
uint32_t opcode,
const struct wl_interface *interface,
...);
struct wl_proxy *
wl_proxy_marshal_constructor_versioned(struct wl_proxy *proxy,
uint32_t opcode,
const struct wl_interface *interface,
uint32_t version,
...);
struct wl_proxy *
wl_proxy_marshal_array_constructor(struct wl_proxy *proxy,
uint32_t opcode, union wl_argument *args,
const struct wl_interface *interface);
struct wl_proxy *
wl_proxy_marshal_array_constructor_versioned(struct wl_proxy *proxy,
uint32_t opcode,
union wl_argument *args,
const struct wl_interface *interface,
uint32_t version);
void
wl_proxy_destroy(struct wl_proxy *proxy);
int
wl_proxy_add_listener(struct wl_proxy *proxy,
void (**implementation)(void), void *data);
const void *
wl_proxy_get_listener(struct wl_proxy *proxy);
int
wl_proxy_add_dispatcher(struct wl_proxy *proxy,
wl_dispatcher_func_t dispatcher_func,
const void * dispatcher_data, void *data);
void
wl_proxy_set_user_data(struct wl_proxy *proxy, void *user_data);
void *
wl_proxy_get_user_data(struct wl_proxy *proxy);
uint32_t
wl_proxy_get_version(struct wl_proxy *proxy);
uint32_t
wl_proxy_get_id(struct wl_proxy *proxy);
void
wl_proxy_set_tag(struct wl_proxy *proxy,
const char * const *tag);
const char * const *
wl_proxy_get_tag(struct wl_proxy *proxy);
const char *
wl_proxy_get_class(struct wl_proxy *proxy);
const struct wl_interface *
wl_proxy_get_interface(struct wl_proxy *proxy);
struct wl_display *
wl_proxy_get_display(struct wl_proxy *proxy);
void
wl_proxy_set_queue(struct wl_proxy *proxy, struct wl_event_queue *queue);
struct wl_event_queue *
wl_proxy_get_queue(const struct wl_proxy *proxy);
const char *
wl_event_queue_get_name(const struct wl_event_queue *queue);
struct wl_display *
wl_display_connect(const char *name);
struct wl_display *
wl_display_connect_to_fd(int fd);
void
wl_display_disconnect(struct wl_display *display);
int
wl_display_get_fd(struct wl_display *display);
int
wl_display_dispatch(struct wl_display *display);
int
wl_display_dispatch_queue(struct wl_display *display,
struct wl_event_queue *queue);
int
wl_display_dispatch_timeout(struct wl_display *display,
const struct timespec *timeout);
int
wl_display_dispatch_queue_timeout(struct wl_display *display,
struct wl_event_queue *queue,
const struct timespec *timeout);
int
wl_display_dispatch_queue_pending(struct wl_display *display,
struct wl_event_queue *queue);
int
wl_display_dispatch_queue_pending_single(struct wl_display *display,
struct wl_event_queue *queue);
int
wl_display_dispatch_pending(struct wl_display *display);
int
wl_display_dispatch_pending_single(struct wl_display *display);
int
wl_display_get_error(struct wl_display *display);
uint32_t
wl_display_get_protocol_error(struct wl_display *display,
const struct wl_interface **interface,
uint32_t *id);
int
wl_display_flush(struct wl_display *display);
int
wl_display_roundtrip_queue(struct wl_display *display,
struct wl_event_queue *queue);
int
wl_display_roundtrip(struct wl_display *display);
struct wl_event_queue *
wl_display_create_queue(struct wl_display *display);
struct wl_event_queue *
wl_display_create_queue_with_name(struct wl_display *display,
const char *name);
int
wl_display_prepare_read_queue(struct wl_display *display,
struct wl_event_queue *queue);
int
wl_display_prepare_read(struct wl_display *display);
void
wl_display_cancel_read(struct wl_display *display);
int
wl_display_read_events(struct wl_display *display);
void
wl_log_set_handler_client(wl_log_func_t handler);
void
wl_display_set_max_buffer_size(struct wl_display *display,
size_t max_buffer_size);
#ifdef __cplusplus
}
#endif
#endif
File diff suppressed because it is too large. Load diff
+42
View File
@@ -0,0 +1,42 @@
/*
* Copyright © 2008 Kristian Høgsberg
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/** \file
*
* \brief Include the client API and protocol C API.
*
* \warning Use of this header file is discouraged. Prefer including
* wayland-client-core.h instead, which does not include the
* client protocol header and as such only defines the library
* API.
*/
#ifndef WAYLAND_CLIENT_H
#define WAYLAND_CLIENT_H
#include "wayland-client-core.h"
#include "wayland-client-protocol.h"
#endif
+768
View File
@@ -0,0 +1,768 @@
/*
* Copyright © 2008 Kristian Høgsberg
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/** \file wayland-util.h
*
* \brief Utility classes, functions, and macros.
*/
#ifndef WAYLAND_UTIL_H
#define WAYLAND_UTIL_H
#include <math.h>
#include <stddef.h>
#include <inttypes.h>
#include <stdarg.h>
#ifdef __cplusplus
extern "C" {
#endif
/** Visibility attribute */
#if defined(__GNUC__) && __GNUC__ >= 4
#define WL_EXPORT __attribute__ ((visibility("default")))
#else
#define WL_EXPORT
#endif
/** Deprecated attribute */
#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L) || (defined(__cplusplus) && __cplusplus >= 201402L)
#define WL_DEPRECATED [[deprecated]]
#elif defined(__GNUC__) && __GNUC__ >= 4
#define WL_DEPRECATED __attribute__ ((deprecated))
#else
#define WL_DEPRECATED
#endif
/**
* Printf-style argument attribute
*
* \param x Ordinality of the format string argument
* \param y Ordinality of the argument to check against the format string
*
* \sa https://gcc.gnu.org/onlinedocs/gcc-3.2.1/gcc/Function-Attributes.html
*/
#if defined(__GNUC__) && __GNUC__ >= 4
#define WL_PRINTF(x, y) __attribute__((__format__(__printf__, x, y)))
#else
#define WL_PRINTF(x, y)
#endif
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L
#define WL_TYPEOF(expr) typeof(expr)
#else
#define WL_TYPEOF(expr) __typeof__(expr)
#endif
/** \class wl_object
*
* \brief A protocol object.
*
* A `wl_object` is an opaque struct identifying the protocol object
* underlying a `wl_proxy` or `wl_resource`.
*
* \note Functions accessing a `wl_object` are not normally used by client code.
* Clients should normally use the higher level interface generated by the
* scanner to interact with compositor objects.
*
*/
struct wl_object;
/**
* The maximum size of a protocol message.
*
* If a message size exceeds this value, the connection will be dropped.
* Servers will send an invalid_method error before disconnecting.
*/
#define WL_MAX_MESSAGE_SIZE 4096
/**
* Protocol message signature
*
* A wl_message describes the signature of an actual protocol message, such as a
* request or event, that adheres to the Wayland protocol wire format. The
* protocol implementation uses a wl_message within its demarshal machinery for
* decoding messages between a compositor and its clients. In a sense, a
* wl_message is to a protocol message like a class is to an object.
*
* The `name` of a wl_message is the name of the corresponding protocol message.
*
* The `signature` is an ordered list of symbols representing the data types
* of message arguments and, optionally, a protocol version and indicators for
* nullability. A leading integer in the `signature` indicates the _since_
* version of the protocol message. A `?` preceding a data type symbol indicates
* that the following argument type is nullable. While it is a protocol violation
* to send messages with non-nullable arguments set to `NULL`, event handlers in
* clients might still get called with non-nullable object arguments set to
* `NULL`. This can happen when the client destroyed the object being used as
* argument on its side and an event referencing that object was sent before the
* server knew about its destruction. As this race cannot be prevented, clients
* should - as a general rule - program their event handlers such that they can
* handle object arguments declared non-nullable being `NULL` gracefully.
*
* When no arguments accompany a message, `signature` is an empty string.
*
* Symbols:
*
* * `i`: int
* * `u`: uint
* * `f`: fixed
* * `s`: string
* * `o`: object
* * `n`: new_id
* * `a`: array
* * `h`: fd
* * `?`: following argument (`o` or `s`) is nullable
*
* While demarshaling primitive arguments is straightforward, when demarshaling
* messages containing `object` or `new_id` arguments, the protocol
* implementation often must determine the type of the object. The `types` of a
* wl_message is an array of wl_interface references that correspond to `o` and
* `n` arguments in `signature`, with `NULL` placeholders for arguments with
* non-object types.
*
* Consider the protocol event wl_display `delete_id` that has a single `uint`
* argument. The wl_message is:
*
* \code
* { "delete_id", "u", [NULL] }
* \endcode
*
* Here, the message `name` is `"delete_id"`, the `signature` is `"u"`, and the
* argument `types` is `[NULL]`, indicating that the `uint` argument has no
* corresponding wl_interface since it is a primitive argument.
*
* In contrast, consider a `wl_foo` interface supporting protocol request `bar`
* that has existed since version 2, and has two arguments: a `uint` and an
* object of type `wl_baz_interface` that may be `NULL`. Such a `wl_message`
* might be:
*
* \code
* { "bar", "2u?o", [NULL, &wl_baz_interface] }
* \endcode
*
* Here, the message `name` is `"bar"`, and the `signature` is `"2u?o"`. Notice
* how the `2` indicates the protocol version, the `u` indicates the first
* argument type is `uint`, and the `?o` indicates that the second argument
* is an object that may be `NULL`. Lastly, the argument `types` array indicates
* that no wl_interface corresponds to the first argument, while the type
* `wl_baz_interface` corresponds to the second argument.
*
* \sa wl_argument
* \sa wl_interface
* \sa <a href="https://wayland.freedesktop.org/docs/html/ch04.html#sect-Protocol-Wire-Format">Wire Format</a>
*/
struct wl_message {
/** Message name */
const char *name;
/** Message signature */
const char *signature;
/** Object argument interfaces */
const struct wl_interface **types;
};
/**
* Protocol object interface
*
* A wl_interface describes the API of a protocol object defined in the Wayland
* protocol specification. The protocol implementation uses a wl_interface
* within its marshalling machinery for encoding client requests.
*
* The `name` of a wl_interface is the name of the corresponding protocol
* interface, and `version` represents the version of the interface. The members
* `method_count` and `event_count` represent the number of `methods` (requests)
* and `events` in the respective wl_message members.
*
* For example, consider a protocol interface `foo`, marked as version `1`, with
* two requests and one event.
*
* \code{.xml}
* <interface name="foo" version="1">
* <request name="a"></request>
* <request name="b"></request>
* <event name="c"></event>
* </interface>
* \endcode
*
* Given two wl_message arrays `foo_requests` and `foo_events`, a wl_interface
* for `foo` might be:
*
* \code
* struct wl_interface foo_interface = {
* "foo", 1,
* 2, foo_requests,
* 1, foo_events
* };
* \endcode
*
* \note The server side of the protocol may define interface <em>implementation
* types</em> that incorporate the term `interface` in their name. Take
* care to not confuse these server-side `struct`s with a wl_interface
* variable whose name also ends in `interface`. For example, while the
* server may define a type `struct wl_foo_interface`, the client may
* define a `struct wl_interface wl_foo_interface`.
*
* \sa wl_message
* \sa wl_proxy
* \sa <a href="https://wayland.freedesktop.org/docs/html/ch04.html#sect-Protocol-Interfaces">Interfaces</a>
* \sa <a href="https://wayland.freedesktop.org/docs/html/ch04.html#sect-Protocol-Versioning">Versioning</a>
*/
struct wl_interface {
/** Interface name */
const char *name;
/** Interface version */
int version;
/** Number of methods (requests) */
int method_count;
/** Method (request) signatures */
const struct wl_message *methods;
/** Number of events */
int event_count;
/** Event signatures */
const struct wl_message *events;
};
/** \class wl_list
*
* \brief Doubly-linked list
*
* On its own, an instance of `struct wl_list` represents the sentinel head of
* a doubly-linked list, and must be initialized using wl_list_init().
* When empty, the list head's `next` and `prev` members point to the list head
* itself, otherwise `next` references the first element in the list, and `prev`
* refers to the last element in the list.
*
* Use the `struct wl_list` type to represent both the list head and the links
* between elements within the list. Use wl_list_empty() to determine if the
* list is empty in O(1).
*
* All elements in the list must be of the same type. The element type must have
* a `struct wl_list` member, often named `link` by convention. Prior to
* insertion, there is no need to initialize an element's `link` - invoking
* wl_list_init() on an individual list element's `struct wl_list` member is
* unnecessary if the very next operation is wl_list_insert(). However, a
* common idiom is to initialize an element's `link` prior to removal - ensure
* safety by invoking wl_list_init() before wl_list_remove().
*
* Consider a list reference `struct wl_list foo_list`, an element type as
* `struct element`, and an element's link member as `struct wl_list link`.
*
* The following code initializes a list and adds three elements to it.
*
* \code
* struct wl_list foo_list;
*
* struct element {
* int foo;
* struct wl_list link;
* };
* struct element e1, e2, e3;
*
* wl_list_init(&foo_list);
* wl_list_insert(&foo_list, &e1.link); // e1 is the first element
* wl_list_insert(&foo_list, &e2.link); // e2 is now the first element
* wl_list_insert(&e2.link, &e3.link); // insert e3 after e2
* \endcode
*
* The list now looks like <em>[e2, e3, e1]</em>.
*
* The `wl_list` API provides some iterator macros. For example, to iterate
* a list in ascending order:
*
* \code
* struct element *e;
* wl_list_for_each(e, foo_list, link) {
* do_something_with_element(e);
* }
* \endcode
*
* See the documentation of each iterator for details.
* \sa http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/include/linux/list.h
*/
struct wl_list {
/** Previous list element */
struct wl_list *prev;
/** Next list element */
struct wl_list *next;
};
/**
* Initializes the list.
*
* \param list List to initialize
*
* \memberof wl_list
*/
void
wl_list_init(struct wl_list *list);
/**
* Inserts an element into the list, after the element represented by \p list.
* When \p list is a reference to the list itself (the head), set the containing
* struct of \p elm as the first element in the list.
*
* \note If \p elm is already part of a list, inserting it again will lead to
* list corruption.
*
* \param list List element after which the new element is inserted
* \param elm Link of the containing struct to insert into the list
*
* \memberof wl_list
*/
void
wl_list_insert(struct wl_list *list, struct wl_list *elm);
/**
* Removes an element from the list.
*
* \note This operation leaves \p elm in an invalid state.
*
* \param elm Link of the containing struct to remove from the list
*
* \memberof wl_list
*/
void
wl_list_remove(struct wl_list *elm);
/**
* Determines the length of the list.
*
* \note This is an O(n) operation.
*
* \param list List whose length is to be determined
*
* \return Number of elements in the list
*
* \memberof wl_list
*/
int
wl_list_length(const struct wl_list *list);
/**
* Determines if the list is empty.
*
* \param list List whose emptiness is to be determined
*
* \return 1 if empty, or 0 if not empty
*
* \memberof wl_list
*/
int
wl_list_empty(const struct wl_list *list);
/**
* Inserts all of the elements of one list into another, after the element
* represented by \p list.
*
* \note This leaves \p other in an invalid state.
*
* \param list List element after which the other list elements will be inserted
* \param other List of elements to insert
*
* \memberof wl_list
*/
void
wl_list_insert_list(struct wl_list *list, struct wl_list *other);
/**
* Retrieves a pointer to a containing struct, given a member name.
*
* This macro allows "conversion" from a pointer to a member to its containing
* struct. This is useful if you have a contained item like a wl_list,
* wl_listener, or wl_signal, provided via a callback or other means, and would
* like to retrieve the struct that contains it.
*
* To demonstrate, the following example retrieves a pointer to
* `example_container` given only its `destroy_listener` member:
*
* \code
* struct example_container {
* struct wl_listener destroy_listener;
* // other members...
* };
*
* void example_container_destroy(struct wl_listener *listener, void *data)
* {
* struct example_container *ctr;
*
* ctr = wl_container_of(listener, ctr, destroy_listener);
* // destroy ctr...
* }
* \endcode
*
* \note `sample` need not be a valid pointer. A null or uninitialised pointer
* is sufficient.
*
* \param ptr Valid pointer to the contained member
* \param sample Pointer to a struct whose type contains \p ptr
* \param member Named location of \p ptr within the \p sample type
*
* \return The container for the specified pointer
*/
#define wl_container_of(ptr, sample, member) \
(WL_TYPEOF(sample))((char *)(ptr) - \
offsetof(WL_TYPEOF(*sample), member))
/**
* Iterates over a list.
*
* This macro expresses a for-each iterator for wl_list. Given a list and
* wl_list link member name (often named `link` by convention), this macro
* assigns each element in the list to \p pos, which can then be referenced in
* a trailing code block. For example, given a wl_list of `struct message`
* elements:
*
* \code
* struct message {
* char *contents;
* wl_list link;
* };
*
* struct wl_list *message_list;
* // Assume message_list now "contains" many messages
*
* struct message *m;
* wl_list_for_each(m, message_list, link) {
* do_something_with_message(m);
* }
* \endcode
*
* \param pos Cursor that each list element will be assigned to
* \param head Head of the list to iterate over
* \param member Name of the link member within the element struct
*
* \relates wl_list
*/
#define wl_list_for_each(pos, head, member) \
for (pos = wl_container_of((head)->next, pos, member); \
&pos->member != (head); \
pos = wl_container_of(pos->member.next, pos, member))
/**
* Iterates over a list, safe against removal of the list element.
*
* \note Only removal of the current element, \p pos, is safe. Removing
* any other element during traversal may lead to a loop malfunction.
*
* \sa wl_list_for_each()
*
* \param pos Cursor that each list element will be assigned to
* \param tmp Temporary pointer of the same type as \p pos
* \param head Head of the list to iterate over
* \param member Name of the link member within the element struct
*
* \relates wl_list
*/
#define wl_list_for_each_safe(pos, tmp, head, member) \
for (pos = wl_container_of((head)->next, pos, member), \
tmp = wl_container_of((pos)->member.next, tmp, member); \
&pos->member != (head); \
pos = tmp, \
tmp = wl_container_of(pos->member.next, tmp, member))
/**
* Iterates backwards over a list.
*
* \sa wl_list_for_each()
*
* \param pos Cursor that each list element will be assigned to
* \param head Head of the list to iterate over
* \param member Name of the link member within the element struct
*
* \relates wl_list
*/
#define wl_list_for_each_reverse(pos, head, member) \
for (pos = wl_container_of((head)->prev, pos, member); \
&pos->member != (head); \
pos = wl_container_of(pos->member.prev, pos, member))
/**
* Iterates backwards over a list, safe against removal of the list element.
*
* \note Only removal of the current element, \p pos, is safe. Removing
* any other element during traversal may lead to a loop malfunction.
*
* \sa wl_list_for_each()
*
* \param pos Cursor that each list element will be assigned to
* \param tmp Temporary pointer of the same type as \p pos
* \param head Head of the list to iterate over
* \param member Name of the link member within the element struct
*
* \relates wl_list
*/
#define wl_list_for_each_reverse_safe(pos, tmp, head, member) \
for (pos = wl_container_of((head)->prev, pos, member), \
tmp = wl_container_of((pos)->member.prev, tmp, member); \
&pos->member != (head); \
pos = tmp, \
tmp = wl_container_of(pos->member.prev, tmp, member))
/**
* \class wl_array
*
* Dynamic array
*
* A wl_array is a dynamic array that can only grow until released. It is
* intended for relatively small allocations whose size is variable or not known
* in advance. While construction of a wl_array does not require all elements to
* be of the same size, wl_array_for_each() does require all elements to have
* the same type and size.
*
*/
struct wl_array {
/** Array size */
size_t size;
/** Allocated space */
size_t alloc;
/** Array data */
void *data;
};
/**
* Initializes the array.
*
* \param array Array to initialize
*
* \memberof wl_array
*/
void
wl_array_init(struct wl_array *array);
/**
* Releases the array data.
*
* \note Leaves the array in an invalid state.
*
* \param array Array whose data is to be released
*
* \memberof wl_array
*/
void
wl_array_release(struct wl_array *array);
/**
* Increases the size of the array by \p size bytes.
*
* \param array Array whose size is to be increased
* \param size Number of bytes to increase the size of the array by
*
* \return A pointer to the beginning of the newly appended space, or NULL when
* resizing fails.
*
* \memberof wl_array
*/
void *
wl_array_add(struct wl_array *array, size_t size);
/**
* Copies the contents of \p source to \p array.
*
* \param array Destination array to copy to
* \param source Source array to copy from
*
* \return 0 on success, or -1 on failure
*
* \memberof wl_array
*/
int
wl_array_copy(struct wl_array *array, struct wl_array *source);
/**
* Iterates over an array.
*
* This macro expresses a for-each iterator for wl_array. It assigns each
* element in the array to \p pos, which can then be referenced in a trailing
* code block. \p pos must be a pointer to the array element type, and all
* array elements must be of the same type and size.
*
* \param pos Cursor that each array element will be assigned to
* \param array Array to iterate over
*
* \relates wl_array
* \sa wl_list_for_each()
*/
#define wl_array_for_each(pos, array) \
for (pos = (array)->data; \
(array)->size != 0 && \
(const char *) pos < ((const char *) (array)->data + (array)->size); \
(pos)++)
/**
* Fixed-point number
*
* A `wl_fixed_t` is a 24.8 signed fixed-point number with a sign bit, 23 bits
* of integer precision and 8 bits of decimal precision. Consider `wl_fixed_t`
* as an opaque struct with methods that facilitate conversion to and from
* `double` and `int` types.
*/
typedef int32_t wl_fixed_t;
/**
* Converts a fixed-point number to a floating-point number.
*
* \param f Fixed-point number to convert
*
* \return Floating-point representation of the fixed-point argument
*/
static inline double
wl_fixed_to_double(wl_fixed_t f)
{
return f / 256.0;
}
/**
* Converts a floating-point number to a fixed-point number.
*
* \param d Floating-point number to convert
*
* \return Fixed-point representation of the floating-point argument
*/
static inline wl_fixed_t
wl_fixed_from_double(double d)
{
return (wl_fixed_t) (round(d * 256.0));
}
/**
* Converts a fixed-point number to an integer.
*
* \param f Fixed-point number to convert
*
* \return Integer component of the fixed-point argument
*/
static inline int
wl_fixed_to_int(wl_fixed_t f)
{
return f / 256;
}
/**
* Converts an integer to a fixed-point number.
*
* \param i Integer to convert
*
* \return Fixed-point representation of the integer argument
*/
static inline wl_fixed_t
wl_fixed_from_int(int i)
{
return i * 256;
}
/**
* Protocol message argument data types
*
* This union represents all of the argument types in the Wayland protocol wire
* format. The protocol implementation uses wl_argument within its marshalling
* machinery for dispatching messages between a client and a compositor.
*
* \sa wl_message
* \sa wl_interface
* \sa <a href="https://wayland.freedesktop.org/docs/html/ch04.html#sect-Protocol-wire-Format">Wire Format</a>
*/
union wl_argument {
int32_t i; /**< `int` */
uint32_t u; /**< `uint` */
wl_fixed_t f; /**< `fixed` */
const char *s; /**< `string` */
struct wl_object *o; /**< `object` */
uint32_t n; /**< `new_id` */
struct wl_array *a; /**< `array` */
int32_t h; /**< `fd` */
};
/**
* Dispatcher function type alias
*
* A dispatcher is a function that handles the emitting of callbacks in client
* code. For programs directly using the C library, this is done by using
* libffi to call function pointers. When binding to languages other than C,
* dispatchers provide a way to abstract the function calling process to be
* friendlier to other function calling systems.
*
* A dispatcher takes five arguments: The first is the dispatcher-specific
* implementation associated with the target object. The second is the object
* upon which the callback is being invoked (either wl_proxy or wl_resource).
* The third and fourth arguments are the opcode and the wl_message
* corresponding to the callback. The final argument is an array of arguments
* received from the other process via the wire protocol.
*
* \param user_data Dispatcher-specific implementation data
* \param target Callback invocation target (wl_proxy or `wl_resource`)
* \param opcode Callback opcode
* \param msg Callback message signature
* \param args Array of received arguments
*
* \return 0 on success, or -1 on failure
*/
typedef int (*wl_dispatcher_func_t)(const void *user_data, void *target,
uint32_t opcode, const struct wl_message *msg,
union wl_argument *args);
/**
* Log function type alias
*
* The C implementation of the Wayland protocol abstracts the details of
* logging. Users may customize the logging behavior, with a function conforming
* to the `wl_log_func_t` type, via `wl_log_set_handler_client` and
* `wl_log_set_handler_server`.
*
* A `wl_log_func_t` must conform to the expectations of `vprintf`, and
* expects two arguments: a string to write and a corresponding variable
* argument list. While the string to write may contain format specifiers and
* use values in the variable argument list, the behavior of any `wl_log_func_t`
* depends on the implementation.
*
* \note Take care to not confuse this with `wl_protocol_logger_func_t`, which
* is a specific server-side logger for requests and events.
*
* \param fmt String to write to the log, containing optional format
* specifiers
* \param args Variable argument list
*
* \sa wl_log_set_handler_client
* \sa wl_log_set_handler_server
*/
typedef void (*wl_log_func_t)(const char *fmt, va_list args) WL_PRINTF(1, 0);
/**
* Return value of an iterator function
*
* \sa wl_client_for_each_resource_iterator_func_t
* \sa wl_client_for_each_resource
*/
enum wl_iterator_result {
/** Stop the iteration */
WL_ITERATOR_STOP,
/** Continue the iteration */
WL_ITERATOR_CONTINUE
};
#ifdef __cplusplus
}
#endif
#endif
+34
View File
@@ -0,0 +1,34 @@
/*
* Copyright © 2012 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef WAYLAND_VERSION_H
#define WAYLAND_VERSION_H
#define WAYLAND_VERSION_MAJOR 1
#define WAYLAND_VERSION_MINOR 26
#define WAYLAND_VERSION_MICRO 0
#define WAYLAND_VERSION "1.26.0"
#endif