Add OpenXR bring-up: render the game as a floating quad in an immersive Quest session
build / build (push) Successful in 2m12s

- New android/app/src/main/cpp/xr_session.c (+.h): owns the OpenXR
  instance/session/local-space/swapchain and the per-frame
  xrWaitFrame/xrBeginFrame/xrEndFrame loop, submitting the game's
  existing flat render as a single head-tracked XrCompositionLayerQuad.
  No stereo rendering or controller input yet - that's steps B/C/D of
  the plan.
- 11-android-openxr-cmake.patch: links the OpenXR loader as a build
  dependency, staged into jniLibs the same way as gl4es/SDL2.
  build-image/Dockerfile and prepare-android-project.sh build and stage
  it.
- 12-android-openxr-present.patch: redirects OpenGL.cc's final present
  step (opengl_swap_and_restore / SDLDraw's software path) into the XR
  swapchain FBO instead of the window, on Android only. Two real gl4es
  bugs had to be worked around to get pixels on screen at all:
    - gl4es's own glBindFramebuffer errors on an FBO id it didn't create
      itself, even though the real driver-level bind succeeds - fixed by
      creating the swapchain FBO container via gl4es's own
      glGenFramebuffers/glBindFramebuffer, and only using the real
      (dlsym'd) driver call for attaching OpenXR's foreign swapchain
      texture, which gl4es's own attach can't handle.
    - gl4es's glBegin/glVertexAttrib/glVertex3f immediate-mode emulation
      only captures a fresh per-vertex value for attribute 0 (position,
      driven directly by glVertex3f) - custom attributes like this
      shader's texcoords/light are GLES2's *constant*-attribute API and
      applied once for the whole draw, not per vertex, silently
      collapsing the UI-overlay quad to a single sampled texel. Fixed by
      switching that one draw call to real vertex arrays
      (glVertexAttribPointer/glDrawArrays).
  Also flips the V texcoord to match SDL's top-down row order against
  GL's texture convention, and reuses a persistent texture object
  instead of a fresh gen/upload/delete every frame.
- AndroidManifest.xml: declares the immersive-HMD intent category and
  focus-aware metadata, drops the 2D-panel layout hint.
- README: documents the new OpenXR immersive mode.
This commit is contained in:
ml
2026-07-25 07:25:27 +02:00
parent 0f59898bb6
commit 2300d081c3
13 changed files with 886 additions and 24 deletions
+9 -1
View File
@@ -115,15 +115,23 @@ android {
// build-image/Dockerfile's ANDROID_16KB_LDFLAGS, which does
// the same for the prebuilt SDL2/SDL2_mixer/fluidsynth-lite/
// gl4es .so's this links against.
// ANDROID_EXTRA_SOURCES is a semicolon-separated CMake list,
// not shell-split - AGP passes each "arguments" string
// straight through as one argv element to cmake, so the
// ';' below survives intact. ANDROID_EXTRA_INCLUDE_DIRS lets
// engine/'s own OpenGL.cc find "xr_session.h" (see
// android/engine-patches/11-android-openxr-cmake.patch,
// which adds it to include_directories()).
arguments "-DENABLE_SDL2=ON", "-DENABLE_SOUND=BUNDLED", "-DENABLE_FLUIDSYNTH=BUNDLED", \
"-DANDROID_PREBUILT_DIR=${prebuiltDir}", \
"-DANDROID_EXTRA_INCLUDE_DIRS=${projectDir}/src/main/cpp", \
"-DCMAKE_PREFIX_PATH=${prebuiltDir}/sdl2", \
"-DCMAKE_FIND_ROOT_PATH=${prebuiltDir}/sdl2", \
"-DCMAKE_FIND_ROOT_PATH_MODE_PACKAGE=BOTH", \
"-DCMAKE_FIND_ROOT_PATH_MODE_LIBRARY=BOTH", \
"-DCMAKE_FIND_ROOT_PATH_MODE_INCLUDE=BOTH", \
"-DCMAKE_SHARED_LINKER_FLAGS=-Wl,-z,max-page-size=16384", \
"-DANDROID_EXTRA_SOURCES=${projectDir}/src/main/cpp/questshock_native.c"
"-DANDROID_EXTRA_SOURCES=${projectDir}/src/main/cpp/questshock_native.c;${projectDir}/src/main/cpp/xr_session.c"
abiFilters 'arm64-v8a'
}
}
+19 -13
View File
@@ -12,6 +12,11 @@
<!-- External mouse input events -->
<uses-feature android:name="android.hardware.type.pc" android:required="false" />
<!-- Immersive OpenXR app now (see android/app/src/main/cpp/xr_session.c),
not a 2D Home panel - vr.headtracking is what actually declares that
to Horizon OS. -->
<uses-feature android:name="android.hardware.vr.headtracking" android:version="1" android:required="true" />
<!-- Plain, unrestricted /sdcard access for the res/data,res/sound the
user drops in and the shaders/soundfont this app extracts there on
first run - see res/GET_ASSETS_QUEST.txt and QuestShockActivity.
@@ -28,6 +33,11 @@
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
android:hardwareAccelerated="true" >
<!-- Tells Horizon OS this activity wants the compositor for itself
(immersive VR), not the Home 2D-panel path - required for an
OpenXR session to actually start. -->
<meta-data android:name="com.oculus.vr.focusaware" android:value="true" />
<activity android:name="de.ladkau.questshock.QuestShockActivity"
android:label="@string/app_name"
android:alwaysRetainTaskState="true"
@@ -40,23 +50,19 @@
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<!-- The vendor-neutral, Khronos-defined way to declare an
immersive OpenXR entry point (vs. e.g. Meta's own
com.oculus.intent.category.VR) - see this project's
"favor OpenXR" rule in the README. If Horizon OS still
launches this as a flat panel on-device, the next thing
to try is adding a com.oculus.supportedDevices meta-data
listing the target Quest models - not confirmed
necessary from static analysis alone. -->
<category android:name="org.khronos.openxr.intent.category.IMMERSIVE_HMD" />
</intent-filter>
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
<!-- Without this, Quest's Home shell picks its own default 2D
panel shape for this activity - a tall portrait rectangle,
which crops a 4:3 landscape game like System Shock's classic
640x480 down to a sliver. defaultWidth/defaultHeight (the
standard Android multi-window sizing hint, which Quest's
panel system honors for 2D apps) requests a properly
landscape, 4:3-ish panel instead; minWidth/minHeight keep it
from being resized below the game's native resolution. -->
<layout android:defaultWidth="1280dp"
android:defaultHeight="960dp"
android:minWidth="640dp"
android:minHeight="480dp"
android:gravity="center" />
</activity>
</application>
+456
View File
@@ -0,0 +1,456 @@
#include "xr_session.h"
#include <dlfcn.h>
#include <stdlib.h>
#include <string.h>
#include <android/log.h>
#include <jni.h>
#include <EGL/egl.h>
#include <GLES3/gl3.h>
#define XR_USE_PLATFORM_ANDROID 1
#define XR_USE_GRAPHICS_API_OPENGL_ES 1
#include <openxr/openxr.h>
#include <openxr/openxr_platform.h>
#include <SDL.h>
#define TAG "QuestShock"
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
// Fixed pose/size for the single game quad - 2m in front of the local space
// origin, sized to preserve the game's own aspect ratio at a comfortable
// visual angle. No per-eye view/projection work is needed for a quad layer
// at all - the compositor handles reprojecting it per eye itself, which is
// exactly why this milestone doesn't need xrLocateViews or any stereo
// rendering (see the plan's step A notes).
#define QUAD_DISTANCE_METERS 2.0f
#define QUAD_WIDTH_METERS 1.6f
// Up to this many swapchain images/FBOs - real runtimes report small counts
// (2-4); this is just a fixed upper bound for the cache arrays below.
#define MAX_SWAPCHAIN_IMAGES 8
static XrInstance g_instance = XR_NULL_HANDLE;
static XrSystemId g_system_id = XR_NULL_SYSTEM_ID;
static XrSession g_session = XR_NULL_HANDLE;
static XrSpace g_local_space = XR_NULL_HANDLE;
static XrSessionState g_session_state = XR_SESSION_STATE_UNKNOWN;
// Distinct from g_session_state - true from a successful xrBeginSession
// until xrEndSession/loss/exit. Many runtimes only advance the *state*
// (e.g. READY -> SYNCHRONIZED -> VISIBLE -> FOCUSED) in response to the
// app actually calling xrWaitFrame/xrBeginFrame/xrEndFrame continuously
// after xrBeginSession - gating frame submission on already having
// reached SYNCHRONIZED+ (as this used to) is a chicken-and-egg deadlock,
// since the runtime never progresses past READY without the frame loop
// running in the first place. Frame calls just need the session to have
// begun, per the standard OpenXR sample pattern - not any particular
// later state.
static bool g_session_running = false;
static XrSwapchain g_game_swapchain = XR_NULL_HANDLE;
static int g_game_width = 0;
static int g_game_height = 0;
static GLuint g_swapchain_fbos[MAX_SWAPCHAIN_IMAGES];
static uint32_t g_swapchain_image_count = 0;
static XrTime g_predicted_display_time = 0;
static bool g_frame_should_render = false;
static bool g_have_acquired_image = false;
// This file's GL calls otherwise resolve to gl4es (the only GL symbol
// provider linked into this binary - see android/engine-patches/
// 02-android-opengl-es.patch), which is fine for anything shared with the
// engine's own gl4es-routed rendering. But the swapchain images OpenXR
// hands us are real driver texture objects gl4es never created itself,
// and gl4es's own glFramebufferTexture2D can't attach a texture it has no
// tracked metadata for. So the FBO *container* is created via gl4es's own
// glGenFramebuffers/glBindFramebuffer (so gl4es recognizes the id as its
// own and its own per-frame glBindFramebuffer succeeds), while the
// texture-attach step - the specifically foreign part - goes through the
// real driver directly, via dlsym against libGLESv2.so.
typedef void (*PFNQSFRAMEBUFFERTEXTURE2D)(GLenum, GLenum, GLenum, GLuint, GLint);
typedef GLenum (*PFNQSCHECKFRAMEBUFFERSTATUS)(GLenum);
static PFNQSFRAMEBUFFERTEXTURE2D real_glFramebufferTexture2D;
static PFNQSCHECKFRAMEBUFFERSTATUS real_glCheckFramebufferStatus;
static bool xr_load_real_gles(void) {
void *lib = dlopen("libGLESv2.so", RTLD_NOW | RTLD_LOCAL);
if (lib == NULL) {
LOGE("XR: dlopen(libGLESv2.so) failed: %s", dlerror());
return false;
}
real_glFramebufferTexture2D = (PFNQSFRAMEBUFFERTEXTURE2D)dlsym(lib, "glFramebufferTexture2D");
real_glCheckFramebufferStatus =
(PFNQSCHECKFRAMEBUFFERSTATUS)dlsym(lib, "glCheckFramebufferStatus");
return real_glFramebufferTexture2D && real_glCheckFramebufferStatus;
}
static bool xr_check(XrResult result, const char *what) {
if (XR_SUCCEEDED(result))
return true;
char resultString[XR_MAX_RESULT_STRING_SIZE] = {0};
if (g_instance != XR_NULL_HANDLE)
xrResultToString(g_instance, result, resultString);
LOGE("XR: %s failed: %s (%d)", what, resultString[0] ? resultString : "?", (int)result);
return false;
}
static PFN_xrVoidFunction xr_get_proc(const char *name) {
PFN_xrVoidFunction fn = NULL;
// xrGetInstanceProcAddr itself works with a NULL instance for the
// handful of functions (like xrInitializeLoaderKHR) that must be called
// before an instance exists.
if (!xr_check(xrGetInstanceProcAddr(g_instance, name, &fn), name))
return NULL;
return fn;
}
// The Android OpenXR loader needs the JavaVM/context before anything else -
// separate from XR_KHR_android_create_instance below, which only affects
// xrCreateInstance itself. Skipping this is a common cause of
// xrCreateInstance silently failing to find a runtime on Android.
static bool xr_initialize_android_loader(JavaVM *vm, jobject activity) {
PFN_xrInitializeLoaderKHR initializeLoader =
(PFN_xrInitializeLoaderKHR)xr_get_proc("xrInitializeLoaderKHR");
if (initializeLoader == NULL) {
LOGE("XR: xrInitializeLoaderKHR not available - no Android OpenXR loader present?");
return false;
}
XrLoaderInitInfoAndroidKHR loaderInitInfo = {XR_TYPE_LOADER_INIT_INFO_ANDROID_KHR};
loaderInitInfo.applicationVM = vm;
loaderInitInfo.applicationContext = activity;
return xr_check(initializeLoader((const XrLoaderInitInfoBaseHeaderKHR *)&loaderInitInfo),
"xrInitializeLoaderKHR");
}
// eglGetCurrentDisplay()/eglGetCurrentContext() hand us the display/context,
// but not the EGLConfig they were created with - eglQueryContext's
// EGL_CONFIG_ID plus eglChooseConfig is the standard way to recover it (the
// same trick Khronos' own hello_xr sample uses).
static EGLConfig xr_get_current_egl_config(EGLDisplay display, EGLContext context) {
EGLint configId = 0;
eglQueryContext(display, context, EGL_CONFIG_ID, &configId);
EGLint attribs[] = {EGL_CONFIG_ID, configId, EGL_NONE};
EGLConfig config = NULL;
EGLint numConfigs = 0;
eglChooseConfig(display, attribs, &config, 1, &numConfigs);
return config;
}
static bool xr_create_instance_and_session(int game_width, int game_height) {
JNIEnv *env = (JNIEnv *)SDL_AndroidGetJNIEnv();
jobject activity = (jobject)SDL_AndroidGetActivity();
if (env == NULL || activity == NULL) {
LOGE("XR: no JNIEnv/Activity from SDL - can't init OpenXR");
return false;
}
JavaVM *vm = NULL;
(*env)->GetJavaVM(env, &vm);
if (!xr_initialize_android_loader(vm, activity))
return false;
const char *extensions[] = {
XR_KHR_ANDROID_CREATE_INSTANCE_EXTENSION_NAME,
XR_KHR_OPENGL_ES_ENABLE_EXTENSION_NAME,
};
XrInstanceCreateInfoAndroidKHR androidInfo = {XR_TYPE_INSTANCE_CREATE_INFO_ANDROID_KHR};
androidInfo.applicationVM = vm;
androidInfo.applicationActivity = activity;
XrInstanceCreateInfo createInfo = {XR_TYPE_INSTANCE_CREATE_INFO};
createInfo.next = &androidInfo;
createInfo.enabledExtensionCount = sizeof(extensions) / sizeof(extensions[0]);
createInfo.enabledExtensionNames = extensions;
strncpy(createInfo.applicationInfo.applicationName, "QuestShock",
XR_MAX_APPLICATION_NAME_SIZE - 1);
strncpy(createInfo.applicationInfo.engineName, "Shockolate", XR_MAX_ENGINE_NAME_SIZE - 1);
createInfo.applicationInfo.applicationVersion = 1;
createInfo.applicationInfo.engineVersion = 1;
createInfo.applicationInfo.apiVersion = XR_CURRENT_API_VERSION;
if (!xr_check(xrCreateInstance(&createInfo, &g_instance), "xrCreateInstance"))
return false;
XrSystemGetInfo systemInfo = {XR_TYPE_SYSTEM_GET_INFO};
systemInfo.formFactor = XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY;
if (!xr_check(xrGetSystem(g_instance, &systemInfo, &g_system_id), "xrGetSystem"))
return false;
// Required by spec before creating an OpenGL ES-backed session, even
// though we don't gate on the returned min/max API version here.
PFN_xrGetOpenGLESGraphicsRequirementsKHR getGLESRequirements =
(PFN_xrGetOpenGLESGraphicsRequirementsKHR)xr_get_proc("xrGetOpenGLESGraphicsRequirementsKHR");
if (getGLESRequirements == NULL)
return false;
XrGraphicsRequirementsOpenGLESKHR glesRequirements = {XR_TYPE_GRAPHICS_REQUIREMENTS_OPENGL_ES_KHR};
if (!xr_check(getGLESRequirements(g_instance, g_system_id, &glesRequirements),
"xrGetOpenGLESGraphicsRequirementsKHR"))
return false;
EGLDisplay display = eglGetCurrentDisplay();
EGLContext context = eglGetCurrentContext();
if (display == EGL_NO_DISPLAY || context == EGL_NO_CONTEXT) {
LOGE("XR: no current EGL display/context - call xr_init() after init_opengl()");
return false;
}
XrGraphicsBindingOpenGLESAndroidKHR graphicsBinding = {
XR_TYPE_GRAPHICS_BINDING_OPENGL_ES_ANDROID_KHR};
graphicsBinding.display = display;
graphicsBinding.config = xr_get_current_egl_config(display, context);
graphicsBinding.context = context;
XrSessionCreateInfo sessionInfo = {XR_TYPE_SESSION_CREATE_INFO};
sessionInfo.next = &graphicsBinding;
sessionInfo.systemId = g_system_id;
if (!xr_check(xrCreateSession(g_instance, &sessionInfo, &g_session), "xrCreateSession"))
return false;
XrReferenceSpaceCreateInfo spaceInfo = {XR_TYPE_REFERENCE_SPACE_CREATE_INFO};
spaceInfo.referenceSpaceType = XR_REFERENCE_SPACE_TYPE_LOCAL;
spaceInfo.poseInReferenceSpace.orientation.w = 1.0f;
if (!xr_check(xrCreateReferenceSpace(g_session, &spaceInfo, &g_local_space),
"xrCreateReferenceSpace"))
return false;
// Prefer a plain linear 8-bit format over GL_SRGB8_ALPHA8: the source
// SDL surface pixels are already sRGB-encoded (as ordinary 8-bit image
// data conventionally is) and get uploaded/sampled as plain linear
// GL_RGBA with no decode step anywhere in this path, matching the
// desktop SDL_RenderCopy path this replaces - an sRGB swapchain format
// would auto-gamma-encode on write and double-encode already-encoded
// data.
uint32_t formatCount = 0;
xrEnumerateSwapchainFormats(g_session, 0, &formatCount, NULL);
int64_t *formats = (int64_t *)malloc(sizeof(int64_t) * formatCount);
xrEnumerateSwapchainFormats(g_session, formatCount, &formatCount, formats);
int64_t chosenFormat = formats[0];
for (uint32_t i = 0; i < formatCount; i++) {
LOGI("XR: swapchain format[%u] = 0x%llx", i, (unsigned long long)formats[i]);
if (formats[i] == GL_RGBA8) {
chosenFormat = GL_RGBA8;
break;
}
}
free(formats);
XrSwapchainCreateInfo swapchainInfo = {XR_TYPE_SWAPCHAIN_CREATE_INFO};
swapchainInfo.usageFlags = XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_SAMPLED_BIT;
swapchainInfo.format = chosenFormat;
swapchainInfo.sampleCount = 1;
swapchainInfo.width = (uint32_t)game_width;
swapchainInfo.height = (uint32_t)game_height;
swapchainInfo.faceCount = 1;
swapchainInfo.arraySize = 1;
swapchainInfo.mipCount = 1;
if (!xr_check(xrCreateSwapchain(g_session, &swapchainInfo, &g_game_swapchain),
"xrCreateSwapchain"))
return false;
g_game_width = game_width;
g_game_height = game_height;
uint32_t imageCount = 0;
xrEnumerateSwapchainImages(g_game_swapchain, 0, &imageCount, NULL);
if (imageCount > MAX_SWAPCHAIN_IMAGES) {
LOGE("XR: swapchain reports %u images, only room for %d", imageCount,
MAX_SWAPCHAIN_IMAGES);
return false;
}
// Zero-initialized, not just `.type` set per element - these structs
// also carry a `next` field the runtime may read, and an
// uninitialized stack array would leave it as garbage.
XrSwapchainImageOpenGLESKHR images[MAX_SWAPCHAIN_IMAGES] = {0};
for (uint32_t i = 0; i < imageCount; i++)
images[i].type = XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_ES_KHR;
if (!xr_check(xrEnumerateSwapchainImages(g_game_swapchain, imageCount, &imageCount,
(XrSwapchainImageBaseHeader *)images),
"xrEnumerateSwapchainImages"))
return false;
g_swapchain_image_count = imageCount;
if (!xr_load_real_gles()) {
LOGE("XR: couldn't resolve real GLES FBO functions via dlsym");
return false;
}
// Wraps each swapchain-provided texture in its own framebuffer, matching
// how OpenGL.cc's own CreateFrameBuffer() wraps backupBuffer - just
// without a depth/stencil attachment, since the final composite draw
// (see opengl_swap_and_restore) never needs one. The Gen/Bind calls are
// gl4es's own (linked, not dlsym'd) - see the comment above
// real_glFramebufferTexture2D for why.
bool all_complete = true;
for (uint32_t i = 0; i < imageCount; i++) {
glGenFramebuffers(1, &g_swapchain_fbos[i]);
glBindFramebuffer(GL_FRAMEBUFFER, g_swapchain_fbos[i]);
real_glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
images[i].image, 0);
GLenum status = real_glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE) {
LOGE("XR: swapchain FBO %u incomplete: 0x%x", i, status);
all_complete = false;
}
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
if (!all_complete)
return false;
LOGI("XR: instance/session/swapchain ready (%dx%d, %u images)", game_width, game_height,
imageCount);
return true;
}
bool xr_init(int game_width, int game_height) {
if (!xr_create_instance_and_session(game_width, game_height)) {
LOGE("XR: bring-up failed - falling back to the normal window present path");
xr_shutdown();
return false;
}
return true;
}
void xr_poll_events(void) {
if (g_instance == XR_NULL_HANDLE)
return;
while (true) {
XrEventDataBuffer event = {XR_TYPE_EVENT_DATA_BUFFER};
XrResult result = xrPollEvent(g_instance, &event);
if (result == XR_EVENT_UNAVAILABLE)
break;
if (!xr_check(result, "xrPollEvent"))
break;
if (event.type == XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED) {
XrEventDataSessionStateChanged *stateEvent = (XrEventDataSessionStateChanged *)&event;
g_session_state = stateEvent->state;
LOGI("XR: session state -> %d", (int)g_session_state);
if (g_session_state == XR_SESSION_STATE_READY) {
XrSessionBeginInfo beginInfo = {XR_TYPE_SESSION_BEGIN_INFO};
beginInfo.primaryViewConfigurationType = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO;
g_session_running = xr_check(xrBeginSession(g_session, &beginInfo), "xrBeginSession");
} else if (g_session_state == XR_SESSION_STATE_STOPPING) {
xr_check(xrEndSession(g_session), "xrEndSession");
g_session_running = false;
} else if (g_session_state == XR_SESSION_STATE_EXITING ||
g_session_state == XR_SESSION_STATE_LOSS_PENDING) {
g_session_running = false;
}
}
}
}
bool xr_is_session_running(void) { return g_session_running; }
bool xr_frame_begin(void) {
g_have_acquired_image = false;
if (!xr_is_session_running())
return false;
XrFrameWaitInfo waitInfo = {XR_TYPE_FRAME_WAIT_INFO};
XrFrameState frameState = {XR_TYPE_FRAME_STATE};
if (!xr_check(xrWaitFrame(g_session, &waitInfo, &frameState), "xrWaitFrame"))
return false;
g_predicted_display_time = frameState.predictedDisplayTime;
g_frame_should_render = frameState.shouldRender;
XrFrameBeginInfo beginInfo = {XR_TYPE_FRAME_BEGIN_INFO};
if (!xr_check(xrBeginFrame(g_session, &beginInfo), "xrBeginFrame"))
return false;
if (!g_frame_should_render)
return false;
uint32_t imageIndex = 0;
XrSwapchainImageAcquireInfo acquireInfo = {XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO};
if (!xr_check(xrAcquireSwapchainImage(g_game_swapchain, &acquireInfo, &imageIndex),
"xrAcquireSwapchainImage"))
return false;
XrSwapchainImageWaitInfo waitImageInfo = {XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO};
waitImageInfo.timeout = XR_INFINITE_DURATION;
if (!xr_check(xrWaitSwapchainImage(g_game_swapchain, &waitImageInfo), "xrWaitSwapchainImage"))
return false;
// gl4es's own (linked, not dlsym'd) bind - this targets an FBO id
// gl4es itself created (see xr_create_instance_and_session()), so its
// own "current FBO" bookkeeping updates correctly and its immediate-
// mode draw calls in android_draw_surface_as_quad() land in the right
// place.
glBindFramebuffer(GL_FRAMEBUFFER, g_swapchain_fbos[imageIndex]);
glViewport(0, 0, g_game_width, g_game_height);
g_have_acquired_image = true;
return true;
}
void xr_frame_end(void) {
if (g_session == XR_NULL_HANDLE)
return;
if (g_have_acquired_image) {
XrSwapchainImageReleaseInfo releaseInfo = {XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO};
xr_check(xrReleaseSwapchainImage(g_game_swapchain, &releaseInfo),
"xrReleaseSwapchainImage");
}
if (!xr_is_session_running())
return;
XrCompositionLayerQuad quad = {XR_TYPE_COMPOSITION_LAYER_QUAD};
quad.space = g_local_space;
quad.eyeVisibility = XR_EYE_VISIBILITY_BOTH;
quad.subImage.swapchain = g_game_swapchain;
quad.subImage.imageRect.extent.width = g_game_width;
quad.subImage.imageRect.extent.height = g_game_height;
quad.pose.orientation.w = 1.0f;
quad.pose.position.z = -QUAD_DISTANCE_METERS;
quad.size.width = QUAD_WIDTH_METERS;
quad.size.height = QUAD_WIDTH_METERS * (float)g_game_height / (float)g_game_width;
const XrCompositionLayerBaseHeader *layers[1] = {(XrCompositionLayerBaseHeader *)&quad};
XrFrameEndInfo endInfo = {XR_TYPE_FRAME_END_INFO};
endInfo.displayTime = g_predicted_display_time;
endInfo.environmentBlendMode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE;
endInfo.layerCount = g_have_acquired_image ? 1 : 0;
endInfo.layers = g_have_acquired_image ? layers : NULL;
xr_check(xrEndFrame(g_session, &endInfo), "xrEndFrame");
}
void xr_shutdown(void) {
for (uint32_t i = 0; i < g_swapchain_image_count; i++) {
if (g_swapchain_fbos[i] != 0)
glDeleteFramebuffers(1, &g_swapchain_fbos[i]);
}
g_swapchain_image_count = 0;
if (g_game_swapchain != XR_NULL_HANDLE)
xrDestroySwapchain(g_game_swapchain);
g_game_swapchain = XR_NULL_HANDLE;
if (g_local_space != XR_NULL_HANDLE)
xrDestroySpace(g_local_space);
g_local_space = XR_NULL_HANDLE;
if (g_session != XR_NULL_HANDLE)
xrDestroySession(g_session);
g_session = XR_NULL_HANDLE;
if (g_instance != XR_NULL_HANDLE)
xrDestroyInstance(g_instance);
g_instance = XR_NULL_HANDLE;
g_session_state = XR_SESSION_STATE_UNKNOWN;
g_session_running = false;
}
+56
View File
@@ -0,0 +1,56 @@
// Minimal OpenXR bring-up for questshock's immersive Quest build. Keeps the
// game's own rendering untouched (see android/engine-patches/
// 12-android-openxr-present.patch) - this module only owns the OpenXR
// instance/session/swapchain and the final "submit a quad layer instead of
// presenting to a window" step. No stereo rendering, no controller input
// yet (see the plan's steps B/C/D for those) - the game composite is shown
// as a single flat quad floating in front of the viewer.
#ifndef QUESTSHOCK_XR_SESSION_H
#define QUESTSHOCK_XR_SESSION_H
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
// Call once, right after init_opengl() (OpenGL.cc) has created and made
// current the GL context SDL/gl4es already use - creates the OpenXR
// instance/session sharing that same EGL display/context, plus one
// swapchain sized to the game's logical resolution (game_width/height, i.e.
// grd_cap->w/h - see Shock.c's InitSDL()). Returns false if OpenXR bring-up
// failed (e.g. no runtime installed) - callers should fall back to the
// existing window-present path in that case.
bool xr_init(int game_width, int game_height);
// Pumps XR session-state events. Call once per frame, before
// xr_frame_begin(). Must still be called even when xr_init() returned
// false (no-op in that case).
void xr_poll_events(void);
// True once the session has reached a state where frames are expected
// (XR_SESSION_STATE_SYNCHRONIZED or later) - i.e. it's safe/required to
// start calling xr_frame_begin()/xr_frame_end() each frame.
bool xr_is_session_running(void);
// Begins the XR frame (xrWaitFrame/xrBeginFrame) and, if the runtime wants
// this frame rendered, acquires the next swapchain image and binds its
// framebuffer as the current render target - ready for the caller to draw
// into exactly as it would have drawn to the default framebuffer. Returns
// true if the caller should draw this frame; xr_frame_end() must be called
// unconditionally afterward either way (a begun XR frame must always be
// ended, rendered or not).
bool xr_frame_begin(void);
// Releases the swapchain image (if one was acquired this frame) and
// submits it as a single XrCompositionLayerQuad positioned in front of the
// local reference space's origin, then ends the XR frame.
void xr_frame_end(void);
void xr_shutdown(void);
#ifdef __cplusplus
}
#endif
#endif