mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 12:35:42 +00:00
feat(quest): DroidDeck's menu, agent pet and keyboards float in the immersive SteamVR view (#3596)
This commit is contained in:
1 parent
153c873898
commit
673675b45e
31 files changed
+3543
-62
No files matched your search
@@ -277,6 +277,17 @@
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
<activity
|
||||
android:name=".agent.AgentChatActivity"
|
||||
android:exported="false"
|
||||
android:launchMode="singleTask"
|
||||
android:taskAffinity="${applicationId}.agentchat"
|
||||
android:resizeableActivity="true"
|
||||
android:theme="@style/AppTheme"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density">
|
||||
<layout android:defaultWidth="720dp" android:defaultHeight="800dp" />
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".agent.AgentStartActivity"
|
||||
android:exported="true"
|
||||
|
||||
@@ -8,6 +8,6 @@ target_compile_features(droiddeckxr PRIVATE cxx_std_17)
|
||||
target_compile_definitions(droiddeckxr PRIVATE XR_USE_PLATFORM_ANDROID XR_USE_GRAPHICS_API_OPENGL_ES XR_USE_TIMESPEC)
|
||||
target_compile_options(droiddeckxr PRIVATE -Wall -Wextra -Wno-missing-field-initializers -Werror=return-type)
|
||||
target_link_options(droiddeckxr PRIVATE -Wl,-z,max-page-size=16384 -uANativeActivity_onCreate)
|
||||
target_link_libraries(droiddeckxr PRIVATE droiddeckxr_glue OpenXR::openxr_loader EGL GLESv3 android log)
|
||||
target_link_libraries(droiddeckxr PRIVATE droiddeckxr_glue OpenXR::openxr_loader EGL GLESv3 android jnigraphics log)
|
||||
|
||||
target_include_directories(droiddeckxr PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../../../../../tools/vr/src)
|
||||
@@ -1,6 +1,7 @@
|
||||
#include <jni.h>
|
||||
#include <EGL/egl.h>
|
||||
#include <GLES3/gl3.h>
|
||||
#include <android/bitmap.h>
|
||||
#include <android/log.h>
|
||||
#include <android_native_app_glue.h>
|
||||
#include <time.h>
|
||||
@@ -22,10 +23,14 @@
|
||||
#include <cerrno>
|
||||
#include <cstddef>
|
||||
#include <ctime>
|
||||
#include <pthread.h>
|
||||
#include <algorithm>
|
||||
#include "xr_tracking.h"
|
||||
#include "xr_frame_channel.h"
|
||||
#include "xr_frame_math.h"
|
||||
#include "gpu_frames.h"
|
||||
#include "xr_host.h"
|
||||
#include "xr_overlay.h"
|
||||
|
||||
static void check(XrResult result, const char *operation) {
|
||||
if (XR_FAILED(result)) throw std::runtime_error(std::string(operation) + ": " + std::to_string(result));
|
||||
@@ -37,6 +42,15 @@ struct Eye {
|
||||
std::vector<XrSwapchainImageOpenGLESKHR> images;
|
||||
};
|
||||
|
||||
struct SurfaceLayer {
|
||||
XrSwapchain swapchain = XR_NULL_HANDLE;
|
||||
jobject surface = nullptr;
|
||||
int width = 0, height = 0;
|
||||
};
|
||||
|
||||
class QuestXR;
|
||||
static QuestXR *g_runtime = nullptr;
|
||||
|
||||
class QuestXR {
|
||||
public:
|
||||
explicit QuestXR(android_app *app) : app_(app) {}
|
||||
@@ -76,21 +90,74 @@ public:
|
||||
"\"headPosition\":[%.6f,%.6f,%.6f],\"controllersActive\":[%s,%s],"
|
||||
"\"periodNs\":%lld,\"surfaceSwapchain\":%s,\"source\":\"%s\",\"guestFrames\":%lld,\"steamvrState\":%d,"
|
||||
"\"receivedFrames\":%llu,\"rejectedFrames\":%llu,\"uploadedFrames\":%llu,\"sourceFrameId\":%llu,"
|
||||
"\"gpuReceivedFrames\":%llu,\"gpuDroppedFrames\":%llu,\"gpuVerifiedFrameId\":%llu,\"gpuChecksum\":%u,\"error\":\"%s\"}\n",
|
||||
"\"gpuReceivedFrames\":%llu,\"gpuDroppedFrames\":%llu,\"gpuVerifiedFrameId\":%llu,\"gpuChecksum\":%u,"
|
||||
"\"hostVersion\":%u,\"visibleLayers\":%d,\"overlay\":%s,\"error\":\"%s\"}\n",
|
||||
(unsigned long long)frames_, (unsigned long long)rendered_, state_,
|
||||
(unsigned long long)head_.locationFlags,
|
||||
head_.pose.position.x, head_.pose.position.y, head_.pose.position.z,
|
||||
handActive_[0] ? "true" : "false", handActive_[1] ? "true" : "false",
|
||||
(long long)period_, "false", "frames",
|
||||
(long long)period_, surfaceSupported_ ? "true" : "false", "frames",
|
||||
0LL, steamvrState, (unsigned long long)(receiver_.Received() + gpuFrames_.Received()),
|
||||
(unsigned long long)(receiver_.Rejected() + gpuFrames_.Rejected()),
|
||||
(unsigned long long)uploadedFrames_, (unsigned long long)sourceHeader_.frame_id,
|
||||
(unsigned long long)gpuFrames_.Received(), (unsigned long long)gpuFrames_.Dropped(),
|
||||
(unsigned long long)verifiedFrame_, gpuChecksum_, error);
|
||||
(unsigned long long)verifiedFrame_, gpuChecksum_,
|
||||
hostBuffers_ ? DROIDDECK_XR_HOST_VERSION : 0u, visibleLayers_,
|
||||
XrOverlay::active(hostControl_) ? "true" : "false", error);
|
||||
std::fclose(file);
|
||||
std::rename(temp.c_str(), path.c_str());
|
||||
}
|
||||
|
||||
bool onXrThread() const { return pthread_equal(pthread_self(), xrThread_); }
|
||||
|
||||
int createLayer(JNIEnv *env, int width, int height) {
|
||||
if (!onXrThread() || !createSurfaceSwapchain_ || session_ == XR_NULL_HANDLE || width <= 0 || height <= 0) return -1;
|
||||
for (int index = 0; index < DROIDDECK_XR_HOST_LAYERS; index++) {
|
||||
SurfaceLayer &layer = layers_[index];
|
||||
if (layer.swapchain) continue;
|
||||
XrSwapchainCreateInfo create{XR_TYPE_SWAPCHAIN_CREATE_INFO};
|
||||
create.usageFlags = XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT;
|
||||
create.width = width; create.height = height;
|
||||
jobject surface = nullptr;
|
||||
XrResult result = createSurfaceSwapchain_(session_, &create, &layer.swapchain, &surface);
|
||||
if (XR_FAILED(result) || !surface) {
|
||||
__android_log_print(ANDROID_LOG_ERROR, "DroidDeckXR", "surface layer %dx%d failed: %d", width, height, result);
|
||||
if (layer.swapchain) xrDestroySwapchain(layer.swapchain);
|
||||
layer = {};
|
||||
return -1;
|
||||
}
|
||||
layer.surface = env->NewGlobalRef(surface);
|
||||
layer.width = width; layer.height = height;
|
||||
__android_log_print(ANDROID_LOG_INFO, "DroidDeckXR", "surface layer %d created %dx%d", index, width, height);
|
||||
return index;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
jobject layerSurface(JNIEnv *env, int index) {
|
||||
if (!onXrThread() || index < 0 || index >= DROIDDECK_XR_HOST_LAYERS || !layers_[index].surface) return nullptr;
|
||||
return env->NewLocalRef(layers_[index].surface);
|
||||
}
|
||||
|
||||
void setOrbImage(JNIEnv *env, jobject bitmap) {
|
||||
if (!onXrThread() || !bitmap) return;
|
||||
AndroidBitmapInfo info{};
|
||||
void *pixels = nullptr;
|
||||
if (AndroidBitmap_getInfo(env, bitmap, &info) != ANDROID_BITMAP_RESULT_SUCCESS
|
||||
|| info.format != ANDROID_BITMAP_FORMAT_RGBA_8888) return;
|
||||
if (AndroidBitmap_lockPixels(env, bitmap, &pixels) != ANDROID_BITMAP_RESULT_SUCCESS) return;
|
||||
overlay_.setLogo(pixels, (int)info.width, (int)info.height, (int)info.stride);
|
||||
AndroidBitmap_unlockPixels(env, bitmap);
|
||||
}
|
||||
|
||||
void destroyLayer(JNIEnv *env, int index) {
|
||||
if (!onXrThread() || index < 0 || index >= DROIDDECK_XR_HOST_LAYERS) return;
|
||||
SurfaceLayer &layer = layers_[index];
|
||||
if (layer.swapchain) xrDestroySwapchain(layer.swapchain);
|
||||
if (layer.surface) env->DeleteGlobalRef(layer.surface);
|
||||
layer = {};
|
||||
}
|
||||
|
||||
private:
|
||||
android_app *app_;
|
||||
JNIEnv *env_ = nullptr;
|
||||
@@ -104,6 +171,20 @@ private:
|
||||
XrAction primary_ = XR_NULL_HANDLE, secondary_ = XR_NULL_HANDLE, menu_ = XR_NULL_HANDLE;
|
||||
XrAction triggerTouch_ = XR_NULL_HANDLE, stickTouch_ = XR_NULL_HANDLE, primaryTouch_ = XR_NULL_HANDLE;
|
||||
XrAction secondaryTouch_ = XR_NULL_HANDLE, thumbrestTouch_ = XR_NULL_HANDLE;
|
||||
PFN_xrCreateSwapchainAndroidSurfaceKHR createSurfaceSwapchain_ = nullptr;
|
||||
bool surfaceSupported_ = false;
|
||||
bool imageLayoutSupported_ = false;
|
||||
pthread_t xrThread_{};
|
||||
SurfaceLayer layers_[DROIDDECK_XR_HOST_LAYERS];
|
||||
DroidDeckXrHostState hostState_{};
|
||||
DroidDeckXrHostControl hostControl_{};
|
||||
bool hostBuffers_ = false;
|
||||
jmethodID hostFrameCallback_ = nullptr;
|
||||
uint64_t hostPulse_[2]{};
|
||||
int visibleLayers_ = 0;
|
||||
XrOverlay overlay_;
|
||||
Eye overlayEyes_[2];
|
||||
GLuint overlayDepth_[2]{};
|
||||
DroidDeckXrHand inputs_[2]{};
|
||||
PFN_xrConvertTimeToTimespecTimeKHR convertTime_ = nullptr;
|
||||
bool timespecSupported_ = false;
|
||||
@@ -220,6 +301,8 @@ private:
|
||||
|
||||
void initialize() {
|
||||
app_->userData = this;
|
||||
xrThread_ = pthread_self();
|
||||
g_runtime = this;
|
||||
app_->onInputEvent = [](android_app *app, AInputEvent *event) -> int32_t {
|
||||
if (AInputEvent_getType(event) != AINPUT_EVENT_TYPE_KEY || AKeyEvent_getKeyCode(event) != AKEYCODE_BACK
|
||||
|| AKeyEvent_getAction(event) != AKEY_EVENT_ACTION_UP) return 0;
|
||||
@@ -244,6 +327,10 @@ private:
|
||||
frameCallback_ = env_->GetMethodID(activityClass, "onXrFrame", "(J)V");
|
||||
statusCallback_ = env_->GetMethodID(activityClass, "onXrStatus", "()I");
|
||||
if (env_->ExceptionCheck()) { env_->ExceptionClear(); throw std::runtime_error("XR activity bridge methods unavailable"); }
|
||||
hostFrameCallback_ = env_->GetMethodID(activityClass, "onXrHostFrame", "()V");
|
||||
jmethodID hostBuffersCallback = hostFrameCallback_ ?
|
||||
env_->GetMethodID(activityClass, "onXrHostBuffers", "(Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)V") : nullptr;
|
||||
if (env_->ExceptionCheck()) { env_->ExceptionClear(); hostFrameCallback_ = nullptr; hostBuffersCallback = nullptr; }
|
||||
env_->DeleteLocalRef(intentClass); env_->DeleteLocalRef(intent); env_->DeleteLocalRef(activityClass);
|
||||
PFN_xrInitializeLoaderKHR initializeLoader = nullptr;
|
||||
check(xrGetInstanceProcAddr(XR_NULL_HANDLE, "xrInitializeLoaderKHR",
|
||||
@@ -261,10 +348,21 @@ private:
|
||||
timespecSupported_ = true;
|
||||
if (!std::strcmp(extension.extensionName, XR_EXT_PERFORMANCE_SETTINGS_EXTENSION_NAME))
|
||||
performanceSupported_ = true;
|
||||
if (!std::strcmp(extension.extensionName, XR_KHR_ANDROID_SURFACE_SWAPCHAIN_EXTENSION_NAME))
|
||||
surfaceSupported_ = true;
|
||||
if (!std::strcmp(extension.extensionName, XR_FB_COMPOSITION_LAYER_IMAGE_LAYOUT_EXTENSION_NAME))
|
||||
imageLayoutSupported_ = true;
|
||||
}
|
||||
__android_log_print(ANDROID_LOG_INFO, "DroidDeckXR", "surface swapchain available=%d image layout=%d",
|
||||
surfaceSupported_, imageLayoutSupported_);
|
||||
// A surface swapchain's image arrives upside down, and a quad's back face is not drawn, so
|
||||
// panels need the layout flag to flip it.
|
||||
surfaceSupported_ = surfaceSupported_ && imageLayoutSupported_;
|
||||
std::vector<const char *> enabled{XR_KHR_ANDROID_CREATE_INSTANCE_EXTENSION_NAME, XR_KHR_OPENGL_ES_ENABLE_EXTENSION_NAME};
|
||||
if (timespecSupported_) enabled.push_back(XR_KHR_CONVERT_TIMESPEC_TIME_EXTENSION_NAME);
|
||||
if (performanceSupported_) enabled.push_back(XR_EXT_PERFORMANCE_SETTINGS_EXTENSION_NAME);
|
||||
if (surfaceSupported_) enabled.push_back(XR_KHR_ANDROID_SURFACE_SWAPCHAIN_EXTENSION_NAME);
|
||||
if (surfaceSupported_) enabled.push_back(XR_FB_COMPOSITION_LAYER_IMAGE_LAYOUT_EXTENSION_NAME);
|
||||
XrInstanceCreateInfoAndroidKHR androidInfo{XR_TYPE_INSTANCE_CREATE_INFO_ANDROID_KHR};
|
||||
androidInfo.applicationVM = app_->activity->vm;
|
||||
androidInfo.applicationActivity = app_->activity->clazz;
|
||||
@@ -281,6 +379,11 @@ private:
|
||||
reinterpret_cast<PFN_xrVoidFunction *>(&setPerformance_));
|
||||
if (XR_FAILED(result)) setPerformance_ = nullptr;
|
||||
}
|
||||
if (surfaceSupported_ && XR_FAILED(xrGetInstanceProcAddr(instance_, "xrCreateSwapchainAndroidSurfaceKHR",
|
||||
reinterpret_cast<PFN_xrVoidFunction *>(&createSurfaceSwapchain_)))) {
|
||||
createSurfaceSwapchain_ = nullptr;
|
||||
surfaceSupported_ = false;
|
||||
}
|
||||
if (timespecSupported_) check(xrGetInstanceProcAddr(instance_, "xrConvertTimeToTimespecTimeKHR",
|
||||
reinterpret_cast<PFN_xrVoidFunction *>(&convertTime_)), "time conversion entrypoint");
|
||||
XrSystemGetInfo systemInfo{XR_TYPE_SYSTEM_GET_INFO};
|
||||
@@ -334,6 +437,16 @@ private:
|
||||
bool gpu = !verifyPixels_ && gpuFrames_.Start(std::string(app_->activity->internalDataPath) + "/.wayland-rt/" DROIDDECK_XR_GPU_SOCKET, display_);
|
||||
__android_log_print(ANDROID_LOG_INFO, "DroidDeckXR", "GPU frame channel available=%d", gpu);
|
||||
}
|
||||
overlay_.initialize();
|
||||
hostState_.version = DROIDDECK_XR_HOST_VERSION;
|
||||
if (hostBuffersCallback) {
|
||||
jobject state = env_->NewDirectByteBuffer(&hostState_, sizeof(hostState_));
|
||||
jobject control = env_->NewDirectByteBuffer(&hostControl_, sizeof(hostControl_));
|
||||
env_->CallVoidMethod(app_->activity->clazz, hostBuffersCallback, state, control);
|
||||
if (env_->ExceptionCheck()) { env_->ExceptionDescribe(); env_->ExceptionClear(); hostFrameCallback_ = nullptr; }
|
||||
else hostBuffers_ = true;
|
||||
env_->DeleteLocalRef(state); env_->DeleteLocalRef(control);
|
||||
}
|
||||
health();
|
||||
}
|
||||
|
||||
@@ -422,6 +535,13 @@ private:
|
||||
target.images.resize(count, {XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_ES_KHR});
|
||||
check(xrEnumerateSwapchainImages(target.swapchain, count, &count,
|
||||
reinterpret_cast<XrSwapchainImageBaseHeader *>(target.images.data())), "images");
|
||||
Eye &overlay = overlayEyes_[eye];
|
||||
overlay.width = target.width; overlay.height = target.height;
|
||||
check(xrCreateSwapchain(session_, &create, &overlay.swapchain), "overlay swapchain");
|
||||
check(xrEnumerateSwapchainImages(overlay.swapchain, 0, &count, nullptr), "overlay image count");
|
||||
overlay.images.resize(count, {XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_ES_KHR});
|
||||
check(xrEnumerateSwapchainImages(overlay.swapchain, count, &count,
|
||||
reinterpret_cast<XrSwapchainImageBaseHeader *>(overlay.images.data())), "overlay images");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -530,6 +650,12 @@ private:
|
||||
|
||||
void initializeGraphics() {
|
||||
glGenFramebuffers(1, &framebuffer_);
|
||||
glGenRenderbuffers(2, overlayDepth_);
|
||||
for (int eye = 0; eye < 2; eye++) {
|
||||
glBindRenderbuffer(GL_RENDERBUFFER, overlayDepth_[eye]);
|
||||
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, overlayEyes_[eye].width, overlayEyes_[eye].height);
|
||||
}
|
||||
glBindRenderbuffer(GL_RENDERBUFFER, 0);
|
||||
glGenVertexArrays(1, &vertexArray_);
|
||||
GLuint vertex = shader(GL_VERTEX_SHADER,
|
||||
"#version 300 es\nout vec2 uv; uniform float eye; void main(){vec2 coordinate=vec2(float((gl_VertexID<<1)&2),float(gl_VertexID&2));uv=vec2(coordinate.x*0.5+eye*0.5,1.0-coordinate.y);gl_Position=vec4(coordinate*2.0-1.0,0.0,1.0);}");
|
||||
@@ -584,24 +710,46 @@ private:
|
||||
if (verifyPixels_ || uploadedFrames_ % 72 == 1) health();
|
||||
}
|
||||
|
||||
void render(Eye &eye, uint32_t image) {
|
||||
void render(Eye &eye, uint32_t image, bool source, const XrPosef &pose, const XrFovf &fov, float seconds) {
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_);
|
||||
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, eye.images[image].image, 0);
|
||||
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
|
||||
throw std::runtime_error("Incomplete eye framebuffer");
|
||||
{
|
||||
glViewport(0, 0, eye.width, eye.height); glDisable(GL_DEPTH_TEST);
|
||||
glViewport(0, 0, eye.width, eye.height); glDisable(GL_DEPTH_TEST);
|
||||
if (source) {
|
||||
glUseProgram(sourceProgram_); glBindVertexArray(vertexArray_);
|
||||
glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, sourceTexture_);
|
||||
glUniform1i(glGetUniformLocation(sourceProgram_, "source"), 0);
|
||||
glUniform1f(glGetUniformLocation(sourceProgram_, "eye"), &eye == &eyes_[1] ? 1.f : 0.f);
|
||||
glDrawArrays(GL_TRIANGLES, 0, 3);
|
||||
} else {
|
||||
glClearColor(0.f, 0.f, 0.f, 1.f);
|
||||
glClear(GL_COLOR_BUFFER_BIT);
|
||||
}
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, 0);
|
||||
if (glGetError() != GL_NO_ERROR) throw std::runtime_error("OpenGL render error");
|
||||
glFlush();
|
||||
}
|
||||
|
||||
// Lasers and the orb go in their own layer above the panels, which only the panels' depth hides.
|
||||
void renderOverlay(int index, uint32_t image, const XrPosef &pose, const XrFovf &fov, float seconds) {
|
||||
Eye &eye = overlayEyes_[index];
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_);
|
||||
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, eye.images[image].image, 0);
|
||||
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, overlayDepth_[index]);
|
||||
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
|
||||
throw std::runtime_error("Incomplete overlay framebuffer");
|
||||
glViewport(0, 0, eye.width, eye.height);
|
||||
glClearColor(0.f, 0.f, 0.f, 0.f); glClearDepthf(1.f);
|
||||
glDepthMask(GL_TRUE);
|
||||
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
|
||||
overlay_.draw(pose, fov, hostControl_, hostState_, seconds);
|
||||
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0);
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, 0);
|
||||
if (glGetError() != GL_NO_ERROR) throw std::runtime_error("OpenGL overlay error");
|
||||
glFlush();
|
||||
}
|
||||
|
||||
void pollEvents() {
|
||||
XrEventDataBuffer event{XR_TYPE_EVENT_DATA_BUFFER};
|
||||
XrResult result;
|
||||
@@ -685,6 +833,7 @@ private:
|
||||
XrViewState viewState{XR_TYPE_VIEW_STATE}; uint32_t count = 0;
|
||||
XrView views[2]{{XR_TYPE_VIEW}, {XR_TYPE_VIEW}};
|
||||
check(xrLocateViews(session_, &locate, &viewState, 2, &count, views), "xrLocateViews");
|
||||
hostFrame(frameState.predictedDisplayTime);
|
||||
publishTracking(views, frameState.predictedDisplayTime);
|
||||
if (guestAttached_) {
|
||||
timespec now{}; clock_gettime(CLOCK_MONOTONIC, &now);
|
||||
@@ -692,29 +841,34 @@ private:
|
||||
if (env_->ExceptionCheck()) { env_->ExceptionClear(); throw std::runtime_error("Guest frame callback failed"); }
|
||||
}
|
||||
XrCompositionLayerProjectionView projection[2]{{XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW}, {XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW}};
|
||||
bool valid = frameState.shouldRender && count == 2 &&
|
||||
const bool viewsValid = frameState.shouldRender && count == 2 &&
|
||||
(viewState.viewStateFlags & (XR_VIEW_STATE_ORIENTATION_VALID_BIT | XR_VIEW_STATE_POSITION_VALID_BIT))
|
||||
== (XR_VIEW_STATE_ORIENTATION_VALID_BIT | XR_VIEW_STATE_POSITION_VALID_BIT);
|
||||
{
|
||||
valid = valid && sourceHeader_.frame_id && xr_frame_now() - sourceHeader_.captured_ns < 500000000LL;
|
||||
if (valid) for (int eye = 0; eye < 2; eye++) {
|
||||
auto source = xr_frame_view(sourceHeader_, eye);
|
||||
views[eye].pose.orientation = {source.orientation[0], source.orientation[1], source.orientation[2], source.orientation[3]};
|
||||
views[eye].pose.position = {source.position[0], source.position[1], source.position[2]};
|
||||
views[eye].fov = {source.fov[0], source.fov[1], source.fov[2], source.fov[3]};
|
||||
}
|
||||
bool valid = viewsValid && sourceHeader_.frame_id && xr_frame_now() - sourceHeader_.captured_ns < 500000000LL;
|
||||
if (valid) for (int eye = 0; eye < 2; eye++) {
|
||||
auto source = xr_frame_view(sourceHeader_, eye);
|
||||
views[eye].pose.orientation = {source.orientation[0], source.orientation[1], source.orientation[2], source.orientation[3]};
|
||||
views[eye].pose.position = {source.position[0], source.position[1], source.position[2]};
|
||||
views[eye].fov = {source.fov[0], source.fov[1], source.fov[2], source.fov[3]};
|
||||
}
|
||||
std::vector<XrCompositionLayerQuad> quads;
|
||||
std::vector<XrCompositionLayerImageLayoutFB> layouts;
|
||||
if (viewsValid) collectQuads(quads, layouts);
|
||||
const bool uiOnly = !valid && viewsValid && !quads.empty();
|
||||
const bool draw = valid || uiOnly;
|
||||
const std::string capture = captureRequest();
|
||||
bool captured = valid;
|
||||
if (!capture.empty() && valid)
|
||||
captured = captureTexture(sourceTexture_, sourceHeader_.width, sourceHeader_.height, "source");
|
||||
if (valid) for (int eye = 0; eye < 2; eye++) {
|
||||
timespec clock{}; clock_gettime(CLOCK_MONOTONIC, &clock);
|
||||
const float seconds = (float)(clock.tv_sec % 3600) + clock.tv_nsec * 1e-9f;
|
||||
if (draw) for (int eye = 0; eye < 2; eye++) {
|
||||
uint32_t image = 0;
|
||||
XrSwapchainImageAcquireInfo acquire{XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO};
|
||||
check(xrAcquireSwapchainImage(eyes_[eye].swapchain, &acquire, &image), "acquire image");
|
||||
XrSwapchainImageWaitInfo imageWait{XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO}; imageWait.timeout = XR_INFINITE_DURATION;
|
||||
check(xrWaitSwapchainImage(eyes_[eye].swapchain, &imageWait), "wait image");
|
||||
render(eyes_[eye], image);
|
||||
render(eyes_[eye], image, valid, views[eye].pose, views[eye].fov, seconds);
|
||||
if (!capture.empty()) captured = captureTexture(eyes_[eye].images[image].image, eyes_[eye].width, eyes_[eye].height, eye ? "right" : "left") && captured;
|
||||
XrSwapchainImageReleaseInfo release{XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO};
|
||||
check(xrReleaseSwapchainImage(eyes_[eye].swapchain, &release), "release image");
|
||||
@@ -722,19 +876,143 @@ private:
|
||||
projection[eye].subImage.swapchain = eyes_[eye].swapchain;
|
||||
projection[eye].subImage.imageRect.extent = {eyes_[eye].width, eyes_[eye].height};
|
||||
}
|
||||
const bool overlay = viewsValid && hostBuffers_ && XrOverlay::active(hostControl_);
|
||||
XrCompositionLayerProjectionView overlayViews[2]{{XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW}, {XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW}};
|
||||
if (overlay) for (int eye = 0; eye < 2; eye++) {
|
||||
uint32_t image = 0;
|
||||
XrSwapchainImageAcquireInfo acquire{XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO};
|
||||
check(xrAcquireSwapchainImage(overlayEyes_[eye].swapchain, &acquire, &image), "acquire overlay image");
|
||||
XrSwapchainImageWaitInfo imageWait{XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO}; imageWait.timeout = XR_INFINITE_DURATION;
|
||||
check(xrWaitSwapchainImage(overlayEyes_[eye].swapchain, &imageWait), "wait overlay image");
|
||||
renderOverlay(eye, image, views[eye].pose, views[eye].fov, seconds);
|
||||
XrSwapchainImageReleaseInfo release{XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO};
|
||||
check(xrReleaseSwapchainImage(overlayEyes_[eye].swapchain, &release), "release overlay image");
|
||||
overlayViews[eye].pose = views[eye].pose; overlayViews[eye].fov = views[eye].fov;
|
||||
overlayViews[eye].subImage.swapchain = overlayEyes_[eye].swapchain;
|
||||
overlayViews[eye].subImage.imageRect.extent = {overlayEyes_[eye].width, overlayEyes_[eye].height};
|
||||
}
|
||||
XrCompositionLayerProjection layer{XR_TYPE_COMPOSITION_LAYER_PROJECTION};
|
||||
layer.space = world_; layer.viewCount = 2; layer.views = projection;
|
||||
const XrCompositionLayerBaseHeader *layers[] = {reinterpret_cast<XrCompositionLayerBaseHeader *>(&layer)};
|
||||
XrCompositionLayerProjection overlayLayer{XR_TYPE_COMPOSITION_LAYER_PROJECTION};
|
||||
overlayLayer.layerFlags = XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT;
|
||||
overlayLayer.space = world_; overlayLayer.viewCount = 2; overlayLayer.views = overlayViews;
|
||||
std::vector<const XrCompositionLayerBaseHeader *> layers;
|
||||
if (draw) layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader *>(&layer));
|
||||
for (auto &quad : quads) layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader *>(&quad));
|
||||
if (overlay) layers.push_back(reinterpret_cast<XrCompositionLayerBaseHeader *>(&overlayLayer));
|
||||
visibleLayers_ = (int)quads.size();
|
||||
XrFrameEndInfo end{XR_TYPE_FRAME_END_INFO}; end.displayTime = frameState.predictedDisplayTime;
|
||||
end.environmentBlendMode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE; end.layerCount = valid ? 1 : 0; end.layers = layers;
|
||||
end.environmentBlendMode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE;
|
||||
end.layerCount = (uint32_t)layers.size(); end.layers = layers.data();
|
||||
check(xrEndFrame(session_, &end), "xrEndFrame");
|
||||
if (!capture.empty()) captureResult(capture, captured, valid, projection, frameState.predictedDisplayTime);
|
||||
frames_++; if (valid) rendered_++;
|
||||
if (frames_ % 72 == 0) {
|
||||
health();
|
||||
__android_log_print(ANDROID_LOG_INFO, "DroidDeckXR", "frames=%llu rendered=%llu head=%llu hands=%d,%d period=%lld",
|
||||
__android_log_print(ANDROID_LOG_INFO, "DroidDeckXR", "frames=%llu rendered=%llu head=%llu hands=%d,%d period=%lld layers=%d",
|
||||
(unsigned long long)frames_, (unsigned long long)rendered_, (unsigned long long)head_.locationFlags,
|
||||
handActive_[0], handActive_[1], (long long)period_);
|
||||
handActive_[0], handActive_[1], (long long)period_, visibleLayers_);
|
||||
}
|
||||
}
|
||||
|
||||
// Android surfaces are stored top row first, while OpenXR samples images bottom row first.
|
||||
void collectQuads(std::vector<XrCompositionLayerQuad> &quads, std::vector<XrCompositionLayerImageLayoutFB> &layouts) {
|
||||
if (!hostBuffers_) return;
|
||||
quads.reserve(DROIDDECK_XR_HOST_LAYERS);
|
||||
layouts.reserve(DROIDDECK_XR_HOST_LAYERS);
|
||||
const DroidDeckXrHostLayer *ordered[DROIDDECK_XR_HOST_LAYERS];
|
||||
int visible = 0;
|
||||
for (const auto &layer : hostControl_.layers) {
|
||||
if (!layer.visible || layer.id < 0 || layer.id >= DROIDDECK_XR_HOST_LAYERS || !layers_[layer.id].swapchain) continue;
|
||||
if (!(layer.width > 0.f) || !(layer.height > 0.f)) continue;
|
||||
ordered[visible++] = &layer;
|
||||
}
|
||||
std::sort(ordered, ordered + visible, [](const DroidDeckXrHostLayer *a, const DroidDeckXrHostLayer *b) { return a->order < b->order; });
|
||||
for (int index = 0; index < visible; index++) {
|
||||
const auto &layer = *ordered[index];
|
||||
const SurfaceLayer &surface = layers_[layer.id];
|
||||
XrCompositionLayerQuad quad{XR_TYPE_COMPOSITION_LAYER_QUAD};
|
||||
quad.layerFlags = (layer.flags & DROIDDECK_XR_HOST_LAYER_ALPHA) ? XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT : 0;
|
||||
quad.space = (layer.flags & DROIDDECK_XR_HOST_LAYER_HEAD_LOCKED) ? view_ : world_;
|
||||
quad.eyeVisibility = XR_EYE_VISIBILITY_BOTH;
|
||||
quad.subImage.swapchain = surface.swapchain;
|
||||
quad.subImage.imageRect.extent = {surface.width, surface.height};
|
||||
quad.pose.orientation = {layer.pose.orientation[0], layer.pose.orientation[1], layer.pose.orientation[2], layer.pose.orientation[3]};
|
||||
quad.pose.position = {layer.pose.position[0], layer.pose.position[1], layer.pose.position[2]};
|
||||
quad.size = {layer.width, layer.height};
|
||||
layouts.push_back({XR_TYPE_COMPOSITION_LAYER_IMAGE_LAYOUT_FB, nullptr, XR_COMPOSITION_LAYER_IMAGE_LAYOUT_VERTICAL_FLIP_BIT_FB});
|
||||
quad.next = &layouts.back();
|
||||
quads.push_back(quad);
|
||||
}
|
||||
}
|
||||
|
||||
// SteamVR draws its laser from the "tip" of the Quest Touch render model the driver names
|
||||
// (resources/rendermodels/oculus_quest_plus_controller_*), placed on the raw grip pose; panels
|
||||
// use the same ray so there is one laser per controller.
|
||||
static DroidDeckXrPose steamVrPointer(const XrSpaceLocation &grip, int hand) {
|
||||
const float q[4] = {grip.pose.orientation.x, grip.pose.orientation.y, grip.pose.orientation.z, grip.pose.orientation.w};
|
||||
const XrVec3 tip{hand == 0 ? 0.016694f : -0.016694f, -0.02522f, 0.024687f};
|
||||
const XrVec3 at = XrVec3{grip.pose.position.x, grip.pose.position.y, grip.pose.position.z} + rotate(q, tip);
|
||||
const float tx = -0.320613f, tw = 0.947210f;
|
||||
DroidDeckXrPose pose{};
|
||||
pose.orientation[0] = q[3] * tx + q[0] * tw;
|
||||
pose.orientation[1] = q[1] * tw + q[2] * tx;
|
||||
pose.orientation[2] = q[2] * tw - q[1] * tx;
|
||||
pose.orientation[3] = q[3] * tw - q[0] * tx;
|
||||
pose.position[0] = at.x; pose.position[1] = at.y; pose.position[2] = at.z;
|
||||
pose.flags = (uint32_t)grip.locationFlags;
|
||||
return pose;
|
||||
}
|
||||
|
||||
void hostFrame(XrTime predicted) {
|
||||
if (!hostBuffers_ || !hostFrameCallback_) return;
|
||||
hostState_.version = DROIDDECK_XR_HOST_VERSION;
|
||||
hostState_.session_state = state_;
|
||||
hostState_.flags = (surfaceSupported_ ? DROIDDECK_XR_HOST_SURFACE_SWAPCHAIN : 0u) |
|
||||
(state_ == XR_SESSION_STATE_FOCUSED ? DROIDDECK_XR_HOST_FOCUSED : 0u);
|
||||
hostState_.frame = (int64_t)frames_;
|
||||
hostState_.display_time_ns = 0;
|
||||
if (convertTime_) {
|
||||
timespec displayTime{};
|
||||
if (XR_SUCCEEDED(convertTime_(instance_, predicted, &displayTime)))
|
||||
hostState_.display_time_ns = (int64_t)displayTime.tv_sec * 1000000000LL + displayTime.tv_nsec;
|
||||
}
|
||||
hostState_.head = posePacket(head_.pose, head_.locationFlags);
|
||||
const XrSpaceLocationFlags tracked = XR_SPACE_LOCATION_ORIENTATION_VALID_BIT | XR_SPACE_LOCATION_POSITION_VALID_BIT;
|
||||
for (int hand = 0; hand < 2; hand++) {
|
||||
auto &out = hostState_.hands[hand];
|
||||
out.grip = posePacket(handLocations_[hand].pose, handLocations_[hand].locationFlags);
|
||||
out.aim = steamVrPointer(handLocations_[hand], hand);
|
||||
out.trigger = inputs_[hand].trigger; out.squeeze = inputs_[hand].squeeze;
|
||||
out.stick[0] = inputs_[hand].stick[0]; out.stick[1] = inputs_[hand].stick[1];
|
||||
out.buttons = inputs_[hand].buttons;
|
||||
out.active = handActive_[hand] && (handLocations_[hand].locationFlags & tracked) == tracked;
|
||||
}
|
||||
env_->CallVoidMethod(app_->activity->clazz, hostFrameCallback_);
|
||||
if (env_->ExceptionCheck()) {
|
||||
env_->ExceptionDescribe(); env_->ExceptionClear();
|
||||
hostControl_ = {};
|
||||
return;
|
||||
}
|
||||
if (hostControl_.version != DROIDDECK_XR_HOST_VERSION) { hostControl_ = {}; return; }
|
||||
for (int hand = 0; hand < 2; hand++) {
|
||||
const auto &control = hostControl_.hands[hand];
|
||||
if (control.mask & DROIDDECK_XR_HOST_MASK_INPUT) {
|
||||
inputs_[hand].trigger = 0; inputs_[hand].squeeze = 0;
|
||||
inputs_[hand].stick[0] = inputs_[hand].stick[1] = 0;
|
||||
inputs_[hand].buttons = 0;
|
||||
}
|
||||
const auto &pulse = control.haptic;
|
||||
if (pulse.id == hostPulse_[hand]) continue;
|
||||
hostPulse_[hand] = pulse.id;
|
||||
if (state_ != XR_SESSION_STATE_FOCUSED || !handActive_[hand]
|
||||
|| pulse.duration_ns < 1000000 || pulse.duration_ns > 1000000000
|
||||
|| !std::isfinite(pulse.amplitude) || pulse.amplitude < 0 || pulse.amplitude > 1
|
||||
|| !std::isfinite(pulse.frequency) || pulse.frequency < 0) continue;
|
||||
XrHapticActionInfo info{XR_TYPE_HAPTIC_ACTION_INFO}; info.action = vibration_; info.subactionPath = hands_[hand];
|
||||
XrHapticVibration vibration{XR_TYPE_HAPTIC_VIBRATION};
|
||||
vibration.duration = pulse.duration_ns; vibration.amplitude = pulse.amplitude; vibration.frequency = pulse.frequency;
|
||||
check(xrApplyHapticFeedback(session_, &info, reinterpret_cast<XrHapticBaseHeader *>(&vibration)), "host haptics");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -749,11 +1027,17 @@ private:
|
||||
munmap(tracking_, sizeof(DroidDeckXrTracking));
|
||||
}
|
||||
if (haptics_) munmap(haptics_, sizeof(DroidDeckXrHaptics));
|
||||
g_runtime = nullptr;
|
||||
hostBuffers_ = false;
|
||||
if (display_ != EGL_NO_DISPLAY && context_ != EGL_NO_CONTEXT) {
|
||||
glDeleteFramebuffers(1, &framebuffer_); glDeleteVertexArrays(1, &vertexArray_);
|
||||
glDeleteTextures(1, &cpuTexture_); glDeleteProgram(sourceProgram_);
|
||||
glDeleteRenderbuffers(2, overlayDepth_);
|
||||
overlay_.destroy();
|
||||
}
|
||||
if (env_) for (int index = 0; index < DROIDDECK_XR_HOST_LAYERS; index++) destroyLayer(env_, index);
|
||||
for (auto &eye : eyes_) if (eye.swapchain) xrDestroySwapchain(eye.swapchain);
|
||||
for (auto &eye : overlayEyes_) if (eye.swapchain) xrDestroySwapchain(eye.swapchain);
|
||||
for (auto space : handSpaces_) if (space) xrDestroySpace(space);
|
||||
if (view_) xrDestroySpace(view_); if (world_) xrDestroySpace(world_);
|
||||
if (session_) xrDestroySession(session_);
|
||||
@@ -769,6 +1053,26 @@ private:
|
||||
}
|
||||
};
|
||||
|
||||
extern "C" JNIEXPORT jint JNICALL
|
||||
Java_com_droiddeck_launcher_QuestXrActivity_nativeCreateLayer(JNIEnv *env, jobject, jint width, jint height) {
|
||||
return g_runtime ? g_runtime->createLayer(env, width, height) : -1;
|
||||
}
|
||||
|
||||
extern "C" JNIEXPORT jobject JNICALL
|
||||
Java_com_droiddeck_launcher_QuestXrActivity_nativeLayerSurface(JNIEnv *env, jobject, jint index) {
|
||||
return g_runtime ? g_runtime->layerSurface(env, index) : nullptr;
|
||||
}
|
||||
|
||||
extern "C" JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_QuestXrActivity_nativeDestroyLayer(JNIEnv *env, jobject, jint index) {
|
||||
if (g_runtime) g_runtime->destroyLayer(env, index);
|
||||
}
|
||||
|
||||
extern "C" JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_QuestXrActivity_nativeSetOrbImage(JNIEnv *env, jobject, jobject bitmap) {
|
||||
if (g_runtime) g_runtime->setOrbImage(env, bitmap);
|
||||
}
|
||||
|
||||
void android_main(android_app *app) {
|
||||
QuestXR runtime(app);
|
||||
try { runtime.run(); }
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
#pragma once
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include "xr_tracking.h"
|
||||
|
||||
// Shared with com.droiddeck.launcher.session.xr.XrHost, which reads and writes these through direct
|
||||
// ByteBuffers by fixed offset: any layout change must bump the version and update both sides.
|
||||
#define DROIDDECK_XR_HOST_VERSION 1u
|
||||
#define DROIDDECK_XR_HOST_LAYERS 6
|
||||
|
||||
#define DROIDDECK_XR_HOST_SURFACE_SWAPCHAIN (1u << 0)
|
||||
#define DROIDDECK_XR_HOST_FOCUSED (1u << 1)
|
||||
|
||||
#define DROIDDECK_XR_HOST_MASK_INPUT (1u << 0)
|
||||
|
||||
#define DROIDDECK_XR_HOST_LAYER_ALPHA (1u << 0)
|
||||
#define DROIDDECK_XR_HOST_LAYER_HEAD_LOCKED (1u << 1)
|
||||
|
||||
struct DroidDeckXrHostHand {
|
||||
DroidDeckXrPose grip;
|
||||
DroidDeckXrPose aim;
|
||||
float trigger, squeeze, stick[2];
|
||||
uint32_t buttons, active;
|
||||
uint32_t reserved[2];
|
||||
};
|
||||
|
||||
struct DroidDeckXrHostState {
|
||||
uint32_t version, session_state, flags, reserved0;
|
||||
int64_t frame, display_time_ns;
|
||||
DroidDeckXrPose head;
|
||||
DroidDeckXrHostHand hands[2];
|
||||
uint32_t reserved[8];
|
||||
};
|
||||
|
||||
struct DroidDeckXrHostHaptic {
|
||||
uint64_t id;
|
||||
int64_t duration_ns;
|
||||
float amplitude, frequency;
|
||||
};
|
||||
|
||||
struct DroidDeckXrHostHandControl {
|
||||
uint32_t mask;
|
||||
float laser;
|
||||
DroidDeckXrHostHaptic haptic;
|
||||
uint32_t reserved[2];
|
||||
};
|
||||
|
||||
struct DroidDeckXrHostOrb {
|
||||
uint32_t visible;
|
||||
float progress, burst, radius;
|
||||
DroidDeckXrPose pose;
|
||||
};
|
||||
|
||||
struct DroidDeckXrHostLayer {
|
||||
int32_t id;
|
||||
uint32_t visible, flags;
|
||||
int32_t order;
|
||||
DroidDeckXrPose pose;
|
||||
float width, height;
|
||||
uint32_t reserved[2];
|
||||
};
|
||||
|
||||
struct DroidDeckXrHostControl {
|
||||
uint32_t version, reserved0;
|
||||
DroidDeckXrHostHandControl hands[2];
|
||||
DroidDeckXrHostOrb orb;
|
||||
DroidDeckXrHostLayer layers[DROIDDECK_XR_HOST_LAYERS];
|
||||
uint32_t reserved[8];
|
||||
};
|
||||
|
||||
static_assert(sizeof(DroidDeckXrHostHand) == 96, "XR host hand layout");
|
||||
static_assert(offsetof(DroidDeckXrHostHand, aim) == 32 && offsetof(DroidDeckXrHostHand, trigger) == 64 &&
|
||||
offsetof(DroidDeckXrHostHand, stick) == 72 && offsetof(DroidDeckXrHostHand, buttons) == 80 &&
|
||||
offsetof(DroidDeckXrHostHand, active) == 84, "XR host hand layout");
|
||||
static_assert(offsetof(DroidDeckXrHostState, flags) == 8 && offsetof(DroidDeckXrHostState, frame) == 16 &&
|
||||
offsetof(DroidDeckXrHostState, head) == 32, "XR host state layout");
|
||||
static_assert(offsetof(DroidDeckXrHostHandControl, laser) == 4 && offsetof(DroidDeckXrHostHandControl, haptic) == 8,
|
||||
"XR host hand control layout");
|
||||
static_assert(offsetof(DroidDeckXrHostHaptic, duration_ns) == 8 && offsetof(DroidDeckXrHostHaptic, amplitude) == 16,
|
||||
"XR host haptic layout");
|
||||
static_assert(offsetof(DroidDeckXrHostOrb, progress) == 4 && offsetof(DroidDeckXrHostOrb, pose) == 16, "XR host orb layout");
|
||||
static_assert(offsetof(DroidDeckXrHostLayer, order) == 12 && offsetof(DroidDeckXrHostLayer, pose) == 16 &&
|
||||
offsetof(DroidDeckXrHostLayer, width) == 48, "XR host layer layout");
|
||||
static_assert(sizeof(DroidDeckXrHostState) == 288, "XR host state layout");
|
||||
static_assert(offsetof(DroidDeckXrHostState, hands) == 64, "XR host state layout");
|
||||
static_assert(sizeof(DroidDeckXrHostHandControl) == 40, "XR host hand control layout");
|
||||
static_assert(sizeof(DroidDeckXrHostOrb) == 48, "XR host orb layout");
|
||||
static_assert(sizeof(DroidDeckXrHostLayer) == 64, "XR host layer layout");
|
||||
static_assert(offsetof(DroidDeckXrHostControl, orb) == 88, "XR host control layout");
|
||||
static_assert(offsetof(DroidDeckXrHostControl, layers) == 136, "XR host control layout");
|
||||
static_assert(sizeof(DroidDeckXrHostControl) == 552, "XR host control layout");
|
||||
@@ -0,0 +1,229 @@
|
||||
#pragma once
|
||||
#include <GLES3/gl3.h>
|
||||
#include <openxr/openxr.h>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <stdexcept>
|
||||
#include "xr_host.h"
|
||||
|
||||
struct XrVec3 { float x, y, z; };
|
||||
|
||||
static inline XrVec3 xrv(float x, float y, float z) { return {x, y, z}; }
|
||||
static inline XrVec3 operator+(XrVec3 a, XrVec3 b) { return {a.x + b.x, a.y + b.y, a.z + b.z}; }
|
||||
static inline XrVec3 operator-(XrVec3 a, XrVec3 b) { return {a.x - b.x, a.y - b.y, a.z - b.z}; }
|
||||
static inline XrVec3 operator*(XrVec3 a, float s) { return {a.x * s, a.y * s, a.z * s}; }
|
||||
static inline float dot(XrVec3 a, XrVec3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
|
||||
static inline XrVec3 cross(XrVec3 a, XrVec3 b) { return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; }
|
||||
static inline XrVec3 normalized(XrVec3 a) {
|
||||
float length = std::sqrt(dot(a, a));
|
||||
return length > 1e-6f ? a * (1.f / length) : xrv(0, 0, 0);
|
||||
}
|
||||
|
||||
static inline XrVec3 rotate(const float q[4], XrVec3 v) {
|
||||
XrVec3 u{q[0], q[1], q[2]};
|
||||
float s = q[3];
|
||||
return u * (2.f * dot(u, v)) + v * (s * s - dot(u, u)) + cross(u, v) * (2.f * s);
|
||||
}
|
||||
|
||||
class XrOverlay {
|
||||
public:
|
||||
void initialize() {
|
||||
GLuint vertex = compile(GL_VERTEX_SHADER,
|
||||
"#version 300 es\nlayout(location=0) in vec3 position; layout(location=1) in vec2 coordinate;"
|
||||
"uniform mat4 viewProjection; out vec2 uv;"
|
||||
"void main(){uv=coordinate;gl_Position=viewProjection*vec4(position,1.0);}");
|
||||
GLuint fragment = compile(GL_FRAGMENT_SHADER,
|
||||
"#version 300 es\nprecision highp float; in vec2 uv; uniform int mode; uniform float progress, burst, time;"
|
||||
"uniform vec3 color; uniform sampler2D logo; uniform int hasLogo; out vec4 outputColor;"
|
||||
"void main(){"
|
||||
" if(mode==0){float across=1.0-abs(uv.y); float a=smoothstep(0.0,0.7,across)*mix(0.95,0.35,uv.x);"
|
||||
" outputColor=vec4(color*a,a);return;}"
|
||||
" if(mode==1){float r=length(uv); float a=1.0-smoothstep(0.55,1.0,r); outputColor=vec4(vec3(1.0)*a,a);return;}"
|
||||
" float r=length(uv); vec3 c=vec3(0.0); float a=0.0;"
|
||||
" float pulse=0.5+0.5*sin(time*6.0);"
|
||||
" float glow=exp(-pow(max(r-0.45,0.0)*6.0,2.0))*(0.25+0.2*pulse)*step(0.5,r); c+=color*glow; a=max(a,glow*0.7);"
|
||||
" if(hasLogo==1&&r<0.52){vec4 l=texture(logo,vec2(0.5+uv.x/1.04,0.5-uv.y/1.04)); c=c*(1.0-l.a)+l.rgb; a=a*(1.0-l.a)+l.a;}"
|
||||
" else if(r<0.5){float core=1.0-smoothstep(0.46,0.5,r); c+=color*core; a=max(a,core);}"
|
||||
" float angle=atan(uv.x,uv.y); float sweep=(angle<0.0?angle+6.2831853:angle)/6.2831853;"
|
||||
" float band=1.0-smoothstep(0.0,0.03,abs(r-0.64));"
|
||||
" float track=band*0.25; float fill=band*step(sweep,progress);"
|
||||
" c+=vec3(1.0)*track+color*fill*1.4; a=max(a,max(track,fill));"
|
||||
" if(burst>0.0){float ring=(1.0-smoothstep(0.0,0.06,abs(r-(0.64+burst*0.3))))*(1.0-burst); c+=color*ring*2.0; a=max(a,ring);}"
|
||||
" a=clamp(a,0.0,1.0); outputColor=vec4(c*a,a);"
|
||||
"}");
|
||||
program_ = glCreateProgram();
|
||||
glAttachShader(program_, vertex); glAttachShader(program_, fragment);
|
||||
glLinkProgram(program_); glDeleteShader(vertex); glDeleteShader(fragment);
|
||||
GLint linked = 0; glGetProgramiv(program_, GL_LINK_STATUS, &linked);
|
||||
if (!linked) throw std::runtime_error("Overlay shader link failed");
|
||||
viewProjection_ = glGetUniformLocation(program_, "viewProjection");
|
||||
mode_ = glGetUniformLocation(program_, "mode");
|
||||
progress_ = glGetUniformLocation(program_, "progress");
|
||||
burst_ = glGetUniformLocation(program_, "burst");
|
||||
time_ = glGetUniformLocation(program_, "time");
|
||||
color_ = glGetUniformLocation(program_, "color");
|
||||
logoSampler_ = glGetUniformLocation(program_, "logo");
|
||||
hasLogo_ = glGetUniformLocation(program_, "hasLogo");
|
||||
glGenVertexArrays(1, &vertexArray_);
|
||||
glGenBuffers(1, &buffer_);
|
||||
glBindVertexArray(vertexArray_);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, buffer_);
|
||||
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 5 * 6, nullptr, GL_DYNAMIC_DRAW);
|
||||
glEnableVertexAttribArray(0);
|
||||
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 5, nullptr);
|
||||
glEnableVertexAttribArray(1);
|
||||
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 5, reinterpret_cast<void *>(sizeof(float) * 3));
|
||||
glBindVertexArray(0);
|
||||
}
|
||||
|
||||
/** [pixels] are premultiplied RGBA rows, top row first, as an Android ARGB_8888 bitmap holds them. */
|
||||
void setLogo(const void *pixels, int width, int height, int stride) {
|
||||
if (!logo_) glGenTextures(1, &logo_);
|
||||
glBindTexture(GL_TEXTURE_2D, logo_);
|
||||
glPixelStorei(GL_UNPACK_ROW_LENGTH, stride / 4);
|
||||
glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB8_ALPHA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
|
||||
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
|
||||
glGenerateMipmap(GL_TEXTURE_2D);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
|
||||
}
|
||||
|
||||
void destroy() {
|
||||
if (logo_) glDeleteTextures(1, &logo_);
|
||||
logo_ = 0;
|
||||
if (program_) glDeleteProgram(program_);
|
||||
if (buffer_) glDeleteBuffers(1, &buffer_);
|
||||
if (vertexArray_) glDeleteVertexArrays(1, &vertexArray_);
|
||||
program_ = buffer_ = vertexArray_ = 0;
|
||||
}
|
||||
|
||||
static bool active(const DroidDeckXrHostControl &control) {
|
||||
return control.orb.visible || control.hands[0].laser > 0.f || control.hands[1].laser > 0.f;
|
||||
}
|
||||
|
||||
void draw(const XrPosef &eye, const XrFovf &fov, const DroidDeckXrHostControl &control,
|
||||
const DroidDeckXrHostState &state, float seconds) {
|
||||
if (!active(control)) return;
|
||||
float matrix[16];
|
||||
viewProjectionOf(eye, fov, matrix);
|
||||
const float eyeOrientation[4] = {eye.orientation.x, eye.orientation.y, eye.orientation.z, eye.orientation.w};
|
||||
const XrVec3 eyePosition{eye.position.x, eye.position.y, eye.position.z};
|
||||
glUseProgram(program_);
|
||||
glUniformMatrix4fv(viewProjection_, 1, GL_FALSE, matrix);
|
||||
glUniform3f(color_, 0.12f, 0.62f, 1.0f);
|
||||
glUniform1f(time_, seconds);
|
||||
glBindVertexArray(vertexArray_);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, buffer_);
|
||||
glEnable(GL_DEPTH_TEST);
|
||||
glDepthFunc(GL_LEQUAL);
|
||||
glDepthMask(GL_TRUE);
|
||||
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
|
||||
glDisable(GL_BLEND);
|
||||
glUniform1i(mode_, 0);
|
||||
for (const auto &layer : control.layers) {
|
||||
if (!layer.visible || !(layer.width > 0.f) || !(layer.height > 0.f)) continue;
|
||||
if (layer.flags & DROIDDECK_XR_HOST_LAYER_HEAD_LOCKED) continue;
|
||||
XrVec3 center{layer.pose.position[0], layer.pose.position[1], layer.pose.position[2]};
|
||||
XrVec3 right = rotate(layer.pose.orientation, xrv(layer.width / 2.f, 0, 0));
|
||||
XrVec3 up = rotate(layer.pose.orientation, xrv(0, layer.height / 2.f, 0));
|
||||
quad(center - right - up, center + right - up, center - right + up, center + right + up, 0.f, 1.f);
|
||||
}
|
||||
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
|
||||
glDepthMask(GL_FALSE);
|
||||
glEnable(GL_BLEND);
|
||||
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
|
||||
for (int hand = 0; hand < 2; hand++) {
|
||||
float length = control.hands[hand].laser;
|
||||
if (!(length > 0.f) || !state.hands[hand].active) continue;
|
||||
const auto &aim = state.hands[hand].aim;
|
||||
XrVec3 start{aim.position[0], aim.position[1], aim.position[2]};
|
||||
XrVec3 direction = normalized(rotate(aim.orientation, xrv(0, 0, -1)));
|
||||
XrVec3 end = start + direction * std::max(length - 0.004f, 0.f);
|
||||
XrVec3 side = normalized(cross(direction, eyePosition - start)) * 0.0022f;
|
||||
glUniform1i(mode_, 0);
|
||||
quad(start - side, start + side, end - side, end + side, 0.f, 1.f);
|
||||
XrVec3 right = rotate(eyeOrientation, xrv(1, 0, 0)) * 0.007f;
|
||||
XrVec3 up = rotate(eyeOrientation, xrv(0, 1, 0)) * 0.007f;
|
||||
glUniform1i(mode_, 1);
|
||||
billboard(end + normalized(eyePosition - end) * 0.008f, right, up);
|
||||
}
|
||||
if (control.orb.visible) {
|
||||
const auto &pose = control.orb.pose;
|
||||
XrVec3 center{pose.position[0], pose.position[1], pose.position[2]};
|
||||
float size = control.orb.radius * 1.25f;
|
||||
XrVec3 right = rotate(eyeOrientation, xrv(1, 0, 0)) * size;
|
||||
XrVec3 up = rotate(eyeOrientation, xrv(0, 1, 0)) * size;
|
||||
glUniform1i(mode_, 2);
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
glBindTexture(GL_TEXTURE_2D, logo_);
|
||||
glUniform1i(logoSampler_, 0);
|
||||
glUniform1i(hasLogo_, logo_ ? 1 : 0);
|
||||
glUniform1f(progress_, control.orb.progress);
|
||||
glUniform1f(burst_, control.orb.burst);
|
||||
billboard(center, right, up);
|
||||
}
|
||||
glBindVertexArray(0);
|
||||
glDisable(GL_BLEND);
|
||||
glDisable(GL_DEPTH_TEST);
|
||||
glDepthMask(GL_TRUE);
|
||||
}
|
||||
|
||||
private:
|
||||
GLuint program_ = 0, buffer_ = 0, vertexArray_ = 0, logo_ = 0;
|
||||
GLint viewProjection_ = -1, mode_ = -1, progress_ = -1, burst_ = -1, time_ = -1, color_ = -1;
|
||||
GLint logoSampler_ = -1, hasLogo_ = -1;
|
||||
|
||||
static GLuint compile(GLenum type, const char *text) {
|
||||
GLuint handle = glCreateShader(type);
|
||||
glShaderSource(handle, 1, &text, nullptr); glCompileShader(handle);
|
||||
GLint success = 0; glGetShaderiv(handle, GL_COMPILE_STATUS, &success);
|
||||
if (!success) { glDeleteShader(handle); throw std::runtime_error("Overlay shader compile failed"); }
|
||||
return handle;
|
||||
}
|
||||
|
||||
void billboard(XrVec3 center, XrVec3 right, XrVec3 up) {
|
||||
quadUv(center - right - up, center + right - up, center - right + up, center + right + up);
|
||||
}
|
||||
|
||||
void quad(XrVec3 a0, XrVec3 a1, XrVec3 b0, XrVec3 b1, float from, float to) {
|
||||
const float vertices[] = {
|
||||
a0.x, a0.y, a0.z, from, -1, a1.x, a1.y, a1.z, from, 1, b0.x, b0.y, b0.z, to, -1,
|
||||
b0.x, b0.y, b0.z, to, -1, a1.x, a1.y, a1.z, from, 1, b1.x, b1.y, b1.z, to, 1};
|
||||
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
|
||||
glDrawArrays(GL_TRIANGLES, 0, 6);
|
||||
}
|
||||
|
||||
void quadUv(XrVec3 bottomLeft, XrVec3 bottomRight, XrVec3 topLeft, XrVec3 topRight) {
|
||||
const float vertices[] = {
|
||||
bottomLeft.x, bottomLeft.y, bottomLeft.z, -1, -1, bottomRight.x, bottomRight.y, bottomRight.z, 1, -1,
|
||||
topLeft.x, topLeft.y, topLeft.z, -1, 1, topLeft.x, topLeft.y, topLeft.z, -1, 1,
|
||||
bottomRight.x, bottomRight.y, bottomRight.z, 1, -1, topRight.x, topRight.y, topRight.z, 1, 1};
|
||||
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
|
||||
glDrawArrays(GL_TRIANGLES, 0, 6);
|
||||
}
|
||||
|
||||
static void viewProjectionOf(const XrPosef &pose, const XrFovf &fov, float out[16]) {
|
||||
const float q[4] = {pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w};
|
||||
XrVec3 xAxis = rotate(q, xrv(1, 0, 0)), yAxis = rotate(q, xrv(0, 1, 0)), zAxis = rotate(q, xrv(0, 0, 1));
|
||||
XrVec3 position{pose.position.x, pose.position.y, pose.position.z};
|
||||
float view[16] = {
|
||||
xAxis.x, yAxis.x, zAxis.x, 0, xAxis.y, yAxis.y, zAxis.y, 0, xAxis.z, yAxis.z, zAxis.z, 0,
|
||||
-dot(xAxis, position), -dot(yAxis, position), -dot(zAxis, position), 1};
|
||||
const float nearZ = 0.05f, farZ = 100.f;
|
||||
float left = std::tan(fov.angleLeft), right = std::tan(fov.angleRight);
|
||||
float up = std::tan(fov.angleUp), down = std::tan(fov.angleDown);
|
||||
float width = right - left, height = up - down;
|
||||
float projection[16] = {
|
||||
2.f / width, 0, 0, 0, 0, 2.f / height, 0, 0,
|
||||
(right + left) / width, (up + down) / height, -(farZ + nearZ) / (farZ - nearZ), -1,
|
||||
0, 0, -2.f * farZ * nearZ / (farZ - nearZ), 0};
|
||||
for (int column = 0; column < 4; column++)
|
||||
for (int row = 0; row < 4; row++) {
|
||||
float sum = 0;
|
||||
for (int k = 0; k < 4; k++) sum += projection[k * 4 + row] * view[column * 4 + k];
|
||||
out[column * 4 + row] = sum;
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -4,25 +4,32 @@ import android.app.NativeActivity
|
||||
import android.os.Bundle
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import android.view.Surface
|
||||
import android.widget.Toast
|
||||
import com.droiddeck.launcher.gpu.SteamVr
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.session.xr.XrLayerSource
|
||||
import com.droiddeck.launcher.session.xr.XrPanels
|
||||
import com.droiddeck.launcher.wayland.CompositorHost
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
|
||||
class QuestXrActivity : NativeActivity() {
|
||||
class QuestXrActivity : NativeActivity(), XrLayerSource {
|
||||
private var steamVrStarted = false
|
||||
@Volatile private var closing = false
|
||||
@Volatile private var steamVrStatus = SteamVr.Status.UNAVAILABLE
|
||||
private var sessionId: String? = null
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
// NativeActivity opens the library itself, but the layer host's JNI methods resolve only
|
||||
// through a System.loadLibrary.
|
||||
System.loadLibrary("droiddeckxr")
|
||||
sessionId = SessionState.sessionId
|
||||
SessionService.setXrActivityVisible(this, true)
|
||||
super.onCreate(savedInstanceState)
|
||||
}
|
||||
|
||||
fun onXrActive(active: Boolean) {
|
||||
XrPanels.setDrawing(active)
|
||||
if (active) {
|
||||
check(CompositorHost.isStarted) { "DroidDeck compositor is not running" }
|
||||
SessionService.resume(this)
|
||||
@@ -100,8 +107,30 @@ class QuestXrActivity : NativeActivity() {
|
||||
|
||||
fun onXrStatus(): Int = steamVrStatus.ordinal
|
||||
|
||||
fun onXrHostBuffers(state: java.nio.ByteBuffer, control: java.nio.ByteBuffer) {
|
||||
runOnUiThread { if (!closing) XrPanels.attach(this, state, control) }
|
||||
}
|
||||
|
||||
fun onXrHostFrame() = XrPanels.frame()
|
||||
|
||||
override val context: android.content.Context get() = this
|
||||
override fun createLayer(width: Int, height: Int) = nativeCreateLayer(width, height)
|
||||
override fun layerSurface(id: Int) = nativeLayerSurface(id)
|
||||
override fun destroyLayer(id: Int) = nativeDestroyLayer(id)
|
||||
override fun setOrbImage(image: android.graphics.Bitmap) = nativeSetOrbImage(image)
|
||||
override fun leave() {
|
||||
closing = true
|
||||
finish()
|
||||
}
|
||||
|
||||
private external fun nativeCreateLayer(width: Int, height: Int): Int
|
||||
private external fun nativeLayerSurface(id: Int): Surface?
|
||||
private external fun nativeDestroyLayer(id: Int)
|
||||
private external fun nativeSetOrbImage(image: android.graphics.Bitmap)
|
||||
|
||||
override fun onDestroy() {
|
||||
closing = true
|
||||
XrPanels.detach()
|
||||
SessionService.setXrActivityVisible(this, false)
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
@@ -162,7 +162,8 @@ import kotlin.math.abs
|
||||
private const val SCREEN_EFFECTS_TARGET_AUTO = "auto"
|
||||
private const val SCREEN_EFFECTS_TARGET_GLOBAL = "global"
|
||||
|
||||
class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droiddeck.launcher.ui.AgentPetHost {
|
||||
class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droiddeck.launcher.ui.AgentPetHost,
|
||||
com.droiddeck.launcher.session.xr.XrMenuHost {
|
||||
override fun attachBaseContext(newBase: android.content.Context) {
|
||||
super.attachBaseContext(newBase)
|
||||
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
|
||||
@@ -546,6 +547,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
private var drawerOpenState by mutableStateOf(false)
|
||||
private var typingReturnMode: SecondScreenMode? = null
|
||||
private var drawerDocked by mutableStateOf(false)
|
||||
/** The menu is open as a floating panel in the immersive Quest view instead of over this window. */
|
||||
private var drawerXr by mutableStateOf(false)
|
||||
private var drawerPinned by mutableStateOf(false)
|
||||
private var drawerLayerOpen = false
|
||||
private var drawerBackRequests by mutableIntStateOf(0)
|
||||
@@ -563,9 +566,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
drawerPinned = false
|
||||
if (value) {
|
||||
releaseHeldKeys()
|
||||
drawerDocked = dockDrawer() && openDockedMenu()
|
||||
drawerXr = com.droiddeck.launcher.session.xr.XrPanels.showMenu()
|
||||
drawerDocked = !drawerXr && dockDrawer() && openDockedMenu()
|
||||
}
|
||||
drawerOpenState = value
|
||||
if (!value && drawerXr) {
|
||||
drawerXr = false
|
||||
com.droiddeck.launcher.session.xr.XrPanels.hideMenu()
|
||||
}
|
||||
if (!value && drawerDocked) closeDockedMenu()
|
||||
}
|
||||
private val dockedMenuIdle: Boolean get() = com.droiddeck.launcher.input.DualScreen.menuIdleOnBottom(drawerOpen, drawerDocked, drawerPinned, dockedMenuController)
|
||||
@@ -850,6 +858,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
com.droiddeck.launcher.session.xr.XrPanels.setMenuHost(this)
|
||||
AgentGuest.readyListener = agentReadyListener
|
||||
com.droiddeck.launcher.agent.AgentAttachments.gameFrame = gameFrame
|
||||
if (com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isRemoving() ||
|
||||
@@ -1193,7 +1202,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
val cursorHidden = cursorHiddenByUi()
|
||||
androidx.compose.runtime.SideEffect {
|
||||
com.droiddeck.launcher.glasses.GlassesMenuMirror.setSessionMenuVisible(this@SessionActivity,
|
||||
(drawerOpen || achievementsOpen || pcKeyboardOpen) && !pipUi && steamVrStatus != SteamVr.Status.RUNNING)
|
||||
(drawerOpen || achievementsOpen || pcKeyboardOpen) && !pipUi && !drawerXr && steamVrStatus != SteamVr.Status.RUNNING)
|
||||
}
|
||||
androidx.compose.runtime.SideEffect { applyPlatformPointer(uiPointer) }
|
||||
androidx.compose.runtime.DisposableEffect(Unit) {
|
||||
@@ -1272,6 +1281,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
if (!drawerOpen && !pcKeyboardOpen && !loading.visible) {
|
||||
com.droiddeck.launcher.ui.DrawerEntryHint(SessionState.mode == SessionService.MODE_STEAM, backActionsInverted) { drawerOpen = true }
|
||||
if (cornerTap) com.droiddeck.launcher.ui.DrawerCornerTap { drawerOpen = true }
|
||||
if (com.droiddeck.launcher.session.QuestExperimental.isSupported())
|
||||
com.droiddeck.launcher.ui.DrawerEdgeSwipe { onBackPressedDispatcher.onBackPressed() }
|
||||
}
|
||||
if (loading.visible) LoadingOverlay(
|
||||
loading.step, loading.percent, loading.elapsed, loading.hint, loading.ended,
|
||||
@@ -1475,11 +1486,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
onAndroidKeyboard = { pcKeyboardOpen = false; togglePrimaryKeyboard() },
|
||||
onClose = { pcKeyboardOpen = false },
|
||||
)
|
||||
if (!drawerDocked) SessionMenu(
|
||||
if (!drawerDocked && !drawerXr) SessionMenu(
|
||||
docked = false,
|
||||
effectsEditorProfileId = effectsEditorProfileId,
|
||||
effectsEditorTarget = effectsEditorTarget,
|
||||
)
|
||||
if (drawerOpen && !drawerDocked && !drawerXr && com.droiddeck.launcher.session.QuestExperimental.isSupported())
|
||||
com.droiddeck.launcher.ui.DrawerEdgeSwipe { onBackPressedDispatcher.onBackPressed() }
|
||||
LaunchedEffect(achievementsOpen) {
|
||||
if (achievementsOpen) {
|
||||
releasePads()
|
||||
@@ -1528,6 +1541,70 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
}
|
||||
|
||||
@androidx.compose.runtime.Composable
|
||||
override fun XrMenuContent() {
|
||||
val activeEffectsProfileId = currentScreenEffectsProfileId()
|
||||
val effectsEditorTarget = if (drawerOpen) screenEffectsTarget else null
|
||||
val effectsEditorProfileId = activeEffectsProfileId.takeIf { effectsEditorTarget == SCREEN_EFFECTS_TARGET_AUTO }
|
||||
androidx.compose.runtime.LaunchedEffect(effectsEditorTarget, effectsEditorProfileId) {
|
||||
when (effectsEditorTarget) {
|
||||
SCREEN_EFFECTS_TARGET_AUTO -> syncActiveScreenEffectsProfile()
|
||||
null -> Unit
|
||||
else -> syncScreenEffectsTarget(effectsEditorTarget)
|
||||
}
|
||||
}
|
||||
SessionMenu(docked = true, effectsEditorProfileId = effectsEditorProfileId, effectsEditorTarget = effectsEditorTarget)
|
||||
}
|
||||
|
||||
override fun xrSetMenuOpen(open: Boolean) {
|
||||
if (open != drawerOpen) drawerOpen = open
|
||||
}
|
||||
|
||||
/**
|
||||
* In the immersive Quest view, Stop takes the user back to this window with the session still
|
||||
* running, and Stop SteamVR leaves at once instead of after the stop is noticed.
|
||||
*/
|
||||
private fun leaveXrMenu() {
|
||||
if (!drawerXr) return
|
||||
drawerOpen = false
|
||||
com.droiddeck.launcher.session.xr.XrPanels.leaveImmersive()
|
||||
}
|
||||
|
||||
override fun xrMenuBack() {
|
||||
if (drawerLayerOpen) drawerBackRequests++ else drawerOpen = false
|
||||
}
|
||||
|
||||
override fun xrSendKey(code: Int, down: Boolean) {
|
||||
if (CompositorHost.isStarted) sendGuestKey(code, down, 32)
|
||||
}
|
||||
|
||||
override fun xrTypeText(text: String) = xrKeys.type(text)
|
||||
|
||||
override fun xrImmersiveChanged(active: Boolean) {
|
||||
if (active) {
|
||||
if (immersiveFlatSize == null) immersiveFlatSize = SessionState.outputSize
|
||||
resizeOutputForWindow(surfaceW, surfaceH)
|
||||
return
|
||||
}
|
||||
val flat = immersiveFlatSize
|
||||
immersiveFlatSize = null
|
||||
if (windowOutputSize(surfaceW, surfaceH) == null && flat != null) applyOutputSize(flat)
|
||||
else resizeOutputForWindow(surfaceW, surfaceH)
|
||||
}
|
||||
|
||||
/** The output's size when the immersive view opened; this window may have no surface while it is up. */
|
||||
private var immersiveFlatSize: Pair<Int, Int>? = null
|
||||
|
||||
override fun xrTapKey(keyCode: Int) = xrKeys.tap(keyCode)
|
||||
|
||||
/** The VR keyboard's keys go straight to the game, past the menu and pad handling a real key passes through. */
|
||||
private val xrKeys by lazy {
|
||||
com.droiddeck.launcher.input.KeyboardHost(this) { event ->
|
||||
CompositorHost.isStarted && (event.action != KeyEvent.ACTION_DOWN || event.repeatCount == 0) &&
|
||||
com.droiddeck.launcher.input.GuestKeys.send(event) { code, pressed -> sendGuestKey(code, pressed, 16) }
|
||||
}
|
||||
}
|
||||
|
||||
@androidx.compose.runtime.Composable
|
||||
private fun SessionMenu(
|
||||
docked: Boolean,
|
||||
@@ -1906,9 +1983,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
SessionService.suspendPolicyChanged(this@SessionActivity)
|
||||
},
|
||||
onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() },
|
||||
onInputSettings = { releasePads(); drawerOpen = false; inputSettingsOpen = true },
|
||||
onInputSettings = { leaveImmersiveForDialog(); releasePads(); drawerOpen = false; inputSettingsOpen = true },
|
||||
onInputSelection = { releasePads(); refreshInputProfile() },
|
||||
onGestureSettings = { drawerOpen = false; gestureSettingsOpen = true },
|
||||
onGestureSettings = { leaveImmersiveForDialog(); drawerOpen = false; gestureSettingsOpen = true },
|
||||
touchActive = drawerTouchMode(),
|
||||
directHoldBehavior = directHoldBehavior,
|
||||
onDirectHoldBehavior = { value ->
|
||||
@@ -2005,18 +2082,26 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
onUnfoldedControlsWithController = ::chooseUnfoldedControlsWithController,
|
||||
onBackground = { drawerOpen = false; pip.background(); moveTaskToBack(true) },
|
||||
onShareLogs = { drawerOpen = false; shareCurrentSessionLogs() },
|
||||
onStop = { drawerOpen = false; SessionService.stop(this@SessionActivity); finish() },
|
||||
onStop = {
|
||||
if (drawerXr) leaveXrMenu() else {
|
||||
drawerOpen = false
|
||||
SessionService.stop(this@SessionActivity)
|
||||
finish()
|
||||
}
|
||||
},
|
||||
onStopFrom = { onScreen ->
|
||||
drawerOpen = false
|
||||
if (onScreen == null || com.droiddeck.launcher.ui.Motion.scale == 0f || quitFrom != null) {
|
||||
if (quitFrom == null) { SessionService.stop(this@SessionActivity); finish() }
|
||||
} else {
|
||||
val at = IntArray(2).also { sessionOverlay.getLocationOnScreen(it) }
|
||||
quitFrom = onScreen.translate(-at[0].toFloat(), -at[1].toFloat())
|
||||
if (drawerXr) leaveXrMenu() else {
|
||||
drawerOpen = false
|
||||
if (onScreen == null || com.droiddeck.launcher.ui.Motion.scale == 0f || quitFrom != null) {
|
||||
if (quitFrom == null) { SessionService.stop(this@SessionActivity); finish() }
|
||||
} else {
|
||||
val at = IntArray(2).also { sessionOverlay.getLocationOnScreen(it) }
|
||||
quitFrom = onScreen.translate(-at[0].toFloat(), -at[1].toFloat())
|
||||
}
|
||||
}
|
||||
},
|
||||
onClose = { drawerOpen = false },
|
||||
onDismissScreen = if (docked) ({ selectSecondScreenMode(SecondScreenMode.NONE) }) else null,
|
||||
onDismissScreen = if (docked && !drawerXr) ({ selectSecondScreenMode(SecondScreenMode.NONE) }) else null,
|
||||
components = drawerComponents,
|
||||
onComponentsRefresh = {
|
||||
refreshDrawerComponents()
|
||||
@@ -2094,7 +2179,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}) else null,
|
||||
onKeyboard = { togglePrimaryKeyboard() },
|
||||
onSessionMenu = { drawerOpen = true },
|
||||
onStopSteamVr = if (vr) ({ steamVrAction("stop") }) else null,
|
||||
onStopSteamVr = if (vr) ({ leaveXrMenu(); steamVrAction("stop") }) else null,
|
||||
brightness = glasses.brightness,
|
||||
brightnessMax = glasses.brightnessMax,
|
||||
onBrightness = if (glasses.canControl && glasses.hardwareControls) Glasses::setBrightness else null,
|
||||
@@ -2133,6 +2218,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
|
||||
private fun togglePcKeyboard() {
|
||||
drawerOpen = false
|
||||
if (com.droiddeck.launcher.session.xr.XrPanels.toggleGameKeyboard(pc = true)) return
|
||||
hidePrimaryKeyboard()
|
||||
onScreenControls?.releaseAll()
|
||||
bottomInputControls?.releaseAll()
|
||||
@@ -2142,12 +2228,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
private fun showPrimaryKeyboard() {
|
||||
pendingFieldKeyboard = false
|
||||
fieldKeyboardOnPrimary = false
|
||||
if (com.droiddeck.launcher.session.xr.XrPanels.showGameKeyboard(pc = false)) return
|
||||
keyboard?.show()
|
||||
}
|
||||
|
||||
private fun togglePrimaryKeyboard() {
|
||||
pendingFieldKeyboard = false
|
||||
fieldKeyboardOnPrimary = false
|
||||
if (com.droiddeck.launcher.session.xr.XrPanels.toggleGameKeyboard(pc = false)) return
|
||||
keyboard?.toggle()
|
||||
}
|
||||
|
||||
@@ -3045,6 +3133,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
|
||||
private fun windowOutputSize(width: Int, height: Int): Pair<Int, Int>? {
|
||||
if (com.droiddeck.launcher.session.xr.XrPanels.immersiveActive) {
|
||||
val flat = immersiveFlatSize ?: SessionState.outputSize
|
||||
return if (steamScreenShown()) vrOutputSize(flat) else flat
|
||||
}
|
||||
if (width <= 0 || height <= 0 || isInPictureInPictureMode) return null
|
||||
if (bottomGame != null) return when {
|
||||
SessionState.followScreen ->
|
||||
@@ -3058,9 +3150,38 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
else if (glassesScreen == null) outputSize() else null
|
||||
}
|
||||
|
||||
/** These editors draw in this window, which the immersive view hides, so they open after leaving it. */
|
||||
private fun leaveImmersiveForDialog() {
|
||||
if (com.droiddeck.launcher.session.xr.XrPanels.immersiveActive) com.droiddeck.launcher.session.xr.XrPanels.leaveImmersive()
|
||||
}
|
||||
|
||||
/** Steam's own screen is up with no game holding a window; with no focus report, a game may be running. */
|
||||
private fun steamScreenShown(): Boolean {
|
||||
if (SessionState.mode != SessionService.MODE_STEAM) return false
|
||||
val focus = com.droiddeck.launcher.agent.AgentGuest.focus(this) ?: return false
|
||||
return com.droiddeck.launcher.session.xr.XrSteamScreen.shown(
|
||||
focus.takeUnless { it.isNull("focusedApp") }?.optLong("focusedApp"),
|
||||
focus.optJSONArray("focusableApps")?.let { list -> (0 until list.length()).map { list.optLong(it) } },
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* SteamVR shows Steam's own screen as its floating Steam window, so in the headset that screen is drawn
|
||||
* tall enough for the window to stay sharp. A flat game keeps the flat size, so the output keeps it
|
||||
* while one is running.
|
||||
*/
|
||||
private fun vrOutputSize(flat: Pair<Int, Int>): Pair<Int, Int> {
|
||||
if (flat.second >= VR_OUTPUT_HEIGHT) return flat
|
||||
val width = (flat.first.toLong() * VR_OUTPUT_HEIGHT / flat.second.coerceAtLeast(1)).toInt() and 1.inv()
|
||||
return width to VR_OUTPUT_HEIGHT
|
||||
}
|
||||
|
||||
private fun resizeOutputForWindow(width: Int, height: Int) {
|
||||
applyOutputSize(windowOutputSize(width, height) ?: return)
|
||||
}
|
||||
|
||||
private fun applyOutputSize(size: Pair<Int, Int>) {
|
||||
if (!CompositorHost.isStarted) return
|
||||
val size = windowOutputSize(width, height) ?: return
|
||||
if (size == SessionState.outputSize) return
|
||||
Log.i(TAG, "output resized: ${SessionState.outputSize.first}x${SessionState.outputSize.second} -> ${size.first}x${size.second}")
|
||||
SessionState.outputSize = size
|
||||
@@ -7150,6 +7271,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
com.droiddeck.launcher.session.xr.XrPanels.clearMenuHost(this)
|
||||
if (drawerXr) com.droiddeck.launcher.session.xr.XrPanels.hideMenu()
|
||||
uiHandler.removeCallbacks(panelHeldCheck)
|
||||
uiHandler.removeCallbacks(panelHeldRetry)
|
||||
synchronized(frameGenGlobalLock) {
|
||||
@@ -7274,6 +7397,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
const val EXTRA_RETURN_HOME = "returnHome"
|
||||
private const val BLUETOOTH_CONNECT = "android.permission.BLUETOOTH_CONNECT"
|
||||
private const val REQUEST_BLUETOOTH = 31
|
||||
private const val VR_OUTPUT_HEIGHT = 1080
|
||||
const val EXTRA_LINK_TASK = "linkTask"
|
||||
const val EXTRA_STEAMVR = "steamVr"
|
||||
const val EXTRA_PLAYED_GAME = "com.droiddeck.launcher.PLAYED_GAME"
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.droiddeck.launcher.agent
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.core.AppUiPrefs
|
||||
import com.droiddeck.launcher.ui.AgentPage
|
||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||
|
||||
/**
|
||||
* The agent's chat in a window of its own, for Quest's flat mode: opened in its own task, it is a
|
||||
* separate Horizon panel the user can move, resize and close like any other.
|
||||
*/
|
||||
class AgentChatActivity : ComponentActivity() {
|
||||
override fun attachBaseContext(newBase: Context) {
|
||||
super.attachBaseContext(newBase)
|
||||
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
setContent {
|
||||
DroidDeckTheme(appScale = AppUiPrefs.scale(this)) {
|
||||
AgentPage(
|
||||
Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background).padding(horizontal = 12.dp, vertical = 6.dp),
|
||||
visible = true, startTyping = AgentHost.entries.isEmpty(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun open(context: Context) {
|
||||
context.startActivity(
|
||||
Intent(context, AgentChatActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,7 @@ import java.util.UUID
|
||||
object AgentGuest {
|
||||
private val main by lazy { Handler(Looper.getMainLooper()) }
|
||||
var focusRevision by mutableIntStateOf(0)
|
||||
private set
|
||||
@androidx.annotation.VisibleForTesting internal set
|
||||
var steamKeyboard by mutableStateOf(false)
|
||||
private set
|
||||
var desktopTextField by mutableStateOf(false)
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.droiddeck.launcher.session.xr
|
||||
|
||||
/**
|
||||
* The menu gesture: both controllers held together. It arms when the two aim points come within
|
||||
* [ARM_METRES], cancels once they part beyond [CANCEL_METRES], and fires after [HOLD_MS] held.
|
||||
* It needs both controllers apart again before it can arm a second time.
|
||||
*/
|
||||
internal class XrGesture {
|
||||
enum class Phase { IDLE, ARMING, FIRED }
|
||||
|
||||
var phase = Phase.IDLE
|
||||
private set
|
||||
var progress = 0f
|
||||
private set
|
||||
var midpoint = Vec3.ZERO
|
||||
private set
|
||||
private var startedMs = 0L
|
||||
private var needsRelease = false
|
||||
|
||||
/** Returns true on the frame the gesture completes. */
|
||||
fun update(left: XrHand, right: XrHand, nowMs: Long): Boolean {
|
||||
if (!left.active || !right.active) {
|
||||
reset(release = false)
|
||||
return false
|
||||
}
|
||||
val a = left.aim.position
|
||||
val b = right.aim.position
|
||||
val distance = (a - b).length
|
||||
midpoint = Vec3.lerp(a, b, 0.5f)
|
||||
if (needsRelease) {
|
||||
if (distance > CANCEL_METRES) needsRelease = false
|
||||
phase = Phase.IDLE
|
||||
progress = 0f
|
||||
return false
|
||||
}
|
||||
when (phase) {
|
||||
Phase.IDLE, Phase.FIRED -> if (distance < ARM_METRES) {
|
||||
phase = Phase.ARMING
|
||||
startedMs = nowMs
|
||||
progress = 0f
|
||||
}
|
||||
Phase.ARMING -> if (distance > CANCEL_METRES) {
|
||||
phase = Phase.IDLE
|
||||
progress = 0f
|
||||
} else {
|
||||
progress = ((nowMs - startedMs).toFloat() / HOLD_MS).coerceIn(0f, 1f)
|
||||
if (progress >= 1f) {
|
||||
phase = Phase.FIRED
|
||||
needsRelease = true
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
fun reset(release: Boolean) {
|
||||
phase = Phase.IDLE
|
||||
progress = 0f
|
||||
if (release) needsRelease = true
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val ARM_METRES = 0.09f
|
||||
const val CANCEL_METRES = 0.14f
|
||||
const val HOLD_MS = 1500L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package com.droiddeck.launcher.session.xr
|
||||
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
/**
|
||||
* Typed access to the two buffers quest_xr.cpp shares each frame (app/src/main/cpp/questxr/xr_host.h).
|
||||
* The offsets here must match that header.
|
||||
*/
|
||||
internal object XrHostLayout {
|
||||
const val VERSION = 1
|
||||
const val LAYERS = 6
|
||||
const val STATE_SIZE = 288
|
||||
const val CONTROL_SIZE = 552
|
||||
const val POSE_SIZE = 32
|
||||
const val HAND_SIZE = 96
|
||||
const val STATE_HEAD = 32
|
||||
const val STATE_HANDS = 64
|
||||
const val HAND_GRIP = 0
|
||||
const val HAND_AIM = 32
|
||||
const val HAND_TRIGGER = 64
|
||||
const val HAND_SQUEEZE = 68
|
||||
const val HAND_STICK = 72
|
||||
const val HAND_BUTTONS = 80
|
||||
const val HAND_ACTIVE = 84
|
||||
const val CONTROL_HANDS = 8
|
||||
const val HAND_CONTROL_SIZE = 40
|
||||
const val HAND_CONTROL_MASK = 0
|
||||
const val HAND_CONTROL_LASER = 4
|
||||
const val HAND_CONTROL_HAPTIC = 8
|
||||
const val CONTROL_ORB = 88
|
||||
const val CONTROL_LAYERS = 136
|
||||
const val LAYER_SIZE = 64
|
||||
|
||||
const val FLAG_SURFACE_SWAPCHAIN = 1
|
||||
const val FLAG_FOCUSED = 2
|
||||
const val MASK_INPUT = 1
|
||||
const val LAYER_ALPHA = 1
|
||||
const val LAYER_HEAD_LOCKED = 2
|
||||
|
||||
const val SECONDARY_CLICK = 1 shl 2
|
||||
}
|
||||
|
||||
internal class XrHand(
|
||||
val grip: Pose,
|
||||
val aim: Pose,
|
||||
val trigger: Float,
|
||||
val squeeze: Float,
|
||||
val stickX: Float,
|
||||
val stickY: Float,
|
||||
val buttons: Int,
|
||||
val active: Boolean,
|
||||
) {
|
||||
val secondary: Boolean get() = buttons and XrHostLayout.SECONDARY_CLICK != 0
|
||||
|
||||
companion object {
|
||||
val IDLE = XrHand(Pose(), Pose(), 0f, 0f, 0f, 0f, 0, false)
|
||||
}
|
||||
}
|
||||
|
||||
internal class XrFrame(val flags: Int, val frame: Long, val displayTimeNs: Long, val head: Pose, val hands: List<XrHand>) {
|
||||
val focused: Boolean get() = flags and XrHostLayout.FLAG_FOCUSED != 0
|
||||
val surfaces: Boolean get() = flags and XrHostLayout.FLAG_SURFACE_SWAPCHAIN != 0
|
||||
}
|
||||
|
||||
internal class XrHaptic(val durationMs: Int, val amplitude: Float, val frequency: Float = 0f)
|
||||
|
||||
internal class XrLayerOut(
|
||||
val id: Int,
|
||||
val pose: Pose,
|
||||
val width: Float,
|
||||
val height: Float,
|
||||
val order: Int,
|
||||
val alpha: Boolean = true,
|
||||
)
|
||||
|
||||
internal class XrControlOut {
|
||||
val masks = BooleanArray(2)
|
||||
val lasers = FloatArray(2)
|
||||
val haptics = arrayOfNulls<XrHaptic>(2)
|
||||
var orb: Orb? = null
|
||||
val layers = mutableListOf<XrLayerOut>()
|
||||
|
||||
class Orb(val position: Vec3, val radius: Float, val progress: Float, val burst: Float)
|
||||
}
|
||||
|
||||
internal class XrHost(state: ByteBuffer, control: ByteBuffer) {
|
||||
private val state = state.order(ByteOrder.nativeOrder())
|
||||
private val control = control.order(ByteOrder.nativeOrder())
|
||||
private val hapticIds = LongArray(2)
|
||||
|
||||
init {
|
||||
require(state.capacity() >= XrHostLayout.STATE_SIZE && control.capacity() >= XrHostLayout.CONTROL_SIZE) { "XR host buffers too small" }
|
||||
}
|
||||
|
||||
fun read(): XrFrame = readFrame(state)
|
||||
|
||||
fun write(out: XrControlOut) = writeControl(control, out, hapticIds)
|
||||
|
||||
companion object {
|
||||
fun readPose(b: ByteBuffer, at: Int) = Pose(
|
||||
Quat(b.getFloat(at), b.getFloat(at + 4), b.getFloat(at + 8), b.getFloat(at + 12)),
|
||||
Vec3(b.getFloat(at + 16), b.getFloat(at + 20), b.getFloat(at + 24)),
|
||||
)
|
||||
|
||||
fun writePose(b: ByteBuffer, at: Int, pose: Pose) {
|
||||
b.putFloat(at, pose.orientation.x); b.putFloat(at + 4, pose.orientation.y)
|
||||
b.putFloat(at + 8, pose.orientation.z); b.putFloat(at + 12, pose.orientation.w)
|
||||
b.putFloat(at + 16, pose.position.x); b.putFloat(at + 20, pose.position.y); b.putFloat(at + 24, pose.position.z)
|
||||
b.putInt(at + 28, 0)
|
||||
}
|
||||
|
||||
fun readFrame(b: ByteBuffer): XrFrame {
|
||||
val hands = (0 until 2).map { hand ->
|
||||
val at = XrHostLayout.STATE_HANDS + hand * XrHostLayout.HAND_SIZE
|
||||
XrHand(
|
||||
readPose(b, at + XrHostLayout.HAND_GRIP), readPose(b, at + XrHostLayout.HAND_AIM),
|
||||
b.getFloat(at + XrHostLayout.HAND_TRIGGER), b.getFloat(at + XrHostLayout.HAND_SQUEEZE),
|
||||
b.getFloat(at + XrHostLayout.HAND_STICK), b.getFloat(at + XrHostLayout.HAND_STICK + 4),
|
||||
b.getInt(at + XrHostLayout.HAND_BUTTONS), b.getInt(at + XrHostLayout.HAND_ACTIVE) != 0,
|
||||
)
|
||||
}
|
||||
return XrFrame(b.getInt(8), b.getLong(16), b.getLong(24), readPose(b, XrHostLayout.STATE_HEAD), hands)
|
||||
}
|
||||
|
||||
fun writeControl(b: ByteBuffer, out: XrControlOut, hapticIds: LongArray) {
|
||||
for (i in 0 until XrHostLayout.CONTROL_SIZE step 4) b.putInt(i, 0)
|
||||
b.putInt(0, XrHostLayout.VERSION)
|
||||
for (hand in 0 until 2) {
|
||||
val at = XrHostLayout.CONTROL_HANDS + hand * XrHostLayout.HAND_CONTROL_SIZE
|
||||
b.putInt(at + XrHostLayout.HAND_CONTROL_MASK, if (out.masks[hand]) XrHostLayout.MASK_INPUT else 0)
|
||||
b.putFloat(at + XrHostLayout.HAND_CONTROL_LASER, out.lasers[hand])
|
||||
out.haptics[hand]?.let { hapticIds[hand]++ }
|
||||
val haptic = at + XrHostLayout.HAND_CONTROL_HAPTIC
|
||||
b.putLong(haptic, hapticIds[hand])
|
||||
out.haptics[hand]?.let {
|
||||
b.putLong(haptic + 8, it.durationMs * 1_000_000L)
|
||||
b.putFloat(haptic + 16, it.amplitude)
|
||||
b.putFloat(haptic + 20, it.frequency)
|
||||
}
|
||||
}
|
||||
out.orb?.let { orb ->
|
||||
val at = XrHostLayout.CONTROL_ORB
|
||||
b.putInt(at, 1)
|
||||
b.putFloat(at + 4, orb.progress); b.putFloat(at + 8, orb.burst); b.putFloat(at + 12, orb.radius)
|
||||
writePose(b, at + 16, Pose(position = orb.position))
|
||||
}
|
||||
out.layers.take(XrHostLayout.LAYERS).forEachIndexed { index, layer ->
|
||||
val at = XrHostLayout.CONTROL_LAYERS + index * XrHostLayout.LAYER_SIZE
|
||||
b.putInt(at, layer.id)
|
||||
b.putInt(at + 4, 1)
|
||||
b.putInt(at + 8, if (layer.alpha) XrHostLayout.LAYER_ALPHA else 0)
|
||||
b.putInt(at + 12, layer.order)
|
||||
writePose(b, at + 16, layer.pose)
|
||||
b.putFloat(at + 48, layer.width); b.putFloat(at + 52, layer.height)
|
||||
}
|
||||
for (index in out.layers.size until XrHostLayout.LAYERS) b.putInt(XrHostLayout.CONTROL_LAYERS + index * XrHostLayout.LAYER_SIZE, -1)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
package com.droiddeck.launcher.session.xr
|
||||
|
||||
import kotlin.math.PI
|
||||
import kotlin.math.abs
|
||||
|
||||
/**
|
||||
* [barButton]: the grab bar has a button at its left end; the menu has its own close button instead.
|
||||
* [tilt]: how far the panel leans back from upright, in radians, as a keyboard lies on a desk.
|
||||
*/
|
||||
internal enum class XrPanelKind(
|
||||
val key: String, val resizable: Boolean, val chrome: Boolean, val barButton: Boolean = false, val tilt: Float = 0f,
|
||||
) {
|
||||
MENU("menu", resizable = true, chrome = true),
|
||||
PET_HEAD("pet_head", resizable = false, chrome = false),
|
||||
PET_CHAT("pet_chat", resizable = true, chrome = true, barButton = true),
|
||||
KEYBOARD("keyboard_desk", resizable = true, chrome = true, barButton = true, tilt = (PI / 4).toFloat());
|
||||
|
||||
/** Turned towards [head] about the vertical axis, then leant back by [tilt]. */
|
||||
fun orient(position: Vec3, head: Vec3): Quat = facing(position, head) * Quat.pitch(-tilt)
|
||||
}
|
||||
|
||||
/** Where a panel is and how big, in metres; [pixelWidth] and [pixelHeight] are its surface's size. */
|
||||
internal class XrPanelState(val kind: XrPanelKind, var pose: Pose, var width: Float, var height: Float) {
|
||||
var pixelWidth = XrUnits.pixels(width)
|
||||
var pixelHeight = XrUnits.pixels(height)
|
||||
/** 0 while it opens or closes from [animationFrom], 1 when it is in place and takes input. */
|
||||
var scale = 1f
|
||||
var animationFrom: Vec3? = null
|
||||
|
||||
val shownPose: Pose get() = animationFrom?.let { Pose(pose.orientation, Vec3.lerp(it, pose.position, scale)) } ?: pose
|
||||
val interactive: Boolean get() = scale >= 1f
|
||||
|
||||
fun hit(ray: Pose): XrHit? = hitPlane(ray, bounded = true)
|
||||
|
||||
/** Where [ray] meets this panel's plane; [bounded] limits it to the panel itself. */
|
||||
fun hitPlane(ray: Pose, bounded: Boolean, plane: Pose = pose, w: Float = width, h: Float = height): XrHit? {
|
||||
val normal = plane.orientation.rotate(Vec3(0f, 0f, 1f))
|
||||
val direction = ray.forward
|
||||
val denominator = direction dot normal
|
||||
if (denominator > -1e-4f) return null
|
||||
val distance = ((plane.position - ray.position) dot normal) / denominator
|
||||
if (distance <= 0f) return null
|
||||
val local = plane.toLocal(ray.position + direction * distance)
|
||||
if (bounded && (abs(local.x) > w / 2f || abs(local.y) > h / 2f)) return null
|
||||
return XrHit(this, local.x, local.y, distance)
|
||||
}
|
||||
|
||||
fun u(localX: Float) = (localX / width + 0.5f).coerceIn(0f, 1f)
|
||||
fun v(localY: Float) = (0.5f - localY / height).coerceIn(0f, 1f)
|
||||
fun pixelX(localX: Float) = u(localX) * pixelWidth
|
||||
fun pixelY(localY: Float) = v(localY) * pixelHeight
|
||||
|
||||
/** The grab bar runs along the bottom, as under Quest's own windows, with its button at the left end. */
|
||||
fun inBar(hit: XrHit) = kind.chrome && hit.y + 0.5f * height <= XrUnits.BAR_METRES
|
||||
fun inBarButtons(hit: XrHit) = kind.barButton && inBar(hit) && hit.x + 0.5f * width <= XrUnits.BAR_BUTTONS_METRES
|
||||
fun inResizeGrip(hit: XrHit) = kind.resizable &&
|
||||
0.5f * width - hit.x <= XrUnits.GRIP_METRES && hit.y + 0.5f * height <= XrUnits.GRIP_METRES
|
||||
}
|
||||
|
||||
internal class XrHit(val panel: XrPanelState, val x: Float, val y: Float, val distance: Float)
|
||||
|
||||
internal object XrUnits {
|
||||
const val DP_PER_METRE = 900f
|
||||
const val DENSITY = 2f
|
||||
const val DPI = 320
|
||||
const val BAR_METRES = 52f / DP_PER_METRE
|
||||
const val BAR_BUTTONS_DP = 150f
|
||||
const val BAR_BUTTONS_METRES = BAR_BUTTONS_DP / DP_PER_METRE
|
||||
const val GRIP_METRES = 0.05f
|
||||
const val MIN_METRES = 0.3f
|
||||
const val MAX_METRES = 1.6f
|
||||
const val MIN_DISTANCE = 0.4f
|
||||
const val MAX_DISTANCE = 3f
|
||||
fun pixels(metres: Float) = (metres * DP_PER_METRE * DENSITY).toInt().coerceAtLeast(16)
|
||||
}
|
||||
|
||||
internal sealed class XrPointerEvent(val panel: XrPanelState) {
|
||||
class Down(panel: XrPanelState, val x: Float, val y: Float, val hand: Int = 0) : XrPointerEvent(panel)
|
||||
class Move(panel: XrPanelState, val x: Float, val y: Float, val hand: Int = 0) : XrPointerEvent(panel)
|
||||
class Up(panel: XrPanelState, val x: Float, val y: Float, val hand: Int = 0) : XrPointerEvent(panel)
|
||||
class Cancel(panel: XrPanelState, val hand: Int = 0) : XrPointerEvent(panel)
|
||||
class Scroll(panel: XrPanelState, val x: Float, val y: Float, val amount: Float) : XrPointerEvent(panel)
|
||||
class Back(panel: XrPanelState) : XrPointerEvent(panel)
|
||||
class Click(panel: XrPanelState) : XrPointerEvent(panel)
|
||||
class Resized(panel: XrPanelState) : XrPointerEvent(panel)
|
||||
class Moved(panel: XrPanelState) : XrPointerEvent(panel)
|
||||
}
|
||||
|
||||
internal class XrInteractionOut {
|
||||
val events = mutableListOf<XrPointerEvent>()
|
||||
val masks = BooleanArray(2)
|
||||
val lasers = FloatArray(2)
|
||||
val ticks = BooleanArray(2)
|
||||
/** Where each controller points on each panel, in its pixels, left hand first; panels with no entry show none. */
|
||||
val cursors = mutableMapOf<XrPanelState, MutableList<Pair<Float, Float>>>()
|
||||
|
||||
fun point(panel: XrPanelState, x: Float, y: Float) {
|
||||
cursors.getOrPut(panel) { mutableListOf() } += x to y
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What the two controllers do to the panels each frame. A controller acts on a panel only while it
|
||||
* points at one, or while it holds one it picked up, pressed or is resizing; only then is its input
|
||||
* taken from the game.
|
||||
*/
|
||||
internal class XrInteraction {
|
||||
private sealed class Hold {
|
||||
object None : Hold()
|
||||
class Press(val panel: XrPanelState, var x: Float, var y: Float) : Hold()
|
||||
class Move(val panel: XrPanelState, var offset: Vec3, val byGrip: Boolean) : Hold()
|
||||
class Resize(val panel: XrPanelState, val plane: Pose, val width: Float, val height: Float, val startX: Float, val startY: Float) : Hold()
|
||||
class HeadPress(val panel: XrPanelState, val startX: Float, val startY: Float, val offset: Vec3) : Hold()
|
||||
}
|
||||
|
||||
private val holds = arrayOf<Hold>(Hold.None, Hold.None)
|
||||
private val trigger = BooleanArray(2)
|
||||
private val grip = BooleanArray(2)
|
||||
private val secondary = BooleanArray(2)
|
||||
|
||||
fun holding(panel: XrPanelState) = holds.any { held(it) === panel }
|
||||
|
||||
private fun held(hold: Hold): XrPanelState? = when (hold) {
|
||||
is Hold.Press -> hold.panel
|
||||
is Hold.Move -> hold.panel
|
||||
is Hold.Resize -> hold.panel
|
||||
is Hold.HeadPress -> hold.panel
|
||||
Hold.None -> null
|
||||
}
|
||||
|
||||
/** Lets go of everything, as when the immersive view goes. A button still held counts only once let go and pressed again. */
|
||||
fun reset() {
|
||||
holds.fill(Hold.None)
|
||||
trigger.fill(true)
|
||||
grip.fill(true)
|
||||
secondary.fill(true)
|
||||
}
|
||||
|
||||
/** Cancels a press and ends a move or resize where it is, as when the headset loses focus; then [reset]. */
|
||||
fun cancel(out: XrInteractionOut) {
|
||||
for ((hand, hold) in holds.withIndex()) when (hold) {
|
||||
is Hold.Press -> out.events += XrPointerEvent.Cancel(hold.panel, hand)
|
||||
is Hold.Move -> out.events += XrPointerEvent.Moved(hold.panel)
|
||||
is Hold.Resize -> out.events += XrPointerEvent.Resized(hold.panel)
|
||||
else -> Unit
|
||||
}
|
||||
reset()
|
||||
}
|
||||
|
||||
/** Lets go of [panel], as when it closes. */
|
||||
fun release(panel: XrPanelState, out: XrInteractionOut) {
|
||||
for (hand in 0..1) if (held(holds[hand]) === panel) {
|
||||
if (holds[hand] is Hold.Press) out.events += XrPointerEvent.Cancel(panel, hand)
|
||||
holds[hand] = Hold.None
|
||||
}
|
||||
}
|
||||
|
||||
fun update(head: Pose, hands: List<XrHand>, panels: List<XrPanelState>, dtSeconds: Float): XrInteractionOut {
|
||||
val out = XrInteractionOut()
|
||||
for (hand in 0..1) handFrame(hand, head, hands[hand], panels.filter { it.interactive }, dtSeconds, out)
|
||||
return out
|
||||
}
|
||||
|
||||
private fun handFrame(index: Int, head: Pose, hand: XrHand, panels: List<XrPanelState>, dt: Float, out: XrInteractionOut) {
|
||||
val wasTrigger = trigger[index]
|
||||
val wasGrip = grip[index]
|
||||
val wasSecondary = secondary[index]
|
||||
trigger[index] = if (wasTrigger) hand.trigger > 0.4f else hand.trigger > 0.6f
|
||||
grip[index] = if (wasGrip) hand.squeeze > 0.5f else hand.squeeze > 0.7f
|
||||
secondary[index] = hand.secondary
|
||||
val triggerDown = trigger[index] && !wasTrigger
|
||||
val triggerUp = !trigger[index] && wasTrigger
|
||||
val gripDown = grip[index] && !wasGrip
|
||||
val secondaryDown = secondary[index] && !wasSecondary
|
||||
val hold = holds[index]
|
||||
if (!hand.active) {
|
||||
if (hold is Hold.Press) out.events += XrPointerEvent.Cancel(hold.panel, index)
|
||||
if (hold is Hold.Move) out.events += XrPointerEvent.Moved(hold.panel)
|
||||
if (hold is Hold.Resize) out.events += XrPointerEvent.Resized(hold.panel)
|
||||
holds[index] = Hold.None
|
||||
return
|
||||
}
|
||||
val ray = hand.aim
|
||||
when (hold) {
|
||||
is Hold.Move -> {
|
||||
val panel = hold.panel
|
||||
if (abs(hand.stickY) > 0.2f) {
|
||||
val length = hold.offset.length
|
||||
val wanted = (length * (1f + hand.stickY * 1.2f * dt)).coerceIn(XrUnits.MIN_DISTANCE, XrUnits.MAX_DISTANCE)
|
||||
hold.offset = hold.offset.normalized() * wanted
|
||||
}
|
||||
val position = ray.toWorld(hold.offset)
|
||||
panel.pose = Pose(panel.kind.orient(position, head.position), position)
|
||||
out.masks[index] = true
|
||||
out.lasers[index] = hold.offset.length
|
||||
val released = if (hold.byGrip) !grip[index] else !trigger[index]
|
||||
if (released) {
|
||||
holds[index] = Hold.None
|
||||
out.events += XrPointerEvent.Moved(panel)
|
||||
}
|
||||
return
|
||||
}
|
||||
is Hold.Resize -> {
|
||||
val panel = hold.panel
|
||||
out.masks[index] = true
|
||||
hold.panel.hitPlane(ray, bounded = false, plane = hold.plane, w = hold.width, h = hold.height)?.let { hit ->
|
||||
val left = -hold.width / 2f
|
||||
val top = hold.height / 2f
|
||||
val width = (hold.width + hit.x - hold.startX).coerceIn(XrUnits.MIN_METRES, XrUnits.MAX_METRES)
|
||||
val height = (hold.height + hold.startY - hit.y).coerceIn(XrUnits.MIN_METRES, XrUnits.MAX_METRES)
|
||||
panel.width = width
|
||||
panel.height = height
|
||||
panel.pose = Pose(hold.plane.orientation, hold.plane.toWorld(Vec3(left + width / 2f, top - height / 2f, 0f)))
|
||||
out.lasers[index] = hit.distance
|
||||
}
|
||||
if (!trigger[index]) {
|
||||
holds[index] = Hold.None
|
||||
out.events += XrPointerEvent.Resized(panel)
|
||||
}
|
||||
return
|
||||
}
|
||||
is Hold.Press -> {
|
||||
val panel = hold.panel
|
||||
out.masks[index] = true
|
||||
val hit = panel.hitPlane(ray, bounded = false)
|
||||
if (hit != null) {
|
||||
val x = panel.pixelX(hit.x)
|
||||
val y = panel.pixelY(hit.y)
|
||||
if (x != hold.x || y != hold.y) out.events += XrPointerEvent.Move(panel, x, y, index)
|
||||
hold.x = x; hold.y = y
|
||||
out.lasers[index] = hit.distance
|
||||
out.point(panel, x, y)
|
||||
}
|
||||
if (secondaryDown) out.events += XrPointerEvent.Back(panel)
|
||||
if (triggerUp || !trigger[index]) {
|
||||
out.events += if (hit != null) XrPointerEvent.Up(panel, hold.x, hold.y, index) else XrPointerEvent.Cancel(panel, index)
|
||||
holds[index] = Hold.None
|
||||
}
|
||||
return
|
||||
}
|
||||
is Hold.HeadPress -> {
|
||||
val panel = hold.panel
|
||||
out.masks[index] = true
|
||||
val hit = panel.hitPlane(ray, bounded = false)
|
||||
if (hit != null) {
|
||||
out.lasers[index] = hit.distance
|
||||
val moved = Vec3(hit.x - hold.startX, hit.y - hold.startY, 0f).length
|
||||
if (moved > HEAD_DRAG_METRES) {
|
||||
holds[index] = Hold.Move(panel, hold.offset, byGrip = false)
|
||||
val position = ray.toWorld(hold.offset)
|
||||
panel.pose = Pose(panel.kind.orient(position, head.position), position)
|
||||
return
|
||||
}
|
||||
}
|
||||
if (!trigger[index]) {
|
||||
holds[index] = Hold.None
|
||||
if (panel.hit(ray) != null) out.events += XrPointerEvent.Click(panel)
|
||||
}
|
||||
return
|
||||
}
|
||||
Hold.None -> Unit
|
||||
}
|
||||
val hit = panels.mapNotNull { it.hit(ray) }.minByOrNull { it.distance } ?: return
|
||||
val panel = hit.panel
|
||||
out.masks[index] = true
|
||||
out.lasers[index] = hit.distance
|
||||
val x = panel.pixelX(hit.x)
|
||||
val y = panel.pixelY(hit.y)
|
||||
out.point(panel, x, y)
|
||||
val other = holds[1 - index]
|
||||
val heldByOther = held(other) === panel && other !is Hold.Press
|
||||
when {
|
||||
heldByOther -> Unit
|
||||
gripDown -> {
|
||||
holds[index] = Hold.Move(panel, ray.toLocal(panel.pose.position), byGrip = true)
|
||||
out.ticks[index] = true
|
||||
}
|
||||
triggerDown && panel.kind == XrPanelKind.PET_HEAD ->
|
||||
holds[index] = Hold.HeadPress(panel, hit.x, hit.y, ray.toLocal(panel.pose.position))
|
||||
triggerDown && panel.inResizeGrip(hit) -> {
|
||||
holds[index] = Hold.Resize(panel, panel.pose, panel.width, panel.height, hit.x, hit.y)
|
||||
out.ticks[index] = true
|
||||
}
|
||||
triggerDown && panel.inBar(hit) && !panel.inBarButtons(hit) -> {
|
||||
holds[index] = Hold.Move(panel, ray.toLocal(panel.pose.position), byGrip = false)
|
||||
out.ticks[index] = true
|
||||
}
|
||||
triggerDown -> {
|
||||
holds[index] = Hold.Press(panel, x, y)
|
||||
out.events += XrPointerEvent.Down(panel, x, y, index)
|
||||
}
|
||||
}
|
||||
if (holds[index] === Hold.None) {
|
||||
if (abs(hand.stickY) > 0.25f) out.events += XrPointerEvent.Scroll(panel, x, y, hand.stickY * SCROLL_PER_SECOND * dt)
|
||||
if (secondaryDown) out.events += XrPointerEvent.Back(panel)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val HEAD_DRAG_METRES = 0.02f
|
||||
const val SCROLL_PER_SECOND = 12f
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
package com.droiddeck.launcher.session.xr
|
||||
|
||||
import android.view.KeyEvent
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import com.droiddeck.launcher.R
|
||||
import androidx.compose.animation.animateColorAsState
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.RowScope
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.outlined.Backspace
|
||||
import androidx.compose.material.icons.automirrored.outlined.KeyboardReturn
|
||||
import androidx.compose.material.icons.outlined.KeyboardArrowUp
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.compositeOver
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.text.TextRange
|
||||
import androidx.compose.ui.text.input.EditCommand
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.ImeOptions
|
||||
import androidx.compose.ui.text.input.PlatformTextInputService
|
||||
import androidx.compose.ui.text.input.TextFieldValue
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.input.PC_KEY_ROWS
|
||||
import kotlinx.coroutines.delay
|
||||
import com.droiddeck.launcher.ui.TypingRequest
|
||||
|
||||
/** Sends text fields in the floating panels to [XrKeyboard], since the system keyboard cannot show in the immersive view. */
|
||||
internal class XrTextInput : PlatformTextInputService {
|
||||
private var request: TypingRequest? = null
|
||||
|
||||
override fun startInput(
|
||||
value: TextFieldValue, imeOptions: ImeOptions,
|
||||
onEditCommand: (List<EditCommand>) -> Unit, onImeActionPerformed: (ImeAction) -> Unit,
|
||||
) {
|
||||
val next = TypingRequest(value, imeOptions, { onEditCommand(TypingRequest.editsFor(it)) }, onImeActionPerformed)
|
||||
request = next
|
||||
XrPanels.startTyping(next)
|
||||
}
|
||||
|
||||
override fun stopInput() {
|
||||
request?.let { XrPanels.stopTyping(it) }
|
||||
request = null
|
||||
}
|
||||
|
||||
override fun showSoftwareKeyboard() {
|
||||
request?.let { XrPanels.startTyping(it) }
|
||||
}
|
||||
|
||||
override fun hideSoftwareKeyboard() {
|
||||
request?.let { XrPanels.stopTyping(it) }
|
||||
}
|
||||
|
||||
override fun updateState(oldValue: TextFieldValue?, newValue: TextFieldValue) {
|
||||
request?.value = newValue
|
||||
}
|
||||
}
|
||||
|
||||
internal object XrKeys {
|
||||
private val letters = listOf("qwertyuiop", "asdfghjkl", "zxcvbnm")
|
||||
private val symbols = listOf("1234567890", "@#&*-+=()", "!?:;'\"/,")
|
||||
|
||||
fun rows(numbers: Boolean, shift: Boolean): List<String> =
|
||||
(if (numbers) symbols else letters).map { if (shift && !numbers) it.uppercase() else it }
|
||||
|
||||
fun insert(value: TextFieldValue, text: String): TextFieldValue {
|
||||
val start = minOf(value.selection.start, value.selection.end)
|
||||
val end = maxOf(value.selection.start, value.selection.end)
|
||||
val next = value.text.substring(0, start) + text + value.text.substring(end)
|
||||
return TextFieldValue(next, TextRange(start + text.length))
|
||||
}
|
||||
|
||||
fun backspace(value: TextFieldValue): TextFieldValue {
|
||||
val start = minOf(value.selection.start, value.selection.end)
|
||||
val end = maxOf(value.selection.start, value.selection.end)
|
||||
if (start != end) return TextFieldValue(value.text.substring(0, start) + value.text.substring(end), TextRange(start))
|
||||
if (start == 0) return value
|
||||
val cut = value.text.offsetByCodePoints(start, -1)
|
||||
return TextFieldValue(value.text.substring(0, cut) + value.text.substring(start), TextRange(cut))
|
||||
}
|
||||
|
||||
const val REPEAT_DELAY_MS = 450L
|
||||
const val REPEAT_MS = 50L
|
||||
|
||||
/** Return sends when the field asks for an action, and starts a new line otherwise. */
|
||||
fun returnSends(options: ImeOptions) = options.imeAction != ImeAction.Default && options.imeAction != ImeAction.None &&
|
||||
options.singleLine
|
||||
}
|
||||
|
||||
/** Where the laser keyboard's keys go: a text field in a panel, or the game. */
|
||||
internal interface XrKeyTarget {
|
||||
fun type(text: String)
|
||||
fun backspace()
|
||||
fun enter()
|
||||
}
|
||||
|
||||
internal class XrFieldTarget(private val request: TypingRequest) : XrKeyTarget {
|
||||
override fun type(text: String) = request.send(XrKeys.insert(request.value, text))
|
||||
override fun backspace() = request.send(XrKeys.backspace(request.value))
|
||||
override fun enter() = if (XrKeys.returnSends(request.imeOptions)) request.action() else type("\n")
|
||||
}
|
||||
|
||||
internal class XrGameTarget(private val host: XrMenuHost) : XrKeyTarget {
|
||||
override fun type(text: String) = host.xrTypeText(text)
|
||||
override fun backspace() = host.xrTapKey(KeyEvent.KEYCODE_DEL)
|
||||
override fun enter() = host.xrTapKey(KeyEvent.KEYCODE_ENTER)
|
||||
}
|
||||
|
||||
/**
|
||||
* DroidDeck's PC keyboard typing into a panel's text field: the keys that make a character type it,
|
||||
* Backspace, Enter and Space edit, and Shift and Caps Lock pick the case. The rest have nothing to do there.
|
||||
*/
|
||||
internal class XrPcText(private val target: XrKeyTarget, private val timer: XrTimer = XrTimer.Main) {
|
||||
private val keys = PC_KEY_ROWS.flatten()
|
||||
.filter { it.labelRes == 0 && it.label.length == 1 && it.code !in ARROWS }
|
||||
.associateBy { it.code }
|
||||
private val shifts = mutableSetOf<Int>()
|
||||
private var caps = false
|
||||
private var stopRepeat: (() -> Unit)? = null
|
||||
|
||||
fun key(code: Int, down: Boolean) {
|
||||
if (code == LEFT_SHIFT || code == RIGHT_SHIFT) {
|
||||
if (down) shifts += code else shifts -= code
|
||||
return
|
||||
}
|
||||
if (!down && code != BACKSPACE) return
|
||||
stopRepeat?.invoke()
|
||||
stopRepeat = null
|
||||
if (!down) return
|
||||
val shifted = shifts.isNotEmpty()
|
||||
when (code) {
|
||||
BACKSPACE -> {
|
||||
target.backspace()
|
||||
stopRepeat = timer.after(XrKeys.REPEAT_DELAY_MS, ::repeatBackspace)
|
||||
}
|
||||
ENTER -> target.enter()
|
||||
SPACE -> target.type(" ")
|
||||
CAPS -> caps = !caps
|
||||
else -> keys[code]?.let { key ->
|
||||
target.type(when {
|
||||
shifted && key.shifted != null -> key.shifted
|
||||
key.label[0].isLetter() && (shifted xor caps) -> key.label.uppercase()
|
||||
else -> key.label
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun repeatBackspace() {
|
||||
target.backspace()
|
||||
stopRepeat = timer.after(XrKeys.REPEAT_MS, ::repeatBackspace)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val LEFT_SHIFT = 42
|
||||
const val RIGHT_SHIFT = 54
|
||||
const val BACKSPACE = 14
|
||||
const val ENTER = 28
|
||||
const val SPACE = 57
|
||||
const val CAPS = 58
|
||||
val ARROWS = setOf(103, 105, 106, 108)
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs an action later on the main thread; the function it returns cancels it. */
|
||||
internal fun interface XrTimer {
|
||||
fun after(ms: Long, action: () -> Unit): () -> Unit
|
||||
|
||||
companion object {
|
||||
private val handler by lazy { android.os.Handler(android.os.Looper.getMainLooper()) }
|
||||
val Main = XrTimer { ms, action ->
|
||||
val runnable = Runnable(action)
|
||||
handler.postDelayed(runnable, ms)
|
||||
({ handler.removeCallbacks(runnable) })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The Android-style text keyboard. */
|
||||
@Composable
|
||||
internal fun XrKeyboard(target: XrKeyTarget) {
|
||||
var shift by remember { mutableStateOf(false) }
|
||||
var numbers by remember { mutableStateOf(false) }
|
||||
fun type(text: String) {
|
||||
target.type(text)
|
||||
if (shift) shift = false
|
||||
}
|
||||
Column(Modifier.fillMaxSize().padding(8.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
XrKeys.rows(numbers, shift).forEachIndexed { index, row ->
|
||||
Row(Modifier.fillMaxWidth().weight(1f), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
if (index == 2) KeyIcon(Icons.Outlined.KeyboardArrowUp, stringResource(R.string.pckb_key_shift), active = shift, weight = 1.5f) { shift = !shift }
|
||||
row.forEach { key -> Key(key.toString()) { type(key.toString()) } }
|
||||
if (index == 2) KeyIcon(Icons.AutoMirrored.Outlined.Backspace, stringResource(R.string.pckb_key_backspace), weight = 1.5f, repeats = true) { target.backspace() }
|
||||
}
|
||||
}
|
||||
Row(Modifier.fillMaxWidth().weight(1f), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Key(if (numbers) "abc" else "?123", weight = 1.5f) { numbers = !numbers }
|
||||
Key(",") { type(",") }
|
||||
Key(" ", weight = 5f) { type(" ") }
|
||||
Key(".") { type(".") }
|
||||
KeyIcon(Icons.AutoMirrored.Outlined.KeyboardReturn, stringResource(R.string.pckb_key_enter), weight = 1.5f) { target.enter() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A key that lights while the laser is over it and dips while it is pressed; [repeats] keeps acting while held. */
|
||||
@Composable
|
||||
private fun RowScope.KeyBox(
|
||||
weight: Float, active: Boolean, onClick: () -> Unit, repeats: Boolean = false, content: @Composable (Color) -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val source = remember { MutableInteractionSource() }
|
||||
val (pointedAt, pointed) = rememberXrPointed()
|
||||
val hovered = pointed.value
|
||||
val pressed by source.collectIsPressedAsState()
|
||||
val action by rememberUpdatedState(onClick)
|
||||
var repeated by remember { mutableStateOf(false) }
|
||||
if (repeats) LaunchedEffect(pressed) {
|
||||
if (!pressed) return@LaunchedEffect
|
||||
repeated = false
|
||||
delay(XrKeys.REPEAT_DELAY_MS)
|
||||
repeated = true
|
||||
while (true) {
|
||||
action()
|
||||
delay(XrKeys.REPEAT_MS)
|
||||
}
|
||||
}
|
||||
val fill by animateColorAsState(
|
||||
when {
|
||||
pressed -> colors.primary
|
||||
active -> colors.primary.copy(alpha = 0.8f)
|
||||
hovered -> colors.onSurface.copy(alpha = 0.22f).compositeOver(colors.surfaceVariant)
|
||||
else -> colors.surfaceVariant
|
||||
}, tween(if (pressed) 40 else 140), label = "keyFill",
|
||||
)
|
||||
val scale by animateFloatAsState(if (pressed) 0.9f else if (hovered) 1.05f else 1f, tween(if (pressed) 40 else 140), label = "keyScale")
|
||||
Box(
|
||||
Modifier.weight(weight).fillMaxHeight()
|
||||
.then(pointedAt)
|
||||
.graphicsLayer { scaleX = 1f + (scale - 1f) * size.height / size.width; scaleY = scale }
|
||||
.clip(RoundedCornerShape(8.dp)).background(fill)
|
||||
.border(if (hovered) 2.dp else 0.dp, if (hovered) colors.primary else Color.Transparent, RoundedCornerShape(8.dp))
|
||||
.clickable(interactionSource = source, indication = null) { if (repeated) repeated = false else onClick() },
|
||||
contentAlignment = Alignment.Center,
|
||||
) { content(if (pressed || active) colors.onPrimary else colors.onSurface) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RowScope.Key(label: String, weight: Float = 1f, onClick: () -> Unit) =
|
||||
KeyBox(weight, active = false, onClick) { tint -> Text(label, color = tint, fontSize = 22.sp, maxLines = 1) }
|
||||
|
||||
@Composable
|
||||
private fun RowScope.KeyIcon(icon: ImageVector, label: String, active: Boolean = false, weight: Float = 1f, repeats: Boolean = false, onClick: () -> Unit) =
|
||||
KeyBox(weight, active, onClick, repeats) { tint -> Icon(icon, label, tint = tint) }
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.droiddeck.launcher.session.xr
|
||||
|
||||
import kotlin.math.atan2
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.sin
|
||||
import kotlin.math.sqrt
|
||||
|
||||
internal data class Vec3(val x: Float, val y: Float, val z: Float) {
|
||||
operator fun plus(o: Vec3) = Vec3(x + o.x, y + o.y, z + o.z)
|
||||
operator fun minus(o: Vec3) = Vec3(x - o.x, y - o.y, z - o.z)
|
||||
operator fun times(s: Float) = Vec3(x * s, y * s, z * s)
|
||||
infix fun dot(o: Vec3) = x * o.x + y * o.y + z * o.z
|
||||
infix fun cross(o: Vec3) = Vec3(y * o.z - z * o.y, z * o.x - x * o.z, x * o.y - y * o.x)
|
||||
val length: Float get() = sqrt(this dot this)
|
||||
fun normalized(): Vec3 = length.let { if (it > 1e-6f) this * (1f / it) else ZERO }
|
||||
|
||||
companion object {
|
||||
val ZERO = Vec3(0f, 0f, 0f)
|
||||
val FORWARD = Vec3(0f, 0f, -1f)
|
||||
val UP = Vec3(0f, 1f, 0f)
|
||||
fun lerp(a: Vec3, b: Vec3, t: Float) = a + (b - a) * t
|
||||
}
|
||||
}
|
||||
|
||||
internal data class Quat(val x: Float, val y: Float, val z: Float, val w: Float) {
|
||||
fun rotate(v: Vec3): Vec3 {
|
||||
val u = Vec3(x, y, z)
|
||||
return u * (2f * (u dot v)) + v * (w * w - (u dot u)) + (u cross v) * (2f * w)
|
||||
}
|
||||
|
||||
fun conjugate() = Quat(-x, -y, -z, w)
|
||||
|
||||
operator fun times(o: Quat) = Quat(
|
||||
w * o.x + x * o.w + y * o.z - z * o.y,
|
||||
w * o.y - x * o.z + y * o.w + z * o.x,
|
||||
w * o.z + x * o.y - y * o.x + z * o.w,
|
||||
w * o.w - x * o.x - y * o.y - z * o.z,
|
||||
)
|
||||
|
||||
companion object {
|
||||
val IDENTITY = Quat(0f, 0f, 0f, 1f)
|
||||
fun yaw(radians: Float) = Quat(0f, sin(radians / 2f), 0f, cos(radians / 2f))
|
||||
fun pitch(radians: Float) = Quat(sin(radians / 2f), 0f, 0f, cos(radians / 2f))
|
||||
}
|
||||
}
|
||||
|
||||
internal data class Pose(val orientation: Quat = Quat.IDENTITY, val position: Vec3 = Vec3.ZERO) {
|
||||
val forward: Vec3 get() = orientation.rotate(Vec3.FORWARD)
|
||||
fun toLocal(world: Vec3): Vec3 = orientation.conjugate().rotate(world - position)
|
||||
fun toWorld(local: Vec3): Vec3 = position + orientation.rotate(local)
|
||||
}
|
||||
|
||||
/** Yaw of a direction in the horizontal plane, 0 along -Z, matching [Quat.yaw] applied to -Z. */
|
||||
internal fun yawOf(direction: Vec3): Float = atan2(-direction.x, -direction.z)
|
||||
|
||||
/** An orientation that turns +Z, the side of a quad that shows, from [position] towards [target] about the vertical axis only. */
|
||||
internal fun facing(position: Vec3, target: Vec3): Quat {
|
||||
val d = target - position
|
||||
if (d.x * d.x + d.z * d.z < 1e-8f) return Quat.IDENTITY
|
||||
return Quat.yaw(atan2(d.x, d.z))
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package com.droiddeck.launcher.session.xr
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
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.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Remove
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.State
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.staticCompositionLocalOf
|
||||
import androidx.compose.runtime.derivedStateOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.geometry.Rect
|
||||
import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.ui.layout.boundsInWindow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
/**
|
||||
* The frame of a floating panel: the content, a bar under it to grab it by with up to two buttons at
|
||||
* its left end, a corner grip to resize it, and the dot where a controller points. Its sizes match [XrUnits].
|
||||
*/
|
||||
@Composable
|
||||
internal fun XrPanelChrome(
|
||||
cursor: State<List<Pair<Float, Float>>>,
|
||||
buttons: List<XrPanelButton>,
|
||||
resizable: Boolean,
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val shape = RoundedCornerShape(18.dp)
|
||||
Box(Modifier.fillMaxSize().clip(shape).background(colors.background).border(1.dp, Color(0x33FFFFFF), shape)) {
|
||||
Column(Modifier.fillMaxSize()) {
|
||||
Box(Modifier.weight(1f).fillMaxWidth().padding(start = 10.dp, top = 10.dp, end = 10.dp)) {
|
||||
CompositionLocalProvider(LocalXrPointers provides cursor) { content() }
|
||||
}
|
||||
Box(
|
||||
Modifier.fillMaxWidth().height(52.dp).background(colors.surfaceVariant.copy(alpha = 0.6f)),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Box(Modifier.width(72.dp).height(6.dp).clip(CircleShape).background(colors.onSurface.copy(alpha = 0.35f)))
|
||||
if (buttons.isNotEmpty()) Row(
|
||||
Modifier.align(Alignment.CenterStart).width(XrUnits.BAR_BUTTONS_DP.dp).padding(start = 8.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
buttons.take(2).forEach { button ->
|
||||
if (button.icon != null) IconButton(onClick = button.onClick, modifier = Modifier.size(44.dp)) {
|
||||
Icon(button.icon, button.label, tint = colors.onSurface)
|
||||
} else TextButton(onClick = button.onClick, modifier = Modifier.height(40.dp), contentPadding = PaddingValues(horizontal = 10.dp)) {
|
||||
Text(button.label, color = colors.onSurface, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, maxLines = 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (resizable) Canvas(Modifier.align(Alignment.BottomEnd).padding(6.dp).size(28.dp)) {
|
||||
val stroke = Stroke(width = 3.dp.toPx())
|
||||
for (step in 1..3) {
|
||||
val inset = size.width * step / 4f
|
||||
drawLine(Color(0x99FFFFFF), Offset(size.width, inset), Offset(inset, size.height), stroke.width)
|
||||
}
|
||||
}
|
||||
val density = LocalDensity.current
|
||||
Canvas(Modifier.fillMaxSize()) {
|
||||
val radius = with(density) { 7.dp.toPx() }
|
||||
for ((x, y) in cursor.value) {
|
||||
drawCircle(Color(0xCC1E9EFF), radius, Offset(x, y))
|
||||
drawCircle(Color.White, radius, Offset(x, y), style = Stroke(with(density) { 2.dp.toPx() }))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Where each laser meets the panel, in the panel's pixels; null off a floating panel. */
|
||||
internal val LocalXrPointers = staticCompositionLocalOf<State<List<Pair<Float, Float>>>?> { null }
|
||||
|
||||
/**
|
||||
* Whether a laser rests on the element the returned [Modifier] is put on, for both controllers at
|
||||
* once, where a mouse hover has room for one. False off a floating panel.
|
||||
*/
|
||||
@Composable
|
||||
internal fun rememberXrPointed(): Pair<Modifier, State<Boolean>> {
|
||||
val pointers = LocalXrPointers.current
|
||||
var bounds by remember { mutableStateOf(Rect.Zero) }
|
||||
val pointed = remember(pointers) {
|
||||
derivedStateOf { pointers != null && pointers.value.any { (x, y) -> bounds.contains(Offset(x, y)) } }
|
||||
}
|
||||
return Modifier.onGloballyPositioned { bounds = it.boundsInWindow() } to pointed
|
||||
}
|
||||
|
||||
/** With no [icon] the button shows [label] itself, for a short word such as a keyboard mode. */
|
||||
internal class XrPanelButton(val icon: ImageVector?, val label: String, val onClick: () -> Unit)
|
||||
|
||||
internal val XrCollapseIcon get() = Icons.Outlined.Remove
|
||||
@@ -0,0 +1,271 @@
|
||||
package com.droiddeck.launcher.session.xr
|
||||
|
||||
import android.app.Presentation
|
||||
import android.content.Context
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.hardware.display.VirtualDisplay
|
||||
import android.os.Bundle
|
||||
import android.os.SystemClock
|
||||
import android.view.InputDevice
|
||||
import android.view.MotionEvent
|
||||
import android.view.Surface
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.view.WindowManager
|
||||
import android.view.inspector.WindowInspector
|
||||
import android.widget.FrameLayout
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.ui.platform.ComposeView
|
||||
import androidx.compose.ui.platform.LocalTextInputService
|
||||
import androidx.compose.ui.text.input.TextInputService
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleOwner
|
||||
import androidx.lifecycle.LifecycleRegistry
|
||||
import androidx.activity.OnBackPressedDispatcher
|
||||
import androidx.activity.OnBackPressedDispatcherOwner
|
||||
import androidx.activity.setViewTreeOnBackPressedDispatcherOwner
|
||||
import androidx.lifecycle.ViewModelStore
|
||||
import androidx.lifecycle.ViewModelStoreOwner
|
||||
import androidx.lifecycle.setViewTreeLifecycleOwner
|
||||
import androidx.lifecycle.setViewTreeViewModelStoreOwner
|
||||
import androidx.savedstate.SavedStateRegistry
|
||||
import androidx.savedstate.SavedStateRegistryController
|
||||
import androidx.savedstate.SavedStateRegistryOwner
|
||||
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
|
||||
import com.droiddeck.launcher.ui.LocalPresentationWindow
|
||||
|
||||
/** Keeps a panel's Compose content running while the activity that made it is stopped behind the XR view. */
|
||||
private class PanelOwner : LifecycleOwner, SavedStateRegistryOwner, ViewModelStoreOwner, OnBackPressedDispatcherOwner {
|
||||
private val registry = LifecycleRegistry(this)
|
||||
private val saved = SavedStateRegistryController.create(this)
|
||||
override val lifecycle: Lifecycle get() = registry
|
||||
override val savedStateRegistry: SavedStateRegistry get() = saved.savedStateRegistry
|
||||
override val viewModelStore = ViewModelStore()
|
||||
override val onBackPressedDispatcher = OnBackPressedDispatcher()
|
||||
|
||||
fun own(view: View) {
|
||||
view.setViewTreeLifecycleOwner(this)
|
||||
view.setViewTreeSavedStateRegistryOwner(this)
|
||||
view.setViewTreeViewModelStoreOwner(this)
|
||||
view.setViewTreeOnBackPressedDispatcherOwner(this)
|
||||
}
|
||||
|
||||
init {
|
||||
saved.performRestore(null)
|
||||
registry.currentState = Lifecycle.State.RESUMED
|
||||
}
|
||||
|
||||
fun destroy() {
|
||||
registry.currentState = Lifecycle.State.DESTROYED
|
||||
viewModelStore.clear()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One floating panel's Android side: a private virtual display drawing into the panel's OpenXR
|
||||
* surface, and a presentation on it holding the Compose content. Main thread only.
|
||||
*/
|
||||
internal class XrPanelWindow(
|
||||
private val context: Context,
|
||||
private var surface: Surface,
|
||||
width: Int,
|
||||
height: Int,
|
||||
startPaused: Boolean,
|
||||
private val content: @Composable () -> Unit,
|
||||
) {
|
||||
private var paused = startPaused
|
||||
private val owner = PanelOwner()
|
||||
private val textInput = TextInputService(XrTextInput())
|
||||
private val display: VirtualDisplay = context.getSystemService(DisplayManager::class.java).createVirtualDisplay(
|
||||
"DroidDeck XR panel", width, height, XrUnits.DPI, surface.takeUnless { paused }, DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY,
|
||||
)
|
||||
private val presentation = PanelPresentation(context, display.display)
|
||||
private var downTime = 0L
|
||||
private var target: View? = null
|
||||
/** The controllers pressing the panel, by hand, as fingers of one touch. */
|
||||
private val touches = linkedMapOf<Int, Pair<Float, Float>>()
|
||||
private var hovering: View? = null
|
||||
private var hoverAt = 0f to 0f
|
||||
private var cursor: Pair<Float, Float>? = null
|
||||
|
||||
init {
|
||||
try {
|
||||
presentation.show()
|
||||
} catch (failure: RuntimeException) {
|
||||
release()
|
||||
throw failure
|
||||
}
|
||||
}
|
||||
|
||||
val displayId: Int get() = display.display.displayId
|
||||
|
||||
fun resize(surface: Surface, width: Int, height: Int) {
|
||||
this.surface = surface
|
||||
if (!paused) display.surface = surface
|
||||
display.resize(width, height, XrUnits.DPI)
|
||||
}
|
||||
|
||||
/** Stops drawing into the panel's layer, or starts again. */
|
||||
fun pause(pause: Boolean) {
|
||||
if (pause == paused) return
|
||||
paused = pause
|
||||
display.surface = if (pause) null else surface
|
||||
}
|
||||
|
||||
fun release() {
|
||||
runCatching { presentation.dismiss() }
|
||||
owner.destroy()
|
||||
display.release()
|
||||
}
|
||||
|
||||
private inner class PanelPresentation(outer: Context, display: android.view.Display) : Presentation(outer, display) {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
window?.setBackgroundDrawableResource(android.R.color.transparent)
|
||||
window?.addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED)
|
||||
val compose = ComposeView(context).apply {
|
||||
owner.own(this)
|
||||
setContent {
|
||||
CompositionLocalProvider(
|
||||
LocalPresentationWindow provides true,
|
||||
LocalTextInputService provides textInput,
|
||||
) { content() }
|
||||
}
|
||||
}
|
||||
val frame = FrameLayout(context).apply {
|
||||
addView(compose, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
|
||||
}
|
||||
setContentView(frame)
|
||||
window?.decorView?.let(owner::own)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The topmost window on this panel's display under the point, so popups and dialogs get the input.
|
||||
* A focusable popup or dialog on top takes a press outside it too, as on a touchscreen, where it
|
||||
* dismisses itself rather than letting the press act on what is behind it.
|
||||
*/
|
||||
private fun rootAt(x: Float, y: Float): View? {
|
||||
val roots = WindowInspector.getGlobalWindowViews().filter { it.isAttachedToWindow && it.display?.displayId == displayId && it.isShown }
|
||||
val location = IntArray(2)
|
||||
fun contains(root: View): Boolean {
|
||||
root.getLocationOnScreen(location)
|
||||
return x >= location[0] && y >= location[1] && x < location[0] + root.width && y < location[1] + root.height
|
||||
}
|
||||
val top = roots.lastOrNull() ?: return null
|
||||
val focusable = (top.layoutParams as? WindowManager.LayoutParams)
|
||||
?.let { it.flags and WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE == 0 } ?: false
|
||||
if (roots.size > 1 && focusable && !contains(top)) return top
|
||||
return roots.lastOrNull(::contains) ?: top
|
||||
}
|
||||
|
||||
/** Sends every finger in [touches] to [target]; [action] is already shifted by its pointer index where it needs one. */
|
||||
private fun sendTouches(action: Int, time: Long) {
|
||||
val view = target ?: return
|
||||
val location = IntArray(2)
|
||||
view.getLocationOnScreen(location)
|
||||
val properties = touches.keys.map { hand ->
|
||||
MotionEvent.PointerProperties().apply { id = hand; toolType = MotionEvent.TOOL_TYPE_FINGER }
|
||||
}.toTypedArray()
|
||||
val coords = touches.values.map { (x, y) ->
|
||||
MotionEvent.PointerCoords().apply { this.x = x - location[0]; this.y = y - location[1]; pressure = 1f; size = 1f }
|
||||
}.toTypedArray()
|
||||
val event = MotionEvent.obtain(downTime, time, action, touches.size, properties, coords, 0, 0, 1f, 1f, 0, 0,
|
||||
InputDevice.SOURCE_TOUCHSCREEN, 0)
|
||||
try {
|
||||
view.dispatchTouchEvent(event)
|
||||
} finally {
|
||||
event.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
private fun indexed(action: Int, hand: Int) =
|
||||
action or (touches.keys.indexOf(hand) shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
|
||||
|
||||
private fun send(view: View, action: Int, x: Float, y: Float, time: Long, generic: Boolean, scroll: Float = 0f): Boolean {
|
||||
val location = IntArray(2)
|
||||
view.getLocationOnScreen(location)
|
||||
val properties = arrayOf(MotionEvent.PointerProperties().apply {
|
||||
id = 0
|
||||
toolType = if (generic) MotionEvent.TOOL_TYPE_MOUSE else MotionEvent.TOOL_TYPE_FINGER
|
||||
})
|
||||
val coords = arrayOf(MotionEvent.PointerCoords().apply {
|
||||
this.x = x - location[0]
|
||||
this.y = y - location[1]
|
||||
pressure = 1f
|
||||
size = 1f
|
||||
if (scroll != 0f) setAxisValue(MotionEvent.AXIS_VSCROLL, scroll)
|
||||
})
|
||||
val source = if (generic) InputDevice.SOURCE_MOUSE else InputDevice.SOURCE_TOUCHSCREEN
|
||||
val event = MotionEvent.obtain(if (generic) time else downTime, time, action, 1, properties, coords, 0, 0, 1f, 1f, 0, 0, source, 0)
|
||||
return try {
|
||||
if (generic) view.dispatchGenericMotionEvent(event) else view.dispatchTouchEvent(event)
|
||||
} finally {
|
||||
event.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
/** The laser resting on the panel, as a mouse hovering, so keys and buttons light under it. Null: it left. */
|
||||
fun hover(at: Pair<Float, Float>?) {
|
||||
cursor = at
|
||||
if (target != null) return
|
||||
val now = SystemClock.uptimeMillis()
|
||||
val root = at?.let { (x, y) -> rootAt(x, y) }
|
||||
if (root !== hovering) endHover(now)
|
||||
if (root == null || at == null) return
|
||||
if (hovering == null) send(root, MotionEvent.ACTION_HOVER_ENTER, at.first, at.second, now, generic = true)
|
||||
send(root, MotionEvent.ACTION_HOVER_MOVE, at.first, at.second, now, generic = true)
|
||||
hovering = root
|
||||
hoverAt = at
|
||||
}
|
||||
|
||||
private fun endHover(now: Long) {
|
||||
hovering?.let { send(it, MotionEvent.ACTION_HOVER_EXIT, hoverAt.first, hoverAt.second, now, generic = true) }
|
||||
hovering = null
|
||||
}
|
||||
|
||||
fun pointer(event: XrPointerEvent) {
|
||||
val now = SystemClock.uptimeMillis()
|
||||
when (event) {
|
||||
is XrPointerEvent.Down -> {
|
||||
if (event.hand in touches) return
|
||||
touches[event.hand] = event.x to event.y
|
||||
if (touches.size == 1) {
|
||||
endHover(now)
|
||||
downTime = now
|
||||
target = rootAt(event.x, event.y)
|
||||
sendTouches(MotionEvent.ACTION_DOWN, now)
|
||||
} else sendTouches(indexed(MotionEvent.ACTION_POINTER_DOWN, event.hand), now)
|
||||
}
|
||||
is XrPointerEvent.Move -> {
|
||||
if (event.hand !in touches) return
|
||||
touches[event.hand] = event.x to event.y
|
||||
sendTouches(MotionEvent.ACTION_MOVE, now)
|
||||
}
|
||||
is XrPointerEvent.Up -> {
|
||||
if (event.hand !in touches) return
|
||||
touches[event.hand] = event.x to event.y
|
||||
if (touches.size > 1) {
|
||||
sendTouches(indexed(MotionEvent.ACTION_POINTER_UP, event.hand), now)
|
||||
touches -= event.hand
|
||||
} else {
|
||||
sendTouches(MotionEvent.ACTION_UP, now)
|
||||
touches.clear()
|
||||
target = null
|
||||
hover(cursor)
|
||||
}
|
||||
}
|
||||
is XrPointerEvent.Cancel -> {
|
||||
if (event.hand !in touches) return
|
||||
sendTouches(MotionEvent.ACTION_CANCEL, now)
|
||||
touches.clear()
|
||||
target = null
|
||||
}
|
||||
is XrPointerEvent.Scroll -> rootAt(event.x, event.y)?.let {
|
||||
send(it, MotionEvent.ACTION_SCROLL, event.x, event.y, now, generic = true, scroll = event.amount)
|
||||
}
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,611 @@
|
||||
package com.droiddeck.launcher.session.xr
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import android.view.Surface
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.KeyboardHide
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.State
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.snapshotFlow
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.agent.AgentHost
|
||||
import com.droiddeck.launcher.session.QuestExperimental
|
||||
import com.droiddeck.launcher.ui.AgentPage
|
||||
import com.droiddeck.launcher.ui.AgentPet
|
||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||
import com.droiddeck.launcher.ui.PcKeyboard
|
||||
import com.droiddeck.launcher.ui.PetFigure
|
||||
import com.droiddeck.launcher.ui.TypingRequest
|
||||
import com.droiddeck.launcher.ui.petStateNow
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.MainScope
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.launch
|
||||
import java.lang.ref.WeakReference
|
||||
import java.nio.ByteBuffer
|
||||
import java.util.concurrent.ConcurrentLinkedQueue
|
||||
import kotlin.math.PI
|
||||
|
||||
/** The 2D session window, which hands its menu to the immersive view while that is open. */
|
||||
internal interface XrMenuHost {
|
||||
@Composable
|
||||
fun XrMenuContent()
|
||||
fun xrSetMenuOpen(open: Boolean)
|
||||
fun xrMenuBack()
|
||||
/** A key of DroidDeck's PC keyboard, by Linux key code, to the game. */
|
||||
fun xrSendKey(code: Int, down: Boolean)
|
||||
/** Text from the laser keyboard to the game, as the Android keyboard sends it. */
|
||||
fun xrTypeText(text: String)
|
||||
fun xrTapKey(keyCode: Int)
|
||||
/** The immersive view opened or closed; Steam's screen, which SteamVR mirrors as its Steam window, sizes for it. */
|
||||
fun xrImmersiveChanged(active: Boolean)
|
||||
}
|
||||
|
||||
/** What the immersive view's native loop offers: surface-backed layers it composites in front of the game. */
|
||||
internal interface XrLayerSource {
|
||||
val context: Context
|
||||
fun createLayer(width: Int, height: Int): Int
|
||||
fun layerSurface(id: Int): Surface?
|
||||
fun destroyLayer(id: Int)
|
||||
fun setOrbImage(image: android.graphics.Bitmap)
|
||||
fun leave()
|
||||
}
|
||||
|
||||
/**
|
||||
* DroidDeck's own windows inside the immersive Quest view: the session menu, opened by holding the
|
||||
* controllers together, and the agent pet with its chat. Quest only. [frame] runs on the XR thread
|
||||
* each frame; the rest runs on the main thread.
|
||||
*/
|
||||
internal object XrPanels {
|
||||
private const val TAG = "XrPanels"
|
||||
private const val OPEN_MS = 350f
|
||||
private const val CLOSE_MS = 250f
|
||||
private const val BURST_MS = 400f
|
||||
|
||||
/** The immersive view is up, so the menu and pet belong in it. Always false off Quest. */
|
||||
@Volatile
|
||||
var immersiveActive = false
|
||||
|
||||
/** Counts attachments, so work posted from one immersive view is dropped once a later one, or none, is up. */
|
||||
@Volatile
|
||||
private var attachment = 0
|
||||
private set
|
||||
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
|
||||
/** Whether the headset shows the session; panels draw into their layers only then. */
|
||||
@Volatile
|
||||
private var drawing = false
|
||||
private val lock = Any()
|
||||
private val ops = ConcurrentLinkedQueue<() -> Unit>()
|
||||
private var source: XrLayerSource? = null
|
||||
private var host: XrHost? = null
|
||||
private var menuHost: WeakReference<XrMenuHost>? = null
|
||||
private var scope: CoroutineScope? = null
|
||||
|
||||
private class Panel(val state: XrPanelState, val content: @Composable (State<List<Pair<Float, Float>>>) -> Unit) {
|
||||
val cursorState = mutableStateOf<List<Pair<Float, Float>>>(emptyList())
|
||||
var layerId = -1
|
||||
var window: XrPanelWindow? = null
|
||||
var openedMs = 0L
|
||||
var closingMs = 0L
|
||||
var resizing = false
|
||||
var cursor: List<Pair<Float, Float>> = emptyList()
|
||||
}
|
||||
|
||||
private val panels = mutableListOf<Panel>()
|
||||
private val gesture = XrGesture()
|
||||
private val interaction = XrInteraction()
|
||||
private var lastFrameMs = 0L
|
||||
private var orbImageSent = false
|
||||
private var lastHead = Pose()
|
||||
private var burstMs = 0L
|
||||
private var burstAt = Vec3.ZERO
|
||||
private var lastTick = 0
|
||||
private var menuFrom: Vec3? = null
|
||||
private val typing = mutableStateOf<TypingRequest?>(null)
|
||||
/** The keyboard was opened for the game, from the session menu; a panel's text field takes it over while it types. */
|
||||
private val gameKeyboard = mutableStateOf(false)
|
||||
private val pcKeyboard = mutableStateOf(false)
|
||||
|
||||
fun gateOpen(model: String, device: String, manufacturer: String, immersive: Boolean) =
|
||||
immersive && QuestExperimental.supported(model, device, manufacturer)
|
||||
|
||||
fun setMenuHost(menu: XrMenuHost?) {
|
||||
menuHost = menu?.let { WeakReference(it) }
|
||||
if (immersiveActive) menu?.xrImmersiveChanged(true)
|
||||
}
|
||||
|
||||
fun clearMenuHost(menu: XrMenuHost) {
|
||||
if (menuHost?.get() === menu) menuHost = null
|
||||
}
|
||||
|
||||
/** Main thread: the immersive view handed over its buffers. */
|
||||
fun attach(layers: XrLayerSource, state: ByteBuffer, control: ByteBuffer) {
|
||||
if (!QuestExperimental.isSupported()) return
|
||||
synchronized(lock) {
|
||||
source = layers
|
||||
host = XrHost(state, control)
|
||||
orbImageSent = false
|
||||
}
|
||||
attachment++
|
||||
immersiveActive = true
|
||||
menuHost?.get()?.xrImmersiveChanged(true)
|
||||
scope?.cancel()
|
||||
scope = MainScope().also { scope ->
|
||||
scope.launch {
|
||||
snapshotFlow { com.droiddeck.launcher.agent.AgentGuest.focusRevision }.collect {
|
||||
menuHost?.get()?.xrImmersiveChanged(true)
|
||||
}
|
||||
}
|
||||
scope.launch {
|
||||
snapshotFlow { AgentPet.enabled && AgentHost.installed }.collect { on ->
|
||||
if (on) { if (!shown(XrPanelKind.PET_CHAT)) open(XrPanelKind.PET_HEAD) }
|
||||
else { close(XrPanelKind.PET_HEAD); close(XrPanelKind.PET_CHAT) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* XR thread, as the session becomes visible or stops being so. OpenXR allows writing into a surface
|
||||
* swapchain only while the session is visible or focused, and requires the writes to have stopped
|
||||
* before xrEndSession, so this returns once the panels have stopped or started drawing.
|
||||
*/
|
||||
fun setDrawing(visible: Boolean) {
|
||||
val done = java.util.concurrent.CountDownLatch(1)
|
||||
val apply = Runnable {
|
||||
try {
|
||||
drawing = visible
|
||||
synchronized(lock) { panels.mapNotNull { it.window } }.forEach { it.pause(!visible) }
|
||||
} finally {
|
||||
done.countDown()
|
||||
}
|
||||
}
|
||||
if (Looper.myLooper() == Looper.getMainLooper()) apply.run()
|
||||
else if (main.post(apply) && !done.await(1, java.util.concurrent.TimeUnit.SECONDS))
|
||||
Log.w(TAG, "panels did not ${if (visible) "start" else "stop"} drawing within a second")
|
||||
}
|
||||
|
||||
/** Main thread: the immersive view is going; every panel goes with it. */
|
||||
fun detach() {
|
||||
if (!immersiveActive) return
|
||||
immersiveActive = false
|
||||
scope?.cancel()
|
||||
scope = null
|
||||
val windows = synchronized(lock) {
|
||||
source = null
|
||||
host = null
|
||||
ops.clear()
|
||||
interaction.reset()
|
||||
panels.mapNotNull { it.window }.also { panels.clear() }
|
||||
}
|
||||
windows.forEach { it.release() }
|
||||
typing.value = null
|
||||
gameKeyboard.value = false
|
||||
gesture.reset(release = false)
|
||||
menuHost?.get()?.xrSetMenuOpen(false)
|
||||
menuHost?.get()?.xrImmersiveChanged(false)
|
||||
}
|
||||
|
||||
/** Main thread, from the session window's menu state. */
|
||||
fun showMenu(): Boolean {
|
||||
if (!immersiveActive) return false
|
||||
open(XrPanelKind.MENU, menuFrom)
|
||||
menuFrom = null
|
||||
return true
|
||||
}
|
||||
|
||||
fun hideMenu() = close(XrPanelKind.MENU)
|
||||
|
||||
/** Main thread: closes the immersive view, as a stop chosen in its menu asks. */
|
||||
fun leaveImmersive() {
|
||||
synchronized(lock) { source }?.leave()
|
||||
}
|
||||
|
||||
/** Main thread: a text field in a panel wants typing, so the laser keyboard opens. */
|
||||
fun startTyping(request: TypingRequest) {
|
||||
if (!immersiveActive) return
|
||||
typing.value = request
|
||||
open(XrPanelKind.KEYBOARD)
|
||||
}
|
||||
|
||||
fun stopTyping(request: TypingRequest) {
|
||||
if (typing.value !== request) return
|
||||
typing.value = null
|
||||
if (!gameKeyboard.value) close(XrPanelKind.KEYBOARD)
|
||||
}
|
||||
|
||||
/**
|
||||
* Main thread: the session menu's keyboards. [pc] picks DroidDeck's PC keyboard over the Android-style one;
|
||||
* asking again for the one already open closes it. False off the immersive view, where the 2D keyboards stay.
|
||||
*/
|
||||
fun toggleGameKeyboard(pc: Boolean): Boolean {
|
||||
if (!immersiveActive) return false
|
||||
if (gameKeyboard.value && pcKeyboard.value == pc && shown(XrPanelKind.KEYBOARD)) hideKeyboard()
|
||||
else showGameKeyboard(pc)
|
||||
return true
|
||||
}
|
||||
|
||||
fun showGameKeyboard(pc: Boolean): Boolean {
|
||||
if (!immersiveActive) return false
|
||||
gameKeyboard.value = true
|
||||
pcKeyboard.value = pc
|
||||
open(XrPanelKind.KEYBOARD)
|
||||
return true
|
||||
}
|
||||
|
||||
private fun hideKeyboard() {
|
||||
typing.value = null
|
||||
gameKeyboard.value = false
|
||||
close(XrPanelKind.KEYBOARD)
|
||||
}
|
||||
|
||||
private fun shown(kind: XrPanelKind) = synchronized(lock) { panels.any { it.state.kind == kind && it.closingMs == 0L } }
|
||||
|
||||
private fun open(kind: XrPanelKind, from: Vec3? = null) {
|
||||
ops += { create(kind, from) }
|
||||
}
|
||||
|
||||
private fun close(kind: XrPanelKind) {
|
||||
ops += {
|
||||
panels.filter { it.state.kind == kind && it.closingMs == 0L }.forEach { panel ->
|
||||
panel.closingMs = SystemClock.uptimeMillis()
|
||||
val out = XrInteractionOut()
|
||||
interaction.release(panel.state, out)
|
||||
dispatch(out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** XR thread. */
|
||||
private fun create(kind: XrPanelKind, from: Vec3?) {
|
||||
val layers = source ?: return
|
||||
panels.firstOrNull { it.state.kind == kind }?.let { existing ->
|
||||
if (existing.closingMs != 0L) {
|
||||
existing.closingMs = 0L
|
||||
val elapsed = 1f - Math.cbrt((1.0 - existing.state.scale).coerceIn(0.0, 1.0)).toFloat()
|
||||
existing.openedMs = SystemClock.uptimeMillis() - (elapsed * OPEN_MS).toLong()
|
||||
}
|
||||
return
|
||||
}
|
||||
val placed = XrPlacement.load(layers.context, kind, lastHead)
|
||||
val state = XrPanelState(kind, placed.pose, placed.width, placed.height)
|
||||
state.scale = 0f
|
||||
state.animationFrom = from ?: placed.pose.position
|
||||
val id = layers.createLayer(state.pixelWidth, state.pixelHeight)
|
||||
val surface = if (id >= 0) layers.layerSurface(id) else null
|
||||
if (surface == null) {
|
||||
Log.w(TAG, "no layer for the ${kind.key} panel")
|
||||
if (id >= 0) layers.destroyLayer(id)
|
||||
if (kind == XrPanelKind.MENU) main.post { menuHost?.get()?.xrSetMenuOpen(false) }
|
||||
return
|
||||
}
|
||||
val panel = Panel(state, contentFor(kind))
|
||||
panel.layerId = id
|
||||
panel.openedMs = SystemClock.uptimeMillis()
|
||||
panels += panel
|
||||
val context = layers.context
|
||||
main.post {
|
||||
synchronized(lock) {
|
||||
if (panel !in panels) return@post
|
||||
panel.window = runCatching {
|
||||
XrPanelWindow(context, surface, state.pixelWidth, state.pixelHeight, startPaused = !drawing) {
|
||||
panel.content(panel.cursorState)
|
||||
}
|
||||
}.onFailure {
|
||||
Log.w(TAG, "could not show the ${kind.key} panel", it)
|
||||
panels -= panel
|
||||
ops += { if (source === layers) layers.destroyLayer(id) }
|
||||
if (kind == XrPanelKind.MENU) menuHost?.get()?.xrSetMenuOpen(false)
|
||||
}.getOrNull()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun contentFor(kind: XrPanelKind): @Composable (State<List<Pair<Float, Float>>>) -> Unit = when (kind) {
|
||||
XrPanelKind.MENU -> { cursor ->
|
||||
DroidDeckTheme {
|
||||
XrPanelChrome(cursor, buttons = emptyList(), resizable = true) {
|
||||
menuHost?.get()?.XrMenuContent()
|
||||
}
|
||||
}
|
||||
}
|
||||
XrPanelKind.PET_HEAD -> { _ ->
|
||||
DroidDeckTheme { Box(Modifier.fillMaxSize()) { PetFigure(petStateNow(), Modifier.fillMaxSize()) } }
|
||||
}
|
||||
XrPanelKind.KEYBOARD -> { cursor ->
|
||||
DroidDeckTheme {
|
||||
val buttons = listOf(
|
||||
XrPanelButton(Icons.Outlined.KeyboardHide, stringResource(R.string.pckb_hide), ::hideKeyboard),
|
||||
XrPanelButton(null, if (pcKeyboard.value) "Android" else "PC") { pcKeyboard.value = !pcKeyboard.value },
|
||||
)
|
||||
XrPanelChrome(cursor, buttons, resizable = true) { KeyboardContent() }
|
||||
}
|
||||
}
|
||||
XrPanelKind.PET_CHAT -> { cursor ->
|
||||
DroidDeckTheme {
|
||||
XrPanelChrome(cursor, listOf(XrPanelButton(XrCollapseIcon, stringResource(R.string.bottom_chat_close), ::collapseChat)), resizable = true) {
|
||||
AgentPage(Modifier.fillMaxSize().padding(horizontal = 12.dp), visible = true, startTyping = false, hidesPet = false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A panel's text field takes the keyboard while it types; otherwise its keys go to the game. */
|
||||
@Composable
|
||||
private fun KeyboardContent() {
|
||||
val request = typing.value
|
||||
val host = menuHost?.get()?.takeIf { gameKeyboard.value }
|
||||
val target = request?.let(::XrFieldTarget) ?: host?.let(::XrGameTarget) ?: return
|
||||
if (pcKeyboard.value) {
|
||||
val pcText = remember(request) { request?.let { XrPcText(XrFieldTarget(it)) } }
|
||||
PcKeyboard(
|
||||
sendKey = { code, down -> pcText?.key(code, down) ?: host?.xrSendKey(code, down) },
|
||||
onAndroidKeyboard = { pcKeyboard.value = false },
|
||||
onClose = ::hideKeyboard,
|
||||
heightFraction = 1f,
|
||||
showButtons = false,
|
||||
hoverFeedback = true,
|
||||
)
|
||||
} else XrKeyboard(target)
|
||||
}
|
||||
|
||||
private fun collapseChat() {
|
||||
close(XrPanelKind.PET_CHAT)
|
||||
open(XrPanelKind.PET_HEAD)
|
||||
}
|
||||
|
||||
private fun expandChat(from: Vec3) {
|
||||
close(XrPanelKind.PET_HEAD)
|
||||
open(XrPanelKind.PET_CHAT, from)
|
||||
}
|
||||
|
||||
/** XR thread, once per frame, from QuestXrActivity.onXrHostFrame. */
|
||||
fun frame() = synchronized(lock) {
|
||||
val host = host ?: return
|
||||
val layers = source ?: return
|
||||
val frame = host.read()
|
||||
lastHead = frame.head
|
||||
while (true) (ops.poll() ?: break).invoke()
|
||||
if (!orbImageSent) {
|
||||
orbImageSent = true
|
||||
runCatching {
|
||||
android.graphics.BitmapFactory.decodeResource(layers.context.resources, R.drawable.logo)
|
||||
}.getOrNull()?.let { layers.setOrbImage(it); it.recycle() }
|
||||
}
|
||||
val now = SystemClock.uptimeMillis()
|
||||
val dt = if (lastFrameMs == 0L) 0f else ((now - lastFrameMs) / 1000f).coerceIn(0f, 0.1f)
|
||||
lastFrameMs = now
|
||||
val control = XrControlOut()
|
||||
animate(now, layers)
|
||||
val active = panels.filter { it.closingMs == 0L && it.window != null }
|
||||
if (frame.focused) {
|
||||
if (gesture.update(frame.hands[0], frame.hands[1], now)) {
|
||||
burstMs = now
|
||||
burstAt = gesture.midpoint
|
||||
lastTick = 0
|
||||
for (hand in 0..1) control.haptics[hand] = XrHaptic(60, 0.9f)
|
||||
val from = gesture.midpoint
|
||||
val posted = attachment
|
||||
main.post { if (immersiveActive && posted == attachment) toggleMenu(from) }
|
||||
} else if (gesture.phase == XrGesture.Phase.ARMING) {
|
||||
val step = (gesture.progress * 4).toInt()
|
||||
if (step > lastTick) for (hand in 0..1) control.haptics[hand] = XrHaptic(18, 0.2f + 0.15f * step)
|
||||
lastTick = step
|
||||
} else lastTick = 0
|
||||
val out = interaction.update(frame.head, frame.hands, active.map { it.state }, dt)
|
||||
for (hand in 0..1) {
|
||||
control.masks[hand] = out.masks[hand]
|
||||
control.lasers[hand] = out.lasers[hand]
|
||||
if (out.ticks[hand] && control.haptics[hand] == null) control.haptics[hand] = XrHaptic(12, 0.35f)
|
||||
}
|
||||
dispatch(out)
|
||||
} else {
|
||||
gesture.reset(release = false)
|
||||
val out = XrInteractionOut()
|
||||
interaction.cancel(out)
|
||||
dispatch(out)
|
||||
}
|
||||
control.orb = orb(now)
|
||||
panels.forEachIndexed { index, panel ->
|
||||
if (panel.layerId < 0 || panel.window == null) return@forEachIndexed
|
||||
val state = panel.state
|
||||
control.layers += XrLayerOut(panel.layerId, state.shownPose, state.width * state.scale, state.height * state.scale,
|
||||
order = if (state.kind == XrPanelKind.PET_HEAD) 100 else index)
|
||||
}
|
||||
host.write(control)
|
||||
}
|
||||
|
||||
private fun orb(now: Long): XrControlOut.Orb? {
|
||||
if (gesture.phase == XrGesture.Phase.ARMING)
|
||||
return XrControlOut.Orb(gesture.midpoint, 0.02f + 0.01f * gesture.progress, gesture.progress, 0f)
|
||||
val burst = (now - burstMs) / BURST_MS
|
||||
if (burstMs != 0L && burst < 1f) return XrControlOut.Orb(burstAt, 0.03f, 1f, burst.coerceAtLeast(0.01f))
|
||||
return null
|
||||
}
|
||||
|
||||
private fun animate(now: Long, layers: XrLayerSource) {
|
||||
val gone = mutableListOf<Panel>()
|
||||
for (panel in panels) {
|
||||
val state = panel.state
|
||||
if (panel.closingMs != 0L) {
|
||||
val t = ((now - panel.closingMs) / CLOSE_MS).coerceIn(0f, 1f)
|
||||
state.scale = minOf(state.scale, 1f - easeOut(t))
|
||||
if (state.animationFrom == null) state.animationFrom = state.pose.position
|
||||
if (t >= 1f) gone += panel
|
||||
} else if (state.scale < 1f) {
|
||||
state.scale = easeOut(((now - panel.openedMs) / OPEN_MS).coerceIn(0f, 1f))
|
||||
if (state.scale >= 1f) state.animationFrom = null
|
||||
}
|
||||
}
|
||||
for (panel in gone) {
|
||||
panels -= panel
|
||||
if (panel.layerId >= 0) layers.destroyLayer(panel.layerId)
|
||||
val window = panel.window
|
||||
val context = layers.context
|
||||
val state = panel.state
|
||||
val head = lastHead
|
||||
main.post {
|
||||
window?.release()
|
||||
XrPlacement.save(context, state.kind, head, state.pose, state.width, state.height)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun easeOut(t: Float) = 1f - (1f - t) * (1f - t) * (1f - t)
|
||||
|
||||
/** XR thread: hands each panel its input on the main thread and follows up on moves and resizes. */
|
||||
private fun dispatch(out: XrInteractionOut) {
|
||||
val layers = source ?: return
|
||||
for (panel in panels) {
|
||||
val cursor = out.cursors[panel.state]?.toList().orEmpty()
|
||||
if (cursor != panel.cursor) {
|
||||
panel.cursor = cursor
|
||||
val target = panel.cursorState
|
||||
val window = panel.window
|
||||
main.post {
|
||||
target.value = cursor
|
||||
window?.hover(cursor.firstOrNull())
|
||||
}
|
||||
}
|
||||
}
|
||||
for (event in out.events) {
|
||||
val panel = panels.firstOrNull { it.state === event.panel } ?: continue
|
||||
when (event) {
|
||||
is XrPointerEvent.Back -> main.post { back(panel.state.kind) }
|
||||
is XrPointerEvent.Click -> {
|
||||
val from = panel.state.pose.position
|
||||
main.post { expandChat(from) }
|
||||
}
|
||||
is XrPointerEvent.Resized -> {
|
||||
savePlacement(panel, layers)
|
||||
resize(panel, layers)
|
||||
}
|
||||
is XrPointerEvent.Moved -> savePlacement(panel, layers)
|
||||
else -> {
|
||||
val window = panel.window
|
||||
main.post { window?.pointer(event) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** XR thread: the place a move or resize ended at, read together now and saved on the main thread. */
|
||||
private fun savePlacement(panel: Panel, layers: XrLayerSource) {
|
||||
val state = panel.state
|
||||
val kind = state.kind
|
||||
val head = lastHead
|
||||
val pose = state.pose
|
||||
val width = state.width
|
||||
val height = state.height
|
||||
val context = layers.context
|
||||
main.post { XrPlacement.save(context, kind, head, pose, width, height) }
|
||||
}
|
||||
|
||||
/** XR thread: gives a resized panel a surface of its new size once its content has moved over to it. */
|
||||
private fun resize(panel: Panel, layers: XrLayerSource) {
|
||||
val state = panel.state
|
||||
val width = XrUnits.pixels(state.width)
|
||||
val height = XrUnits.pixels(state.height)
|
||||
if (width == state.pixelWidth && height == state.pixelHeight) return
|
||||
val id = layers.createLayer(width, height)
|
||||
val surface = if (id >= 0) layers.layerSurface(id) else null
|
||||
if (surface == null) {
|
||||
if (id >= 0) layers.destroyLayer(id)
|
||||
return
|
||||
}
|
||||
val window = panel.window
|
||||
main.post {
|
||||
window?.resize(surface, width, height)
|
||||
ops += {
|
||||
if (panel in panels) {
|
||||
val old = panel.layerId
|
||||
panel.layerId = id
|
||||
state.pixelWidth = width
|
||||
state.pixelHeight = height
|
||||
if (old >= 0) layers.destroyLayer(old)
|
||||
} else if (source === layers) layers.destroyLayer(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Main thread. */
|
||||
private fun toggleMenu(from: Vec3) {
|
||||
val menu = menuHost?.get() ?: return
|
||||
if (shown(XrPanelKind.MENU)) menu.xrSetMenuOpen(false)
|
||||
else {
|
||||
menuFrom = from
|
||||
menu.xrSetMenuOpen(true)
|
||||
}
|
||||
}
|
||||
|
||||
/** Main thread: B on a panel goes back a step, as Back does in the 2D window. */
|
||||
private fun back(kind: XrPanelKind) {
|
||||
when (kind) {
|
||||
XrPanelKind.MENU -> menuHost?.get()?.xrMenuBack()
|
||||
XrPanelKind.PET_CHAT -> collapseChat()
|
||||
XrPanelKind.PET_HEAD -> Unit
|
||||
XrPanelKind.KEYBOARD -> hideKeyboard()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Where each panel kind was left, relative to where the user faced, so it comes back there. */
|
||||
internal object XrPlacement {
|
||||
class Placed(val pose: Pose, val width: Float, val height: Float)
|
||||
|
||||
private class Default(val yaw: Float, val distance: Float, val dy: Float, val width: Float, val height: Float)
|
||||
|
||||
private val defaults = mapOf(
|
||||
XrPanelKind.MENU to Default(0f, 0.95f, -0.12f, 0.9f, 0.6f),
|
||||
XrPanelKind.PET_CHAT to Default(0.6f, 0.95f, -0.12f, 0.6f, 0.7f),
|
||||
XrPanelKind.PET_HEAD to Default(0.7f, 0.75f, -0.45f, 0.12f, 0.12f),
|
||||
XrPanelKind.KEYBOARD to Default(0f, 0.5f, -0.5f, 0.8f, 0.36f),
|
||||
)
|
||||
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("quest_xr_panels", Context.MODE_PRIVATE)
|
||||
|
||||
fun place(kind: XrPanelKind, head: Pose, yaw: Float, distance: Float, dy: Float): Pose {
|
||||
val angle = yawOf(head.forward) + yaw
|
||||
val direction = Quat.yaw(angle).rotate(Vec3.FORWARD)
|
||||
val position = head.position + direction * distance + Vec3(0f, dy, 0f)
|
||||
return Pose(kind.orient(position, head.position), position)
|
||||
}
|
||||
|
||||
fun relative(head: Pose, position: Vec3): Triple<Float, Float, Float> {
|
||||
val offset = position - head.position
|
||||
val distance = Vec3(offset.x, 0f, offset.z).length
|
||||
var yaw = yawOf(offset) - yawOf(head.forward)
|
||||
while (yaw > PI) yaw -= (2 * PI).toFloat()
|
||||
while (yaw < -PI) yaw += (2 * PI).toFloat()
|
||||
return Triple(yaw, distance, offset.y)
|
||||
}
|
||||
|
||||
fun load(context: Context, kind: XrPanelKind, head: Pose): Placed {
|
||||
val fallback = defaults.getValue(kind)
|
||||
val saved = prefs(context).getString(kind.key, null)?.split(',')?.mapNotNull { it.toFloatOrNull() }
|
||||
val values = saved?.takeIf { it.size == 5 } ?: listOf(fallback.yaw, fallback.distance, fallback.dy, fallback.width, fallback.height)
|
||||
val distance = values[1].coerceIn(XrUnits.MIN_DISTANCE, XrUnits.MAX_DISTANCE)
|
||||
val width = if (kind.resizable) values[3].coerceIn(XrUnits.MIN_METRES, XrUnits.MAX_METRES) else fallback.width
|
||||
val height = if (kind.resizable) values[4].coerceIn(XrUnits.MIN_METRES, XrUnits.MAX_METRES) else fallback.height
|
||||
return Placed(place(kind, head, values[0], distance, values[2].coerceIn(-1.5f, 1.5f)), width, height)
|
||||
}
|
||||
|
||||
fun save(context: Context, kind: XrPanelKind, head: Pose, pose: Pose, width: Float, height: Float) {
|
||||
val (yaw, distance, dy) = relative(head, pose.position)
|
||||
prefs(context).edit().putString(kind.key, listOf(yaw, distance, dy, width, height).joinToString(",")).apply()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.droiddeck.launcher.session.xr
|
||||
|
||||
/** Whether the guest's focus report shows Steam's own screen, with no game holding a window. */
|
||||
internal object XrSteamScreen {
|
||||
/** Steam's own UI and SteamVR, which have windows of their own but are not games. */
|
||||
private val STEAM_APPS = setOf(769L, 250820L)
|
||||
|
||||
/**
|
||||
* Gamescope lists Steam itself while its screen is up, so a report naming no app at all, as the guest
|
||||
* writes when it could not collect focus or gamescope has not published it, says nothing.
|
||||
*/
|
||||
fun shown(focusedApp: Long?, focusableApps: List<Long>?): Boolean {
|
||||
val apps = (listOfNotNull(focusedApp) + focusableApps.orEmpty()).filter { it > 0 }
|
||||
return apps.isNotEmpty() && apps.all { it in STEAM_APPS }
|
||||
}
|
||||
}
|
||||
@@ -88,7 +88,14 @@ internal object AgentPet {
|
||||
private set
|
||||
/** The floating windows could not be made, so the pet stays in DroidDeck's own windows instead. */
|
||||
private var floatFailed by mutableStateOf(false)
|
||||
val floating get() = enabled && allowed && !floatFailed
|
||||
val floating get() = enabled && allowed && !floatFailed && usesOverlayWindows(onQuest)
|
||||
/** Quest's shell turns overlay windows into system panels that take input from the VR view. */
|
||||
private val onQuest = com.droiddeck.launcher.session.QuestExperimental.isSupported()
|
||||
|
||||
internal fun usesOverlayWindows(quest: Boolean) = !quest
|
||||
|
||||
/** On Quest the chat opens as its own panel window, which Horizon moves, resizes and closes. */
|
||||
internal fun chatInOwnWindow(quest: Boolean = onQuest) = quest
|
||||
/** How to close the chat open inside each DroidDeck window that has one. */
|
||||
private val closeInWindow = java.util.WeakHashMap<AgentPetHost, () -> Unit>()
|
||||
|
||||
@@ -118,7 +125,7 @@ internal object AgentPet {
|
||||
AgentHost.prefs(context).edit().putBoolean(KEY, on).apply()
|
||||
if (on) {
|
||||
allowed = PetWindows.allowed(context)
|
||||
if (!allowed) requestFloating(context)
|
||||
if (!allowed && usesOverlayWindows(onQuest)) requestFloating(context)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -251,9 +258,12 @@ private fun PetLayer(host: AgentPetHost) {
|
||||
val density = LocalDensity.current
|
||||
val openLabel = androidx.compose.ui.res.stringResource(com.droiddeck.launcher.R.string.agent_pet_open)
|
||||
val openChat = {
|
||||
motion.dock()
|
||||
chatShown = true
|
||||
chatOpen = true
|
||||
if (AgentPet.chatInOwnWindow()) com.droiddeck.launcher.agent.AgentChatActivity.open(context)
|
||||
else {
|
||||
motion.dock()
|
||||
chatShown = true
|
||||
chatOpen = true
|
||||
}
|
||||
}
|
||||
val closeChat = {
|
||||
chatOpen = false
|
||||
|
||||
@@ -7,13 +7,16 @@ import androidx.compose.animation.slideInHorizontally
|
||||
import androidx.compose.animation.slideOutHorizontally
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
|
||||
import androidx.compose.foundation.gestures.detectTapGestures
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.WindowInsets
|
||||
import androidx.compose.foundation.layout.displayCutout
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
@@ -35,6 +38,7 @@ import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
@@ -90,6 +94,29 @@ internal fun DrawerEntryHint(steam: Boolean, inverted: Boolean, onOpen: () -> Un
|
||||
}
|
||||
}
|
||||
|
||||
/** A Quest has no system Back gesture, so a laser drag in from the right edge stands in for it. */
|
||||
@Composable
|
||||
internal fun DrawerEdgeSwipe(onBack: () -> Unit) {
|
||||
val density = LocalDensity.current
|
||||
val threshold = with(density) { 48.dp.toPx() }
|
||||
val strip = with(density) { 12.toDp() }
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.CenterEnd) {
|
||||
Box(
|
||||
Modifier.fillMaxHeight().width(strip).testTag("drawer-edge")
|
||||
.pointerInput(Unit) {
|
||||
var travelled = 0f
|
||||
detectHorizontalDragGestures(
|
||||
onDragStart = { travelled = 0f },
|
||||
onDragEnd = { if (travelled <= -threshold) onBack() },
|
||||
) { change, amount ->
|
||||
change.consume()
|
||||
travelled += amount
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun DrawerCornerTap(onOpen: () -> Unit) {
|
||||
Box(Modifier.fillMaxSize().windowInsetsPadding(WindowInsets.displayCutout), contentAlignment = Alignment.TopEnd) {
|
||||
|
||||
@@ -711,7 +711,7 @@ internal fun SetupPanel(
|
||||
ToggleRow(host, "agent-pet", stringResource(R.string.setup_agent_pet), stringResource(R.string.setup_agent_pet_hint), AgentPet.enabled) {
|
||||
AgentPet.set(agentContext, it)
|
||||
}
|
||||
if (AgentPet.enabled && !AgentPet.allowed) ActionRow(
|
||||
if (AgentPet.enabled && !AgentPet.allowed && AgentPet.usesOverlayWindows(com.droiddeck.launcher.session.QuestExperimental.isSupported())) ActionRow(
|
||||
stringResource(R.string.setup_agent_pet_float), stringResource(R.string.setup_agent_pet_float_hint),
|
||||
stringResource(R.string.setup_agent_pet_allow), onClick = { AgentPet.requestFloating(agentContext) },
|
||||
)
|
||||
|
||||
@@ -8,6 +8,9 @@ import com.droiddeck.launcher.input.PcKey
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import android.view.KeyEvent
|
||||
import androidx.compose.animation.animateColorAsState
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.foundation.hoverable
|
||||
import androidx.compose.foundation.interaction.collectIsHoveredAsState
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
@@ -69,6 +72,9 @@ fun PcKeyboard(
|
||||
sendKey: (Int, Boolean) -> Unit,
|
||||
onAndroidKeyboard: () -> Unit,
|
||||
onClose: () -> Unit,
|
||||
heightFraction: Float? = null,
|
||||
showButtons: Boolean = true,
|
||||
hoverFeedback: Boolean = false,
|
||||
) {
|
||||
val pal = LocalPalette.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
@@ -76,31 +82,40 @@ fun PcKeyboard(
|
||||
var capsOn by remember { mutableStateOf(false) }
|
||||
val firstKey = remember { FocusRequester() }
|
||||
val shifted = (mods[42] ?: MOD_OFF) != MOD_OFF || (mods[54] ?: MOD_OFF) != MOD_OFF
|
||||
// Keys go to wherever sendKey points now, but a held key is let go where it went down.
|
||||
val currentSend by androidx.compose.runtime.rememberUpdatedState(sendKey)
|
||||
val heldAt = remember { mutableMapOf<Int, (Int, Boolean) -> Unit>() }
|
||||
fun down(code: Int) {
|
||||
val send = currentSend
|
||||
heldAt[code] = send
|
||||
send(code, true)
|
||||
}
|
||||
fun up(code: Int) = (heldAt.remove(code) ?: currentSend)(code, false)
|
||||
|
||||
fun releaseOnceModifiers() {
|
||||
for ((code, state) in mods.toMap()) if (state == MOD_ONCE) { sendKey(code, false); mods[code] = MOD_OFF }
|
||||
for ((code, state) in mods.toMap()) if (state == MOD_ONCE) { up(code); mods[code] = MOD_OFF }
|
||||
}
|
||||
fun press(key: PcKey) {
|
||||
if (key.code in PC_MODIFIERS) {
|
||||
when (mods[key.code] ?: MOD_OFF) {
|
||||
MOD_OFF -> { sendKey(key.code, true); mods[key.code] = MOD_ONCE }
|
||||
MOD_OFF -> { down(key.code); mods[key.code] = MOD_ONCE }
|
||||
MOD_ONCE -> mods[key.code] = MOD_LOCKED
|
||||
else -> { sendKey(key.code, false); mods[key.code] = MOD_OFF }
|
||||
else -> { up(key.code); mods[key.code] = MOD_OFF }
|
||||
}
|
||||
return
|
||||
}
|
||||
sendKey(key.code, true)
|
||||
down(key.code)
|
||||
}
|
||||
fun release(key: PcKey) {
|
||||
if (key.code in PC_MODIFIERS) return
|
||||
sendKey(key.code, false)
|
||||
up(key.code)
|
||||
if (key.code == 58) capsOn = !capsOn
|
||||
releaseOnceModifiers()
|
||||
}
|
||||
androidx.compose.runtime.DisposableEffect(Unit) {
|
||||
onDispose { for ((code, state) in mods.toMap()) if (state != MOD_OFF) sendKey(code, false) }
|
||||
onDispose { for (code in heldAt.keys.toList()) up(code) }
|
||||
}
|
||||
LaunchedEffect(Unit) { runCatching { firstKey.requestFocus() } }
|
||||
LaunchedEffect(Unit) { if (!hoverFeedback) runCatching { firstKey.requestFocus() } }
|
||||
|
||||
val prefsContext = LocalContext.current
|
||||
remember { PcKeyboardPrefs.load(prefsContext) }
|
||||
@@ -108,7 +123,7 @@ fun PcKeyboard(
|
||||
val rows = PC_KEY_ROWS.map { row -> row.filter { it.code !in hiddenCodes } }.filter { it.isNotEmpty() }
|
||||
|
||||
BoxWithConstraints(Modifier.fillMaxSize(), contentAlignment = Alignment.BottomCenter) {
|
||||
val rowHeight = ((maxHeight * (PcKeyboardPrefs.size / 100f) - 24.dp - 3.dp * rows.size - 10.dp) / rows.size)
|
||||
val rowHeight = ((maxHeight * (heightFraction ?: (PcKeyboardPrefs.size / 100f)) - 24.dp - 3.dp * rows.size - 10.dp) / rows.size)
|
||||
.coerceIn(20.dp, 56.dp)
|
||||
Box(
|
||||
Modifier.fillMaxWidth()
|
||||
@@ -122,9 +137,11 @@ fun PcKeyboard(
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().height(24.dp)) {
|
||||
Text(stringResource(R.string.drawer_pc_keyboard), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurfaceVariant)
|
||||
Spacer(Modifier.weight(1f))
|
||||
HeaderButton(stringResource(R.string.pckb_android), onAndroidKeyboard)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
HeaderButton(stringResource(R.string.pckb_hide), onClose)
|
||||
if (showButtons) {
|
||||
HeaderButton(stringResource(R.string.pckb_android), onAndroidKeyboard)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
HeaderButton(stringResource(R.string.pckb_hide), onClose)
|
||||
}
|
||||
}
|
||||
rows.forEachIndexed { r, row ->
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(3.dp), modifier = Modifier.fillMaxWidth().height(rowHeight)) {
|
||||
@@ -139,7 +156,7 @@ fun PcKeyboard(
|
||||
}
|
||||
key(key.code) {
|
||||
KeyCap(
|
||||
label, key.weight, lit, locked = state == MOD_LOCKED,
|
||||
label, key.weight, lit, locked = state == MOD_LOCKED, hoverFeedback = hoverFeedback,
|
||||
modifier = if (r == 0 && i == 0) Modifier.focusRequester(firstKey) else Modifier,
|
||||
onDown = { press(key) }, onUp = { release(key) },
|
||||
)
|
||||
@@ -154,25 +171,35 @@ fun PcKeyboard(
|
||||
|
||||
@Composable
|
||||
private fun RowScope.KeyCap(
|
||||
label: String, weight: Float, lit: Boolean, locked: Boolean,
|
||||
label: String, weight: Float, lit: Boolean, locked: Boolean, hoverFeedback: Boolean,
|
||||
modifier: Modifier, onDown: () -> Unit, onUp: () -> Unit,
|
||||
) {
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val focused by src.collectIsFocusedAsState()
|
||||
val hovered by src.collectIsHoveredAsState()
|
||||
val (pointedAt, laser) = com.droiddeck.launcher.session.xr.rememberXrPointed()
|
||||
val pointed = hoverFeedback && (hovered || laser.value)
|
||||
var down by remember { mutableStateOf(false) }
|
||||
val fill by animateColorAsState(
|
||||
when {
|
||||
down -> pal.signal.copy(alpha = 0.55f)
|
||||
lit -> pal.signal.copy(alpha = if (locked) 0.45f else 0.28f)
|
||||
pointed -> Color.White.copy(alpha = 0.2f)
|
||||
else -> Color.White.copy(alpha = 0.07f)
|
||||
}, Motion.tw(160), label = "keyFill",
|
||||
}, Motion.tw(if (down) 40 else 160), label = "keyFill",
|
||||
)
|
||||
val scale by animateFloatAsState(
|
||||
if (!hoverFeedback) 1f else if (down) 0.9f else if (pointed) 1.06f else 1f, Motion.tw(if (down) 40 else 140), label = "keyScale",
|
||||
)
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = modifier.weight(weight).fillMaxHeight()
|
||||
.then(pointedAt)
|
||||
.graphicsLayer { scaleX = 1f + (scale - 1f) * size.height / size.width; scaleY = scale }
|
||||
.background(fill, RoundedCornerShape(7.dp))
|
||||
.glideBorder(focused, RoundedCornerShape(7.dp), pal.signal, if (lit) pal.signal.copy(alpha = 0.7f) else Color.White.copy(alpha = 0.12f))
|
||||
.glideBorder(if (hoverFeedback) pointed || down else focused, RoundedCornerShape(7.dp), pal.signal, if (lit) pal.signal.copy(alpha = 0.7f) else Color.White.copy(alpha = 0.12f))
|
||||
.then(if (hoverFeedback) Modifier.hoverable(src) else Modifier)
|
||||
.pointerInput(Unit) {
|
||||
awaitEachGesture {
|
||||
awaitFirstDown().consume()
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.droiddeck.launcher.session.xr
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class XrGestureTest {
|
||||
private fun hand(x: Float, active: Boolean = true) =
|
||||
XrHand(Pose(), Pose(Quat.IDENTITY, Vec3(x, 1.2f, -0.3f)), 0f, 0f, 0f, 0f, 0, active)
|
||||
|
||||
@Test
|
||||
fun holdingTheControllersTogetherFiresAfterTheHold() {
|
||||
val gesture = XrGesture()
|
||||
assertFalse(gesture.update(hand(-0.03f), hand(0.03f), 0))
|
||||
assertEquals(XrGesture.Phase.ARMING, gesture.phase)
|
||||
assertFalse(gesture.update(hand(-0.03f), hand(0.03f), XrGesture.HOLD_MS / 2))
|
||||
assertEquals(0.5f, gesture.progress, 0.01f)
|
||||
assertEquals(0f, gesture.midpoint.x, 1e-6f)
|
||||
assertTrue(gesture.update(hand(-0.03f), hand(0.03f), XrGesture.HOLD_MS))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun pullingApartCancels() {
|
||||
val gesture = XrGesture()
|
||||
gesture.update(hand(-0.03f), hand(0.03f), 0)
|
||||
gesture.update(hand(-0.06f), hand(0.06f), 500)
|
||||
assertEquals(XrGesture.Phase.ARMING, gesture.phase)
|
||||
gesture.update(hand(-0.08f), hand(0.08f), 600)
|
||||
assertEquals(XrGesture.Phase.IDLE, gesture.phase)
|
||||
assertFalse(gesture.update(hand(-0.03f), hand(0.03f), XrGesture.HOLD_MS + 600))
|
||||
assertEquals(0f, gesture.progress, 0f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun itDoesNotFireAgainUntilTheControllersPart() {
|
||||
val gesture = XrGesture()
|
||||
gesture.update(hand(-0.03f), hand(0.03f), 0)
|
||||
assertTrue(gesture.update(hand(-0.03f), hand(0.03f), XrGesture.HOLD_MS))
|
||||
for (t in 1..5) assertFalse(gesture.update(hand(-0.03f), hand(0.03f), XrGesture.HOLD_MS * (t + 1)))
|
||||
gesture.update(hand(-0.2f), hand(0.2f), 20_000)
|
||||
gesture.update(hand(-0.03f), hand(0.03f), 21_000)
|
||||
assertTrue(gesture.update(hand(-0.03f), hand(0.03f), 21_000 + XrGesture.HOLD_MS))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aLostControllerStopsIt() {
|
||||
val gesture = XrGesture()
|
||||
gesture.update(hand(-0.03f), hand(0.03f), 0)
|
||||
assertFalse(gesture.update(hand(-0.03f), hand(0.03f, active = false), XrGesture.HOLD_MS))
|
||||
assertEquals(XrGesture.Phase.IDLE, gesture.phase)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.droiddeck.launcher.session.xr
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
class XrHostTest {
|
||||
private fun buffer(size: Int) = ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder())
|
||||
|
||||
@Test
|
||||
fun readsHandsAtTheNativeOffsets() {
|
||||
val state = buffer(XrHostLayout.STATE_SIZE)
|
||||
state.putInt(8, XrHostLayout.FLAG_FOCUSED or XrHostLayout.FLAG_SURFACE_SWAPCHAIN)
|
||||
state.putLong(16, 42L)
|
||||
XrHost.writePose(state, XrHostLayout.STATE_HEAD, Pose(Quat.IDENTITY, Vec3(0f, 1.6f, 0f)))
|
||||
val right = XrHostLayout.STATE_HANDS + XrHostLayout.HAND_SIZE
|
||||
XrHost.writePose(state, right + XrHostLayout.HAND_AIM, Pose(Quat.IDENTITY, Vec3(0.2f, 1.2f, -0.3f)))
|
||||
state.putFloat(right + XrHostLayout.HAND_TRIGGER, 0.75f)
|
||||
state.putFloat(right + XrHostLayout.HAND_STICK + 4, -0.5f)
|
||||
state.putInt(right + XrHostLayout.HAND_BUTTONS, XrHostLayout.SECONDARY_CLICK)
|
||||
state.putInt(right + XrHostLayout.HAND_ACTIVE, 1)
|
||||
|
||||
val frame = XrHost(state, buffer(XrHostLayout.CONTROL_SIZE)).read()
|
||||
|
||||
assertTrue(frame.focused)
|
||||
assertTrue(frame.surfaces)
|
||||
assertEquals(42L, frame.frame)
|
||||
assertEquals(1.6f, frame.head.position.y, 0f)
|
||||
assertFalse(frame.hands[0].active)
|
||||
val hand = frame.hands[1]
|
||||
assertTrue(hand.active)
|
||||
assertTrue(hand.secondary)
|
||||
assertEquals(0.75f, hand.trigger, 0f)
|
||||
assertEquals(-0.5f, hand.stickY, 0f)
|
||||
assertEquals(Vec3(0.2f, 1.2f, -0.3f), hand.aim.position)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun writesControlAtTheNativeOffsets() {
|
||||
val control = buffer(XrHostLayout.CONTROL_SIZE)
|
||||
val host = XrHost(buffer(XrHostLayout.STATE_SIZE), control)
|
||||
val out = XrControlOut().apply {
|
||||
masks[1] = true
|
||||
lasers[1] = 0.8f
|
||||
haptics[0] = XrHaptic(20, 0.5f)
|
||||
orb = XrControlOut.Orb(Vec3(0f, 1f, -0.5f), 0.04f, 0.25f, 0f)
|
||||
layers += XrLayerOut(3, Pose(Quat.IDENTITY, Vec3(0f, 1.5f, -1f)), 0.9f, 0.6f, order = 2)
|
||||
}
|
||||
host.write(out)
|
||||
|
||||
assertEquals(XrHostLayout.VERSION, control.getInt(0))
|
||||
val right = XrHostLayout.CONTROL_HANDS + XrHostLayout.HAND_CONTROL_SIZE
|
||||
assertEquals(XrHostLayout.MASK_INPUT, control.getInt(right))
|
||||
assertEquals(0.8f, control.getFloat(right + XrHostLayout.HAND_CONTROL_LASER), 0f)
|
||||
assertEquals(0, control.getInt(XrHostLayout.CONTROL_HANDS))
|
||||
val haptic = XrHostLayout.CONTROL_HANDS + XrHostLayout.HAND_CONTROL_HAPTIC
|
||||
assertEquals(1L, control.getLong(haptic))
|
||||
assertEquals(20_000_000L, control.getLong(haptic + 8))
|
||||
assertEquals(1, control.getInt(XrHostLayout.CONTROL_ORB))
|
||||
assertEquals(0.25f, control.getFloat(XrHostLayout.CONTROL_ORB + 4), 0f)
|
||||
val layer = XrHostLayout.CONTROL_LAYERS
|
||||
assertEquals(3, control.getInt(layer))
|
||||
assertEquals(1, control.getInt(layer + 4))
|
||||
assertEquals(2, control.getInt(layer + 12))
|
||||
assertEquals(-1f, control.getFloat(layer + 16 + 24), 0f)
|
||||
assertEquals(0.9f, control.getFloat(layer + 48), 0f)
|
||||
assertEquals(-1, control.getInt(layer + XrHostLayout.LAYER_SIZE))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aHapticIsSentOnceAndTheNextGetsANewId() {
|
||||
val control = buffer(XrHostLayout.CONTROL_SIZE)
|
||||
val host = XrHost(buffer(XrHostLayout.STATE_SIZE), control)
|
||||
val haptic = XrHostLayout.CONTROL_HANDS + XrHostLayout.HAND_CONTROL_HAPTIC
|
||||
host.write(XrControlOut().apply { haptics[0] = XrHaptic(10, 0.3f) })
|
||||
host.write(XrControlOut())
|
||||
assertEquals(1L, control.getLong(haptic))
|
||||
host.write(XrControlOut().apply { haptics[0] = XrHaptic(10, 0.3f) })
|
||||
assertEquals(2L, control.getLong(haptic))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
package com.droiddeck.launcher.session.xr
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class XrInteractionTest {
|
||||
private val head = Pose(Quat.IDENTITY, Vec3(0f, 1.6f, 0f))
|
||||
|
||||
/** A panel 1 m ahead facing the user, 1 m wide and 0.6 m high. */
|
||||
private fun panel(kind: XrPanelKind = XrPanelKind.MENU, z: Float = -1f) =
|
||||
XrPanelState(kind, Pose(Quat.IDENTITY, Vec3(0f, 1.6f, z)), 1f, 0.6f)
|
||||
|
||||
/** A controller at the head's height pointing straight ahead at ([x], [y]) on the panel's plane. */
|
||||
private fun aim(x: Float = 0f, y: Float = 0f, trigger: Float = 0f, squeeze: Float = 0f, stickY: Float = 0f,
|
||||
buttons: Int = 0, active: Boolean = true) =
|
||||
XrHand(Pose(), Pose(Quat.IDENTITY, Vec3(x, 1.6f + y, 0f)), trigger, squeeze, 0f, stickY, buttons, active)
|
||||
|
||||
private val idle = XrHand.IDLE
|
||||
|
||||
@Test
|
||||
fun aRayHitsThePanelInItsPixels() {
|
||||
val panel = panel()
|
||||
val hit = panel.hit(aim(0.25f, 0.15f).aim)
|
||||
assertNotNull(hit)
|
||||
assertEquals(1f, hit!!.distance, 1e-4f)
|
||||
assertEquals(panel.pixelWidth * 0.75f, panel.pixelX(hit.x), 0.5f)
|
||||
assertEquals(panel.pixelHeight * 0.25f, panel.pixelY(hit.y), 0.5f)
|
||||
assertNull(panel.hit(aim(0.7f).aim))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aPanelBehindTheControllerOrSeenFromBehindIsMissed() {
|
||||
assertNull(panel(z = 1f).hit(aim().aim))
|
||||
val turned = XrPanelState(XrPanelKind.MENU, Pose(Quat.yaw(Math.PI.toFloat()), Vec3(0f, 1.6f, -1f)), 1f, 0.6f)
|
||||
assertNull(turned.hit(aim().aim))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theNearestPanelTakesTheRay() {
|
||||
val far = panel(z = -2f)
|
||||
val near = panel(z = -1f)
|
||||
val out = XrInteraction().update(head, listOf(aim(trigger = 0f), idle), listOf(far, near), 0.014f)
|
||||
assertTrue(out.cursors.containsKey(near))
|
||||
assertFalse(out.cursors.containsKey(far))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun onlyTheControllerPointingAtAPanelIsTakenFromTheGame() {
|
||||
val panel = panel()
|
||||
val away = XrHand(Pose(), Pose(Quat.yaw(Math.PI.toFloat()), Vec3(0f, 1.6f, 0f)), 0f, 0f, 0f, 0f, 0, true)
|
||||
val out = XrInteraction().update(head, listOf(away, aim()), listOf(panel), 0.014f)
|
||||
assertFalse(out.masks[0])
|
||||
assertEquals(0f, out.lasers[0], 0f)
|
||||
assertTrue(out.masks[1])
|
||||
assertEquals(1f, out.lasers[1], 1e-4f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theTriggerPressesMovesAndReleases() {
|
||||
val panel = panel()
|
||||
val interaction = XrInteraction()
|
||||
val down = interaction.update(head, listOf(aim(0f, 0f, trigger = 0.9f), idle), listOf(panel), 0.014f)
|
||||
assertTrue(down.events.single() is XrPointerEvent.Down)
|
||||
val moved = interaction.update(head, listOf(aim(0.1f, 0f, trigger = 0.5f), idle), listOf(panel), 0.014f)
|
||||
assertTrue(moved.events.single() is XrPointerEvent.Move)
|
||||
assertTrue(moved.masks[0])
|
||||
val up = interaction.update(head, listOf(aim(0.1f, 0f, trigger = 0.1f), idle), listOf(panel), 0.014f)
|
||||
val release = up.events.single() as XrPointerEvent.Up
|
||||
assertEquals(panel.pixelWidth * 0.6f, release.x, 0.5f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aHeldPressFollowsTheRayOffThePanelAndAlostControllerCancels() {
|
||||
val panel = panel()
|
||||
val interaction = XrInteraction()
|
||||
interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(panel), 0.014f)
|
||||
val off = interaction.update(head, listOf(aim(0.9f, trigger = 0.9f), idle), listOf(panel), 0.014f)
|
||||
assertTrue((off.events.single() as XrPointerEvent.Move).x >= panel.pixelWidth - 0.5f)
|
||||
assertTrue(off.masks[0])
|
||||
val lost = interaction.update(head, listOf(aim(active = false), idle), listOf(panel), 0.014f)
|
||||
assertTrue(lost.events.single() is XrPointerEvent.Cancel)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theStickScrollsAndBGoesBack() {
|
||||
val panel = panel()
|
||||
val interaction = XrInteraction()
|
||||
val scroll = interaction.update(head, listOf(aim(stickY = 1f), idle), listOf(panel), 0.1f)
|
||||
assertTrue((scroll.events.single() as XrPointerEvent.Scroll).amount > 0f)
|
||||
val back = interaction.update(head, listOf(aim(buttons = XrHostLayout.SECONDARY_CLICK), idle), listOf(panel), 0.014f)
|
||||
assertTrue(back.events.single() is XrPointerEvent.Back)
|
||||
val held = interaction.update(head, listOf(aim(buttons = XrHostLayout.SECONDARY_CLICK), idle), listOf(panel), 0.014f)
|
||||
assertTrue(held.events.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun gripCarriesThePanelAndTheStickPushesItAway() {
|
||||
val panel = panel()
|
||||
val interaction = XrInteraction()
|
||||
interaction.update(head, listOf(aim(squeeze = 0.9f), idle), listOf(panel), 0.014f)
|
||||
interaction.update(head, listOf(aim(0.3f, 0.1f, squeeze = 0.9f), idle), listOf(panel), 0.014f)
|
||||
assertEquals(0.3f, panel.pose.position.x, 1e-4f)
|
||||
assertEquals(1.7f, panel.pose.position.y, 1e-4f)
|
||||
val before = panel.pose.position.z
|
||||
repeat(10) { interaction.update(head, listOf(aim(0.3f, 0.1f, squeeze = 0.9f, stickY = 1f), idle), listOf(panel), 0.1f) }
|
||||
assertTrue(panel.pose.position.z < before)
|
||||
repeat(200) { interaction.update(head, listOf(aim(0.3f, 0.1f, squeeze = 0.9f, stickY = 1f), idle), listOf(panel), 0.1f) }
|
||||
assertTrue((panel.pose.position - Vec3(0.3f, 1.7f, 0f)).length <= XrUnits.MAX_DISTANCE + 1e-3f)
|
||||
val dropped = interaction.update(head, listOf(aim(0.3f, 0.1f), idle), listOf(panel), 0.014f)
|
||||
assertTrue(dropped.events.single() is XrPointerEvent.Moved)
|
||||
val facingHead = panel.pose.orientation.rotate(Vec3(0f, 0f, 1f))
|
||||
val toHead = (head.position - panel.pose.position).let { Vec3(it.x, 0f, it.z).normalized() }
|
||||
assertEquals(1f, facingHead dot toHead, 1e-3f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theBottomBarCarriesThePanelButItsButtonIsClicked() {
|
||||
val panel = panel()
|
||||
val interaction = XrInteraction()
|
||||
val barY = -0.3f + XrUnits.BAR_METRES / 2f
|
||||
val bar = interaction.update(head, listOf(aim(0.1f, barY, trigger = 0.9f), idle), listOf(panel), 0.014f)
|
||||
assertTrue(bar.events.isEmpty())
|
||||
interaction.update(head, listOf(aim(0.2f, barY, trigger = 0.9f), idle), listOf(panel), 0.014f)
|
||||
assertEquals(0.1f, panel.pose.position.x, 1e-4f)
|
||||
interaction.update(head, listOf(aim(0.2f, barY), idle), listOf(panel), 0.014f)
|
||||
|
||||
val chat = panel(XrPanelKind.PET_CHAT)
|
||||
val button = XrInteraction().update(head, listOf(aim(-0.48f, barY, trigger = 0.9f), idle), listOf(chat), 0.014f)
|
||||
assertTrue(button.events.single() is XrPointerEvent.Down)
|
||||
|
||||
val menu = panel()
|
||||
val noButton = XrInteraction().update(head, listOf(aim(-0.48f, barY, trigger = 0.9f), idle), listOf(menu), 0.014f)
|
||||
assertTrue(noButton.events.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theCornerResizesWithTheTopLeftCornerFixed() {
|
||||
val panel = panel()
|
||||
val interaction = XrInteraction()
|
||||
interaction.update(head, listOf(aim(0.48f, -0.28f, trigger = 0.9f), idle), listOf(panel), 0.014f)
|
||||
assertEquals(1f, panel.width, 1e-4f)
|
||||
assertEquals(0.6f, panel.height, 1e-4f)
|
||||
interaction.update(head, listOf(aim(0.78f, -0.48f, trigger = 0.9f), idle), listOf(panel), 0.014f)
|
||||
assertEquals(1.3f, panel.width, 1e-3f)
|
||||
assertEquals(0.8f, panel.height, 1e-3f)
|
||||
assertEquals(-0.5f, panel.pose.position.x - panel.width / 2f, 1e-3f)
|
||||
assertEquals(1.9f, panel.pose.position.y + panel.height / 2f, 1e-3f)
|
||||
interaction.update(head, listOf(aim(-2f, 2f, trigger = 0.9f), idle), listOf(panel), 0.014f)
|
||||
assertEquals(XrUnits.MIN_METRES, panel.width, 1e-4f)
|
||||
assertEquals(XrUnits.MIN_METRES, panel.height, 1e-4f)
|
||||
val done = interaction.update(head, listOf(aim(-2f, 2f), idle), listOf(panel), 0.014f)
|
||||
assertTrue(done.events.single() is XrPointerEvent.Resized)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun thePetHeadClicksOrIsDragged() {
|
||||
val head0 = XrPanelState(XrPanelKind.PET_HEAD, Pose(Quat.IDENTITY, Vec3(0f, 1.6f, -1f)), 0.12f, 0.12f)
|
||||
val interaction = XrInteraction()
|
||||
interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(head0), 0.014f)
|
||||
val click = interaction.update(head, listOf(aim(), idle), listOf(head0), 0.014f)
|
||||
assertTrue(click.events.single() is XrPointerEvent.Click)
|
||||
|
||||
interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(head0), 0.014f)
|
||||
interaction.update(head, listOf(aim(0.05f, trigger = 0.9f), idle), listOf(head0), 0.014f)
|
||||
interaction.update(head, listOf(aim(0.2f, trigger = 0.9f), idle), listOf(head0), 0.014f)
|
||||
assertEquals(0.2f, head0.pose.position.x, 1e-3f)
|
||||
val dropped = interaction.update(head, listOf(aim(0.2f), idle), listOf(head0), 0.014f)
|
||||
assertTrue(dropped.events.single() is XrPointerEvent.Moved)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aClosingPanelLetsGo() {
|
||||
val panel = panel()
|
||||
val interaction = XrInteraction()
|
||||
interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(panel), 0.014f)
|
||||
val out = XrInteractionOut()
|
||||
interaction.release(panel, out)
|
||||
assertTrue(out.events.single() is XrPointerEvent.Cancel)
|
||||
assertFalse(interaction.holding(panel))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aReleaseAimedAwayFromThePanelCancels() {
|
||||
val panel = panel()
|
||||
val interaction = XrInteraction()
|
||||
interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(panel), 0.014f)
|
||||
val away = XrHand(Pose(), Pose(Quat.yaw(Math.PI.toFloat()), Vec3(0f, 1.6f, 0f)), 0f, 0f, 0f, 0f, 0, true)
|
||||
val out = interaction.update(head, listOf(away, idle), listOf(panel), 0.014f)
|
||||
assertTrue(out.events.single() is XrPointerEvent.Cancel)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aPanelOneControllerHoldsCannotBeTakenByTheOther() {
|
||||
val panel = panel()
|
||||
val interaction = XrInteraction()
|
||||
interaction.update(head, listOf(aim(0.48f, -0.28f, trigger = 0.9f), idle), listOf(panel), 0.014f)
|
||||
interaction.update(head, listOf(aim(0.48f, -0.28f, trigger = 0.9f), aim(squeeze = 0.9f)), listOf(panel), 0.014f)
|
||||
val out = interaction.update(head, listOf(aim(0.48f, -0.28f, trigger = 0.9f), aim(0.3f, squeeze = 0.9f)), listOf(panel), 0.014f)
|
||||
assertEquals(0f, panel.pose.position.x, 1e-3f)
|
||||
assertTrue(out.events.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun losingFocusCancelsAndAButtonStillHeldNeedsANewPress() {
|
||||
val panel = panel()
|
||||
val interaction = XrInteraction()
|
||||
interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(panel), 0.014f)
|
||||
val out = XrInteractionOut()
|
||||
interaction.cancel(out)
|
||||
assertTrue(out.events.single() is XrPointerEvent.Cancel)
|
||||
assertFalse(interaction.holding(panel))
|
||||
val stillHeld = interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(panel), 0.014f)
|
||||
assertTrue(stillHeld.events.isEmpty())
|
||||
interaction.update(head, listOf(aim(), idle), listOf(panel), 0.014f)
|
||||
val pressed = interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(panel), 0.014f)
|
||||
assertTrue(pressed.events.single() is XrPointerEvent.Down)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun bothControllersPressOnePanelAtOnce() {
|
||||
val panel = panel()
|
||||
val interaction = XrInteraction()
|
||||
val first = interaction.update(head, listOf(aim(-0.2f, trigger = 0.9f), aim(0.2f)), listOf(panel), 0.014f)
|
||||
assertEquals(2, first.cursors.getValue(panel).size)
|
||||
assertEquals(0, (first.events.single() as XrPointerEvent.Down).hand)
|
||||
val second = interaction.update(head, listOf(aim(-0.2f, trigger = 0.9f), aim(0.2f, trigger = 0.9f)), listOf(panel), 0.014f)
|
||||
assertEquals(1, (second.events.single() as XrPointerEvent.Down).hand)
|
||||
val up = interaction.update(head, listOf(aim(-0.2f, trigger = 0.9f), aim(0.2f)), listOf(panel), 0.014f)
|
||||
assertEquals(1, (up.events.single() as XrPointerEvent.Up).hand)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun lettingGoOfThePetHeadOffItIsNoClick() {
|
||||
val pet = XrPanelState(XrPanelKind.PET_HEAD, Pose(Quat.IDENTITY, Vec3(0f, 1.6f, -1f)), 0.12f, 0.12f)
|
||||
val interaction = XrInteraction()
|
||||
interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(pet), 0.014f)
|
||||
val away = XrHand(Pose(), Pose(Quat.yaw(Math.PI.toFloat()), Vec3(0f, 1.6f, 0f)), 0f, 0f, 0f, 0f, 0, true)
|
||||
val out = interaction.update(head, listOf(away, idle), listOf(pet), 0.014f)
|
||||
assertTrue(out.events.isEmpty())
|
||||
assertFalse(interaction.holding(pet))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package com.droiddeck.launcher.session.xr
|
||||
|
||||
import android.content.Context
|
||||
import android.view.Surface
|
||||
import org.junit.After
|
||||
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.RuntimeEnvironment
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.shadows.ShadowBuild
|
||||
import java.nio.ByteBuffer
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33], manifest = Config.NONE)
|
||||
class XrPanelsGateTest {
|
||||
private val layers = object : XrLayerSource {
|
||||
override val context: Context get() = RuntimeEnvironment.getApplication()
|
||||
override fun createLayer(width: Int, height: Int) = -1
|
||||
override fun layerSurface(id: Int): Surface? = null
|
||||
override fun destroyLayer(id: Int) = Unit
|
||||
override fun setOrbImage(image: android.graphics.Bitmap) = Unit
|
||||
override fun leave() = Unit
|
||||
}
|
||||
|
||||
private fun attach() = XrPanels.attach(
|
||||
layers, ByteBuffer.allocateDirect(XrHostLayout.STATE_SIZE), ByteBuffer.allocateDirect(XrHostLayout.CONTROL_SIZE),
|
||||
)
|
||||
|
||||
@After
|
||||
fun detach() = XrPanels.detach()
|
||||
|
||||
@Test
|
||||
fun onlyAQuestInTheImmersiveViewOpensTheGate() {
|
||||
assertTrue(XrPanels.gateOpen("Quest 3", "eureka", "Oculus", immersive = true))
|
||||
assertTrue(XrPanels.gateOpen("Quest 3S", "panther", "Oculus", immersive = true))
|
||||
assertFalse(XrPanels.gateOpen("Quest 3", "eureka", "Oculus", immersive = false))
|
||||
assertFalse(XrPanels.gateOpen("BKQ_N49", "BKQ", "HONOR", immersive = true))
|
||||
assertFalse(XrPanels.gateOpen("Pixel 9", "tokay", "Google", immersive = true))
|
||||
assertFalse(XrPanels.gateOpen("Rift", "rift", "Oculus", immersive = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun offQuestTheMenuStaysInTheSessionWindow() {
|
||||
ShadowBuild.setModel("BKQ_N49")
|
||||
ShadowBuild.setDevice("BKQ")
|
||||
ShadowBuild.setManufacturer("HONOR")
|
||||
attach()
|
||||
assertFalse(XrPanels.immersiveActive)
|
||||
assertFalse(XrPanels.showMenu())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun onQuestTheImmersiveViewTakesTheMenu() {
|
||||
ShadowBuild.setModel("Quest 3")
|
||||
ShadowBuild.setDevice("eureka")
|
||||
ShadowBuild.setManufacturer("Oculus")
|
||||
assertFalse(XrPanels.showMenu())
|
||||
attach()
|
||||
assertTrue(XrPanels.immersiveActive)
|
||||
assertTrue(XrPanels.showMenu())
|
||||
XrPanels.detach()
|
||||
assertFalse(XrPanels.immersiveActive)
|
||||
assertFalse(XrPanels.showMenu())
|
||||
}
|
||||
|
||||
private class Host : XrMenuHost {
|
||||
val immersive = mutableListOf<Boolean>()
|
||||
@androidx.compose.runtime.Composable
|
||||
override fun XrMenuContent() = Unit
|
||||
override fun xrSetMenuOpen(open: Boolean) = Unit
|
||||
override fun xrMenuBack() = Unit
|
||||
override fun xrSendKey(code: Int, down: Boolean) = Unit
|
||||
override fun xrTypeText(text: String) = Unit
|
||||
override fun xrTapKey(keyCode: Int) = Unit
|
||||
override fun xrImmersiveChanged(active: Boolean) { immersive += active }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aFocusChangeInTheImmersiveViewSizesSteamsScreenAgain() {
|
||||
ShadowBuild.setModel("Quest 3")
|
||||
ShadowBuild.setDevice("eureka")
|
||||
ShadowBuild.setManufacturer("Oculus")
|
||||
val host = Host()
|
||||
XrPanels.setMenuHost(host)
|
||||
try {
|
||||
attach()
|
||||
settle()
|
||||
val opened = host.immersive.size
|
||||
assertTrue(opened >= 1 && host.immersive.all { it })
|
||||
com.droiddeck.launcher.agent.AgentGuest.focusRevision++
|
||||
settle()
|
||||
assertTrue(host.immersive.size > opened)
|
||||
assertTrue(host.immersive.all { it })
|
||||
XrPanels.detach()
|
||||
val left = host.immersive.size
|
||||
com.droiddeck.launcher.agent.AgentGuest.focusRevision++
|
||||
settle()
|
||||
assertEquals(false, host.immersive.last())
|
||||
assertEquals(left, host.immersive.size)
|
||||
} finally {
|
||||
XrPanels.clearMenuHost(host)
|
||||
}
|
||||
}
|
||||
|
||||
private fun settle() {
|
||||
androidx.compose.runtime.snapshots.Snapshot.sendApplyNotifications()
|
||||
org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.droiddeck.launcher.session.xr
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class XrPcTextTest {
|
||||
private class Field : XrKeyTarget {
|
||||
val text = StringBuilder()
|
||||
var entered = 0
|
||||
override fun type(text: String) { this.text.append(text) }
|
||||
override fun backspace() { if (text.isNotEmpty()) text.setLength(text.length - 1) }
|
||||
override fun enter() { entered++ }
|
||||
}
|
||||
|
||||
private fun XrPcText.tap(code: Int) { key(code, true); key(code, false) }
|
||||
|
||||
@Test
|
||||
fun pcKeysTypeIntoAPanelField() {
|
||||
val field = Field()
|
||||
val keys = XrPcText(field)
|
||||
keys.key(42, true); keys.tap(35); keys.key(42, false)
|
||||
keys.tap(18); keys.tap(57); keys.key(54, true); keys.tap(2); keys.key(54, false)
|
||||
assertEquals("He !", field.text.toString())
|
||||
keys.tap(58); keys.tap(30); keys.tap(58); keys.tap(30)
|
||||
assertEquals("He !Aa", field.text.toString())
|
||||
keys.tap(14); keys.tap(28)
|
||||
assertEquals("He !A", field.text.toString())
|
||||
assertEquals(1, field.entered)
|
||||
}
|
||||
|
||||
private class FakeTimer : XrTimer {
|
||||
var pending: (() -> Unit)? = null
|
||||
override fun after(ms: Long, action: () -> Unit): () -> Unit {
|
||||
pending = action
|
||||
return { if (pending === action) pending = null }
|
||||
}
|
||||
fun fire() = pending!!.invoke()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun holdingBackspaceKeepsDeletingUntilItIsLetGo() {
|
||||
val field = Field().apply { text.append("hello") }
|
||||
val timer = FakeTimer()
|
||||
val keys = XrPcText(field, timer)
|
||||
keys.key(14, true)
|
||||
assertEquals("hell", field.text.toString())
|
||||
timer.fire(); timer.fire()
|
||||
assertEquals("he", field.text.toString())
|
||||
keys.key(14, false)
|
||||
assertEquals(null, timer.pending)
|
||||
assertEquals("he", field.text.toString())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anotherKeyLetGoLeavesBackspaceRepeating() {
|
||||
val field = Field().apply { text.append("hello") }
|
||||
val timer = FakeTimer()
|
||||
val keys = XrPcText(field, timer)
|
||||
keys.key(14, true)
|
||||
keys.key(30, false)
|
||||
timer.fire()
|
||||
assertEquals("hel", field.text.toString())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun keysWithNoCharacterTypeNothing() {
|
||||
val field = Field()
|
||||
val keys = XrPcText(field)
|
||||
for (code in listOf(1, 59, 29, 56, 103, 105, 15, 111)) keys.tap(code)
|
||||
assertEquals("", field.text.toString())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.droiddeck.launcher.session.xr
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Test
|
||||
|
||||
class XrPlacementTest {
|
||||
@Test
|
||||
fun aPanelComesBackAtTheSamePlaceRelativeToWhereTheUserFaces() {
|
||||
val head = Pose(Quat.yaw(0.4f), Vec3(0.5f, 1.6f, 0.2f))
|
||||
val placed = XrPlacement.place(XrPanelKind.MENU, head, yaw = 0.3f, distance = 1.1f, dy = -0.2f)
|
||||
val (yaw, distance, dy) = XrPlacement.relative(head, placed.position)
|
||||
assertEquals(0.3f, yaw, 1e-4f)
|
||||
assertEquals(1.1f, distance, 1e-4f)
|
||||
assertEquals(-0.2f, dy, 1e-4f)
|
||||
|
||||
val turned = Pose(Quat.yaw(1.4f), Vec3(-1f, 1.5f, 3f))
|
||||
val again = XrPlacement.place(XrPanelKind.MENU, turned, yaw, distance, dy)
|
||||
val (yaw2, distance2, dy2) = XrPlacement.relative(turned, again.position)
|
||||
assertEquals(yaw, yaw2, 1e-4f)
|
||||
assertEquals(distance, distance2, 1e-4f)
|
||||
assertEquals(dy, dy2, 1e-4f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aPlacedPanelFacesTheHead() {
|
||||
val head = Pose(Quat.yaw(-0.8f), Vec3(0f, 1.6f, 0f))
|
||||
val placed = XrPlacement.place(XrPanelKind.MENU, head, yaw = 0.5f, distance = 0.9f, dy = 0f)
|
||||
val front = placed.orientation.rotate(Vec3(0f, 0f, 1f))
|
||||
val toHead = (head.position - placed.position).normalized()
|
||||
assertEquals(1f, front dot toHead, 1e-4f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun straightAheadIsStraightAhead() {
|
||||
val placed = XrPlacement.place(XrPanelKind.MENU, Pose(Quat.IDENTITY, Vec3(0f, 1.6f, 0f)), 0f, 1f, 0f)
|
||||
assertEquals(0f, placed.position.x, 1e-5f)
|
||||
assertEquals(-1f, placed.position.z, 1e-5f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theKeyboardLeansBackLikeOneOnADeskAndStillTakesTheLaser() {
|
||||
val head = Pose(Quat.yaw(0.6f), Vec3(0f, 1.6f, 0f))
|
||||
val placed = XrPlacement.place(XrPanelKind.KEYBOARD, head, yaw = 0f, distance = 0.5f, dy = -0.5f)
|
||||
val front = placed.orientation.rotate(Vec3(0f, 0f, 1f))
|
||||
val level = (head.position - placed.position).let { Vec3(it.x, 0f, it.z).normalized() }
|
||||
assertEquals(0.7071f, front.y, 1e-3f)
|
||||
assertEquals(0.7071f, front dot level, 1e-3f)
|
||||
|
||||
val keyboard = XrPanelState(XrPanelKind.KEYBOARD, placed, 0.8f, 0.36f)
|
||||
val hand = placed.position + Vec3(0f, 0.25f, 0f) + level * 0.15f
|
||||
val down = (placed.position - hand).normalized()
|
||||
val aim = Pose(rotationFromForward(down), hand)
|
||||
val hit = keyboard.hit(aim)
|
||||
assertNotNull(hit)
|
||||
assertEquals(0f, hit!!.x, 1e-3f)
|
||||
assertEquals(0f, hit.y, 1e-3f)
|
||||
}
|
||||
|
||||
private fun rotationFromForward(direction: Vec3): Quat {
|
||||
val axis = Vec3.FORWARD cross direction
|
||||
val angle = kotlin.math.acos((Vec3.FORWARD dot direction).coerceIn(-1f, 1f))
|
||||
val unit = axis.normalized()
|
||||
val s = kotlin.math.sin(angle / 2f)
|
||||
return Quat(unit.x * s, unit.y * s, unit.z * s, kotlin.math.cos(angle / 2f))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.droiddeck.launcher.session.xr
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class XrSteamScreenTest {
|
||||
@Test fun steamAndSteamVrAloneAreSteamsScreen() {
|
||||
assertTrue(XrSteamScreen.shown(250820L, listOf(769L, 250820L)))
|
||||
assertTrue(XrSteamScreen.shown(0L, listOf(769L)))
|
||||
}
|
||||
|
||||
@Test fun aRunningGameKeepsItFlatEvenWithSteamVrFocused() {
|
||||
assertFalse(XrSteamScreen.shown(250820L, listOf(769L, 250820L, 1245620L)))
|
||||
assertFalse(XrSteamScreen.shown(1245620L, null))
|
||||
}
|
||||
|
||||
@Test fun aReportWithNoFocusIsUnknown() {
|
||||
assertFalse(XrSteamScreen.shown(null, null))
|
||||
assertFalse(XrSteamScreen.shown(null, emptyList()))
|
||||
assertFalse(XrSteamScreen.shown(0L, emptyList()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
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
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33], manifest = Config.NONE)
|
||||
class AgentPetQuestTest {
|
||||
@Test
|
||||
fun phonesKeepTheFloatingPetAndItsChat() {
|
||||
assertTrue(AgentPet.usesOverlayWindows(quest = false))
|
||||
assertFalse(AgentPet.chatInOwnWindow(quest = false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun questUsesNoOverlayWindowsAndOpensTheChatAsItsOwnPanel() {
|
||||
assertFalse(AgentPet.usesOverlayWindows(quest = true))
|
||||
assertTrue(AgentPet.chatInOwnWindow(quest = true))
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,7 @@ else
|
||||
python3 "$here/axml_rename.py" "$in" "$work/renamed.apk" \
|
||||
"$P=$pkg" "$P.androidx-startup=$pkg.androidx-startup" "$P.logs=$pkg.logs" \
|
||||
"$P.pairingguide=$pkg.pairingguide" "$P.devicecode=$pkg.devicecode" "$P.pin=$pkg.pin" \
|
||||
"$P.documents=$pkg.documents" "$P.home=$pkg.home" "$P.agent=$pkg.agent" \
|
||||
"$P.documents=$pkg.documents" "$P.home=$pkg.home" "$P.agent=$pkg.agent" "$P.agentchat=$pkg.agentchat" \
|
||||
"$P.vr_recovery=$pkg.vr_recovery" "$P.dualscreen=$pkg.dualscreen" "$P.typing=$pkg.typing" "$P.keeptop=$pkg.keeptop" \
|
||||
"$P.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION=$pkg.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION"
|
||||
fi
|
||||
|
||||
Reference in new issue
Block a user