mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 20:45:43 +00:00
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
21bbf2f840 | ||
|
|
349a36b3b8 | ||
|
|
24d0074777 | ||
|
|
975c76e3e8 | ||
|
|
a394dfd31b | ||
|
|
a2e555f4cc | ||
|
|
31d12a9f6c | ||
|
|
3820445561 | ||
|
|
75d7edd2c3 | ||
|
|
da8fe068d9 |
No files matched your search
@@ -186,7 +186,7 @@ jobs:
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: app/src/main/assets/linuxfs
|
||||
key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'app/src/main/cpp/adrenotools/src/hook/kgsl.h', 'tools/quest/*', 'tools/linuxfs/preload/*.c', 'tools/linuxfs/build-x86-preloads.sh', 'tools/linuxfs/fex/*', 'tools/linuxfs/clipboard/*.c', 'tools/linuxfs/ssbs/*.c', 'tools/proot/fastpath/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/wlroots/release.env', 'tools/linuxfs/uruntime.env', 'tools/linuxfs/licenses/*', 'tools/mangoapp/*', 'tools/msitools/**', 'tools/comet/**', 'tools/linuxfs/debian-image.env') }}
|
||||
key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'app/src/main/cpp/adrenotools/src/hook/kgsl.h', 'tools/quest/*', 'tools/linuxfs/preload/*.c', 'tools/linuxfs/build-x86-preloads.sh', 'tools/linuxfs/fex/*', 'tools/linuxfs/clipboard/*.c', 'tools/linuxfs/ssbs/*.c', 'tools/proot/fastpath/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/wlroots/release.env', 'tools/linuxfs/uruntime.env', 'tools/linuxfs/licenses/*', 'tools/mangoapp/*', 'tools/msitools/**', 'tools/comet/**', 'tools/linuxfs/debian-image.env', 'tools/vr/**') }}
|
||||
|
||||
- name: Build libfakeinput.so and libblsession.so (glibc aarch64)
|
||||
if: steps.preloads.outputs.cache-hit != 'true'
|
||||
@@ -218,6 +218,9 @@ jobs:
|
||||
mkdir -p "$D/usr/local/bin"
|
||||
aarch64-linux-gnu-gcc -O2 -Wall -Wextra -o "$D/usr/local/bin/droiddeck-clipboard" tools/linuxfs/clipboard/clipboard.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$D/usr/local/bin/droiddeck-clipboard"
|
||||
# Cardboard mode's SteamVR driver and Vulkan layer (tools/vr), Vulkan headers from the runner's NDK.
|
||||
VK_INCLUDE=$(ls -d "${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"/toolchains/llvm/prebuilt/*/sysroot/usr/include | head -1) \
|
||||
tools/vr/build.sh --native "$D/usr/local/lib/droiddeck-vr"
|
||||
for script in tools/linuxfs/overlay/usr/local/bin/droiddeck-* tools/linuxfs/overlay/usr/local/bin/steam-compatibility; do
|
||||
install -Dm644 "$script" "$D/usr/local/bin/$(basename "$script")"
|
||||
done
|
||||
@@ -625,10 +628,11 @@ jobs:
|
||||
|
||||
# Each signed main build as a prerelease of the public Droid-Deck/DroidDeck-CI (main-<sha>, the
|
||||
# last KEEP kept), where anyone can download it without a GitHub account, then a post in the
|
||||
# Discord's builds channel linking to it. The release is made with a token of the org's
|
||||
# Discord's #preview-builds channel linking to it. The release is made with a token of the org's
|
||||
# "DroidDeck CI Publisher" app (installed on DroidDeck-CI only, Contents: write): its ID in the
|
||||
# DROIDDECK_CI_APP_ID variable, its private key in the DROIDDECK_CI_APP_KEY secret.
|
||||
# DISCORD_BUILDS_WEBHOOK is the channel's webhook URL.
|
||||
# DISCORD_BUILDS_WEBHOOK is the channel's webhook URL. Keep this secret name when renaming
|
||||
# the channel: Discord routes the existing webhook by channel ID, not its display name.
|
||||
announce:
|
||||
needs: [build, sign]
|
||||
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
|
||||
@@ -730,7 +734,7 @@ jobs:
|
||||
echo "apk=$GITHUB_SERVER_URL/$CI_REPO/releases/download/$tag/$apk" >> "$GITHUB_OUTPUT"
|
||||
echo "Published $url"
|
||||
|
||||
- name: Post to Discord
|
||||
- name: Post the Preview build to Discord
|
||||
env:
|
||||
WEBHOOK: ${{ secrets.DISCORD_BUILDS_WEBHOOK }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
@@ -754,7 +758,7 @@ jobs:
|
||||
what="[\`${GITHUB_SHA::7}\`]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/commit/$GITHUB_SHA): $subject"
|
||||
fi
|
||||
get=$(printf 'Download: [standard APK](<%s>) · [all variants](<%s>)' "$APK" "$RELEASE")
|
||||
content=$(printf '**New signed build** `main-%s`\n%s\n%s' "${GITHUB_SHA::7}" "$what" "$get")
|
||||
content=$(printf '**New signed Preview build** `main-%s`\n%s\nIn the app: **Updates → Preview**\n%s' "${GITHUB_SHA::7}" "$what" "$get")
|
||||
jq -n --arg content "$content" '{content: $content, allowed_mentions: {parse: []}}' |
|
||||
curl -fsS -H 'Content-Type: application/json' -d @- "$WEBHOOK" -o /dev/null
|
||||
echo "Posted: $content"
|
||||
|
||||
@@ -40,3 +40,4 @@ __pycache__/
|
||||
# Local signing with the release key (tools/build_local.sh); holds a password.
|
||||
.signing.env
|
||||
app/src/main/assets/directaudio/
|
||||
/tools/vr/out/
|
||||
@@ -8,6 +8,7 @@ add_library(droiddeckwayland SHARED
|
||||
src/compositor.c
|
||||
src/vk_present.c
|
||||
src/effects_chain.c
|
||||
src/cardboard.c
|
||||
src/vk_loader.c
|
||||
src/sc_layer.c
|
||||
src/ahb_swapchain.c
|
||||
|
||||
@@ -0,0 +1,447 @@
|
||||
/* Cardboard pass - see cardboard.h. Compositor thread unless noted.
|
||||
*
|
||||
* The shader is cardboard.frag, pre-compiled like the rest of the compositor's SPIR-V:
|
||||
* glslangValidator -V --vn cardboard_frag_code -o cardboard_frag.h cardboard.frag
|
||||
*/
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include "cardboard.h"
|
||||
#include <math.h>
|
||||
#include <pthread.h>
|
||||
#include <string.h>
|
||||
|
||||
#ifndef CARDBOARD_HOST_TEST
|
||||
#include <fcntl.h>
|
||||
#include <stdatomic.h>
|
||||
#include <sys/mman.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
#include "headpose_shm.h"
|
||||
#endif
|
||||
|
||||
#ifndef CARDBOARD_HOST_TEST
|
||||
#include "vk_loader.h"
|
||||
#include "vk_present.h" /* droiddeck_log */
|
||||
/* upscale_vert.h defines its array non-static, and effects_chain.c includes it too: a private name here. */
|
||||
#define upscale_vert_code cardboard_upscale_vert_code
|
||||
#include "upscale_vert.h"
|
||||
#undef upscale_vert_code
|
||||
#include "cardboard_frag.h"
|
||||
#endif
|
||||
|
||||
/* ------------------------------------------------------------------ pure helpers */
|
||||
|
||||
static float clampf(float v, float lo, float hi) { return v < lo ? lo : v > hi ? hi : v; }
|
||||
|
||||
void cardboard_clamp(struct cardboard_params *p) {
|
||||
p->enabled = p->enabled ? 1 : 0;
|
||||
p->source = p->source == CARDBOARD_SOURCE_SBS ? CARDBOARD_SOURCE_SBS : CARDBOARD_SOURCE_SCREEN;
|
||||
p->ipd_m = clampf(p->ipd_m, 0.0f, 0.1f);
|
||||
p->screen_dist_m = clampf(p->screen_dist_m, 0.5f, 50.0f);
|
||||
p->screen_width_m = clampf(p->screen_width_m, 0.2f, 60.0f);
|
||||
p->k1 = clampf(p->k1, -1.0f, 2.0f);
|
||||
p->k2 = clampf(p->k2, -1.0f, 2.0f);
|
||||
p->fov_deg = clampf(p->fov_deg, 30.0f, 140.0f);
|
||||
p->lens_inset = clampf(p->lens_inset, -0.25f, 0.25f);
|
||||
p->chroma = clampf(p->chroma, 0.0f, 0.05f);
|
||||
}
|
||||
|
||||
void cardboard_push_constants(const struct cardboard_params *p, const float pose[9],
|
||||
int src_w, int src_h, int out_w, int out_h, float out[24]) {
|
||||
/* rot0..rot2: the pose's rows, each with one scalar riding in w. */
|
||||
for (int r = 0; r < 3; r++)
|
||||
for (int c = 0; c < 3; c++) out[r * 4 + c] = pose[r * 3 + c];
|
||||
out[3] = p->ipd_m * 0.5f;
|
||||
out[7] = p->screen_dist_m;
|
||||
out[11] = p->screen_width_m * 0.5f;
|
||||
/* lens */
|
||||
out[12] = p->k1;
|
||||
out[13] = p->k2;
|
||||
out[14] = tanf(p->fov_deg * 0.5f * (float)M_PI / 180.0f);
|
||||
out[15] = p->chroma;
|
||||
/* view */
|
||||
out[16] = p->lens_inset;
|
||||
out[17] = (src_w > 0 && src_h > 0) ? (float)src_w / (float)src_h : 16.0f / 9.0f;
|
||||
if (p->source == CARDBOARD_SOURCE_SBS) out[17] *= 0.5f; /* one eye's half */
|
||||
out[18] = (float)p->source;
|
||||
out[19] = (out_w > 0 && out_h > 0) ? ((float)out_w * 0.5f) / (float)out_h : 1.0f;
|
||||
out[20] = out[21] = out[22] = out[23] = 0.0f; /* reserved */
|
||||
}
|
||||
|
||||
#ifndef CARDBOARD_HOST_TEST
|
||||
|
||||
/* ------------------------------------------------------------------ settings + pose */
|
||||
|
||||
static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static struct cardboard_params g_set = {
|
||||
.enabled = 0, .source = CARDBOARD_SOURCE_SCREEN, .ipd_m = 0.064f, .screen_dist_m = 3.0f,
|
||||
.screen_width_m = 4.0f, .k1 = 0.22f, .k2 = 0.24f, .fov_deg = 90.0f, .lens_inset = 0.0f, .chroma = 0.0f};
|
||||
static float g_pose[9] = {1, 0, 0, 0, 1, 0, 0, 0, 1};
|
||||
static volatile int g_changed = 1;
|
||||
|
||||
static int g_live; /* the last pose came from a sensor */
|
||||
static void shm_publish(int live); /* below: the guest's copy of the pose */
|
||||
|
||||
void vkp_cardboard_set(const struct cardboard_params *p) {
|
||||
struct cardboard_params c = *p;
|
||||
cardboard_clamp(&c);
|
||||
pthread_mutex_lock(&g_lock);
|
||||
int was = g_set.enabled;
|
||||
g_set = c;
|
||||
g_changed = 1;
|
||||
shm_publish(g_live);
|
||||
pthread_mutex_unlock(&g_lock);
|
||||
if (was != c.enabled || c.enabled)
|
||||
droiddeck_log("cardboard", "%s: %s, ipd %.0f mm, screen %.1f m wide at %.1f m, lens k1 %.2f k2 %.2f, fov %.0f, inset %.3f, chroma %.3f",
|
||||
c.enabled ? "on" : "off", c.source == CARDBOARD_SOURCE_SBS ? "side-by-side source" : "virtual screen",
|
||||
c.ipd_m * 1000.0f, c.screen_width_m, c.screen_dist_m, c.k1, c.k2, c.fov_deg, c.lens_inset, c.chroma);
|
||||
}
|
||||
|
||||
/* The guest's copy of the pose (headpose_shm.h), mapped once a path is known. */
|
||||
static struct droiddeck_headpose *g_shm;
|
||||
static int g_eye_w, g_eye_h; /* the last eye viewport drawn, for the guest */
|
||||
|
||||
void vkp_cardboard_set_pose_file(const char *path) {
|
||||
pthread_mutex_lock(&g_lock);
|
||||
if (!g_shm && path && *path) {
|
||||
int fd = open(path, O_RDWR | O_CREAT | O_CLOEXEC, 0600);
|
||||
if (fd >= 0 && ftruncate(fd, sizeof(struct droiddeck_headpose)) == 0) {
|
||||
void *p = mmap(NULL, sizeof(struct droiddeck_headpose), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
|
||||
if (p != MAP_FAILED) {
|
||||
g_shm = p;
|
||||
memset(g_shm, 0, sizeof(*g_shm));
|
||||
g_shm->magic = DROIDDECK_HEADPOSE_MAGIC;
|
||||
g_shm->version = DROIDDECK_HEADPOSE_VERSION;
|
||||
memcpy(g_shm->rot, g_pose, sizeof(g_shm->rot));
|
||||
}
|
||||
}
|
||||
if (fd >= 0) close(fd);
|
||||
droiddeck_log("cardboard", g_shm ? "head pose shared with the guest at %s" : "could not share the head pose at %s", path);
|
||||
}
|
||||
pthread_mutex_unlock(&g_lock);
|
||||
}
|
||||
|
||||
/* Under g_lock. */
|
||||
static void shm_publish(int live) {
|
||||
if (!g_shm) return;
|
||||
struct timespec ts;
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
atomic_uint *seq = (atomic_uint *)&g_shm->seq;
|
||||
unsigned s = atomic_load_explicit(seq, memory_order_relaxed);
|
||||
atomic_store_explicit(seq, s | 1u, memory_order_relaxed);
|
||||
atomic_thread_fence(memory_order_release);
|
||||
memcpy(g_shm->rot, g_pose, sizeof(g_shm->rot));
|
||||
g_shm->ipd_m = g_set.ipd_m;
|
||||
g_shm->flags = (live ? DROIDDECK_HEADPOSE_LIVE : 0u) | (g_set.enabled ? DROIDDECK_HEADPOSE_ENABLED : 0u);
|
||||
g_shm->time_ns = (int64_t)ts.tv_sec * 1000000000LL + ts.tv_nsec;
|
||||
g_shm->tan_half_fov = tanf(g_set.fov_deg * 0.5f * (float)M_PI / 180.0f);
|
||||
g_shm->eye_w = (uint32_t)(g_eye_w > 0 ? g_eye_w : 0);
|
||||
g_shm->eye_h = (uint32_t)(g_eye_h > 0 ? g_eye_h : 0);
|
||||
g_shm->eye_aspect = g_eye_h > 0 ? (float)g_eye_w / (float)g_eye_h : 1.0f;
|
||||
atomic_thread_fence(memory_order_release);
|
||||
atomic_store_explicit(seq, (s | 1u) + 1u, memory_order_relaxed);
|
||||
}
|
||||
|
||||
|
||||
void vkp_cardboard_set_pose(const float m[9], int live) {
|
||||
pthread_mutex_lock(&g_lock);
|
||||
memcpy(g_pose, m, sizeof(g_pose));
|
||||
g_live = live;
|
||||
if (g_set.enabled && g_set.source == CARDBOARD_SOURCE_SCREEN) g_changed = 1;
|
||||
shm_publish(live);
|
||||
pthread_mutex_unlock(&g_lock);
|
||||
}
|
||||
|
||||
static struct cardboard_params g_cur;
|
||||
static float g_cur_pose[9];
|
||||
|
||||
static void snapshot(void) {
|
||||
pthread_mutex_lock(&g_lock);
|
||||
g_cur = g_set;
|
||||
memcpy(g_cur_pose, g_pose, sizeof(g_cur_pose));
|
||||
pthread_mutex_unlock(&g_lock);
|
||||
}
|
||||
|
||||
int vkp_cardboard_active(void) {
|
||||
pthread_mutex_lock(&g_lock);
|
||||
int on = g_set.enabled;
|
||||
pthread_mutex_unlock(&g_lock);
|
||||
return on;
|
||||
}
|
||||
|
||||
int vkp_cardboard_pose_changed(void) {
|
||||
if (!g_changed) return 0;
|
||||
g_changed = 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ Vulkan objects */
|
||||
|
||||
#define CB_FORMAT VK_FORMAT_R8G8B8A8_UNORM
|
||||
#define CB_PC_SIZE (4 * 4 + 24 * 4) /* ndc + the 24 floats: 112 bytes, under the 128 guaranteed */
|
||||
#define CB_MAX_SOURCES 8 /* source views per frame: the real frame + generated ones */
|
||||
|
||||
static VkDevice g_dev;
|
||||
static VkPhysicalDeviceMemoryProperties g_mp;
|
||||
static int g_ready; /* 0 = not built, 1 = ok, -1 = failed (said once) */
|
||||
static VkRenderPass g_rp;
|
||||
static VkDescriptorSetLayout g_dsl;
|
||||
static VkPipelineLayout g_pl;
|
||||
static VkDescriptorPool g_dpool;
|
||||
static VkSampler g_sampler;
|
||||
static VkPipeline g_pipe;
|
||||
static struct { VkImage img; VkDeviceMemory mem; VkImageView view; VkFramebuffer fb; int w, h; } g_t;
|
||||
static struct { VkImageView view; VkDescriptorSet ds; } g_src[CB_MAX_SOURCES];
|
||||
static int g_nsrc;
|
||||
|
||||
void vkp_cardboard_bind_device(VkDevice dev, const VkPhysicalDeviceMemoryProperties *memprops) {
|
||||
g_dev = dev;
|
||||
g_mp = *memprops;
|
||||
}
|
||||
|
||||
static int memtype(uint32_t bits, VkMemoryPropertyFlags want) {
|
||||
for (uint32_t i = 0; i < g_mp.memoryTypeCount; i++)
|
||||
if ((bits & (1u << i)) && (g_mp.memoryTypes[i].propertyFlags & want) == want) return (int)i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
static void sources_release(void) {
|
||||
for (int i = 0; i < g_nsrc; i++) {
|
||||
if (g_src[i].ds) g_vk.FreeDescriptorSets(g_dev, g_dpool, 1, &g_src[i].ds);
|
||||
if (g_src[i].view) g_vk.DestroyImageView(g_dev, g_src[i].view, NULL);
|
||||
}
|
||||
memset(g_src, 0, sizeof(g_src));
|
||||
g_nsrc = 0;
|
||||
}
|
||||
|
||||
void vkp_cardboard_begin_frame(void) {
|
||||
if (g_ready == 1) sources_release();
|
||||
}
|
||||
|
||||
static void target_destroy(void) {
|
||||
if (g_t.fb) g_vk.DestroyFramebuffer(g_dev, g_t.fb, NULL);
|
||||
if (g_t.view) g_vk.DestroyImageView(g_dev, g_t.view, NULL);
|
||||
if (g_t.img) g_vk.DestroyImage(g_dev, g_t.img, NULL);
|
||||
if (g_t.mem) g_vk.FreeMemory(g_dev, g_t.mem, NULL);
|
||||
memset(&g_t, 0, sizeof(g_t));
|
||||
}
|
||||
|
||||
static VkImageView make_view(VkImage img) {
|
||||
VkImageView v = VK_NULL_HANDLE;
|
||||
VkImageViewCreateInfo ci = {.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, .image = img,
|
||||
.viewType = VK_IMAGE_VIEW_TYPE_2D, .format = CB_FORMAT,
|
||||
.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
|
||||
if (g_vk.CreateImageView(g_dev, &ci, NULL, &v) != VK_SUCCESS) return VK_NULL_HANDLE;
|
||||
return v;
|
||||
}
|
||||
|
||||
/* The panel-sized output: rendered into, then blitted 1:1 to the swapchain. Kept uncompressed
|
||||
* (mutable format) like the effect chain's targets: UBWC render-then-blit targets corrupt on
|
||||
* Adreno 740. */
|
||||
static int target_ensure(int w, int h) {
|
||||
if (g_t.img && g_t.w == w && g_t.h == h) return 0;
|
||||
target_destroy();
|
||||
VkImageCreateInfo ii = {.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .flags = VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT,
|
||||
.imageType = VK_IMAGE_TYPE_2D, .format = CB_FORMAT, .extent = {(uint32_t)w, (uint32_t)h, 1},
|
||||
.mipLevels = 1, .arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT,
|
||||
.tiling = VK_IMAGE_TILING_OPTIMAL,
|
||||
.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
|
||||
.sharingMode = VK_SHARING_MODE_EXCLUSIVE, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
|
||||
if (g_vk.CreateImage(g_dev, &ii, NULL, &g_t.img) != VK_SUCCESS) goto fail;
|
||||
VkMemoryRequirements req;
|
||||
g_vk.GetImageMemoryRequirements(g_dev, g_t.img, &req);
|
||||
int idx = memtype(req.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
|
||||
if (idx < 0) idx = memtype(req.memoryTypeBits, 0);
|
||||
VkMemoryAllocateInfo mai = {.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .allocationSize = req.size,
|
||||
.memoryTypeIndex = (uint32_t)(idx < 0 ? 0 : idx)};
|
||||
if (g_vk.AllocateMemory(g_dev, &mai, NULL, &g_t.mem) != VK_SUCCESS) goto fail;
|
||||
g_vk.BindImageMemory(g_dev, g_t.img, g_t.mem, 0);
|
||||
if (!(g_t.view = make_view(g_t.img))) goto fail;
|
||||
VkFramebufferCreateInfo fi = {.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, .renderPass = g_rp,
|
||||
.attachmentCount = 1, .pAttachments = &g_t.view, .width = (uint32_t)w,
|
||||
.height = (uint32_t)h, .layers = 1};
|
||||
if (g_vk.CreateFramebuffer(g_dev, &fi, NULL, &g_t.fb) != VK_SUCCESS) goto fail;
|
||||
g_t.w = w;
|
||||
g_t.h = h;
|
||||
droiddeck_log("cardboard", "eye target %dx%d (two %dx%d eyes)", w, h, w / 2, h);
|
||||
return 0;
|
||||
fail:
|
||||
droiddeck_log("error", "cardboard: could not create the %dx%d eye target", w, h);
|
||||
target_destroy();
|
||||
return -1;
|
||||
}
|
||||
|
||||
static VkShaderModule shader(const uint32_t *code, size_t size) {
|
||||
VkShaderModule m = VK_NULL_HANDLE;
|
||||
VkShaderModuleCreateInfo ci = {.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, .codeSize = size, .pCode = code};
|
||||
if (g_vk.CreateShaderModule(g_dev, &ci, NULL, &m) != VK_SUCCESS) return VK_NULL_HANDLE;
|
||||
return m;
|
||||
}
|
||||
|
||||
static void objects_destroy(void) {
|
||||
if (!g_dev) return;
|
||||
sources_release();
|
||||
target_destroy();
|
||||
if (g_pipe) g_vk.DestroyPipeline(g_dev, g_pipe, NULL);
|
||||
if (g_dpool) g_vk.DestroyDescriptorPool(g_dev, g_dpool, NULL);
|
||||
if (g_pl) g_vk.DestroyPipelineLayout(g_dev, g_pl, NULL);
|
||||
if (g_dsl) g_vk.DestroyDescriptorSetLayout(g_dev, g_dsl, NULL);
|
||||
if (g_sampler) g_vk.DestroySampler(g_dev, g_sampler, NULL);
|
||||
if (g_rp) g_vk.DestroyRenderPass(g_dev, g_rp, NULL);
|
||||
g_pipe = VK_NULL_HANDLE; g_dpool = VK_NULL_HANDLE; g_pl = VK_NULL_HANDLE;
|
||||
g_dsl = VK_NULL_HANDLE; g_sampler = VK_NULL_HANDLE; g_rp = VK_NULL_HANDLE;
|
||||
}
|
||||
|
||||
static int objects_ensure(void) {
|
||||
if (g_ready) return g_ready == 1 ? 0 : -1;
|
||||
if (!g_dev || !g_vk.CreateGraphicsPipelines) goto fail;
|
||||
{
|
||||
/* One colour target, overwritten whole, left GENERAL for the 1:1 blit that follows. */
|
||||
VkAttachmentDescription att = {.format = CB_FORMAT, .samples = VK_SAMPLE_COUNT_1_BIT,
|
||||
.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, .storeOp = VK_ATTACHMENT_STORE_OP_STORE,
|
||||
.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
|
||||
.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
|
||||
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, .finalLayout = VK_IMAGE_LAYOUT_GENERAL};
|
||||
VkAttachmentReference ref = {0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL};
|
||||
VkSubpassDescription sub = {.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS, .colorAttachmentCount = 1,
|
||||
.pColorAttachments = &ref};
|
||||
VkSubpassDependency deps[2] = {
|
||||
{.srcSubpass = VK_SUBPASS_EXTERNAL, .dstSubpass = 0,
|
||||
.srcStageMask = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
|
||||
.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
|
||||
.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT,
|
||||
.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT},
|
||||
{.srcSubpass = 0, .dstSubpass = VK_SUBPASS_EXTERNAL,
|
||||
.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
|
||||
.dstStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT,
|
||||
.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT}};
|
||||
VkRenderPassCreateInfo rci = {.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, .attachmentCount = 1,
|
||||
.pAttachments = &att, .subpassCount = 1, .pSubpasses = &sub,
|
||||
.dependencyCount = 2, .pDependencies = deps};
|
||||
if (g_vk.CreateRenderPass(g_dev, &rci, NULL, &g_rp) != VK_SUCCESS) goto fail;
|
||||
|
||||
VkSamplerCreateInfo sci = {.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, .magFilter = VK_FILTER_LINEAR,
|
||||
.minFilter = VK_FILTER_LINEAR, .mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST,
|
||||
.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
|
||||
.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
|
||||
.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE};
|
||||
if (g_vk.CreateSampler(g_dev, &sci, NULL, &g_sampler) != VK_SUCCESS) goto fail;
|
||||
|
||||
VkDescriptorSetLayoutBinding b = {.binding = 0, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
|
||||
.descriptorCount = 1, .stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT};
|
||||
VkDescriptorSetLayoutCreateInfo dli = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
|
||||
.bindingCount = 1, .pBindings = &b};
|
||||
if (g_vk.CreateDescriptorSetLayout(g_dev, &dli, NULL, &g_dsl) != VK_SUCCESS) goto fail;
|
||||
VkPushConstantRange pcr = {.stageFlags = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT,
|
||||
.offset = 0, .size = CB_PC_SIZE};
|
||||
VkPipelineLayoutCreateInfo pli = {.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .setLayoutCount = 1,
|
||||
.pSetLayouts = &g_dsl, .pushConstantRangeCount = 1, .pPushConstantRanges = &pcr};
|
||||
if (g_vk.CreatePipelineLayout(g_dev, &pli, NULL, &g_pl) != VK_SUCCESS) goto fail;
|
||||
VkDescriptorPoolSize ps = {VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, CB_MAX_SOURCES};
|
||||
VkDescriptorPoolCreateInfo dpi = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
|
||||
.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT,
|
||||
.maxSets = CB_MAX_SOURCES, .poolSizeCount = 1, .pPoolSizes = &ps};
|
||||
if (g_vk.CreateDescriptorPool(g_dev, &dpi, NULL, &g_dpool) != VK_SUCCESS) goto fail;
|
||||
|
||||
VkShaderModule vert = shader(cardboard_upscale_vert_code, sizeof(cardboard_upscale_vert_code));
|
||||
VkShaderModule frag = shader(cardboard_frag_code, sizeof(cardboard_frag_code));
|
||||
if (!vert || !frag) {
|
||||
if (vert) g_vk.DestroyShaderModule(g_dev, vert, NULL);
|
||||
if (frag) g_vk.DestroyShaderModule(g_dev, frag, NULL);
|
||||
goto fail;
|
||||
}
|
||||
VkPipelineShaderStageCreateInfo st[2] = {
|
||||
{.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, .stage = VK_SHADER_STAGE_VERTEX_BIT, .module = vert, .pName = "main"},
|
||||
{.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, .stage = VK_SHADER_STAGE_FRAGMENT_BIT, .module = frag, .pName = "main"}};
|
||||
VkPipelineVertexInputStateCreateInfo vi = {.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO};
|
||||
VkPipelineInputAssemblyStateCreateInfo ia = {.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,
|
||||
.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP};
|
||||
VkDynamicState dyn[2] = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR};
|
||||
VkPipelineDynamicStateCreateInfo ds = {.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO,
|
||||
.dynamicStateCount = 2, .pDynamicStates = dyn};
|
||||
VkPipelineViewportStateCreateInfo vp = {.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO,
|
||||
.viewportCount = 1, .scissorCount = 1};
|
||||
VkPipelineRasterizationStateCreateInfo rs = {.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO,
|
||||
.polygonMode = VK_POLYGON_MODE_FILL, .cullMode = VK_CULL_MODE_NONE,
|
||||
.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE, .lineWidth = 1.0f};
|
||||
VkPipelineMultisampleStateCreateInfo ms = {.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO,
|
||||
.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT};
|
||||
VkPipelineColorBlendAttachmentState ba = {.blendEnable = VK_FALSE, .colorWriteMask = 0xF};
|
||||
VkPipelineColorBlendStateCreateInfo cb = {.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO,
|
||||
.attachmentCount = 1, .pAttachments = &ba};
|
||||
VkGraphicsPipelineCreateInfo pi = {.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, .stageCount = 2,
|
||||
.pStages = st, .pVertexInputState = &vi, .pInputAssemblyState = &ia,
|
||||
.pViewportState = &vp, .pRasterizationState = &rs, .pMultisampleState = &ms,
|
||||
.pColorBlendState = &cb, .pDynamicState = &ds, .layout = g_pl,
|
||||
.renderPass = g_rp, .subpass = 0};
|
||||
VkResult r = g_vk.CreateGraphicsPipelines(g_dev, VK_NULL_HANDLE, 1, &pi, NULL, &g_pipe);
|
||||
g_vk.DestroyShaderModule(g_dev, vert, NULL);
|
||||
g_vk.DestroyShaderModule(g_dev, frag, NULL);
|
||||
if (r != VK_SUCCESS) goto fail;
|
||||
}
|
||||
g_ready = 1;
|
||||
droiddeck_log("cardboard", "pass ready on %s", vkp_gpu_name());
|
||||
return 0;
|
||||
fail:
|
||||
objects_destroy();
|
||||
g_ready = -1;
|
||||
droiddeck_log("error", "cardboard: the pass could not be built on this driver; frames are shown flat");
|
||||
return -1;
|
||||
}
|
||||
|
||||
static VkDescriptorSet source_ds(VkImage src) {
|
||||
if (g_nsrc >= CB_MAX_SOURCES) return VK_NULL_HANDLE;
|
||||
VkImageView view = make_view(src);
|
||||
if (!view) return VK_NULL_HANDLE;
|
||||
VkDescriptorSet ds = VK_NULL_HANDLE;
|
||||
VkDescriptorSetAllocateInfo ai = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
|
||||
.descriptorPool = g_dpool, .descriptorSetCount = 1, .pSetLayouts = &g_dsl};
|
||||
if (g_vk.AllocateDescriptorSets(g_dev, &ai, &ds) != VK_SUCCESS) {
|
||||
g_vk.DestroyImageView(g_dev, view, NULL);
|
||||
return VK_NULL_HANDLE;
|
||||
}
|
||||
VkDescriptorImageInfo ii = {.sampler = g_sampler, .imageView = view, .imageLayout = VK_IMAGE_LAYOUT_GENERAL};
|
||||
VkWriteDescriptorSet wr = {.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = ds, .dstBinding = 0,
|
||||
.descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
|
||||
.pImageInfo = &ii};
|
||||
g_vk.UpdateDescriptorSets(g_dev, 1, &wr, 0, NULL);
|
||||
g_src[g_nsrc].view = view;
|
||||
g_src[g_nsrc].ds = ds;
|
||||
g_nsrc++;
|
||||
return ds;
|
||||
}
|
||||
|
||||
VkImage vkp_cardboard_run(VkCommandBuffer cmd, VkImage src, int src_w, int src_h, int out_w, int out_h) {
|
||||
if (out_w < 2 || out_h < 1 || objects_ensure() != 0 || target_ensure(out_w, out_h) != 0) return VK_NULL_HANDLE;
|
||||
VkDescriptorSet ds = source_ds(src);
|
||||
if (!ds) {
|
||||
static int said;
|
||||
if (!said) { said = 1; droiddeck_log("error", "cardboard: no descriptor for the frame; shown flat"); }
|
||||
return VK_NULL_HANDLE;
|
||||
}
|
||||
if (g_eye_w != out_w / 2 || g_eye_h != out_h) {
|
||||
pthread_mutex_lock(&g_lock);
|
||||
g_eye_w = out_w / 2;
|
||||
g_eye_h = out_h;
|
||||
shm_publish(g_live);
|
||||
pthread_mutex_unlock(&g_lock);
|
||||
}
|
||||
snapshot();
|
||||
struct { float ndc[4]; float rest[24]; } pc = {{-1.0f, -1.0f, 1.0f, 1.0f}, {0}};
|
||||
cardboard_push_constants(&g_cur, g_cur_pose, src_w, src_h, out_w, out_h, pc.rest);
|
||||
|
||||
VkRenderPassBeginInfo rpi = {.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, .renderPass = g_rp,
|
||||
.framebuffer = g_t.fb, .renderArea = {{0, 0}, {(uint32_t)out_w, (uint32_t)out_h}}};
|
||||
VkViewport vp = {0, 0, (float)out_w, (float)out_h, 0, 1};
|
||||
VkRect2D sc = {{0, 0}, {(uint32_t)out_w, (uint32_t)out_h}};
|
||||
g_vk.CmdBeginRenderPass(cmd, &rpi, VK_SUBPASS_CONTENTS_INLINE);
|
||||
g_vk.CmdSetViewport(cmd, 0, 1, &vp);
|
||||
g_vk.CmdSetScissor(cmd, 0, 1, &sc);
|
||||
g_vk.CmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, g_pipe);
|
||||
g_vk.CmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, g_pl, 0, 1, &ds, 0, NULL);
|
||||
g_vk.CmdPushConstants(cmd, g_pl, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(pc), &pc);
|
||||
g_vk.CmdDraw(cmd, 4, 1, 0, 0);
|
||||
g_vk.CmdEndRenderPass(cmd);
|
||||
return g_t.img;
|
||||
}
|
||||
|
||||
#endif /* CARDBOARD_HOST_TEST */
|
||||
@@ -0,0 +1,83 @@
|
||||
#version 450
|
||||
// Cardboard pass (cardboard.c): the finished frame -> two eye viewports, side by side, each
|
||||
// barrel-distorted for a phone-in-a-viewer lens. Runs on upscale.vert's full quad, so uv covers
|
||||
// the whole panel with (0,0) at the top left.
|
||||
//
|
||||
// Source modes:
|
||||
// 0 = virtual screen: the frame is a flat screen hanging in front of the viewer. Each eye casts
|
||||
// a ray through its lens, rotated by the head pose, from its own position (half the IPD to
|
||||
// either side), so the screen has real stereo depth and stays put while the head turns.
|
||||
// 1 = side by side: the frame already holds a left and a right eye image (SteamVR, an SBS 3D
|
||||
// game or video); each eye samples its own half. The head pose belongs to whoever rendered
|
||||
// it, so none is applied here.
|
||||
//
|
||||
// Regenerate cardboard_frag.h after editing (glslangValidator, see cardboard.c).
|
||||
layout(binding = 0) uniform sampler2D Source;
|
||||
layout(location = 0) in vec2 uv;
|
||||
layout(location = 0) out vec4 outColor;
|
||||
|
||||
layout(push_constant) uniform PC {
|
||||
vec4 ndc; // upscale.vert's quad
|
||||
vec4 rot0; // xyz: head -> world rotation, row 0; w: half the IPD (m)
|
||||
vec4 rot1; // xyz: row 1; w: distance to the virtual screen (m)
|
||||
vec4 rot2; // xyz: row 2; w: half the virtual screen's width (m)
|
||||
vec4 lens; // x: k1, y: k2, z: tan of half the eye's vertical field of view, w: chromatic spread
|
||||
vec4 view; // x: lens centre inset (fraction of an eye viewport), y: source aspect w/h,
|
||||
// z: source mode, w: eye viewport aspect w/h
|
||||
} pc;
|
||||
|
||||
const vec3 BACKDROP = vec3(0.015, 0.015, 0.02);
|
||||
|
||||
// Lens: a point on the panel at tangent-space offset t (from the lens centre) shows the ray that
|
||||
// leaves the eye at t * (1 + k1 r^2 + k2 r^4). Sampling outwards like this draws the picture
|
||||
// barrel-shaped; the viewer's lens pincushions it back.
|
||||
vec2 undistort(vec2 t, float scale) {
|
||||
float r2 = dot(t, t);
|
||||
return t * scale * (1.0 + pc.lens.x * r2 + pc.lens.y * r2 * r2);
|
||||
}
|
||||
|
||||
// What one eye sees along tangent direction tan (x right, y down): colour, or the backdrop.
|
||||
vec3 eyeSample(vec2 tan, float eye) {
|
||||
if (pc.view.z > 0.5) {
|
||||
// Side by side: this eye's half of the source covers the eye's field of view.
|
||||
float tanH = pc.lens.z;
|
||||
vec2 s = vec2(tan.x / (tanH * pc.view.w), tan.y / tanH) * 0.5 + 0.5;
|
||||
if (any(lessThan(s, vec2(0.0))) || any(greaterThan(s, vec2(1.0)))) return vec3(0.0);
|
||||
return texture(Source, vec2((s.x + eye) * 0.5, s.y)).rgb;
|
||||
}
|
||||
// mat3() takes columns; the push constants carry rows.
|
||||
mat3 R = transpose(mat3(pc.rot0.xyz, pc.rot1.xyz, pc.rot2.xyz));
|
||||
vec3 d = R * normalize(vec3(tan.x, -tan.y, -1.0));
|
||||
vec3 o = R * vec3((eye < 0.5 ? -1.0 : 1.0) * pc.rot0.w, 0.0, 0.0);
|
||||
if (d.z > -1e-4) return BACKDROP; // looking away from the screen
|
||||
float t = (-pc.rot1.w - o.z) / d.z;
|
||||
vec3 hit = o + d * t;
|
||||
float halfW = pc.rot2.w, halfH = halfW / pc.view.y;
|
||||
vec2 s = vec2(hit.x / halfW, -hit.y / halfH) * 0.5 + 0.5;
|
||||
if (any(lessThan(s, vec2(0.0))) || any(greaterThan(s, vec2(1.0)))) return BACKDROP;
|
||||
return texture(Source, s).rgb;
|
||||
}
|
||||
|
||||
void main() {
|
||||
float eye = uv.x < 0.5 ? 0.0 : 1.0;
|
||||
vec2 local = vec2(uv.x * 2.0 - eye, uv.y);
|
||||
// Lens centres sit inset towards the nose by view.x of a viewport.
|
||||
float cx = 0.5 + (eye < 0.5 ? pc.view.x : -pc.view.x);
|
||||
vec2 p = local - vec2(cx, 0.5);
|
||||
float tanH = pc.lens.z;
|
||||
vec2 t = vec2(p.x * pc.view.w, p.y) * 2.0 * tanH;
|
||||
|
||||
vec3 c;
|
||||
if (pc.lens.w > 0.0) {
|
||||
// Chromatic aberration: the lens bends red least and blue most; pre-spread to match.
|
||||
c.r = eyeSample(undistort(t, 1.0 - pc.lens.w), eye).r;
|
||||
c.g = eyeSample(undistort(t, 1.0), eye).g;
|
||||
c.b = eyeSample(undistort(t, 1.0 + pc.lens.w), eye).b;
|
||||
} else {
|
||||
c = eyeSample(undistort(t, 1.0), eye);
|
||||
}
|
||||
// Fade out towards each viewport's edge so the lens rim never shows a hard cut.
|
||||
vec2 e = min(local, 1.0 - local);
|
||||
float fade = smoothstep(0.0, 0.03, min(e.x * pc.view.w, e.y));
|
||||
outColor = vec4(c * fade, 1.0);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
#ifndef CARDBOARD_H
|
||||
#define CARDBOARD_H
|
||||
/*
|
||||
* Cardboard mode: the last stage of the compositor pass. The finished frame (after the effects and
|
||||
* frame generation) is drawn twice, once per eye, side by side on the panel, barrel-distorted for a
|
||||
* phone-in-a-viewer lens (cardboard.frag). The frame either hangs as a flat virtual screen in front
|
||||
* of the viewer, world-locked by the phone's rotation sensor (3DoF), or is already a side-by-side
|
||||
* stereo pair (SteamVR, SBS 3D content) that only gets the lens treatment.
|
||||
*
|
||||
* Present-pass order with Cardboard on (vk_present.c, render_impl):
|
||||
* scene -> effects -> frame generation -> vkp_cardboard_run (whole panel) -> 1:1 blit -> present
|
||||
* The Fullscreen Mode mapping does not apply: the pass fills the output itself.
|
||||
*
|
||||
* Settings and the head pose come from any thread (JNI, the sensor thread); the compositor thread
|
||||
* snapshots them per frame. A new pose redraws even a static scene (vkp_cardboard_pose_changed), so
|
||||
* the virtual screen stays put while the head turns.
|
||||
*/
|
||||
#define VK_USE_PLATFORM_ANDROID_KHR
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
enum { CARDBOARD_SOURCE_SCREEN = 0, CARDBOARD_SOURCE_SBS = 1 };
|
||||
|
||||
struct cardboard_params {
|
||||
int enabled;
|
||||
int source; /* CARDBOARD_SOURCE_* */
|
||||
float ipd_m; /* distance between the eyes, metres */
|
||||
float screen_dist_m; /* virtual screen distance, metres */
|
||||
float screen_width_m;/* virtual screen width, metres */
|
||||
float k1, k2; /* lens distortion coefficients */
|
||||
float fov_deg; /* vertical field of view of one eye before distortion */
|
||||
float lens_inset; /* lens centre inset towards the nose, fraction of an eye viewport */
|
||||
float chroma; /* chromatic aberration pre-correction (0 = off) */
|
||||
};
|
||||
|
||||
/* Any thread. Values are clamped to sane ranges. */
|
||||
void vkp_cardboard_set(const struct cardboard_params *p);
|
||||
/* Any thread: the head -> world rotation, row-major 3x3. Identity = looking straight at the screen.
|
||||
* live = a sensor produced it. Also published to the guest (headpose_shm.h) once a file is set. */
|
||||
void vkp_cardboard_set_pose(const float m[9], int live);
|
||||
/* Any thread, once: where the guest's copy of the pose lives (<files>/.wayland-rt/droiddeck-headpose). */
|
||||
void vkp_cardboard_set_pose_file(const char *path);
|
||||
|
||||
/* Compositor thread. */
|
||||
void vkp_cardboard_bind_device(VkDevice dev, const VkPhysicalDeviceMemoryProperties *memprops);
|
||||
/* 1 while Cardboard mode is on (the frame must take the compositor pass). */
|
||||
int vkp_cardboard_active(void);
|
||||
/* 1 when the settings or the pose changed since the last call: the caller redraws. */
|
||||
int vkp_cardboard_pose_changed(void);
|
||||
/* Called once per frame before any vkp_cardboard_run: releases the previous frame's source views
|
||||
* (that frame is fenced by now). */
|
||||
void vkp_cardboard_begin_frame(void);
|
||||
/* Records the pass into cmd: src (src_w x src_h, R8G8B8A8, in GENERAL) -> a panel-sized image
|
||||
* (out_w x out_h), returned in GENERAL. VK_NULL_HANDLE when the pass is unavailable (the caller
|
||||
* presents the frame the usual way). */
|
||||
VkImage vkp_cardboard_run(VkCommandBuffer cmd, VkImage src, int src_w, int src_h, int out_w, int out_h);
|
||||
|
||||
/* Pure helpers, shared with the host test (tools/tests). */
|
||||
void cardboard_clamp(struct cardboard_params *p);
|
||||
/* The 24 floats after the quad's ndc in the shader's push constants. */
|
||||
void cardboard_push_constants(const struct cardboard_params *p, const float pose[9],
|
||||
int src_w, int src_h, int out_w, int out_h, float out[24]);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,266 @@
|
||||
// 1116.2.0
|
||||
#pragma once
|
||||
const uint32_t cardboard_frag_code[] = {
|
||||
0x07230203,0x00010000,0x0008000b,0x0000016d,0x00000000,0x00020011,0x00000001,0x0006000b,
|
||||
0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001,
|
||||
0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x000000ee,0x00000165,0x00030010,
|
||||
0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d,
|
||||
0x00000000,0x00070005,0x0000000d,0x69646e75,0x726f7473,0x66762874,0x31663b32,0x0000003b,
|
||||
0x00030005,0x0000000b,0x00000074,0x00040005,0x0000000c,0x6c616373,0x00000065,0x00070005,
|
||||
0x00000013,0x53657965,0x6c706d61,0x66762865,0x31663b32,0x0000003b,0x00030005,0x00000011,
|
||||
0x006e6174,0x00030005,0x00000012,0x00657965,0x00030005,0x00000015,0x00003272,0x00030005,
|
||||
0x0000001e,0x00004350,0x00040006,0x0000001e,0x00000000,0x0063646e,0x00050006,0x0000001e,
|
||||
0x00000001,0x30746f72,0x00000000,0x00050006,0x0000001e,0x00000002,0x31746f72,0x00000000,
|
||||
0x00050006,0x0000001e,0x00000003,0x32746f72,0x00000000,0x00050006,0x0000001e,0x00000004,
|
||||
0x736e656c,0x00000000,0x00050006,0x0000001e,0x00000005,0x77656976,0x00000000,0x00030005,
|
||||
0x00000020,0x00006370,0x00040005,0x0000003f,0x486e6174,0x00000000,0x00030005,0x00000042,
|
||||
0x00000073,0x00040005,0x00000068,0x72756f53,0x00006563,0x00030005,0x00000077,0x00000052,
|
||||
0x00030005,0x00000094,0x00000064,0x00030005,0x0000009f,0x0000006f,0x00030005,0x000000b3,
|
||||
0x00000074,0x00030005,0x000000bd,0x00746968,0x00040005,0x000000c3,0x666c6168,0x00000057,
|
||||
0x00040005,0x000000c6,0x666c6168,0x00000048,0x00030005,0x000000cb,0x00000073,0x00030005,
|
||||
0x000000ec,0x00657965,0x00030005,0x000000ee,0x00007675,0x00040005,0x000000f4,0x61636f6c,
|
||||
0x0000006c,0x00030005,0x000000fe,0x00007863,0x00030005,0x0000010c,0x00000070,0x00040005,
|
||||
0x00000111,0x486e6174,0x00000000,0x00030005,0x00000114,0x00000074,0x00030005,0x00000125,
|
||||
0x00000063,0x00040005,0x00000129,0x61726170,0x0000006d,0x00040005,0x0000012b,0x61726170,
|
||||
0x0000006d,0x00040005,0x0000012d,0x61726170,0x0000006d,0x00040005,0x0000012e,0x61726170,
|
||||
0x0000006d,0x00040005,0x00000133,0x61726170,0x0000006d,0x00040005,0x00000135,0x61726170,
|
||||
0x0000006d,0x00040005,0x00000137,0x61726170,0x0000006d,0x00040005,0x00000138,0x61726170,
|
||||
0x0000006d,0x00040005,0x00000140,0x61726170,0x0000006d,0x00040005,0x00000142,0x61726170,
|
||||
0x0000006d,0x00040005,0x00000144,0x61726170,0x0000006d,0x00040005,0x00000145,0x61726170,
|
||||
0x0000006d,0x00040005,0x0000014b,0x61726170,0x0000006d,0x00040005,0x0000014d,0x61726170,
|
||||
0x0000006d,0x00040005,0x0000014f,0x61726170,0x0000006d,0x00040005,0x00000150,0x61726170,
|
||||
0x0000006d,0x00030005,0x00000153,0x00000065,0x00040005,0x00000159,0x65646166,0x00000000,
|
||||
0x00050005,0x00000165,0x4374756f,0x726f6c6f,0x00000000,0x00030047,0x0000001e,0x00000002,
|
||||
0x00050048,0x0000001e,0x00000000,0x00000023,0x00000000,0x00050048,0x0000001e,0x00000001,
|
||||
0x00000023,0x00000010,0x00050048,0x0000001e,0x00000002,0x00000023,0x00000020,0x00050048,
|
||||
0x0000001e,0x00000003,0x00000023,0x00000030,0x00050048,0x0000001e,0x00000004,0x00000023,
|
||||
0x00000040,0x00050048,0x0000001e,0x00000005,0x00000023,0x00000050,0x00040047,0x00000068,
|
||||
0x00000021,0x00000000,0x00040047,0x00000068,0x00000022,0x00000000,0x00040047,0x000000ee,
|
||||
0x0000001e,0x00000000,0x00040047,0x00000165,0x0000001e,0x00000000,0x00020013,0x00000002,
|
||||
0x00030021,0x00000003,0x00000002,0x00030016,0x00000006,0x00000020,0x00040017,0x00000007,
|
||||
0x00000006,0x00000002,0x00040020,0x00000008,0x00000007,0x00000007,0x00040020,0x00000009,
|
||||
0x00000007,0x00000006,0x00050021,0x0000000a,0x00000007,0x00000008,0x00000009,0x00040017,
|
||||
0x0000000f,0x00000006,0x00000003,0x00050021,0x00000010,0x0000000f,0x00000008,0x00000009,
|
||||
0x0004002b,0x00000006,0x0000001c,0x3f800000,0x00040017,0x0000001d,0x00000006,0x00000004,
|
||||
0x0008001e,0x0000001e,0x0000001d,0x0000001d,0x0000001d,0x0000001d,0x0000001d,0x0000001d,
|
||||
0x00040020,0x0000001f,0x00000009,0x0000001e,0x0004003b,0x0000001f,0x00000020,0x00000009,
|
||||
0x00040015,0x00000021,0x00000020,0x00000001,0x0004002b,0x00000021,0x00000022,0x00000004,
|
||||
0x00040015,0x00000023,0x00000020,0x00000000,0x0004002b,0x00000023,0x00000024,0x00000000,
|
||||
0x00040020,0x00000025,0x00000009,0x00000006,0x0004002b,0x00000023,0x0000002b,0x00000001,
|
||||
0x0004002b,0x00000021,0x00000036,0x00000005,0x0004002b,0x00000023,0x00000037,0x00000002,
|
||||
0x0004002b,0x00000006,0x0000003a,0x3f000000,0x00020014,0x0000003b,0x0004002b,0x00000023,
|
||||
0x00000046,0x00000003,0x0004002b,0x00000006,0x00000054,0x00000000,0x0005002c,0x00000007,
|
||||
0x00000055,0x00000054,0x00000054,0x00040017,0x00000056,0x0000003b,0x00000002,0x0005002c,
|
||||
0x00000007,0x0000005d,0x0000001c,0x0000001c,0x0006002c,0x0000000f,0x00000063,0x00000054,
|
||||
0x00000054,0x00000054,0x00090019,0x00000065,0x00000006,0x00000001,0x00000000,0x00000000,
|
||||
0x00000000,0x00000001,0x00000000,0x0003001b,0x00000066,0x00000065,0x00040020,0x00000067,
|
||||
0x00000000,0x00000066,0x0004003b,0x00000067,0x00000068,0x00000000,0x00040018,0x00000075,
|
||||
0x0000000f,0x00000003,0x00040020,0x00000076,0x00000007,0x00000075,0x0004002b,0x00000021,
|
||||
0x00000078,0x00000001,0x00040020,0x00000079,0x00000009,0x0000001d,0x0004002b,0x00000021,
|
||||
0x0000007d,0x00000002,0x0004002b,0x00000021,0x00000081,0x00000003,0x00040020,0x00000093,
|
||||
0x00000007,0x0000000f,0x0004002b,0x00000006,0x0000009b,0xbf800000,0x0004002b,0x00000006,
|
||||
0x000000ab,0xb8d1b717,0x0004002b,0x00000006,0x000000af,0x3c75c28f,0x0004002b,0x00000006,
|
||||
0x000000b0,0x3ca3d70a,0x0006002c,0x0000000f,0x000000b1,0x000000af,0x000000af,0x000000b0,
|
||||
0x00040020,0x000000ed,0x00000001,0x00000007,0x0004003b,0x000000ed,0x000000ee,0x00000001,
|
||||
0x00040020,0x000000ef,0x00000001,0x00000006,0x0004002b,0x00000006,0x000000f7,0x40000000,
|
||||
0x0004002b,0x00000006,0x0000015a,0x3cf5c28f,0x00040020,0x00000164,0x00000003,0x0000001d,
|
||||
0x0004003b,0x00000164,0x00000165,0x00000003,0x00050036,0x00000002,0x00000004,0x00000000,
|
||||
0x00000003,0x000200f8,0x00000005,0x0004003b,0x00000009,0x000000ec,0x00000007,0x0004003b,
|
||||
0x00000008,0x000000f4,0x00000007,0x0004003b,0x00000009,0x000000fe,0x00000007,0x0004003b,
|
||||
0x00000009,0x00000101,0x00000007,0x0004003b,0x00000008,0x0000010c,0x00000007,0x0004003b,
|
||||
0x00000009,0x00000111,0x00000007,0x0004003b,0x00000008,0x00000114,0x00000007,0x0004003b,
|
||||
0x00000093,0x00000125,0x00000007,0x0004003b,0x00000008,0x00000129,0x00000007,0x0004003b,
|
||||
0x00000009,0x0000012b,0x00000007,0x0004003b,0x00000008,0x0000012d,0x00000007,0x0004003b,
|
||||
0x00000009,0x0000012e,0x00000007,0x0004003b,0x00000008,0x00000133,0x00000007,0x0004003b,
|
||||
0x00000009,0x00000135,0x00000007,0x0004003b,0x00000008,0x00000137,0x00000007,0x0004003b,
|
||||
0x00000009,0x00000138,0x00000007,0x0004003b,0x00000008,0x00000140,0x00000007,0x0004003b,
|
||||
0x00000009,0x00000142,0x00000007,0x0004003b,0x00000008,0x00000144,0x00000007,0x0004003b,
|
||||
0x00000009,0x00000145,0x00000007,0x0004003b,0x00000008,0x0000014b,0x00000007,0x0004003b,
|
||||
0x00000009,0x0000014d,0x00000007,0x0004003b,0x00000008,0x0000014f,0x00000007,0x0004003b,
|
||||
0x00000009,0x00000150,0x00000007,0x0004003b,0x00000008,0x00000153,0x00000007,0x0004003b,
|
||||
0x00000009,0x00000159,0x00000007,0x00050041,0x000000ef,0x000000f0,0x000000ee,0x00000024,
|
||||
0x0004003d,0x00000006,0x000000f1,0x000000f0,0x000500b8,0x0000003b,0x000000f2,0x000000f1,
|
||||
0x0000003a,0x000600a9,0x00000006,0x000000f3,0x000000f2,0x00000054,0x0000001c,0x0003003e,
|
||||
0x000000ec,0x000000f3,0x00050041,0x000000ef,0x000000f5,0x000000ee,0x00000024,0x0004003d,
|
||||
0x00000006,0x000000f6,0x000000f5,0x00050085,0x00000006,0x000000f8,0x000000f6,0x000000f7,
|
||||
0x0004003d,0x00000006,0x000000f9,0x000000ec,0x00050083,0x00000006,0x000000fa,0x000000f8,
|
||||
0x000000f9,0x00050041,0x000000ef,0x000000fb,0x000000ee,0x0000002b,0x0004003d,0x00000006,
|
||||
0x000000fc,0x000000fb,0x00050050,0x00000007,0x000000fd,0x000000fa,0x000000fc,0x0003003e,
|
||||
0x000000f4,0x000000fd,0x0004003d,0x00000006,0x000000ff,0x000000ec,0x000500b8,0x0000003b,
|
||||
0x00000100,0x000000ff,0x0000003a,0x000300f7,0x00000103,0x00000000,0x000400fa,0x00000100,
|
||||
0x00000102,0x00000106,0x000200f8,0x00000102,0x00060041,0x00000025,0x00000104,0x00000020,
|
||||
0x00000036,0x00000024,0x0004003d,0x00000006,0x00000105,0x00000104,0x0003003e,0x00000101,
|
||||
0x00000105,0x000200f9,0x00000103,0x000200f8,0x00000106,0x00060041,0x00000025,0x00000107,
|
||||
0x00000020,0x00000036,0x00000024,0x0004003d,0x00000006,0x00000108,0x00000107,0x0004007f,
|
||||
0x00000006,0x00000109,0x00000108,0x0003003e,0x00000101,0x00000109,0x000200f9,0x00000103,
|
||||
0x000200f8,0x00000103,0x0004003d,0x00000006,0x0000010a,0x00000101,0x00050081,0x00000006,
|
||||
0x0000010b,0x0000003a,0x0000010a,0x0003003e,0x000000fe,0x0000010b,0x0004003d,0x00000007,
|
||||
0x0000010d,0x000000f4,0x0004003d,0x00000006,0x0000010e,0x000000fe,0x00050050,0x00000007,
|
||||
0x0000010f,0x0000010e,0x0000003a,0x00050083,0x00000007,0x00000110,0x0000010d,0x0000010f,
|
||||
0x0003003e,0x0000010c,0x00000110,0x00060041,0x00000025,0x00000112,0x00000020,0x00000022,
|
||||
0x00000037,0x0004003d,0x00000006,0x00000113,0x00000112,0x0003003e,0x00000111,0x00000113,
|
||||
0x00050041,0x00000009,0x00000115,0x0000010c,0x00000024,0x0004003d,0x00000006,0x00000116,
|
||||
0x00000115,0x00060041,0x00000025,0x00000117,0x00000020,0x00000036,0x00000046,0x0004003d,
|
||||
0x00000006,0x00000118,0x00000117,0x00050085,0x00000006,0x00000119,0x00000116,0x00000118,
|
||||
0x00050041,0x00000009,0x0000011a,0x0000010c,0x0000002b,0x0004003d,0x00000006,0x0000011b,
|
||||
0x0000011a,0x00050050,0x00000007,0x0000011c,0x00000119,0x0000011b,0x0005008e,0x00000007,
|
||||
0x0000011d,0x0000011c,0x000000f7,0x0004003d,0x00000006,0x0000011e,0x00000111,0x0005008e,
|
||||
0x00000007,0x0000011f,0x0000011d,0x0000011e,0x0003003e,0x00000114,0x0000011f,0x00060041,
|
||||
0x00000025,0x00000120,0x00000020,0x00000022,0x00000046,0x0004003d,0x00000006,0x00000121,
|
||||
0x00000120,0x000500ba,0x0000003b,0x00000122,0x00000121,0x00000054,0x000300f7,0x00000124,
|
||||
0x00000000,0x000400fa,0x00000122,0x00000123,0x0000014a,0x000200f8,0x00000123,0x00060041,
|
||||
0x00000025,0x00000126,0x00000020,0x00000022,0x00000046,0x0004003d,0x00000006,0x00000127,
|
||||
0x00000126,0x00050083,0x00000006,0x00000128,0x0000001c,0x00000127,0x0004003d,0x00000007,
|
||||
0x0000012a,0x00000114,0x0003003e,0x00000129,0x0000012a,0x0003003e,0x0000012b,0x00000128,
|
||||
0x00060039,0x00000007,0x0000012c,0x0000000d,0x00000129,0x0000012b,0x0003003e,0x0000012d,
|
||||
0x0000012c,0x0004003d,0x00000006,0x0000012f,0x000000ec,0x0003003e,0x0000012e,0x0000012f,
|
||||
0x00060039,0x0000000f,0x00000130,0x00000013,0x0000012d,0x0000012e,0x00050051,0x00000006,
|
||||
0x00000131,0x00000130,0x00000000,0x00050041,0x00000009,0x00000132,0x00000125,0x00000024,
|
||||
0x0003003e,0x00000132,0x00000131,0x0004003d,0x00000007,0x00000134,0x00000114,0x0003003e,
|
||||
0x00000133,0x00000134,0x0003003e,0x00000135,0x0000001c,0x00060039,0x00000007,0x00000136,
|
||||
0x0000000d,0x00000133,0x00000135,0x0003003e,0x00000137,0x00000136,0x0004003d,0x00000006,
|
||||
0x00000139,0x000000ec,0x0003003e,0x00000138,0x00000139,0x00060039,0x0000000f,0x0000013a,
|
||||
0x00000013,0x00000137,0x00000138,0x00050051,0x00000006,0x0000013b,0x0000013a,0x00000001,
|
||||
0x00050041,0x00000009,0x0000013c,0x00000125,0x0000002b,0x0003003e,0x0000013c,0x0000013b,
|
||||
0x00060041,0x00000025,0x0000013d,0x00000020,0x00000022,0x00000046,0x0004003d,0x00000006,
|
||||
0x0000013e,0x0000013d,0x00050081,0x00000006,0x0000013f,0x0000001c,0x0000013e,0x0004003d,
|
||||
0x00000007,0x00000141,0x00000114,0x0003003e,0x00000140,0x00000141,0x0003003e,0x00000142,
|
||||
0x0000013f,0x00060039,0x00000007,0x00000143,0x0000000d,0x00000140,0x00000142,0x0003003e,
|
||||
0x00000144,0x00000143,0x0004003d,0x00000006,0x00000146,0x000000ec,0x0003003e,0x00000145,
|
||||
0x00000146,0x00060039,0x0000000f,0x00000147,0x00000013,0x00000144,0x00000145,0x00050051,
|
||||
0x00000006,0x00000148,0x00000147,0x00000002,0x00050041,0x00000009,0x00000149,0x00000125,
|
||||
0x00000037,0x0003003e,0x00000149,0x00000148,0x000200f9,0x00000124,0x000200f8,0x0000014a,
|
||||
0x0004003d,0x00000007,0x0000014c,0x00000114,0x0003003e,0x0000014b,0x0000014c,0x0003003e,
|
||||
0x0000014d,0x0000001c,0x00060039,0x00000007,0x0000014e,0x0000000d,0x0000014b,0x0000014d,
|
||||
0x0003003e,0x0000014f,0x0000014e,0x0004003d,0x00000006,0x00000151,0x000000ec,0x0003003e,
|
||||
0x00000150,0x00000151,0x00060039,0x0000000f,0x00000152,0x00000013,0x0000014f,0x00000150,
|
||||
0x0003003e,0x00000125,0x00000152,0x000200f9,0x00000124,0x000200f8,0x00000124,0x0004003d,
|
||||
0x00000007,0x00000154,0x000000f4,0x0004003d,0x00000007,0x00000155,0x000000f4,0x00050050,
|
||||
0x00000007,0x00000156,0x0000001c,0x0000001c,0x00050083,0x00000007,0x00000157,0x00000156,
|
||||
0x00000155,0x0007000c,0x00000007,0x00000158,0x00000001,0x00000025,0x00000154,0x00000157,
|
||||
0x0003003e,0x00000153,0x00000158,0x00050041,0x00000009,0x0000015b,0x00000153,0x00000024,
|
||||
0x0004003d,0x00000006,0x0000015c,0x0000015b,0x00060041,0x00000025,0x0000015d,0x00000020,
|
||||
0x00000036,0x00000046,0x0004003d,0x00000006,0x0000015e,0x0000015d,0x00050085,0x00000006,
|
||||
0x0000015f,0x0000015c,0x0000015e,0x00050041,0x00000009,0x00000160,0x00000153,0x0000002b,
|
||||
0x0004003d,0x00000006,0x00000161,0x00000160,0x0007000c,0x00000006,0x00000162,0x00000001,
|
||||
0x00000025,0x0000015f,0x00000161,0x0008000c,0x00000006,0x00000163,0x00000001,0x00000031,
|
||||
0x00000054,0x0000015a,0x00000162,0x0003003e,0x00000159,0x00000163,0x0004003d,0x0000000f,
|
||||
0x00000166,0x00000125,0x0004003d,0x00000006,0x00000167,0x00000159,0x0005008e,0x0000000f,
|
||||
0x00000168,0x00000166,0x00000167,0x00050051,0x00000006,0x00000169,0x00000168,0x00000000,
|
||||
0x00050051,0x00000006,0x0000016a,0x00000168,0x00000001,0x00050051,0x00000006,0x0000016b,
|
||||
0x00000168,0x00000002,0x00070050,0x0000001d,0x0000016c,0x00000169,0x0000016a,0x0000016b,
|
||||
0x0000001c,0x0003003e,0x00000165,0x0000016c,0x000100fd,0x00010038,0x00050036,0x00000007,
|
||||
0x0000000d,0x00000000,0x0000000a,0x00030037,0x00000008,0x0000000b,0x00030037,0x00000009,
|
||||
0x0000000c,0x000200f8,0x0000000e,0x0004003b,0x00000009,0x00000015,0x00000007,0x0004003d,
|
||||
0x00000007,0x00000016,0x0000000b,0x0004003d,0x00000007,0x00000017,0x0000000b,0x00050094,
|
||||
0x00000006,0x00000018,0x00000016,0x00000017,0x0003003e,0x00000015,0x00000018,0x0004003d,
|
||||
0x00000007,0x00000019,0x0000000b,0x0004003d,0x00000006,0x0000001a,0x0000000c,0x0005008e,
|
||||
0x00000007,0x0000001b,0x00000019,0x0000001a,0x00060041,0x00000025,0x00000026,0x00000020,
|
||||
0x00000022,0x00000024,0x0004003d,0x00000006,0x00000027,0x00000026,0x0004003d,0x00000006,
|
||||
0x00000028,0x00000015,0x00050085,0x00000006,0x00000029,0x00000027,0x00000028,0x00050081,
|
||||
0x00000006,0x0000002a,0x0000001c,0x00000029,0x00060041,0x00000025,0x0000002c,0x00000020,
|
||||
0x00000022,0x0000002b,0x0004003d,0x00000006,0x0000002d,0x0000002c,0x0004003d,0x00000006,
|
||||
0x0000002e,0x00000015,0x00050085,0x00000006,0x0000002f,0x0000002d,0x0000002e,0x0004003d,
|
||||
0x00000006,0x00000030,0x00000015,0x00050085,0x00000006,0x00000031,0x0000002f,0x00000030,
|
||||
0x00050081,0x00000006,0x00000032,0x0000002a,0x00000031,0x0005008e,0x00000007,0x00000033,
|
||||
0x0000001b,0x00000032,0x000200fe,0x00000033,0x00010038,0x00050036,0x0000000f,0x00000013,
|
||||
0x00000000,0x00000010,0x00030037,0x00000008,0x00000011,0x00030037,0x00000009,0x00000012,
|
||||
0x000200f8,0x00000014,0x0004003b,0x00000009,0x0000003f,0x00000007,0x0004003b,0x00000008,
|
||||
0x00000042,0x00000007,0x0004003b,0x00000076,0x00000077,0x00000007,0x0004003b,0x00000093,
|
||||
0x00000094,0x00000007,0x0004003b,0x00000093,0x0000009f,0x00000007,0x0004003b,0x00000009,
|
||||
0x000000b3,0x00000007,0x0004003b,0x00000093,0x000000bd,0x00000007,0x0004003b,0x00000009,
|
||||
0x000000c3,0x00000007,0x0004003b,0x00000009,0x000000c6,0x00000007,0x0004003b,0x00000008,
|
||||
0x000000cb,0x00000007,0x00060041,0x00000025,0x00000038,0x00000020,0x00000036,0x00000037,
|
||||
0x0004003d,0x00000006,0x00000039,0x00000038,0x000500ba,0x0000003b,0x0000003c,0x00000039,
|
||||
0x0000003a,0x000300f7,0x0000003e,0x00000000,0x000400fa,0x0000003c,0x0000003d,0x0000003e,
|
||||
0x000200f8,0x0000003d,0x00060041,0x00000025,0x00000040,0x00000020,0x00000022,0x00000037,
|
||||
0x0004003d,0x00000006,0x00000041,0x00000040,0x0003003e,0x0000003f,0x00000041,0x00050041,
|
||||
0x00000009,0x00000043,0x00000011,0x00000024,0x0004003d,0x00000006,0x00000044,0x00000043,
|
||||
0x0004003d,0x00000006,0x00000045,0x0000003f,0x00060041,0x00000025,0x00000047,0x00000020,
|
||||
0x00000036,0x00000046,0x0004003d,0x00000006,0x00000048,0x00000047,0x00050085,0x00000006,
|
||||
0x00000049,0x00000045,0x00000048,0x00050088,0x00000006,0x0000004a,0x00000044,0x00000049,
|
||||
0x00050041,0x00000009,0x0000004b,0x00000011,0x0000002b,0x0004003d,0x00000006,0x0000004c,
|
||||
0x0000004b,0x0004003d,0x00000006,0x0000004d,0x0000003f,0x00050088,0x00000006,0x0000004e,
|
||||
0x0000004c,0x0000004d,0x00050050,0x00000007,0x0000004f,0x0000004a,0x0000004e,0x0005008e,
|
||||
0x00000007,0x00000050,0x0000004f,0x0000003a,0x00050050,0x00000007,0x00000051,0x0000003a,
|
||||
0x0000003a,0x00050081,0x00000007,0x00000052,0x00000050,0x00000051,0x0003003e,0x00000042,
|
||||
0x00000052,0x0004003d,0x00000007,0x00000053,0x00000042,0x000500b8,0x00000056,0x00000057,
|
||||
0x00000053,0x00000055,0x0004009a,0x0000003b,0x00000058,0x00000057,0x000400a8,0x0000003b,
|
||||
0x00000059,0x00000058,0x000300f7,0x0000005b,0x00000000,0x000400fa,0x00000059,0x0000005a,
|
||||
0x0000005b,0x000200f8,0x0000005a,0x0004003d,0x00000007,0x0000005c,0x00000042,0x000500ba,
|
||||
0x00000056,0x0000005e,0x0000005c,0x0000005d,0x0004009a,0x0000003b,0x0000005f,0x0000005e,
|
||||
0x000200f9,0x0000005b,0x000200f8,0x0000005b,0x000700f5,0x0000003b,0x00000060,0x00000058,
|
||||
0x0000003d,0x0000005f,0x0000005a,0x000300f7,0x00000062,0x00000000,0x000400fa,0x00000060,
|
||||
0x00000061,0x00000062,0x000200f8,0x00000061,0x000200fe,0x00000063,0x000200f8,0x00000062,
|
||||
0x0004003d,0x00000066,0x00000069,0x00000068,0x00050041,0x00000009,0x0000006a,0x00000042,
|
||||
0x00000024,0x0004003d,0x00000006,0x0000006b,0x0000006a,0x0004003d,0x00000006,0x0000006c,
|
||||
0x00000012,0x00050081,0x00000006,0x0000006d,0x0000006b,0x0000006c,0x00050085,0x00000006,
|
||||
0x0000006e,0x0000006d,0x0000003a,0x00050041,0x00000009,0x0000006f,0x00000042,0x0000002b,
|
||||
0x0004003d,0x00000006,0x00000070,0x0000006f,0x00050050,0x00000007,0x00000071,0x0000006e,
|
||||
0x00000070,0x00050057,0x0000001d,0x00000072,0x00000069,0x00000071,0x0008004f,0x0000000f,
|
||||
0x00000073,0x00000072,0x00000072,0x00000000,0x00000001,0x00000002,0x000200fe,0x00000073,
|
||||
0x000200f8,0x0000003e,0x00050041,0x00000079,0x0000007a,0x00000020,0x00000078,0x0004003d,
|
||||
0x0000001d,0x0000007b,0x0000007a,0x0008004f,0x0000000f,0x0000007c,0x0000007b,0x0000007b,
|
||||
0x00000000,0x00000001,0x00000002,0x00050041,0x00000079,0x0000007e,0x00000020,0x0000007d,
|
||||
0x0004003d,0x0000001d,0x0000007f,0x0000007e,0x0008004f,0x0000000f,0x00000080,0x0000007f,
|
||||
0x0000007f,0x00000000,0x00000001,0x00000002,0x00050041,0x00000079,0x00000082,0x00000020,
|
||||
0x00000081,0x0004003d,0x0000001d,0x00000083,0x00000082,0x0008004f,0x0000000f,0x00000084,
|
||||
0x00000083,0x00000083,0x00000000,0x00000001,0x00000002,0x00050051,0x00000006,0x00000085,
|
||||
0x0000007c,0x00000000,0x00050051,0x00000006,0x00000086,0x0000007c,0x00000001,0x00050051,
|
||||
0x00000006,0x00000087,0x0000007c,0x00000002,0x00050051,0x00000006,0x00000088,0x00000080,
|
||||
0x00000000,0x00050051,0x00000006,0x00000089,0x00000080,0x00000001,0x00050051,0x00000006,
|
||||
0x0000008a,0x00000080,0x00000002,0x00050051,0x00000006,0x0000008b,0x00000084,0x00000000,
|
||||
0x00050051,0x00000006,0x0000008c,0x00000084,0x00000001,0x00050051,0x00000006,0x0000008d,
|
||||
0x00000084,0x00000002,0x00060050,0x0000000f,0x0000008e,0x00000085,0x00000086,0x00000087,
|
||||
0x00060050,0x0000000f,0x0000008f,0x00000088,0x00000089,0x0000008a,0x00060050,0x0000000f,
|
||||
0x00000090,0x0000008b,0x0000008c,0x0000008d,0x00060050,0x00000075,0x00000091,0x0000008e,
|
||||
0x0000008f,0x00000090,0x00040054,0x00000075,0x00000092,0x00000091,0x0003003e,0x00000077,
|
||||
0x00000092,0x0004003d,0x00000075,0x00000095,0x00000077,0x00050041,0x00000009,0x00000096,
|
||||
0x00000011,0x00000024,0x0004003d,0x00000006,0x00000097,0x00000096,0x00050041,0x00000009,
|
||||
0x00000098,0x00000011,0x0000002b,0x0004003d,0x00000006,0x00000099,0x00000098,0x0004007f,
|
||||
0x00000006,0x0000009a,0x00000099,0x00060050,0x0000000f,0x0000009c,0x00000097,0x0000009a,
|
||||
0x0000009b,0x0006000c,0x0000000f,0x0000009d,0x00000001,0x00000045,0x0000009c,0x00050091,
|
||||
0x0000000f,0x0000009e,0x00000095,0x0000009d,0x0003003e,0x00000094,0x0000009e,0x0004003d,
|
||||
0x00000075,0x000000a0,0x00000077,0x0004003d,0x00000006,0x000000a1,0x00000012,0x000500b8,
|
||||
0x0000003b,0x000000a2,0x000000a1,0x0000003a,0x000600a9,0x00000006,0x000000a3,0x000000a2,
|
||||
0x0000009b,0x0000001c,0x00060041,0x00000025,0x000000a4,0x00000020,0x00000078,0x00000046,
|
||||
0x0004003d,0x00000006,0x000000a5,0x000000a4,0x00050085,0x00000006,0x000000a6,0x000000a3,
|
||||
0x000000a5,0x00060050,0x0000000f,0x000000a7,0x000000a6,0x00000054,0x00000054,0x00050091,
|
||||
0x0000000f,0x000000a8,0x000000a0,0x000000a7,0x0003003e,0x0000009f,0x000000a8,0x00050041,
|
||||
0x00000009,0x000000a9,0x00000094,0x00000037,0x0004003d,0x00000006,0x000000aa,0x000000a9,
|
||||
0x000500ba,0x0000003b,0x000000ac,0x000000aa,0x000000ab,0x000300f7,0x000000ae,0x00000000,
|
||||
0x000400fa,0x000000ac,0x000000ad,0x000000ae,0x000200f8,0x000000ad,0x000200fe,0x000000b1,
|
||||
0x000200f8,0x000000ae,0x00060041,0x00000025,0x000000b4,0x00000020,0x0000007d,0x00000046,
|
||||
0x0004003d,0x00000006,0x000000b5,0x000000b4,0x0004007f,0x00000006,0x000000b6,0x000000b5,
|
||||
0x00050041,0x00000009,0x000000b7,0x0000009f,0x00000037,0x0004003d,0x00000006,0x000000b8,
|
||||
0x000000b7,0x00050083,0x00000006,0x000000b9,0x000000b6,0x000000b8,0x00050041,0x00000009,
|
||||
0x000000ba,0x00000094,0x00000037,0x0004003d,0x00000006,0x000000bb,0x000000ba,0x00050088,
|
||||
0x00000006,0x000000bc,0x000000b9,0x000000bb,0x0003003e,0x000000b3,0x000000bc,0x0004003d,
|
||||
0x0000000f,0x000000be,0x0000009f,0x0004003d,0x0000000f,0x000000bf,0x00000094,0x0004003d,
|
||||
0x00000006,0x000000c0,0x000000b3,0x0005008e,0x0000000f,0x000000c1,0x000000bf,0x000000c0,
|
||||
0x00050081,0x0000000f,0x000000c2,0x000000be,0x000000c1,0x0003003e,0x000000bd,0x000000c2,
|
||||
0x00060041,0x00000025,0x000000c4,0x00000020,0x00000081,0x00000046,0x0004003d,0x00000006,
|
||||
0x000000c5,0x000000c4,0x0003003e,0x000000c3,0x000000c5,0x0004003d,0x00000006,0x000000c7,
|
||||
0x000000c3,0x00060041,0x00000025,0x000000c8,0x00000020,0x00000036,0x0000002b,0x0004003d,
|
||||
0x00000006,0x000000c9,0x000000c8,0x00050088,0x00000006,0x000000ca,0x000000c7,0x000000c9,
|
||||
0x0003003e,0x000000c6,0x000000ca,0x00050041,0x00000009,0x000000cc,0x000000bd,0x00000024,
|
||||
0x0004003d,0x00000006,0x000000cd,0x000000cc,0x0004003d,0x00000006,0x000000ce,0x000000c3,
|
||||
0x00050088,0x00000006,0x000000cf,0x000000cd,0x000000ce,0x00050041,0x00000009,0x000000d0,
|
||||
0x000000bd,0x0000002b,0x0004003d,0x00000006,0x000000d1,0x000000d0,0x0004007f,0x00000006,
|
||||
0x000000d2,0x000000d1,0x0004003d,0x00000006,0x000000d3,0x000000c6,0x00050088,0x00000006,
|
||||
0x000000d4,0x000000d2,0x000000d3,0x00050050,0x00000007,0x000000d5,0x000000cf,0x000000d4,
|
||||
0x0005008e,0x00000007,0x000000d6,0x000000d5,0x0000003a,0x00050050,0x00000007,0x000000d7,
|
||||
0x0000003a,0x0000003a,0x00050081,0x00000007,0x000000d8,0x000000d6,0x000000d7,0x0003003e,
|
||||
0x000000cb,0x000000d8,0x0004003d,0x00000007,0x000000d9,0x000000cb,0x000500b8,0x00000056,
|
||||
0x000000da,0x000000d9,0x00000055,0x0004009a,0x0000003b,0x000000db,0x000000da,0x000400a8,
|
||||
0x0000003b,0x000000dc,0x000000db,0x000300f7,0x000000de,0x00000000,0x000400fa,0x000000dc,
|
||||
0x000000dd,0x000000de,0x000200f8,0x000000dd,0x0004003d,0x00000007,0x000000df,0x000000cb,
|
||||
0x000500ba,0x00000056,0x000000e0,0x000000df,0x0000005d,0x0004009a,0x0000003b,0x000000e1,
|
||||
0x000000e0,0x000200f9,0x000000de,0x000200f8,0x000000de,0x000700f5,0x0000003b,0x000000e2,
|
||||
0x000000db,0x000000ae,0x000000e1,0x000000dd,0x000300f7,0x000000e4,0x00000000,0x000400fa,
|
||||
0x000000e2,0x000000e3,0x000000e4,0x000200f8,0x000000e3,0x000200fe,0x000000b1,0x000200f8,
|
||||
0x000000e4,0x0004003d,0x00000066,0x000000e6,0x00000068,0x0004003d,0x00000007,0x000000e7,
|
||||
0x000000cb,0x00050057,0x0000001d,0x000000e8,0x000000e6,0x000000e7,0x0008004f,0x0000000f,
|
||||
0x000000e9,0x000000e8,0x000000e8,0x00000000,0x00000001,0x00000002,0x000200fe,0x000000e9,
|
||||
0x00010038
|
||||
};
|
||||
@@ -50,6 +50,7 @@
|
||||
#include "framegen_bridge.h"
|
||||
#include <pthread.h>
|
||||
#include "effects_chain.h"
|
||||
#include "cardboard.h"
|
||||
#include "droiddeck_ext.h"
|
||||
#include "droiddeck_color.h"
|
||||
#include "compositor_internal.h"
|
||||
@@ -260,6 +261,7 @@ struct surface {
|
||||
/* Toplevel placement on the scene. */
|
||||
int mapped; /* in g_toplevels */
|
||||
struct wl_list toplevel_link;
|
||||
int keep_on_top; /* Cardboard mode's SteamVR window: above every other toplevel (raise_kept_on_top) */
|
||||
int x, y, placed;
|
||||
uint32_t hwnd;
|
||||
|
||||
@@ -291,6 +293,7 @@ static struct wl_event_source *g_render_idle, *g_frame_timer;
|
||||
* window) a fallback timer renders instead. */
|
||||
static int g_dirty; /* something changed since the last render */
|
||||
static int64_t g_last_vsync_ns; /* last tick, 0 = none yet */
|
||||
static int64_t g_tick_vsync_ns; /* the vsync that tick is for (Choreographer's frame time) */
|
||||
static int64_t g_refresh_ns = 16666667; /* measured tick interval (pacing only, never reported) */
|
||||
static struct wl_event_source *g_fallback_timer;
|
||||
static int g_fallback_armed;
|
||||
@@ -631,6 +634,8 @@ static struct surface *toplevel_by_hwnd(uint32_t hwnd) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void raise_kept_on_top(void);
|
||||
|
||||
/* Reorder the mapped toplevels to match the last reported Windows z-order. Windows the
|
||||
* report doesn't mention keep their relative order below the ones it does. */
|
||||
static void apply_zorder(void) {
|
||||
@@ -640,6 +645,17 @@ static void apply_zorder(void) {
|
||||
wl_list_remove(&s->toplevel_link);
|
||||
wl_list_insert(g_toplevels.prev, &s->toplevel_link);
|
||||
}
|
||||
raise_kept_on_top();
|
||||
}
|
||||
|
||||
/* Windows marked keep_on_top go back to the top of the stack (the end of g_toplevels). */
|
||||
static void raise_kept_on_top(void) {
|
||||
struct surface *s, *tmp, *kept[4];
|
||||
int n = 0;
|
||||
wl_list_for_each_safe(s, tmp, &g_toplevels, toplevel_link) {
|
||||
if (s->keep_on_top && n < 4) { wl_list_remove(&s->toplevel_link); kept[n++] = s; }
|
||||
}
|
||||
for (int i = 0; i < n; i++) wl_list_insert(g_toplevels.prev, &kept[i]->toplevel_link);
|
||||
}
|
||||
|
||||
static void map_toplevel(struct surface *s) {
|
||||
@@ -654,6 +670,7 @@ static void map_toplevel(struct surface *s) {
|
||||
s->placed ? "" : " (no desktop position yet)");
|
||||
}
|
||||
wl_list_insert(g_toplevels.prev, &s->toplevel_link); /* new windows start on top */
|
||||
raise_kept_on_top();
|
||||
/* Without a Wine desktop the clients are whole programs (the Linux desktop, a gamescope a
|
||||
* program on it started over it): a window that opens on top takes the keys too, as it would
|
||||
* on any desktop, rather than the one clicked last that is now underneath it. */
|
||||
@@ -763,8 +780,11 @@ static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resou
|
||||
/* The window the app's performance HUD follows: the latest one at least as big as the last to
|
||||
* start presenting GPU frames (take_dmabuf) (X11 binds the HUD to the _MESA_DRV window and counts X presents instead). JNI upcalls. */
|
||||
static struct surface *g_hud_surface;
|
||||
/* When the HUD's window last presented a frame (now_ns), to let a replacement take over. */
|
||||
static int64_t g_hud_last_ns;
|
||||
/* When the HUD's window last presented a new frame (now_ns), and when it last committed at all,
|
||||
* a repeat of the frame it shows included. A replacement may take over only once it has gone
|
||||
* quiet in the second sense: gamescope repeats a paused game's frame under a busy overlay, and
|
||||
* that overlay must not become the game. */
|
||||
static int64_t g_hud_last_ns, g_hud_alive_ns;
|
||||
/* That window committed a frame the screen has not drawn yet. */
|
||||
static int g_hud_fresh;
|
||||
extern void droiddeck_on_game_surface(const char *window, const char *gpu); /* window NULL = gone */
|
||||
@@ -774,7 +794,14 @@ extern void droiddeck_on_game_frame(void);
|
||||
extern void droiddeck_on_game_program(int pid, const char *program);
|
||||
|
||||
static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_resource *buffer) {
|
||||
if (s->dmabuf != buffer || s->dmabuf_buf != b) {
|
||||
/* The buffer this surface already shows, committed again. Gamescope's Wayland backend attaches
|
||||
* every plane on every frame it outputs, so its game plane comes back unchanged whenever only
|
||||
* something above it moved (MangoHud's graph, Steam's overlay). The surface still holds it and
|
||||
* never released it, so the client cannot have drawn into it: it is no new frame. Counted as
|
||||
* one, a game capped at 30 read 50-60 fps in the HUD, and frame generation took those repeats
|
||||
* as source frames ("LSFG 2x 59 -> 54" instead of 30 -> 60). */
|
||||
const int repeat = s->dmabuf == buffer && s->dmabuf_buf == b;
|
||||
if (!repeat) {
|
||||
drop_dmabuf(s, 1);
|
||||
s->dmabuf = buffer;
|
||||
s->dmabuf_buf = b;
|
||||
@@ -809,7 +836,7 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
|
||||
s->buf_h = b->height;
|
||||
s->buf_alpha = (b->format & 0xff) == 'A';
|
||||
s->has_content = b->img != NULL;
|
||||
g_stat_dmabuf++;
|
||||
if (!repeat) g_stat_dmabuf++;
|
||||
const int announced_now = !s->announced_vulkan;
|
||||
if (!s->announced_vulkan) {
|
||||
char name[160];
|
||||
@@ -840,7 +867,7 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
|
||||
* full-screen gamescope over the desktop still does), and a window gone quiet for a second
|
||||
* gives way to whatever draws next. */
|
||||
if (s != g_hud_surface && (b->img || ahb_swapchain_has_ahb(b)) &&
|
||||
(!g_hud_surface || now_ns() - g_hud_last_ns > 1000000000LL ||
|
||||
(!g_hud_surface || now_ns() - g_hud_alive_ns > 1000000000LL ||
|
||||
(announced_now && (int64_t)b->width * b->height >= (int64_t)g_hud_surface->buf_w * g_hud_surface->buf_h))) {
|
||||
char name[160];
|
||||
describe(s, name, sizeof(name));
|
||||
@@ -869,7 +896,10 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
|
||||
* Asking whether the compositor could import it, as this used to, is a question about the
|
||||
* copy path and not about whether a frame happened: a game whose buffers go straight to
|
||||
* the display layer draws on screen while the counter sat at 0.0 fps and 1000.0 ms. */
|
||||
if (s == g_hud_surface) { g_hud_last_ns = now_ns(); g_hud_fresh = 1; droiddeck_on_game_frame(); }
|
||||
if (s == g_hud_surface) {
|
||||
g_hud_alive_ns = now_ns();
|
||||
if (!repeat) { g_hud_last_ns = g_hud_alive_ns; g_hud_fresh = 1; droiddeck_on_game_frame(); }
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- hooks for ahb_swapchain.c (zero-copy layers) */
|
||||
@@ -933,6 +963,20 @@ static uint32_t nominal_refresh_ns(void) {
|
||||
return (uint32_t)(1000000000000LL / (int64_t)mhz);
|
||||
}
|
||||
|
||||
/* The vblank a scene drawn at render_ns belongs to, for wp_presentation: the vsync of the tick that
|
||||
* drew it (Choreographer's frame time). Gamescope's Wayland backend anchors its vblank clock to this
|
||||
* and wakes a red zone before the next refresh. Reporting the end of the render instead (a few ms
|
||||
* past the tick) put its wakeups on top of the next tick: some frames missed it and showed twice,
|
||||
* others were replaced before they were shown (a 60 Hz Thor got ~50 distinct frames a second from
|
||||
* gamescope). Not the refresh after it either: gamescope then wakes a whole refresh late and runs
|
||||
* at half rate. Without a fresh tick (the fallback timer) it is the render time. */
|
||||
static int64_t presented_ns(int64_t render_ns) {
|
||||
if (!g_tick_vsync_ns || render_ns - g_last_vsync_ns > (int64_t)nominal_refresh_ns() ||
|
||||
render_ns < g_tick_vsync_ns)
|
||||
return render_ns;
|
||||
return g_tick_vsync_ns;
|
||||
}
|
||||
|
||||
static void feedback_present_all(struct wl_list *list, int64_t t) {
|
||||
struct wl_resource *fb, *tmp;
|
||||
uint64_t sec = (uint64_t)(t / 1000000000LL);
|
||||
@@ -1458,7 +1502,13 @@ static void xdg_toplevel_set_title(struct wl_client *c, struct wl_resource *r, c
|
||||
droiddeck_log("window", "renamed %s -> %s", before, after);
|
||||
}
|
||||
}
|
||||
static void xdg_toplevel_set_app_id(struct wl_client *c, struct wl_resource *r, const char *id) {}
|
||||
static void xdg_toplevel_set_app_id(struct wl_client *c, struct wl_resource *r, const char *id) {
|
||||
struct surface *s = wl_resource_get_user_data(r);
|
||||
/* Cardboard mode's SteamVR window (tools/vr/src/presenter.cpp) stays above every other window,
|
||||
* gamescope's included: gamescope reopens its window when Steam notices VR, and a reopened window
|
||||
* would otherwise come up over it (new windows start on top). */
|
||||
if (s && id && !strcmp(id, "droiddeck-cardboard-vr")) s->keep_on_top = 1;
|
||||
}
|
||||
static void xdg_toplevel_show_menu(struct wl_client *c, struct wl_resource *r, struct wl_resource *seat,
|
||||
uint32_t serial, int32_t x, int32_t y) {}
|
||||
static void xdg_toplevel_move(struct wl_client *c, struct wl_resource *r, struct wl_resource *seat,
|
||||
@@ -2071,6 +2121,8 @@ static void render_scene(void) {
|
||||
int rendered = 0;
|
||||
int fx_on = vkp_effects_active();
|
||||
int framegen = vkp_framegen_active();
|
||||
/* Cardboard mode draws the whole panel itself, so the game never gets a display layer of its own. */
|
||||
const int cardboard = vkp_cardboard_active();
|
||||
/* HDR (see hdr_plan): route 0 = the old paths below; 1 / 2 = composed; 3 = layer only, effects and
|
||||
* frame generation skipped. Always 0 while the HDR gate is closed: nothing changes for that session. */
|
||||
struct hdr_scene hs;
|
||||
@@ -2117,7 +2169,7 @@ static void render_scene(void) {
|
||||
* - screen effects DO when a window is drawn above the game: the chain has to see the whole
|
||||
* scene to look the way it does on the copy path, and here the game is only part of it. */
|
||||
const int pass_on = fx_on || framegen;
|
||||
int li = (g_zero_copy && !framegen) ? layer_candidate(&dl, w, h) : -1;
|
||||
int li = (g_zero_copy && !framegen && !cardboard) ? layer_candidate(&dl, w, h) : -1;
|
||||
int over = li >= 0 ? dl.n - 1 - li : 0; /* draws above the fullscreen game (0 or 1) */
|
||||
const int fx_blocks = (li >= 0 && fx_on && over > 0);
|
||||
if (fx_blocks) { li = -1; over = 0; }
|
||||
@@ -2147,6 +2199,7 @@ static void render_scene(void) {
|
||||
/* HDR: the same, for a game's SUBSURFACE swapchain whose 10-bit frame the compositor could not
|
||||
* import (NULL whenever the HDR gate is closed - nothing is ever noted then). */
|
||||
if (li < 0 && !ls) ls = hdr_unimported_fullscreen(&dl, w, h);
|
||||
if (cardboard) ls = NULL;
|
||||
if (ls && pass_on && li < 0 && !g_zero_copy_fx_skip_said) {
|
||||
g_zero_copy_fx_skip_said = 1;
|
||||
droiddeck_log(framegen ? "framegen" : "effects",
|
||||
@@ -2218,7 +2271,7 @@ static void render_scene(void) {
|
||||
free(hs.is_hdr);
|
||||
if (hdr_copy && rendered && droiddeck_color_hdr_open()) hdr_count_copied(&dl, hdr_copy);
|
||||
if (rendered) {
|
||||
int64_t t = now_ns();
|
||||
int64_t t = presented_ns(t_scene);
|
||||
g_stat_frames++;
|
||||
/* A surface outside the scene (role-less, not placed yet, a hidden helper window such
|
||||
* as wined3d's device window) was not shown, so its feedback is discarded rather than
|
||||
@@ -2283,12 +2336,14 @@ static void on_vsync(int64_t frame_time_ns) {
|
||||
if (d > 3000000LL && d < 40000000LL) g_refresh_ns = (g_refresh_ns * 7 + d) / 8;
|
||||
}
|
||||
g_last_vsync_ns = now;
|
||||
(void)frame_time_ns;
|
||||
g_tick_vsync_ns = frame_time_ns;
|
||||
/* The app's surface may have been replaced or taken away since the last frame: apply that now
|
||||
* (the app never waits for us), and redraw the scene onto a new one. */
|
||||
if (vkp_apply_window_request()) g_dirty = 1;
|
||||
/* A screen-effect setting changed (JNI, any thread): redraw so it shows on a static scene too. */
|
||||
if (vkp_effects_sync()) g_dirty = 1;
|
||||
/* Cardboard mode: a new head pose (or setting) moves the virtual screen, static scene or not. */
|
||||
if (vkp_cardboard_pose_changed()) g_dirty = 1;
|
||||
if (g_dirty && !scene_waits_for_game(now)) render_scene();
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
#ifndef HEADPOSE_SHM_H
|
||||
#define HEADPOSE_SHM_H
|
||||
/*
|
||||
* The head pose Cardboard mode tracks, shared with the guest: a 128-byte file the compositor maps
|
||||
* at <files>/.wayland-rt/droiddeck-headpose, which the guest sees as /run/droiddeck/droiddeck-headpose.
|
||||
* Written by the app (cardboard.c) at the sensor's rate; read by guest VR code (the SteamVR driver in
|
||||
* tools/vr) without any call into the app.
|
||||
*
|
||||
* Seqlock: the writer makes seq odd, writes the rest, then makes it even again. A reader copies the
|
||||
* struct and keeps the copy only if seq was even and unchanged across the copy.
|
||||
*
|
||||
* Axes are OpenVR's (and the cardboard shader's): x right, y up, z back (-z is straight ahead).
|
||||
* rot maps head directions to the recentred world, row-major. time_ns is CLOCK_MONOTONIC, the same
|
||||
* clock inside the guest (one kernel).
|
||||
*/
|
||||
#include <stdint.h>
|
||||
|
||||
#define DROIDDECK_HEADPOSE_MAGIC 0x50484444u /* "DDHP" */
|
||||
#define DROIDDECK_HEADPOSE_VERSION 1u
|
||||
#define DROIDDECK_HEADPOSE_FILE "droiddeck-headpose"
|
||||
|
||||
enum {
|
||||
DROIDDECK_HEADPOSE_LIVE = 1u << 0, /* a rotation sensor is feeding it (else identity) */
|
||||
DROIDDECK_HEADPOSE_ENABLED = 1u << 1, /* Cardboard mode is on */
|
||||
};
|
||||
|
||||
struct droiddeck_headpose {
|
||||
uint32_t magic;
|
||||
uint32_t version;
|
||||
uint32_t seq;
|
||||
uint32_t flags;
|
||||
float rot[9];
|
||||
float ipd_m;
|
||||
int64_t time_ns;
|
||||
/* What the lens pass expects of a side-by-side source, so a VR renderer can match it: one eye's
|
||||
* half of the frame covers tan_half_fov up and down and eye_aspect times that left and right. */
|
||||
float tan_half_fov;
|
||||
float eye_aspect;
|
||||
uint32_t eye_w, eye_h; /* one eye's viewport on the panel, pixels (0 = not drawn yet) */
|
||||
uint32_t reserved[12];
|
||||
};
|
||||
|
||||
#ifdef __cplusplus
|
||||
static_assert(sizeof(struct droiddeck_headpose) == 128, "headpose layout");
|
||||
#else
|
||||
_Static_assert(sizeof(struct droiddeck_headpose) == 128, "headpose layout");
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -5,6 +5,7 @@
|
||||
#include "vk_loader.h"
|
||||
#include "sc_layer.h"
|
||||
#include "effects_chain.h"
|
||||
#include "cardboard.h"
|
||||
#include "framegen_bridge.h"
|
||||
#include "hdr_compose.h"
|
||||
#include "blend_pass.h"
|
||||
@@ -541,6 +542,7 @@ static int dev_init(void) {
|
||||
g_vk.CreateFence(g_dev, &fci, NULL, &g_fence);
|
||||
|
||||
vkp_effects_bind_device(g_dev, g_pd, &g_memprops);
|
||||
vkp_cardboard_bind_device(g_dev, &g_memprops);
|
||||
hdrc_bind_device(g_dev, &g_memprops);
|
||||
blendp_bind_device(g_dev);
|
||||
g_dev_state = 1;
|
||||
@@ -1342,8 +1344,28 @@ static const char *vk_result_name(VkResult r) {
|
||||
* standing for the whole scene) through the scene -> output mapping, and leave the image ready
|
||||
* to present. */
|
||||
static void record_screen_blit(VkCommandBuffer cmd, VkImage src, int src_w, int src_h,
|
||||
int scene_w, int scene_h, uint32_t img, VkFilter filter) {
|
||||
int scene_w, int scene_h, uint32_t img, VkFilter filter, int cardboard) {
|
||||
VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
|
||||
/* Cardboard mode (cardboard.h): the pass turns src into the two eye views over the whole panel,
|
||||
* and that image is blitted 1:1 instead of src going through the scene mapping. */
|
||||
int direct = 0;
|
||||
if (cardboard) {
|
||||
VkImageMemoryBarrier rd = {
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_GENERAL,
|
||||
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
|
||||
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.image = src, .subresourceRange = range,
|
||||
.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT, .dstAccessMask = VK_ACCESS_SHADER_READ_BIT};
|
||||
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
|
||||
0, 0, NULL, 0, NULL, 1, &rd);
|
||||
VkImage eyes = vkp_cardboard_run(cmd, src, src_w, src_h, (int)g_extent.width, (int)g_extent.height);
|
||||
if (eyes) {
|
||||
src = eyes;
|
||||
src_w = (int)g_extent.width;
|
||||
src_h = (int)g_extent.height;
|
||||
direct = 1;
|
||||
}
|
||||
}
|
||||
VkImageMemoryBarrier pre[2] = {
|
||||
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
|
||||
@@ -1361,7 +1383,12 @@ static void record_screen_blit(VkCommandBuffer cmd, VkImage src, int src_w, int
|
||||
struct vkp_image tmp = {.w = src_w, .h = src_h}; /* only its size is looked at */
|
||||
struct vkp_draw d = {&tmp, 0, 0, (float)src_w, (float)src_h, 0, 0, scene_w, scene_h};
|
||||
VkImageBlit blit;
|
||||
const int have_blit = draw_to_blit(&d, &blit);
|
||||
const int have_blit = direct ? 1 : draw_to_blit(&d, &blit);
|
||||
if (direct)
|
||||
blit = (VkImageBlit){.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
|
||||
.srcOffsets = {{0, 0, 0}, {src_w, src_h, 1}},
|
||||
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
|
||||
.dstOffsets = {{0, 0, 0}, {src_w, src_h, 1}}};
|
||||
/* The result fills its whole mapped rectangle, so only the letterbox bars around it need black. */
|
||||
if (!have_blit || !record_bars_clear(cmd, g_images[img], &blit)) {
|
||||
VkClearColorValue black = {.float32 = {0.0f, 0.0f, 0.0f, 1.0f}};
|
||||
@@ -1571,6 +1598,15 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
* blit filter follows the scaling mode. */
|
||||
const int fx = !g_plain_frame && vkp_effects_active();
|
||||
const int fg = !g_plain_frame && vkp_framegen_active();
|
||||
/* Cardboard mode needs the whole frame too; it works on the 8-bit picture only (an HDR frame
|
||||
* is shown flat, said once). */
|
||||
int cb = !g_plain_frame && vkp_cardboard_active();
|
||||
if (cb && hf) {
|
||||
static int said;
|
||||
if (!said) { said = 1; droiddeck_log("cardboard", "HDR frames are shown flat: the cardboard pass is 8-bit only"); }
|
||||
cb = 0;
|
||||
}
|
||||
vkp_cardboard_begin_frame();
|
||||
/* HDR frames with frame generation through an HDR10 swapchain: the scene, the effects and the
|
||||
* engine's frames in FP16 (FG_HDR_FMT) where the engine can take that format - more than 8 bits of
|
||||
* PQ through interpolation - else the 8-bit scene, as before. */
|
||||
@@ -1594,7 +1630,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
}
|
||||
}
|
||||
/* An HDR scene always takes the pass: its draws are composed into one encoding first. */
|
||||
const int pass = deep || ((fx || fg || (hf && n > 0)) && ensure_scene_image(scene_w, scene_h) == 0);
|
||||
const int pass = deep || ((fx || fg || cb || (hf && n > 0)) && ensure_scene_image(scene_w, scene_h) == 0);
|
||||
VkImage scene_img = deep ? g_fgscene.img : g_scene.img;
|
||||
const VkFormat scene_fmt = deep ? FG_HDR_FMT : SCENE_FMT;
|
||||
const VkFilter blit_filter = vkp_effects_blit_filter();
|
||||
@@ -1746,7 +1782,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
}
|
||||
|
||||
/* 4. Mapping/blit: the first present carries generated frame 0, or the result itself. */
|
||||
record_screen_blit(cmd, ngen ? gens[0] : result, rw, rh, scene_w, scene_h, img, blit_filter);
|
||||
record_screen_blit(cmd, ngen ? gens[0] : result, rw, rh, scene_w, scene_h, img, blit_filter, cb);
|
||||
}
|
||||
g_vk.EndCommandBuffer(cmd);
|
||||
|
||||
@@ -1770,7 +1806,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
VkCommandBuffer ck = g_cmds[k];
|
||||
g_vk.ResetCommandBuffer(ck, 0);
|
||||
g_vk.BeginCommandBuffer(ck, &bi);
|
||||
record_screen_blit(ck, k < ngen ? gens[k] : result, rw, rh, scene_w, scene_h, img, blit_filter);
|
||||
record_screen_blit(ck, k < ngen ? gens[k] : result, rw, rh, scene_w, scene_h, img, blit_filter, cb);
|
||||
g_vk.EndCommandBuffer(ck);
|
||||
}
|
||||
const int last = (k + 1 == presents);
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
#include "ahb_swapchain.h"
|
||||
#include "sc_layer.h"
|
||||
#include "effects_chain.h"
|
||||
#include "cardboard.h"
|
||||
#include "droiddeck_color.h"
|
||||
|
||||
extern int droiddeck_wayland_run(void);
|
||||
@@ -463,6 +464,36 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetScreenEffects(JNI
|
||||
vkp_effects_set_screen(brightness, contrast, gamma, saturation, fxaa ? 1 : 0, toon ? 1 : 0, crt ? 1 : 0, ntsc ? 1 : 0);
|
||||
}
|
||||
|
||||
/* Cardboard mode - WaylandCompositor.nativeSetCardboard. */
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetCardboard(JNIEnv *env, jclass clazz, jboolean enabled,
|
||||
jint source, jfloat ipd, jfloat dist, jfloat width, jfloat k1, jfloat k2, jfloat fov, jfloat inset, jfloat chroma) {
|
||||
struct cardboard_params p = {.enabled = enabled ? 1 : 0, .source = source, .ipd_m = ipd, .screen_dist_m = dist,
|
||||
.screen_width_m = width, .k1 = k1, .k2 = k2, .fov_deg = fov, .lens_inset = inset,
|
||||
.chroma = chroma};
|
||||
vkp_cardboard_set(&p);
|
||||
}
|
||||
|
||||
/* The head pose (row-major 3x3, head -> world), from the sensor thread. */
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetCardboardPose(JNIEnv *env, jclass clazz, jfloatArray rot,
|
||||
jboolean live) {
|
||||
float m[9];
|
||||
if (!rot || (*env)->GetArrayLength(env, rot) < 9) return;
|
||||
(*env)->GetFloatArrayRegion(env, rot, 0, 9, m);
|
||||
vkp_cardboard_set_pose(m, live ? 1 : 0);
|
||||
}
|
||||
|
||||
/* Where the head pose is shared with the guest - WaylandCompositor.nativeSetCardboardPoseFile. */
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetCardboardPoseFile(JNIEnv *env, jclass clazz, jstring path) {
|
||||
if (!path) return;
|
||||
const char *p = (*env)->GetStringUTFChars(env, path, NULL);
|
||||
if (!p) return;
|
||||
vkp_cardboard_set_pose_file(p);
|
||||
(*env)->ReleaseStringUTFChars(env, path, p);
|
||||
}
|
||||
|
||||
/* One "display" line in the session log, written from Java: facts that live in the Android
|
||||
* framework (the panel's HDR capability) rather than in the compositor. droiddeck_log() mirrors to
|
||||
* logcat and appends to the session file when one is open, so this is safe at any point. */
|
||||
|
||||
@@ -49,7 +49,10 @@ import com.droiddeck.launcher.stores.StoreAchievements
|
||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||
import com.droiddeck.launcher.stores.StoreLaunchRequests
|
||||
import com.droiddeck.launcher.ui.SessionAchievements
|
||||
import com.droiddeck.launcher.gpu.Cardboard
|
||||
import com.droiddeck.launcher.gpu.FrameGen
|
||||
import com.droiddeck.launcher.gpu.HeadTracker
|
||||
import com.droiddeck.launcher.gpu.SteamVr
|
||||
import com.droiddeck.launcher.gpu.ScreenEffectLooks
|
||||
import com.droiddeck.launcher.gpu.ScreenEffects
|
||||
import com.droiddeck.launcher.gpu.Lossless
|
||||
@@ -297,6 +300,25 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private var upscaler by mutableStateOf(0)
|
||||
private var upscaleSharpness by mutableStateOf(75)
|
||||
private var effects by mutableStateOf(ScreenEffects.OFF)
|
||||
/** Cardboard mode (gpu/Cardboard) and the sensor that turns the virtual screen with the head. */
|
||||
private var cardboard by mutableStateOf(Cardboard.OFF)
|
||||
private var headTracker: HeadTracker? = null
|
||||
private var steamVrStatus by mutableStateOf<SteamVr.Status?>(null)
|
||||
/** The picture was switched to side-by-side for SteamVR and goes back when it stops. */
|
||||
private var steamVrSwitchedPicture by mutableStateOf(false)
|
||||
/** SteamVR has been seen running since the switch: only then does "not running" mean it stopped. */
|
||||
private var steamVrSeenRunning = false
|
||||
private val hasRotationSensor by lazy {
|
||||
(getSystemService(SENSOR_SERVICE) as android.hardware.SensorManager).let {
|
||||
it.getDefaultSensor(android.hardware.Sensor.TYPE_GAME_ROTATION_VECTOR)
|
||||
?: it.getDefaultSensor(android.hardware.Sensor.TYPE_ROTATION_VECTOR)
|
||||
} != null
|
||||
}
|
||||
// Held in a field: SharedPreferences keeps its listeners weakly. A change from anywhere (the
|
||||
// drawer, tools/droiddeckctl prefs set) applies live.
|
||||
private val cardboardPrefListener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
|
||||
if (key == SessionPrefs.CARDBOARD_KEY) uiHandler.post { applyCardboard(SessionPrefs.cardboard(this)) }
|
||||
}
|
||||
private var textureAnisotropy by mutableStateOf(0)
|
||||
private var textureLodBias by mutableStateOf(TextureFiltering.LOD_BIAS_OFF)
|
||||
private var drawerTextureAnisotropy by mutableStateOf<Int?>(null)
|
||||
@@ -571,6 +593,18 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
releaseDrawerDirection()
|
||||
}
|
||||
}
|
||||
// SteamVR's state for the Cardboard group, refreshed while the drawer shows it.
|
||||
// Watched for as long as Cardboard mode is on (or the picture is switched for it), drawer open or
|
||||
// not: however SteamVR is started or quit, the picture follows it.
|
||||
LaunchedEffect(cardboard.enabled, steamVrSwitchedPicture) {
|
||||
while (cardboard.enabled || steamVrSwitchedPicture) {
|
||||
val now = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
|
||||
SteamVr.status(this@SessionActivity)
|
||||
}
|
||||
onSteamVrStatus(now)
|
||||
kotlinx.coroutines.delay(3000)
|
||||
}
|
||||
}
|
||||
LaunchedEffect(drawerOpen, achievementsOpen, AgentGuest.focusRevision, StoreAchievements.revision) {
|
||||
if (!drawerOpen && !achievementsOpen) return@LaunchedEffect
|
||||
val found = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
|
||||
@@ -596,6 +630,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
hudOn = hudOn,
|
||||
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
|
||||
effects = effects,
|
||||
cardboard = cardboard,
|
||||
cardboardSensor = hasRotationSensor,
|
||||
onCardboard = { c -> SessionPrefs.setCardboard(this@SessionActivity, c); applyCardboard(c) },
|
||||
onCardboardRecenter = { headTracker?.recenter() },
|
||||
steamVr = steamVrStatus,
|
||||
onSteamVr = { action -> steamVrAction(action) },
|
||||
textureAnisotropy = if (drawerGameProfileId == null) textureAnisotropy else drawerTextureAnisotropy,
|
||||
textureLodBias = if (drawerGameProfileId == null) textureLodBias else drawerTextureLodBias,
|
||||
frameGen = frameGen,
|
||||
@@ -1126,6 +1166,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
upscaler = SessionPrefs.upscaler(this)
|
||||
upscaleSharpness = SessionPrefs.upscaleSharpness(this)
|
||||
effects = SessionPrefs.screenEffects(this)
|
||||
applyCardboard(SessionPrefs.cardboard(this))
|
||||
// A switch left from before this activity (or this resume): SteamVR was running then, so the next
|
||||
// "not running" hands the picture back.
|
||||
if (SessionPrefs.cardboardSourceBeforeSteamVr(this) >= 0 && !steamVrSwitchedPicture) {
|
||||
steamVrSwitchedPicture = true
|
||||
steamVrSeenRunning = true
|
||||
}
|
||||
textureAnisotropy = SessionPrefs.textureAnisotropy(this)
|
||||
textureLodBias = SessionPrefs.textureLodBias(this)
|
||||
val nextTouchMode = SessionPrefs.touchMode(this)
|
||||
@@ -1331,6 +1378,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
WaylandCompositor.nativeSetUpscaler(SessionPrefs.upscaler(this))
|
||||
WaylandCompositor.nativeSetUpscaleSharpness(SessionPrefs.upscaleSharpness(this))
|
||||
SessionPrefs.screenEffects(this).push(SessionPrefs.upscaler(this))
|
||||
panelSizeMm().let { (w, h) -> SessionPrefs.cardboard(this).push(w, h) }
|
||||
WaylandCompositor.nativeSetCardboardPoseFile(File(filesDir, ".wayland-rt/droiddeck-headpose").path)
|
||||
// The session's folder, claimed here because the compositor starts before the service and
|
||||
// opens its log once. The compositor reads the path from its environment; setting it after
|
||||
// it has started changes nothing, which is why the service copies the file in at teardown.
|
||||
@@ -1489,13 +1538,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
* The rate of the mode PerfMode asked for, not the one the panel is still in: the switch lands
|
||||
* some frames after onCreate, and read too early it gave gamescope `-r 60` on a 120 Hz panel -
|
||||
* the client and every game then paced themselves to 60. (WinNative's requestedPanelRefreshRate.)
|
||||
* Never above the user's peak refresh rate, which Android holds the panel to whatever mode is
|
||||
* active; it is the rate gamescope gives Steam, and the QAM's Frame Limit divides it.
|
||||
*/
|
||||
private fun refreshHz(): Float {
|
||||
val display = if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay
|
||||
val wanted = window.attributes.preferredDisplayModeId
|
||||
val hz = display?.supportedModes?.firstOrNull { wanted != 0 && it.modeId == wanted }?.refreshRate
|
||||
?: display?.refreshRate ?: 60f
|
||||
return if (hz > 1f) hz else 60f
|
||||
val capped = minOf(hz, PerfMode.peakRefreshCap(this))
|
||||
return if (capped > 1f) capped else 60f
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2512,6 +2564,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
readPrefs()
|
||||
if (::pip.isInitialized) pip.resumed()
|
||||
if (CompositorHost.isStarted) applyFrameGen()
|
||||
SessionPrefs.sessionPrefs(this).registerOnSharedPreferenceChangeListener(cardboardPrefListener)
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
@@ -2530,9 +2583,103 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
updatePointerCapture()
|
||||
updatePadMotion()
|
||||
keyboard?.takeIf { it.shown }?.hide()
|
||||
SessionPrefs.sessionPrefs(this).unregisterOnSharedPreferenceChangeListener(cardboardPrefListener)
|
||||
updateHeadTracker()
|
||||
super.onPause()
|
||||
}
|
||||
|
||||
/** SteamVR for Cardboard mode: install, start or stop it in the guest. Starting switches the
|
||||
* picture to side-by-side, which is what SteamVR draws. */
|
||||
private fun steamVrAction(action: String) {
|
||||
if (action == "start") {
|
||||
switchPictureForSteamVr()
|
||||
steamVrSeenRunning = false
|
||||
}
|
||||
if (action == "stop") restoreSteamVrPicture()
|
||||
if (action == "install") steamVrStatus = SteamVr.Status.INSTALLING
|
||||
Thread({
|
||||
val ok = SteamVr.run(this, action)
|
||||
val now = SteamVr.status(this)
|
||||
uiHandler.post {
|
||||
// A start that failed leaves nothing side-by-side to show: the picture goes back.
|
||||
if (!ok && action == "start" && now != SteamVr.Status.RUNNING) restoreSteamVrPicture()
|
||||
onSteamVrStatus(now)
|
||||
if (!ok) Toast.makeText(this, getString(R.string.cardboard_steamvr_failed), Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}, "steamvr-$action").start()
|
||||
}
|
||||
|
||||
/** SteamVR draws a side-by-side pair: the picture switches to that, remembering what it was. */
|
||||
private fun switchPictureForSteamVr() {
|
||||
if (cardboard.source != Cardboard.SOURCE_SBS) {
|
||||
SessionPrefs.setCardboardSourceBeforeSteamVr(this, cardboard.source)
|
||||
val c = cardboard.copy(source = Cardboard.SOURCE_SBS)
|
||||
SessionPrefs.setCardboard(this, c)
|
||||
applyCardboard(c)
|
||||
}
|
||||
steamVrSwitchedPicture = SessionPrefs.cardboardSourceBeforeSteamVr(this) >= 0
|
||||
}
|
||||
|
||||
private fun onSteamVrStatus(now: SteamVr.Status) {
|
||||
steamVrStatus = now
|
||||
// Started some other way than the drawer (a script, a VR game): the picture follows it all the same.
|
||||
if (now == SteamVr.Status.RUNNING && cardboard.enabled && !steamVrSwitchedPicture &&
|
||||
cardboard.source != Cardboard.SOURCE_SBS) {
|
||||
switchPictureForSteamVr()
|
||||
steamVrSeenRunning = true
|
||||
}
|
||||
if (!steamVrSwitchedPicture) return
|
||||
if (now == SteamVr.Status.RUNNING) steamVrSeenRunning = true
|
||||
else if (steamVrSeenRunning && now != SteamVr.Status.UNAVAILABLE) restoreSteamVrPicture()
|
||||
}
|
||||
|
||||
/** SteamVR stopped: the Cardboard picture goes back to what it was before Start. */
|
||||
private fun restoreSteamVrPicture() {
|
||||
val before = SessionPrefs.cardboardSourceBeforeSteamVr(this)
|
||||
SessionPrefs.setCardboardSourceBeforeSteamVr(this, -1)
|
||||
steamVrSwitchedPicture = false
|
||||
steamVrSeenRunning = false
|
||||
if (before < 0 || cardboard.source == before) return
|
||||
val c = cardboard.copy(source = before)
|
||||
SessionPrefs.setCardboard(this, c)
|
||||
applyCardboard(c)
|
||||
}
|
||||
|
||||
/** Cardboard mode: hand the settings to the compositor and run the head tracker while it needs one. */
|
||||
private fun applyCardboard(c: Cardboard) {
|
||||
val was = cardboard
|
||||
cardboard = c
|
||||
if (CompositorHost.isStarted) panelSizeMm().let { (w, h) -> c.push(w, h) }
|
||||
if (c.enabled && !was.enabled) headTracker?.recenter()
|
||||
updateHeadTracker()
|
||||
}
|
||||
|
||||
private fun updateHeadTracker() {
|
||||
// Side-by-side sources track too: the compositor leaves their picture alone, but whoever renders
|
||||
// it (the SteamVR driver, tools/vr) reads the pose from the shared file.
|
||||
val want = resumed && cardboard.enabled && cardboard.headTracking
|
||||
if (want) {
|
||||
val t = headTracker ?: HeadTracker(this) {
|
||||
@Suppress("DEPRECATION")
|
||||
(if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay)?.rotation ?: android.view.Surface.ROTATION_0
|
||||
}.also { headTracker = it }
|
||||
t.start()
|
||||
} else {
|
||||
headTracker?.stop()
|
||||
}
|
||||
}
|
||||
|
||||
/** The panel's physical size in millimetres, long side first, for lining the eyes up with the lenses. */
|
||||
private fun panelSizeMm(): Pair<Float, Float> {
|
||||
val dm = resources.displayMetrics
|
||||
val landscape = dm.widthPixels >= dm.heightPixels
|
||||
val longPx = maxOf(dm.widthPixels, dm.heightPixels).toFloat()
|
||||
val shortPx = minOf(dm.widthPixels, dm.heightPixels).toFloat()
|
||||
val longDpi = if (landscape) dm.xdpi else dm.ydpi
|
||||
val shortDpi = if (landscape) dm.ydpi else dm.xdpi
|
||||
return (if (longDpi > 0f) longPx / longDpi * 25.4f else 0f) to (if (shortDpi > 0f) shortPx / shortDpi * 25.4f else 0f)
|
||||
}
|
||||
|
||||
override fun onAttachedToWindow() {
|
||||
super.onAttachedToWindow()
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import org.json.JSONObject
|
||||
import kotlin.math.sqrt
|
||||
|
||||
/**
|
||||
* Cardboard mode: the compositor draws the session as two lens-distorted eye views side by side
|
||||
* (waylandcomp/src/cardboard.c), for a phone or handheld dropped into a Google Cardboard-style
|
||||
* viewer. Units are the menu's own:
|
||||
*
|
||||
* - [ipdMm] distance between the eyes, millimetres
|
||||
* - [screenWidthDm] the virtual screen's width, decimetres (40 = 4 m)
|
||||
* - [screenDistanceDm] how far away it hangs, decimetres (30 = 3 m)
|
||||
* - [viewer] a [Viewer] id: the lens it is drawn for
|
||||
*
|
||||
* [source] SCREEN shows the frame as a flat virtual screen, world-locked by the rotation sensor
|
||||
* when [headTracking] is on (3DoF), with real stereo depth from the IPD. SBS takes a frame that is
|
||||
* already a left/right pair (SteamVR, SBS 3D games and video) and only adds the lens.
|
||||
*/
|
||||
data class Cardboard(
|
||||
val enabled: Boolean = false,
|
||||
val source: Int = SOURCE_SCREEN,
|
||||
val viewer: String = Viewer.CARDBOARD_V2.id,
|
||||
val ipdMm: Int = 64,
|
||||
val screenWidthDm: Int = 40,
|
||||
val screenDistanceDm: Int = 30,
|
||||
val headTracking: Boolean = true,
|
||||
) {
|
||||
val lens: Viewer get() = Viewer.byId(viewer)
|
||||
|
||||
/**
|
||||
* Hands the settings to the compositor. [panelWidthMm] x [panelHeightMm] is the physical size of
|
||||
* the panel the eyes are drawn on (0 = unknown). The width decides how far each lens centre sits
|
||||
* from its viewport's centre, so the two pictures line up with the viewer's lenses; the height,
|
||||
* seen through the lens from its focal distance, is the field of view the distortion works in.
|
||||
*/
|
||||
fun push(panelWidthMm: Float, panelHeightMm: Float) {
|
||||
val l = lens
|
||||
WaylandCompositor.nativeSetCardboard(enabled, source, ipdMm / 1000f, screenDistanceDm / 10f,
|
||||
screenWidthDm / 10f, l.k1, l.k2, fovDeg(l, panelHeightMm), lensInset(panelWidthMm, l.lensSeparationMm), l.chroma)
|
||||
}
|
||||
|
||||
fun encode(): JSONObject = JSONObject()
|
||||
.put("enabled", enabled).put("source", source).put("viewer", viewer).put("ipdMm", ipdMm)
|
||||
.put("screenWidthDm", screenWidthDm).put("screenDistanceDm", screenDistanceDm).put("headTracking", headTracking)
|
||||
|
||||
/**
|
||||
* A lens the eyes can be drawn for: its distortion (Cardboard viewer profile coefficients, in
|
||||
* tangent units at the panel), how far it sits from the panel, and how far apart the two are.
|
||||
* [fallbackFovDeg] is the eye's field of view when the panel's size is unknown, or with no lens.
|
||||
*/
|
||||
enum class Viewer(val id: String, val k1: Float, val k2: Float, val screenToLensMm: Float,
|
||||
val lensSeparationMm: Float, val chroma: Float, val fallbackFovDeg: Float) {
|
||||
/** Google Cardboard (2015): the common plastic and cardboard viewers. */
|
||||
CARDBOARD_V2("cardboard2", 0.34f, 0.55f, 39.3f, 63.9f, 0.006f, 90f),
|
||||
/** The original 2014 Cardboard: narrower, gentler lenses. */
|
||||
CARDBOARD_V1("cardboard1", 0.441f, 0.156f, 42f, 60f, 0.004f, 80f),
|
||||
/** No lens: side-by-side 3D glasses, a 3D TV, or just looking at the stereo pair. */
|
||||
NONE("none", 0f, 0f, 0f, 0f, 0f, 60f);
|
||||
|
||||
companion object {
|
||||
fun byId(id: String): Viewer = entries.firstOrNull { it.id == id } ?: CARDBOARD_V2
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val SOURCE_SCREEN = 0
|
||||
const val SOURCE_SBS = 1
|
||||
|
||||
val OFF = Cardboard()
|
||||
|
||||
fun decode(json: JSONObject): Cardboard = Cardboard(
|
||||
enabled = json.optBoolean("enabled", false),
|
||||
source = if (json.optInt("source", SOURCE_SCREEN) == SOURCE_SBS) SOURCE_SBS else SOURCE_SCREEN,
|
||||
viewer = Viewer.byId(json.optString("viewer", Viewer.CARDBOARD_V2.id)).id,
|
||||
ipdMm = json.optInt("ipdMm", 64).coerceIn(50, 80),
|
||||
screenWidthDm = json.optInt("screenWidthDm", 40).coerceIn(5, 200),
|
||||
screenDistanceDm = json.optInt("screenDistanceDm", 30).coerceIn(5, 200),
|
||||
headTracking = json.optBoolean("headTracking", true),
|
||||
)
|
||||
|
||||
/**
|
||||
* One eye's vertical field of view on the panel side of the lens: half the panel's height
|
||||
* seen from the lens's focal distance. The lens then spreads it wider (the distortion).
|
||||
*/
|
||||
fun fovDeg(viewer: Viewer, panelHeightMm: Float): Float {
|
||||
if (panelHeightMm <= 0f || viewer.screenToLensMm <= 0f) return viewer.fallbackFovDeg
|
||||
val half = Math.toDegrees(kotlin.math.atan((panelHeightMm / 2f / viewer.screenToLensMm).toDouble())).toFloat()
|
||||
return (2f * half).coerceIn(30f, 140f)
|
||||
}
|
||||
|
||||
/**
|
||||
* The lens centre's inset towards the nose, as a fraction of one eye viewport's width. Each
|
||||
* eye gets half the panel, so its viewport centre is a quarter of the panel from the middle;
|
||||
* the lens centre is half the lens separation from it. 0 when either is unknown.
|
||||
*/
|
||||
fun lensInset(panelWidthMm: Float, lensSeparationMm: Float): Float {
|
||||
if (panelWidthMm <= 0f || lensSeparationMm <= 0f) return 0f
|
||||
val inset = (panelWidthMm / 4f - lensSeparationMm / 2f) / (panelWidthMm / 2f)
|
||||
return inset.coerceIn(-0.25f, 0.25f)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Head pose maths for Cardboard mode, kept free of Android types so it is unit-tested on the JVM.
|
||||
* Matrices are row-major 3x3 FloatArrays. "World" is Android's sensor world (x east, y north,
|
||||
* z up); "screen" axes are x right, y up, z out of the panel towards the viewer's eyes.
|
||||
*/
|
||||
object HeadPose {
|
||||
val IDENTITY = floatArrayOf(1f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 1f)
|
||||
|
||||
/** Unit quaternion (x, y, z, w) -> rotation matrix: what SensorManager.getRotationMatrixFromVector gives. */
|
||||
fun fromQuaternion(x: Float, y: Float, z: Float, w: Float): FloatArray {
|
||||
val n = sqrt(x * x + y * y + z * z + w * w).takeIf { it > 1e-6f } ?: 1f
|
||||
val qx = x / n; val qy = y / n; val qz = z / n; val qw = w / n
|
||||
return floatArrayOf(
|
||||
1 - 2 * (qy * qy + qz * qz), 2 * (qx * qy - qz * qw), 2 * (qx * qz + qy * qw),
|
||||
2 * (qx * qy + qz * qw), 1 - 2 * (qx * qx + qz * qz), 2 * (qy * qz - qx * qw),
|
||||
2 * (qx * qz - qy * qw), 2 * (qy * qz + qx * qw), 1 - 2 * (qx * qx + qy * qy),
|
||||
)
|
||||
}
|
||||
|
||||
/** The rotation vector sensor's values -> (x, y, z, w), computing w when the sensor leaves it out. */
|
||||
fun quaternionFromRotationVector(v: FloatArray): FloatArray {
|
||||
val x = v[0]; val y = v[1]; val z = v[2]
|
||||
val w = if (v.size >= 4) v[3] else sqrt((1f - x * x - y * y - z * z).coerceAtLeast(0f))
|
||||
return floatArrayOf(x, y, z, w)
|
||||
}
|
||||
|
||||
/**
|
||||
* Device -> screen axes for a Display rotation (Surface.ROTATION_* as 0..3): the returned matrix
|
||||
* maps screen to world, given the device's own device -> world matrix. The same transform as
|
||||
* input/PadMotion's and SensorManager.remapCoordinateSystem's (ROTATION_90 = AXIS_Y, AXIS_MINUS_X:
|
||||
* the device's x is the screen's y, its y the screen's -x).
|
||||
*/
|
||||
fun toScreen(deviceToWorld: FloatArray, rotation: Int): FloatArray {
|
||||
// Columns of A: where each screen axis points in device coordinates.
|
||||
val a = when (rotation and 3) {
|
||||
1 -> floatArrayOf(0f, 1f, 0f, -1f, 0f, 0f, 0f, 0f, 1f) // screen x = -device y, y = device x
|
||||
2 -> floatArrayOf(-1f, 0f, 0f, 0f, -1f, 0f, 0f, 0f, 1f) // screen x = -device x, y = -device y
|
||||
3 -> floatArrayOf(0f, -1f, 0f, 1f, 0f, 0f, 0f, 0f, 1f) // screen x = device y, y = -device x
|
||||
else -> IDENTITY
|
||||
}
|
||||
return multiply(deviceToWorld, a)
|
||||
}
|
||||
|
||||
/** sin(60 degrees): a view further from level than this is "held flat" for recentring. */
|
||||
private const val FLAT_SIN = 0.866f
|
||||
|
||||
/**
|
||||
* What a recentre locks to. The pose the compositor gets is basis^T * screenToWorld * tilt:
|
||||
* - [basis]: a level frame (columns right, up, back in world) facing the recentred heading. Every
|
||||
* rotation is measured in it, so turning about the real vertical always pans the view;
|
||||
* - [tilt]: the device's own tilt at the recentre, taken out so that pose starts straight ahead.
|
||||
* Identity when the device was held upright: the horizon then stays the true one.
|
||||
*/
|
||||
class Reference(val basis: FloatArray, val tilt: FloatArray)
|
||||
|
||||
/**
|
||||
* Recentre on the current orientation. Held upright (the screen within 60 degrees of vertical, as
|
||||
* in a viewer), only the heading resets: forward is where the screen faces. Held flat (lying back,
|
||||
* or the device on a table or in the hands like a tray), forward is where the top of the screen
|
||||
* points and the tilt resets too; turning at the hips still pans, tipping the device still tilts.
|
||||
*/
|
||||
fun recenter(screenToWorld: FloatArray): Reference {
|
||||
val fz = -screenToWorld[8]
|
||||
val flat = kotlin.math.abs(fz) > FLAT_SIN
|
||||
// Upright: the screen's -z. Flat: the screen's +y (its top edge), which is level then.
|
||||
var fx = if (flat) screenToWorld[1] else -screenToWorld[2]
|
||||
var fy = if (flat) screenToWorld[4] else -screenToWorld[5]
|
||||
val len = sqrt(fx * fx + fy * fy).takeIf { it > 1e-4f } ?: run { fx = 0f; fy = 1f; 1f }
|
||||
fx /= len; fy /= len
|
||||
// right = forward x up(0,0,1) = (fy, -fx, 0); up = (0,0,1); back = -forward.
|
||||
val basis = floatArrayOf(
|
||||
fy, 0f, -fx,
|
||||
-fx, 0f, -fy,
|
||||
0f, 1f, 0f,
|
||||
)
|
||||
val tilt = if (flat) multiply(transpose(screenToWorld), basis) else IDENTITY
|
||||
return Reference(basis, tilt)
|
||||
}
|
||||
|
||||
/** head -> recentred world: what the compositor takes. */
|
||||
fun relative(ref: Reference, screenToWorld: FloatArray): FloatArray =
|
||||
multiply(multiply(transpose(ref.basis), screenToWorld), ref.tilt)
|
||||
|
||||
fun multiply(a: FloatArray, b: FloatArray): FloatArray = FloatArray(9) { i ->
|
||||
val r = i / 3; val c = i % 3
|
||||
a[r * 3] * b[c] + a[r * 3 + 1] * b[3 + c] + a[r * 3 + 2] * b[6 + c]
|
||||
}
|
||||
|
||||
fun transpose(m: FloatArray): FloatArray = floatArrayOf(m[0], m[3], m[6], m[1], m[4], m[7], m[2], m[5], m[8])
|
||||
|
||||
/** m * v for a 3-vector. */
|
||||
fun apply(m: FloatArray, v: FloatArray): FloatArray = floatArrayOf(
|
||||
m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
|
||||
m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
|
||||
m[6] * v[0] + m[7] * v[1] + m[8] * v[2],
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import android.content.Context
|
||||
import android.hardware.Sensor
|
||||
import android.hardware.SensorEvent
|
||||
import android.hardware.SensorEventListener
|
||||
import android.hardware.SensorManager
|
||||
import android.os.Handler
|
||||
import android.os.HandlerThread
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
|
||||
/**
|
||||
* 3DoF head tracking for Cardboard mode: the rotation sensor -> the compositor's head pose
|
||||
* ([HeadPose] for the maths). Game rotation vector first (gyro + accelerometer: no compass jumps
|
||||
* indoors, and only the heading drifts, which a recentre fixes); the plain rotation vector where a
|
||||
* device has no game one. Events arrive on a thread of their own and go straight to native code,
|
||||
* so the session's UI thread never sits between the sensor and the screen.
|
||||
*
|
||||
* [rotation] is the Display rotation (Surface.ROTATION_*) the session is drawn in.
|
||||
*/
|
||||
class HeadTracker(context: Context, private val rotation: () -> Int) : SensorEventListener {
|
||||
private val sensors = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
|
||||
private val sensor: Sensor? = sensors.getDefaultSensor(Sensor.TYPE_GAME_ROTATION_VECTOR)
|
||||
?: sensors.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR)
|
||||
private var thread: HandlerThread? = null
|
||||
@Volatile private var reference: HeadPose.Reference? = null
|
||||
@Volatile private var recenterPending = true
|
||||
@Volatile private var latest: FloatArray? = null
|
||||
|
||||
/** Whether this device has a rotation sensor at all (no sensor = a fixed, head-locked screen). */
|
||||
val available: Boolean get() = sensor != null
|
||||
val sensorName: String get() = sensor?.let { "${it.name} (${if (it.type == Sensor.TYPE_GAME_ROTATION_VECTOR) "game rotation vector" else "rotation vector"})" } ?: "none"
|
||||
|
||||
fun start() {
|
||||
val s = sensor ?: run {
|
||||
WaylandCompositor.nativeLog("cardboard", "no rotation sensor: the virtual screen stays head-locked")
|
||||
WaylandCompositor.nativeSetCardboardPose(HeadPose.IDENTITY, false)
|
||||
return
|
||||
}
|
||||
if (thread != null) return
|
||||
recenterPending = true
|
||||
val t = HandlerThread("droiddeck-headtracker").also { it.start() }
|
||||
thread = t
|
||||
sensors.registerListener(this, s, SensorManager.SENSOR_DELAY_FASTEST, Handler(t.looper))
|
||||
WaylandCompositor.nativeLog("cardboard", "head tracking on: $sensorName")
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
val t = thread ?: return
|
||||
sensors.unregisterListener(this)
|
||||
t.quitSafely()
|
||||
thread = null
|
||||
WaylandCompositor.nativeSetCardboardPose(HeadPose.IDENTITY, false)
|
||||
}
|
||||
|
||||
/** Make where the viewer looks now straight ahead (see HeadPose.recenter). */
|
||||
fun recenter() {
|
||||
recenterPending = true
|
||||
latest?.let { apply(it) }
|
||||
}
|
||||
|
||||
override fun onSensorChanged(event: SensorEvent) {
|
||||
val q = HeadPose.quaternionFromRotationVector(event.values)
|
||||
val m = HeadPose.toScreen(HeadPose.fromQuaternion(q[0], q[1], q[2], q[3]), rotation())
|
||||
latest = m
|
||||
apply(m)
|
||||
}
|
||||
|
||||
private fun apply(screenToWorld: FloatArray) {
|
||||
val ref = reference.takeUnless { recenterPending } ?: HeadPose.recenter(screenToWorld).also {
|
||||
reference = it
|
||||
recenterPending = false
|
||||
}
|
||||
WaylandCompositor.nativeSetCardboardPose(HeadPose.relative(ref, screenToWorld), true)
|
||||
}
|
||||
|
||||
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
|
||||
Log.d("DroidDeck", "head tracker accuracy $accuracy")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.agent.AgentGuest
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* Cardboard mode's SteamVR (docs/cardboard-vr.md): Valve's ARM64 SteamVR in the guest, rendering
|
||||
* through the DroidDeck driver as a side-by-side pair that the Cardboard pass puts the lens on. Driven
|
||||
* through the guest agent's fixed "vr" request (droiddeck-steamvr), so it needs no agent commands.
|
||||
* Every call blocks on the guest: run them off the main thread.
|
||||
*/
|
||||
object SteamVr {
|
||||
enum class Status {
|
||||
/** No session, no agent, or a runtime without the helper or the driver. */
|
||||
UNAVAILABLE,
|
||||
NOT_INSTALLED,
|
||||
/** Downloading or unpacking (571 MB). */
|
||||
INSTALLING,
|
||||
READY,
|
||||
RUNNING,
|
||||
}
|
||||
|
||||
fun status(context: Context): Status = runCatching {
|
||||
parse(AgentGuest.call(context, JSONObject().put("kind", "vr").put("action", "status"), STATUS_TIMEOUT_MS))
|
||||
}.getOrDefault(Status.UNAVAILABLE)
|
||||
|
||||
/** install, start or stop; true when the guest did it. */
|
||||
fun run(context: Context, action: String): Boolean = runCatching {
|
||||
require(action in setOf("install", "start", "stop"))
|
||||
succeeded(action, AgentGuest.call(context, JSONObject().put("kind", "vr").put("action", action), ACTION_TIMEOUT_MS))
|
||||
}.getOrDefault(false)
|
||||
|
||||
/**
|
||||
* The agent answers ok whenever it ran the request, even when droiddeck-steamvr then failed; the
|
||||
* helper's own exit code says whether start or stop worked. install runs detached and only reports
|
||||
* that it started (its progress shows in status).
|
||||
*/
|
||||
fun succeeded(action: String, answer: JSONObject): Boolean = when {
|
||||
!answer.optBoolean("ok", false) -> false
|
||||
action == "install" -> answer.optBoolean("started", false)
|
||||
else -> answer.optInt("exitCode", -1) == 0
|
||||
}
|
||||
|
||||
/** The agent's status answer -> what the menu shows. */
|
||||
fun parse(answer: JSONObject): Status = when {
|
||||
!answer.optBoolean("ok", false) -> Status.UNAVAILABLE
|
||||
answer.optInt("exitCode", 0) != 0 -> Status.UNAVAILABLE
|
||||
answer.optBoolean("installing") -> Status.INSTALLING
|
||||
!answer.optBoolean("driver") -> Status.UNAVAILABLE
|
||||
!answer.optBoolean("installed") -> Status.NOT_INSTALLED
|
||||
answer.optBoolean("running") -> Status.RUNNING
|
||||
else -> Status.READY
|
||||
}
|
||||
|
||||
private const val STATUS_TIMEOUT_MS = 10_000L
|
||||
private const val ACTION_TIMEOUT_MS = 40_000L
|
||||
}
|
||||
@@ -3,7 +3,9 @@ package com.droiddeck.launcher.session
|
||||
import android.app.Activity
|
||||
import android.app.GameManager
|
||||
import android.app.GameState
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
|
||||
/**
|
||||
@@ -16,8 +18,9 @@ import android.util.Log
|
||||
* a level the device can hold indefinitely rather than holding a floor, which cost games and
|
||||
* Big Picture their peak clocks. WinNative never asks for it; the thermal budget is left to
|
||||
* the game;
|
||||
* - the panel's fastest mode at its current size (Android 6+): a 120 Hz phone is switched to
|
||||
* 120 Hz for the menu, not only when a game votes for it. With a frame cap, the fastest mode
|
||||
* - the panel's fastest mode at its current size (Android 6+), up to the user's peak refresh rate
|
||||
* ([peakRefreshCap]): a 120 Hz phone is switched to 120 Hz for the menu, not only when a game
|
||||
* votes for it. With a frame cap, the fastest mode
|
||||
* the cap divides evenly, so every capped frame is shown for the same number of refreshes;
|
||||
* - GameManager's game state (Android 13+): "in gameplay", so an OEM framework that releases
|
||||
* its boost on loading screens or menus keeps it up.
|
||||
@@ -36,8 +39,11 @@ object PerfMode {
|
||||
val display = if (Build.VERSION.SDK_INT >= 30) a.display else @Suppress("DEPRECATION") a.windowManager.defaultDisplay
|
||||
if (display == null || Build.VERSION.SDK_INT < 23) "display mode unchanged" else {
|
||||
val cur = display.mode
|
||||
val cap = peakRefreshCap(a)
|
||||
val sameSize = display.supportedModes
|
||||
.filter { it.physicalWidth == cur.physicalWidth && it.physicalHeight == cur.physicalHeight }
|
||||
.filter { it.refreshRate <= cap + 0.5f }
|
||||
.ifEmpty { display.supportedModes.filter { it.modeId == cur.modeId } }
|
||||
val best = sameSize.filter { cadenceFits(it.refreshRate, fpsLimit) }.maxByOrNull { it.refreshRate }
|
||||
?: sameSize.maxByOrNull { it.refreshRate }
|
||||
if (best != null && best.modeId != cur.modeId &&
|
||||
@@ -68,6 +74,20 @@ object PerfMode {
|
||||
return parts.joinToString(" · ")
|
||||
}
|
||||
|
||||
/**
|
||||
* The highest rate Android will run the panel at: the user's "peak refresh rate" (Smooth display,
|
||||
* or the AYN/Odin quick-settings tile). Above it a mode can be requested and is even reported back
|
||||
* as active, while SurfaceFlinger keeps composing at the cap. The Thor set to 60 Hz ran 120 Hz
|
||||
* sessions at 60: gamescope and Steam were told 120, every game topped out at 60, and the QAM's
|
||||
* Frame Limit read "60 FPS (120 Hz)" and changed nothing. Unset (most phones) is no cap.
|
||||
*/
|
||||
fun peakRefreshCap(context: Context): Float {
|
||||
val peak = try {
|
||||
Settings.System.getFloat(context.contentResolver, "peak_refresh_rate")
|
||||
} catch (_: Throwable) { 0f }
|
||||
return if (peak >= 1f) peak else Float.POSITIVE_INFINITY
|
||||
}
|
||||
|
||||
/** A panel rate that shows every capped frame for a whole number of refreshes (no cap: any). */
|
||||
fun cadenceFits(hz: Float, fpsLimit: Int): Boolean {
|
||||
if (fpsLimit <= 0) return true
|
||||
|
||||
@@ -87,6 +87,8 @@ object SessionFiles {
|
||||
"usr/local/bin/droiddeck-open-url" to "usr/local/bin/droiddeck-open-url",
|
||||
"usr/local/bin/droiddeck-steam-games" to "usr/local/bin/droiddeck-steam-games",
|
||||
"usr/local/bin/droiddeck-pad-defaults" to "usr/local/bin/droiddeck-pad-defaults",
|
||||
// Cardboard mode's SteamVR: install, start and stop (docs/cardboard-vr.md).
|
||||
"usr/local/bin/droiddeck-steamvr" to "usr/local/bin/droiddeck-steamvr",
|
||||
// Flatpak: the bwrap stand-in, the store's helper and setup, and the front end's launcher.
|
||||
"usr/local/bin/droiddeck-bwrap" to "usr/local/bin/droiddeck-bwrap",
|
||||
"usr/local/bin/droiddeck-flatpak" to "usr/local/bin/droiddeck-flatpak",
|
||||
@@ -133,6 +135,18 @@ object SessionFiles {
|
||||
val msitools = listOf("msiinfo", "cabextract", "7z", "7z.so", "libmsi-1.0.so.0", "libgsf-1.so.114", "libgcab-1.0.so.0")
|
||||
.map { "usr/local/lib/droiddeck-msitools/$it" } +
|
||||
listOf("NOTICE", "GPL-2", "GPL-3", "LGPL-2.1", "7zip-License", "7zip-unRarLicense").map { "usr/local/share/licenses/droiddeck-msitools/$it" }
|
||||
// Cardboard mode's SteamVR driver and the Vulkan layer its compositor needs (tools/vr).
|
||||
val vr = listOf(
|
||||
"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",
|
||||
).map { "usr/local/lib/droiddeck-vr/$it" to "usr/local/lib/droiddeck-vr/$it" } +
|
||||
// The same layer, implicit for the whole session: it passes everything through until SteamVR
|
||||
// runs, then Steam's own web helper gets the shared-texture support it needs (tools/vr).
|
||||
listOf("usr/local/lib/droiddeck-vr/layer/VK_LAYER_DROIDDECK_vr_implicit.json" to
|
||||
"usr/share/vulkan/implicit_layer.d/droiddeck_vr.json")
|
||||
val fexPreloads = listOf("x86_64", "i386").flatMap { arch ->
|
||||
listOf("libblsession.so", "libfakeinput.so", "libfaultreport.so").map { "$arch/$it" to "usr/local/lib/droiddeck-fex/$arch/$it" }
|
||||
} + listOf("libthunkaudit.so", "libvulkan-thunk.so").map { "x86_64/$it" to "usr/local/lib/droiddeck-fex/x86_64/$it" }
|
||||
@@ -140,7 +154,7 @@ object SessionFiles {
|
||||
"usr/local/bin/gamescope" to "usr/local/bin/gamescope",
|
||||
"usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime",
|
||||
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
|
||||
) + mangoapp + listOf("comet", "GalaxyCommunication.exe", "update-permissions.exe", "LICENSE", "version").map { "usr/local/lib/droiddeck-comet/$it" to "usr/local/lib/droiddeck-comet/$it" } + msitools.map { it to it } + fexPreloads).filter { (asset, _) ->
|
||||
) + mangoapp + listOf("comet", "GalaxyCommunication.exe", "update-permissions.exe", "LICENSE", "version").map { "usr/local/lib/droiddeck-comet/$it" to "usr/local/lib/droiddeck-comet/$it" } + msitools.map { it to it } + vr + fexPreloads).filter { (asset, _) ->
|
||||
val dir = asset.substringBeforeLast('/')
|
||||
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.core.CpuAllocationDefaults
|
||||
import com.droiddeck.launcher.core.GameEnvironment
|
||||
import com.droiddeck.launcher.core.TextureFiltering
|
||||
import com.droiddeck.launcher.gpu.Cardboard
|
||||
import com.droiddeck.launcher.gpu.ScreenEffects
|
||||
import org.json.JSONObject
|
||||
|
||||
@@ -845,6 +846,31 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("screenEffects", effects.encode().toString()).apply()
|
||||
}
|
||||
|
||||
/** The key [cardboard] lives under; SessionActivity watches it so a change applies live. */
|
||||
const val CARDBOARD_KEY = "cardboard"
|
||||
|
||||
/** Cardboard mode (gpu/Cardboard) as last set; off by default. */
|
||||
fun cardboard(context: Context): Cardboard {
|
||||
val text = prefs(context).getString(CARDBOARD_KEY, null) ?: return Cardboard.OFF
|
||||
return runCatching { Cardboard.decode(JSONObject(text)) }.getOrDefault(Cardboard.OFF)
|
||||
}
|
||||
|
||||
fun setCardboard(context: Context, cardboard: Cardboard) {
|
||||
prefs(context).edit().putString(CARDBOARD_KEY, cardboard.encode().toString()).apply()
|
||||
}
|
||||
|
||||
/** The Cardboard picture (Cardboard.SOURCE_*) to go back to once SteamVR stops; -1 = none (it was
|
||||
* not switched for SteamVR). Kept across activity restarts, so a SteamVR session that outlives the
|
||||
* activity still hands the picture back. */
|
||||
fun cardboardSourceBeforeSteamVr(context: Context): Int = prefs(context).getInt("cardboardSourceBeforeSteamVr", -1)
|
||||
|
||||
fun setCardboardSourceBeforeSteamVr(context: Context, source: Int) {
|
||||
prefs(context).edit().putInt("cardboardSourceBeforeSteamVr", source).apply()
|
||||
}
|
||||
|
||||
/** The prefs file [cardboard] lives in, for a change listener. */
|
||||
fun sessionPrefs(context: Context): android.content.SharedPreferences = prefs(context)
|
||||
|
||||
val textureAnisotropyChoices = TextureFiltering.ANISOTROPY.map { it to if (it == 0) "Off" else "${it}x" }
|
||||
|
||||
/** [textureAnisotropyChoices] labelled in the app's language. */
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
package com.droiddeck.launcher.stores
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.net.URLEncoder
|
||||
import java.time.LocalDate
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.time.format.FormatStyle
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
/**
|
||||
* What other sites know of a store game, looked up by its title: the Metacritic score (as Steam's
|
||||
* store search carries it) and HowLongToBeat's times. Neither store publishes these, so every
|
||||
* lookup is a name match against someone else's catalog, kept on disk a fortnight (a miss for two
|
||||
* days) and in memory for the process. Blocking: call off the main thread.
|
||||
*/
|
||||
object GameFacts {
|
||||
private const val TAG = "GameFacts"
|
||||
private const val HIT_TTL_MS = 14L * 24 * 60 * 60 * 1000
|
||||
private const val MISS_TTL_MS = 2L * 24 * 60 * 60 * 1000
|
||||
private const val TIMEOUT_MS = 10_000
|
||||
|
||||
/** Metacritic's critic score (0-100) and the game's page there. */
|
||||
data class Metacritic(val score: Int, val url: String)
|
||||
|
||||
/** HowLongToBeat's community times, in seconds (0 when nobody has logged that kind of run), and the game's page there. */
|
||||
data class Hltb(val main: Int, val extras: Int, val completionist: Int, val url: String) {
|
||||
val isEmpty: Boolean get() = main <= 0 && extras <= 0 && completionist <= 0
|
||||
}
|
||||
|
||||
/** A remembered answer: [value] null is a remembered miss. */
|
||||
private class Entry<T>(val value: T?, val at: Long) {
|
||||
fun fresh(now: Long) = now - at < if (value != null) HIT_TTL_MS else MISS_TTL_MS
|
||||
}
|
||||
|
||||
private val memory = ConcurrentHashMap<String, Entry<*>>()
|
||||
|
||||
/** The score or the times already in memory, without touching disk or network; null when not yet known. */
|
||||
fun peekMetacritic(title: String): Lookup<Metacritic>? = peek("metacritic", title)
|
||||
fun peekHltb(title: String): Lookup<Hltb>? = peek("hltb", title)
|
||||
|
||||
/** The score, or null when Steam does not list the game or has no score for it. */
|
||||
fun metacritic(context: Context, title: String): Metacritic? =
|
||||
remembered(context, "metacritic", title,
|
||||
read = { o -> o.optInt("score").takeIf { it > 0 }?.let { Metacritic(it, o.optString("url").ifEmpty { metacriticSearch(title) }) } },
|
||||
write = { o, v -> o.put("score", v.score).put("url", v.url) },
|
||||
) { searchSteamScore(title) }
|
||||
|
||||
fun hltb(context: Context, title: String): Hltb? =
|
||||
remembered(context, "hltb", title,
|
||||
read = { o -> Hltb(o.optInt("main"), o.optInt("extras"), o.optInt("completionist"), o.optString("url").ifEmpty { hltbSearch(title) }).takeUnless { it.isEmpty } },
|
||||
write = { o, v -> o.put("main", v.main).put("extras", v.extras).put("completionist", v.completionist).put("url", v.url) },
|
||||
) { searchHltb(title) }
|
||||
|
||||
// Where a game goes when its own page is not known: the site's search for its name.
|
||||
private fun metacriticSearch(title: String) = "https://www.metacritic.com/search/${encodePath(TitleMatch.searchTerm(title))}/?category=13"
|
||||
private fun hltbSearch(title: String) = "$HLTB/?q=${URLEncoder.encode(TitleMatch.searchTerm(title), "UTF-8")}"
|
||||
private fun encodePath(s: String) = URLEncoder.encode(s, "UTF-8").replace("+", "%20")
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
private fun <T> peek(kind: String, title: String): Lookup<T>? {
|
||||
val e = memory[key(kind, title)] as Entry<T>? ?: return null
|
||||
return e.value?.let { Lookup.Found(it) } ?: Lookup.None
|
||||
}
|
||||
|
||||
/**
|
||||
* The memory copy, else the disk copy while fresh, else [fetch]. [fetch] answers a [Fetched]:
|
||||
* a failed request is not a miss, so it leaves the stale copy (if any) standing.
|
||||
*/
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
private fun <T : Any> remembered(
|
||||
context: Context, kind: String, title: String,
|
||||
read: (JSONObject) -> T?, write: (JSONObject, T) -> Unit, fetch: () -> Fetched<T>,
|
||||
): T? {
|
||||
val now = System.currentTimeMillis()
|
||||
val k = key(kind, title)
|
||||
(memory[k] as Entry<T>?)?.takeIf { it.fresh(now) }?.let { return it.value }
|
||||
val file = File(context.filesDir, "game-facts/$kind/${fileName(title)}.json")
|
||||
val disk = runCatching { JSONObject(file.readText()) }.getOrNull()
|
||||
?.let { o -> Entry(if (o.optBoolean("none")) null else read(o), o.optLong("at")) }
|
||||
if (disk != null && disk.fresh(now)) { memory[k] = disk; return disk.value }
|
||||
return when (val got = fetch()) {
|
||||
is Fetched.Failed -> disk?.value
|
||||
is Fetched.Answer -> {
|
||||
val entry = Entry(got.value, now)
|
||||
memory[k] = entry
|
||||
runCatching {
|
||||
file.parentFile?.mkdirs()
|
||||
val o = JSONObject().put("at", now)
|
||||
if (got.value != null) write(o, got.value) else o.put("none", true)
|
||||
file.writeText(o.toString())
|
||||
}
|
||||
got.value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private sealed interface Fetched<out T> {
|
||||
object Failed : Fetched<Nothing>
|
||||
class Answer<T>(val value: T?) : Fetched<T>
|
||||
}
|
||||
|
||||
private fun key(kind: String, title: String) = "$kind:${TitleMatch.normalize(title)}"
|
||||
|
||||
private fun fileName(title: String) = TitleMatch.normalize(title).take(80).ifEmpty { "_" + title.hashCode().toUInt() }
|
||||
|
||||
// Steam's store search lists a game's Metacritic score beside its name: one request, no key.
|
||||
// The game's own Metacritic page is in its app details, asked for only once there is a score.
|
||||
private fun searchSteamScore(title: String): Fetched<Metacritic> {
|
||||
val term = URLEncoder.encode(TitleMatch.searchTerm(title), "UTF-8")
|
||||
val body = StoreNet.get("https://store.steampowered.com/api/storesearch/?l=english&cc=US&term=$term", timeoutMs = TIMEOUT_MS)
|
||||
?: return Fetched.Failed
|
||||
return runCatching {
|
||||
val items = JSONObject(body).optJSONArray("items") ?: JSONArray()
|
||||
val scored = (0 until items.length()).mapNotNull { items.optJSONObject(it) }
|
||||
.filter { it.optString("type") == "app" && (it.optString("metascore").toIntOrNull() ?: 0) > 0 }
|
||||
val best = TitleMatch.pick(title, scored) { listOf(it.optString("name")) }
|
||||
val score = best?.optString("metascore")?.toIntOrNull() ?: return Fetched.Answer(null)
|
||||
Fetched.Answer(Metacritic(score, metacriticPage(best.optLong("id")) ?: metacriticSearch(title)))
|
||||
}.getOrElse { Fetched.Failed }
|
||||
}
|
||||
|
||||
/** Steam's link to the game on Metacritic, without its tracking tag; null when Steam gives none. */
|
||||
private fun metacriticPage(appId: Long): String? {
|
||||
if (appId <= 0) return null
|
||||
val body = StoreNet.get("https://store.steampowered.com/api/appdetails?appids=$appId&filters=metacritic", timeoutMs = TIMEOUT_MS) ?: return null
|
||||
return runCatching {
|
||||
JSONObject(body).optJSONObject("$appId")?.optJSONObject("data")?.optJSONObject("metacritic")?.optString("url")
|
||||
?.substringBefore('?')?.takeIf { it.startsWith("https://") }
|
||||
}.getOrNull()
|
||||
}
|
||||
|
||||
// HowLongToBeat's own site search: a short-lived token from init, sent back as x-auth-token.
|
||||
// The token is bound to the User-Agent that asked for it, so both calls send the same one.
|
||||
private const val HLTB = "https://howlongtobeat.com"
|
||||
private val hltbHeaders = mapOf("Referer" to "$HLTB/", "Origin" to HLTB)
|
||||
@Volatile private var hltbToken: Pair<String, Long>? = null
|
||||
|
||||
private fun hltbToken(renew: Boolean): String? {
|
||||
val now = System.currentTimeMillis()
|
||||
hltbToken?.takeIf { !renew && now - it.second < 10 * 60 * 1000 }?.let { return it.first }
|
||||
val body = StoreNet.get("$HLTB/api/search/site/init?t=$now", timeoutMs = TIMEOUT_MS, headers = hltbHeaders) ?: return null
|
||||
val token = runCatching { JSONObject(body).optString("token") }.getOrNull()?.takeIf { it.isNotBlank() } ?: return null
|
||||
hltbToken = token to now
|
||||
return token
|
||||
}
|
||||
|
||||
private fun searchHltb(title: String): Fetched<Hltb> {
|
||||
val terms = JSONArray().apply { TitleMatch.searchTerm(title).split(' ').filter { it.isNotBlank() }.forEach { put(it) } }
|
||||
val request = JSONObject()
|
||||
.put("searchType", "games").put("searchTerms", terms).put("searchPage", 1).put("size", 20)
|
||||
.put("searchOptions", JSONObject()
|
||||
.put("games", JSONObject().put("userId", 0).put("platform", "").put("sortCategory", "popular").put("rangeCategory", "main")
|
||||
.put("rangeTime", JSONObject().put("min", 0).put("max", 0))
|
||||
.put("gameplay", JSONObject().put("perspective", "").put("flow", "").put("genre", ""))
|
||||
.put("year", "").put("modifier", ""))
|
||||
.put("users", JSONObject().put("sortCategory", "postcount"))
|
||||
.put("lists", JSONObject().put("sortCategory", "follows"))
|
||||
.put("filter", "").put("sort", 0).put("randomizer", 0))
|
||||
.put("useCache", true)
|
||||
.toString()
|
||||
// A token can lapse between init and search; one fresh one is worth a second try.
|
||||
var body: String? = null
|
||||
for (renew in listOf(false, true)) {
|
||||
val token = hltbToken(renew) ?: return Fetched.Failed
|
||||
body = StoreNet.postJson("$HLTB/api/search/site", request, timeoutMs = TIMEOUT_MS, headers = hltbHeaders + ("x-auth-token" to token))
|
||||
if (body != null) break
|
||||
}
|
||||
if (body == null) return Fetched.Failed
|
||||
return runCatching {
|
||||
val data = JSONObject(body).optJSONArray("data") ?: JSONArray()
|
||||
val games = (0 until data.length()).mapNotNull { data.optJSONObject(it) }
|
||||
.sortedByDescending { it.optString("game_type") == "game" }
|
||||
val best = TitleMatch.pick(title, games) { g -> listOf(g.optString("game_name")) + g.optString("game_alias").split(',') }
|
||||
Fetched.Answer(best?.let {
|
||||
val page = it.optInt("game_id").takeIf { id -> id > 0 }?.let { id -> "$HLTB/game/$id" } ?: hltbSearch(title)
|
||||
Hltb(it.optInt("comp_main"), it.optInt("comp_plus"), it.optInt("comp_100"), page)
|
||||
}?.takeUnless { it.isEmpty })
|
||||
}.getOrElse {
|
||||
Log.w(TAG, "HowLongToBeat answer unreadable: ${it.javaClass.simpleName}")
|
||||
Fetched.Failed
|
||||
}
|
||||
}
|
||||
|
||||
/** A store's release date ("2015.05.19", "2015-05-19T00:00:00+02:00", ...) in the reader's own words, or null. */
|
||||
fun releaseLabel(raw: String): String? {
|
||||
val m = Regex("""^(\d{4})[.\-/](\d{2})[.\-/](\d{2})""").find(raw.trim()) ?: return null
|
||||
val (y, mo, d) = m.destructured
|
||||
// Epic dates a title it has no date for 2099-01-01.
|
||||
val date = runCatching { LocalDate.of(y.toInt(), mo.toInt(), d.toInt()) }.getOrNull()?.takeIf { it.year in 1970..2098 } ?: return null
|
||||
return date.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM))
|
||||
}
|
||||
|
||||
/** Whole hours, with a half when the time is nearer one: "51½". Under an hour, null (the caller says minutes). */
|
||||
fun hours(seconds: Int): String? {
|
||||
if (seconds < 3600) return null
|
||||
val halves = Math.round(seconds / 1800.0).toInt()
|
||||
return "${halves / 2}" + if (halves % 2 == 1) "½" else ""
|
||||
}
|
||||
}
|
||||
|
||||
/** A fact looked up off the page: still asking, found, or not to be had. */
|
||||
sealed interface Lookup<out T> {
|
||||
object Pending : Lookup<Nothing>
|
||||
object None : Lookup<Nothing>
|
||||
data class Found<T>(val value: T) : Lookup<T>
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether two catalogs mean the same game. Store titles carry marks, editions and subtitles the
|
||||
* other site spells differently ("The Witcher 3: Wild Hunt" is Steam's "...Wild Hunt — Remastered");
|
||||
* a sequel is never the same game ("Hades" is not "Hades II").
|
||||
*/
|
||||
internal object TitleMatch {
|
||||
private val MARKS = Regex("[™®©]")
|
||||
private val EDITION = Regex(
|
||||
"(?i)[\\s:\\-–—]*\\b(?:(?:complete|definitive|legendary|deluxe|ultimate|enhanced|gold|premium|standard|special|anniversary|collector'?s|digital deluxe|game of the year|goty)\\s+edition|goty|director'?s cut)\\b",
|
||||
)
|
||||
// Where a subtitle starts: a colon or dash with space around it, or an opening bracket.
|
||||
private val SUBTITLE = Regex("\\s*[:–—]\\s*|\\s+-\\s+|\\s*\\(")
|
||||
|
||||
fun normalize(s: String): String = s.lowercase().replace(MARKS, "").replace("&", "and").replace(Regex("[^\\p{L}\\p{N}]"), "")
|
||||
|
||||
fun stripEdition(s: String): String = s.replace(EDITION, " ").trim().ifEmpty { s }
|
||||
|
||||
/**
|
||||
* What to type into another site's search: the title without its marks, edition or subtitle
|
||||
* punctuation (Steam finds nothing for "Disco Elysium - The Final Cut", all of it for the words).
|
||||
*/
|
||||
fun searchTerm(title: String): String =
|
||||
stripEdition(title.replace(MARKS, "")).replace(Regex("\\s+[-–—]\\s+|[:–—()\\[\\]]"), " ").replace(Regex("\\s+"), " ").trim()
|
||||
|
||||
/** 3 the same name, 2 the same but for the edition, 1 one is the other with a subtitle, 0 not the same game. */
|
||||
fun score(want: String, got: String): Int {
|
||||
val w = normalize(want)
|
||||
val g = normalize(got)
|
||||
if (w.isEmpty() || g.isEmpty()) return 0
|
||||
if (w == g) return 3
|
||||
val ws = normalize(stripEdition(want))
|
||||
val gs = normalize(stripEdition(got))
|
||||
if (ws == gs || ws == g || w == gs) return 2
|
||||
if (ws in heads(got) || gs in heads(want)) return 1
|
||||
return 0
|
||||
}
|
||||
|
||||
/** The title up to each place a subtitle could start, normalized. */
|
||||
private fun heads(title: String): Set<String> =
|
||||
SUBTITLE.findAll(title).map { normalize(title.substring(0, it.range.first)) }.filter { it.isNotEmpty() }.toSet()
|
||||
|
||||
/** The best-named of [items] in their order (the site's own ranking breaks a tie), or null when none is the game. */
|
||||
fun <T> pick(want: String, items: List<T>, names: (T) -> List<String>): T? {
|
||||
var best: T? = null
|
||||
var bestScore = 0
|
||||
for (item in items) {
|
||||
val s = names(item).filter { it.isNotBlank() }.maxOfOrNull { score(want, it.trim()) } ?: 0
|
||||
if (s > bestScore) { best = item; bestScore = s }
|
||||
}
|
||||
return best
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,7 @@ data class CatalogItem(
|
||||
/** The web product page: where "Get for free" and "View on <store>" land. */
|
||||
val storeUrl: String = "",
|
||||
val developer: String = "",
|
||||
val publisher: String = "",
|
||||
val releaseDate: String = "",
|
||||
val description: String = "",
|
||||
/** True for a title the signed-in account owns (a library entry). */
|
||||
|
||||
@@ -41,7 +41,7 @@ internal object StoreNet {
|
||||
}
|
||||
}
|
||||
|
||||
fun postJson(url: String, body: String, bearer: String? = null, userAgent: String = BROWSER_UA, timeoutMs: Int = 25_000): String? {
|
||||
fun postJson(url: String, body: String, bearer: String? = null, userAgent: String = BROWSER_UA, timeoutMs: Int = 25_000, headers: Map<String, String> = emptyMap()): String? {
|
||||
var conn: HttpURLConnection? = null
|
||||
return try {
|
||||
conn = (URL(url).openConnection() as HttpURLConnection).apply {
|
||||
@@ -53,6 +53,7 @@ internal object StoreNet {
|
||||
setRequestProperty("Content-Type", "application/json")
|
||||
setRequestProperty("Accept", "application/json")
|
||||
if (bearer != null) setRequestProperty("Authorization", "Bearer $bearer")
|
||||
headers.forEach { (k, v) -> setRequestProperty(k, v) }
|
||||
}
|
||||
OutputStreamWriter(conn.outputStream, "UTF-8").use { it.write(body) }
|
||||
val code = conn.responseCode
|
||||
|
||||
@@ -103,7 +103,11 @@ public final class EpicApiClient {
|
||||
if (attrs != null) {
|
||||
JSONObject offline = attrs.optJSONObject("CanRunOffline");
|
||||
if (offline != null) game.canRunOffline = !"false".equalsIgnoreCase(offline.optString("value", "true"));
|
||||
JSONObject publisher = attrs.optJSONObject("publisherName");
|
||||
if (publisher != null) game.publisher = publisher.optString("value", "").trim();
|
||||
}
|
||||
JSONObject seller = item.optJSONObject("seller");
|
||||
if (game.publisher.isEmpty() && seller != null) game.publisher = seller.optString("name", "").trim();
|
||||
String rd = item.optString("viewableDate", "");
|
||||
if (rd.isEmpty()) rd = item.optString("effectiveDate", "");
|
||||
if (!rd.isEmpty()) game.releaseDate = rd;
|
||||
|
||||
@@ -80,7 +80,12 @@ object EpicBackend : StoreBackend, EpicLaunchSupport {
|
||||
val byCatalogItem = owned.associateBy { it.extra["catalogItemId"] ?: "" }
|
||||
fun mark(l: List<CatalogItem>) = l.map { i ->
|
||||
val match = i.extra["items"]?.split(',')?.firstNotNullOfOrNull { byCatalogItem[it] }
|
||||
if (match != null) match.copy(imageUrl = i.imageUrl ?: match.imageUrl, tallImageUrl = i.tallImageUrl ?: match.tallImageUrl) else i
|
||||
// The offer's art, and its facts where the library's catalog record has none.
|
||||
if (match != null) match.copy(
|
||||
imageUrl = i.imageUrl ?: match.imageUrl, tallImageUrl = i.tallImageUrl ?: match.tallImageUrl,
|
||||
developer = match.developer.ifBlank { i.developer }, publisher = match.publisher.ifBlank { i.publisher },
|
||||
releaseDate = match.releaseDate.ifBlank { i.releaseDate },
|
||||
) else i
|
||||
}
|
||||
return StoreShelves(mark(s.whatsNew), mark(s.deals), mark(s.free), mark(s.trending))
|
||||
}
|
||||
|
||||
@@ -22,4 +22,5 @@ public class EpicGame {
|
||||
public boolean isDLC = false;
|
||||
public String baseGameCatalogItemId = "";
|
||||
public String releaseDate = "";
|
||||
public String publisher = "";
|
||||
}
|
||||
@@ -44,6 +44,8 @@ object EpicLibrary {
|
||||
g.developer = j.optString("developer", ""); g.description = j.optString("description", ""); g.version = j.optString("version", "")
|
||||
g.installSize = j.optLong("installSize", 0L).let { if (it > 1_099_511_627_776L) 0L else it }
|
||||
g.canRunOffline = j.optBoolean("canRunOffline", true)
|
||||
g.releaseDate = j.optString("releaseDate", "")
|
||||
g.publisher = j.optString("publisher", "")
|
||||
if (g.appName.isNotEmpty()) list.add(g)
|
||||
}
|
||||
list.distinctBy { it.appName }.sortedBy { it.title.lowercase() }
|
||||
@@ -74,7 +76,6 @@ object EpicLibrary {
|
||||
var done = 0
|
||||
for (game in raw) {
|
||||
EpicApiClient.enrichFromCatalog(token, game)
|
||||
if (game.releaseDate.isNotEmpty()) p.edit().putString("release_${game.appName}", game.releaseDate).apply()
|
||||
done++
|
||||
if (done % 5 == 0) onStatus("Loading game details… ($done/$total)")
|
||||
}
|
||||
@@ -102,7 +103,8 @@ object EpicLibrary {
|
||||
val arr = JSONArray()
|
||||
for (g in games) arr.put(JSONObject().put("appName", g.appName).put("namespace", g.namespace).put("catalogItemId", g.catalogItemId)
|
||||
.put("title", g.title).put("artCover", g.artCover).put("artSquare", g.artSquare).put("developer", g.developer)
|
||||
.put("description", g.description).put("version", g.version).put("installSize", g.installSize).put("canRunOffline", g.canRunOffline))
|
||||
.put("description", g.description).put("version", g.version).put("installSize", g.installSize).put("canRunOffline", g.canRunOffline)
|
||||
.put("releaseDate", g.releaseDate).put("publisher", g.publisher))
|
||||
prefs.edit().putString(CACHE_KEY, arr.toString()).apply()
|
||||
}
|
||||
}
|
||||
@@ -111,7 +113,9 @@ object EpicLibrary {
|
||||
store = Store.EPIC, id = g.appName, title = g.title.ifBlank { g.appName },
|
||||
imageUrl = g.artSquare.ifBlank { null } ?: g.artCover.ifBlank { null },
|
||||
tallImageUrl = g.artCover.ifBlank { null } ?: g.artSquare.ifBlank { null },
|
||||
developer = g.developer, description = com.droiddeck.launcher.stores.cleanStoreText(g.description), owned = true,
|
||||
developer = g.developer, publisher = g.publisher, description = com.droiddeck.launcher.stores.cleanStoreText(g.description), owned = true,
|
||||
// A cache from before the release date was kept still has it under the older per-game key.
|
||||
releaseDate = g.releaseDate.ifEmpty { EpicPrefs.get(context).getString("release_${g.appName}", "").orEmpty() },
|
||||
sizeBytes = EpicPrefs.get(context).getLong("size_${g.appName}", g.installSize),
|
||||
storeUrl = "https://store.epicgames.com/en-US/browse?q=${java.net.URLEncoder.encode(g.title, "UTF-8")}",
|
||||
extra = mapOf("namespace" to g.namespace, "catalogItemId" to g.catalogItemId, "version" to (g.version ?: "")),
|
||||
|
||||
@@ -32,7 +32,7 @@ object EpicStoreCatalog {
|
||||
|
||||
private const val ELEMENT_FIELDS =
|
||||
"title id namespace description effectiveDate releaseDate offerType productSlug urlSlug " +
|
||||
"items{id namespace} keyImages{type url} seller{name} tags{name} " +
|
||||
"items{id namespace} keyImages{type url} seller{name} tags{name} customAttributes{key value} " +
|
||||
"catalogNs{mappings(pageType:\"productHome\"){pageSlug pageType}} " +
|
||||
"price(country:\$country){totalPrice{discountPrice originalPrice discount currencyCode " +
|
||||
"fmtPrice(locale:\$locale){originalPrice discountPrice}}}"
|
||||
@@ -116,13 +116,21 @@ object EpicStoreCatalog {
|
||||
return CatalogItem(
|
||||
store = Store.EPIC, id = id, title = title, imageUrl = wide ?: thumb, tallImageUrl = tall ?: thumb, tags = tagLine,
|
||||
isFree = isFree, hasPrice = hasPrice, finalPrice = finalPrice, originalPrice = if (discountPct > 0) fmtOriginal else "", discountPercent = discountPct,
|
||||
storeUrl = storeUrl, developer = e.optJSONObject("seller")?.optString("name", "").orEmpty(),
|
||||
storeUrl = storeUrl, developer = attribute(e, "developerName"),
|
||||
publisher = attribute(e, "publisherName").ifEmpty { e.optJSONObject("seller")?.optString("name", "").orEmpty() },
|
||||
releaseDate = e.optString("releaseDate", e.optString("effectiveDate", "")), description = com.droiddeck.launcher.stores.cleanStoreText(e.optString("description", "")),
|
||||
extra = buildMap { put("namespace", ns); if (itemIds.isNotEmpty()) put("items", itemIds.joinToString(",")); if (slug.isNotBlank()) put("slug", slug) },
|
||||
mature = com.droiddeck.launcher.stores.matureByTags(allTags),
|
||||
)
|
||||
}
|
||||
|
||||
// An offer's custom attribute (developerName, publisherName), or "".
|
||||
private fun attribute(e: JSONObject, key: String): String {
|
||||
val attrs = e.optJSONArray("customAttributes") ?: return ""
|
||||
return (0 until attrs.length()).mapNotNull { attrs.optJSONObject(it) }.firstOrNull { it.optString("key") == key }
|
||||
?.optString("value", "")?.trim().orEmpty()
|
||||
}
|
||||
|
||||
private fun pageSlugOf(e: JSONObject): String {
|
||||
e.optJSONObject("catalogNs")?.optJSONArray("mappings")?.let { m ->
|
||||
for (i in 0 until m.length()) { val map = m.optJSONObject(i) ?: continue; if (map.optString("pageType") == "productHome") { val s = map.optString("pageSlug", ""); if (s.isNotBlank()) return s } }
|
||||
@@ -193,7 +201,7 @@ object EpicStoreCatalog {
|
||||
private fun itemToJson(i: CatalogItem): JSONObject = JSONObject().apply {
|
||||
put("id", i.id); put("title", i.title); put("image", i.imageUrl ?: ""); put("tall", i.tallImageUrl ?: ""); put("tags", i.tags)
|
||||
put("free", i.isFree); put("hasPrice", i.hasPrice); put("final", i.finalPrice); put("orig", i.originalPrice); put("disc", i.discountPercent)
|
||||
put("url", i.storeUrl); put("dev", i.developer); put("rel", i.releaseDate); put("desc", i.description); put("extra", JSONObject(i.extra as Map<*, *>))
|
||||
put("url", i.storeUrl); put("dev", i.developer); put("pub", i.publisher); put("rel", i.releaseDate); put("desc", i.description); put("extra", JSONObject(i.extra as Map<*, *>))
|
||||
if (i.mature) put("mature", true)
|
||||
}
|
||||
|
||||
@@ -203,7 +211,7 @@ object EpicStoreCatalog {
|
||||
return CatalogItem(
|
||||
store = Store.EPIC, id = o.optString("id"), title = o.optString("title"), imageUrl = o.optString("image").ifBlank { null }, tallImageUrl = o.optString("tall").ifBlank { null },
|
||||
tags = o.optString("tags"), isFree = o.optBoolean("free"), hasPrice = o.optBoolean("hasPrice"), finalPrice = o.optString("final"), originalPrice = o.optString("orig"),
|
||||
discountPercent = o.optInt("disc"), storeUrl = o.optString("url"), developer = o.optString("dev"), releaseDate = o.optString("rel"), description = o.optString("desc"), extra = extra,
|
||||
discountPercent = o.optInt("disc"), storeUrl = o.optString("url"), developer = o.optString("dev"), publisher = o.optString("pub"), releaseDate = o.optString("rel"), description = o.optString("desc"), extra = extra,
|
||||
mature = o.optBoolean("mature"),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -71,7 +71,7 @@ object GogBackend : StoreBackend {
|
||||
|
||||
override fun install(context: Context, item: CatalogItem, root: File) {
|
||||
val app = context.applicationContext
|
||||
val game = GogGame(item.id, item.title, item.imageUrl ?: "", item.description, item.developer, item.tags, 2, item.tallImageUrl)
|
||||
val game = GogGame(item.id, item.title, item.imageUrl ?: "", item.description, item.developer, item.tags, 2, item.tallImageUrl, item.releaseDate, item.publisher)
|
||||
val folder = StoreInstallRoot.folderFor(app, Store.GOG, game.gameId, game.title, root)
|
||||
val entry = DownloadEntry(store, item.id, item.title, cover = item.imageUrl, bytesTotal = item.sizeBytes, location = StoreInstallRoot.labelFor(app, folder))
|
||||
DownloadQueue.enqueue(app, entry) { InstallJob(app, game, item, folder) }
|
||||
|
||||
@@ -12,9 +12,12 @@ public class GogGame {
|
||||
public final int generation;
|
||||
/** gamesdb.gog.com 2:3 box art, or null when the lookup found none. */
|
||||
public final String verticalCover;
|
||||
/** ISO date-time of the worldwide release, or "" when GOG gave none. */
|
||||
public final String releaseDate;
|
||||
public final String publisher;
|
||||
|
||||
public GogGame(String gameId, String title, String imageUrl, String description, String developer,
|
||||
String category, int generation, String verticalCover) {
|
||||
String category, int generation, String verticalCover, String releaseDate, String publisher) {
|
||||
this.gameId = gameId;
|
||||
this.title = title;
|
||||
this.imageUrl = imageUrl;
|
||||
@@ -23,5 +26,7 @@ public class GogGame {
|
||||
this.category = category;
|
||||
this.generation = generation;
|
||||
this.verticalCover = verticalCover;
|
||||
this.releaseDate = releaseDate;
|
||||
this.publisher = publisher;
|
||||
}
|
||||
}
|
||||
@@ -45,7 +45,8 @@ object GogLibrary {
|
||||
(0 until arr.length()).mapNotNull { i ->
|
||||
val o = arr.optJSONObject(i) ?: return@mapNotNull null
|
||||
GogGame(o.optString("gameId", ""), o.optString("title", ""), o.optString("imageUrl", ""), cleanStoreText(o.optString("description", "")),
|
||||
o.optString("developer", ""), o.optString("category", ""), o.optInt("generation", 1), o.optString("verticalCover", "").ifEmpty { null })
|
||||
o.optString("developer", ""), o.optString("category", ""), o.optInt("generation", 1), o.optString("verticalCover", "").ifEmpty { null },
|
||||
o.optString("releaseDate", ""), o.optString("publisher", ""))
|
||||
}.filter { it.gameId.isNotEmpty() }.sortedBy { it.title.lowercase() }
|
||||
}.getOrDefault(emptyList())
|
||||
}
|
||||
@@ -148,7 +149,15 @@ object GogLibrary {
|
||||
val desc = cleanStoreText(prod.optJSONObject("description")?.optString("lead", ""))
|
||||
.ifEmpty { cleanStoreText(v2?.optString("overview", "")) }
|
||||
.ifEmpty { cleanStoreText(v2?.optString("description", "")) }
|
||||
val developer = prod.optJSONObject("developers")?.optString("name", "") ?: prod.optString("developer", "")
|
||||
// The products endpoint names no developer or publisher; the v2 record does, with the worldwide release date.
|
||||
val embedded = v2?.optJSONObject("_embedded")
|
||||
fun names(key: String) = embedded?.optJSONArray(key)
|
||||
?.let { arr -> (0 until arr.length()).mapNotNull { arr.optJSONObject(it)?.optString("name")?.takeIf(String::isNotBlank) } }
|
||||
?.joinToString(", ").orEmpty()
|
||||
val developer = names("developers")
|
||||
val publisher = embedded?.optJSONObject("publisher")?.optString("name")?.takeIf(String::isNotBlank) ?: names("publishers")
|
||||
val releaseDate = listOf(embedded?.optJSONObject("product")?.optString("globalReleaseDate"), prod.optString("release_date"))
|
||||
.firstOrNull { !it.isNullOrBlank() && it != "null" }.orEmpty()
|
||||
val genres = prod.optJSONArray("genres")
|
||||
val category = if (genres != null && genres.length() > 0) genres.optJSONObject(0)?.optString("name", "") ?: "" else ""
|
||||
|
||||
@@ -164,9 +173,7 @@ object GogLibrary {
|
||||
if (maxGen > 0) generation = maxGen
|
||||
}
|
||||
}
|
||||
val ed = prefs.edit().putInt("gen_$id", generation)
|
||||
prod.optString("release_date", "").takeIf { it.isNotEmpty() }?.let { ed.putString("release_$id", it) }
|
||||
ed.apply()
|
||||
prefs.edit().putInt("gen_$id", generation).apply()
|
||||
if (prefs.getLong("size_$id", -1L) <= 0) {
|
||||
val size = GogDownloadManager.fetchInstallSizeBytes(id, token)
|
||||
if (size > 0) prefs.edit().putLong("size_$id", size).apply()
|
||||
@@ -182,7 +189,7 @@ object GogLibrary {
|
||||
verticalCover = fetchVerticalCover(id).ifEmpty { StoreNet.sgdbPoster(title) }
|
||||
}
|
||||
if (!verticalCover.isNullOrEmpty()) prefs.edit().putString("vcover_$id", verticalCover).apply()
|
||||
return GogGame(id, title, GogStoreCatalog.absolutize(imageUrl), desc, developer, category, generation, verticalCover?.ifEmpty { null })
|
||||
return GogGame(id, title, GogStoreCatalog.absolutize(imageUrl), desc, developer, category, generation, verticalCover?.ifEmpty { null }, releaseDate, publisher)
|
||||
} catch (_: Exception) {
|
||||
return null
|
||||
}
|
||||
@@ -203,7 +210,7 @@ object GogLibrary {
|
||||
val arr = JSONArray()
|
||||
for (g in games) {
|
||||
arr.put(JSONObject().put("gameId", g.gameId).put("title", g.title).put("imageUrl", g.imageUrl).put("description", g.description)
|
||||
.put("developer", g.developer).put("category", g.category).put("generation", g.generation)
|
||||
.put("developer", g.developer).put("category", g.category).put("generation", g.generation).put("releaseDate", g.releaseDate).put("publisher", g.publisher)
|
||||
.apply { if (!g.verticalCover.isNullOrEmpty()) put("verticalCover", g.verticalCover) })
|
||||
}
|
||||
prefs.edit().putString(CACHE_KEY, arr.toString()).apply()
|
||||
@@ -215,7 +222,9 @@ object GogLibrary {
|
||||
store = Store.GOG, id = g.gameId, title = g.title,
|
||||
imageUrl = GogStoreCatalog.absolutize(g.imageUrl).ifBlank { null },
|
||||
tallImageUrl = GogStoreCatalog.absolutize(g.verticalCover ?: g.imageUrl).ifBlank { null },
|
||||
tags = g.category, developer = g.developer, description = g.description, owned = true,
|
||||
tags = g.category, developer = g.developer, publisher = g.publisher, description = g.description, owned = true,
|
||||
// A cache from before the release date was kept still has it under the older per-game key.
|
||||
releaseDate = g.releaseDate.ifEmpty { GogPrefs.get(context).getString("release_${g.gameId}", "").orEmpty() },
|
||||
sizeBytes = sizeOf(context, g.gameId),
|
||||
storeUrl = "https://www.gog.com/en/game/${g.gameId}",
|
||||
)
|
||||
|
||||
@@ -133,6 +133,7 @@ object GogStoreCatalog {
|
||||
finalPrice = finalStr, originalPrice = if (discount > 0) baseStr else "",
|
||||
discountPercent = if (discount > 0 && baseStr.isNotBlank()) discount else 0,
|
||||
storeUrl = storeLink, developer = p.optJSONArray("developers")?.optString(0, "").orEmpty(),
|
||||
publisher = p.optJSONArray("publishers")?.optString(0, "").orEmpty(),
|
||||
releaseDate = p.optString("releaseDate", ""),
|
||||
extra = buildMap { if (slug.isNotBlank()) put("slug", slug) },
|
||||
mature = mature,
|
||||
@@ -175,7 +176,7 @@ object GogStoreCatalog {
|
||||
private fun itemToJson(i: CatalogItem): JSONObject = JSONObject().apply {
|
||||
put("id", i.id); put("title", i.title); put("image", i.imageUrl ?: ""); put("tall", i.tallImageUrl ?: "")
|
||||
put("tags", i.tags); put("free", i.isFree); put("hasPrice", i.hasPrice); put("final", i.finalPrice); put("orig", i.originalPrice)
|
||||
put("disc", i.discountPercent); put("url", i.storeUrl); put("dev", i.developer); put("rel", i.releaseDate)
|
||||
put("disc", i.discountPercent); put("url", i.storeUrl); put("dev", i.developer); put("pub", i.publisher); put("rel", i.releaseDate)
|
||||
if (i.mature) put("mature", true)
|
||||
}
|
||||
|
||||
@@ -184,7 +185,7 @@ object GogStoreCatalog {
|
||||
imageUrl = o.optString("image").ifBlank { null }, tallImageUrl = o.optString("tall").ifBlank { null },
|
||||
tags = o.optString("tags"), isFree = o.optBoolean("free"), hasPrice = o.optBoolean("hasPrice"),
|
||||
finalPrice = o.optString("final"), originalPrice = o.optString("orig"), discountPercent = o.optInt("disc"),
|
||||
storeUrl = o.optString("url"), developer = o.optString("dev"), releaseDate = o.optString("rel"),
|
||||
storeUrl = o.optString("url"), developer = o.optString("dev"), publisher = o.optString("pub"), releaseDate = o.optString("rel"),
|
||||
mature = o.optBoolean("mature"),
|
||||
)
|
||||
|
||||
|
||||
@@ -137,6 +137,8 @@ import com.droiddeck.launcher.core.TextureFiltering
|
||||
import com.droiddeck.launcher.gpu.FrameGen
|
||||
import com.droiddeck.launcher.gpu.Lossless
|
||||
import com.droiddeck.launcher.gpu.ScreenEffectLooks
|
||||
import com.droiddeck.launcher.gpu.Cardboard
|
||||
import com.droiddeck.launcher.gpu.SteamVr
|
||||
import com.droiddeck.launcher.gpu.ScreenEffects
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.ComponentsManager
|
||||
@@ -209,6 +211,12 @@ class DrawerActions(
|
||||
val upscaleSharpness: Int = 75,
|
||||
/** The compositor's post chain (gpu/ScreenEffects), changed live. */
|
||||
val effects: ScreenEffects = ScreenEffects.OFF,
|
||||
/** Cardboard mode (gpu/Cardboard): side-by-side eyes for a phone VR viewer, changed live. */
|
||||
val cardboard: Cardboard = Cardboard.OFF,
|
||||
/** Whether the device has a rotation sensor (head tracking possible). */
|
||||
val cardboardSensor: Boolean = false,
|
||||
/** SteamVR in the guest for Cardboard mode (gpu/SteamVr); null while unknown. */
|
||||
val steamVr: SteamVr.Status? = null,
|
||||
/** Texture filtering for DirectX 9-11 games (core/TextureFiltering); lands on their next launch. */
|
||||
val textureAnisotropy: Int? = 0,
|
||||
val textureLodBias: String? = TextureFiltering.LOD_BIAS_OFF,
|
||||
@@ -244,6 +252,10 @@ class DrawerActions(
|
||||
val onUpscaler: (Int) -> Unit = {},
|
||||
val onUpscaleSharpness: (Int) -> Unit = {},
|
||||
val onEffects: (ScreenEffects) -> Unit = {},
|
||||
val onCardboard: (Cardboard) -> Unit = {},
|
||||
val onCardboardRecenter: () -> Unit = {},
|
||||
/** install, start or stop SteamVR. */
|
||||
val onSteamVr: (String) -> Unit = {},
|
||||
val onTextureAnisotropy: (Int?) -> Unit = {},
|
||||
val onTextureLodBias: (String?) -> Unit = {},
|
||||
val onSecondScreenMode: (SecondScreenMode) -> Unit,
|
||||
@@ -465,6 +477,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
stringResource(R.string.display_sharpness), null, a.upscaleSharpness, 0..100, step = 5,
|
||||
format = { "$it%" }, modifier = focus.track(page, "upscale-sharpness"), onChange = a.onUpscaleSharpness)
|
||||
}
|
||||
CardboardGroup(host, a) { key -> focus.track(page, key) }
|
||||
}
|
||||
SessionDrawerPage.EFFECTS -> {
|
||||
ScreenEffectsGroup(host, a, advancedEffectsExpanded,
|
||||
@@ -903,6 +916,53 @@ private fun ScreenEffectsGroup(
|
||||
}
|
||||
}
|
||||
|
||||
/** Cardboard mode: the eyes, the lens and the virtual screen; everything applies live. */
|
||||
@Composable
|
||||
private fun CardboardGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
|
||||
val c = a.cardboard
|
||||
SettingsGroup(stringResource(R.string.cardboard_title)) {
|
||||
ToggleRow(host, "cardboard", stringResource(R.string.cardboard_mode), stringResource(R.string.cardboard_mode_hint),
|
||||
c.enabled, chipModifier = track("cardboard")) { a.onCardboard(c.copy(enabled = it)) }
|
||||
if (!c.enabled) return@SettingsGroup
|
||||
ChoiceRow(host, "cardboard-source", stringResource(R.string.cardboard_source), null,
|
||||
listOf(Cardboard.SOURCE_SCREEN to stringResource(R.string.cardboard_source_screen),
|
||||
Cardboard.SOURCE_SBS to stringResource(R.string.cardboard_source_sbs)),
|
||||
c.source, chipModifier = track("cardboard-source")) { a.onCardboard(c.copy(source = it)) }
|
||||
ChoiceRow(host, "cardboard-viewer", stringResource(R.string.cardboard_viewer), null,
|
||||
listOf(Cardboard.Viewer.CARDBOARD_V2.id to stringResource(R.string.cardboard_viewer_v2),
|
||||
Cardboard.Viewer.CARDBOARD_V1.id to stringResource(R.string.cardboard_viewer_v1),
|
||||
Cardboard.Viewer.NONE.id to stringResource(R.string.cardboard_viewer_none)),
|
||||
c.viewer, chipModifier = track("cardboard-viewer")) { a.onCardboard(c.copy(viewer = it)) }
|
||||
SliderRow(stringResource(R.string.cardboard_ipd), null, c.ipdMm, 50..80, step = 1,
|
||||
format = { "$it mm" }, modifier = track("cardboard-ipd")) { a.onCardboard(c.copy(ipdMm = it)) }
|
||||
if (c.source == Cardboard.SOURCE_SCREEN) {
|
||||
SliderRow(stringResource(R.string.cardboard_screen_width), null, c.screenWidthDm, 5..200, step = 5,
|
||||
format = { String.format(Locale.US, "%.1f m", it / 10f) }, modifier = track("cardboard-width")) { a.onCardboard(c.copy(screenWidthDm = it)) }
|
||||
SliderRow(stringResource(R.string.cardboard_screen_distance), null, c.screenDistanceDm, 5..200, step = 5,
|
||||
format = { String.format(Locale.US, "%.1f m", it / 10f) }, modifier = track("cardboard-distance")) { a.onCardboard(c.copy(screenDistanceDm = it)) }
|
||||
}
|
||||
ToggleRow(host, "cardboard-tracking", stringResource(R.string.cardboard_head_tracking),
|
||||
if (a.cardboardSensor) null else stringResource(R.string.cardboard_no_sensor),
|
||||
c.headTracking && a.cardboardSensor, enabled = a.cardboardSensor, chipModifier = track("cardboard-tracking")) {
|
||||
a.onCardboard(c.copy(headTracking = it))
|
||||
}
|
||||
if (c.headTracking && a.cardboardSensor)
|
||||
ActionRow(stringResource(R.string.cardboard_recenter), null, stringResource(R.string.cardboard_recenter_button), a.onCardboardRecenter)
|
||||
val vrLabel = stringResource(R.string.cardboard_steamvr)
|
||||
when (a.steamVr) {
|
||||
SteamVr.Status.NOT_INSTALLED -> ActionRow(vrLabel, stringResource(R.string.cardboard_steamvr_install_hint),
|
||||
stringResource(R.string.cardboard_steamvr_install), { a.onSteamVr("install") })
|
||||
SteamVr.Status.INSTALLING -> SettingsRow(vrLabel, stringResource(R.string.cardboard_steamvr_installing)) {}
|
||||
SteamVr.Status.READY -> ActionRow(vrLabel, stringResource(R.string.cardboard_steamvr_ready_hint),
|
||||
stringResource(R.string.cardboard_steamvr_start), { a.onSteamVr("start") })
|
||||
SteamVr.Status.RUNNING -> ActionRow(vrLabel, stringResource(R.string.cardboard_steamvr_running_hint),
|
||||
stringResource(R.string.cardboard_steamvr_stop), { a.onSteamVr("stop") })
|
||||
SteamVr.Status.UNAVAILABLE -> SettingsRow(vrLabel, stringResource(R.string.cardboard_steamvr_unavailable)) {}
|
||||
null -> {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Secondary-display modes are mutually exclusive and apply immediately. */
|
||||
@Composable
|
||||
private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.ExitTransition
|
||||
import androidx.compose.animation.core.FastOutSlowInEasing
|
||||
import androidx.compose.animation.core.RepeatMode
|
||||
import androidx.compose.animation.core.animateFloat
|
||||
import androidx.compose.animation.core.infiniteRepeatable
|
||||
import androidx.compose.animation.core.rememberInfiniteTransition
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.shrinkHorizontally
|
||||
import androidx.compose.animation.shrinkVertically
|
||||
import androidx.compose.foundation.LocalIndication
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.hoverable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.OpenInNew
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.text.SpanStyle
|
||||
import androidx.compose.ui.text.buildAnnotatedString
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.text.withStyle
|
||||
import androidx.compose.ui.tooling.preview.Preview
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.GameFacts
|
||||
import com.droiddeck.launcher.stores.Lookup
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
// A store game's facts under its hero: who made it and when, from the store; the Metacritic score
|
||||
// and HowLongToBeat's times, looked up elsewhere by name. The store's facts are there at once; the
|
||||
// looked-up ones hold their place while they come and step out if there is nothing to show.
|
||||
|
||||
internal class GameScores(val metacritic: Lookup<GameFacts.Metacritic>, val hltb: Lookup<GameFacts.Hltb>)
|
||||
|
||||
/** Both lookups at once and off the main thread, each landing on its own; what memory already has shows without a wait. */
|
||||
@Composable
|
||||
internal fun rememberGameScores(title: String?): GameScores {
|
||||
val ctx = LocalContext.current.applicationContext
|
||||
var metacritic by remember(title) { mutableStateOf(title?.let { GameFacts.peekMetacritic(it) } ?: if (title == null) Lookup.None else Lookup.Pending) }
|
||||
var hltb by remember(title) { mutableStateOf(title?.let { GameFacts.peekHltb(it) } ?: if (title == null) Lookup.None else Lookup.Pending) }
|
||||
LaunchedEffect(title) {
|
||||
if (title == null) return@LaunchedEffect
|
||||
launch { metacritic = withContext(Dispatchers.IO) { GameFacts.metacritic(ctx, title) }?.let { Lookup.Found(it) } ?: Lookup.None }
|
||||
launch { hltb = withContext(Dispatchers.IO) { GameFacts.hltb(ctx, title) }?.let { Lookup.Found(it) } ?: Lookup.None }
|
||||
}
|
||||
return GameScores(metacritic, hltb)
|
||||
}
|
||||
|
||||
/**
|
||||
* The facts: who made it, when, and what critics made of it on the first row; how long it takes,
|
||||
* across the page, on the second. A looked-up tile holds its place while it asks and steps out if
|
||||
* the site does not have the game; nothing is drawn when there is nothing to say.
|
||||
*/
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
internal fun StoreGameFacts(developer: String, publisher: String, releaseDate: String, scores: GameScores, modifier: Modifier = Modifier) {
|
||||
val released = remember(releaseDate) { GameFacts.releaseLabel(releaseDate) }
|
||||
// A studio that publishes itself is named once.
|
||||
val publishedBy = publisher.takeUnless { it.isBlank() || it.trim().equals(developer.trim(), ignoreCase = true) }
|
||||
val firstRow = developer.isNotBlank() || publishedBy != null || released != null || scores.metacritic != Lookup.None
|
||||
if (!firstRow && scores.hltb == Lookup.None) return
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = modifier.fillMaxWidth().padding(top = 12.dp)) {
|
||||
if (firstRow) FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
if (developer.isNotBlank()) FactTile(stringResource(R.string.stores_fact_developer)) { FactText(developer) }
|
||||
if (publishedBy != null) FactTile(stringResource(R.string.stores_fact_publisher)) { FactText(publishedBy) }
|
||||
if (released != null) FactTile(stringResource(R.string.stores_fact_released)) { FactText(released) }
|
||||
Looked(scores.metacritic, exit = shrinkHorizontally()) { lookup ->
|
||||
val found = (lookup as? Lookup.Found)?.value
|
||||
FactTile(stringResource(R.string.stores_fact_metacritic), link = found?.url) {
|
||||
if (found != null) MetacriticBadge(found.score) else Placeholder(ValueHeight)
|
||||
}
|
||||
}
|
||||
}
|
||||
Looked(scores.hltb, exit = shrinkVertically()) { lookup ->
|
||||
val found = (lookup as? Lookup.Found)?.value
|
||||
FactTile(stringResource(R.string.stores_fact_hltb), fill = true, link = found?.url) {
|
||||
if (found != null) HltbTimes(found) else Placeholder(220.dp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A looked-up tile: in from the start (holding its place while it asks), out with a fade when there was nothing. */
|
||||
@Composable
|
||||
private fun <T> Looked(lookup: Lookup<T>, exit: ExitTransition, content: @Composable (Lookup<T>) -> Unit) {
|
||||
// The last answer worth drawing, so the tile does not blank as it leaves.
|
||||
var shown by remember { mutableStateOf(lookup) }
|
||||
if (lookup != Lookup.None) shown = lookup
|
||||
AnimatedVisibility(visible = lookup != Lookup.None, enter = fadeIn(), exit = fadeOut() + exit) { content(shown) }
|
||||
}
|
||||
|
||||
private val FactShape = RoundedCornerShape(12.dp)
|
||||
private val ValueHeight = 24.dp
|
||||
|
||||
/**
|
||||
* A label over its value; [fill] takes the row's whole width, for a value laid out across it. With
|
||||
* a [link] it is a control like any other on the page: focus, hover and A or a tap open the page.
|
||||
*/
|
||||
@Composable
|
||||
private fun FactTile(label: String, fill: Boolean = false, link: String? = null, value: @Composable () -> Unit) {
|
||||
val pal = LocalPalette.current
|
||||
val ctx = LocalContext.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = link != null && rememberHot(src)
|
||||
val open = { if (link != null) openUrl(ctx, link) }
|
||||
val base = if (fill) Modifier.fillMaxWidth() else Modifier.widthIn(max = 360.dp)
|
||||
val tile = if (link == null) base.clip(FactShape).background(pal.surface).border(1.dp, pal.line, FactShape)
|
||||
else base.paneItem("fact:$label").clip(FactShape)
|
||||
.background(if (hot) pal.signal.copy(alpha = 0.14f) else pal.surface)
|
||||
.glideBorder(hot, FactShape, pal.signal, restColor = pal.line)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = open)
|
||||
.controllerConfirm(onClick = open)
|
||||
Column(verticalArrangement = Arrangement.spacedBy(4.dp), modifier = tile.padding(horizontal = 14.dp, vertical = 10.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Text(label.uppercase(), fontSize = 11.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.sp, color = if (hot) pal.signal else pal.onSurfaceVariant, maxLines = 1)
|
||||
if (link != null) Icon(Icons.AutoMirrored.Filled.OpenInNew, contentDescription = null, tint = if (hot) pal.signal else pal.onSurfaceVariant, modifier = Modifier.size(12.dp))
|
||||
}
|
||||
Box(contentAlignment = Alignment.CenterStart, modifier = (if (fill) Modifier.fillMaxWidth() else Modifier).heightIn(min = ValueHeight)) { value() }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FactText(text: String) =
|
||||
Text(text, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
|
||||
/** Metacritic's own bands: green from 75, yellow from 50, red below. */
|
||||
internal fun metacriticColour(score: Int): Color = when {
|
||||
score >= 75 -> Color(0xFF66CC33)
|
||||
score >= 50 -> Color(0xFFFFCC33)
|
||||
else -> Color(0xFFFF6874)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MetacriticBadge(score: Int) {
|
||||
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(ValueHeight).clip(RoundedCornerShape(6.dp)).background(metacriticColour(score))) {
|
||||
Text("$score", fontSize = 13.sp, fontWeight = FontWeight.Black, color = Color(0xFF0A0B0D), maxLines = 1)
|
||||
}
|
||||
}
|
||||
|
||||
/** Each kind of run HowLongToBeat has times for, sharing the tile's width: the hours in full, what they are for beside them. */
|
||||
@Composable
|
||||
private fun HltbTimes(t: GameFacts.Hltb) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val runs = listOf(
|
||||
t.main to stringResource(R.string.stores_hltb_main),
|
||||
t.extras to stringResource(R.string.stores_hltb_extras),
|
||||
t.completionist to stringResource(R.string.stores_hltb_completionist),
|
||||
).filter { it.first > 0 }
|
||||
Row(Modifier.fillMaxWidth()) {
|
||||
for ((secs, what) in runs) {
|
||||
val hours = GameFacts.hours(secs)?.let { stringResource(R.string.stores_hltb_hours, it) } ?: stringResource(R.string.stores_hltb_minutes, maxOf(1, secs / 60))
|
||||
val run = buildAnnotatedString {
|
||||
withStyle(SpanStyle(fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)) { append(hours) }
|
||||
withStyle(SpanStyle(fontSize = 12.sp, color = colors.onSurfaceVariant)) { append(" $what") }
|
||||
}
|
||||
Text(run, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Where a value will be, breathing while it is asked for. */
|
||||
@Composable
|
||||
private fun Placeholder(width: Dp) {
|
||||
val pulse by rememberInfiniteTransition(label = "fact").animateFloat(
|
||||
0.35f, 0.8f, infiniteRepeatable(tween(900, easing = FastOutSlowInEasing), RepeatMode.Reverse), label = "pulse",
|
||||
)
|
||||
Box(Modifier.width(width).height(16.dp).alpha(pulse).clip(RoundedCornerShape(5.dp)).background(LocalPalette.current.line2))
|
||||
}
|
||||
|
||||
// Previews: every state the row can be in, at a TV pane's width and a narrow one.
|
||||
|
||||
private val previewScores = GameScores(
|
||||
Lookup.Found(GameFacts.Metacritic(93, "https://www.metacritic.com/game/the-witcher-3-wild-hunt/")),
|
||||
Lookup.Found(GameFacts.Hltb(main = 186_070, extras = 373_519, completionist = 630_794, url = "https://howlongtobeat.com/game/10270")),
|
||||
)
|
||||
|
||||
private fun previewScore(score: Int) = Lookup.Found(GameFacts.Metacritic(score, "https://www.metacritic.com/"))
|
||||
|
||||
@Composable
|
||||
private fun FactsPreview(theme: String = Themes.GRAPHITE, narrow: Boolean = false, content: @Composable () -> Unit) {
|
||||
DroidDeckTheme(theme = theme) {
|
||||
CompositionLocalProvider(LocalNarrowPane provides narrow) {
|
||||
Box(Modifier.fillMaxSize().background(LocalPalette.current.background).padding(16.dp)) {
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(4.dp)) { content() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PreviewCaption(text: String) = Text(text, fontSize = 11.sp, color = LocalPalette.current.onSurfaceVariant, modifier = Modifier.padding(top = 8.dp))
|
||||
|
||||
@Preview(name = "Facts, all found", widthDp = 800, heightDp = 200)
|
||||
@Composable
|
||||
private fun FactsFoundPreview() = FactsPreview {
|
||||
StoreGameFacts("CD PROJEKT RED", "CD PROJEKT RED", "2015-05-19T00:00:00+02:00", previewScores)
|
||||
}
|
||||
|
||||
@Preview(name = "Facts, looking up", widthDp = 800, heightDp = 200)
|
||||
@Composable
|
||||
private fun FactsPendingPreview() = FactsPreview {
|
||||
StoreGameFacts("Supergiant Games", "Supergiant Games", "2020.09.17", GameScores(Lookup.Pending, Lookup.Pending))
|
||||
}
|
||||
|
||||
@Preview(name = "Facts, mixed", widthDp = 800, heightDp = 640)
|
||||
@Composable
|
||||
private fun FactsMixedPreview() = FactsPreview {
|
||||
PreviewCaption("Another studio's publisher; score found, times still coming")
|
||||
StoreGameFacts("New World Computing", "Ubisoft", "1999-02-28", GameScores(previewScore(87), Lookup.Pending))
|
||||
PreviewCaption("Score found, no times")
|
||||
StoreGameFacts("Mane6", "Maximum Entertainment", "2022-12-19T16:00:00.000Z", GameScores(previewScore(68), Lookup.None))
|
||||
PreviewCaption("Neither site knows it: store facts only")
|
||||
StoreGameFacts("Tiny Indie Studio", "", "2024.03.01", GameScores(Lookup.None, Lookup.None))
|
||||
PreviewCaption("A low score, a short game with only a main-story time")
|
||||
StoreGameFacts("", "", "2019-11-05", GameScores(previewScore(42), Lookup.Found(GameFacts.Hltb(main = 2_400, extras = 0, completionist = 0, url = "https://howlongtobeat.com/"))))
|
||||
PreviewCaption("Epic's no-date placeholder (2099) is not shown")
|
||||
StoreGameFacts("Studio", "", "2099-01-01T00:00:00.000Z", GameScores(previewScore(81), Lookup.None))
|
||||
}
|
||||
|
||||
@Preview(name = "Facts, narrow pane", widthDp = 420, heightDp = 300)
|
||||
@Composable
|
||||
private fun FactsNarrowPreview() = FactsPreview(narrow = true) {
|
||||
StoreGameFacts("CD PROJEKT RED", "CD PROJEKT RED", "2015-05-19T00:00:00+02:00", previewScores)
|
||||
}
|
||||
|
||||
@Preview(name = "Facts, Paper theme", widthDp = 800, heightDp = 200)
|
||||
@Composable
|
||||
private fun FactsPaperPreview() = FactsPreview(theme = Themes.PAPER) {
|
||||
StoreGameFacts("CD PROJEKT RED", "CD PROJEKT RED", "2015-05-19T00:00:00+02:00", previewScores)
|
||||
}
|
||||
|
||||
// The real hero reads the stores' live state, so this stands one in to show where the row sits.
|
||||
@Preview(name = "Game page, facts in place", widthDp = 800, heightDp = 520)
|
||||
@Composable
|
||||
private fun FactsOnPagePreview() = FactsPreview {
|
||||
val title = "The Witcher 3: Wild Hunt"
|
||||
Box(Modifier.fillMaxWidth().height(180.dp).clip(Shape16).background(artBrush(hueOf(title)))) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.align(Alignment.BottomStart).padding(horizontal = 22.dp, vertical = 18.dp)) {
|
||||
Text(stringResource(R.string.stores_eyebrow_library).uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.2.sp, color = LocalPalette.current.signal)
|
||||
Text(title, fontSize = 30.sp, fontWeight = FontWeight.Black, color = MaterialTheme.colorScheme.onBackground)
|
||||
}
|
||||
}
|
||||
StoreGameFacts("CD PROJEKT RED", "CD PROJEKT RED", "2015-05-19T00:00:00+02:00", previewScores)
|
||||
Text(
|
||||
"As war rages on throughout the Northern Realms, you take on the greatest contract of your life — tracking down the Child of Prophecy, a living weapon that can alter the shape of the world.",
|
||||
fontSize = 13.sp, lineHeight = 19.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(top = 12.dp),
|
||||
)
|
||||
}
|
||||
@@ -122,11 +122,20 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
|
||||
}
|
||||
}
|
||||
if (StoresMotion.heroLands) hero() else Rise(1) { hero() }
|
||||
if (store == Store.GOG || store == Store.EPIC) {
|
||||
// An owned game resolves to its library entry; the storefront's copy of it may know more.
|
||||
val listed = StoresState.shelves[store]?.all.orEmpty().firstOrNull { it.id == id }
|
||||
val developer = item?.developer?.ifBlank { null } ?: listed?.developer.orEmpty()
|
||||
val publisher = item?.publisher?.ifBlank { null } ?: listed?.publisher.orEmpty()
|
||||
val releaseDate = item?.releaseDate?.ifBlank { null } ?: listed?.releaseDate.orEmpty()
|
||||
val scores = rememberGameScores(title.takeIf { it != id })
|
||||
Rise(2) { StoreGameFacts(developer, publisher, releaseDate, scores) }
|
||||
}
|
||||
// Plain text only, and nothing at all when the store sent a template key instead of words.
|
||||
// A description that is only the title again (some stores fill it so) is no description.
|
||||
val description = item?.let { com.droiddeck.launcher.stores.cleanStoreText(it.description) }.orEmpty()
|
||||
.takeUnless { it.trim().equals(title.trim(), ignoreCase = true) }.orEmpty()
|
||||
if (description.isNotBlank()) Rise(2) {
|
||||
if (description.isNotBlank()) Rise(3) {
|
||||
Text(description, fontSize = 13.sp, lineHeight = 19.sp, color = colors.onSurfaceVariant, maxLines = 6, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 12.dp))
|
||||
}
|
||||
val achievements = remember(store, id, item?.owned, installed) {
|
||||
@@ -137,7 +146,7 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
if (achievements != null) Rise(3) { StoreAchievementsSection(achievements) }
|
||||
if (achievements != null) Rise(4) { StoreAchievementsSection(achievements) }
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1306,8 +1306,11 @@ internal fun stageLabel(stage: DownloadStage): String = when (stage) {
|
||||
}
|
||||
|
||||
/** The game's web page, in the device's browser: this app buys nothing and claims nothing itself. */
|
||||
internal fun openStoreUrl(ctx: android.content.Context, item: CatalogItem) {
|
||||
val url = item.storeUrl.ifBlank { return }
|
||||
internal fun openStoreUrl(ctx: android.content.Context, item: CatalogItem) = openUrl(ctx, item.storeUrl)
|
||||
|
||||
/** A web page in the browser; nothing when the URL is blank or no app can open it. */
|
||||
internal fun openUrl(ctx: android.content.Context, url: String) {
|
||||
if (url.isBlank()) return
|
||||
runCatching { ctx.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(url)).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)) }
|
||||
}
|
||||
|
||||
|
||||
@@ -450,6 +450,20 @@ public final class WaylandCompositor {
|
||||
/** The Look the controls currently match ({@code null} = Custom); only named in the log line. */
|
||||
public static native void nativeSetLookName(String name);
|
||||
|
||||
/** Cardboard mode (waylandcomp/src/cardboard.h): two lens-distorted eye views side by side.
|
||||
* {@code source} 0 = the frame as a virtual screen, 1 = the frame is already a side-by-side
|
||||
* stereo pair. Distances in metres, field of view in degrees. */
|
||||
public static native void nativeSetCardboard(boolean enabled, int source, float ipdM, float screenDistM,
|
||||
float screenWidthM, float k1, float k2, float fovDeg,
|
||||
float lensInset, float chroma);
|
||||
|
||||
/** The head pose for Cardboard mode: head -> world rotation, row-major 3x3 (any thread). {@code live}
|
||||
* = a sensor produced it. */
|
||||
public static native void nativeSetCardboardPose(float[] rotation, boolean live);
|
||||
|
||||
/** Where the head pose is shared with the guest (waylandcomp/src/headpose_shm.h); set once. */
|
||||
public static native void nativeSetCardboardPoseFile(String path);
|
||||
|
||||
/** The in-game FPS limiter: frames per second, 0 = unlimited. Paces when replaced buffers go
|
||||
* back to the game, like the X11 IdleNotify pacer, so the game itself slows to the cap. */
|
||||
public static native void nativeSetFpsLimit(int fps);
|
||||
|
||||
@@ -2147,4 +2147,12 @@
|
||||
<string name="achievements_none">%1$s no indica logros para este juego.</string>
|
||||
<string name="achievements_show_all">Ver los %1$d</string>
|
||||
<string name="achievements_dialog_title">Logros · %1$s</string>
|
||||
<string name="stores_fact_developer">Desarrollador</string>
|
||||
<string name="stores_fact_publisher">Distribuidor</string>
|
||||
<string name="stores_fact_released">Lanzamiento</string>
|
||||
<string name="stores_hltb_main">Principal</string>
|
||||
<string name="stores_hltb_extras">+ Extras</string>
|
||||
<string name="stores_hltb_completionist">Completista</string>
|
||||
<string name="stores_hltb_hours">%1$s h</string>
|
||||
<string name="stores_hltb_minutes">%1$d min</string>
|
||||
</resources>
|
||||
@@ -977,4 +977,12 @@
|
||||
<string name="achievements_none">%1$s n\'indique aucun succès pour ce jeu.</string>
|
||||
<string name="achievements_show_all">Tout afficher (%1$d)</string>
|
||||
<string name="achievements_dialog_title">Succès · %1$s</string>
|
||||
<string name="stores_fact_developer">Développeur</string>
|
||||
<string name="stores_fact_publisher">Éditeur</string>
|
||||
<string name="stores_fact_released">Sortie</string>
|
||||
<string name="stores_hltb_main">Principal</string>
|
||||
<string name="stores_hltb_extras">+ Extras</string>
|
||||
<string name="stores_hltb_completionist">Complétionniste</string>
|
||||
<string name="stores_hltb_hours">%1$s h</string>
|
||||
<string name="stores_hltb_minutes">%1$d min</string>
|
||||
</resources>
|
||||
@@ -2103,4 +2103,12 @@
|
||||
<string name="achievements_none">%1$s にはこのゲームの実績がありません。</string>
|
||||
<string name="achievements_show_all">すべて表示(%1$d)</string>
|
||||
<string name="achievements_dialog_title">実績 · %1$s</string>
|
||||
<string name="stores_fact_developer">開発元</string>
|
||||
<string name="stores_fact_publisher">パブリッシャー</string>
|
||||
<string name="stores_fact_released">発売日</string>
|
||||
<string name="stores_hltb_main">メイン</string>
|
||||
<string name="stores_hltb_extras">+ やり込み</string>
|
||||
<string name="stores_hltb_completionist">完全制覇</string>
|
||||
<string name="stores_hltb_hours">%1$s時間</string>
|
||||
<string name="stores_hltb_minutes">%1$d分</string>
|
||||
</resources>
|
||||
@@ -2103,4 +2103,12 @@
|
||||
<string name="achievements_none">%1$s에 이 게임의 도전 과제가 없습니다.</string>
|
||||
<string name="achievements_show_all">모두 보기(%1$d)</string>
|
||||
<string name="achievements_dialog_title">도전 과제 · %1$s</string>
|
||||
<string name="stores_fact_developer">개발사</string>
|
||||
<string name="stores_fact_publisher">배급사</string>
|
||||
<string name="stores_fact_released">출시일</string>
|
||||
<string name="stores_hltb_main">메인</string>
|
||||
<string name="stores_hltb_extras">+ 추가 요소</string>
|
||||
<string name="stores_hltb_completionist">완전 정복</string>
|
||||
<string name="stores_hltb_hours">%1$s시간</string>
|
||||
<string name="stores_hltb_minutes">%1$d분</string>
|
||||
</resources>
|
||||
@@ -1088,4 +1088,12 @@
|
||||
<string name="achievements_none">В %1$s нет достижений для этой игры.</string>
|
||||
<string name="achievements_show_all">Показать все (%1$d)</string>
|
||||
<string name="achievements_dialog_title">Достижения · %1$s</string>
|
||||
<string name="stores_fact_developer">Разработчик</string>
|
||||
<string name="stores_fact_publisher">Издатель</string>
|
||||
<string name="stores_fact_released">Дата выхода</string>
|
||||
<string name="stores_hltb_main">Сюжет</string>
|
||||
<string name="stores_hltb_extras">+ Доп. задания</string>
|
||||
<string name="stores_hltb_completionist">Полностью</string>
|
||||
<string name="stores_hltb_hours">%1$s ч</string>
|
||||
<string name="stores_hltb_minutes">%1$d мин</string>
|
||||
</resources>
|
||||
@@ -2103,4 +2103,12 @@
|
||||
<string name="achievements_none">%1$s 未列出此游戏的成就。</string>
|
||||
<string name="achievements_show_all">显示全部 %1$d 项</string>
|
||||
<string name="achievements_dialog_title">成就 · %1$s</string>
|
||||
<string name="stores_fact_developer">开发商</string>
|
||||
<string name="stores_fact_publisher">发行商</string>
|
||||
<string name="stores_fact_released">发行日期</string>
|
||||
<string name="stores_hltb_main">主线</string>
|
||||
<string name="stores_hltb_extras">+ 支线</string>
|
||||
<string name="stores_hltb_completionist">全收集</string>
|
||||
<string name="stores_hltb_hours">%1$s 小时</string>
|
||||
<string name="stores_hltb_minutes">%1$d 分钟</string>
|
||||
</resources>
|
||||
@@ -2103,4 +2103,12 @@
|
||||
<string name="achievements_none">%1$s 未列出此遊戲的成就。</string>
|
||||
<string name="achievements_show_all">顯示全部 %1$d 項</string>
|
||||
<string name="achievements_dialog_title">成就 · %1$s</string>
|
||||
<string name="stores_fact_developer">開發商</string>
|
||||
<string name="stores_fact_publisher">發行商</string>
|
||||
<string name="stores_fact_released">發行日期</string>
|
||||
<string name="stores_hltb_main">主線</string>
|
||||
<string name="stores_hltb_extras">+ 支線</string>
|
||||
<string name="stores_hltb_completionist">全收集</string>
|
||||
<string name="stores_hltb_hours">%1$s 小時</string>
|
||||
<string name="stores_hltb_minutes">%1$d 分鐘</string>
|
||||
</resources>
|
||||
@@ -2103,4 +2103,12 @@
|
||||
<string name="achievements_none">%1$s 沒有列出這款遊戲的成就。</string>
|
||||
<string name="achievements_show_all">顯示全部 %1$d 項</string>
|
||||
<string name="achievements_dialog_title">成就 · %1$s</string>
|
||||
<string name="stores_fact_developer">開發商</string>
|
||||
<string name="stores_fact_publisher">發行商</string>
|
||||
<string name="stores_fact_released">發行日期</string>
|
||||
<string name="stores_hltb_main">主線</string>
|
||||
<string name="stores_hltb_extras">+ 支線</string>
|
||||
<string name="stores_hltb_completionist">全收集</string>
|
||||
<string name="stores_hltb_hours">%1$s 小時</string>
|
||||
<string name="stores_hltb_minutes">%1$d 分鐘</string>
|
||||
</resources>
|
||||
@@ -575,6 +575,33 @@
|
||||
<string name="drawer_cas">Sharpening (CAS)</string>
|
||||
<string name="drawer_cas_level">Sharpening level</string>
|
||||
<string name="drawer_fake_hdr">Fake HDR</string>
|
||||
<string name="cardboard_title">Cardboard VR</string>
|
||||
<string name="cardboard_mode">Cardboard mode</string>
|
||||
<string name="cardboard_mode_hint">Left and right eye views for a phone VR viewer.</string>
|
||||
<string name="cardboard_source">Picture</string>
|
||||
<string name="cardboard_source_screen">Virtual screen</string>
|
||||
<string name="cardboard_source_sbs">Side-by-side 3D</string>
|
||||
<string name="cardboard_viewer">Viewer</string>
|
||||
<string name="cardboard_viewer_v2">Cardboard</string>
|
||||
<string name="cardboard_viewer_v1">Cardboard (2014)</string>
|
||||
<string name="cardboard_viewer_none">No lens</string>
|
||||
<string name="cardboard_ipd">Eye distance</string>
|
||||
<string name="cardboard_screen_width">Screen width</string>
|
||||
<string name="cardboard_screen_distance">Screen distance</string>
|
||||
<string name="cardboard_head_tracking">Head tracking</string>
|
||||
<string name="cardboard_no_sensor">This device has no rotation sensor.</string>
|
||||
<string name="cardboard_recenter">Recenter view</string>
|
||||
<string name="cardboard_recenter_button">Recenter</string>
|
||||
<string name="cardboard_steamvr">SteamVR (experimental)</string>
|
||||
<string name="cardboard_steamvr_install">Install</string>
|
||||
<string name="cardboard_steamvr_install_hint">Downloads Valve\'s ARM64 SteamVR (571 MB).</string>
|
||||
<string name="cardboard_steamvr_installing">Downloading and unpacking SteamVR…</string>
|
||||
<string name="cardboard_steamvr_start">Start</string>
|
||||
<string name="cardboard_steamvr_ready_hint">Runs SteamVR with your head as the headset; the picture switches to side-by-side 3D.</string>
|
||||
<string name="cardboard_steamvr_stop">Stop</string>
|
||||
<string name="cardboard_steamvr_running_hint">SteamVR is running.</string>
|
||||
<string name="cardboard_steamvr_unavailable">Not available in this session.</string>
|
||||
<string name="cardboard_steamvr_failed">SteamVR did not respond; see the session log.</string>
|
||||
<string name="drawer_deband">Debanding</string>
|
||||
<string name="drawer_deband_strength">Debanding strength</string>
|
||||
<string name="drawer_brightness">Brightness</string>
|
||||
@@ -2144,6 +2171,17 @@
|
||||
<string name="achievements_none">%1$s lists no achievements for this game.</string>
|
||||
<string name="achievements_show_all">Show all %1$d</string>
|
||||
<string name="achievements_dialog_title">Achievements · %1$s</string>
|
||||
<!-- A store game's facts row: the store's own facts, then Metacritic and HowLongToBeat, looked up by name. -->
|
||||
<string name="stores_fact_developer">Developer</string>
|
||||
<string name="stores_fact_publisher">Publisher</string>
|
||||
<string name="stores_fact_released">Released</string>
|
||||
<string name="stores_fact_metacritic" translatable="false">Metacritic</string>
|
||||
<string name="stores_fact_hltb" translatable="false">HowLongToBeat</string>
|
||||
<string name="stores_hltb_main">Main</string>
|
||||
<string name="stores_hltb_extras">+ Extras</string>
|
||||
<string name="stores_hltb_completionist">Completionist</string>
|
||||
<string name="stores_hltb_hours">%1$s h</string>
|
||||
<string name="stores_hltb_minutes">%1$d min</string>
|
||||
<string name="stores_in_steam">✓ In Steam</string>
|
||||
<string name="stores_uninstall">Uninstall</string>
|
||||
<string name="stores_uninstalling">Uninstalling…</string>
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
package com.droiddeck.launcher.gpu
|
||||
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import kotlin.math.PI
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.sin
|
||||
import kotlin.math.sqrt
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], manifest = Config.NONE)
|
||||
class CardboardTest {
|
||||
private val eps = 1e-4f
|
||||
|
||||
private fun assertVec(expected: FloatArray, actual: FloatArray) = assertArrayEquals(expected, actual, eps)
|
||||
|
||||
/** Rotation about a unit axis by an angle, as a quaternion (x, y, z, w). */
|
||||
private fun quat(ax: Float, ay: Float, az: Float, deg: Double): FloatArray {
|
||||
val h = deg * PI / 360.0
|
||||
val s = sin(h).toFloat()
|
||||
return floatArrayOf(ax * s, ay * s, az * s, cos(h).toFloat())
|
||||
}
|
||||
|
||||
private fun matrix(q: FloatArray) = HeadPose.fromQuaternion(q[0], q[1], q[2], q[3])
|
||||
|
||||
@Test fun settingsRoundTripAndClamp() {
|
||||
val c = Cardboard(enabled = true, source = Cardboard.SOURCE_SBS, viewer = "none", ipdMm = 70,
|
||||
screenWidthDm = 55, screenDistanceDm = 25, headTracking = false)
|
||||
assertEquals(c, Cardboard.decode(c.encode()))
|
||||
val wild = Cardboard.decode(JSONObject().put("ipdMm", 500).put("screenWidthDm", -3).put("viewer", "nope").put("source", 7))
|
||||
assertEquals(80, wild.ipdMm)
|
||||
assertEquals(5, wild.screenWidthDm)
|
||||
assertEquals(Cardboard.Viewer.CARDBOARD_V2.id, wild.viewer)
|
||||
assertEquals(Cardboard.SOURCE_SCREEN, wild.source)
|
||||
assertEquals(Cardboard.OFF, Cardboard.decode(JSONObject()))
|
||||
}
|
||||
|
||||
@Test fun lensInsetLinesTheEyesUpWithTheLenses() {
|
||||
// A 128 mm panel with 64 mm lenses: each viewport centre is 32 mm out, exactly under its lens.
|
||||
assertEquals(0f, Cardboard.lensInset(128f, 64f), eps)
|
||||
// A wider 150 mm panel: viewport centres 37.5 mm out, lenses 32 mm: 5.5 mm of a 75 mm viewport inwards.
|
||||
assertEquals(5.5f / 75f, Cardboard.lensInset(150f, 64f), eps)
|
||||
// A narrow panel puts the lens centres outside the viewport centres (negative inset).
|
||||
assertEquals(true, Cardboard.lensInset(110f, 64f) < 0f)
|
||||
assertEquals(0f, Cardboard.lensInset(0f, 64f), eps)
|
||||
assertEquals(0f, Cardboard.lensInset(150f, 0f), eps)
|
||||
}
|
||||
|
||||
@Test fun steamVrStatusFollowsTheAgentAnswer() {
|
||||
fun answer(vararg pairs: Pair<String, Boolean>) = JSONObject().apply { pairs.forEach { put(it.first, it.second) } }
|
||||
assertEquals(SteamVr.Status.UNAVAILABLE, SteamVr.parse(answer("ok" to false, "installed" to true, "driver" to true)))
|
||||
assertEquals(SteamVr.Status.UNAVAILABLE, SteamVr.parse(answer("ok" to true, "installed" to true, "driver" to false)))
|
||||
assertEquals(SteamVr.Status.NOT_INSTALLED, SteamVr.parse(answer("ok" to true, "driver" to true)))
|
||||
assertEquals(SteamVr.Status.INSTALLING, SteamVr.parse(answer("ok" to true, "installing" to true)))
|
||||
assertEquals(SteamVr.Status.READY, SteamVr.parse(answer("ok" to true, "installed" to true, "driver" to true)))
|
||||
assertEquals(SteamVr.Status.RUNNING,
|
||||
SteamVr.parse(answer("ok" to true, "installed" to true, "driver" to true, "running" to true)))
|
||||
// The helper itself failed: the agent still says ok.
|
||||
assertEquals(SteamVr.Status.UNAVAILABLE,
|
||||
SteamVr.parse(answer("ok" to true, "installed" to true, "driver" to true).put("exitCode", 1)))
|
||||
}
|
||||
|
||||
@Test fun steamVrActionsSucceedOnlyWhenTheHelperDid() {
|
||||
fun answer(ok: Boolean, exitCode: Int? = null, started: Boolean? = null) = JSONObject().apply {
|
||||
put("ok", ok)
|
||||
exitCode?.let { put("exitCode", it) }
|
||||
started?.let { put("started", it) }
|
||||
}
|
||||
assertTrue(SteamVr.succeeded("start", answer(true, exitCode = 0)))
|
||||
assertTrue(SteamVr.succeeded("stop", answer(true, exitCode = 0)))
|
||||
// The agent ran the request, but droiddeck-steamvr start failed (not installed, no driver).
|
||||
assertFalse(SteamVr.succeeded("start", answer(true, exitCode = 1)))
|
||||
assertFalse(SteamVr.succeeded("stop", answer(true, exitCode = 2)))
|
||||
assertFalse(SteamVr.succeeded("start", answer(true)))
|
||||
assertFalse(SteamVr.succeeded("start", answer(false, exitCode = 0)))
|
||||
assertTrue(SteamVr.succeeded("install", answer(true, started = true)))
|
||||
assertFalse(SteamVr.succeeded("install", answer(true)))
|
||||
assertFalse(SteamVr.succeeded("install", answer(false, started = true)))
|
||||
}
|
||||
|
||||
@Test fun quaternionMatchesKnownRotations() {
|
||||
// 90 degrees about z: x -> y.
|
||||
val m = matrix(quat(0f, 0f, 1f, 90.0))
|
||||
assertVec(floatArrayOf(0f, 1f, 0f), HeadPose.apply(m, floatArrayOf(1f, 0f, 0f)))
|
||||
// Rotation vector without w: computed from the other three.
|
||||
val q = HeadPose.quaternionFromRotationVector(floatArrayOf(0f, 0f, sin(PI / 4).toFloat()))
|
||||
assertEquals(cos(PI / 4).toFloat(), q[3], eps)
|
||||
}
|
||||
|
||||
@Test fun recenterMakesTheCurrentViewStraightAhead() {
|
||||
// Phone upright in landscape, screen facing the viewer, who faces north-east-ish.
|
||||
// Upright device: screen up = world up; looking direction = the screen's -z.
|
||||
for (heading in listOf(0.0, 37.0, 140.0, -100.0)) {
|
||||
// Start from "screen faces south, viewer looks north": device x = east, y = up, z = south.
|
||||
val upright = floatArrayOf(1f, 0f, 0f, 0f, 0f, -1f, 0f, 1f, 0f)
|
||||
val yaw = matrix(quat(0f, 0f, 1f, heading))
|
||||
val screenToWorld = HeadPose.multiply(yaw, upright)
|
||||
assertVec(HeadPose.IDENTITY, HeadPose.relative(HeadPose.recenter(screenToWorld), screenToWorld))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun recenterKeepsPitchButDropsHeading() {
|
||||
val upright = floatArrayOf(1f, 0f, 0f, 0f, 0f, -1f, 0f, 1f, 0f)
|
||||
// Looking 30 degrees down, then turning 50 degrees: after a recentre the view is still 30 degrees down.
|
||||
val pitched = HeadPose.multiply(upright, matrix(quat(1f, 0f, 0f, -30.0)))
|
||||
val turned = HeadPose.multiply(matrix(quat(0f, 0f, 1f, 50.0)), pitched)
|
||||
val pose = HeadPose.relative(HeadPose.recenter(turned), turned)
|
||||
val forward = HeadPose.apply(pose, floatArrayOf(0f, 0f, -1f))
|
||||
assertEquals(0f, forward[0], eps)
|
||||
assertEquals(-sin(PI / 6).toFloat(), forward[1], eps)
|
||||
assertEquals(-cos(PI / 6).toFloat(), forward[2], eps)
|
||||
}
|
||||
|
||||
@Test fun turningTheHeadTurnsTheView() {
|
||||
val upright = floatArrayOf(1f, 0f, 0f, 0f, 0f, -1f, 0f, 1f, 0f)
|
||||
val ref = HeadPose.recenter(upright)
|
||||
// Turn the head 90 degrees to the left (counter-clockwise seen from above).
|
||||
val turned = HeadPose.multiply(matrix(quat(0f, 0f, 1f, 90.0)), upright)
|
||||
val forward = HeadPose.apply(HeadPose.relative(ref, turned), floatArrayOf(0f, 0f, -1f))
|
||||
// The view now points to the left of the recentred forward direction: -x.
|
||||
assertVec(floatArrayOf(-1f, 0f, 0f), forward)
|
||||
}
|
||||
|
||||
@Test fun heldFlatTheViewStartsStraightAhead() {
|
||||
// Screen facing up (device on a table, held like a tray, or lying back looking up at it).
|
||||
for (m in listOf(HeadPose.IDENTITY, HeadPose.multiply(matrix(quat(0f, 0f, 1f, 30.0)), matrix(quat(1f, 0f, 0f, 20.0))))) {
|
||||
assertVec(HeadPose.IDENTITY, HeadPose.relative(HeadPose.recenter(m), m))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun heldFlatTurningAtTheHipsPans() {
|
||||
// Held flat, then the body turns 40 degrees to the left about the real vertical: the view
|
||||
// turns left about its own up axis - it must not roll (the bug: yaw came out as a tilt).
|
||||
val flat = HeadPose.IDENTITY
|
||||
val ref = HeadPose.recenter(flat)
|
||||
val turned = HeadPose.multiply(matrix(quat(0f, 0f, 1f, 40.0)), flat)
|
||||
val pose = HeadPose.relative(ref, turned)
|
||||
val forward = HeadPose.apply(pose, floatArrayOf(0f, 0f, -1f))
|
||||
val up = HeadPose.apply(pose, floatArrayOf(0f, 1f, 0f))
|
||||
assertVec(floatArrayOf(-sin(PI * 40 / 180).toFloat(), 0f, -cos(PI * 40 / 180).toFloat()), forward)
|
||||
assertVec(floatArrayOf(0f, 1f, 0f), up)
|
||||
// Tipping the top edge down (pitching the tray towards you) looks down.
|
||||
val tipped = HeadPose.multiply(flat, matrix(quat(1f, 0f, 0f, -20.0)))
|
||||
val down = HeadPose.apply(HeadPose.relative(ref, tipped), floatArrayOf(0f, 0f, -1f))
|
||||
assertEquals(-sin(PI / 9).toFloat(), down[1], eps)
|
||||
}
|
||||
|
||||
@Test fun fieldOfViewComesFromThePanelSeenThroughTheLens() {
|
||||
val v2 = Cardboard.Viewer.CARDBOARD_V2
|
||||
// A 74.7 mm tall panel 39.3 mm behind the lens: atan(37.35 / 39.3) = 43.5 degrees each way.
|
||||
assertEquals(87.07f, Cardboard.fovDeg(v2, 74.7f), 0.05f)
|
||||
assertEquals(v2.fallbackFovDeg, Cardboard.fovDeg(v2, 0f), eps)
|
||||
assertEquals(Cardboard.Viewer.NONE.fallbackFovDeg, Cardboard.fovDeg(Cardboard.Viewer.NONE, 74.7f), eps)
|
||||
}
|
||||
|
||||
@Test fun displayRotationRemapsTheScreenAxes() {
|
||||
val r = matrix(quat(0.3f, -0.5f, 0.2f, 70.0).let { q ->
|
||||
val n = sqrt(q[0] * q[0] + q[1] * q[1] + q[2] * q[2] + q[3] * q[3]); floatArrayOf(q[0] / n, q[1] / n, q[2] / n, q[3] / n)
|
||||
})
|
||||
assertVec(r, HeadPose.toScreen(r, 0))
|
||||
// ROTATION_90 (as input/PadMotion maps it): screen x is the device's -y, screen y the device's x.
|
||||
val s90 = HeadPose.toScreen(r, 1)
|
||||
assertVec(HeadPose.apply(r, floatArrayOf(0f, -1f, 0f)), HeadPose.apply(s90, floatArrayOf(1f, 0f, 0f)))
|
||||
assertVec(HeadPose.apply(r, floatArrayOf(1f, 0f, 0f)), HeadPose.apply(s90, floatArrayOf(0f, 1f, 0f)))
|
||||
// ROTATION_270 is the opposite turn; four quarter turns of 90 give the original back.
|
||||
val s270 = HeadPose.toScreen(r, 3)
|
||||
assertVec(HeadPose.apply(r, floatArrayOf(0f, 1f, 0f)), HeadPose.apply(s270, floatArrayOf(1f, 0f, 0f)))
|
||||
assertVec(r, HeadPose.toScreen(HeadPose.toScreen(HeadPose.toScreen(HeadPose.toScreen(r, 1), 1), 1), 1))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.droiddeck.launcher.stores
|
||||
|
||||
import java.util.Locale
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
|
||||
/** The name match that finds a store game on Steam and HowLongToBeat, and how its facts read. */
|
||||
class GameFactsTest {
|
||||
private val saved = Locale.getDefault()
|
||||
|
||||
@Before fun english() = Locale.setDefault(Locale.US)
|
||||
@After fun restore() = Locale.setDefault(saved)
|
||||
|
||||
@Test fun theSameNameMatchesWhateverItsMarksAndPunctuation() {
|
||||
assertEquals(3, TitleMatch.score("The Witcher 3: Wild Hunt", "The Witcher 3: Wild Hunt"))
|
||||
assertEquals(3, TitleMatch.score("DOOM Eternal™", "DOOM Eternal"))
|
||||
assertEquals(3, TitleMatch.score("Ori & the Will of the Wisps", "Ori and the Will of the Wisps"))
|
||||
}
|
||||
|
||||
@Test fun anEditionIsTheSameGame() {
|
||||
assertEquals(2, TitleMatch.score("The Witcher 3: Wild Hunt - Complete Edition", "The Witcher 3: Wild Hunt"))
|
||||
assertEquals(2, TitleMatch.score("Control", "Control Ultimate Edition"))
|
||||
assertEquals(2, TitleMatch.score("Fallout: New Vegas - Ultimate Edition", "Fallout: New Vegas"))
|
||||
}
|
||||
|
||||
@Test fun aSubtitleOnEitherSideStillMatchesButLessWell() {
|
||||
assertEquals(1, TitleMatch.score("The Witcher 3: Wild Hunt", "The Witcher 3: Wild Hunt — Remastered"))
|
||||
assertEquals(1, TitleMatch.score("Alan Wake Remastered (2021)", "Alan Wake Remastered"))
|
||||
}
|
||||
|
||||
@Test fun aSequelOrASiblingIsNotTheSameGame() {
|
||||
assertEquals(0, TitleMatch.score("Hades", "Hades II"))
|
||||
assertEquals(0, TitleMatch.score("Batman: Arkham City", "Batman: Arkham Knight"))
|
||||
assertEquals(0, TitleMatch.score("Portal", "Portal 2"))
|
||||
assertEquals(0, TitleMatch.score("", "Portal"))
|
||||
}
|
||||
|
||||
@Test fun thePickPrefersTheClosestNameThenTheSitesOwnOrder() {
|
||||
val results = listOf("Hades II", "The Witcher 3: Wild Hunt — Songs of the Past", "Hades", "Hades")
|
||||
assertEquals(2, TitleMatch.pick("Hades", results.withIndex().toList()) { listOf(it.value) }?.index)
|
||||
assertNull(TitleMatch.pick("Hades", listOf("Hades II", "Hadesville")) { listOf(it) })
|
||||
// An alias counts as a name.
|
||||
assertEquals("x", TitleMatch.pick("The Witcher III: Wild Hunt", listOf("x" to "The Witcher 3: Wild Hunt, The Witcher III: Wild Hunt")) { it.second.split(',') }?.first)
|
||||
}
|
||||
|
||||
@Test fun theSearchTermDropsMarksAndTheEdition() {
|
||||
assertEquals("The Witcher 3 Wild Hunt", TitleMatch.searchTerm("The Witcher® 3: Wild Hunt - Game of the Year Edition"))
|
||||
assertEquals("Disco Elysium The Final Cut", TitleMatch.searchTerm("Disco Elysium - The Final Cut"))
|
||||
assertEquals("Marvel's Spider-Man Remastered", TitleMatch.searchTerm("Marvel's Spider-Man Remastered"))
|
||||
assertEquals("Deluxe Ski Jump", TitleMatch.searchTerm("Deluxe Ski Jump"))
|
||||
}
|
||||
|
||||
@Test fun eachStoresDateReadsTheSameAndAPlaceholderIsDropped() {
|
||||
assertEquals("May 19, 2015", GameFacts.releaseLabel("2015-05-19T00:00:00+02:00"))
|
||||
assertEquals("May 19, 2015", GameFacts.releaseLabel("2015.05.19"))
|
||||
assertEquals("Dec 19, 2022", GameFacts.releaseLabel("2022-12-19T16:00:00.000Z"))
|
||||
assertNull(GameFacts.releaseLabel("2099-01-01T00:00:00.000Z"))
|
||||
assertNull(GameFacts.releaseLabel("null"))
|
||||
assertNull(GameFacts.releaseLabel(""))
|
||||
}
|
||||
|
||||
@Test fun hoursRoundToTheNearestHalf() {
|
||||
assertEquals("51½", GameFacts.hours(186_070))
|
||||
assertEquals("52", GameFacts.hours(52 * 3600 + 500))
|
||||
assertEquals("51½", GameFacts.hours(51 * 3600 + 1900))
|
||||
assertEquals("1", GameFacts.hours(3600))
|
||||
assertNull(GameFacts.hours(2_400))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
# Cardboard VR (experimental)
|
||||
|
||||
Cardboard mode turns the session screen into a phone VR viewer (Google Cardboard and similar): the
|
||||
panel is split into a left and a right eye, each drawn through a barrel distortion that the viewer's
|
||||
lenses undo. Two sources can feed it:
|
||||
|
||||
- **Virtual screen** (any game, Steam, the desktop): the session hangs as a flat screen in front of
|
||||
you, with real stereo depth from the eye distance. With head tracking on, the phone's rotation
|
||||
sensor keeps the screen fixed in the room while your head turns (3DoF).
|
||||
- **Side-by-side 3D**: the frame already holds a left and a right image. This is what SteamVR draws
|
||||
here (below), and what SBS 3D video or a stereo shader like SuperDepth3D produces. Only the lens is
|
||||
added.
|
||||
|
||||
The settings live in the session drawer, **Display > Cardboard VR**: mode, picture, viewer (lens
|
||||
profile), eye distance, screen size and distance, head tracking and recenter, and SteamVR. Everything
|
||||
applies live. `tools/droiddeckctl prefs set session cardboard '{"enabled":true,...}'` drives the same
|
||||
settings (`gpu/Cardboard.kt` has the keys).
|
||||
|
||||
## How the picture is made
|
||||
|
||||
```
|
||||
game / Steam -> gamescope -> DroidDeck compositor -> effects -> frame generation
|
||||
-> Cardboard pass (cardboard.frag) -> 1:1 blit -> panel
|
||||
```
|
||||
|
||||
`app/src/main/cpp/waylandcomp/src/cardboard.c` is the last stage of the compositor pass. It forces the
|
||||
copy path (no zero-copy layer: the pass draws the whole panel) and renders `cardboard.frag` into a
|
||||
panel-sized target:
|
||||
|
||||
- each output pixel picks its eye, finds its offset from that eye's lens centre in tangent space, and
|
||||
applies the viewer's distortion polynomial `r(1 + k1 r² + k2 r⁴)` (sampling outwards draws the image
|
||||
barrel-shaped; the lens pincushions it back), optionally per colour channel for chromatic
|
||||
aberration;
|
||||
- **virtual screen**: the ray from the eye (offset by half the IPD), rotated by the head pose,
|
||||
meets a plane `screenDistance` away; outside it is a dark backdrop;
|
||||
- **side-by-side**: the eye samples its own half of the frame over the same field of view.
|
||||
|
||||
The lens centres sit inset towards the nose so they line up with the viewer's lenses on the panel
|
||||
actually used (the panel's physical size from DisplayMetrics). The field of view is the panel's height
|
||||
seen from the lens's focal distance (`Cardboard.fovDeg`). Viewer profiles are in `Cardboard.Viewer`.
|
||||
|
||||
Head tracking (`gpu/HeadTracker.kt`) reads the game rotation vector (gyro and accelerometer, no compass)
|
||||
on a thread of its own and hands a row-major head-to-world matrix straight to native code. Recenter
|
||||
resets the heading only, so the horizon stays level. When the view is more than 60° from level (lying
|
||||
back, or the device flat on a table) it takes the whole orientation as straight ahead. A new pose
|
||||
redraws even a static scene (`vkp_cardboard_pose_changed` on the vsync tick).
|
||||
|
||||
The pose is also published to the guest: a 128-byte seqlocked file, `headpose_shm.h`, at
|
||||
`/run/droiddeck/droiddeck-headpose`. It carries the rotation, the IPD, and the frustum the side-by-side
|
||||
pass expects of a source (`tan_half_fov`, `eye_aspect`, eye size), so a renderer in the guest can match
|
||||
the lens exactly.
|
||||
|
||||
## SteamVR
|
||||
|
||||
Valve's ARM64 SteamVR, the build the Steam Frame runs, comes from Valve's public SteamOS package
|
||||
server (`deckard-steamvr`, pinned by version and SHA-256 in `droiddeck-steamvr`; the same hash
|
||||
[steam-frame-nixos](https://github.com/y0usaf/steam-frame-nixos) pins). `droiddeck-steamvr install`
|
||||
unpacks it to `/opt/steamvr`. The drawer's **Install** button runs that (571 MB). **Start** then
|
||||
switches the picture to side-by-side and runs SteamVR with three DroidDeck pieces (`tools/vr`):
|
||||
|
||||
1. **`driver_droiddeck.so`**, an OpenVR driver with one HMD:
|
||||
- pose: the shared head pose file (3DoF, standing height);
|
||||
- projection: exactly the frustum the Cardboard pass samples, with identity distortion (the app does
|
||||
the lens);
|
||||
- a proximity sensor that reads "worn" while Cardboard mode is on. Without it SteamVR takes a still
|
||||
headset (a phone on a table) for an unused one, enters standby after a few seconds, and the
|
||||
compositor stops submitting frames;
|
||||
- frames: `IVRDriverDirectModeComponent` with a free-running 60 Hz vsync announcer, as ALVR does on
|
||||
Linux. SteamVR renders each eye into textures the driver allocates through its IPC resource
|
||||
manager (dmabufs);
|
||||
- `presenter.cpp` imports those eye textures into a Vulkan device of its own and blits them side
|
||||
by side into a fullscreen window on DroidDeck's own compositor (`wayland-0`, the app_id
|
||||
`droiddeck-cardboard-vr` keeps it above gamescope's window), sized to the Cardboard panel so
|
||||
nothing scales it down. SteamVR hands the textures over with no fence the driver can wait on, so
|
||||
the presenter gives the compositor's GPU work a few milliseconds first, as ALVR does.
|
||||
`DROIDDECK_VR_PRESENT=x11` uses the older path instead: an X11 window on gamescope's Xwayland marked
|
||||
`STEAM_OVERLAY` (the external overlay slot is mangoapp's), at the session's resolution;
|
||||
2. **`VK_LAYER_DROIDDECK_vr`**, a Vulkan layer, enabled explicitly in SteamVR's processes and implicit
|
||||
for the rest of the session (Steam's own web helper shares its in-VR overlay with SteamVR too, and
|
||||
crashes without it until Steam quits). Implicitly it does nothing in an ordinary session:
|
||||
- the display stand-in below happens only while SteamVR runs (`droiddeck-steamvr`'s `active`
|
||||
marker, which a new session clears) or where the layer is enabled by name. Gamescope and games
|
||||
asking for display extensions outside SteamVR get them untouched;
|
||||
- the semaphore bridge runs in those same processes, and in Steam's web helper once SteamVR is
|
||||
installed;
|
||||
- with SteamVR not installed, every process gets the driver's functions unchanged.
|
||||
|
||||
What it does in SteamVR's processes:
|
||||
- `vrcompositor` always asks for `VK_KHR_display` and keeps a direct-mode window even with a
|
||||
driver-direct HMD. Turnip on KGSL refuses to enumerate any GPU when `VK_KHR_display` is enabled
|
||||
("I can't KHR_display"). The layer takes the display extensions off the instance and stands in
|
||||
for one display with one mode and one plane, whose surface is a headless one
|
||||
(`VK_EXT_headless_surface`, sized from the mode because headless reports none). The vblank side
|
||||
of `VK_EXT_display_control` is a 60 Hz clock;
|
||||
- SteamVR shares a timeline semaphore with every shared image, exported as an opaque fd, which
|
||||
Turnip/KGSL cannot export. The layer creates it unshared and hands out a memfd holding a 64-bit
|
||||
counter instead. Every process with the semaphore keeps a real local one, and a poller thread
|
||||
carries values both ways (reached locally: up into the counter; seen in the counter: signalled
|
||||
locally from the host), so GPU waits work as written, a poll period late. Waits on an imported
|
||||
binary semaphore, which cannot be bridged that way, are dropped. With the semaphores dropped
|
||||
outright (the first version) the dashboard showed torn, half-drawn tiles;
|
||||
- Turnip on KGSL does not defer a submit that waits on a timeline value nobody has signalled yet:
|
||||
`vkQueueSubmit` blocks until it is. SteamVR's client waits on a compositor value that the
|
||||
compositor signals only after the client has submitted and said so, which deadlocked every app
|
||||
before its first frame (`helloxr`'s swapchain acquire, DXVK's submit thread in a Proton game).
|
||||
A submit's wait on an imported shared value that is neither reached nor queued in that process
|
||||
gets 3 ms for the other process to reach it, then is dropped;
|
||||
- Steam's web helper has the semaphore bridge whenever SteamVR is installed: its GPU process
|
||||
outlives SteamVR runs, and one started without the layer crashed when SteamVR showed Steam's
|
||||
overlays, until Steam quit;
|
||||
- `DROIDDECK_VR_CRASHTRACE=1` (or a `crashtrace` file beside the `active` marker, for processes like
|
||||
Steam whose environment is not ours) prints a backtrace on a fatal signal. `vrcompositor`'s
|
||||
launcher drops `LD_PRELOAD`, but the layer is loaded there. It only takes signals nobody handles
|
||||
yet: Wine and FEX handle `SIGSEGV` as part of running a Proton game, and a replaced handler
|
||||
crashed The Lab;
|
||||
- a `semtrace` file beside the marker logs, every 2 s, each bridged semaphore's local and shared
|
||||
value and the memfd inode that names it in every process, plus the first waits and signals
|
||||
(values up to 3) submitted on them.
|
||||
3. **`droiddeck-steamvr`**, the guest helper (`status | install | start | stop`), which the app drives
|
||||
through the guest agent's fixed `vr` request (no agent commands needed). It also supplies an `xset`
|
||||
stand-in, because the dashboard's web helper checks the X server with it.
|
||||
|
||||
Imported eye textures carry the same format list SteamVR's mutable sRGB images do. With it Turnip keeps
|
||||
UBWC compression on, and an import that disagreed read compressed data as garbage.
|
||||
|
||||
Two more fixes outside `tools/vr` were needed for the dashboard (Steam's library, in VR):
|
||||
|
||||
- **SysV semaphores** (`tools/linuxfs/preload/sysv.c`): the session emulates them, and `IPC_STAT`
|
||||
reported `sem_otime` 0 forever. SteamVR's web helper does the usual race-free init (wait until
|
||||
`sem_otime` is non-zero), so its zygotes slept in a `semctl`/`usleep` loop and the dashboard never
|
||||
appeared. `semop` now stamps `sem_otime`, `SETVAL`/`SETALL`/`IPC_SET` stamp `sem_ctime`;
|
||||
`test_sysv_preload.py` covers it.
|
||||
- `vrwebhelper` gets the same tracer treatment as Steam's `steamwebhelper` (`tracer.c`).
|
||||
|
||||
Verified on the AYN Thor (SD 8 Gen 2, Turnip): SteamVR 2.17.10 starts with the DroidDeck HMD active,
|
||||
the compositor runs driver-direct at about 60 fps, the dashboard (Steam's library in VR, with the
|
||||
controller's laser) shows cleanly in both eyes at the panel's resolution while Steam keeps running, and
|
||||
a pose written to the shared file turns SteamVR's view. Started from the drawer button through the agent.
|
||||
|
||||
### Not done yet
|
||||
|
||||
- **Controllers**: the driver adds two Vive-profile hands driven by the session's game pad. It reads
|
||||
the absolute-state snapshot the app already publishes in fake input ring 0
|
||||
(`FAKE_EVDEV_MEMFD_PATHS`), so the app needs no new plumbing. They are a gaze pointer: low in front
|
||||
of each hand, pointing where the head looks. Mapping, right hand: right stick = trackpad, A/R3 =
|
||||
trackpad click, RT = trigger, RB = grip, Start = menu, guide = system. Left hand: left stick, X/L3,
|
||||
LT, LB, Select. Both hands activate in SteamVR and their laser shows on the dashboard; guide, Start and
|
||||
A presses show up in the ring the driver reads.
|
||||
- **Layers**: only the first layer of each frame is drawn. SteamVR's compositor composites the
|
||||
dashboard into it, so this has not mattered yet.
|
||||
- **Timing**: no reprojection, and the presenter blits whatever was submitted last, a guard delay
|
||||
after it arrived. The chain is SteamVR → presenter → DroidDeck compositor → lens pass.
|
||||
- **Cross-process GPU sync** is a poll away from exact (see the semaphore note above); binary
|
||||
semaphores are not bridged.
|
||||
- **Apps and games**: Windows VR games run through Proton ARM64 (FEX for the x86-64 game, DXVK, and
|
||||
Proton's `vrclient_x64` bridging to SteamVR's ARM64 `vrclient.so`). Tested on the Thor:
|
||||
- **Thumper** (356400, its own D3D11 engine), started with its VR launch option: menus and levels
|
||||
at 60 Hz, about 7 ms CPU and 13 ms GPU a frame, 23 dropped frames in 6485;
|
||||
- **The Thrill of the Fight** (494150, Unity): loads into its gym, 60 Hz with 6.5 ms CPU and 8.5 ms
|
||||
GPU a frame;
|
||||
- **The Lab** (6.6 GB) loads, but Android's low-memory killer took the whole app while it did, next
|
||||
to Steam and SteamVR. Two VR games at once do the same, so quit one (`droiddeckctl quit <appid>`)
|
||||
before starting the next;
|
||||
- **SUPERHOT VR** stops at its EULA, which SteamVR's dashboard shows in VR;
|
||||
- **SteamVR Home** is not in the ARM64 package. Steam's own Windows SteamVR (250820) has it
|
||||
(`tools/steamvr_environments`, `steamtours.exe`), and it starts under Proton, but Proton's
|
||||
`vrclient_x64` implements only `IVROverlayView_003` and Home asks for `_002`, so it stops at
|
||||
"SteamVR initialization failed!";
|
||||
- SteamVR's ARM64 OpenXR sample, `helloxr -g Vulkan2`, reaches a focused session and submits frames
|
||||
(it was stuck before the first one until the wait fix above), but its picture shows up as torn
|
||||
tiles: next to chase. `hellovr_sdl` (OpenGL) needs GLEW, which the runtime lacks.
|
||||
|
||||
SteamVR opens its game menu over a newly started game; `vrcmd --hidedashboard` (in
|
||||
`/opt/steamvr/bin/linuxarm64`) closes it.
|
||||
- **Quest 3**: unrelated to this; on the Quest DroidDeck stays a 2D panel (`docs/quest.md`).
|
||||
|
||||
## Building and testing
|
||||
|
||||
- `tools/vr/build.sh [OUT]` builds the driver and the layer in the local cross image, or
|
||||
`--native OUT` with aarch64 compilers on PATH (CI). `tools/build_local.sh` and CI put them in the
|
||||
APK under `assets/linuxfs/usr/local/lib/droiddeck-vr`; `SessionFiles` stages them, and
|
||||
`droiddeck-steamvr`, into the rootfs.
|
||||
- Shader: `cardboard_frag.h` is generated from `cardboard.frag`
|
||||
(`glslangValidator -V --vn cardboard_frag_code -o cardboard_frag.h cardboard.frag`).
|
||||
`tools/tests/test_cardboard.py` checks it is current, and checks the push-constant packing on the
|
||||
host.
|
||||
- `CardboardTest` covers the settings, lens inset and field of view, the head-pose maths (quaternions,
|
||||
display-rotation remaps, recentring) and the SteamVR status. `test_droiddeck_agent.py` covers the
|
||||
`vr` request.
|
||||
- Logs: the compositor's `[cardboard]` lines; SteamVR's in `~/.local/share/Steam/logs`
|
||||
(`vrserver.txt`, `vrcompositor.txt`) and `/run/droiddeck/droiddeck-steamvr/vrstartup.log`. The
|
||||
driver's lines start with `droiddeck:`.
|
||||
|
||||
Lessons from bringing this up on the Thor, and how to debug a live session: `docs/development/cardboard-vr-learnings.md`.
|
||||
@@ -0,0 +1,131 @@
|
||||
# Cardboard VR and SteamVR on Turnip: what we learned
|
||||
|
||||
Written 2026-10-13, after the first stretch of Cardboard mode work on the AYN Thor (Snapdragon 8 Gen 2,
|
||||
Adreno 740, Turnip on KGSL). `docs/cardboard-vr.md` describes how the feature works. This page records
|
||||
what it took to get there: the traps, why each fix looks the way it does, how to debug a live session,
|
||||
and what is still open. Read it before the next round of VR work.
|
||||
|
||||
## Where it stands
|
||||
|
||||
| What | Result |
|
||||
| --- | --- |
|
||||
| Cardboard mode (lens pass, 3DoF head tracking, recentre) | Works on any picture; picture follows SteamVR on and off |
|
||||
| SteamVR 2.17.10 ARM64 (the Steam Frame's `deckard-steamvr`) | Starts from the drawer; driver-direct at 60 Hz, dashboard and Steam library in VR |
|
||||
| Thumper (356400, D3D11, VR launch option) | Menus and levels at 60 Hz, 7 ms CPU / 13 ms GPU, 23 of 6485 frames dropped |
|
||||
| The Thrill of the Fight (494150, Unity) | Gym loads, 60 Hz, 6.5 ms CPU / 8.5 ms GPU |
|
||||
| The Lab (450390) | Loads, then Android's low-memory killer takes the whole app |
|
||||
| SUPERHOT VR (617830) | Reaches its EULA in the dashboard (not accepted in testing) |
|
||||
| SteamVR Home | Blocked: Proton's `vrclient_x64` lacks `IVROverlayView_002` |
|
||||
| `helloxr -g Vulkan2` (OpenXR) | Session focused and submitting, picture shows as torn tiles |
|
||||
|
||||
Screenshots from the Thor: [Thumper gameplay](evidence/cardboard-thumper-vr-gameplay-2026-10-13.png),
|
||||
[Thumper title](evidence/cardboard-thumper-vr-cardboard-2026-10-13.png),
|
||||
[The Thrill of the Fight](evidence/cardboard-thrill-of-the-fight-cardboard-2026-10-13.png),
|
||||
[the SteamVR dashboard with a game's EULA](evidence/cardboard-steamvr-dashboard-2026-10-13.png).
|
||||
|
||||
Games run as x86-64 Windows builds through Proton ARM64 (FEX, DXVK). Proton's `vrclient_x64` forwards
|
||||
OpenVR to SteamVR's ARM64 `vrclient.so`, so no x86 SteamVR is involved.
|
||||
|
||||
## Turnip on KGSL: the four things SteamVR trips over
|
||||
|
||||
1. **`VK_KHR_display` makes the GPU disappear.** Turnip on KGSL enumerates no physical device when an
|
||||
instance enables it ("I can't KHR_display"). `vrcompositor` always asks for it. The layer takes the
|
||||
display extensions off the instance and fakes one display, mode and plane backed by a headless
|
||||
surface. Headless surfaces report a `UINT32_MAX` extent, so the swapchain is sized from the mode.
|
||||
2. **No exportable semaphores.** SteamVR shares a timeline semaphore with every shared image as an
|
||||
opaque fd, and Turnip/KGSL cannot export one. The layer creates the semaphore unshared and hands out
|
||||
a memfd (`droiddeck-shared-sem`) holding a 64-bit counter. A poller thread in each process carries
|
||||
values both ways every 300 µs. Dropping the semaphores outright, the first attempt, gave torn
|
||||
dashboard tiles.
|
||||
3. **Wait-before-signal blocks the submitting thread.** Turnip does not defer a submit that waits on
|
||||
a timeline value nobody has signalled yet; `vkQueueSubmit` sleeps until it is. SteamVR's client
|
||||
waits on a compositor value that the compositor signals only after the client has submitted and
|
||||
said so, so every client deadlocked before its first frame:
|
||||
- `helloxr` blocked in a wait-idle in `vrclient.so`;
|
||||
- DXVK's `dxvk-queue` thread blocked in Proton games.
|
||||
|
||||
The layer now gives a submit's wait on an imported shared value 3 ms, then drops it. It is kept
|
||||
when the value is already reached, or when this process has queued the signal itself. Two details
|
||||
mattered:
|
||||
- the waits are judged before the submit's own signals count, because an acquire waits on one
|
||||
value and signals the next on the same semaphore;
|
||||
- SteamVR's client interop device is Vulkan 1.0, so only the `KHR` entry points resolve there.
|
||||
4. **UBWC layouts must agree.** An imported image has to be created with the same
|
||||
`VkImageFormatListCreateInfo` (sRGB + UNORM) as its creator, or Turnip lays out the compression
|
||||
differently and the reader sees garbage. The presenter's eye-texture import does this.
|
||||
|
||||
## Other traps, in the order they cost time
|
||||
|
||||
- **A still headset goes to standby.** A phone on a table looks unworn, SteamVR enters standby after
|
||||
about 15 s, and the compositor stops submitting. The driver's proximity sensor reads "worn" while
|
||||
Cardboard is on.
|
||||
- **Emulated SysV semaphores never set `sem_otime`.** SteamVR's web helper waits for it to become
|
||||
non-zero before using a semaphore set, so the dashboard never appeared. `sysv.c` now stamps
|
||||
`sem_otime` and `sem_ctime`.
|
||||
- **Steam's web helper needs the layer too.** It shares Steam's in-VR overlays with SteamVR and crashed
|
||||
without the layer; after a few crashes Steam quits. Its GPU process outlives SteamVR runs, so
|
||||
`steamwebhelper` gets the semaphore bridge whenever SteamVR is installed, not only while SteamVR's
|
||||
`active` marker exists. It never gets the display stand-in.
|
||||
- **Keep the layer out of ordinary sessions.** As an implicit layer it loads everywhere. Display
|
||||
extensions are only taken off while SteamVR runs, a new session clears a leftover `active` marker,
|
||||
and without SteamVR installed every process gets the driver's functions unchanged. Review feedback
|
||||
on the first version pointed out that gamescope asking for a display extension would have been
|
||||
rewritten in an ordinary session.
|
||||
- **The `active` marker race.** Clearing a stale marker whenever `vrserver` is not running also
|
||||
cleared it during startup, before `vrserver` appeared, because the app polls status every 3 s. Steam
|
||||
quit as a result. Only a marker older than 2 minutes is cleared now.
|
||||
- **Signal handlers in Proton games.** The layer's crash tracer replaced the `SIGSEGV` handler that FEX
|
||||
and Wine rely on, and The Lab crashed in FEX's JIT. It now installs only where nothing handles the
|
||||
signal.
|
||||
- **mangoapp owns gamescope's single external overlay slot**, so an X11 presenter has to use
|
||||
`STEAM_OVERLAY`. The default presenter is now a Wayland window on DroidDeck's own compositor, kept
|
||||
on top by app id.
|
||||
- **Memory.** Steam, SteamVR and one VR game fit in the Thor's 12 GB. A large game such as The Lab, or
|
||||
two games at once, push the device into critical pressure, and the low-memory killer takes
|
||||
DroidDeck itself (`ended-without-teardown.txt` in the session logs, `lowmemorykiller` in logcat).
|
||||
- **Head-tracking axes.** With the display at `ROTATION_90`, screen x is minus device y and screen y is
|
||||
device x. Getting this wrong made a turn at the hips tilt the view. Recentring now keeps the world
|
||||
vertical and resets the heading only.
|
||||
|
||||
## Debugging a live session
|
||||
|
||||
- **Logs:** `~/.local/share/Steam/logs/{vrserver,vrcompositor,xrclient_*}.txt` and
|
||||
`/run/droiddeck/droiddeck-steamvr/vrstartup.log`. Lines from the driver start with `droiddeck:`,
|
||||
lines from the layer with `[droiddeck-vr-layer]`. A game's layer messages land in the session log.
|
||||
- **Markers beside `active`** in `/run/droiddeck/droiddeck-steamvr/`:
|
||||
- `crashtrace` prints backtraces on fatal signals;
|
||||
- `semtrace` logs each bridged semaphore's local and shared value every 2 s, named by the memfd
|
||||
inode so the same semaphore can be matched across processes, plus the first waits, signals and
|
||||
shared image create infos.
|
||||
|
||||
Both are read when a process starts.
|
||||
- **Frame stats:** in `/opt/steamvr/bin/linuxarm64`, `LD_LIBRARY_PATH=. ./vrcmd --stats` reports
|
||||
submits, drops and app CPU/GPU times. `./vrcmd --hidedashboard` closes the menu SteamVR opens over a
|
||||
new game.
|
||||
- **Where a process is stuck:** a stack scan of `/proc/<tid>/mem` from the saved stack pointer (a small
|
||||
Python helper) gives module+offset frames. That is how the wait-idle in `vrclient.so` and the
|
||||
blocked `dxvk-queue` thread were found.
|
||||
- **VR launch options:** `SteamClient.Apps.GetLaunchOptionsForApp(id)` lists them, and
|
||||
`SteamClient.Apps.RunGame("<id>", "", <index>, 100)` starts one, through `droiddeckctl cdp eval`.
|
||||
- **Quitting:** `droiddeckctl quit <appid>`. Without the id the game keeps running.
|
||||
- **Pitfalls when testing:**
|
||||
- never `pkill -f` or `pgrep -f` a pattern inside a guest command, because it matches the
|
||||
command's own shell; use `pgrep -x`;
|
||||
- replace a loaded `.so` by copying to a temporary name and `mv`, never `cp` over it;
|
||||
- a session start restages the driver and layer from the APK assets, so a hand-copied build is
|
||||
lost on the next start.
|
||||
|
||||
## Open items
|
||||
|
||||
- **`helloxr` picture.** Both sides create the swapchain images with identical parameters, so this is
|
||||
not the UBWC import issue. Reading an image mid-render (the dropped wait) or binning tiles is the
|
||||
next suspicion.
|
||||
- **SteamVR Home** needs `IVROverlayView_002` in Proton's `vrclient`, or an ARM64 build of Home.
|
||||
- **The Lab and other large games** need memory headroom. Candidates: stop Steam's own web helpers
|
||||
while a VR game runs, or lower SteamVR's footprint.
|
||||
- **Wait drops are a heuristic.** A 3 ms grace keeps the common case in sync. A submit thread in the
|
||||
layer, deferring submits until their waits are reachable, would be exact.
|
||||
- **Layers:** only the first layer of each frame is presented. No reprojection.
|
||||
- **Controllers** are a gaze pointer driven by the pad. Pad presses did not close the SteamVR menu in
|
||||
testing. Untested: whether that came from gamescope focus being on Steam, or from the system button
|
||||
mapping.
|
||||
@@ -0,0 +1,29 @@
|
||||
# Discord build channels
|
||||
|
||||
Use the same names as the app's Updates page:
|
||||
|
||||
| App | Discord | Builds | Existing webhook secret |
|
||||
| --- | --- | --- | --- |
|
||||
| Preview | [#preview-builds](https://discord.com/channels/1552707793247539220/1554202932965015583) | Signed builds of `main`, including merged fixes | `DISCORD_BUILDS_WEBHOOK` |
|
||||
| Test builds | [#test-builds](https://discord.com/channels/1552707793247539220/1557605185365217340) | Signed builds of individual open pull requests | `DISCORD_PR_BUILDS_WEBHOOK` |
|
||||
|
||||
Stable contains tested releases published from version tags. Preview contains the newest
|
||||
merged fixes before Stable; Test builds let users try an unmerged fix by its PR number.
|
||||
|
||||
## Renaming safely
|
||||
|
||||
Rename the existing Discord channels in place. Keep their IDs, permissions, and webhooks.
|
||||
The webhook URLs used by `build.yml`, `pr-release-publish.yml`, and `pr-release-cleanup.yml`
|
||||
route by ID, so changing a channel's name or topic needs no secret rotation or routing change.
|
||||
Keep the existing GitHub secret names even though they use the old channel terminology.
|
||||
|
||||
PR publication saves `webhook_id` and `message_id` in the signed build report comment.
|
||||
Republishing edits that message; closing or merging the PR retires it. Neither operation
|
||||
looks up a Discord channel by name. Keep the existing webhook so those saved references
|
||||
continue to work. Recreating a channel or webhook is a different operation and needs a
|
||||
separate migration.
|
||||
|
||||
For future renames, check the channel and webhook IDs before and after, verify that the
|
||||
existing webhook token can still read an earlier build message, and inspect the next
|
||||
publish/update/retirement runs. Separately hosted bots may have their own configuration;
|
||||
this repository only controls the GitHub Actions build announcements.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 251 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 256 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 644 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 614 KiB |
@@ -8,3 +8,6 @@ android.nonTransitiveRClass=true
|
||||
# The NDK the compositor is built with. CI passes the one the runner has installed
|
||||
# (-PndkVersion=…); this is the fallback for a local build.
|
||||
ndkVersion=27.3.13750724
|
||||
|
||||
# Enabled parallel sync for Gradle 9.4+
|
||||
org.gradle.tooling.parallel=true
|
||||
@@ -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)
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -45,5 +45,13 @@ library list, before anything is published.
|
||||
`GAMESCOPE_FOCUSABLE_WINDOWS`, so the client kept its loading screen over the running game
|
||||
(Skyrim SE, A Plague Tale: Innocence, on the games' own Xwayland). MapNotify now refreshes the flag.
|
||||
|
||||
- `0115-vblank-timer-once-per-refresh.patch` - this app: host presentation feedback can re-arm
|
||||
the nested vblank timer after it already woke for a refresh. As the draw offset decays, the
|
||||
same refresh's new wakeup can be ahead of the current time, so it fires twice and advances the
|
||||
FPS limiter's counter twice. A 30 FPS FIFO game then reaches the host 1 or 3 refreshes apart
|
||||
instead of 2, particularly with MangoHud redrawing between game frames. Remember the last
|
||||
timerfd refresh dispatched and schedule beyond it, allowing small host-clock corrections.
|
||||
This does not change the frame-sync/nudge path or add compositor buffering.
|
||||
|
||||
Sixteen more of Armada's patches are DRM/lease/HDR-on-KMS work for a native display, which this
|
||||
app's Wayland-hosted gamescope never reaches, or need a newer gamescope than the runtime has.
|
||||
@@ -0,0 +1,36 @@
|
||||
--- a/src/vblankmanager.cpp
|
||||
+++ b/src/vblankmanager.cpp
|
||||
@@ -89,7 +89,12 @@
|
||||
|
||||
uint64_t ulTargetPoint = GetLastVBlank() + ulIntervalNSecs - ulOffset;
|
||||
|
||||
- while ( ulTargetPoint < ulNow )
|
||||
+ // Host feedback can re-arm us after we already woke for this refresh.
|
||||
+ // A decaying draw offset then puts the same refresh's wakeup ahead of
|
||||
+ // now again. Do not count it twice; allow small host-clock corrections.
|
||||
+ const uint64_t ulLastTimerVBlank = m_ulLastTimerVBlank.load();
|
||||
+ while ( ulTargetPoint < ulNow ||
|
||||
+ ulTargetPoint + ulOffset < ulLastTimerVBlank + ulIntervalNSecs / 2 )
|
||||
ulTargetPoint += ulIntervalNSecs;
|
||||
|
||||
return ulTargetPoint;
|
||||
@@ -299,6 +304,8 @@
|
||||
return;
|
||||
|
||||
|
||||
+ m_ulLastTimerVBlank = m_TimerFDSchedule.ulTargetVBlank;
|
||||
+
|
||||
m_PendingVBlank = VBlankTime
|
||||
{
|
||||
.schedule = m_TimerFDSchedule,
|
||||
--- a/src/vblankmanager.hpp
|
||||
+++ b/src/vblankmanager.hpp
|
||||
@@ -69,6 +69,8 @@
|
||||
|
||||
uint64_t m_ulTargetVBlank = 0;
|
||||
std::atomic<uint64_t> m_ulLastVBlank = { 0 };
|
||||
+ // Last timerfd refresh dispatched; the frame-sync/nudge path is unchanged.
|
||||
+ std::atomic<uint64_t> m_ulLastTimerVBlank = { 0 };
|
||||
std::atomic<bool> m_bArmed = { false };
|
||||
std::atomic<bool> m_bRunning = { true };
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
--- a/src/Backends/WaylandBackend.cpp
|
||||
+++ b/src/Backends/WaylandBackend.cpp
|
||||
@@ -1183,7 +1183,12 @@
|
||||
wl_display_flush( m_pBackend->GetDisplay() );
|
||||
|
||||
GetVBlankTimer().UpdateWasCompositing( bNeedsFullComposite );
|
||||
- GetVBlankTimer().UpdateLastDrawTime( get_time_in_nanos() - g_SteamCompMgrVBlankTime.ulWakeupTime );
|
||||
+ // Direct planes still need time for the host compositor to dispatch and draw.
|
||||
+ // Measuring only our submission lets the offset decay towards the host's
|
||||
+ // latch deadline, so small dispatch delays make a capped frame miss a refresh.
|
||||
+ GetVBlankTimer().UpdateLastDrawTime( std::max<uint64_t>(
|
||||
+ get_time_in_nanos() - g_SteamCompMgrVBlankTime.ulWakeupTime,
|
||||
+ CVBlankTimer::kDefaultVBlankDrawTimeMinCompositing ) );
|
||||
|
||||
m_pBackend->PollState();
|
||||
|
||||
@@ -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
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -103,10 +103,11 @@ def description_excerpt(body):
|
||||
|
||||
def build_content(repo, number, title, sha, apk, release, description=None):
|
||||
excerpt = description_excerpt(description)
|
||||
return (f"**Signed PR test build** `pr-{number}` · `{sha[:7]}`\n"
|
||||
return (f"**Signed test build** `pr-{number}` · `{sha[:7]}`\n"
|
||||
f"[#{number}](https://github.com/{repo}/pull/{number}): {plain_title(title)}\n"
|
||||
+ (f"\n{excerpt}\n\n" if excerpt else "") +
|
||||
"_Not merged — for testing._\n"
|
||||
f"In the app: **Updates → Test builds → #{number}**\n"
|
||||
f"Download: [standard APK](<{apk}>) · [all variants](<{release}>)")
|
||||
|
||||
|
||||
@@ -116,7 +117,7 @@ def retired_content(content, merged):
|
||||
content = "\n".join(line[2:-2] if line.startswith("~~") and line.endswith("~~") else line
|
||||
for line in content.splitlines()[2:])
|
||||
struck = "\n".join(f"~~{line}~~" if line else "" for line in content.splitlines())
|
||||
return f"**{label}** — this PR test build is no longer available.\n\n{struck}"
|
||||
return f"**{label}** — this test build is no longer available.\n\n{struck}"
|
||||
|
||||
|
||||
def sync(mode, repo, number, discord, sha="", apk="", release=""):
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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"])
|
||||
|
||||
@@ -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()
|
||||
Executable
+72
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
@@ -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
@@ -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, ®Listener, 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
|
||||
@@ -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
@@ -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
@@ -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
@@ -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
|
||||
+6807
File diff suppressed because it is too large.
Load diff
+42
@@ -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
@@ -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
@@ -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
|
||||
Reference in new issue
Block a user