6 Commits
Author SHA1 Message Date
Pixelplanet 22ed9e1ede fix(install): support case-insensitive Shortcuts key in shortcuts.vdf and copy install.sh from unpacked tarball 2026-10-17 20:55:13 +02:00
Pixelplanet 7987fffed4 feat(vault): hidden vault, file actions submenu, dual controller models, and display sharpness
- Add Hidden Vault system:
  - Secure directory storage under ~/.pixelvr_vault with 0700 permissions.
  - Cheat-code combo unlocking triggered on full grip squeeze (A-B-B-A-X-Y default, customizable).
  - Headset removal / face detection gating and inactivity auto-lock.
  - Automatic download history clearing upon vault lock.
- Add File Actions Submenu (Button Y):
  - In-browser file/folder submenu with Move to Vault, Delete, Move, and Rename.
  - Recursive folder move to vault with collision handling.
  - Folder deletion with confirmation dialog.
- Enhance VR controllers and interactions:
  - Dynamic left and right Steam Frame controller render models.
  - Single laser pointer priority with hand swapping via full grip squeeze.
- Fix video format detection:
  - Correct auto-detection and default projection for high-resolution VR180 SBS media (e.g. 7200x3600).
- Visual sharpness & rendering stability:
  - Render swapchain at native 2160x2160 per eye.
  - SDF font rendering with RMS pixel footprint and stem darkening.
  - Razor-sharp procedural UI anti-aliasing and crisp border highlights without distortion.
- Add unit test suite (tests/test_vault.cpp) and documentation specs.
2026-10-17 18:06:19 +02:00
PixelplanetandCopilot 858293663b feat(install): one-command installer with automatic Steam library entry
Users can now install with a single command, either piped or from the
release tarball:

  curl -fsSL .../tools/install.sh | sh
  ./install.sh

Tools/install.sh downloads the latest (or a pinned) ARM64 release, verifies
the published checksum, installs to ~/PixelVRPlayer, and registers
"Pixel VR Player" as a Non-Steam Game by editing shortcuts.vdf through an
embedded binary-KeyValues helper (existing shortcuts are preserved, the file
is backed up, and unsupported files are left untouched). Options cover
--dir, --version, --no-steam, --restart-steam and --uninstall. Upgrades never
touch ~/.config/pixelvr or ~/.cache/pixelvr.

Also:
- package-release.sh ships install.sh and a VERSION file in the tarball.
- The release workflow publishes .sha256 checksums and syntax-checks the
  installer before building.
- Docs describe the one-command path for end users.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-17 10:16:06 +02:00
PixelplanetandCopilot 6f9a9ac6b5 feat(ui): unified spatial UI with video thumbnails and richer settings
- Add ThumbnailCache: a worker thread extracts 256x144 thumbnails and media
  metadata with FFmpeg, SBS-aware cropping, and an on-disk cache under
  ~/.cache/pixelvr/thumbs.
- Draw thumbnails on browser cards through a new rounded-corner thumb.frag
  pipeline with per-card descriptor sets.
- Redesign the browser as a sidebar + card grid, with horizontal stick
  navigation and direct shortcuts to Network/Home/Videos/Downloads/Drives.
- Expand Settings: screen curvature, UI text scale and colour, accent colour
  and UI distance, organised into sections.
- Downloads window: per-job state, progress, speed and ETA, plus pause/resume
  and cancel-active controls.
- Decoder: multi-threaded software decode and four V4L2 output buffers.
- docs: unified UI concept, redesign plan and mockups.

Release packaging is now reproducible: tools/run.sh is the shipped launcher,
tools/package-release.sh assembles the tarball, and a GitHub Actions workflow
builds it natively on ARM64 for every v* tag. Stop committing release tarballs;
they are attached to releases instead.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-17 09:55:48 +02:00
Pixelplanet ee95d79efe feat(input): trigger selects in the browser, grip toggles the laser, downloads window replaces the browser
- Restore trigger-to-select in the file browser (it is the intuitive gesture);
  A remains an alternative for thumbstick/d-pad navigation. Both skip when the
  laser is resting on a control-bar button, which owns that click.
- Grip now toggles that hand's laser pointer, SteamVR-style: turn one off to
  drive a panel with the stick without the beam fighting it, and to pick the
  pointing hand. The raycast and the beam both honour it per hand.
- Recenter moves from Grip to Bumper (saved grip bindings migrate), since Grip
  is now the laser toggle.
- The downloads window replaces the browser panel instead of stacking over it,
  and browser input is suspended while it (or the confirm dialog) is open.
2026-10-15 20:52:38 +02:00
Pixelplanet e39fd5e77c feat(input): X/Y download buttons; bar clickable with A; Downloads window opens over the browser
- X (or Y) downloads the entry highlighted in the browser. A dedicated
  physical button means the trigger never has to double as a pointer click.
- The control bar now accepts A as well as the trigger, and A prefers the
  pointed-at bar button over the browser entry, so the bar always works.
- The downloads window was gated on !browser_.isOpen(), so pressing its bar
  button while browsing appeared to do nothing; it now opens over the browser.
- Log control-bar clicks to make input routing diagnosable.
2026-10-15 20:35:23 +02:00
48 changed files with 6770 additions and 1097 deletions

No files matched your search

+88
View File
@@ -0,0 +1,88 @@
name: Release
on:
push:
tags: ["v*"]
workflow_dispatch:
inputs:
tag:
description: "Existing v* tag to publish (leave empty for a build-only run)"
required: false
default: ""
permissions:
contents: write
jobs:
build:
name: Build Steam Frame ARM64 release
# Native aarch64 runner: no cross-toolchain or device sysroot needed.
# Debian 13 (trixie) ships FFmpeg 7, matching the SONAMEs present on the
# Steam Frame (libavcodec.so.61, libavutil.so.59, ...).
runs-on: ubuntu-24.04-arm
container: debian:trixie
steps:
- name: Install build dependencies
run: |
apt-get update
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
build-essential cmake ninja-build git ca-certificates pkg-config file \
glslang-tools libvulkan-dev \
libavcodec-dev libavformat-dev libavutil-dev libswscale-dev libswresample-dev \
libpulse-dev libfreetype-dev libsmbclient-dev \
libx11-dev libxrandr-dev libxxf86vm-dev libgl-dev
- uses: actions/checkout@v4
with:
ref: ${{ inputs.tag || github.ref }}
fetch-depth: 1
- name: Check scripts
run: |
set -eux
sh -n tools/install.sh
bash -n tools/package-release.sh
bash -n tools/build.sh
- name: Build
run: bash tools/build.sh
- name: Package
run: |
set -eux
tag="${{ inputs.tag || github.ref_name }}"
bash tools/package-release.sh build pixelvr-linux-arm64.tar.gz "${tag}"
cp pixelvr-linux-arm64.tar.gz "pixelvr-linux-arm64-${tag}.tar.gz"
sha256sum pixelvr-linux-arm64.tar.gz > pixelvr-linux-arm64.tar.gz.sha256
sha256sum "pixelvr-linux-arm64-${tag}.tar.gz" > "pixelvr-linux-arm64-${tag}.tar.gz.sha256"
- name: Verify artifact
run: |
file build/bin/pixelvr
file build/bin/pixelvr | grep -q 'ARM aarch64'
tar -tzf pixelvr-linux-arm64.tar.gz | grep -q '^PixelVRPlayer/run.sh$'
tar -tzf pixelvr-linux-arm64.tar.gz | grep -q '^PixelVRPlayer/install.sh$'
tar -tzf pixelvr-linux-arm64.tar.gz | grep -q '^PixelVRPlayer/VERSION$'
tar -tzf pixelvr-linux-arm64.tar.gz | grep -q '/shaders/thumb.frag.spv$'
sha256sum -c pixelvr-linux-arm64.tar.gz.sha256
- name: Upload build artifact
uses: actions/upload-artifact@v4
with:
name: pixelvr-linux-arm64
path: |
pixelvr-linux-arm64.tar.gz
pixelvr-linux-arm64.tar.gz.sha256
pixelvr-linux-arm64-v*.tar.gz
- name: Publish GitHub release
if: startsWith(github.ref, 'refs/tags/v') || inputs.tag != ''
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ inputs.tag || github.ref_name }}
generate_release_notes: true
files: |
pixelvr-linux-arm64.tar.gz
pixelvr-linux-arm64.tar.gz.sha256
pixelvr-linux-arm64-v*.tar.gz
pixelvr-linux-arm64-v*.tar.gz.sha256
+5
View File
@@ -5,6 +5,8 @@
/install/
/dist/
/sysroot/
# Release artifacts are attached to GitHub releases, not committed
/*.tar.gz
*.o
*.obj
*.a
@@ -40,3 +42,6 @@ Thumbs.db
# Local secrets / device config
/local.env
/secrets/
/scratch/
/test_vault
/*-plan.md
+4 -1
View File
@@ -108,7 +108,8 @@ set(PIXELVR_SHADERS
shaders/ui.vert
shaders/ui.frag
shaders/text.vert
shaders/text.frag)
shaders/text.frag
shaders/thumb.frag)
pixelvr_compile_shaders(pixelvr_shaders
OUTPUT_DIR "${CMAKE_BINARY_DIR}/shaders"
SOURCES ${PIXELVR_SHADERS})
@@ -124,6 +125,8 @@ add_library(pixelvr_core STATIC
src/gfx/vulkan_renderer.cpp
src/gfx/gltf_mesh.cpp
src/ui/settings_menu.cpp
src/ui/thumbnail_cache.cpp
src/app/vault_manager.cpp
src/app/app.cpp)
target_include_directories(pixelvr_core PUBLIC
+49 -16
View File
@@ -20,19 +20,41 @@ A native VR video player for the **Valve Steam Frame**, playing flat 2D, 180°,
## Install (prebuilt release)
Download `pixelvr-linux-arm64.tar.gz` from the
[Releases](../../releases) page and copy it to your Steam Frame, then:
One command, from a terminal on the headset (Desktop Mode or over SSH):
```bash
curl -fsSL https://raw.githubusercontent.com/Pixelplanet/Pixel-VR-Player/main/tools/install.sh | sh
```
It downloads the latest ARM64 release, verifies its checksum, installs it to
`~/PixelVRPlayer`, and adds **Pixel VR Player** to your Steam library as a
Non-Steam Game. Restart Steam if it was already running. SteamVR must be
installed.
Launch **Pixel VR Player** from your library, or directly:
```bash
tar -xzf pixelvr-linux-arm64.tar.gz -C ~
chmod +x ~/PixelVRPlayer/run.sh
~/PixelVRPlayer/run.sh # opens the in-headset file browser
~/PixelVRPlayer/run.sh /path/clip.mp4 # …or auto-play a specific clip
```
To launch it from the headset library, add `~/PixelVRPlayer/run.sh` as a
**Non-Steam Game** (Steam ▸ Add a Non-Steam Game). SteamVR must be running; the
app logs to `~/pixelvr-run.log`.
Installer options:
| Option | Effect |
| --- | --- |
| `--dir DIR` | install somewhere other than `~/PixelVRPlayer` |
| `--version vX.Y.Z` | install a specific release instead of the latest |
| `--no-steam` | skip the Steam library entry |
| `--restart-steam` | close Steam first, then reopen it so the entry appears at once |
| `--uninstall` | remove the app and its Steam shortcut |
Re-run the same command to upgrade. Settings (`~/.config/pixelvr`) and cached
thumbnails (`~/.cache/pixelvr`) live outside the install directory and are kept.
**Offline install:** download `pixelvr-linux-arm64.tar.gz` from the
[Releases](../../releases) page, copy it to the headset, extract it and run
`./install.sh` from the extracted folder — or use `run.sh` directly. The app logs
to `~/pixelvr-run.log`.
Requirements: the SteamVR OpenXR runtime (SteamOS), Vulkan, and FFmpeg with the
V4L2 M2M decoders. For zero-copy dma-buf decoding, build the patched FFmpeg into
@@ -47,17 +69,19 @@ stays usable while a panel is open.
| Input | Action |
| --- | --- |
| **Trigger** | Point and click: open the entry under the laser, or press a control-bar button |
| **A** | Open the highlighted entry — folder navigates, video plays / streams. Outside the browser it is play / pause |
| **X** / **Y** | Download the highlighted entry (folders confirm first, showing their size) |
| **B** | Open or close the file browser; also closes a panel and cancels the download dialog |
| **Grip** | Toggle **that hand's** laser pointer on/off. Turn one off to navigate with the thumbstick or d-pad without the beam interfering, and to choose which controller points |
| Thumbstick | Move the highlight in a panel; left/right seeks while playing |
| **A** | Open the highlighted browser entry — folder navigates, video plays / streams. Outside the browser it is play / pause |
| **B** | Open or close the file browser; also closes the settings panel and cancels the download dialog |
| **Trigger** | Laser pointer: click a panel row, or a control-bar button |
| **Grip** | Recenter the view in front of you |
| **Bumper** | Recenter the view in front of you |
The control bar has a dedicated **Download** button (arrow) that downloads the
entry highlighted in the browser — folders ask for confirmation and show their
size first. The **Downloads** button (list icon) opens the downloads manager,
where you can pause, resume, stop and clear jobs, then play a finished file or
open a finished folder.
The control bar has a **Download** button (arrow) that downloads the entry
highlighted in the browser, and a **Downloads** button (list icon) that opens the
downloads manager — where you can pause, resume, stop and clear jobs, then play a
finished file or open a finished folder. Opening the downloads manager replaces
the file browser rather than stacking on top of it.
All button bindings can be changed in **Settings ▸ Controls** (press-to-bind).
@@ -145,6 +169,15 @@ aarch64 cross (for the Steam Frame):
./tools/build.sh --aarch64 # configures + builds build-aarch64/
```
Release builds are automated: `.github/workflows/release.yml` builds natively on
an ARM64 runner in a Debian 13 container (FFmpeg 7, matching the headset's
SONAMEs) and attaches `pixelvr-linux-arm64.tar.gz` to each `v*` tag's release.
To package a local build by hand:
```bash
./tools/package-release.sh build-aarch64 pixelvr-linux-arm64.tar.gz
```
## Deploy to Steam Frame
See the full walkthrough in
+124
View File
@@ -0,0 +1,124 @@
# PixelVR Hidden Vault: Technical Specification & Architecture
## 1. Overview & Core Objectives
The **Hidden Vault** provides a private, zero-trace media storage and viewing capability within PixelVR Player. It allows users to store and view sensitive or private videos without virtual keyboard input, PIN dialogs, or visible hints in the default user interface.
### Key Requirements
* **Zero Keyboard Input:** Unlocks strictly through a physical controller combination.
* **Invisible by Default:** The vault directory (`~/.pixelvr_vault/`) is excluded from all directory scans on startup and cold boot.
* **Discrete Full Press Squeeze:** Squeeze has two separate functions: *Soft Squeeze* (analog) and *Full Press* (discrete click). The combo operates **exclusively** on Full Press.
* **Re-Lock Control:** When unlocked, a dedicated `[ 🔒 Lock Vault ]` button appears in the sidebar. It is completely absent when locked.
* **Move to Vault:** Downloaded/local media can be moved into the vault when unlocked, using a button binding configured in the Vault Settings tab.
* **Strict Privacy Isolation:** Thumbnails and memory textures for vault media are purged immediately upon re-locking.
---
## 2. Discrete Grip Architecture: Soft Squeeze vs. Full Press
Modern VR controllers (Valve Frame, Valve Index, Oculus/Meta Touch) provide two separate functional signals for controller grip:
```mermaid
flowchart LR
subgraph "Controller Hardware"
GripSensor["Grip Sensor"]
end
subgraph "OpenXR Functional Pathways"
GripSensor -->|"Gentle / Resting Hold"| SoftSqueeze["Soft Squeeze<br>(/input/squeeze/value)<br>Analog Float (0.0 .. 1.0)"]
GripSensor -->|"Mechanical Click / Bottom-Out"| FullPress["Full Press<br>(/input/squeeze/click)<br>Discrete Boolean Click"]
end
subgraph "PixelVR Input Dispatch"
SoftSqueeze -->|"Used for Laser Toggle / Holding"| NormalInput["Standard Input Handling<br>(Ignored by Vault)"]
FullPress -->|"Prerequisite for Combo"| ComboDetector["Vault Combo State Machine<br>(A-B-B-A-X-Y)"]
end
```
### Hardware Functional Separation
1. **Soft Squeeze (`/input/squeeze/value`):**
* Continuous analog range ($0.0 \dots 1.0$).
* Triggered whenever fingers rest casually on the controller or squeeze lightly.
* **Behavior:** Completely disregarded by the Vault combo detector. A user can squeeze or hold the controller at any pressure without accidentally arming the combo.
2. **Full Press (`/input/squeeze/click` or `/input/grip/click`):**
* Discrete boolean action representing the physical bottom-out or tactile click of the grip mechanism.
* **Behavior:** Required as the continuous hold prerequisite for the combo state machine. The user must intentionally bottom out the grip to enter the code.
---
## 3. Unlock Sequence & Combo State Machine
### 3.1 Default Sequence
$$\text{Grip Full Press (Held)} + [\text{BtnA} \rightarrow \text{BtnB} \rightarrow \text{BtnB} \rightarrow \text{BtnA} \rightarrow \text{BtnX} \rightarrow \text{BtnY}]$$
### 3.2 State Machine Rules
* **Sliding Timeout:** 2.5 seconds between button presses. If no button is pressed within 2.5 seconds, or if the grip Full Press is released before completion, the buffer resets to empty.
* **Wrong Button Penalty:** An incorrect button immediately clears the buffer.
* **Input Interception:** While `gripFullPressHeld` is true, face button presses (`A`, `B`, `X`, `Y`) are consumed exclusively by the combo detector. They are **suppressed from normal UI actions** (play/pause, back/close, download), preventing accidental interaction with the background player while entering the code.
* **Haptic Feedback:**
* Valid sequence step: subtle 10ms click vibration.
* Successful Unlock / Lock: distinct 60ms double pulse.
---
## 4. UI States & Spatial Navigation
### 4.1 State: LOCKED (Default State on Launch)
* The vault directory `~/.pixelvr_vault/` is excluded from all directory enumerations in `Browser::scanLocalInto()`.
* The sidebar navigation rail contains standard entries only (`Local Storage`, `Videos`, `SMB Shares`, `Downloads`).
* The `[ 🔒 Lock Vault ]` button is completely omitted from the layout.
* The Settings menu displays standard 4 tabs (`Display`, `Controls`, `Audio`, `System`).
### 4.2 State: UNLOCKED
* **Navigation Rail:** A glowing `[ 🔒 Vault ]` shortcut appears under Library categories. Clicking it opens `~/.pixelvr_vault/` in the 3x2 media grid.
* **Re-Lock Button:** A prominent `[ 🔒 Lock Vault ]` button appears in the sidebar.
* **Settings:** A 5th tab appears: **`Vault & Privacy`**.
* **Re-locking Actions:** Clicking the lock button (or repeating the combo):
1. Stops any currently playing video if its path is within `~/.pixelvr_vault/` and calls `renderer_.clearVideo()`.
2. Resets the file browser immediately to `Home` (`openHome()`).
3. Purges all in-memory thumbnail cache entries and GPU card textures for vault files.
4. Hides the `[ 🔒 Vault ]` shortcut, `[ 🔒 Lock Vault ]` button, and the `Vault & Privacy` settings tab.
---
## 5. "Move to Vault" File Management Engine
To allow seamless transfer of downloaded videos into the vault without using desktop file managers:
1. **Availability:** The move feature is active **only when the vault is unlocked** and **only for downloaded / local files** (SMB files cannot be moved directly; they must be downloaded first).
2. **Dedicated Button Binding:** Configured inside the **Vault & Privacy** settings tab (e.g. `X`, `Y`, `Left Stick Click`, or `None`), independent of regular playback control bindings.
3. **Robust Move Implementation:**
* Primary: `std::filesystem::rename(src, dest)`.
* Cross-device fallback: If `rename()` fails with `EXDEV` (e.g. moving from a MicroSD card or external drive on `/run/media/...` to internal storage `~/.pixelvr_vault/`), the engine automatically performs `std::filesystem::copy_file(src, dest)` followed by `std::filesystem::remove(src)`.
4. **Collision Handling:** If `~/.pixelvr_vault/video.mp4` already exists, the destination is automatically renamed to `video_1.mp4`.
5. **Cache Eviction:** Any public preview file previously generated in `~/.cache/pixelvr/thumbnails/` for the original path is deleted immediately upon moving.
---
## 6. Dynamic "Vault & Privacy" Settings Tab
When the vault is unlocked, a 5th tab becomes available in the Settings menu:
| Setting | Options | Default | Description |
|---|---|---|---|
| **Auto-Lock on Headset Off** | `[Enabled / Disabled]` | `Enabled` | Instantly locks the vault when headset proximity/focus is lost |
| **Inactivity Auto-Lock** | `[Disabled, 2m, 5m, 10m]` | `5 min` | Automatically locks if no controller input is detected |
| **Move to Vault Button** | `[X, Y, Stick Click, None]` | `Button X` | Physical button to move focused local file to vault |
| **Custom Combo Sequence** | `[Configure / Record]` | `A B B A X Y` | Records a custom 6-button sequence |
| **Lock Vault Now** | Action Button | — | Manually locks the vault immediately |
*Settings are persisted in `~/.config/pixelvr/pixelvr.conf` under the `[vault]` section.*
---
## 7. Edge Cases & Mitigation Matrix
| Edge Case | Failure Mode / Risk | Architectural Mitigation |
|---|---|---|
| **Accidental Soft Squeeze** | Resting fingers squeeze grip slightly and start recording combo inputs. | **Hardware Function Separation:** Only the discrete `Full Press` (`squeeze/click`) arms the combo. The analog `Soft Squeeze` (`squeeze/value`) is completely ignored. |
| **Normal Button Contamination** | Pressing `A B B A X Y` pauses video or starts downloads. | Face button events are suppressed from the UI while `gripFullPressHeld` is true. |
| **Cross-Filesystem Moves** | Moving a file from a MicroSD card to internal storage fails with `EXDEV`. | Automatic fallback from `rename()` to `copy_file()` + `remove()`. |
| **Name Collisions** | Moving `clip.mp4` when `~/.pixelvr_vault/clip.mp4` already exists. | Target automatically becomes `clip_1.mp4` to prevent data loss. |
| **Thumbnail Leakage** | Public thumbnail remains in shared cache after moving video to vault. | Old public thumbnail is deleted upon move; vault previews are stored only in `~/.pixelvr_vault/.thumbs/`. |
| **Active Video on Lock** | Video from vault is playing when headset is removed or lock button is clicked. | Playback engine calls `media_.close()` and `renderer_.clearVideo()` immediately so no private frame lingers. |
| **Headset Sleep / SteamVR Menu** | User presses SteamVR system button or takes off headset. | OpenXR session state loss (`XR_SESSION_STATE_VISIBLE` or `FOCUSED` lost) triggers immediate lock and resets to Home. |
+161
View File
@@ -0,0 +1,161 @@
# PixelVR Hidden Vault: Architectural Concept & Design Proposals
## 1. Executive Summary & Objective
The objective is to provide a frictionless, privacy-focused **Hidden Vault** feature in PixelVR Player for confidential/private media files without requiring a virtual keyboard or password prompt. Virtual keyboard entry in VR is notoriously cumbersome, immersion-breaking, and vulnerable to "shoulder surfing" (people watching the VR mirror window on a PC or TV screen).
### Core Requirements
1. **Zero Keyboard Input:** Unlock mechanism must use physical VR controller interactions or spatial UI patterns.
2. **Locked & Hidden by Default:** On app launch and cold restart, the folder and all its contents are completely invisible and unlisted.
3. **Explicit Re-Lock Control:** Once unlocked, a visible "Lock Vault" / "Hide" button appears in the UI. When locked, this button vanishes completely.
4. **Thumbnail & Cache Privacy:** Thumbnails and metadata of private videos must never leak into shared/public system caches or stay resident in GPU memory when locked.
5. **No Clues in Default UI:** The default UI must not look like anything is missing or locked (no "Enter PIN to access Vault" prompt).
---
## 2. Comparative Analysis of Unlock Mechanisms
We have developed three distinct non-keyboard unlock concepts tailored for spatial computing, each with unique trade-offs in stealth, speed, and ergonomics.
```mermaid
flowchart TD
subgraph "Unlock Mechanisms"
M1["Method 1: Cheat Code<br>(Grip + Face Button Combo)"]
M2["Method 2: Spatial Corner Tap<br>(Hidden Hitboxes on Panel)"]
M3["Method 3: Dual-Stick Chord<br>(Simultaneous Analog Directions)"]
end
subgraph "Vault Lifecycle"
LockedState["State: LOCKED (Default)<br>- Zero UI trace<br>- Path unlisted"]
UnlockedState["State: UNLOCKED<br>- 'Vault' in Sidebar<br>- 'Lock' Button Visible"]
end
M1 -->|Sequence Match| UnlockedState
M2 -->|Sequence Match| UnlockedState
M3 -->|Chord Match| UnlockedState
UnlockedState -->|Click Lock Button / Combo / Sleep| LockedState
```
---
### Method 1: The "Controller Cheat Code" (Grip + Button Sequence) ⭐ Recommended
*Inspired by classic gaming cheat codes (e.g., Konami Code), adapted for VR motion controllers.*
- **How It Works:**
1. The user holds down one of the controller grips fully (e.g., **Left Grip held > 75%**).
2. While the grip is held, the user enters a short 4-button sequence using the face buttons on either controller (e.g. `X -> Y -> B -> A` or `X -> X -> Y -> Y`).
3. A 2.5-second sliding timeout window resets the buffer if a pause occurs or an incorrect button is pressed.
4. On successful sequence: A subtle double-haptic vibration buzzes in the controller, and the Vault immediately unlocks.
- **Stealth Level:** **Maximum (5/5)**.
- To anyone watching the player in real life or viewing the desktop mirror window, the player’s hands remain completely stationary. No laser beams move, no UI buttons highlight.
- **Speed & Ergonomics:** Takes **under 1 second** to perform. Natural finger resting positions on Steam Frame / Quest / Index controllers.
- **False-Positive Prevention:** Because a grip must be held continuously while a distinct button sequence is pressed, normal navigation (which uses single clicks of A, B, X, Y without holding grips) will never accidentally unlock the vault.
---
### Method 2: The "Secret UI Corner Pattern" (Spatial Easter Egg)
*Inspired by mobile OS developer-mode unlocking (e.g. tapping Android build number 7 times) and pattern locks.*
- **How It Works:**
- The 1.8m x 1.12m Unified Spatial Hub floating panel has 4 invisible hit targets (5cm x 5cm) positioned at its four outer corners:
- `[TL]` Top-Left
- `[TR]` Top-Right
- `[BR]` Bottom-Right
- `[BL]` Bottom-Left
- The user points the laser and clicks the trigger in a predefined sequence:
- *Example Sequence:* `[TL] -> [TR] -> [BR] -> [TL]`.
- *Alternative (Logo Multi-Tap):* Quadruple-clicking the "PIXEL VR" brand logo in the left navigation rail within 1.5 seconds.
- **Stealth Level:** **Moderate (3/5)**.
- An observer watching the desktop mirror might see the laser pointer flick to the corners. However, to someone in the physical room, it looks like normal browsing.
- **Speed & Ergonomics:** Takes 2–3 seconds. Only requires one hand and the laser pointer.
- **Pros:** Very discoverable and intuitive once known; no button memorization required.
---
### Method 3: The "Dual-Stick Analog Chord" (Physical Key Turn)
*Inspired by physical safe dials.*
- **How It Works:**
- The user deflects both thumbsticks outward simultaneously (Left Stick pushed fully Left $\leftarrow$, Right Stick pushed fully Right $\rightarrow$) and clicks both stick buttons (L3 + R3) or pulls both triggers.
- **Stealth Level:** **Maximum (5/5)**.
- Completely invisible on screen mirrors.
- **Speed & Ergonomics:** Near-instantaneous (0.5s).
- **Cons:** Less sequence flexibility (can only be binary rather than a multi-step combination).
---
## 3. Recommended Hybrid Approach
We recommend implementing **Method 1 (Grip + Button Sequence)** as the primary unlock mechanism, with an optional fallback to **Method 2 (Logo Multi-Tap)** for maximum accessibility:
1. **Primary Combo:** Hold **Left Grip** + Press `X -> Y -> B -> A`.
2. **Alternative Laser Gesture:** 4 rapid trigger clicks on the **"PIXEL VR" Logo** in the top-left rail.
3. **Emergency Quick-Lock:** Repeating the combo from anywhere (even during full-screen video playback) immediately locks the vault and stops any private video currently playing.
---
## 4. UI Architecture & Presentation
### State 1: Locked (Default State)
- **Files View:** Only normal directories (`Videos`, `Downloads`, `SMB Shares`, external drives) appear.
- **Sidebar Rail:** Standard navigation items only (`Local Storage`, `Videos`, `SMB Shares`, `Downloads`).
- **Settings:** Zero settings or toggles referencing the vault.
- **Lock Button:** Completely absent and unrendered.
### State 2: Unlocked
- **Sidebar Rail:** A new glowing pill button appears in the sidebar library list:
- `[ 🔒 Vault ]` (or `[ Private ]` / `[ Stash ]`).
- Clicking this pill immediately opens the vault folder in the 3x2 card grid.
- **Action / Lock Button:** A dedicated **`[ 🔒 Lock Vault ]`** button appears in the navigation rail (either at the bottom of the sidebar or adjacent to the breadcrumbs).
- **Files Grid:** Media cards inside the vault display normal 16:9 thumbnails, format tags, and durations.
### Relocking Behavior:
When the user clicks `[ 🔒 Lock Vault ]` (or triggers the quick-lock combo):
1. If the user is currently inside the vault directory, the browser instantly navigates back to `Home` (`openHome()`).
2. If a video from the vault is currently playing, playback stops immediately and the screen resets.
3. The `[ 🔒 Vault ]` entry and `[ 🔒 Lock Vault ]` button disappear.
4. All memory buffers and GPU textures containing vault thumbnails are purged.
---
## 5. Filesystem & Privacy Architecture
### 1. Storage Location
- **Path:** `~/.pixelvr_vault/` (or `~/Videos/.vault/`).
- By utilizing a standard UNIX dotfile directory (`.pixelvr_vault`), the folder is automatically hidden from standard file managers in SteamOS Desktop Mode (Dolphin) unless "Show Hidden Files" is explicitly turned on.
- The directory will support sub-folders (e.g. `~/.pixelvr_vault/3D_VR180/`, `~/.pixelvr_vault/Movies/`).
### 2. Thumbnail Isolation & Zero-Leakage Guarantee
- **Vulnerability in Standard Caching:** Usually, thumbnail generators save image previews into a shared directory like `~/.cache/pixelvr/thumbs/` with predictable names. Anyone exploring the cache could see the private video previews.
- **The Vault Solution:**
- Thumbnails for files located within `~/.pixelvr_vault/` are stored strictly inside `~/.pixelvr_vault/.thumbs/`.
- When the vault is locked, all in-memory cache entries pointing to `~/.pixelvr_vault/` are evicted from the `ThumbnailCache` map, and the 6 GPU card thumbnail textures in `VulkanRenderer` are cleared to null/placeholders.
### 3. Downloads Integration
- When the vault is unlocked, downloading an SMB file can offer a quick-action: `[Download to Vault]`, allowing users to transfer files directly into the hidden folder over the network without placing them in the public `~/media` folder first.
---
## 6. Auto-Lock Safety Policies (Anti-Exposure Guards)
To protect the user from accidentally leaving their private media visible:
| Event | Action Taken |
|---|---|
| **Headset Removed** (Proximity sensor detects headset off) | **Instant Lock & Return to Home** |
| **SteamVR Dashboard Opened** (User presses system menu button) | **Instant Lock** |
| **App Minimized / Focus Lost** | **Instant Lock** |
| **Inactivity Timeout** (e.g. 5 minutes with no controller input) | **Auto-Lock & Return to Home** |
| **App Close / Restart** | **Always Cold Boots into Locked State** |
---
## 7. Configuration & Customization Options (Optional Future Settings)
Once the vault is unlocked, an advanced item can appear in the **Settings > Privacy** tab:
- **Change Unlock Combo:** Allows the user to record their own 4-step button sequence.
- **Auto-Lock Timer:** Adjust timeout (`2 min`, `5 min`, `10 min`, `Never while active`).
- **Emergency Panic Button:** Mapping a specific physical gesture (e.g., pressing both thumbsticks for 1 second) to immediately stop playback, lock vault, and switch to a decoy video or home screen.
+22 -2
View File
@@ -4,8 +4,25 @@ This guide covers how to get the built app running on the headset, the available
options, and which one to pick.
**What you're shipping:** a single self-contained ARM64 binary
(`build-aarch64/bin/pixelvr`, ~11 MB, static OpenXR loader) plus four SPIR-V
shaders. That's it — no `libopenxr_loader.so` or other bundled libraries.
(`build-aarch64/bin/pixelvr`, ~11 MB, static OpenXR loader) plus SPIR-V shaders
and a shell launcher. That's it — no `libopenxr_loader.so` or other bundled
libraries.
---
## Just installing a release (no devkit, no build)
End users do not need any of the steps below. From a terminal on the headset
(Desktop Mode or over SSH):
```bash
curl -fsSL https://raw.githubusercontent.com/Pixelplanet/Pixel-VR-Player/main/tools/install.sh | sh
```
That verifies the checksum, installs to `~/PixelVRPlayer`, and registers
**Pixel VR Player** as a Non-Steam Game. Relaunch Steam if it was running. Rerun
the same command to upgrade; `--uninstall` removes it. The rest of this document
covers building and iterating as a developer.
---
@@ -20,6 +37,9 @@ shaders. That's it — no `libopenxr_loader.so` or other bundled libraries.
# 2b. Or stage a clean folder for the GUI Devkit Client:
./tools/stage.sh # -> dist/PixelVRPlayer/
# 2c. Or build the release tarball end users install from:
./tools/package-release.sh build-aarch64 pixelvr-linux-arm64.tar.gz v1.3.0
```
---
+201
View File
@@ -0,0 +1,201 @@
# Pixel VR Player: Implementation Plan for Modern Spatial UI
This document details the concrete implementation plan to bring **Mockup #1 (Spatial Card Media Browser)** and **Mockup #2 (Floating Cinema Transport Dock)** into Pixel VR Player, including the **Flat vs. Curved Cinema Screen** engine and **180°/360° VR contextual adaptations**, without breaking existing hardware-accelerated playback or network functionality.
---
## 1. Architectural Overview & Design Decisions
### Selected Concepts
- **File Browser:** **Concept #1 (Spatial Media Browser)** — 3x2 / 4x2 responsive card grid, 16:9 thumbnail previews, format badges (`VR180 3D`, `4K HEVC`), breadcrumb path bar, source tabs (`Local`, `SMB Shares`, `Downloads`), left navigation rail.
- **Video Controls:** **Concept #2 (Floating Transport Dock)** — Frosted glassmorphic pill dock, prominent glowing central Play/Pause hero button, wide tactile scrubber bar with buffered track & hover timestamp, quick format pill (`VR 180° SBS`), audio track pill (`ENG 5.1`), screen distance/tilt controls, and download status badge.
- **Cinema Screen:** **Parametric Flat ↔ Curved Screen Engine** — Dynamically adjustable curvature (from $0.0$ flat plane to $1.0$ IMAX-style cylindrical wrap around the viewer).
- **180° / 360° VR Adaptation:** Context-aware HUD positioning, torso/yaw "lazy follow", auto-hide fading, and 180°-specific controls (Horizon Tilt & FOV Zoom).
### Visual Mockups
#### Mockup #1: Spatial Media Browser (Card Grid & Navigation Rail)
![Mockup 1 - Spatial Media Browser](./mockup-1-spatial-media-browser.jpg)
#### Mockup #2: Floating Cinema Transport Dock (Interactive Control HUD)
![Mockup 2 - Floating Cinema Transport Dock](./mockup-2-cinema-playback-hud.jpg)
#### Mockup #3: Minimalist Floating HUD Alternative
![Mockup 3 - Minimalist Playback HUD](./mockup-3-minimalist-playback-hud.jpg)
```mermaid
graph TD
subgraph "Vulkan Graphics Pipeline"
QuadVert["quad.vert (Parametric Curvature)"]
UIFrag["ui.frag (SDF Pills, Halos, Frosted Glass)"]
TextEngine["text_atlas.cpp (Proportional Sans-Serif SDF)"]
ThumbPool["VkImage Thumbnail Texture Array"]
end
subgraph "Core UI Layer (C++20)"
BrowserView["Browser Grid & Navigation (ui/browser.cpp)"]
ThumbService["Thumbnail Extractor (media/thumb_service.cpp)"]
HUDView["Transport Dock & 180VR Tracker (ui/hud_view.cpp)"]
SettingsDrawer["Tabbed Settings Modal (ui/settings_menu.cpp)"]
end
subgraph "Playback Engine"
HWDecoder["FFmpeg V4L2 M2M Zero-Copy"]
OpenXRInput["Valve Steam Frame Controllers"]
end
QuadVert --> HWDecoder
UIFrag --> HUDView
UIFrag --> BrowserView
TextEngine --> BrowserView
TextEngine --> HUDView
ThumbPool --> ThumbService
ThumbService --> BrowserView
OpenXRInput --> HUDView
OpenXRInput --> BrowserView
```
---
## 2. Flat vs. Curved Cinema Screen Engine
### 2.1 The Problem
Currently, in `shaders/quad.vert`, the flat screen is a hardcoded 6-vertex 2D planar quad (`vec2 positions[6] = ...`). It cannot curve, which leads to edge perspective stretching and focal mismatch in VR headsets when viewing large cinema screens.
### 2.2 The Curved Mesh Solution
We replace the 2-triangle flat quad with a **tessellated parametric cylindrical ribbon** (e.g. 64 horizontal subdivisions):
$$\theta(u) = (u - 0.5) \cdot \alpha_{\text{arc}}, \quad \text{where } \alpha_{\text{arc}} = \frac{W_{\text{screen}}}{R} \cdot \text{curvature}$$
$$x(u) = R \cdot \sin(\theta(u)), \quad z(u) = -R \cdot (1 - \cos(\theta(u)))$$
- **Curvature Parameter ($C \in [0.0, 1.0]$):**
- $C = 0.0$: Perfectly flat planar screen ($z = 0$).
- $C = 0.5$: Gentle cinema curve (subtle focal distance equalization).
- $C = 1.0$: Immersive IMAX deep wrap (constant focal distance to the eyes across the entire field of view).
- **Aspect Ratio & Stereo Preservation:**
- Full SBS, Half-SBS, and Top-Bottom stereo scaling remain completely intact.
- Anamorphic widescreen formats (2.39:1, 21:9) wrap naturally around the viewer.
- **In-HUD & Settings Control:**
- Users can toggle between **Flat** and **Curved** or adjust curvature smoothly using thumbstick left/right while pointing at the screen geometry pill.
---
## 3. 180° and 360° VR Video Adaptations
When playing VR180 or 360° videos, the video is projected onto a hemisphere/sphere around the user. The UI needs specific behavioral adaptations:
### 3.1 Lazy-Follow (Torso / Gaze Smoothing)
- **Problem:** If the HUD is locked in world space, turning around in a 180°/360° scene leaves the controls behind you. If rigidly head-locked, the controls shake with head micro-movements and induce motion sickness.
- **Solution (Torso Follow with Deadband):**
- Allow a **$\pm 20^\circ$ yaw deadband**: Small head turns leave the HUD stationary.
- When the user turns past $20^\circ$, the HUD smoothly glides (exponential damping, $\tau = 0.35\text{s}$) to catch up with their forward orientation.
- Positioned $15^\circ$ below horizontal eye-level so it never blocks the primary focal center of the 180VR scene.
### 3.2 Auto-Fade Immersion Timer
- During active 180VR/360VR playback, the HUD automatically fades out after **3.5 seconds** of inactivity.
- Woken up instantly by:
- Moving the controller (velocity threshold).
- Touching the thumbstick or trigger.
- Looking downward toward the dock position.
### 3.3 Dynamic Context Controls
In Flat/Cinema mode, the controls adjust *Screen Distance* and *Screen Curvature*. In 180VR/360VR, these concepts do not exist. The controls dynamically adapt:
| Feature | Cinema / Flat Mode | 180° / 360° VR Mode |
| :--- | :--- | :--- |
| **Geometry Pill** | `[ Flat / Curved Screen ]` | `[ Horizon Level / FOV ]` |
| **Thumbstick Up/Down** | Screen Distance (1.5m – 7.0m) | Horizon Pitch Tilt (`spherePitch_`) |
| **Thumbstick Left/Right** | Screen Curvature (0% – 100%) | FOV Zoom / IPD scale (`sphereZoom_`) |
| **Bumper Action** | Recenter Screen to view line | Recenter 180° Longitude to view line |
| **Comfort Depth** | Positioned just below bottom bezel | Floats at 1.8m depth, angled 18° up toward eyes |
---
## 4. Step-by-Step Implementation Roadmap
```mermaid
flowchart LR
P1["Phase 1<br>Vulkan Shaders & Fonts"] --> P2["Phase 2<br>Curved Screen Engine"]
P2 --> P3["Phase 3<br>Transport Dock (HUD)"]
P3 --> P4["Phase 4<br>Thumbnail Engine"]
P4 --> P5["Phase 5<br>Spatial Media Browser"]
P5 --> P6["Phase 6<br>180VR Polish & QA"]
```
### Phase 1: Vulkan Shaders & Proportional Font Engine
*Goal: Provide the visual primitives for modern UI without touching playback logic.*
1. **Shader Primitives (`shaders/ui.frag`):**
- Add new SDF shape types:
- `UiShape::Pill` (stadium shape for badges and buttons).
- `UiShape::GlowRing` (for hero play/pause button active halo).
- `UiShape::GradientCard` (smooth two-stop vertical gradient for cards).
- Add frosted glass background tinting with antialiased borders.
2. **Proportional Font Engine (`src/gfx/text_atlas.cpp`):**
- Update `buildFontAtlas` to support proportional fonts (`Inter-Regular.ttf` / `Roboto-Medium.ttf`).
- Store proportional advance and bearing metrics in `Glyph` struct.
- Maintain ASCII & common Unicode symbol support (`✓`, `‹`, `›`, `✕`, `●`, `★`).
### Phase 2: Parametric Curved Screen Engine
*Goal: Support seamless switching between flat cinema screen and curved cinema screen.*
1. **Curvature Geometry in `vulkan_renderer.cpp`:**
- Create a static index/vertex buffer for a 64x1 tessellated ribbon or evaluate parametric cylindrical curvature in `quad.vert`.
- Pass `screenCurvature` ($0.0 \dots 1.0$) through the vertex push constants.
2. **Raycasting Update:**
- When raycasting against the curved screen (for direct laser pointer scrub), intersect ray with cylinder $(x^2 + z^2 = R^2)$.
### Phase 3: Modern Floating Transport Dock (Mockup #2)
*Goal: Implement the sleek, intuitive playback dock.*
1. **Dock Layout Architecture:**
- Left section: Download status badge & duration readout.
- Center section: Hero Play/Pause button ($\varnothing 68\text{mm}$) + Seek -10s / +10s + tactile scrubber.
- Right section: Format Pill (`VR 180° SBS`), Audio Pill (`ENG 5.1`), Geometry Pill (`Flat/Curved` or `Horizon/FOV`).
2. **180VR Lazy Follow & Auto-Hide:**
- Integrate yaw deadband tracking and alpha fade timer into `src/app/app.cpp` and `vulkan_renderer.cpp`.
- Smooth alpha transition ($0.0 \to 1.0$ in 150ms).
### Phase 4: Thumbnail Extraction & Caching Engine
*Goal: Enable visual preview cards in the browser without UI thread stalls.*
1. **Lightweight Extractor (`src/media/thumbnail_service.cpp`):**
- Background worker thread with queue.
- For local and downloaded files: reads first keyframe at $t \approx 10\%$ using `avformat_open_input` + `avcodec_receive_frame`.
- Rescales to 256x144 RGBA thumbnail.
- Caches to `~/.cache/pixelvr/thumbs/<hash>.bin`.
2. **Vulkan Texture Pool:**
- Allocate a `VkImage` 2D Texture Array (e.g. 16–32 slots) for currently visible browser cards.
- Stream loaded thumbnails into the array descriptors.
### Phase 5: Spatial Media Browser (Mockup #1)
*Goal: Implement the 3D curved card grid file browser.*
1. **Browser Layout Tree:**
- Left Navigation Rail (Home, Videos, SMB Shares, Downloads).
- Top Header (Breadcrumb trail, Source tabs, View toggle).
- 3x2 Grid of Media Cards:
- 16:9 Thumbnail quad.
- Title string with proportional font.
- Format pill badges (`VR180 3D`, `4K HEVC`).
- Duration pill (`32:45`).
2. **Input & Pointer Physics:**
- 2D grid raycasting: maps hit point directly to `(col, row)`.
- Magnetic snap: gentle suction on laser ray when near card center.
- Smooth thumbstick grid navigation (Up/Down/Left/Right).
### Phase 6: System Verification & Rigorous QA
*Goal: Ensure zero regressions across both desktop and ARM64 hardware.*
1. **Hardware Validation:**
- Cross-compile for aarch64 Steam Frame.
- Verify 90 Hz / 120 Hz render loop budget with Vulkan pipeline timers.
- Confirm zero-copy DMA-BUF hardware decode remains unaffected.
2. **Functional Validation:**
- SMB network streaming and background downloading.
- Multi-audio stream switching and eye swapping.
- Controller button remapping.
---
## 5. Non-Breaking Safety Guarantees
1. **Zero External Heavy Dependencies:** No Qt, no WebViews, no massive libraries. Everything builds with existing CMake toolchain and Vulkan/OpenXR/FreeType/FFmpeg stack.
2. **Graceful Fallback:** If thumbnails are not yet extracted or unavailable (e.g. slow SMB network share), the browser instantly displays clean stylized gradient placeholder cards with format icons.
3. **Model Separation:** `Browser` and `SettingsMenu` remain headless data models. All new visual enhancements live purely in the presentation/renderer layer.
+144
View File
@@ -0,0 +1,144 @@
# PixelVR Unified Spatial Hub Architecture & UI Redesign Specification
## 1. Executive Summary & Design Paradigm Shift
### The Problem With Separate Overlays
In previous iterations, the VR player utilized three disconnected overlay windows with distinct dimensional footprints and conflicting layout logic:
1. **File Browser:** A 3x2 card grid with an ad-hoc left sidebar.
2. **Downloads Window:** A smaller centered modal with custom progress rows.
3. **Settings Overlay:** A tall vertical list that occluded the screen.
Because these interfaces were built as disjointed panels, buttons and text had inconsistent paddings. When text lengths varied, font scaling was applied dynamically, creating an unpolished look where adjacent buttons had wildly different font sizes. Furthermore, controller laser raycasting had to switch between multiple collision hulls.
### The Solution: One Unified Spatial Window
We unify the entire non-playback experience into a single, cohesive **Unified Spatial Hub** floating panel (1.8m x 1.1m, curved 15° radius).
- **Fixed, Consistent Dimensions:** Button heights, pill paddings, and typography sizes are standardized across all screens.
- **Section Tabs in Left Navigation Rail:**
- `FILES` (Browse local storage, videos, SMB shares, external drives)
- `DOWNLOADS` (Monitor active downloads with live speed, ETA, progress bars, pause/cancel controls, and completed library)
- `SETTINGS` (Configure cinema screen curvature, distance, hardware decode engine, projection, laser controls)
- **Single Raycast Hull & State Machine:** The controller laser interacts with one unified surface with dedicated collision zones, eliminating edge cases where rays pass into infinity or click through hidden layers.
---
## 2. Global Design System & Spatial Metric Tokens
All coordinates and dimensions are defined in metric VR panel-local units:
| Token | Metric Value | Purpose |
|---|---|---|
| `kHubWidth` | `1.80m` | Total unified floating window width |
| `kHubHeight` | `1.12m` | Total unified floating window height |
| `kNavRailWidth` | `0.38m` | Left navigation rail width |
| `kContentWidth` | `1.36m` | Main content area width (`kHubWidth - kNavRailWidth - padding`) |
| `kNavButtonHeight` | `0.065m` | Standard height for primary navigation pills |
| `kButtonPadX` | `0.028m` | Uniform horizontal padding for all interactive pills |
| `kStandardFontSize` | `0.024m` | Primary font size for all UI button labels |
| `kTitleFontSize` | `0.032m` | Screen headers, modal titles |
| `kDetailFontSize` | `0.018m` | Secondary status, subtitles, file size/specs |
| `kBadgeFontSize` | `0.014m` | Chip tags (`VR180 3D`, `4K HEVC`) |
| `kCardWidth` | `0.42m` | Media card width in 3x2 grid |
| `kCardHeight` | `0.38m` | Media card height in 3x2 grid |
| `kThumbAspect` | `16:9` | Fixed 16:9 aspect ratio for thumbnail preview boxes |
### Color Palette (Glassmorphism & Cyber-Cinema)
- **Panel Backdrop:** `rgba(6, 9, 15, 0.94)` with frosted glass border `rgba(50, 75, 115, 0.40)`
- **Navigation Rail:** `rgba(4, 6, 11, 0.96)` with separator divider `rgba(45, 65, 95, 0.50)`
- **Interactive Button Normal:** `rgba(18, 26, 42, 0.70)` with border `rgba(55, 80, 120, 0.50)`
- **Interactive Button Hover:** `rgba(35, 75, 140, 0.90)` with border `rgba(100, 190, 255, 1.00)` + glow
- **Active / Selected Pill:** `rgba(20, 110, 210, 0.95)` with border `rgba(120, 210, 255, 1.00)`
- **Accent Primary (Cyan):** `rgba(70, 195, 255, 1.00)`
- **Accent Success (Emerald):** `rgba(35, 195, 105, 1.00)`
- **Text Primary (White):** `rgba(245, 248, 255, 1.00)`
- **Text Secondary (Slate):** `rgba(145, 175, 215, 0.85)`
---
## 3. UI Page Layout Specifications & Mockups
### Page 1: Files Section (Spatial Media Browser)
![Files View Mockup](./mockup-unified-1-files.jpg)
- **Top Bar:**
- Dynamic breadcrumb display with overflow protection: `Local Storage > Videos > VR180`
- Right-aligned page switcher: `PAGE [ < ] 1 / 4 [ > ]` and sort dropdown.
- **Main Grid (3x2 Media Cards):**
- Six cards per page.
- Card upper 65% is dedicated to a 16:9 thumbnail preview with rounded corners.
- Overlaid tags: Top-left format badge (`VR180 3D`, `4K HEVC`), bottom-right duration pill (`42:15`).
- Card lower 35% contains fixed-size, multi-line typography:
- Line 1: Video Title (truncated with ellipsis if length > card text area, preserving standard font size).
- Line 2: Details: `7200x3600 • 59.94 FPS • 14.2 GB`
- **Bottom Status Rail:** Action key hints: `[Trigger: Play] [X: Download to Local] [Thumbstick: Navigate]`.
---
### Page 2: Downloads Section (Active Transfers & Queue Manager)
![Downloads View Mockup](./mockup-unified-2-downloads.jpg)
- **Top Bar:** `Downloads > Active Transfers` with aggregate stats `Total Speed: 28.4 MB/s • Free Space: 184 GB`.
- **Main View (Active Job Cards):**
- Each job is rendered as a wide card (`1.32m x 0.12m`):
- Left: File thumbnail / icon.
- Center Top: Filename with standardized font size.
- Center Mid: Dynamic progress bar with smooth cyan glow gradient fill.
- Center Bottom: Metrics line: `Transferred: 6.4 GB / 14.8 GB (43%) • Speed: 18.2 MB/s • ETA: 07:42`.
- Right: Action buttons (`Pause/Resume`, `Cancel (X)`) with fixed 0.05m circular dimensions.
- **Completed Transfers Section:**
- Displays finished downloads with an emerald green `Completed` pill and quick-action `[Play Now]` or `[Open In Folder]` buttons.
- **Bottom Control Bar:** Global buttons: `[Pause All]`, `[Resume All]`, `[Clear Finished]`.
---
### Page 3: Settings Section (Cinema & Playback Configuration)
![Settings View Mockup](./mockup-unified-3-settings.jpg)
- **Top Bar:** `Settings > Display & Playback` with version pill `v1.2.0 • Steam Frame`.
- **Two-Column Settings Grid:**
- **Screen Geometry:** Segmented pill toggle: `[Flat Screen]` vs `[Curved Cinema]`.
- **Screen Distance & Scale:** Dual slider controls (`Distance: 1.5m - 5.0m`, `Scale: 80% - 200%`).
- **Hardware Video Decoder:** Segmented toggle: `[Auto (Iris/V4L2)]` vs `[Software (Multi-Thread)]`.
- **Stereo Projection Default:** `[Auto-Detect]` | `[VR180 SBS]` | `[360 Mono]` | `[2D Cinema]`.
- **Controller Laser Mode:** `[Right Hand Only]` | `[Left Hand Only]` | `[Both Hands]`.
- **Network / SMB Shares:** Dedicated button to trigger the share credentials modal.
---
### Page 4: In-Playback Cinema Floating Transport HUD
![Cinema Transport HUD Mockup](./mockup-unified-4-cinema-hud.jpg)
- **Location:** Floating at `y = -0.65m, z = -2.2m`, tilted 20° up toward viewer.
- **Scrubber Bar (Top Row):**
- Full-width interactive timeline scrubber with elapsed time (`18:24`) and remaining (`-41:36`).
- Laser hover reveals a floating mini-thumbnail tooltip at the seek position.
- **Center Transport Cluster:**
- 4 primary circular buttons with generous touch targets:
`[Stop]` `[Seek -10s]` `(Play/Pause)` `[Seek +10s]`.
- **Left Flank:**
- `[HUB]` button (opens the Unified Spatial Hub).
- `[RECENTER]` button (yaw/pitch reset).
- **Right Flank:**
- `[FORMAT]` toggle pill (cycles 2D, 3D SBS, VR180, 360).
- `[AUDIO]` track selector pill (greys out to `DEFAULT` if only 1 audio stream exists).
- `[SCREEN]` toggle pill (toggles Flat / Curved geometry).
---
## 4. Root Causes & Direct Fixes for Previous Issues
### Issue A: Thumbnail Generation Failure on Headset
- **Root Cause Identified:**
1. `ThumbnailCache::workerLoop` ran `ffmpeg` without `-nostdin` or with `-threads 4` inside `std::system`. When ffmpeg prompts for stdin or encounters an existing file without `-y` in certain subshells, it fails.
2. Thumbnail request targets in `app.cpp` passed `/home/steamos/Downloads/.../sample.mkv` but some MKV/MP4 files had deep directories where `ffmpeg` needed `-ss 00:00:05` before `-i` and `-nostdin` to prevent process suspension.
3. The descriptor set allocation for thumbnail slots was previously leaking or getting overwritten.
- **Solution for Implementation:**
- Run ffmpeg with: `ffmpeg -nostdin -y -v error -ss 00:00:05 -i "<file>" -vframes 1 -s 256x144 -f rawvideo -pix_fmt rgba "<cacheFile>"`.
- Add fallback to `-ss 00:00:00`.
- Pre-allocate a dedicated `VkDescriptorPool` of 6 persistent image sampler sets exclusively for the 6 card slots so no descriptor reallocation occurs during runtime.
### Issue B: Inconsistent Text Sizes Across Buttons
- **Root Cause Identified:**
The previous `drawFit` function dynamically shrunk the font size of each button individually based on the length of its text. This caused short labels like `HOME` to look huge while longer labels looked tiny and misaligned.
- **Solution for Implementation:**
- Fix button width and font scale globally to `kStandardFontSize`.
- If a label exceeds the generous button width, wrap or cleanly truncate with an ellipsis (`...`), keeping all button font scales strictly identical across the interface.
Binary file not shown.

After

Width:  |  Height:  |  Size: 642 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 549 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 556 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 465 KiB

Binary file not shown.
+39 -12
View File
@@ -1,26 +1,53 @@
#version 450
// Textured video screen: a 16:9 quad whose distance, yaw and aspect are applied
// by the model matrix on the CPU. Geometry and UVs are hardcoded and indexed by
// gl_VertexIndex (no vertex buffer).
// Textured video screen: a 16:9 screen with parametric curvature (Flat -> Curved).
// 64 horizontal segments (384 vertices) are procedurally evaluated from gl_VertexIndex.
// pc.stereo.w carries the curvature factor in [0.0, 1.0] (0 = flat, >0 = curved arc).
layout(push_constant) uniform Push {
mat4 mvp;
vec4 conversion;
vec4 range;
vec4 stereo;
vec4 stereo; // x: stereoMode, y: viewIndex, z: swapEyes, w: curvature
} pc;
layout(location = 0) out vec2 vUV;
void main() {
vec2 positions[6] = vec2[](
vec2(-1.6, 0.9), vec2(-1.6, -0.9), vec2( 1.6, -0.9),
vec2(-1.6, 0.9), vec2( 1.6, -0.9), vec2( 1.6, 0.9));
vec2 uvs[6] = vec2[](
vec2(0.0, 0.0), vec2(0.0, 1.0), vec2(1.0, 1.0),
vec2(0.0, 0.0), vec2(1.0, 1.0), vec2(1.0, 0.0));
const int kSegments = 64;
int seg = gl_VertexIndex / 6;
int vid = gl_VertexIndex % 6;
gl_Position = pc.mvp * vec4(positions[gl_VertexIndex], 0.0, 1.0);
vUV = uvs[gl_VertexIndex];
float u0 = float(seg) / float(kSegments);
float u1 = float(seg + 1) / float(kSegments);
// Quad vertex coordinates for this segment
float u = u0;
float y = 0.9;
if (vid == 1) { u = u0; y = -0.9; }
else if (vid == 2) { u = u1; y = -0.9; }
else if (vid == 3) { u = u0; y = 0.9; }
else if (vid == 4) { u = u1; y = -0.9; }
else if (vid == 5) { u = u1; y = 0.9; }
vUV = vec2(u, (0.9 - y) / 1.8);
// Nominal screen width = 3.2 (-1.6 to +1.6)
const float kWidth = 3.2;
float curv = clamp(pc.stereo.w, 0.0, 1.0);
float x = (u - 0.5) * kWidth;
float z = 0.0;
if (curv > 0.005) {
// Pure cylindrical arc of constant arc length kWidth.
// At curv=1.0, total wrap angle is ~100 degrees (1.75 rad) around the viewer.
float totalAngle = curv * 1.75;
float radius = kWidth / totalAngle;
float theta = (u - 0.5) * totalAngle;
x = radius * sin(theta);
z = radius * (1.0 - cos(theta));
}
gl_Position = pc.mvp * vec4(x, y, z, 1.0);
}
+29 -4
View File
@@ -12,10 +12,35 @@ layout(push_constant) uniform Push {
layout(location = 0) in vec2 vUV;
layout(location = 0) out vec4 outColor;
vec3 toLinear(vec3 srgb) {
return pow(max(srgb, vec3(0.0)), vec3(2.2));
}
void main() {
// Signed-distance text: a crisp ~1px edge in screen space so it stays sharp
// at any size (a coverage-bitmap fallback also reads acceptably here).
// Stable screen-space signed-distance field text rendering:
// Screen-space derivatives of texture coordinates (vUV) provide a smooth,
// noise-free measure of font texels per screen pixel across the glyph quad,
// completely eliminating fragment-derivative jitter during head movement in VR.
vec2 texSize = vec2(textureSize(fontAtlas, 0));
vec2 ddx = dFdx(vUV) * texSize;
vec2 ddy = dFdy(vUV) * texSize;
// RMS font-texel footprint per screen pixel (rotation and perspective invariant)
float fontPixelsPerScreenPixel = 0.70710678 * sqrt(dot(ddx, ddx) + dot(ddy, ddy));
float d = texture(fontAtlas, vUV).r;
float a = clamp((d - 0.5) / max(fwidth(d), 0.0001) + 0.5, 0.0, 1.0);
outColor = vec4(pc.color.rgb, pc.color.a * a);
// FreeType SDF: spread = 8 font pixels, contour zero-crossing is 128 / 255.0 = 0.50196078.
// Range [-8, +8] font pixels is mapped across [0, 1].
float distInFontPixels = (d - 0.50196078) * 16.0;
// Convert distance to screen pixels, adding a subtle stem-darkening bias (+0.14 screen px)
// to preserve thin strokes and legibility against high-contrast dark VR backgrounds.
float distInScreenPixels = (distInFontPixels / max(fontPixelsPerScreenPixel, 1e-4)) + 0.14;
// Smooth Hermite anti-aliasing across 1.4 screen pixels (smooth transition matches VR subpixel PSF)
float a = smoothstep(-0.70, 0.70, distInScreenPixels);
if (a <= 0.002) {
discard;
}
outColor = vec4(toLinear(pc.color.rgb), pc.color.a * a);
}
+35
View File
@@ -0,0 +1,35 @@
#version 450
layout(binding = 0) uniform sampler2D thumbTex;
layout(push_constant) uniform Push {
mat4 mvp;
vec4 color;
vec4 rect; // x, y (bottom-left), w, h in panel-local units
vec4 uv; // u0, v0, u1, v1
} pc;
layout(location = 0) in vec2 vUV;
layout(location = 0) out vec4 outColor;
void main() {
vec4 col = texture(thumbTex, vUV);
// Exact metric rounded rectangle SDF matching panel styling with screen-space AA
vec2 p = abs(vUV - 0.5) * pc.rect.zw;
vec2 b = 0.5 * pc.rect.zw - vec2(0.018);
vec2 q = max(p - b, 0.0);
float dist = length(q) - 0.018;
vec2 dpx = dFdx(p);
vec2 dpy = dFdy(p);
float pixSize = 0.70710678 * sqrt(dot(dpx, dpx) + dot(dpy, dpy));
float aa = max(pixSize * 1.4, 0.001);
float alpha = 1.0 - smoothstep(-aa, aa, dist);
if (alpha <= 0.002) {
discard;
}
// Thumbnail pixels are sRGB; convert to linear for the VK_FORMAT_*_SRGB framebuffer
vec3 linRgb = pow(max(col.rgb, vec3(0.0)), vec3(2.2));
outColor = vec4(linRgb * pc.color.rgb, col.a * pc.color.a * alpha);
}
+49 -7
View File
@@ -132,24 +132,66 @@ void main() {
float p2 = sdRoundedBox(p - vec2(-0.50, 0.00), vec2(0.10, 0.10), 0.05);
float p3 = sdRoundedBox(p - vec2(-0.50, -0.46), vec2(0.10, 0.10), 0.05);
d = min(min(min(b1, b2), min(b3, p1)), min(p2, p3));
} else if (shape == 14) {
// Shape 14: Hero Glow Ring (circular outline for primary buttons)
float r = length(p);
d = abs(r - 0.72) - 0.08;
} else if (shape == 15) {
// Shape 15: Audio Speaker icon (cone + sound wave)
float box = sdRoundedBox(p - vec2(-0.32, 0.0), vec2(0.12, 0.18), 0.03);
float cone = sdTriangle(p, vec2(-0.20, 0.18), vec2(0.16, 0.45), vec2(-0.20, -0.18)) - 0.02;
float cone2 = sdTriangle(p, vec2(-0.20, -0.18), vec2(0.16, -0.45), vec2(0.16, 0.45)) - 0.02;
float rArc = length(p - vec2(-0.05, 0.0));
float arc1 = max(abs(rArc - 0.46) - 0.06, -p.x + 0.10);
float arc2 = max(abs(rArc - 0.68) - 0.06, -p.x + 0.22);
d = min(min(box, min(cone, cone2)), min(arc1, arc2));
} else if (shape == 16) {
// Shape 16: VR Headset / Display goggles
float gBody = sdRoundedBox(p, vec2(0.55, 0.30), 0.14);
float nose = sdTriangle(p - vec2(0.0, -0.30), vec2(-0.16, -0.08), vec2(0.16, -0.08), vec2(0.0, 0.12)) - 0.04;
float strapL = sdRoundedBox(p - vec2(-0.62, 0.0), vec2(0.08, 0.10), 0.03);
float strapR = sdRoundedBox(p - vec2(0.62, 0.0), vec2(0.08, 0.10), 0.03);
d = max(min(gBody, min(strapL, strapR)), -nose);
} else if (shape == 17) {
// Shape 17: Curved Cinema Display icon
float rScreen = length(p - vec2(0.0, 1.3));
float arcDisp = abs(rScreen - 1.62) - 0.10;
float cutX = abs(p.x) - 0.58;
float cutY = abs(p.y) - 0.32;
d = max(arcDisp, max(cutX, cutY));
} else if (shape == 18) {
// Shape 18: Chevron (>) for breadcrumbs & pagination
float c1 = sdSegment(p, vec2(-0.22, 0.40), vec2(0.24, 0.0)) - 0.08;
float c2 = sdSegment(p, vec2(0.24, 0.0), vec2(-0.22, -0.40)) - 0.08;
d = min(c1, c2);
} else if (shape == 19) {
// Shape 19: Home / Library icon
float roof = sdTriangle(p - vec2(0.0, 0.12), vec2(-0.52, 0.0), vec2(0.52, 0.0), vec2(0.0, 0.42)) - 0.04;
float baseH = sdRoundedBox(p - vec2(0.0, -0.20), vec2(0.35, 0.26), 0.04);
d = min(roof, baseH);
} else {
d = sdRoundedBox(p, vec2(1.0), 0.0);
}
float aa = fwidth(d);
if (aa < 1e-4) aa = 0.015;
float fillAlpha = 1.0 - smoothstep(-aa * 0.5, aa * 0.5, d);
// Exact screen-space gradient magnitude of the distance field along the contour normal.
// Produces a crisp, razor-sharp 1.5 screen-pixel anti-aliased outline without crawling.
float gradLen = length(vec2(dFdx(d), dFdy(d)));
float aa = max(gradLen * 0.75, 0.0005);
float fillAlpha = 1.0 - smoothstep(-aa, aa, d);
if (fillAlpha <= 0.0) {
if (fillAlpha <= 0.002) {
discard;
}
vec4 finalColor = pc.color;
vec4 fillLin = vec4(pow(max(pc.color.rgb, vec3(0.0)), vec3(2.2)), pc.color.a);
vec4 finalColor = fillLin;
if (hasBorder) {
// Crisp, razor-sharp border highlight line matching requested thickness
float borderWidth = pc.params.z;
float innerD = d + borderWidth;
float borderAlpha = 1.0 - smoothstep(-aa * 0.5, aa * 0.5, innerD);
finalColor = mix(pc.borderColor, pc.color, borderAlpha);
float borderAlpha = 1.0 - smoothstep(-aa, aa, innerD);
vec4 bordLin = vec4(pow(max(pc.borderColor.rgb, vec3(0.0)), vec3(2.2)), pc.borderColor.a);
finalColor = mix(bordLin, fillLin, borderAlpha);
}
finalColor.a *= fillAlpha;
+1014 -182
View File
File diff suppressed because it is too large. Load diff
+14 -6
View File
@@ -10,6 +10,7 @@
#ifdef PIXELVR_HAVE_FREETYPE
#include "ui/browser.hpp"
#include "ui/thumbnail_cache.hpp"
#endif
#include "ui/settings_menu.hpp"
@@ -50,6 +51,8 @@ private:
bool seekStepArmed_ = true; // right-stick +/-30s debounce
bool navArmed_ = true; // menu nav: armed for the next stick press
std::chrono::steady_clock::time_point navNextRepeat_{}; // nav auto-repeat
bool navArmedX_ = true; // horizontal grid nav
std::chrono::steady_clock::time_point navNextRepeatX_{};
bool scrubbing_ = false; // dragging the timeline / stick-scrubbing
double scrubTarget_ = 0.0; // pending scrub position (seconds)
std::chrono::steady_clock::time_point perfLastLog_{};
@@ -58,12 +61,12 @@ private:
// Place the screen in front of the user on the first valid head pose.
bool didInitialRecenter_ = false;
bool controllerModelLoaded_ = false; // real glTF model uploaded once
// Local grip->render-model-space correction so the model sits exactly where
// the runtime renders it (derived from the fetched model's owner hand).
bool modelCorrValid_ = false;
float modelCorrPos_[3] = {0.0f, 0.0f, 0.0f};
float modelCorrQuat_[4] = {0.0f, 0.0f, 0.0f, 1.0f};
bool controllerModelLoaded_[2] = {false, false}; // glTF model uploaded per hand
// Local grip->render-model-space correction per hand so each model sits
// exactly where the runtime renders it.
bool modelCorrValid_[2] = {false, false};
float modelCorrPos_[2][3] = {{0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}};
float modelCorrQuat_[2][4] = {{0.0f, 0.0f, 0.0f, 1.0f}, {0.0f, 0.0f, 0.0f, 1.0f}};
// Background download status line: shown while active and briefly after a
// download finishes (so success/failure is visible with the browser closed).
std::chrono::steady_clock::time_point downloadToast_{};
@@ -92,9 +95,14 @@ private:
void updateStats();
// Menu nav stick auto-repeat: -1/+1 to step (initial press + hold), else 0.
int navStep(float axisY, std::chrono::steady_clock::time_point now);
int navStepX(float axisX, std::chrono::steady_clock::time_point now);
void performVaultLock();
VulkanRenderer::ActionMenuData actionMenu_{};
void openActionMenu();
#ifdef PIXELVR_HAVE_FREETYPE
Browser browser_;
ThumbnailCache thumbnailCache_;
#endif
SettingsMenu settings_;
+398
View File
@@ -0,0 +1,398 @@
#include "app/vault_manager.hpp"
#include "util/logging.hpp"
#include <algorithm>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <sstream>
namespace pixelvr {
namespace fs = std::filesystem;
namespace {
std::string getVaultConfigPath() {
#ifdef _WIN32
const char* appData = std::getenv("APPDATA");
if (appData) return std::string(appData) + "/PixelVR/vault.conf";
#else
const char* home = std::getenv("HOME");
if (home) return std::string(home) + "/.config/pixelvr/vault.conf";
#endif
return "pixelvr_vault.conf";
}
const char* btnName(int b) {
switch (b) {
case XrInputState::BtnA: return "A";
case XrInputState::BtnB: return "B";
case XrInputState::BtnX: return "X";
case XrInputState::BtnY: return "Y";
case XrInputState::BtnMenu: return "Menu";
case XrInputState::BtnView: return "View";
case XrInputState::BtnBumper: return "Bumper";
case XrInputState::BtnThumb: return "Thumb";
case XrInputState::BtnGrip: return "Grip";
default: return "?";
}
}
static uint64_t fnv1a64(const std::string& str) {
uint64_t hash = 14695981039346656037ULL;
for (char c : str) {
hash ^= static_cast<uint8_t>(c);
hash *= 1099511628211ULL;
}
return hash;
}
} // namespace
VaultManager& VaultManager::instance() {
static VaultManager s_instance;
return s_instance;
}
VaultManager::VaultManager() {
const char* home = std::getenv("HOME");
if (home != nullptr) {
vaultDir_ = std::string(home) + "/.pixelvr_vault";
} else {
vaultDir_ = "/home/steamos/.pixelvr_vault";
}
thumbsDir_ = vaultDir_ + "/.thumbs";
// Default sequence: A -> B -> B -> A -> X -> Y
comboSequence_ = {
XrInputState::BtnA,
XrInputState::BtnB,
XrInputState::BtnB,
XrInputState::BtnA,
XrInputState::BtnX,
XrInputState::BtnY
};
loadConfig();
}
void VaultManager::ensureDirectories() {
std::error_code ec;
fs::create_directories(vaultDir_, ec);
if (!ec) {
fs::permissions(vaultDir_, fs::perms::owner_all, fs::perm_options::replace, ec);
}
fs::create_directories(thumbsDir_, ec);
if (!ec) {
fs::permissions(thumbsDir_, fs::perms::owner_all, fs::perm_options::replace, ec);
}
}
bool VaultManager::isVaultPath(const std::string& path) const {
if (path.empty() || vaultDir_.empty()) return false;
return path.rfind(vaultDir_, 0) == 0;
}
void VaultManager::lock() {
if (!unlocked_) return;
unlocked_ = false;
comboIndex_ = 0;
headsetLostTime_ = {};
isRecordingCombo_ = false;
recordingBuffer_.clear();
PIXELVR_LOG_INFO("Vault locked");
}
void VaultManager::unlock() {
ensureDirectories();
unlocked_ = true;
comboIndex_ = 0;
headsetLostTime_ = {};
lastActivity_ = std::chrono::steady_clock::now();
PIXELVR_LOG_INFO("Vault unlocked at %s", vaultDir_.c_str());
}
VaultManager::ComboResult VaultManager::feedInput(int button, bool gripFullPressHeld,
std::chrono::steady_clock::time_point now) {
if (!gripFullPressHeld) {
comboIndex_ = 0;
return ComboResult::None;
}
// Only face buttons participate in the cheat code
if (button != XrInputState::BtnA && button != XrInputState::BtnB &&
button != XrInputState::BtnX && button != XrInputState::BtnY) {
return ComboResult::None;
}
using namespace std::chrono_literals;
if (comboIndex_ > 0 && (now - lastComboInput_) > 2500ms) {
comboIndex_ = 0;
}
lastComboInput_ = now;
if (comboIndex_ < comboSequence_.size() && button == comboSequence_[comboIndex_]) {
comboIndex_++;
if (comboIndex_ >= comboSequence_.size()) {
comboIndex_ = 0;
if (unlocked_) {
lock();
return ComboResult::Locked;
} else {
unlock();
return ComboResult::Unlocked;
}
}
return ComboResult::StepMatched;
} else {
// Wrong button pressed while grip was held
comboIndex_ = 0;
return ComboResult::Failed;
}
}
void VaultManager::recordActivity(std::chrono::steady_clock::time_point now) {
lastActivity_ = now;
}
bool VaultManager::tick(std::chrono::steady_clock::time_point now, bool headsetFocused) {
if (!unlocked_) return false;
// Guard 1: Headset removed / focus lost (debounced with 3.0s threshold to avoid momentary tracking glitches)
if (autoLockHeadsetOff_) {
if (!headsetFocused) {
if (headsetLostTime_.time_since_epoch().count() == 0) {
headsetLostTime_ = now;
} else {
auto elapsedMs = std::chrono::duration_cast<std::chrono::milliseconds>(now - headsetLostTime_).count();
if (elapsedMs >= 3000) {
PIXELVR_LOG_INFO("Auto-locking vault: headset removed or session lost focus for %lld ms",
static_cast<long long>(elapsedMs));
headsetLostTime_ = {};
lock();
return true;
}
}
} else {
headsetLostTime_ = {};
}
} else {
headsetLostTime_ = {};
}
// Guard 2: Inactivity timeout (bypassed if autoLockTimeoutSec_ <= 0)
if (autoLockTimeoutSec_ > 0 && lastActivity_.time_since_epoch().count() > 0) {
auto elapsed = std::chrono::duration_cast<std::chrono::seconds>(now - lastActivity_).count();
if (elapsed >= autoLockTimeoutSec_) {
PIXELVR_LOG_INFO("Auto-locking vault: inactivity timeout (%llds >= %ds)",
static_cast<long long>(elapsed), autoLockTimeoutSec_);
lock();
return true;
}
}
return false;
}
void VaultManager::cleanPublicThumbs(const std::string& path) {
const char* home = std::getenv("HOME");
if (!home) return;
std::error_code ec;
std::string pubThumbDir = std::string(home) + "/.cache/pixelvr/thumbs";
if (!fs::exists(pubThumbDir, ec)) return;
auto removeThumbFor = [&](const std::string& fpath) {
const std::string baseHash = std::to_string(fnv1a64(fpath));
std::error_code e;
fs::remove(pubThumbDir + "/" + baseHash + ".rgba", e);
e.clear();
fs::remove(pubThumbDir + "/" + baseHash + ".meta", e);
};
if (fs::is_directory(path, ec)) {
for (const auto& it : fs::recursive_directory_iterator(path, ec)) {
if (it.is_regular_file()) {
removeThumbFor(it.path().string());
}
}
} else {
removeThumbFor(path);
}
}
std::string VaultManager::moveFileToVault(const std::string& srcPath, std::string& outNewPath) {
if (!unlocked_) {
return "Vault is locked";
}
if (srcPath.empty()) {
return "Source path is empty";
}
std::error_code ec;
if (!fs::exists(srcPath, ec)) {
return "Path does not exist";
}
ensureDirectories();
fs::path src(srcPath);
const bool isDir = fs::is_directory(src, ec);
std::string stem = src.stem().string();
std::string ext = isDir ? "" : src.extension().string();
std::string targetFilename = src.filename().string();
fs::path dest = fs::path(vaultDir_) / targetFilename;
// Prevent collision by appending _1, _2, etc.
int counter = 1;
while (fs::exists(dest, ec)) {
targetFilename = isDir ? (stem + "_" + std::to_string(counter++))
: (stem + "_" + std::to_string(counter++) + ext);
dest = fs::path(vaultDir_) / targetFilename;
}
// Try rename first
fs::rename(src, dest, ec);
if (ec) {
ec.clear();
if (isDir) {
fs::copy(src, dest, fs::copy_options::recursive, ec);
if (ec) {
return "Failed to copy directory: " + ec.message();
}
fs::remove_all(src, ec);
} else {
fs::copy_file(src, dest, fs::copy_options::overwrite_existing, ec);
if (ec) {
return "Failed to copy file: " + ec.message();
}
fs::remove(src, ec);
}
}
// Ensure 0700 permissions
ec.clear();
fs::permissions(dest, fs::perms::owner_all, fs::perm_options::replace, ec);
if (isDir) {
for (const auto& it : fs::recursive_directory_iterator(dest, ec)) {
std::error_code pe;
fs::permissions(it.path(), fs::perms::owner_all, fs::perm_options::replace, pe);
}
}
outNewPath = dest.string();
PIXELVR_LOG_INFO("Moved into vault: %s -> %s", srcPath.c_str(), outNewPath.c_str());
// Clean up any public thumbnails that existed for srcPath
cleanPublicThumbs(srcPath);
return "";
}
void VaultManager::setAutoLockHeadsetOff(bool enable) {
autoLockHeadsetOff_ = enable;
saveConfig();
}
void VaultManager::setAutoLockTimeoutSec(int sec) {
autoLockTimeoutSec_ = sec;
saveConfig();
}
void VaultManager::setMoveButton(int btn) {
moveButton_ = btn;
saveConfig();
}
std::string VaultManager::comboString() const {
if (comboSequence_.empty()) return "None";
std::string s;
for (std::size_t i = 0; i < comboSequence_.size(); ++i) {
if (i > 0) s += " ";
s += btnName(comboSequence_[i]);
}
return s;
}
void VaultManager::startRecordingCombo() {
isRecordingCombo_ = true;
recordingBuffer_.clear();
}
void VaultManager::cancelRecordingCombo() {
isRecordingCombo_ = false;
recordingBuffer_.clear();
}
bool VaultManager::feedRecordButton(int button) {
if (!isRecordingCombo_) return false;
if (button != XrInputState::BtnA && button != XrInputState::BtnB &&
button != XrInputState::BtnX && button != XrInputState::BtnY) {
return false;
}
recordingBuffer_.push_back(button);
if (recordingBuffer_.size() >= 6) {
comboSequence_ = recordingBuffer_;
isRecordingCombo_ = false;
recordingBuffer_.clear();
saveConfig();
return true; // Finished recording 6-step combo
}
return false;
}
void VaultManager::loadConfig() {
const std::string path = getVaultConfigPath();
std::ifstream file(path);
if (!file.is_open()) return;
std::string line;
while (std::getline(file, line)) {
auto eq = line.find('=');
if (eq == std::string::npos) continue;
std::string key = line.substr(0, eq);
std::string val = line.substr(eq + 1);
if (key == "auto_lock_headset_off") {
autoLockHeadsetOff_ = (val == "1");
} else if (key == "auto_lock_timeout_sec") {
try { autoLockTimeoutSec_ = std::stoi(val); } catch (...) {}
} else if (key == "move_button") {
try { moveButton_ = std::stoi(val); } catch (...) {}
} else if (key == "combo") {
std::vector<int> loaded;
std::stringstream ss(val);
std::string item;
while (std::getline(ss, item, ',')) {
try { loaded.push_back(std::stoi(item)); } catch (...) {}
}
if (loaded.size() >= 4 && loaded.size() <= 8) {
comboSequence_ = loaded;
}
}
}
}
void VaultManager::saveConfig() const {
const std::string path = getVaultConfigPath();
try {
fs::path p(path);
if (p.has_parent_path()) {
fs::create_directories(p.parent_path());
}
std::ofstream file(path);
if (file.is_open()) {
file << "auto_lock_headset_off=" << (autoLockHeadsetOff_ ? 1 : 0) << "\n";
file << "auto_lock_timeout_sec=" << autoLockTimeoutSec_ << "\n";
file << "move_button=" << moveButton_ << "\n";
file << "combo=";
for (std::size_t i = 0; i < comboSequence_.size(); ++i) {
if (i > 0) file << ",";
file << comboSequence_[i];
}
file << "\n";
}
} catch (const std::exception& e) {
PIXELVR_LOG_WARN("Could not save vault settings: %s", e.what());
}
}
} // namespace pixelvr
+102
View File
@@ -0,0 +1,102 @@
#pragma once
#include "xr/xr_context.hpp"
#include <chrono>
#include <string>
#include <vector>
namespace pixelvr {
class VaultManager {
public:
enum class ComboResult {
None,
StepMatched,
Unlocked,
Locked,
Failed
};
static VaultManager& instance();
bool isUnlocked() const { return unlocked_; }
void lock();
void unlock();
// Process button input during frame loop.
// If gripFullPressHeld is true, face buttons are consumed for the combo and
// caller should suppress them from normal UI.
ComboResult feedInput(int button, bool gripFullPressHeld,
std::chrono::steady_clock::time_point now);
// Call when any user activity occurs (sticks, triggers, buttons)
void recordActivity(std::chrono::steady_clock::time_point now);
// Frame tick: checks inactivity timeout and headset focus loss.
// Returns true if the vault was locked as a result of the tick.
bool tick(std::chrono::steady_clock::time_point now, bool headsetFocused);
// Storage paths
const std::string& vaultDir() const { return vaultDir_; }
const std::string& thumbsDir() const { return thumbsDir_; }
bool isVaultPath(const std::string& path) const;
void ensureDirectories();
// Move file or directory into vault (local paths only).
// Returns empty string on success, or error message on failure.
std::string moveFileToVault(const std::string& srcPath, std::string& outNewPath);
// Clean up cached public thumbnails for a file or directory
void cleanPublicThumbs(const std::string& path);
// Settings
bool autoLockHeadsetOff() const { return autoLockHeadsetOff_; }
void setAutoLockHeadsetOff(bool enable);
int autoLockTimeoutSec() const { return autoLockTimeoutSec_; }
void setAutoLockTimeoutSec(int sec);
int moveButton() const { return moveButton_; }
void setMoveButton(int btn);
const std::vector<int>& comboSequence() const { return comboSequence_; }
std::string comboString() const;
// Custom combo recording
bool isRecordingCombo() const { return isRecordingCombo_; }
void startRecordingCombo();
void cancelRecordingCombo();
bool feedRecordButton(int button);
int recordedCount() const { return static_cast<int>(recordingBuffer_.size()); }
void loadConfig();
void saveConfig() const;
private:
VaultManager();
~VaultManager() = default;
bool unlocked_ = false;
std::string vaultDir_;
std::string thumbsDir_;
// Combo state machine
std::vector<int> comboSequence_;
std::size_t comboIndex_ = 0;
std::chrono::steady_clock::time_point lastComboInput_{};
// Recording custom combo
bool isRecordingCombo_ = false;
std::vector<int> recordingBuffer_;
// Settings
bool autoLockHeadsetOff_ = true;
int autoLockTimeoutSec_ = 0; // Disabled by default (headset face detection active)
int moveButton_ = XrInputState::BtnY;
std::chrono::steady_clock::time_point lastActivity_{};
std::chrono::steady_clock::time_point headsetLostTime_{};
};
} // namespace pixelvr
+18 -3
View File
@@ -5,6 +5,7 @@
#ifdef PIXELVR_HAVE_FREETYPE
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_MODULE_H
#endif
namespace pixelvr {
@@ -17,6 +18,15 @@ FontAtlas buildFontAtlas(const char* ttfPath, int pixelHeight) {
PIXELVR_LOG_ERROR("FreeType: init failed");
return atlas;
}
// Expand the distance field ramp from FreeType's default 2px to 8px.
// At typical VR UI viewing distances, 8 font pixels produces a smooth,
// noise-free gradient spanning multiple screen pixels, completely eliminating
// edge shimmering during head movement.
constexpr FT_UInt kSpread = 8;
FT_Property_Set(lib, "sdf", "spread", &kSpread);
FT_Property_Set(lib, "bsdf", "spread", &kSpread);
atlas.spread = static_cast<float>(kSpread);
FT_Face face = nullptr;
if (FT_New_Face(lib, ttfPath, 0, &face) != 0) {
PIXELVR_LOG_ERROR("FreeType: cannot open %s", ttfPath);
@@ -26,7 +36,7 @@ FontAtlas buildFontAtlas(const char* ttfPath, int pixelHeight) {
FT_Set_Pixel_Sizes(face, 0, static_cast<FT_UInt>(pixelHeight));
constexpr int kFirst = 32;
constexpr int kLast = 126;
constexpr int kLast = 127;
constexpr int kCols = 16;
const int count = kLast - kFirst + 1;
const int rows = (count + kCols - 1) / kCols;
@@ -39,8 +49,13 @@ FontAtlas buildFontAtlas(const char* ttfPath, int pixelHeight) {
atlas.ascent = face->size->metrics.ascender / 64.0f;
for (int ch = kFirst; ch <= kLast; ++ch) {
if (FT_Load_Char(face, static_cast<FT_ULong>(ch), FT_LOAD_DEFAULT) != 0) {
continue;
FT_ULong codepoint = (ch == 127) ? 0x2022UL : static_cast<FT_ULong>(ch);
if (FT_Load_Char(face, codepoint, FT_LOAD_DEFAULT) != 0) {
if (ch == 127 && FT_Load_Char(face, 0x00B7UL, FT_LOAD_DEFAULT) != 0) {
continue;
} else if (ch != 127) {
continue;
}
}
const FT_GlyphSlot g = face->glyph;
// Render a signed-distance field (crisp at any VR distance); fall back to
+1
View File
@@ -22,6 +22,7 @@ struct FontAtlas {
float lineHeight = 0.0f;
float ascent = 0.0f;
bool sdf = false; // true = signed-distance field (crisp at scale)
float spread = 8.0f; // SDF spread distance in font pixels (contour zero-crossing at 128)
bool ok = false;
};
+1807 -627
View File
File diff suppressed because it is too large. Load diff
+180 -24
View File
@@ -13,6 +13,7 @@ namespace pixelvr {
class XrContext;
struct ViewSwapchain;
struct DrmVideoFrame;
struct GltfMesh;
// Owns the Vulkan device (created through OpenXR) and the per-eye render
// resources. For Phase 0/1 it draws a pose-anchored test triangle into each eye
@@ -96,6 +97,13 @@ public:
void recenterScreen(const float headPos[3], const float headForward[3]);
// Moves the flat screen farther (positive) or nearer (negative), clamped.
void adjustScreenDistance(float delta);
// Parametric curvature for cinema screen: 0.0 = flat plane, 1.0 = full cylinder wrap.
void setScreenCurvature(float c) { screenCurvature_ = c < 0.0f ? 0.0f : (c > 1.0f ? 1.0f : c); }
float screenCurvature() const { return screenCurvature_; }
void adjustScreenCurvature(float delta) {
setScreenCurvature(screenCurvature_ + delta);
}
// Transport HUD: progress in [0,1]. Drawn head-locked when visible.
void setTransport(bool visible, float progress, bool paused,
@@ -110,22 +118,63 @@ public:
bool pointerOnTimeToggle() const { return pointerOnTimeToggle_; }
void toggleTimeDisplay() { timeShowRemaining_ = !timeShowRemaining_; }
// File browser overlay: a title, list rows, selected index and a status line.
struct BrowserItem {
std::string name;
std::string path;
std::string detail;
std::string tag;
std::string durationTag;
std::string previewPath;
bool isDir = false;
bool isVideo = false;
bool isBack = false;
};
struct DownloadItem {
std::string label;
int state = 0; // 0=active, 1=done, 2=failed, 3=stopped
float progress = 0.0f; // 0.0 to 1.0
std::string detail;
};
// File browser overlay: rich spatial card grid + sidebar navigation
void setBrowserItems(bool visible, const std::string& title,
const std::vector<BrowserItem>& items, int selected,
const std::string& status);
void setBrowser(bool visible, const std::string& title,
const std::vector<std::string>& rows, int selected,
const std::string& status);
void updateCardThumbnail(int slot, const std::string& path, const uint8_t* rgba, int width, int height);
void clearCardThumbnails();
int browserFirst() const { return browserFirst_; }
int browserSidebarHovered() const { return browserSidebarHovered_; }
int browserPageBtnHovered() const { return browserPageBtnHovered_; }
void setDownloadsFilter(int f) { downloadsFilter_ = f; }
int downloadsFilter() const { return downloadsFilter_; }
void setActiveDownloadCount(int c) { activeDownloadCount_ = c; }
void setSettingsSection(int s) { settingsSection_ = s; }
void setVaultUnlocked(bool u) { vaultUnlocked_ = u; }
bool vaultUnlocked() const { return vaultUnlocked_; }
void setUiAppearance(float textScale, int textColorIdx, int accentColorIdx,
float uiDistance) {
uiTextScale_ = textScale;
uiTextColorIdx_ = textColorIdx;
uiAccentColorIdx_ = accentColorIdx;
uiDistance_ = uiDistance;
}
// Downloads overlay: a simple list of download jobs plus a status line,
// shown while downloads run (and briefly after) with the browser closed.
// Downloads overlay: modern glassmorphic window with job cards
void setDownloads(bool visible, const std::string& title,
const std::vector<std::string>& rows,
const std::string& status,
const std::vector<std::string>& buttons = {}) {
const std::vector<std::string>& buttons = {},
const std::vector<DownloadItem>& jobs = {}) {
downloadsVisible_ = visible;
downloadsTitle_ = title;
downloadsRows_ = rows;
downloadsStatus_ = status;
downloadsButtons_ = buttons; // content-sized buttons along the bottom
downloadJobs_ = jobs;
}
// Draws a stronger modal backdrop behind the panel (for confirmations).
void setDownloadsModal(bool modal) { downloadsModal_ = modal; }
@@ -133,6 +182,22 @@ public:
int downloadsHovered() const { return downloadsHovered_; }
int downloadsButtonHovered() const { return downloadsBtnHovered_; }
// File Action Submenu (opened by button Y in file browser)
struct ActionMenuData {
bool visible = false;
int page = 0; // 0: Main, 1: MoveDestinations, 2: DeleteConfirm, 3: Rename
std::string title;
std::string subtitle;
std::vector<std::string> options;
int selectedOption = -1;
std::string renameBuffer;
};
void setActionMenu(const ActionMenuData& data) { actionMenu_ = data; }
const ActionMenuData& actionMenu() const { return actionMenu_; }
int actionMenuBtnHovered() const { return actionMenuBtnHovered_; }
int actionMenuKeyHovered() const { return actionMenuKeyHovered_; }
void setBrowserNetwork(bool onNet) { browserOnNetwork_ = onNet; }
// Tracked controllers: aim poses used to draw pointer rays, controller
// models and the UI cursor. Index 0 = left, 1 = right. Call once per frame,
// after setBrowser, so the pointer can be raycast against the current panel.
@@ -149,8 +214,11 @@ public:
void setControllers(const ControllerVis& left, const ControllerVis& right);
// Replaces the procedural controller geometry with the runtime-provided glTF
// render model (parsed from the GLB bytes). Call once when the asset is ready.
bool loadControllerModel(const std::vector<uint8_t>& glb);
// render model (parsed from the GLB bytes) for hand (0 = left, 1 = right).
bool loadControllerModel(int hand, const std::vector<uint8_t>& glb);
bool loadControllerModel(const std::vector<uint8_t>& glb) {
return loadControllerModel(1, glb);
}
// Per-node animated transforms from xrGetRenderModelStateEXT, matched to
// submeshes by node name (drives button-press motion on the model).
@@ -160,7 +228,10 @@ public:
float quat[4] = {0.0f, 0.0f, 0.0f, 1.0f};
bool visible = true;
};
void setControllerNodeStates(const std::vector<NodeStateVis>& states);
void setControllerNodeStates(int hand, const std::vector<NodeStateVis>& states);
void setControllerNodeStates(const std::vector<NodeStateVis>& states) {
setControllerNodeStates(1, states);
}
enum class UiShape : int {
RoundedBox = 0,
@@ -177,19 +248,22 @@ public:
Stop = 11,
Download = 12,
List = 13,
GlowRing = 14,
Speaker = 15,
Headset = 16,
CurvedDisplay = 17,
Chevron = 18,
Home = 19,
};
// The browser row currently under the pointer, or -1 if none.
int pointerRow() const { return pointerRow_; }
int browserHovered() const { return browserHovered_; }
int browserFirst() const { return browserFirst_; }
void scrollBrowser(int deltaRows);
// Updates just the highlighted browser row (used by the pointer each frame).
void setBrowserSelected(int index) { browserSelected_ = index; }
// Media control bar shown below the video (point-and-click transport). The
// buttons are: seek back, play/pause, seek forward, open files, settings, recenter.
enum class CtrlButton {
SeekBack = 0,
PlayPause = 1,
@@ -198,9 +272,35 @@ public:
Files = 4,
Settings = 5,
Downloads = 6, // open the downloads window (list of jobs)
Download = 7 // download the focused file-browser entry
Download = 7, // download the focused file-browser entry
FormatToggle = 8,
AudioToggle = 9,
ScreenToggle = 10,
Recenter = 11 // recenter screen/view from HUD
};
void setControlBar(bool visible) { controlBarVisible_ = visible; }
void setHudLabels(const std::string& format, const std::string& audio,
const std::string& screen, bool formatEnabled = true,
bool audioEnabled = true) {
hudFormat_ = format;
hudAudio_ = audio;
hudScreen_ = screen;
hudFormatEnabled_ = formatEnabled;
hudAudioEnabled_ = audioEnabled;
}
// Per-hand laser pointer toggle (grip full press). Only one controller has
// an active laser pointer at any time. When a hand enables its laser, the
// other hand's laser is turned off.
void setLaserOn(int hand, bool on) {
if (hand >= 0 && hand < 2) {
laserOn_[hand] = on;
if (on) laserOn_[1 - hand] = false;
}
}
bool laserOn(int hand) const {
return (hand >= 0 && hand < 2) ? laserOn_[hand] : false;
}
// The control-bar button currently under the pointer, or -1 if none.
int pointerButton() const { return pointerButton_; }
@@ -307,9 +407,16 @@ private:
bool downloadsFailed_ = false;
bool downloadsModal_ = false;
std::vector<std::string> downloadsButtons_;
std::vector<DownloadItem> downloadJobs_;
int downloadsBtnHovered_ = -1;
int downloadsHovered_ = -1;
// Action menu state
ActionMenuData actionMenu_{};
int actionMenuBtnHovered_ = -1;
int actionMenuKeyHovered_ = -1;
bool browserOnNetwork_ = false;
// Flat-screen placement in the app reference space (updated by recenter and
// thumbstick distance control).
float screenPivot_[3] = {0.0f, 0.0f, 0.0f};
@@ -320,6 +427,7 @@ private:
float spherePitch_ = 0.0f; // 360/180 viewpoint tilt (radians)
float sphereZoom_ = 1.0f; // 360/180 FOV scale (>1 pushes content farther)
float screenDistance_ = 3.0f;
float screenCurvature_ = 0.0f; // 0.0 = flat plane (default), 1.0 = deep cinema curve
// Transport HUD state.
bool transportVisible_ = false;
@@ -329,12 +437,32 @@ private:
double transportDuration_ = 0.0; // seconds total
bool timeShowRemaining_ = false; // right readout shows time-left vs. total
bool pointerOnTimeToggle_ = false;
std::string hudFormat_ = "2D FLAT";
std::string hudAudio_ = "AUDIO";
std::string hudScreen_ = "CURVED";
bool hudFormatEnabled_ = true;
bool hudAudioEnabled_ = true;
float sphereFollowYaw_ = 0.0f;
bool sphereFollowInit_ = false;
struct CardThumbnail {
VkImage image = VK_NULL_HANDLE;
VkDeviceMemory memory = VK_NULL_HANDLE;
VkImageView view = VK_NULL_HANDLE;
VkDescriptorSet set = VK_NULL_HANDLE;
std::string path;
bool ready = false;
};
CardThumbnail cardThumbs_[6];
VkPipeline thumbPipeline_ = VK_NULL_HANDLE;
VkDescriptorPool thumbPool_ = VK_NULL_HANDLE;
// Text rendering (FreeType glyph atlas) + file browser overlay.
FontAtlas fontAtlas_;
VkImage fontImage_ = VK_NULL_HANDLE;
VkDeviceMemory fontMemory_ = VK_NULL_HANDLE;
VkImageView fontView_ = VK_NULL_HANDLE;
VkSampler fontSampler_ = VK_NULL_HANDLE;
VkDescriptorSetLayout textSetLayout_ = VK_NULL_HANDLE;
VkDescriptorPool textPool_ = VK_NULL_HANDLE;
VkDescriptorSet textSet_ = VK_NULL_HANDLE;
@@ -349,6 +477,16 @@ private:
int browserSelected_ = 0;
int browserHovered_ = -1; // pointer hover target (independent of scroll)
int browserFirst_ = 0; // scroll offset for visible window
std::vector<BrowserItem> browserItems_;
int browserSidebarHovered_ = -1;
int browserPageBtnHovered_ = -1;
int downloadsFilter_ = 0; // 0=All, 1=Active, 2=Completed
int activeDownloadCount_ = 0;
int settingsSection_ = 0;
float uiTextScale_ = 1.20f;
int uiTextColorIdx_ = 0;
int uiAccentColorIdx_ = 0;
float uiDistance_ = 1.9f;
// Settings panel overlay
bool settingsVisible_ = false;
@@ -365,8 +503,12 @@ private:
bool pointerActive_ = false;
int pointerRow_ = -1;
int pointerHand_ = -1;
// Whether each hand's laser pointer is on. Only one controller has an active
// laser pointer at any time. Defaults to right controller active, left off.
bool laserOn_[2] = {false, true};
float pointerHit_[3] = {0.0f, 0.0f, 0.0f};
bool controlBarVisible_ = false;
bool vaultUnlocked_ = false;
int pointerButton_ = -1;
bool pointerOnTimeline_ = false;
float pointerScrub_ = 0.0f;
@@ -470,18 +612,18 @@ private:
int resolveH_ = 0;
uint32_t resolveMips_ = 1;
// Lit, textured 3D controller render models. The merged glTF geometry is
// split into submeshes by material; each samples its own base-color texture
// (which carries the part colors and printed button labels). Drawn with the
// depth buffer so near parts occlude far ones.
// Lit, textured 3D controller render models. The glTF geometry is loaded
// separately for left (0) and right (1) hands into handModels_[2].
// Drawn with the depth buffer so near parts occlude far ones.
VkPipelineLayout modelLayout_ = VK_NULL_HANDLE;
VkPipeline modelPipeline_ = VK_NULL_HANDLE;
VkBuffer modelVertexBuffer_ = VK_NULL_HANDLE;
VkDeviceMemory modelVertexMemory_ = VK_NULL_HANDLE;
VkBuffer modelIndexBuffer_ = VK_NULL_HANDLE;
VkDeviceMemory modelIndexMemory_ = VK_NULL_HANDLE;
uint32_t modelIndexCount_ = 0;
VkIndexType modelIndexType_ = VK_INDEX_TYPE_UINT16; // UINT32 for glTF models
// Procedural capsule fallback buffers (used before glTF is fetched)
VkBuffer capsuleVertexBuffer_ = VK_NULL_HANDLE;
VkDeviceMemory capsuleVertexMemory_ = VK_NULL_HANDLE;
VkBuffer capsuleIndexBuffer_ = VK_NULL_HANDLE;
VkDeviceMemory capsuleIndexMemory_ = VK_NULL_HANDLE;
uint32_t capsuleIndexCount_ = 0;
struct ModelTexture {
VkImage image = VK_NULL_HANDLE;
@@ -496,13 +638,27 @@ private:
float color[4] = {1.0f, 1.0f, 1.0f, 1.0f};
std::string nodeName; // matched to an animated render-model node state
};
struct HandModel {
VkBuffer vertexBuffer = VK_NULL_HANDLE;
VkDeviceMemory vertexMemory = VK_NULL_HANDLE;
VkBuffer indexBuffer = VK_NULL_HANDLE;
VkDeviceMemory indexMemory = VK_NULL_HANDLE;
uint32_t indexCount = 0;
VkIndexType indexType = VK_INDEX_TYPE_UINT32;
std::vector<ModelTexture> textures;
std::vector<ModelSubmesh> submeshes;
std::vector<NodeStateVis> nodeStates;
bool ready = false;
};
HandModel handModels_[2]; // 0 = left, 1 = right
VkDescriptorSetLayout modelSetLayout_ = VK_NULL_HANDLE;
VkDescriptorPool modelDescPool_ = VK_NULL_HANDLE;
VkSampler modelSampler_ = VK_NULL_HANDLE;
ModelTexture modelWhite_; // 1x1 white fallback for untextured submeshes
std::vector<ModelTexture> modelTextures_;
std::vector<ModelSubmesh> modelSubmeshes_;
std::vector<NodeStateVis> modelNodeStates_;
void destroyHandModel(HandModel& hm);
bool uploadHandMesh(int hand, const GltfMesh& mesh);
bool createModelTexture(const uint8_t* rgba, int width, int height,
ModelTexture& out);
};
+10
View File
@@ -464,6 +464,11 @@ struct MediaEngine::Impl {
return false;
}
codec->pkt_timebase = s->time_base;
codec->thread_count = 0; // Multi-threaded SW decode across all CPU cores
codec->thread_type = FF_THREAD_FRAME | FF_THREAD_SLICE;
if (std::strstr(videoDecoder->name, "v4l2m2m") != nullptr) {
av_opt_set_int(codec->priv_data, "num_output_buffers", 4, 0);
}
if (decoderDrm) {
av_opt_set_int(codec->priv_data, "num_capture_buffers", captureBuffers, 0);
av_opt_set_int(codec->priv_data, "drm_prime", 1, 0);
@@ -922,7 +927,12 @@ bool MediaEngine::open(const std::string& path) {
return false;
}
impl_->codec->pkt_timebase = stream->time_base;
impl_->codec->thread_count = 0; // Auto-detect and utilize all CPU cores
impl_->codec->thread_type = FF_THREAD_FRAME | FF_THREAD_SLICE;
impl_->videoDecoder = dec; // retained so the decode thread can reopen on seek
if (std::strstr(dec->name, "v4l2m2m") != nullptr) {
av_opt_set_int(impl_->codec->priv_data, "num_output_buffers", 4, 0);
}
impl_->decoderDrm = drmPrime && std::strstr(dec->name, "v4l2m2m") != nullptr;
if (impl_->decoderDrm) {
// Export decoder output as DMA-BUF (AV_PIX_FMT_DRM_PRIME) for zero-copy
+362 -24
View File
@@ -1,4 +1,5 @@
#include "ui/browser.hpp"
#include "app/vault_manager.hpp"
#include "util/logging.hpp"
#include "util/smb_lock.hpp"
@@ -81,11 +82,14 @@ std::string smb_parent(const std::string& uri) {
void sort_and_append(std::vector<Browser::Entry>& out,
std::vector<Browser::Entry>& dirs,
std::vector<Browser::Entry>& files) {
auto by_label = [](const Browser::Entry& a, const Browser::Entry& b) {
auto by_media_then_label = [](const Browser::Entry& a, const Browser::Entry& b) {
const bool aHasMedia = a.isVideo || !a.previewPath.empty();
const bool bHasMedia = b.isVideo || !b.previewPath.empty();
if (aHasMedia != bHasMedia) return aHasMedia > bHasMedia;
return a.label < b.label;
};
std::sort(dirs.begin(), dirs.end(), by_label);
std::sort(files.begin(), files.end(), by_label);
std::sort(dirs.begin(), dirs.end(), by_media_then_label);
std::sort(files.begin(), files.end(), by_media_then_label);
out.insert(out.end(), dirs.begin(), dirs.end());
out.insert(out.end(), files.begin(), files.end());
}
@@ -141,7 +145,11 @@ std::string format_size(long long bytes) {
void Browser::scanLocalInto(const std::string& dir, ScanResult& out) {
out.inSmb = false;
out.location = dir;
out.title = dir;
if (VaultManager::instance().isVaultPath(dir)) {
out.title = "Vault (Private)";
} else {
out.title = dir;
}
out.entries.clear();
if (dir == homeDir_) {
@@ -160,12 +168,65 @@ void Browser::scanLocalInto(const std::string& dir, ScanResult& out) {
if (name.empty() || name[0] == '.') continue; // skip hidden
std::error_code dec;
if (it->is_directory(dec)) {
dirs.push_back({name + "/", p.string(), true, false, false, false});
if (dir == homeDir_) {
if (name == "devkit-game" || name == "devkit-utils" ||
name == "ffbuild" || name == "pixelvr-src" ||
name == "steamvr" || name == "work" ||
name == "Desktop" || name == "Templates" ||
name == "Public" || name == "Documents" || name == "Music") {
continue;
}
}
std::string preview;
long long bestPreviewSize = -1;
int videoCount = 0;
std::error_code sec;
for (fs::directory_iterator subIt(p, sec), subEnd; !sec && subIt != subEnd; subIt.increment(sec)) {
const std::string subName = subIt->path().filename().string();
if (subName.empty() || subName[0] == '.') continue;
std::error_code sdec;
if (!subIt->is_directory(sdec) && is_video(subName)) {
std::error_code fsec;
const long long vsz = static_cast<long long>(fs::file_size(subIt->path(), fsec));
const long long score = (!fsec ? vsz : 1);
if (score > bestPreviewSize) {
bestPreviewSize = score;
preview = subIt->path().string();
}
++videoCount;
} else if (subIt->is_directory(sdec)) {
// Check one level deeper (e.g. ~/Videos/MovieFolder/movie.mp4)
std::error_code ssec2;
for (fs::directory_iterator subIt2(subIt->path(), ssec2), subEnd2;
!ssec2 && subIt2 != subEnd2; subIt2.increment(ssec2)) {
const std::string subName2 = subIt2->path().filename().string();
if (subName2.empty() || subName2[0] == '.') continue;
if (!subIt2->is_directory(ssec2) && is_video(subName2)) {
std::error_code fsec2;
const long long vsz2 = static_cast<long long>(fs::file_size(subIt2->path(), fsec2));
const long long score2 = (!fsec2 ? vsz2 : 1);
if (score2 > bestPreviewSize) {
bestPreviewSize = score2;
preview = subIt2->path().string();
}
++videoCount;
}
}
}
}
std::string detail = (videoCount > 0)
? (std::to_string(videoCount) + (videoCount == 1 ? " video" : " videos") +
(bestPreviewSize > 0 ? " \xB7 " + format_size(bestPreviewSize) : ""))
: "Folder";
dirs.push_back({name + "/", p.string(), true, false, false, false, detail,
bestPreviewSize > 0 ? bestPreviewSize : 0, preview});
} else {
const bool isVid = is_video(name);
if (dir == homeDir_ && !isVid) continue; // hide log/tarball files in home root
std::error_code sec;
const long long sz = static_cast<long long>(fs::file_size(p, sec));
files.push_back({name, p.string(), false, is_video(name), false, false,
format_size(sec ? 0 : sz), sec ? 0 : sz});
files.push_back({name, p.string(), false, isVid, false, false,
format_size(sec ? 0 : sz), sec ? 0 : sz, isVid ? p.string() : ""});
}
}
sort_and_append(out.entries, dirs, files);
@@ -305,6 +366,181 @@ void Browser::openPath(const std::string& localDir) {
beginScan(localDir, false);
}
void Browser::openNetwork() {
open_ = true;
browseOpen_.store(true);
status_.clear();
beginScan("smb://", true);
}
void Browser::openHome() {
openPath(homeDir_);
}
void Browser::openVideos() {
const std::string v = homeDir_ + "/Videos";
std::error_code ec;
if (fs::is_directory(v, ec)) {
openPath(v);
} else {
openPath(homeDir_);
}
}
void Browser::openDownloads() {
std::error_code ec;
if (!fs::is_directory(downloadDir_, ec)) {
fs::create_directories(downloadDir_, ec);
}
openPath(downloadDir_);
}
void Browser::openDrives() {
const std::string d = "/run/media";
std::error_code ec;
if (fs::is_directory(d, ec)) {
openPath(d);
} else {
openPath("/");
}
}
void Browser::openVault() {
if (!VaultManager::instance().isUnlocked()) return;
VaultManager::instance().ensureDirectories();
openPath(VaultManager::instance().vaultDir());
}
bool Browser::inVault() const {
return VaultManager::instance().isVaultPath(location_);
}
bool Browser::moveFocusedToVault(std::string& outNewPath) {
if (!VaultManager::instance().isUnlocked()) return false;
const Entry* e = focused();
if (e == nullptr || e->isBack || inSmb_) return false;
std::string err = VaultManager::instance().moveFileToVault(e->path, outNewPath);
if (!err.empty()) {
status_ = "Move error: " + err;
return false;
}
status_ = "Moved " + e->label + " to Vault";
beginScan(location_, inSmb_);
return true;
}
bool Browser::moveFocusedTo(const std::string& destDir, std::string& outNewPath) {
const Entry* e = focused();
if (e == nullptr || e->isBack || inSmb_) return false;
std::error_code ec;
if (!fs::exists(destDir, ec) || !fs::is_directory(destDir, ec)) {
status_ = "Destination folder does not exist";
return false;
}
fs::path src(e->path);
const bool isDir = fs::is_directory(src, ec);
std::string stem = src.stem().string();
std::string ext = isDir ? "" : src.extension().string();
std::string targetFilename = src.filename().string();
fs::path dest = fs::path(destDir) / targetFilename;
int counter = 1;
while (fs::exists(dest, ec)) {
targetFilename = isDir ? (stem + "_" + std::to_string(counter++))
: (stem + "_" + std::to_string(counter++) + ext);
dest = fs::path(destDir) / targetFilename;
}
fs::rename(src, dest, ec);
if (ec) {
ec.clear();
if (isDir) {
fs::copy(src, dest, fs::copy_options::recursive, ec);
if (ec) {
status_ = "Move failed: " + ec.message();
return false;
}
fs::remove_all(src, ec);
} else {
fs::copy_file(src, dest, fs::copy_options::overwrite_existing, ec);
if (ec) {
status_ = "Move failed: " + ec.message();
return false;
}
fs::remove(src, ec);
}
}
outNewPath = dest.string();
status_ = "Moved " + e->label + " to " + fs::path(destDir).filename().string();
beginScan(location_, inSmb_);
return true;
}
bool Browser::deleteFocused(std::string& deletedName) {
const Entry* e = focused();
if (e == nullptr || e->isBack || inSmb_) return false;
std::error_code ec;
deletedName = e->label;
fs::path p(e->path);
VaultManager::instance().cleanPublicThumbs(e->path);
if (fs::is_directory(p, ec)) {
fs::remove_all(p, ec);
} else {
fs::remove(p, ec);
}
if (ec) {
status_ = "Delete failed: " + ec.message();
return false;
}
status_ = "Deleted " + deletedName;
beginScan(location_, inSmb_);
return true;
}
bool Browser::renameFocused(const std::string& newName) {
const Entry* e = focused();
if (e == nullptr || e->isBack || inSmb_ || newName.empty()) return false;
std::error_code ec;
fs::path src(e->path);
fs::path dest = src.parent_path() / newName;
if (dest == src) return true; // unchanged
if (fs::exists(dest, ec)) {
status_ = "An item with that name already exists";
return false;
}
fs::rename(src, dest, ec);
if (ec) {
status_ = "Rename failed: " + ec.message();
return false;
}
status_ = "Renamed to " + newName;
beginScan(location_, inSmb_);
return true;
}
std::string Browser::parentDir() const {
if (location_.empty() || location_ == "/" || inSmb_) return "";
fs::path p(location_);
return p.parent_path().string();
}
std::string Browser::homeDir() const {
const char* h = std::getenv("HOME");
return h ? std::string(h) : "/";
}
std::string Browser::videosDir() const {
std::string d = homeDir() + "/Videos";
std::error_code ec;
return fs::is_directory(d, ec) ? d : homeDir();
}
std::string Browser::downloadsDir() const {
std::string d = homeDir() + "/Downloads";
std::error_code ec;
return fs::is_directory(d, ec) ? d : homeDir();
}
void Browser::runScan(std::string location, bool isSmb) {
ScanResult r;
if (isSmb) {
@@ -337,8 +573,17 @@ Browser::Result Browser::activate(std::string& playPath) {
beginScan(parent, true);
}
} else {
const fs::path p(location_);
beginScan(p.has_parent_path() ? p.parent_path().string() : "/", false);
if (VaultManager::instance().isVaultPath(location_)) {
if (location_ == VaultManager::instance().vaultDir()) {
beginScan(homeDir_, false);
} else {
const fs::path p(location_);
beginScan(p.has_parent_path() ? p.parent_path().string() : homeDir_, false);
}
} else {
const fs::path p(location_);
beginScan(p.has_parent_path() ? p.parent_path().string() : "/", false);
}
}
return Result::Navigated;
}
@@ -362,7 +607,7 @@ Browser::Result Browser::activate(std::string& playPath) {
}
bool Browser::downloadFocused() {
if (dlActive_.load() || selected_ < 0 ||
if (selected_ < 0 ||
selected_ >= static_cast<int>(entries_.size())) {
return false;
}
@@ -393,19 +638,36 @@ Browser::~Browser() {
void Browser::startDownload(const std::string& uri, const std::string& nameIn,
bool isDir) {
if (dlActive_.load()) return;
std::string name = nameIn;
while (!name.empty() && name.back() == '/') name.pop_back();
const std::size_t slash = name.find_last_of('/');
if (slash != std::string::npos) name = name.substr(slash + 1);
if (name.empty()) return;
dlName_ = name;
for (const auto& j : dlJobs_) {
if (j.uri == uri && (j.state == 0 || j.state == 4)) {
status_ = "Already downloading or in queue: " + name;
return;
}
}
const std::string destDir =
downloadDir_.empty() ? homeDir_ + "/media" : downloadDir_;
const std::string targetPath = destDir + "/" + name;
if (dlActive_.load()) {
dlQueue_.push_back({uri, name, targetPath, isDir});
dlJobs_.push_back({name, targetPath, uri, 4, 0, 0, isDir});
status_ = "Added to download queue: " + name;
PIXELVR_LOG_INFO("Added to download queue: %s (%s)", name.c_str(), uri.c_str());
return;
}
dlName_ = name;
if (isDir) {
startDownloadFolder(uri, destDir + "/" + name);
startDownloadFolder(uri, targetPath);
} else {
startDownloadFile(uri, destDir + "/" + name);
startDownloadFile(uri, targetPath);
}
}
@@ -433,11 +695,33 @@ void Browser::startDownloadFile(const std::string& uri, const std::string& local
dlActive_.store(true);
status_ = "Downloading " + dlName_ + " ...";
PIXELVR_LOG_INFO("Download file: %s -> %s", uri.c_str(), local.c_str());
dlJobs_.push_back({dlName_, local, uri, 0, 0, 0, false});
dlActiveJob_ = static_cast<int>(dlJobs_.size()) - 1;
if (dlJobs_.size() > 12) {
dlJobs_.erase(dlJobs_.begin());
int existingIdx = -1;
for (std::size_t i = 0; i < dlJobs_.size(); ++i) {
if (dlJobs_[i].uri == uri && (dlJobs_[i].state == 4 || dlJobs_[i].state == 0)) {
existingIdx = static_cast<int>(i);
dlJobs_[i].state = 0;
dlJobs_[i].name = dlName_;
dlJobs_[i].localPath = local;
break;
}
}
if (existingIdx >= 0) {
dlActiveJob_ = existingIdx;
} else {
dlJobs_.push_back({dlName_, local, uri, 0, 0, 0, false});
dlActiveJob_ = static_cast<int>(dlJobs_.size()) - 1;
if (dlJobs_.size() > 16) {
for (auto it = dlJobs_.begin(); it != dlJobs_.end(); ++it) {
if (it->state != 0 && it->state != 4) {
dlJobs_.erase(it);
break;
}
}
for (std::size_t i = 0; i < dlJobs_.size(); ++i) {
if (dlJobs_[i].state == 0) dlActiveJob_ = static_cast<int>(i);
}
}
}
const std::string name = dlName_;
dlLocalPath_ = local;
@@ -557,11 +841,32 @@ void Browser::startDownloadFolder(const std::string& uri,
dlStopped_.store(false);
dlPaused_.store(false);
dlAbort_.store(false);
dlJobs_.push_back({dlName_, destDir, uri, 0, 0, 0, true});
dlActiveJob_ = static_cast<int>(dlJobs_.size()) - 1;
if (dlJobs_.size() > 12) {
dlJobs_.erase(dlJobs_.begin());
int existingIdx = -1;
for (std::size_t i = 0; i < dlJobs_.size(); ++i) {
if (dlJobs_[i].uri == uri && (dlJobs_[i].state == 4 || dlJobs_[i].state == 0)) {
existingIdx = static_cast<int>(i);
dlJobs_[i].state = 0;
dlJobs_[i].name = dlName_;
dlJobs_[i].localPath = destDir;
break;
}
}
if (existingIdx >= 0) {
dlActiveJob_ = existingIdx;
} else {
dlJobs_.push_back({dlName_, destDir, uri, 0, 0, 0, true});
dlActiveJob_ = static_cast<int>(dlJobs_.size()) - 1;
if (dlJobs_.size() > 16) {
for (auto it = dlJobs_.begin(); it != dlJobs_.end(); ++it) {
if (it->state != 0 && it->state != 4) {
dlJobs_.erase(it);
break;
}
}
for (std::size_t i = 0; i < dlJobs_.size(); ++i) {
if (dlJobs_[i].state == 0) dlActiveJob_ = static_cast<int>(i);
}
}
}
dlThread_ = std::thread([this, uri, destDir]() {
std::error_code ec;
@@ -734,8 +1039,8 @@ void Browser::clearFinished() {
std::vector<DownloadJob> keep;
keep.reserve(dlJobs_.size());
for (const DownloadJob& j : dlJobs_) {
if (j.state == 0) {
keep.push_back(j); // keep the in-flight job
if (j.state == 0 || j.state == 4) {
keep.push_back(j); // keep the in-flight and queued jobs
continue;
}
// Remove partial files from stopped/failed single-file downloads.
@@ -752,6 +1057,38 @@ void Browser::clearFinished() {
status_ = "Cleared finished downloads";
}
void Browser::cancelQueued(const std::string& uri) {
for (auto it = dlQueue_.begin(); it != dlQueue_.end(); ++it) {
if (it->uri == uri) {
dlQueue_.erase(it);
break;
}
}
for (auto it = dlJobs_.begin(); it != dlJobs_.end(); ++it) {
if (it->uri == uri && it->state == 4) {
dlJobs_.erase(it);
break;
}
}
status_ = "Removed from download queue";
}
void Browser::startNextQueued() {
if (dlActive_.load()) return;
if (dlQueue_.empty()) return;
DownloadQueueItem item = dlQueue_.front();
dlQueue_.pop_front();
dlName_ = item.name;
PIXELVR_LOG_INFO("Starting next queued download: %s (%s)", item.name.c_str(), item.uri.c_str());
if (item.isDir) {
startDownloadFolder(item.uri, item.destDir);
} else {
startDownloadFile(item.uri, item.destDir);
}
}
void Browser::measureFolder(const std::string& uri) {
#ifdef PIXELVR_HAVE_SMB
if (measuring_.load()) return;
@@ -889,6 +1226,7 @@ Browser::Result Browser::poll(std::string& playPath) {
} else {
status_ = "Download failed: " + dlName_;
}
startNextQueued();
}
return Result::None;
}
+30 -1
View File
@@ -2,6 +2,7 @@
#include <atomic>
#include <chrono>
#include <deque>
#include <mutex>
#include <string>
#include <thread>
@@ -23,6 +24,7 @@ public:
bool isNetwork = false; // "Network (SMB)" entry point
std::string detail; // human-readable type/size for the row
long long size = 0; // bytes (0 if unknown)
std::string previewPath; // video file inside folder or self (for thumbnail)
};
enum class Result { None, Navigated, Play };
@@ -33,6 +35,23 @@ public:
// Opens the browser directly at a local directory (used when a finished
// folder download is selected).
void openPath(const std::string& localDir);
// Direct shortcut navigation (for spatial browser sidebar rail)
void openNetwork();
void openHome();
void openVideos();
void openDownloads();
void openDrives();
void openVault();
bool inVault() const;
bool moveFocusedToVault(std::string& outNewPath);
bool moveFocusedTo(const std::string& destDir, std::string& outNewPath);
bool deleteFocused(std::string& deletedName);
bool renameFocused(const std::string& newName);
const std::string& currentLocation() const { return location_; }
std::string parentDir() const;
std::string homeDir() const;
std::string videosDir() const;
std::string downloadsDir() const;
bool isOpen() const { return open_; }
// The download worker yields the shared SMB connection while the browser is
// open, so directory listing stays responsive (downloads resume afterwards).
@@ -97,13 +116,21 @@ public:
std::string name;
std::string localPath;
std::string uri;
int state = 0; // 0 downloading, 1 done, 2 failed, 3 stopped
int state = 0; // 0 downloading, 1 done, 2 failed, 3 stopped, 4 queued
long long bytes = 0;
long long total = 0;
bool isDir = false;
};
struct DownloadQueueItem {
std::string uri;
std::string name;
std::string destDir;
bool isDir = false;
};
const std::vector<DownloadJob>& downloadJobs() const { return dlJobs_; }
bool hasDownloads() const { return !dlJobs_.empty(); }
bool hasQueuedDownloads() const { return !dlQueue_.empty(); }
void cancelQueued(const std::string& uri);
bool downloadPaused() const { return dlPaused_.load(); }
void togglePause(); // SIGSTOP/SIGCONT the curl child
void stopDownload(); // SIGKILL the child and drop the partial file
@@ -139,6 +166,7 @@ private:
void scanSmbInto(const std::string& uri, ScanResult& out);
void startDownloadFile(const std::string& uri, const std::string& local);
void startDownloadFolder(const std::string& uri, const std::string& name);
void startNextQueued();
bool open_ = false;
bool inSmb_ = false;
@@ -169,6 +197,7 @@ private:
std::string dlName_;
std::string downloadDir_; // "" => default ~/media
std::vector<DownloadJob> dlJobs_;
std::deque<DownloadQueueItem> dlQueue_;
int dlActiveJob_ = -1; // index of the job in flight, or -1
std::atomic<bool> dlPaused_{false};
std::atomic<bool> dlAbort_{false};
+205 -34
View File
@@ -1,4 +1,5 @@
#include "ui/settings_menu.hpp"
#include "app/vault_manager.hpp"
#include "util/logging.hpp"
@@ -29,6 +30,30 @@ const char* kLangCodes[] = {"", "eng", "deu", "fra", "spa",
"jpn", "ita", "rus", "chi", "kor"};
constexpr int kLangCount = 10;
const char* kCurvatureNames[] = {"Flat (0%)", "Gentle (25%)", "Cinema (50%)",
"Deep Curve (75%)", "IMAX Wrap (100%)"};
const float kCurvatureValues[] = {0.0f, 0.25f, 0.50f, 0.75f, 1.00f};
constexpr int kCurvatureCount = 5;
const char* kUiTextScaleNames[] = {"Compact (90%)", "Standard (105%)",
"Large (120%)", "Extra Large (140%)",
"Huge (160%)"};
const float kUiTextScaleValues[] = {0.90f, 1.05f, 1.20f, 1.40f, 1.60f};
constexpr int kUiTextScaleCount = 5;
const char* kUiTextColorNames[] = {"Pure White", "Ice Cyan", "Warm Cream",
"Soft Gold", "Mint Green"};
constexpr int kUiTextColorCount = 5;
const char* kUiAccentColorNames[] = {"Cyber Cyan", "Emerald Green", "Amber Gold",
"Royal Purple", "Crimson Red"};
constexpr int kUiAccentColorCount = 5;
const char* kUiDistanceNames[] = {"Near (1.5 m)", "Comfort (1.9 m)",
"Medium (2.3 m)", "Far (2.8 m)"};
const float kUiDistanceValues[] = {1.5f, 1.9f, 2.3f, 2.8f};
constexpr int kUiDistanceCount = 4;
std::string getConfigPath() {
#ifdef _WIN32
const char* appData = std::getenv("APPDATA");
@@ -53,6 +78,7 @@ SettingsMenu::SettingsMenu() {
void SettingsMenu::open() {
open_ = true;
if (section_ < 0 || section_ > 3) section_ = 0;
refresh();
}
@@ -81,7 +107,7 @@ void SettingsMenu::refresh() {
}
if (section_ == 0) {
title_ = "Display & Projection";
title_ = "Settings > Display & Cinema";
const char* projNames[] = {"Flat Screen", "360 Equirectangular",
"180 Equirectangular"};
const char* stereoNames[] = {"2D Mono", "Side-by-Side (SBS)",
@@ -94,28 +120,35 @@ void SettingsMenu::refresh() {
Action::CycleProjection});
rows_.push_back({"Stereo 3D Format", stereoNames[stereoMode_ % 3],
Action::CycleStereo});
rows_.push_back({"Swap Left/Right Eye", swapEyes_ ? "On" : "Off",
Action::ToggleSwapEyes});
rows_.push_back({"Cinema Screen Curve", kCurvatureNames[curvatureIdx_ % kCurvatureCount],
Action::CycleCurvature});
rows_.push_back({"Screen Distance", distStream.str(),
Action::CycleDistance});
rows_.push_back({"Swap Left/Right Eye", swapEyes_ ? "On" : "Off",
Action::ToggleSwapEyes});
rows_.push_back({"Recenter Screen View", "Recenter Now",
Action::RecenterScreen});
} else if (section_ == 1) {
title_ = "Controls & Bindings";
auto btnLabel = [&](int func, int btn) -> std::string {
return listeningFunc_ == func
? std::string("[ press a button ]")
: std::string(kButtonNames[btn % kButtonCount]);
};
rows_.push_back({"Play / Pause", btnLabel(0, bindPlayBtn_),
Action::ListenPlay});
rows_.push_back({"Open Menu / Browser", btnLabel(1, bindMenuBtn_),
Action::ListenMenu});
rows_.push_back({"Recenter View", btnLabel(2, bindRecenterBtn_),
Action::ListenRecenter});
rows_.push_back({"Select / Click", "Trigger", Action::None});
rows_.push_back({"Controller Models", drawModels_ ? "On" : "Off",
Action::ToggleModels});
title_ = "Settings > UI & Appearance";
rows_.push_back({"UI Text Size",
kUiTextScaleNames[uiTextScaleIdx_ % kUiTextScaleCount],
Action::CycleUiTextScale});
rows_.push_back({"UI Text Color",
kUiTextColorNames[uiTextColorIdx_ % kUiTextColorCount],
Action::CycleUiTextColor});
rows_.push_back({"UI Accent Theme",
kUiAccentColorNames[uiAccentColorIdx_ % kUiAccentColorCount],
Action::CycleUiAccentColor});
rows_.push_back({"UI Panel Distance",
kUiDistanceNames[uiDistanceIdx_ % kUiDistanceCount],
Action::CycleUiDistance});
rows_.push_back({"Download Folder",
kDownloadDirs[downloadDirIdx_ % kDownloadDirCount],
Action::CycleDownloadDir});
rows_.push_back({"Debug Statistics", showStats_ ? "On" : "Off",
Action::ToggleStats});
} else if (section_ == 2) {
title_ = "Audio / Video Tracks";
title_ = "Settings > Audio & Video Tracks";
Row v{"Video Track",
videoStreams_.empty()
? "(none)"
@@ -138,40 +171,85 @@ void SettingsMenu::refresh() {
kLangNames[audioLangIdx_ % kLangCount],
Action::EnterLangList});
} else if (section_ == 3) {
title_ = "System & Debug";
rows_.push_back({"Debug Statistics", showStats_ ? "On" : "Off",
Action::ToggleStats});
rows_.push_back({"Download Folder",
kDownloadDirs[downloadDirIdx_ % kDownloadDirCount],
Action::CycleDownloadDir});
title_ = "Settings > Controls & Bindings";
auto btnLabel = [&](int func, int btn) -> std::string {
return listeningFunc_ == func
? std::string("[ press a button ]")
: std::string(kButtonNames[btn % kButtonCount]);
};
rows_.push_back({"Play / Pause", btnLabel(0, bindPlayBtn_),
Action::ListenPlay});
rows_.push_back({"Open Menu / Browser", btnLabel(1, bindMenuBtn_),
Action::ListenMenu});
rows_.push_back({"Recenter View", btnLabel(2, bindRecenterBtn_),
Action::ListenRecenter});
rows_.push_back({"Select / Click", "Trigger", Action::None});
rows_.push_back({"Controller Models", drawModels_ ? "On" : "Off",
Action::ToggleModels});
} else if (section_ == 4) {
title_ = "Settings > Vault & Privacy";
rows_.push_back({"Auto-Lock on Headset Removal",
VaultManager::instance().autoLockHeadsetOff() ? "Enabled" : "Disabled",
Action::CycleVaultAutoLockHeadset});
int toSec = VaultManager::instance().autoLockTimeoutSec();
std::string toStr = "Disabled";
if (toSec == 120) toStr = "2 Minutes";
else if (toSec == 300) toStr = "5 Minutes";
else if (toSec == 600) toStr = "10 Minutes";
rows_.push_back({"Inactivity Auto-Lock Timeout", toStr,
Action::CycleVaultTimeout});
auto moveBtnLabel = [&]() -> std::string {
if (listeningFunc_ == 3) return "[ press a button ]";
int mb = VaultManager::instance().moveButton();
if (mb < 0 || mb >= kButtonCount) return "Disabled";
return kButtonNames[mb % kButtonCount];
};
rows_.push_back({"File Actions Button", moveBtnLabel(),
Action::ListenVaultMoveBtn});
std::string comboLabel;
if (VaultManager::instance().isRecordingCombo()) {
comboLabel = "[ Recording: " + std::to_string(VaultManager::instance().recordedCount()) + "/6 ]";
} else {
comboLabel = VaultManager::instance().comboString();
}
rows_.push_back({"Unlock Combo Sequence", comboLabel,
Action::RecordVaultCombo});
rows_.push_back({"Lock Vault Now", "[ Lock & Return Home ]",
Action::LockVaultAction});
} else if (section_ == 10) {
title_ = "Select Video Track";
title_ = "Settings > Select Video Track";
for (std::size_t i = 0; i < videoStreams_.size(); ++i) {
Row r{videoStreams_[i].second,
static_cast<int>(i) == videoSel_ ? "<" : "",
static_cast<int>(i) == videoSel_ ? "ACTIVE" : "Select",
Action::PickVideoStream};
r.data = static_cast<int>(i);
rows_.push_back(r);
}
rows_.push_back({"< Back to Tracks", "", Action::Back});
} else if (section_ == 11) {
title_ = "Select Audio Track";
title_ = "Settings > Select Audio Track";
for (std::size_t i = 0; i < audioStreams_.size(); ++i) {
Row r{audioStreams_[i].second,
static_cast<int>(i) == audioSel_ ? "<" : "",
static_cast<int>(i) == audioSel_ ? "ACTIVE" : "Select",
Action::PickAudioStream};
r.data = static_cast<int>(i);
rows_.push_back(r);
}
rows_.push_back({"< Back to Tracks", "", Action::Back});
} else { // section_ == 12: preferred-language list
title_ = "Preferred Audio Language";
title_ = "Settings > Preferred Audio Language";
for (int i = 0; i < kLangCount; ++i) {
Row r{kLangNames[i], i == audioLangIdx_ ? "<" : "",
Row r{kLangNames[i], i == audioLangIdx_ ? "ACTIVE" : "Select",
Action::PickLanguage};
r.data = i;
rows_.push_back(r);
}
rows_.push_back({"< Back to Tracks", "", Action::Back});
}
rows_.push_back({"< Back", "", Action::Back});
}
SettingsMenu::Action SettingsMenu::activate() {
@@ -188,7 +266,7 @@ SettingsMenu::Action SettingsMenu::activate() {
case Action::EnterAudioList: section_ = 11; selected_ = 0; refresh(); break;
case Action::EnterLangList: section_ = 12; selected_ = 0; refresh(); break;
case Action::Back:
section_ = (section_ >= 10) ? 2 : -1; // list -> Tracks; else -> root
section_ = (section_ >= 10) ? 2 : 0; // list -> Tracks; else -> Display
selected_ = 0;
refresh();
break;
@@ -243,6 +321,31 @@ SettingsMenu::Action SettingsMenu::activate() {
saveConfig();
refresh();
break;
case Action::CycleCurvature:
curvatureIdx_ = (curvatureIdx_ + 1) % kCurvatureCount;
saveConfig();
refresh();
break;
case Action::CycleUiTextScale:
uiTextScaleIdx_ = (uiTextScaleIdx_ + 1) % kUiTextScaleCount;
saveConfig();
refresh();
break;
case Action::CycleUiTextColor:
uiTextColorIdx_ = (uiTextColorIdx_ + 1) % kUiTextColorCount;
saveConfig();
refresh();
break;
case Action::CycleUiAccentColor:
uiAccentColorIdx_ = (uiAccentColorIdx_ + 1) % kUiAccentColorCount;
saveConfig();
refresh();
break;
case Action::CycleUiDistance:
uiDistanceIdx_ = (uiDistanceIdx_ + 1) % kUiDistanceCount;
saveConfig();
refresh();
break;
case Action::PickVideoStream:
videoSel_ = rows_[selected_].data;
section_ = 2;
@@ -262,6 +365,40 @@ SettingsMenu::Action SettingsMenu::activate() {
selected_ = 0;
refresh();
break;
case Action::CycleVaultAutoLockHeadset:
VaultManager::instance().setAutoLockHeadsetOff(!VaultManager::instance().autoLockHeadsetOff());
refresh();
break;
case Action::CycleVaultTimeout: {
int to = VaultManager::instance().autoLockTimeoutSec();
if (to == 0) to = 120;
else if (to == 120) to = 300;
else if (to == 300) to = 600;
else to = 0;
VaultManager::instance().setAutoLockTimeoutSec(to);
refresh();
break;
}
case Action::ListenVaultMoveBtn:
listeningFunc_ = 3;
status_ = "Press a controller button for Move-to-Vault";
refresh();
break;
case Action::RecordVaultCombo:
if (VaultManager::instance().isRecordingCombo()) {
VaultManager::instance().cancelRecordingCombo();
status_ = "Combo recording cancelled";
} else {
VaultManager::instance().startRecordingCombo();
status_ = "Press 6 face buttons (A, B, X, Y) to record new combo";
}
refresh();
break;
case Action::LockVaultAction:
VaultManager::instance().lock();
section_ = 0;
refresh();
break;
case Action::RecenterScreen:
break;
case Action::Close:
@@ -310,6 +447,7 @@ void SettingsMenu::assignListening(int button) {
if (listeningFunc_ == 0) bindPlayBtn_ = b;
else if (listeningFunc_ == 1) bindMenuBtn_ = b;
else if (listeningFunc_ == 2) bindRecenterBtn_ = b;
else if (listeningFunc_ == 3) VaultManager::instance().setMoveButton(b);
listeningFunc_ = -1;
status_ = "Bound to " + std::string(kButtonNames[b]);
saveConfig();
@@ -323,6 +461,24 @@ std::string SettingsMenu::downloadDir() const {
return d[0] == '~' ? base + (d + 1) : std::string(d);
}
float SettingsMenu::screenCurvature() const {
return kCurvatureValues[curvatureIdx_ % kCurvatureCount];
}
void SettingsMenu::setCurvatureIdx(int idx) {
curvatureIdx_ = ((idx % kCurvatureCount) + kCurvatureCount) % kCurvatureCount;
saveConfig();
refresh();
}
float SettingsMenu::uiTextScale() const {
return kUiTextScaleValues[uiTextScaleIdx_ % kUiTextScaleCount];
}
float SettingsMenu::uiDistance() const {
return kUiDistanceValues[uiDistanceIdx_ % kUiDistanceCount];
}
void SettingsMenu::loadConfig() {
const std::string path = getConfigPath();
std::ifstream file(path);
@@ -343,9 +499,19 @@ void SettingsMenu::loadConfig() {
else if (key == "distance") screenDistance_ = std::clamp(std::stof(val), 1.0f, 10.0f);
else if (key == "bind_play_btn") bindPlayBtn_ = std::clamp(std::stoi(val), 0, kButtonCount - 1);
else if (key == "bind_menu_btn") bindMenuBtn_ = std::clamp(std::stoi(val), 0, kButtonCount - 1);
else if (key == "bind_recenter_btn") bindRecenterBtn_ = std::clamp(std::stoi(val), 0, kButtonCount - 1);
else if (key == "bind_recenter_btn") {
const int b = std::clamp(std::stoi(val), 0, kButtonCount - 1);
// Grip used to default to recenter; it now toggles the laser pointer,
// so a saved grip binding is migrated to the new default (Bumper).
bindRecenterBtn_ = (b == 8) ? 6 : b;
}
else if (key == "download_dir") downloadDirIdx_ = std::clamp(std::stoi(val), 0, kDownloadDirCount - 1);
else if (key == "audio_lang") audioLangIdx_ = std::clamp(std::stoi(val), 0, kLangCount - 1);
else if (key == "curvature") curvatureIdx_ = std::clamp(std::stoi(val), 0, kCurvatureCount - 1);
else if (key == "ui_text_scale") uiTextScaleIdx_ = std::clamp(std::stoi(val), 0, kUiTextScaleCount - 1);
else if (key == "ui_text_color") uiTextColorIdx_ = std::clamp(std::stoi(val), 0, kUiTextColorCount - 1);
else if (key == "ui_accent_color") uiAccentColorIdx_ = std::clamp(std::stoi(val), 0, kUiAccentColorCount - 1);
else if (key == "ui_distance") uiDistanceIdx_ = std::clamp(std::stoi(val), 0, kUiDistanceCount - 1);
}
PIXELVR_LOG_INFO("Loaded settings from %s", path.c_str());
}
@@ -370,6 +536,11 @@ void SettingsMenu::saveConfig() const {
file << "bind_recenter_btn=" << bindRecenterBtn_ << "\n";
file << "download_dir=" << downloadDirIdx_ << "\n";
file << "audio_lang=" << audioLangIdx_ << "\n";
file << "curvature=" << curvatureIdx_ << "\n";
file << "ui_text_scale=" << uiTextScaleIdx_ << "\n";
file << "ui_text_color=" << uiTextColorIdx_ << "\n";
file << "ui_accent_color=" << uiAccentColorIdx_ << "\n";
file << "ui_distance=" << uiDistanceIdx_ << "\n";
}
} catch (const std::exception& e) {
PIXELVR_LOG_WARN("Could not save settings: %s", e.what());
+32 -4
View File
@@ -25,6 +25,11 @@ public:
ToggleModels,
ToggleStats,
CycleDistance,
CycleCurvature,
CycleUiTextScale,
CycleUiTextColor,
CycleUiAccentColor,
CycleUiDistance,
EnterVideoList,
EnterAudioList,
EnterLangList,
@@ -32,6 +37,11 @@ public:
PickAudioStream,
PickLanguage,
RecenterScreen,
CycleVaultAutoLockHeadset,
CycleVaultTimeout,
ListenVaultMoveBtn,
RecordVaultCombo,
LockVaultAction,
Close
};
@@ -49,6 +59,7 @@ public:
void close() { open_ = false; }
bool isOpen() const { return open_; }
void setOpen(bool o) { open_ = o; if (o) refresh(); }
void refresh();
const std::string& title() const { return title_; }
const std::string& status() const { return status_; }
@@ -77,6 +88,20 @@ public:
std::string downloadDir() const;
float screenDistance() const { return screenDistance_; }
void setScreenDistance(float d) { screenDistance_ = d; refresh(); }
float screenCurvature() const;
void setCurvatureIdx(int idx);
int curvatureIdx() const { return curvatureIdx_; }
float uiTextScale() const;
int uiTextColorIdx() const { return uiTextColorIdx_; }
int uiAccentColorIdx() const { return uiAccentColorIdx_; }
float uiDistance() const;
int section() const { return section_; }
void setSection(int s) {
section_ = s;
selected_ = 0;
refresh();
}
// Track lists (container index + label) for the current media, pushed by the
// app on load. selected*Stream() return the chosen container index (-1 none).
@@ -91,8 +116,6 @@ public:
void saveConfig() const;
private:
void refresh();
bool open_ = false;
std::string title_ = "Settings & Controller Remap";
std::string status_ = "Point + Trigger: Change Setting | Grip: Recenter | B/Y: Close";
@@ -109,11 +132,16 @@ private:
// Function -> physical button (XrInputState::Button index); press-to-bind.
int bindPlayBtn_ = 0; // default A
int bindMenuBtn_ = 1; // default B
int bindRecenterBtn_ = 8; // default Grip
int bindRecenterBtn_ = 6; // default Bumper (grip toggles the laser)
int listeningFunc_ = -1; // 0=play 1=menu 2=recenter while binding, else -1
int downloadDirIdx_ = 0; // index into the download-destination presets
int curvatureIdx_ = 0; // 0=Flat (0%), 1=Gentle (25%), 2=Cinema (50%), 3=Deep (75%), 4=IMAX (100%)
int uiTextScaleIdx_ = 2; // 0=90%, 1=105%, 2=120% (default), 3=140%, 4=160%
int uiTextColorIdx_ = 0; // 0=Pure White, 1=Ice Cyan, 2=Warm Cream, 3=Soft Gold, 4=Mint Green
int uiAccentColorIdx_ = 0; // 0=Cyber Cyan, 1=Emerald, 2=Amber Gold, 3=Royal Purple, 4=Crimson
int uiDistanceIdx_ = 1; // 0=Near (1.5m), 1=Comfort (1.9m), 2=Mid (2.3m), 3=Far (2.8m)
int section_ = -1; // -1 = top-level section list; 0..3 = a section's rows
int section_ = 0; // 0=Display, 1=Controls, 2=Streams, 3=System; 10..12=sub-lists
std::vector<std::pair<int, std::string>> videoStreams_; // (index, label)
std::vector<std::pair<int, std::string>> audioStreams_;
int videoSel_ = 0; // position within videoStreams_
+352
View File
@@ -0,0 +1,352 @@
#include "ui/thumbnail_cache.hpp"
#include "app/vault_manager.hpp"
#include "util/logging.hpp"
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <fstream>
#ifdef PIXELVR_HAVE_MEDIA
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/imgutils.h>
#include <libswscale/swscale.h>
}
#endif
namespace fs = std::filesystem;
namespace pixelvr {
constexpr int kThumbW = 256;
constexpr int kThumbH = 144;
constexpr std::size_t kThumbBytes = kThumbW * kThumbH * 4;
struct DiskMetaHeader {
uint32_t magic = 0x5056524D; // 'PVRM'
int32_t width = 0;
int32_t height = 0;
double fps = 0.0;
double durationSec = 0.0;
};
static uint64_t fnv1a64(const std::string& str) {
uint64_t hash = 14695981039346656037ULL;
for (char c : str) {
hash ^= static_cast<uint8_t>(c);
hash *= 1099511628211ULL;
}
return hash;
}
ThumbnailCache::ThumbnailCache() {
const char* home = std::getenv("HOME");
std::string base = (home != nullptr) ? home : "/home/steamos";
cacheDir_ = base + "/.cache/pixelvr/thumbs";
std::error_code ec;
fs::create_directories(cacheDir_, ec);
worker_ = std::thread([this] { workerLoop(); });
}
ThumbnailCache::~ThumbnailCache() {
stop_.store(true);
cv_.notify_all();
if (worker_.joinable()) {
worker_.join();
}
}
void ThumbnailCache::request(const std::string& videoPath) {
if (videoPath.empty() || videoPath[0] != '/') return;
std::lock_guard<std::mutex> lk(mutex_);
if (queuedPaths_.find(videoPath) != queuedPaths_.end() ||
cache_.find(videoPath) != cache_.end()) {
return;
}
queuedPaths_[videoPath] = true;
queue_.push(videoPath);
cv_.notify_one();
}
bool ThumbnailCache::get(const std::string& videoPath, std::vector<uint8_t>& outRgba) {
if (videoPath.empty()) return false;
std::lock_guard<std::mutex> lk(mutex_);
auto it = cache_.find(videoPath);
if (it != cache_.end() && it->second.size() == kThumbBytes) {
outRgba = it->second;
return true;
}
return false;
}
bool ThumbnailCache::getMeta(const std::string& videoPath, MediaMeta& outMeta) {
if (videoPath.empty()) return false;
std::lock_guard<std::mutex> lk(mutex_);
auto it = metaCache_.find(videoPath);
if (it != metaCache_.end() && it->second.ready) {
outMeta = it->second;
return true;
}
return false;
}
void ThumbnailCache::clearVaultThumbs(const std::string& vaultDir) {
if (vaultDir.empty()) return;
std::lock_guard<std::mutex> lk(mutex_);
for (auto it = cache_.begin(); it != cache_.end(); ) {
if (it->first.rfind(vaultDir, 0) == 0) {
it = cache_.erase(it);
} else {
++it;
}
}
for (auto it = metaCache_.begin(); it != metaCache_.end(); ) {
if (it->first.rfind(vaultDir, 0) == 0) {
it = metaCache_.erase(it);
} else {
++it;
}
}
for (auto it = queuedPaths_.begin(); it != queuedPaths_.end(); ) {
if (it->first.rfind(vaultDir, 0) == 0) {
it = queuedPaths_.erase(it);
} else {
++it;
}
}
}
bool ThumbnailCache::extractThumbnailAndMeta(const std::string& videoPath,
std::vector<uint8_t>& outRgba,
MediaMeta& outMeta) {
#ifdef PIXELVR_HAVE_MEDIA
AVFormatContext* fmt = nullptr;
if (avformat_open_input(&fmt, videoPath.c_str(), nullptr, nullptr) < 0 || !fmt) {
return false;
}
if (avformat_find_stream_info(fmt, nullptr) < 0) {
avformat_close_input(&fmt);
return false;
}
int vIdx = av_find_best_stream(fmt, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0);
if (vIdx < 0) {
avformat_close_input(&fmt);
return false;
}
AVStream* st = fmt->streams[vIdx];
outMeta.width = st->codecpar->width;
outMeta.height = st->codecpar->height;
if (st->avg_frame_rate.den > 0 && st->avg_frame_rate.num > 0) {
outMeta.fps = av_q2d(st->avg_frame_rate);
} else if (st->r_frame_rate.den > 0 && st->r_frame_rate.num > 0) {
outMeta.fps = av_q2d(st->r_frame_rate);
}
if (fmt->duration > 0) {
outMeta.durationSec = static_cast<double>(fmt->duration) / AV_TIME_BASE;
} else if (st->duration > 0 && st->time_base.den > 0) {
outMeta.durationSec = static_cast<double>(st->duration) * av_q2d(st->time_base);
}
outMeta.ready = true;
// Find standard software decoder for thumbnail extraction so we never touch V4L2/DRM hardware slots
const AVCodec* dec = avcodec_find_decoder(st->codecpar->codec_id);
if (dec && dec->name && std::strstr(dec->name, "v4l2") != nullptr) {
if (st->codecpar->codec_id == AV_CODEC_ID_HEVC) {
if (const AVCodec* sw = avcodec_find_decoder_by_name("hevc")) dec = sw;
} else if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
if (const AVCodec* sw = avcodec_find_decoder_by_name("h264")) dec = sw;
}
}
if (!dec) {
avformat_close_input(&fmt);
return false;
}
AVCodecContext* ctx = avcodec_alloc_context3(dec);
if (!ctx) {
avformat_close_input(&fmt);
return false;
}
avcodec_parameters_to_context(ctx, st->codecpar);
ctx->thread_count = 2;
ctx->skip_loop_filter = AVDISCARD_ALL;
if (avcodec_open2(ctx, dec, nullptr) < 0) {
avcodec_free_context(&ctx);
avformat_close_input(&fmt);
return false;
}
// Seek ~10% into the clip (clamped between 3s and 30s) to avoid black intros
if (outMeta.durationSec > 6.0) {
double targetSec = std::clamp(outMeta.durationSec * 0.10, 3.0, 30.0);
int64_t ts = static_cast<int64_t>(targetSec * AV_TIME_BASE);
av_seek_frame(fmt, -1, ts, AVSEEK_FLAG_BACKWARD);
avcodec_flush_buffers(ctx);
}
AVPacket* pkt = av_packet_alloc();
AVFrame* frame = av_frame_alloc();
bool gotFrame = false;
auto decodeAttempt = [&]() {
int packetsRead = 0;
while (packetsRead < 300 && av_read_frame(fmt, pkt) >= 0) {
if (pkt->stream_index == vIdx) {
++packetsRead;
if (avcodec_send_packet(ctx, pkt) == 0) {
if (avcodec_receive_frame(ctx, frame) == 0) {
gotFrame = true;
av_packet_unref(pkt);
break;
}
}
}
av_packet_unref(pkt);
}
};
decodeAttempt();
if (!gotFrame && outMeta.durationSec > 6.0) {
// Fallback to start of file if seek landed near EOF
av_seek_frame(fmt, -1, 0, AVSEEK_FLAG_BACKWARD);
avcodec_flush_buffers(ctx);
decodeAttempt();
}
bool ok = false;
if (gotFrame && frame->width > 0 && frame->height > 0) {
// For Side-by-Side (SBS) 3D or VR180 videos (aspect >= 1.95 or width == 2*height),
// crop the left eye (left half of frame) so the thumbnail shows a normal single view
// instead of a squished double-eye image!
int srcW = frame->width;
int srcH = frame->height;
const float ar = static_cast<float>(srcW) / static_cast<float>(srcH);
std::string lowerPath = videoPath;
for (char& c : lowerPath) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
const bool isSbs = (lowerPath.find("sbs") != std::string::npos ||
lowerPath.find("vr180") != std::string::npos ||
lowerPath.find("180") != std::string::npos ||
ar >= 2.6f);
if (isSbs && srcW >= 2 * kThumbW) {
srcW = frame->width / 2;
}
SwsContext* sws = sws_getContext(
srcW, srcH, static_cast<AVPixelFormat>(frame->format),
kThumbW, kThumbH, AV_PIX_FMT_RGBA,
SWS_BILINEAR, nullptr, nullptr, nullptr);
if (sws) {
outRgba.resize(kThumbBytes);
uint8_t* dstData[4] = {outRgba.data(), nullptr, nullptr, nullptr};
int dstLinesize[4] = {kThumbW * 4, 0, 0, 0};
sws_scale(sws, frame->data, frame->linesize, 0, srcH, dstData, dstLinesize);
sws_freeContext(sws);
ok = true;
}
}
av_frame_free(&frame);
av_packet_free(&pkt);
avcodec_free_context(&ctx);
avformat_close_input(&fmt);
return ok;
#else
(void)videoPath;
(void)outRgba;
(void)outMeta;
return false;
#endif
}
void ThumbnailCache::workerLoop() {
while (!stop_.load()) {
std::string path;
{
std::unique_lock<std::mutex> lk(mutex_);
cv_.wait(lk, [this] { return stop_.load() || !queue_.empty(); });
if (stop_.load()) break;
path = queue_.front();
queue_.pop();
}
if (path.empty() || path[0] != '/') {
continue;
}
const bool inVault = VaultManager::instance().isVaultPath(path);
const std::string targetCacheDir = inVault ? VaultManager::instance().thumbsDir() : cacheDir_;
const std::string baseHash = std::to_string(fnv1a64(path));
const std::string cacheFile = targetCacheDir + "/" + baseHash + ".rgba";
const std::string metaFile = targetCacheDir + "/" + baseHash + ".meta";
std::error_code ec;
if (fs::is_regular_file(cacheFile, ec) && fs::file_size(cacheFile, ec) == kThumbBytes) {
std::ifstream in(cacheFile, std::ios::binary);
std::vector<uint8_t> data(kThumbBytes);
if (in.read(reinterpret_cast<char*>(data.data()), kThumbBytes)) {
MediaMeta meta{};
if (fs::is_regular_file(metaFile, ec) &&
fs::file_size(metaFile, ec) == sizeof(DiskMetaHeader)) {
std::ifstream min(metaFile, std::ios::binary);
DiskMetaHeader hdr{};
if (min.read(reinterpret_cast<char*>(&hdr), sizeof(hdr)) &&
hdr.magic == 0x5056524D) {
meta.width = hdr.width;
meta.height = hdr.height;
meta.fps = hdr.fps;
meta.durationSec = hdr.durationSec;
meta.ready = true;
}
}
if (!meta.ready) {
// Quick metadata probe if .meta was not cached yet
std::vector<uint8_t> dummy;
extractThumbnailAndMeta(path, dummy, meta);
if (meta.ready) {
DiskMetaHeader hdr{0x5056524D, meta.width, meta.height, meta.fps, meta.durationSec};
std::ofstream mout(metaFile, std::ios::binary);
mout.write(reinterpret_cast<const char*>(&hdr), sizeof(hdr));
}
}
std::lock_guard<std::mutex> lk(mutex_);
cache_[path] = std::move(data);
if (meta.ready) metaCache_[path] = meta;
continue;
}
}
std::vector<uint8_t> rgba;
MediaMeta meta{};
const bool ok = extractThumbnailAndMeta(path, rgba, meta);
if (meta.ready) {
DiskMetaHeader hdr{0x5056524D, meta.width, meta.height, meta.fps, meta.durationSec};
std::ofstream mout(metaFile, std::ios::binary);
mout.write(reinterpret_cast<const char*>(&hdr), sizeof(hdr));
std::lock_guard<std::mutex> lk(mutex_);
metaCache_[path] = meta;
}
if (ok && rgba.size() == kThumbBytes) {
{
std::ofstream out(cacheFile, std::ios::binary);
out.write(reinterpret_cast<const char*>(rgba.data()), kThumbBytes);
}
std::lock_guard<std::mutex> lk(mutex_);
cache_[path] = std::move(rgba);
PIXELVR_LOG_INFO("Thumbnail generated for %s (%dx%d, %.0fs)",
path.c_str(), meta.width, meta.height, meta.durationSec);
} else {
PIXELVR_LOG_WARN("Thumbnail generation failed for %s", path.c_str());
}
}
}
} // namespace pixelvr
+57
View File
@@ -0,0 +1,57 @@
#pragma once
#include <atomic>
#include <condition_variable>
#include <cstdint>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>
namespace pixelvr {
class ThumbnailCache {
public:
struct MediaMeta {
int width = 0;
int height = 0;
double fps = 0.0;
double durationSec = 0.0;
bool ready = false;
};
ThumbnailCache();
~ThumbnailCache();
// Requests thumbnail extraction/load and metadata probe for a path (non-blocking).
void request(const std::string& videoPath);
// Returns true and copies out the 256x144 RGBA pixels if ready.
bool get(const std::string& videoPath, std::vector<uint8_t>& outRgba);
// Returns true and populates MediaMeta if probed.
bool getMeta(const std::string& videoPath, MediaMeta& outMeta);
// Clears cached thumbnails and metadata whose paths start with vaultDir.
void clearVaultThumbs(const std::string& vaultDir);
private:
void workerLoop();
bool extractThumbnailAndMeta(const std::string& videoPath,
std::vector<uint8_t>& outRgba,
MediaMeta& outMeta);
std::string cacheDir_;
std::mutex mutex_;
std::condition_variable cv_;
std::queue<std::string> queue_;
std::unordered_map<std::string, bool> queuedPaths_;
std::unordered_map<std::string, std::vector<uint8_t>> cache_;
std::unordered_map<std::string, MediaMeta> metaCache_;
std::atomic<bool> stop_{false};
std::thread worker_;
};
} // namespace pixelvr
+172 -113
View File
@@ -29,6 +29,10 @@ bool RenderModelSystem::init(XrInstance instance, XrSession session, bool enable
load("xrGetRenderModelStateEXT", pfnGetState_) &&
load("xrDestroyRenderModelEXT", pfnDestroyModel_) &&
load("xrDestroyRenderModelAssetEXT", pfnDestroyAsset_);
// Optional helper to map models to hands directly:
load("xrEnumerateRenderModelSubactionPathsEXT", pfnEnumerateSubactionPaths_);
if (!available_) {
PIXELVR_LOG_WARN("XR_EXT_render_model entry points unavailable");
}
@@ -37,13 +41,13 @@ bool RenderModelSystem::init(XrInstance instance, XrSession session, bool enable
bool RenderModelSystem::poll() {
if (!available_ || done_) {
return assetReady();
return assetReady(0) || assetReady(1);
}
fetchFirstModel();
return assetReady();
fetchModels();
return assetReady(0) || assetReady(1);
}
bool RenderModelSystem::fetchFirstModel() {
bool RenderModelSystem::fetchModels() {
XrInteractionRenderModelIdsEnumerateInfoEXT enumInfo{
XR_TYPE_INTERACTION_RENDER_MODEL_IDS_ENUMERATE_INFO_EXT};
uint32_t idCount = 0;
@@ -57,104 +61,153 @@ bool RenderModelSystem::fetchFirstModel() {
return false;
}
XrRenderModelIdEXT id = XR_NULL_RENDER_MODEL_ID_EXT;
for (auto v : ids) {
if (v != XR_NULL_RENDER_MODEL_ID_EXT) {
id = v;
break;
PIXELVR_LOG_INFO("OpenXR enumerated %u render model IDs", idCount);
for (uint32_t i = 0; i < idCount; ++i) {
XrRenderModelIdEXT id = ids[i];
if (id == XR_NULL_RENDER_MODEL_ID_EXT) continue;
if ((models_[0].ready && models_[0].id == id) ||
(models_[1].ready && models_[1].id == id)) {
continue;
}
}
if (id == XR_NULL_RENDER_MODEL_ID_EXT) {
return false;
}
done_ = true; // from here on, success or hard failure — do not retry
XrRenderModelCreateInfoEXT mci{XR_TYPE_RENDER_MODEL_CREATE_INFO_EXT};
mci.renderModelId = id;
if (XR_FAILED(pfnCreateModel_(session_, &mci, &model_))) {
PIXELVR_LOG_WARN("xrCreateRenderModelEXT failed");
return false;
}
XrRenderModelCreateInfoEXT mci{XR_TYPE_RENDER_MODEL_CREATE_INFO_EXT};
mci.renderModelId = id;
XrRenderModelEXT model = XR_NULL_HANDLE;
if (XR_FAILED(pfnCreateModel_(session_, &mci, &model))) {
PIXELVR_LOG_WARN("xrCreateRenderModelEXT failed for id %llu",
static_cast<unsigned long long>(id));
continue;
}
XrRenderModelPropertiesGetInfoEXT pgi{
XR_TYPE_RENDER_MODEL_PROPERTIES_GET_INFO_EXT};
XrRenderModelPropertiesEXT props{XR_TYPE_RENDER_MODEL_PROPERTIES_EXT};
if (XR_FAILED(pfnGetProps_(model_, &pgi, &props))) {
PIXELVR_LOG_WARN("xrGetRenderModelPropertiesEXT failed");
return false;
}
animatableNodeCount_ = props.animatableNodeCount;
XrRenderModelAssetCreateInfoEXT aci{XR_TYPE_RENDER_MODEL_ASSET_CREATE_INFO_EXT};
aci.cacheId = props.cacheId;
if (XR_FAILED(pfnCreateAsset_(session_, &aci, &asset_))) {
PIXELVR_LOG_WARN("xrCreateRenderModelAssetEXT failed");
return false;
}
XrRenderModelAssetDataGetInfoEXT adi{
XR_TYPE_RENDER_MODEL_ASSET_DATA_GET_INFO_EXT};
XrRenderModelAssetDataEXT data{XR_TYPE_RENDER_MODEL_ASSET_DATA_EXT};
if (XR_FAILED(pfnGetAssetData_(asset_, &adi, &data))) { // size query
PIXELVR_LOG_WARN("xrGetRenderModelAssetDataEXT (size) failed");
return false;
}
gltf_.resize(data.bufferCountOutput);
data.bufferCapacityInput = static_cast<uint32_t>(gltf_.size());
data.buffer = gltf_.data();
if (XR_FAILED(pfnGetAssetData_(asset_, &adi, &data))) {
PIXELVR_LOG_WARN("xrGetRenderModelAssetDataEXT (data) failed");
gltf_.clear();
return false;
}
XrRenderModelSpaceCreateInfoEXT sci{XR_TYPE_RENDER_MODEL_SPACE_CREATE_INFO_EXT};
sci.renderModel = model_;
pfnCreateSpace_(session_, &sci, &modelSpace_); // used by later stages
// Animatable node names, in the same order as xrGetRenderModelStateEXT node
// states, so an animated node can be mapped back to glTF geometry.
if (pfnGetAssetProps_ != nullptr) {
XrRenderModelAssetPropertiesGetInfoEXT agi{
XR_TYPE_RENDER_MODEL_ASSET_PROPERTIES_GET_INFO_EXT};
XrRenderModelAssetPropertiesEXT props{
XR_TYPE_RENDER_MODEL_ASSET_PROPERTIES_EXT};
if (XR_FAILED(pfnGetAssetProps_(asset_, &agi, &props))) {
PIXELVR_LOG_WARN("xrGetRenderModelAssetPropertiesEXT (size) failed");
} else {
std::vector<XrRenderModelAssetNodePropertiesEXT> names(
props.nodePropertyCount);
props.nodePropertyCount = static_cast<uint32_t>(names.size());
props.nodeProperties = names.data();
if (XR_SUCCEEDED(pfnGetAssetProps_(asset_, &agi, &props))) {
nodeNames_.reserve(names.size());
for (const auto& np : names) nodeNames_.emplace_back(np.uniqueName);
std::string joined;
for (const auto& n : nodeNames_) {
joined += n;
joined += ' ';
int hand = -1;
if (pfnEnumerateSubactionPaths_ != nullptr) {
XrInteractionRenderModelSubactionPathInfoEXT spi{
XR_TYPE_INTERACTION_RENDER_MODEL_SUBACTION_PATH_INFO_EXT};
uint32_t pathCount = 0;
if (XR_SUCCEEDED(pfnEnumerateSubactionPaths_(model, &spi, 0, &pathCount, nullptr)) && pathCount > 0) {
std::vector<XrPath> paths(pathCount);
if (XR_SUCCEEDED(pfnEnumerateSubactionPaths_(model, &spi, pathCount, &pathCount, paths.data()))) {
for (XrPath p : paths) {
char pathBuf[XR_MAX_PATH_LENGTH];
uint32_t len = 0;
if (XR_SUCCEEDED(xrPathToString(instance_, p, sizeof(pathBuf), &len, pathBuf))) {
std::string ps = pathBuf;
if (ps.find("left") != std::string::npos) hand = 0;
else if (ps.find("right") != std::string::npos) hand = 1;
}
}
}
PIXELVR_LOG_INFO("Render model nodes: %s", joined.c_str());
} else {
PIXELVR_LOG_WARN("xrGetRenderModelAssetPropertiesEXT (data) failed");
}
}
XrRenderModelPropertiesGetInfoEXT pgi{
XR_TYPE_RENDER_MODEL_PROPERTIES_GET_INFO_EXT};
XrRenderModelPropertiesEXT props{XR_TYPE_RENDER_MODEL_PROPERTIES_EXT};
if (XR_FAILED(pfnGetProps_(model, &pgi, &props))) {
PIXELVR_LOG_WARN("xrGetRenderModelPropertiesEXT failed");
pfnDestroyModel_(model);
continue;
}
XrRenderModelAssetCreateInfoEXT aci{XR_TYPE_RENDER_MODEL_ASSET_CREATE_INFO_EXT};
aci.cacheId = props.cacheId;
XrRenderModelAssetEXT asset = XR_NULL_HANDLE;
if (XR_FAILED(pfnCreateAsset_(session_, &aci, &asset))) {
PIXELVR_LOG_WARN("xrCreateRenderModelAssetEXT failed");
pfnDestroyModel_(model);
continue;
}
XrRenderModelAssetDataGetInfoEXT adi{
XR_TYPE_RENDER_MODEL_ASSET_DATA_GET_INFO_EXT};
XrRenderModelAssetDataEXT data{XR_TYPE_RENDER_MODEL_ASSET_DATA_EXT};
if (XR_FAILED(pfnGetAssetData_(asset, &adi, &data))) { // size query
PIXELVR_LOG_WARN("xrGetRenderModelAssetDataEXT (size) failed");
pfnDestroyAsset_(asset);
pfnDestroyModel_(model);
continue;
}
std::vector<uint8_t> gltf(data.bufferCountOutput);
data.bufferCapacityInput = static_cast<uint32_t>(gltf.size());
data.buffer = gltf.data();
if (XR_FAILED(pfnGetAssetData_(asset, &adi, &data))) {
PIXELVR_LOG_WARN("xrGetRenderModelAssetDataEXT (data) failed");
pfnDestroyAsset_(asset);
pfnDestroyModel_(model);
continue;
}
// If hand is still undetermined, inspect glTF JSON header
if (hand < 0 && gltf.size() > 50) {
std::string gltfText(reinterpret_cast<const char*>(gltf.data()),
std::min<std::size_t>(gltf.size(), 4096));
if (gltfText.find("left") != std::string::npos ||
gltfText.find("Left") != std::string::npos) {
hand = 0;
} else if (gltfText.find("right") != std::string::npos ||
gltfText.find("Right") != std::string::npos) {
hand = 1;
}
}
// Fallback: assign to the first unfilled hand slot
if (hand < 0) {
hand = !models_[0].ready ? 0 : 1;
}
XrRenderModelSpaceCreateInfoEXT sci{XR_TYPE_RENDER_MODEL_SPACE_CREATE_INFO_EXT};
sci.renderModel = model;
XrSpace modelSpace = XR_NULL_HANDLE;
pfnCreateSpace_(session_, &sci, &modelSpace);
std::vector<std::string> nodeNames;
if (pfnGetAssetProps_ != nullptr) {
XrRenderModelAssetPropertiesGetInfoEXT agi{
XR_TYPE_RENDER_MODEL_ASSET_PROPERTIES_GET_INFO_EXT};
XrRenderModelAssetPropertiesEXT aprops{
XR_TYPE_RENDER_MODEL_ASSET_PROPERTIES_EXT};
if (XR_SUCCEEDED(pfnGetAssetProps_(asset, &agi, &aprops))) {
std::vector<XrRenderModelAssetNodePropertiesEXT> names(
aprops.nodePropertyCount);
aprops.nodePropertyCount = static_cast<uint32_t>(names.size());
aprops.nodeProperties = names.data();
if (XR_SUCCEEDED(pfnGetAssetProps_(asset, &agi, &aprops))) {
nodeNames.reserve(names.size());
for (const auto& np : names) nodeNames.emplace_back(np.uniqueName);
}
}
}
ModelInfo& mi = models_[hand];
mi.id = id;
mi.model = model;
mi.asset = asset;
mi.space = modelSpace;
mi.gltf = std::move(gltf);
mi.animatableNodeCount = props.animatableNodeCount;
mi.nodeNames = std::move(nodeNames);
mi.ready = true;
PIXELVR_LOG_INFO("Render model for %s hand fetched: %u nodes, glTF %zu bytes",
hand == 0 ? "left" : "right",
mi.animatableNodeCount, mi.gltf.size());
}
PIXELVR_LOG_INFO("Render model fetched: %u animatable nodes, glTF %zu bytes",
animatableNodeCount_, gltf_.size());
if (FILE* f = std::fopen("/tmp/controller_model.glb", "wb")) {
std::fwrite(gltf_.data(), 1, gltf_.size(), f);
std::fclose(f);
if (models_[0].ready && models_[1].ready) {
done_ = true;
}
return true;
return models_[0].ready || models_[1].ready;
}
bool RenderModelSystem::locate(XrSpace base, XrTime time, float outPos[3],
bool RenderModelSystem::locate(int hand, XrSpace base, XrTime time, float outPos[3],
float outQuat[4]) const {
if (modelSpace_ == XR_NULL_HANDLE || time == 0) return false;
if (hand < 0 || hand >= 2) return false;
const XrSpace space = models_[hand].space;
if (space == XR_NULL_HANDLE || time == 0) return false;
XrSpaceLocation loc{XR_TYPE_SPACE_LOCATION};
if (XR_FAILED(xrLocateSpace(modelSpace_, base, time, &loc))) return false;
if (XR_FAILED(xrLocateSpace(space, base, time, &loc))) return false;
constexpr XrSpaceLocationFlags need =
XR_SPACE_LOCATION_ORIENTATION_VALID_BIT |
XR_SPACE_LOCATION_POSITION_VALID_BIT;
@@ -169,33 +222,35 @@ bool RenderModelSystem::locate(XrSpace base, XrTime time, float outPos[3],
return true;
}
bool RenderModelSystem::nodeStates(XrTime time, std::vector<NodeState>& out) {
if (!available_ || model_ == XR_NULL_HANDLE || pfnGetState_ == nullptr ||
bool RenderModelSystem::nodeStates(int hand, XrTime time, std::vector<NodeState>& out) {
if (hand < 0 || hand >= 2) return false;
ModelInfo& mi = models_[hand];
if (!available_ || mi.model == XR_NULL_HANDLE || pfnGetState_ == nullptr ||
time == 0) {
return false;
}
if (nodeStateBuf_.size() < animatableNodeCount_) {
nodeStateBuf_.resize(animatableNodeCount_);
if (mi.nodeStateBuf.size() < mi.animatableNodeCount) {
mi.nodeStateBuf.resize(mi.animatableNodeCount);
}
XrRenderModelStateGetInfoEXT gi{XR_TYPE_RENDER_MODEL_STATE_GET_INFO_EXT};
gi.displayTime = time;
XrRenderModelStateEXT st{XR_TYPE_RENDER_MODEL_STATE_EXT};
st.nodeStateCount = static_cast<uint32_t>(nodeStateBuf_.size());
st.nodeStates = nodeStateBuf_.data();
if (XR_FAILED(pfnGetState_(model_, &gi, &st))) {
st.nodeStateCount = static_cast<uint32_t>(mi.nodeStateBuf.size());
st.nodeStates = mi.nodeStateBuf.data();
if (XR_FAILED(pfnGetState_(mi.model, &gi, &st))) {
return false;
}
if (st.nodeStateCount > nodeStateBuf_.size()) { // grew; retry once
nodeStateBuf_.resize(st.nodeStateCount);
st.nodeStateCount = static_cast<uint32_t>(nodeStateBuf_.size());
st.nodeStates = nodeStateBuf_.data();
if (XR_FAILED(pfnGetState_(model_, &gi, &st))) {
if (st.nodeStateCount > mi.nodeStateBuf.size()) { // grew; retry once
mi.nodeStateBuf.resize(st.nodeStateCount);
st.nodeStateCount = static_cast<uint32_t>(mi.nodeStateBuf.size());
st.nodeStates = mi.nodeStateBuf.data();
if (XR_FAILED(pfnGetState_(mi.model, &gi, &st))) {
return false;
}
}
out.resize(st.nodeStateCount);
for (uint32_t i = 0; i < st.nodeStateCount; ++i) {
const XrRenderModelNodeStateEXT& n = nodeStateBuf_[i];
const XrRenderModelNodeStateEXT& n = mi.nodeStateBuf[i];
NodeState& o = out[i];
o.pos[0] = n.nodePose.position.x;
o.pos[1] = n.nodePose.position.y;
@@ -210,17 +265,21 @@ bool RenderModelSystem::nodeStates(XrTime time, std::vector<NodeState>& out) {
}
void RenderModelSystem::shutdown() {
if (modelSpace_ != XR_NULL_HANDLE) {
xrDestroySpace(modelSpace_);
modelSpace_ = XR_NULL_HANDLE;
}
if (asset_ != XR_NULL_HANDLE && pfnDestroyAsset_ != nullptr) {
pfnDestroyAsset_(asset_);
asset_ = XR_NULL_HANDLE;
}
if (model_ != XR_NULL_HANDLE && pfnDestroyModel_ != nullptr) {
pfnDestroyModel_(model_);
model_ = XR_NULL_HANDLE;
for (int h = 0; h < 2; ++h) {
ModelInfo& mi = models_[h];
if (mi.space != XR_NULL_HANDLE) {
xrDestroySpace(mi.space);
mi.space = XR_NULL_HANDLE;
}
if (mi.asset != XR_NULL_HANDLE && pfnDestroyAsset_ != nullptr) {
pfnDestroyAsset_(mi.asset);
mi.asset = XR_NULL_HANDLE;
}
if (mi.model != XR_NULL_HANDLE && pfnDestroyModel_ != nullptr) {
pfnDestroyModel_(mi.model);
mi.model = XR_NULL_HANDLE;
}
mi.ready = false;
}
}
+42 -24
View File
@@ -9,9 +9,7 @@
namespace pixelvr {
// Fetches (and, in later stages, renders) the runtime-provided controller models
// via XR_EXT_render_model. Stage 2 scope: resolve the extension entry points,
// enumerate the active interaction render models, and pull the first one's
// glTF/GLB asset bytes so the renderer can parse and draw it.
// via XR_EXT_render_model for both left (0) and right (1) hands.
class RenderModelSystem {
public:
// Resolves the extension function pointers. `enabled` is whether the three
@@ -20,22 +18,33 @@ public:
bool available() const { return available_; }
// Lazily enumerates + fetches the first controller model's glTF the first
// time a controller is active. Safe to call every frame. Returns true once
// the asset bytes are ready.
// Lazily enumerates + fetches controller models for both hands.
// Safe to call every frame.
bool poll();
bool assetReady() const { return !gltf_.empty(); }
const std::vector<uint8_t>& gltf() const { return gltf_; }
uint32_t animatableNodeCount() const { return animatableNodeCount_; }
bool assetReady(int hand = 1) const {
return hand >= 0 && hand < 2 && models_[hand].ready && !models_[hand].gltf.empty();
}
const std::vector<uint8_t>& gltf(int hand = 1) const {
static const std::vector<uint8_t> kEmpty;
return (hand >= 0 && hand < 2) ? models_[hand].gltf : kEmpty;
}
uint32_t animatableNodeCount(int hand = 1) const {
return (hand >= 0 && hand < 2) ? models_[hand].animatableNodeCount : 0;
}
// Locates the render-model space in `base` at `time` (the pose the runtime
// expects the glTF to be rendered at). False if not fetched or untracked.
bool locate(XrSpace base, XrTime time, float outPos[3], float outQuat[4]) const;
// Locates the render-model space in `base` at `time` for `hand` (0 = left, 1 = right).
bool locate(int hand, XrSpace base, XrTime time, float outPos[3], float outQuat[4]) const;
bool locate(XrSpace base, XrTime time, float outPos[3], float outQuat[4]) const {
return locate(1, base, time, outPos, outQuat);
}
// Names of the model's animatable nodes, in the same order as the node
// states returned by nodeStates() (maps a node state to glTF geometry).
const std::vector<std::string>& nodeNames() const { return nodeNames_; }
const std::vector<std::string>& nodeNames(int hand = 1) const {
static const std::vector<std::string> kEmpty;
return (hand >= 0 && hand < 2) ? models_[hand].nodeNames : kEmpty;
}
// Animated per-node transform the runtime wants applied this frame (drives
// button-press movement, trigger pull, thumbstick tilt, etc.).
@@ -44,28 +53,37 @@ public:
float quat[4] = {0.0f, 0.0f, 0.0f, 1.0f};
bool visible = true;
};
// Fills `out` (parallel to nodeNames()) for `time`. False if unavailable.
bool nodeStates(XrTime time, std::vector<NodeState>& out);
// Fills `out` (parallel to nodeNames()) for `hand` at `time`. False if unavailable.
bool nodeStates(int hand, XrTime time, std::vector<NodeState>& out);
bool nodeStates(XrTime time, std::vector<NodeState>& out) {
return nodeStates(1, time, out);
}
void shutdown();
private:
bool fetchFirstModel();
bool fetchModels();
XrInstance instance_ = XR_NULL_HANDLE;
XrSession session_ = XR_NULL_HANDLE;
bool available_ = false;
bool done_ = false; // asset fetched (or permanently failed)
bool done_ = false; // all models fetched (or permanently failed)
XrRenderModelEXT model_ = XR_NULL_HANDLE;
XrRenderModelAssetEXT asset_ = XR_NULL_HANDLE;
XrSpace modelSpace_ = XR_NULL_HANDLE;
std::vector<uint8_t> gltf_;
uint32_t animatableNodeCount_ = 0;
std::vector<std::string> nodeNames_;
std::vector<XrRenderModelNodeStateEXT> nodeStateBuf_; // reused per frame
struct ModelInfo {
XrRenderModelIdEXT id = XR_NULL_RENDER_MODEL_ID_EXT;
XrRenderModelEXT model = XR_NULL_HANDLE;
XrRenderModelAssetEXT asset = XR_NULL_HANDLE;
XrSpace space = XR_NULL_HANDLE;
std::vector<uint8_t> gltf;
std::vector<std::string> nodeNames;
std::vector<XrRenderModelNodeStateEXT> nodeStateBuf; // reused per frame
uint32_t animatableNodeCount = 0;
bool ready = false;
};
ModelInfo models_[2]; // 0 = left, 1 = right
PFN_xrEnumerateInteractionRenderModelIdsEXT pfnEnumerateIds_ = nullptr;
PFN_xrEnumerateRenderModelSubactionPathsEXT pfnEnumerateSubactionPaths_ = nullptr;
PFN_xrCreateRenderModelEXT pfnCreateModel_ = nullptr;
PFN_xrGetRenderModelPropertiesEXT pfnGetProps_ = nullptr;
PFN_xrCreateRenderModelAssetEXT pfnCreateAsset_ = nullptr;
+181 -13
View File
@@ -3,6 +3,7 @@
#include "xr/xr_result.hpp"
#include "util/logging.hpp"
#include <algorithm>
#include <array>
#include <cstring>
@@ -236,8 +237,18 @@ bool XrContext::createSwapchains(int64_t colorFormat) {
for (const auto& view : configViews_) {
ViewSwapchain sc;
sc.width = static_cast<int32_t>(view.recommendedImageRectWidth);
sc.height = static_cast<int32_t>(view.recommendedImageRectHeight);
// Boost swapchain resolution from SteamVR's conservative default (1728) to the headset's
// native physical display resolution (2160x2160, 1.25x).
// Rendering at 1:1 panel resolution eliminates compositor magnification blur and
// edge shimmering during head movement in VR.
const uint32_t maxW = (view.maxImageRectWidth > 0) ? view.maxImageRectWidth : 4096;
const uint32_t maxH = (view.maxImageRectHeight > 0) ? view.maxImageRectHeight : 4096;
const uint32_t targetW = std::clamp(static_cast<uint32_t>(view.recommendedImageRectWidth * 1.25f),
view.recommendedImageRectWidth, maxW);
const uint32_t targetH = std::clamp(static_cast<uint32_t>(view.recommendedImageRectHeight * 1.25f),
view.recommendedImageRectHeight, maxH);
sc.width = static_cast<int32_t>(targetW);
sc.height = static_cast<int32_t>(targetH);
sc.format = colorFormat;
XrSwapchainCreateInfo createInfo{XR_TYPE_SWAPCHAIN_CREATE_INFO};
@@ -245,8 +256,8 @@ bool XrContext::createSwapchains(int64_t colorFormat) {
XR_SWAPCHAIN_USAGE_SAMPLED_BIT;
createInfo.format = colorFormat;
createInfo.sampleCount = 1;
createInfo.width = view.recommendedImageRectWidth;
createInfo.height = view.recommendedImageRectHeight;
createInfo.width = targetW;
createInfo.height = targetH;
createInfo.faceCount = 1;
createInfo.arraySize = 1;
createInfo.mipCount = 1;
@@ -267,7 +278,9 @@ bool XrContext::createSwapchains(int64_t colorFormat) {
swapchains_.push_back(std::move(sc));
}
PIXELVR_LOG_INFO("Created %zu swapchains", swapchains_.size());
PIXELVR_LOG_INFO("Created %zu swapchains (%dx%d per eye)", swapchains_.size(),
swapchains_.empty() ? 0 : swapchains_[0].width,
swapchains_.empty() ? 0 : swapchains_[0].height);
return true;
}
@@ -337,6 +350,42 @@ bool XrContext::createActions() {
gripPoseAction_ = XR_NULL_HANDLE;
}
}
{
XrActionCreateInfo ai{XR_TYPE_ACTION_CREATE_INFO};
std::strcpy(ai.actionName, "grip_full_press");
std::strcpy(ai.localizedActionName, "Grip Full Press Click");
ai.actionType = XR_ACTION_TYPE_BOOLEAN_INPUT;
ai.countSubactionPaths = 2;
ai.subactionPaths = handPaths_;
if (XR_FAILED(xrCreateAction(actionSet_, &ai, &gripFullPressAction_))) {
PIXELVR_LOG_WARN("Failed to create grip full press action");
gripFullPressAction_ = XR_NULL_HANDLE;
}
}
{
XrActionCreateInfo ai{XR_TYPE_ACTION_CREATE_INFO};
std::strcpy(ai.actionName, "squeeze_val");
std::strcpy(ai.localizedActionName, "Squeeze Value");
ai.actionType = XR_ACTION_TYPE_FLOAT_INPUT;
ai.countSubactionPaths = 2;
ai.subactionPaths = handPaths_;
if (XR_FAILED(xrCreateAction(actionSet_, &ai, &squeezeValueAction_))) {
PIXELVR_LOG_WARN("Failed to create squeeze value action");
squeezeValueAction_ = XR_NULL_HANDLE;
}
}
{
XrActionCreateInfo ai{XR_TYPE_ACTION_CREATE_INFO};
std::strcpy(ai.actionName, "haptic_out");
std::strcpy(ai.localizedActionName, "Haptic Output");
ai.actionType = XR_ACTION_TYPE_VIBRATION_OUTPUT;
ai.countSubactionPaths = 2;
ai.subactionPaths = handPaths_;
if (XR_FAILED(xrCreateAction(actionSet_, &ai, &hapticAction_))) {
PIXELVR_LOG_WARN("Failed to create haptic action");
hapticAction_ = XR_NULL_HANDLE;
}
}
// Physical buttons for user-configurable bindings (native Steam Frame paths).
static const struct {
@@ -344,11 +393,11 @@ bool XrContext::createActions() {
const char* p0;
const char* p1;
} kBtns[] = {
{"btn_a", "/user/hand/right/input/a/click", nullptr},
{"btn_b", "/user/hand/right/input/b/click", nullptr},
{"btn_x", "/user/hand/right/input/x/click", nullptr},
{"btn_y", "/user/hand/right/input/y/click", nullptr},
{"btn_menu", "/user/hand/right/input/menu/click", nullptr},
{"btn_a", "/user/hand/right/input/a/click", "/user/hand/left/input/a/click"},
{"btn_b", "/user/hand/right/input/b/click", "/user/hand/left/input/b/click"},
{"btn_x", "/user/hand/left/input/x/click", "/user/hand/right/input/x/click"},
{"btn_y", "/user/hand/left/input/y/click", "/user/hand/right/input/y/click"},
{"btn_menu", "/user/hand/left/input/menu/click", "/user/hand/right/input/menu/click"},
{"btn_view", "/user/hand/left/input/view/click", nullptr},
{"btn_bumper", "/user/hand/left/input/bumper/click",
"/user/hand/right/input/bumper/click"},
@@ -397,7 +446,9 @@ bool XrContext::createActions() {
{aimPoseAction_, path("/user/hand/left/input/aim/pose")},
{aimPoseAction_, path("/user/hand/right/input/aim/pose")},
{gripPoseAction_, path("/user/hand/left/input/grip/pose")},
{gripPoseAction_, path("/user/hand/right/input/grip/pose")}});
{gripPoseAction_, path("/user/hand/right/input/grip/pose")},
{hapticAction_, path("/user/hand/left/output/haptic")},
{hapticAction_, path("/user/hand/right/output/haptic")}});
suggest("/interaction_profiles/oculus/touch_controller",
{{togglePlayAction_, path("/user/hand/right/input/a/click")},
@@ -408,6 +459,8 @@ bool XrContext::createActions() {
{selectAction_, path("/user/hand/left/input/trigger/value")},
{recenterAction_, path("/user/hand/right/input/squeeze/value")},
{recenterAction_, path("/user/hand/left/input/squeeze/value")},
{squeezeValueAction_, path("/user/hand/right/input/squeeze/value")},
{squeezeValueAction_, path("/user/hand/left/input/squeeze/value")},
{thumbstickAction_, path("/user/hand/right/input/thumbstick")},
{thumbstickAction_, path("/user/hand/left/input/thumbstick")},
{thumbstickLeftAction_, path("/user/hand/left/input/thumbstick")},
@@ -415,7 +468,18 @@ bool XrContext::createActions() {
{aimPoseAction_, path("/user/hand/right/input/aim/pose")},
{aimPoseAction_, path("/user/hand/left/input/aim/pose")},
{gripPoseAction_, path("/user/hand/right/input/grip/pose")},
{gripPoseAction_, path("/user/hand/left/input/grip/pose")}});
{gripPoseAction_, path("/user/hand/left/input/grip/pose")},
{hapticAction_, path("/user/hand/right/output/haptic")},
{hapticAction_, path("/user/hand/left/output/haptic")},
{buttonActions_[XrInputState::BtnA], path("/user/hand/right/input/a/click")},
{buttonActions_[XrInputState::BtnB], path("/user/hand/right/input/b/click")},
{buttonActions_[XrInputState::BtnX], path("/user/hand/left/input/x/click")},
{buttonActions_[XrInputState::BtnY], path("/user/hand/left/input/y/click")},
{buttonActions_[XrInputState::BtnMenu], path("/user/hand/left/input/menu/click")},
{buttonActions_[XrInputState::BtnThumb], path("/user/hand/right/input/thumbstick/click")},
{buttonActions_[XrInputState::BtnThumb], path("/user/hand/left/input/thumbstick/click")},
{buttonActions_[XrInputState::BtnGrip], path("/user/hand/right/input/squeeze/value")},
{buttonActions_[XrInputState::BtnGrip], path("/user/hand/left/input/squeeze/value")}});
suggest("/interaction_profiles/valve/index_controller",
{{togglePlayAction_, path("/user/hand/right/input/a/click")},
@@ -426,6 +490,10 @@ bool XrContext::createActions() {
{selectAction_, path("/user/hand/left/input/trigger/value")},
{recenterAction_, path("/user/hand/right/input/squeeze/value")},
{recenterAction_, path("/user/hand/left/input/squeeze/value")},
{gripFullPressAction_, path("/user/hand/right/input/squeeze/click")},
{gripFullPressAction_, path("/user/hand/left/input/squeeze/click")},
{squeezeValueAction_, path("/user/hand/right/input/squeeze/value")},
{squeezeValueAction_, path("/user/hand/left/input/squeeze/value")},
{thumbstickAction_, path("/user/hand/right/input/thumbstick")},
{thumbstickAction_, path("/user/hand/left/input/thumbstick")},
{thumbstickLeftAction_, path("/user/hand/left/input/thumbstick")},
@@ -433,7 +501,17 @@ bool XrContext::createActions() {
{aimPoseAction_, path("/user/hand/right/input/aim/pose")},
{aimPoseAction_, path("/user/hand/left/input/aim/pose")},
{gripPoseAction_, path("/user/hand/right/input/grip/pose")},
{gripPoseAction_, path("/user/hand/left/input/grip/pose")}});
{gripPoseAction_, path("/user/hand/left/input/grip/pose")},
{hapticAction_, path("/user/hand/right/output/haptic")},
{hapticAction_, path("/user/hand/left/output/haptic")},
{buttonActions_[XrInputState::BtnA], path("/user/hand/right/input/a/click")},
{buttonActions_[XrInputState::BtnA], path("/user/hand/left/input/a/click")},
{buttonActions_[XrInputState::BtnB], path("/user/hand/right/input/b/click")},
{buttonActions_[XrInputState::BtnB], path("/user/hand/left/input/b/click")},
{buttonActions_[XrInputState::BtnThumb], path("/user/hand/right/input/thumbstick/click")},
{buttonActions_[XrInputState::BtnThumb], path("/user/hand/left/input/thumbstick/click")},
{buttonActions_[XrInputState::BtnGrip], path("/user/hand/right/input/squeeze/value")},
{buttonActions_[XrInputState::BtnGrip], path("/user/hand/left/input/squeeze/value")}});
// Native Steam Frame profile: the runtime rejects the whole set if any path
// is invalid, so probe each candidate individually, keep the accepted ones,
@@ -466,6 +544,16 @@ bool XrContext::createActions() {
probe(recenterAction_, "/user/hand/right/input/squeeze/value");
probe(recenterAction_, "/user/hand/left/input/grip/value");
probe(recenterAction_, "/user/hand/right/input/grip/value");
probe(gripFullPressAction_, "/user/hand/left/input/squeeze/click");
probe(gripFullPressAction_, "/user/hand/right/input/squeeze/click");
probe(gripFullPressAction_, "/user/hand/left/input/grip/click");
probe(gripFullPressAction_, "/user/hand/right/input/grip/click");
probe(squeezeValueAction_, "/user/hand/left/input/squeeze/value");
probe(squeezeValueAction_, "/user/hand/right/input/squeeze/value");
probe(squeezeValueAction_, "/user/hand/left/input/grip/value");
probe(squeezeValueAction_, "/user/hand/right/input/grip/value");
probe(hapticAction_, "/user/hand/left/output/haptic");
probe(hapticAction_, "/user/hand/right/output/haptic");
probe(togglePlayAction_, "/user/hand/right/input/a/click");
probe(browserAction_, "/user/hand/right/input/b/click");
probe(browserAction_, "/user/hand/left/input/view/click");
@@ -543,6 +631,8 @@ void XrContext::syncActions() {
input_.thumbstickRX = 0.0f;
input_.thumbstickRY = 0.0f;
for (int i = 0; i < XrInputState::BtnCount; ++i) input_.buttonDown[i] = false;
input_.gripDown[0] = false;
input_.gripDown[1] = false;
if (!actionsReady_) {
return;
}
@@ -628,6 +718,84 @@ void XrContext::syncActions() {
st.isActive && st.currentState && st.changedSinceLastSync;
}
}
// Per-hand grip press: `buttonDown` above aggregates both hands, but the laser
// pointer is toggled per hand, so query the squeeze action for each subaction.
if (buttonActions_[XrInputState::BtnGrip] != XR_NULL_HANDLE) {
for (int h = 0; h < 2; ++h) {
XrActionStateGetInfo gi{XR_TYPE_ACTION_STATE_GET_INFO};
gi.action = buttonActions_[XrInputState::BtnGrip];
gi.subactionPath = handPaths_[h];
XrActionStateBoolean st{XR_TYPE_ACTION_STATE_BOOLEAN};
if (XR_SUCCEEDED(xrGetActionStateBoolean(session_, &gi, &st))) {
input_.gripDown[h] =
st.isActive && st.currentState && st.changedSinceLastSync;
}
}
}
// Discrete full-press click vs analog soft squeeze
for (int h = 0; h < 2; ++h) {
float sqVal = 0.0f;
if (squeezeValueAction_ != XR_NULL_HANDLE) {
XrActionStateGetInfo gi{XR_TYPE_ACTION_STATE_GET_INFO};
gi.action = squeezeValueAction_;
gi.subactionPath = handPaths_[h];
XrActionStateFloat st{XR_TYPE_ACTION_STATE_FLOAT};
if (XR_SUCCEEDED(xrGetActionStateFloat(session_, &gi, &st)) && st.isActive) {
sqVal = st.currentState;
}
}
input_.gripValue[h] = sqVal;
bool fullHeld = false;
bool fullDown = false;
if (gripFullPressAction_ != XR_NULL_HANDLE) {
XrActionStateGetInfo gi{XR_TYPE_ACTION_STATE_GET_INFO};
gi.action = gripFullPressAction_;
gi.subactionPath = handPaths_[h];
XrActionStateBoolean st{XR_TYPE_ACTION_STATE_BOOLEAN};
if (XR_SUCCEEDED(xrGetActionStateBoolean(session_, &gi, &st)) && st.isActive) {
fullHeld = st.currentState;
fullDown = st.currentState && st.changedSinceLastSync;
}
}
// Fallback for hardware profiles where squeeze/click is not exposed separately:
// Use a strict bottom-out threshold (>= 0.90f to engage, < 0.80f to release)
static bool sPrevFull[2] = {false, false};
if (!fullHeld) {
if (sPrevFull[h]) {
if (sqVal >= 0.80f) {
fullHeld = true;
} else {
sPrevFull[h] = false;
}
} else {
if (sqVal >= 0.90f) {
fullHeld = true;
fullDown = true;
sPrevFull[h] = true;
}
}
}
input_.gripFullPressHeld[h] = fullHeld;
input_.gripFullPressDown[h] = fullDown;
}
}
void XrContext::triggerHaptic(int hand, float durationSec, float frequencyHz, float amplitude) {
if (session_ == XR_NULL_HANDLE || hapticAction_ == XR_NULL_HANDLE) return;
if (hand < 0 || hand >= 2 || handPaths_[hand] == XR_NULL_PATH) return;
XrHapticVibration vib{XR_TYPE_HAPTIC_VIBRATION};
vib.duration = static_cast<XrDuration>(durationSec * 1e9f);
vib.frequency = frequencyHz;
vib.amplitude = std::clamp(amplitude, 0.0f, 1.0f);
XrHapticActionInfo hai{XR_TYPE_HAPTIC_ACTION_INFO};
hai.action = hapticAction_;
hai.subactionPath = handPaths_[hand];
xrApplyHapticFeedback(session_, &hai, reinterpret_cast<const XrHapticBaseHeader*>(&vib));
}
void XrContext::handleSessionStateChange(const XrEventDataSessionStateChanged& ev,
+16
View File
@@ -56,6 +56,17 @@ struct XrInputState {
BtnDpadUp, BtnDpadDown, BtnDpadLeft, BtnDpadRight, BtnCount
};
bool buttonDown[BtnCount] = {};
// Per-hand grip (squeeze) rising edge: toggles that hand's laser pointer, so
// one controller can drive a panel with the stick while the other points.
// Index 0 = left, 1 = right.
bool gripDown[2] = {false, false};
// Discrete full-press click per hand (Index / Frame / Touch squeeze click).
// Distinct from soft/resting squeeze. Index 0 = left, 1 = right.
bool gripFullPressHeld[2] = {false, false};
bool gripFullPressDown[2] = {false, false};
float gripValue[2] = {0.0f, 0.0f}; // analog soft squeeze value (0.0 to 1.0)
};
// Owns the OpenXR instance, system, session, reference space, and swapchains,
@@ -89,12 +100,14 @@ public:
// Controller input (OpenXR actions). Call createActions after createSession.
bool createActions();
const XrInputState& input() const { return input_; }
void triggerHaptic(int hand, float durationSec = 0.015f, float frequencyHz = 0.0f, float amplitude = 0.5f);
// --- Runtime ---------------------------------------------------------
// Pumps the event queue and advances the session state machine.
// Sets exitRequested when the runtime asks the app to quit.
bool pollEvents(bool& exitRequested);
bool sessionRunning() const { return sessionRunning_; }
bool sessionFocused() const { return sessionState_ == XR_SESSION_STATE_FOCUSED; }
// Callback invoked once per view when the frame should be rendered.
using RenderViewFn = std::function<void(uint32_t viewIndex, uint32_t imageIndex,
@@ -156,6 +169,9 @@ private:
XrAction aimPoseAction_ = XR_NULL_HANDLE;
XrAction gripPoseAction_ = XR_NULL_HANDLE;
XrAction buttonActions_[XrInputState::BtnCount] = {};
XrAction gripFullPressAction_ = XR_NULL_HANDLE;
XrAction squeezeValueAction_ = XR_NULL_HANDLE;
XrAction hapticAction_ = XR_NULL_HANDLE;
XrPath handPaths_[2] = {XR_NULL_PATH, XR_NULL_PATH};
XrSpace aimSpaces_[2] = {XR_NULL_HANDLE, XR_NULL_HANDLE};
XrSpace gripSpaces_[2] = {XR_NULL_HANDLE, XR_NULL_HANDLE};
+198
View File
@@ -0,0 +1,198 @@
#include "app/vault_manager.hpp"
#include <cassert>
#include <iostream>
#include <fstream>
#include <filesystem>
using namespace pixelvr;
namespace fs = std::filesystem;
int main() {
std::cout << "[TEST] Starting VaultManager verification..." << std::endl;
auto& vm = VaultManager::instance();
// Reset to default combo sequence for reproducible testing
vm.startRecordingCombo();
vm.feedRecordButton(XrInputState::BtnA);
vm.feedRecordButton(XrInputState::BtnB);
vm.feedRecordButton(XrInputState::BtnB);
vm.feedRecordButton(XrInputState::BtnA);
vm.feedRecordButton(XrInputState::BtnX);
vm.feedRecordButton(XrInputState::BtnY);
// 1. Initial locked state
vm.lock();
assert(!vm.isUnlocked());
std::cout << "[PASS] Initial state is locked." << std::endl;
// 2. Discrete grip requirement (soft squeeze / grip=false should not advance)
auto now = std::chrono::steady_clock::now();
assert(vm.feedInput(XrInputState::BtnA, false, now) == VaultManager::ComboResult::None);
assert(vm.feedInput(XrInputState::BtnB, false, now) == VaultManager::ComboResult::None);
assert(!vm.isUnlocked());
std::cout << "[PASS] Soft squeeze / no grip full press does not trigger combo." << std::endl;
// 3. Step through default combo: A -> B -> B -> A -> X -> Y
assert(vm.feedInput(XrInputState::BtnA, true, now) == VaultManager::ComboResult::StepMatched);
assert(vm.feedInput(XrInputState::BtnB, true, now) == VaultManager::ComboResult::StepMatched);
assert(vm.feedInput(XrInputState::BtnB, true, now) == VaultManager::ComboResult::StepMatched);
assert(vm.feedInput(XrInputState::BtnA, true, now) == VaultManager::ComboResult::StepMatched);
assert(vm.feedInput(XrInputState::BtnX, true, now) == VaultManager::ComboResult::StepMatched);
assert(vm.feedInput(XrInputState::BtnY, true, now) == VaultManager::ComboResult::Unlocked);
assert(vm.isUnlocked());
std::cout << "[PASS] Cheat code A-B-B-A-X-Y with grip full press unlocks vault!" << std::endl;
// Verify vault directories exist and have 0700 permissions
assert(fs::exists(vm.vaultDir()));
assert(fs::exists(vm.thumbsDir()));
auto perms = fs::status(vm.vaultDir()).permissions();
assert((perms & fs::perms::others_all) == fs::perms::none);
std::cout << "[PASS] Vault directory created with secure 0700 permissions: " << vm.vaultDir() << std::endl;
// 4. Test re-lock via combo
assert(vm.feedInput(XrInputState::BtnA, true, now) == VaultManager::ComboResult::StepMatched);
assert(vm.feedInput(XrInputState::BtnB, true, now) == VaultManager::ComboResult::StepMatched);
assert(vm.feedInput(XrInputState::BtnB, true, now) == VaultManager::ComboResult::StepMatched);
assert(vm.feedInput(XrInputState::BtnA, true, now) == VaultManager::ComboResult::StepMatched);
assert(vm.feedInput(XrInputState::BtnX, true, now) == VaultManager::ComboResult::StepMatched);
assert(vm.feedInput(XrInputState::BtnY, true, now) == VaultManager::ComboResult::Locked);
assert(!vm.isUnlocked());
std::cout << "[PASS] Entering combo again locks the vault." << std::endl;
// 5. Test Headset removal auto-lock with 3-second debounce
vm.unlock();
assert(vm.isUnlocked());
assert(!vm.tick(now, false)); // Momentary flicker (<3s) does NOT lock
assert(vm.isUnlocked());
assert(vm.tick(now + std::chrono::milliseconds(3100), false)); // >=3s continuous loss locks
assert(!vm.isUnlocked());
std::cout << "[PASS] Auto-lock on headset removal successfully locks vault after 3s debounce." << std::endl;
// 6. Test Inactivity timeout (enabled vs disabled)
vm.unlock();
vm.setAutoLockTimeoutSec(2); // 2 seconds for test
vm.recordActivity(now);
assert(!vm.tick(now, true)); // immediate tick does not lock
assert(vm.isUnlocked());
assert(vm.tick(now + std::chrono::seconds(3), true)); // 3s later -> timeout
assert(!vm.isUnlocked());
std::cout << "[PASS] Inactivity timeout successfully locks vault when enabled." << std::endl;
// Test Inactivity timeout disabled (default)
vm.unlock();
vm.setAutoLockTimeoutSec(0); // 0 = disabled
vm.recordActivity(now);
assert(!vm.tick(now + std::chrono::hours(1), true)); // 1 hour later -> still unlocked because disabled
assert(vm.isUnlocked());
std::cout << "[PASS] Inactivity timeout = 0 disables timeout auto-lock." << std::endl;
// 7. Test Move-to-Vault for single file and collision resolution
vm.unlock();
std::string testSrc = "/tmp/pixelvr_test_clip.mp4";
{
std::ofstream f(testSrc);
f << "dummy video content 12345";
}
std::string outPath1;
std::string err1 = vm.moveFileToVault(testSrc, outPath1);
assert(err1.empty());
assert(!fs::exists(testSrc));
assert(fs::exists(outPath1));
std::cout << "[PASS] Move file to vault succeeded: " << outPath1 << std::endl;
// Collision test: create another file with same name
{
std::ofstream f(testSrc);
f << "dummy video content second version";
}
std::string outPath2;
std::string err2 = vm.moveFileToVault(testSrc, outPath2);
assert(err2.empty());
assert(!fs::exists(testSrc));
assert(fs::exists(outPath2));
assert(outPath1 != outPath2);
std::cout << "[PASS] Collision resolved properly: " << outPath2 << std::endl;
// Clean up test files
fs::remove(outPath1);
fs::remove(outPath2);
// 8. Test Move-to-Vault for entire directory and recursive permissions
std::string testDir = "/tmp/pixelvr_test_folder";
fs::create_directories(testDir);
{
std::ofstream f1(testDir + "/subvideo1.mp4");
f1 << "sub video 1 content";
std::ofstream f2(testDir + "/subvideo2.mp4");
f2 << "sub video 2 content";
}
std::string outDir1;
std::string errDir1 = vm.moveFileToVault(testDir, outDir1);
assert(errDir1.empty());
assert(!fs::exists(testDir));
assert(fs::exists(outDir1));
assert(fs::is_directory(outDir1));
assert(fs::exists(outDir1 + "/subvideo1.mp4"));
assert(fs::exists(outDir1 + "/subvideo2.mp4"));
// Check directory permissions
auto dirPerms = fs::status(outDir1).permissions();
assert((dirPerms & fs::perms::others_all) == fs::perms::none);
std::cout << "[PASS] Move entire folder to vault succeeded with 0700 permissions: " << outDir1 << std::endl;
// Folder collision test: recreate folder and move again
fs::create_directories(testDir);
{
std::ofstream f(testDir + "/subvideo3.mp4");
f << "sub video 3 content";
}
std::string outDir2;
std::string errDir2 = vm.moveFileToVault(testDir, outDir2);
assert(errDir2.empty());
assert(!fs::exists(testDir));
assert(fs::exists(outDir2));
assert(outDir1 != outDir2);
assert(fs::exists(outDir2 + "/subvideo3.mp4"));
std::cout << "[PASS] Folder collision resolved properly: " << outDir2 << std::endl;
// Clean up test directories
fs::remove_all(outDir1);
fs::remove_all(outDir2);
// 9. Custom combo recording
vm.startRecordingCombo();
assert(vm.isRecordingCombo());
assert(!vm.feedRecordButton(XrInputState::BtnX));
assert(!vm.feedRecordButton(XrInputState::BtnX));
assert(!vm.feedRecordButton(XrInputState::BtnY));
assert(!vm.feedRecordButton(XrInputState::BtnY));
assert(!vm.feedRecordButton(XrInputState::BtnA));
assert(vm.feedRecordButton(XrInputState::BtnB)); // 6th button finishes
assert(!vm.isRecordingCombo());
assert(vm.comboString() == "X X Y Y A B");
std::cout << "[PASS] Custom combo recording verified: " << vm.comboString() << std::endl;
// Test new combo works
vm.lock();
assert(vm.feedInput(XrInputState::BtnX, true, now) == VaultManager::ComboResult::StepMatched);
assert(vm.feedInput(XrInputState::BtnX, true, now) == VaultManager::ComboResult::StepMatched);
assert(vm.feedInput(XrInputState::BtnY, true, now) == VaultManager::ComboResult::StepMatched);
assert(vm.feedInput(XrInputState::BtnY, true, now) == VaultManager::ComboResult::StepMatched);
assert(vm.feedInput(XrInputState::BtnA, true, now) == VaultManager::ComboResult::StepMatched);
assert(vm.feedInput(XrInputState::BtnB, true, now) == VaultManager::ComboResult::Unlocked);
assert(vm.isUnlocked());
std::cout << "[PASS] New custom combo successfully unlocked vault!" << std::endl;
// Restore default combo
vm.startRecordingCombo();
vm.feedRecordButton(XrInputState::BtnA);
vm.feedRecordButton(XrInputState::BtnB);
vm.feedRecordButton(XrInputState::BtnB);
vm.feedRecordButton(XrInputState::BtnA);
vm.feedRecordButton(XrInputState::BtnX);
vm.feedRecordButton(XrInputState::BtnY);
vm.lock();
std::cout << "\n*** ALL VAULT MANAGER UNIT TESTS PASSED PERFECTLY! ***" << std::endl;
return 0;
}
Regular → Executable
View File
File mode changed.
Regular → Executable
View File
File mode changed.
Regular → Executable
View File
File mode changed.
Regular → Executable
View File
File mode changed.
+559
View File
@@ -0,0 +1,559 @@
#!/bin/sh
# Pixel VR Player installer for the Valve Steam Frame.
#
# Download-and-run (no other files needed):
# curl -fsSL https://raw.githubusercontent.com/Pixelplanet/Pixel-VR-Player/main/tools/install.sh | sh
#
# Or from an extracted release tarball:
# ./install.sh
#
# Options:
# --dir DIR install directory (default: ~/PixelVRPlayer)
# --version vX.Y.Z release to install (default: the latest release)
# --no-steam do not add the Non-Steam Game shortcut
# --restart-steam close Steam before registering, then start it again
# --uninstall remove the app and its Steam shortcut
# --force install even if the CPU is not aarch64
# -h, --help show this help
#
# Settings (~/.config/pixelvr) and the thumbnail cache (~/.cache/pixelvr) live
# outside the install directory, so reinstalling or upgrading never loses them.
set -eu
REPO="Pixelplanet/Pixel-VR-Player"
ASSET="pixelvr-linux-arm64.tar.gz"
APP_NAME="Pixel VR Player"
INSTALL_DIR="${PIXELVR_INSTALL_DIR:-$HOME/PixelVRPlayer}"
VERSION=""
DO_STEAM=1
RESTART_STEAM=0
UNINSTALL=0
FORCE=0
if [ -t 1 ]; then
C_INFO=$(printf '\0033[36m')
C_OK=$(printf '\0033[32m')
C_WARN=$(printf '\0033[33m')
C_ERR=$(printf '\0033[31m')
C_OFF=$(printf '\0033[0m')
else
C_INFO=""; C_OK=""; C_WARN=""; C_ERR=""; C_OFF=""
fi
info() { printf '%s==>%s %s\n' "$C_INFO" "$C_OFF" "$*"; }
ok() { printf '%s ok%s %s\n' "$C_OK" "$C_OFF" "$*"; }
warn() { printf '%swarn%s %s\n' "$C_WARN" "$C_OFF" "$*" >&2; }
die() { printf '%serror%s %s\n' "$C_ERR" "$C_OFF" "$*" >&2; exit 1; }
usage() {
cat <<'USAGE'
Pixel VR Player installer for the Valve Steam Frame.
Usage:
curl -fsSL https://raw.githubusercontent.com/Pixelplanet/Pixel-VR-Player/main/tools/install.sh | sh
./install.sh [options]
Options:
--dir DIR install directory (default: ~/PixelVRPlayer)
--version vX.Y.Z release to install (default: the latest release)
--no-steam do not add the Non-Steam Game shortcut
--restart-steam close Steam before registering, then start it again
--uninstall remove the app and its Steam shortcut
--force install even if the CPU is not aarch64
-h, --help show this help
Settings in ~/.config/pixelvr and cached thumbnails in ~/.cache/pixelvr are
never touched by install, upgrade or uninstall.
USAGE
}
while [ $# -gt 0 ]; do
case "$1" in
--dir)
[ $# -ge 2 ] || die "--dir needs a value"
case "$2" in
"~/"*) INSTALL_DIR="$HOME/${2#\~/}" ;;
*) INSTALL_DIR="$2" ;;
esac
shift ;;
--dir=*) INSTALL_DIR="${1#--dir=}" ; case "$INSTALL_DIR" in "~/"*) INSTALL_DIR="$HOME/${INSTALL_DIR#\~/}" ;; esac ;;
--version)
[ $# -ge 2 ] || die "--version needs a value"
VERSION="$2"; shift ;;
--version=*) VERSION="${1#--version=}" ;;
--no-steam) DO_STEAM=0 ;;
--restart-steam) RESTART_STEAM=1 ;;
--uninstall) UNINSTALL=1 ;;
--force) FORCE=1 ;;
-h|--help) usage; exit 0 ;;
*) die "unknown option: $1 (try --help)" ;;
esac
shift
done
case "$INSTALL_DIR" in
""|"/"|".") die "refusing to use '$INSTALL_DIR' as install directory" ;;
esac
# ---------------------------------------------------------------------------
# Steam shortcut registration (non-Steam game in the library)
# ---------------------------------------------------------------------------
steam_running() {
command -v pgrep >/dev/null 2>&1 && pgrep -x steam >/dev/null 2>&1
}
find_steam_userdata() {
steam_root=""
for candidate in "$HOME/.steam/steam" "$HOME/.local/share/Steam" "$HOME/.steam/root"; do
if [ -d "$candidate/userdata" ]; then
steam_root="$candidate"
break
fi
done
[ -n "$steam_root" ] || return 1
vdf=""
newest=0
for dir in "$steam_root"/userdata/*; do
case "${dir##*/}" in ''|*[!0-9]*) continue ;; esac
file="$dir/config/shortcuts.vdf"
[ -f "$file" ] || continue
stamp=$(stat -c %Y "$file" 2>/dev/null || stat -f %m "$file" 2>/dev/null || echo 0)
if [ -z "$vdf" ] || [ "$stamp" -ge "$newest" ]; then
vdf="$file"
newest="$stamp"
fi
done
if [ -z "$vdf" ]; then
# No shortcuts.vdf yet: create it for the most recently used account.
for dir in "$steam_root"/userdata/*; do
case "${dir##*/}" in ''|*[!0-9]*) continue ;; esac
[ -d "$dir/config" ] || continue
stamp=$(stat -c %Y "$dir/config" 2>/dev/null || stat -f %m "$dir/config" 2>/dev/null || echo 0)
if [ -z "$vdf" ] || [ "$stamp" -ge "$newest" ]; then
vdf="$dir/config/shortcuts.vdf"
newest="$stamp"
fi
done
fi
[ -n "$vdf" ] || return 1
printf '%s\n' "$vdf"
}
# Binary KeyValues editor for shortcuts.vdf. Arguments:
# <add|remove> <vdf path> <app name> <exe> <start dir>
run_vdf_helper() {
python3 - "$@" <<'PYEOF'
import os
import struct
import sys
import zlib
OBJ, STR, INT, U64, END = 0x00, 0x01, 0x02, 0x07, 0x08
class Unsupported(Exception):
pass
def read_cstr(buf, pos):
end = buf.find(b"\0", pos)
if end < 0:
raise ValueError("unterminated string")
return buf[pos:end].decode("utf-8", "surrogateescape"), end + 1
def parse_obj(buf, pos):
entries = {}
while True:
if pos >= len(buf):
raise ValueError("truncated object")
kind = buf[pos]
if kind in (END, 0x0B):
return entries, pos + 1
key, pos = read_cstr(buf, pos + 1)
if kind == OBJ:
value, pos = parse_obj(buf, pos)
elif kind == STR:
value, pos = read_cstr(buf, pos)
elif kind == INT:
value = struct.unpack_from("<i", buf, pos)[0]
pos += 4
elif kind == U64:
value = struct.unpack_from("<Q", buf, pos)[0]
pos += 8
else:
raise Unsupported("unsupported type 0x%02x at key %r" % (kind, key))
entries[key] = [kind, value]
return entries, pos
def parse_file(buf):
if not buf:
return {"shortcuts": [OBJ, {}]}
if buf[0] != OBJ:
raise Unsupported("not a binary KeyValues file")
key, pos = read_cstr(buf, 1)
value, _ = parse_obj(buf, pos)
return {key: [OBJ, value]}
def dump(entries):
out = bytearray()
for key, (kind, value) in entries.items():
kb = key.encode("utf-8", "surrogateescape")
if kind == OBJ:
out += bytes([OBJ]) + kb + b"\0" + dump(value) + bytes([END])
elif kind == STR:
out += bytes([STR]) + kb + b"\0" + value.encode("utf-8", "surrogateescape") + b"\0"
elif kind == INT:
out += bytes([INT]) + kb + b"\0" + struct.pack("<i", value)
elif kind == U64:
out += bytes([U64]) + kb + b"\0" + struct.pack("<Q", value)
return bytes(out)
def app_id(exe, name):
# Steam derives the shortcut id from the quoted exe path plus the name.
return (zlib.crc32((exe + name).encode("utf-8")) | 0x80000000) & 0xFFFFFFFF
def to_i32(value):
return value - 0x100000000 if value >= 0x80000000 else value
def find(shortcuts, name, exe):
for key in shortcuts:
kind, entry = shortcuts[key]
if kind != OBJ:
continue
stored_exe = entry.get("Exe", [STR, ""])[1].strip('"')
stored_name = entry.get("AppName", [STR, ""])[1]
if (exe and stored_exe == exe) or stored_name == name:
return key, entry
return None, None
def main():
mode, path, name = sys.argv[1], sys.argv[2], sys.argv[3]
exe = sys.argv[4] if len(sys.argv) > 4 else ""
start_dir = sys.argv[5] if len(sys.argv) > 5 else ""
buf = b""
if os.path.exists(path):
with open(path, "rb") as handle:
buf = handle.read()
root = parse_file(buf)
root_key = next((k for k in root if k.lower() == "shortcuts"), None)
if root_key is None:
root_key = "shortcuts"
root[root_key] = [OBJ, {}]
shortcuts = root[root_key][1]
key, entry = find(shortcuts, name, exe)
if mode == "remove":
if entry is None:
print("no matching shortcut, nothing to remove")
return 0
del shortcuts[key]
renumbered = {}
ordered = sorted(shortcuts, key=lambda k: int(k) if k.isdigit() else 1 << 30)
for index, old in enumerate(ordered):
renumbered[str(index)] = shortcuts[old]
root[root_key][1] = renumbered
print("removed '%s'" % name)
else:
quoted_exe = '"%s"' % exe
created = entry is None
if created:
index = 0
for existing in shortcuts:
if existing.isdigit() and int(existing) >= index:
index = int(existing) + 1
entry = {}
shortcuts[str(index)] = [OBJ, entry]
if "appid" not in entry:
entry["appid"] = [INT, to_i32(app_id(quoted_exe, name))]
for field, value in (
("AppName", [STR, name]),
("Exe", [STR, quoted_exe]),
("StartDir", [STR, '"%s"' % start_dir]),
("icon", [STR, ""]),
("ShortcutPath", [STR, ""]),
("LaunchOptions", [STR, ""]),
("IsHidden", [INT, 0]),
("AllowDesktopConfig", [INT, 1]),
("AllowOverlay", [INT, 1]),
("OpenVR", [INT, 1]),
("Devkit", [INT, 0]),
("DevkitGameID", [STR, ""]),
("DevkitOverrideAppID", [INT, 0]),
("LastPlayTime", [INT, 0]),
("FlatpakAppID", [STR, ""]),
):
entry[field] = value
entry.setdefault("tags", [OBJ, {}])
print("%s '%s' (%d shortcut(s) in the library)" % (
"added" if created else "updated", name, len(shortcuts)))
data = dump(root) + bytes([END])
tmp = path + ".tmp"
with open(tmp, "wb") as handle:
handle.write(data)
if os.path.exists(path):
os.chmod(tmp, os.stat(path).st_mode & 0o777)
os.replace(tmp, path)
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except Unsupported as exc:
sys.stderr.write("cannot edit shortcuts.vdf: %s\n" % exc)
sys.exit(3)
except Exception as exc: # noqa: BLE001 - surface any failure to the shell
sys.stderr.write("cannot edit shortcuts.vdf: %s\n" % exc)
sys.exit(1)
PYEOF
}
register_steam_shortcut() {
vdf=$(find_steam_userdata) || {
warn "Steam userdata not found - is Steam installed and logged in at least once?"
return 1
}
if ! command -v python3 >/dev/null 2>&1; then
warn "python3 not found - skipping Steam registration"
return 1
fi
steam_was_running=0
if steam_running; then
steam_was_running=1
if [ "$RESTART_STEAM" -eq 1 ]; then
info "Closing Steam so the new shortcut is kept..."
steam -shutdown >/dev/null 2>&1 || true
waited=0
while steam_running && [ "$waited" -lt 30 ]; do
sleep 1
waited=$((waited + 1))
done
if steam_running; then
warn "Steam did not close in time"
fi
else
warn "Steam is running - restart Steam afterwards to see '$APP_NAME' in the library"
fi
fi
if [ -f "$vdf" ]; then
backup="$vdf.bak.$(date +%Y%m%d%H%M%S)"
cp "$vdf" "$backup"
else
backup=""
fi
if ! run_vdf_helper add "$vdf" "$APP_NAME" "$INSTALL_DIR/run.sh" "$INSTALL_DIR"; then
[ -n "$backup" ] && [ -f "$backup" ] && cp "$backup" "$vdf"
return 1
fi
[ -n "$backup" ] && ok "shortcuts.vdf backed up to ${backup}"
if [ "$RESTART_STEAM" -eq 1 ] && [ "$steam_was_running" -eq 1 ] && ! steam_running; then
info "Starting Steam again..."
if command -v steam >/dev/null 2>&1; then
nohup steam >/dev/null 2>&1 &
fi
fi
STEAM_REGISTERED=1
}
unregister_steam_shortcut() {
vdf=$(find_steam_userdata) || return 1
[ -f "$vdf" ] || return 1
command -v python3 >/dev/null 2>&1 || return 1
run_vdf_helper remove "$vdf" "$APP_NAME" "" "" || return 1
}
# ---------------------------------------------------------------------------
# Uninstall
# ---------------------------------------------------------------------------
if [ "$UNINSTALL" -eq 1 ]; then
info "Removing Pixel VR Player from $INSTALL_DIR"
if [ "$DO_STEAM" -eq 1 ]; then
if unregister_steam_shortcut; then
ok "removed the Steam shortcut"
else
warn "could not remove the Steam shortcut; delete it in Steam manually"
fi
fi
rm -rf "$INSTALL_DIR"
ok "removed $INSTALL_DIR"
printf '\nSettings (%s/.config/pixelvr) and cached thumbnails were kept.\n' "$HOME"
printf 'Delete them too with: rm -rf ~/.config/pixelvr ~/.cache/pixelvr\n'
exit 0
fi
# ---------------------------------------------------------------------------
# Platform checks
# ---------------------------------------------------------------------------
machine=$(uname -m)
case "$machine" in
aarch64|arm64) ok "CPU: $machine" ;;
*)
if [ "$FORCE" -eq 0 ]; then
die "this release is built for the Steam Frame (aarch64), not '$machine'.
Build from source for other machines, or pass --force."
fi
warn "installing an aarch64 build on '$machine' (--force)" ;;
esac
# ---------------------------------------------------------------------------
# Fetch (reused by the local and download paths)
# ---------------------------------------------------------------------------
fetch() { # <url> <dest>
if command -v curl >/dev/null 2>&1; then
curl -fsSL "$1" -o "$2"
elif command -v wget >/dev/null 2>&1; then
wget -qO "$2" "$1"
else
die "need curl or wget to download the release"
fi
}
script_dir=""
if [ -f "$0" ]; then
script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" 2>/dev/null && pwd) || script_dir=""
fi
tmp=""
cleanup() { [ -z "$tmp" ] || rm -rf "$tmp"; }
trap cleanup EXIT INT TERM
if [ -n "$script_dir" ] && [ -f "$script_dir/pixelvr" ] && [ -d "$script_dir/shaders" ]; then
info "Installing from $script_dir"
srcdir="$script_dir"
if [ -f "$script_dir/VERSION" ]; then
VERSION="$(cat "$script_dir/VERSION")"
fi
if [ -n "$VERSION" ]; then
version_label="$VERSION"
else
version_label="local build"
fi
else
case "$VERSION" in
"") base="https://github.com/$REPO/releases/latest/download"
version_label="latest" ;;
v*) base="https://github.com/$REPO/releases/download/$VERSION"
version_label="$VERSION" ;;
*) VERSION="v$VERSION"
base="https://github.com/$REPO/releases/download/$VERSION"
version_label="$VERSION" ;;
esac
tmp=$(mktemp -d) || die "cannot create a temporary directory"
info "Downloading $version_label for aarch64"
fetch "$base/$ASSET" "$tmp/$ASSET" || die "download failed: $base/$ASSET"
if fetch "$base/$ASSET.sha256" "$tmp/$ASSET.sha256" 2>/dev/null; then
expected=$(awk 'NR == 1 { print $1 }' "$tmp/$ASSET.sha256")
if command -v sha256sum >/dev/null 2>&1; then
actual=$(sha256sum "$tmp/$ASSET" | awk '{ print $1 }')
elif command -v shasum >/dev/null 2>&1; then
actual=$(shasum -a 256 "$tmp/$ASSET" | awk '{ print $1 }')
else
actual=""
fi
if [ -n "$actual" ]; then
[ "$actual" = "$expected" ] || die "checksum mismatch for $ASSET"
ok "checksum verified"
fi
else
warn "no checksum published for this release"
fi
mkdir -p "$tmp/unpacked"
tar -xzf "$tmp/$ASSET" -C "$tmp/unpacked" || die "cannot unpack $ASSET"
srcdir="$tmp/unpacked/PixelVRPlayer"
[ -x "$srcdir/pixelvr" ] || [ -f "$srcdir/pixelvr" ] || die "unexpected archive layout"
fi
# ---------------------------------------------------------------------------
# Install
# ---------------------------------------------------------------------------
info "Installing to $INSTALL_DIR"
mkdir -p "$INSTALL_DIR/shaders"
rm -f "$INSTALL_DIR/pixelvr"
cp "$srcdir/pixelvr" "$INSTALL_DIR/pixelvr"
chmod 0755 "$INSTALL_DIR/pixelvr"
rm -f "$INSTALL_DIR/shaders/"*.spv
cp "$srcdir/shaders/"*.spv "$INSTALL_DIR/shaders/"
cp "$srcdir/run.sh" "$INSTALL_DIR/run.sh"
chmod 0755 "$INSTALL_DIR/run.sh"
INSTALLED_SCRIPT=0
if [ -f "$srcdir/install.sh" ]; then
cp "$srcdir/install.sh" "$INSTALL_DIR/install.sh"
chmod 0755 "$INSTALL_DIR/install.sh"
INSTALLED_SCRIPT=1
elif [ -n "$script_dir" ] && [ -f "$script_dir/install.sh" ]; then
cp "$script_dir/install.sh" "$INSTALL_DIR/install.sh"
chmod 0755 "$INSTALL_DIR/install.sh"
INSTALLED_SCRIPT=1
fi
if [ -f "$srcdir/VERSION" ]; then
cp "$srcdir/VERSION" "$INSTALL_DIR/VERSION"
elif [ -n "$VERSION" ]; then
printf '%s\n' "$VERSION" > "$INSTALL_DIR/VERSION"
fi
ok "$(ls -1 "$INSTALL_DIR/shaders" | wc -l | tr -d ' ') shaders, $(du -h "$INSTALL_DIR/pixelvr" 2>/dev/null | cut -f1) binary"
missing_libs=""
if command -v ldd >/dev/null 2>&1; then
missing_libs=$(ldd "$INSTALL_DIR/pixelvr" 2>/dev/null | awk '/not found/ { print $1 }' \
| sort -u | tr '\n' ' ' || true)
fi
if [ -n "$missing_libs" ]; then
warn "missing shared libraries: $missing_libs"
warn "if these are libav* libraries, the system FFmpeg is too old"
fi
if [ ! -f /opt/steamvr/steamxr_linuxarm64.json ]; then
warn "SteamVR not found - install it from Steam before launching"
fi
# ---------------------------------------------------------------------------
# Steam library entry
# ---------------------------------------------------------------------------
STEAM_REGISTERED=0
if [ "$DO_STEAM" -eq 1 ]; then
info "Adding '$APP_NAME' to the Steam library"
if register_steam_shortcut; then
ok "Steam library entry ready"
else
warn "add $INSTALL_DIR/run.sh as a Non-Steam Game manually"
fi
fi
# ---------------------------------------------------------------------------
# Summary
# ---------------------------------------------------------------------------
printf '\n%s%s installed%s\n' "$C_OK" "$APP_NAME" "$C_OFF"
printf ' Version : %s\n' "$version_label"
printf ' Install dir : %s\n' "$INSTALL_DIR"
if [ "$DO_STEAM" -eq 1 ] && [ "$STEAM_REGISTERED" -eq 1 ]; then
printf ' Steam entry : Non-Steam Game "%s"\n' "$APP_NAME"
fi
printf '\n Launch now : %s/run.sh\n' "$INSTALL_DIR"
printf ' From Steam : Library > Non-Steam > %s\n' "$APP_NAME"
printf ' Play a clip : %s/run.sh /path/to/clip.mp4\n' "$INSTALL_DIR"
printf ' Logs : ~/pixelvr-run.log\n'
printf ' Update : run this script again (settings and cache are kept)\n'
if [ "$INSTALLED_SCRIPT" -eq 1 ]; then
printf ' Remove : %s/install.sh --uninstall\n\n' "$INSTALL_DIR"
else
printf ' Remove : rerun this script with --uninstall\n\n'
fi
Regular → Executable
View File
File mode changed.
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env bash
# Assemble the Steam Frame release tarball for a finished ARM64 build.
#
# Contents (extracted to ~/PixelVRPlayer):
# PixelVRPlayer/pixelvr self-contained binary (static OpenXR loader)
# PixelVRPlayer/run.sh launcher (logs to ~/pixelvr-run.log)
# PixelVRPlayer/install.sh one-command installer / Steam registration
# PixelVRPlayer/shaders/*.spv SPIR-V shaders
# PixelVRPlayer/VERSION release tag (when given)
#
# ./tools/package-release.sh [build-dir] [out-tar] [version]
#
# Defaults: build -> pixelvr-linux-arm64.tar.gz
set -euo pipefail
cd "$(dirname "$0")/.."
BUILD_DIR="${1:-build}"
OUT_TAR="${2:-pixelvr-linux-arm64.tar.gz}"
VERSION="${3:-}"
bin="${BUILD_DIR}/bin/pixelvr"
if [[ ! -f "${bin}" ]]; then
echo "error: ${bin} not found. Build first: ./tools/build.sh" >&2
exit 1
fi
if [[ -z "$(find "${BUILD_DIR}/shaders" -maxdepth 1 -name '*.spv' -print -quit)" ]]; then
echo "error: no shaders in ${BUILD_DIR}/shaders" >&2
exit 1
fi
stage="$(mktemp -d)"
trap 'rm -rf "${stage}"' EXIT
mkdir -p "${stage}/PixelVRPlayer/shaders"
cp "${bin}" "${stage}/PixelVRPlayer/pixelvr"
cp "${BUILD_DIR}/shaders/"*.spv "${stage}/PixelVRPlayer/shaders/"
cp tools/run.sh "${stage}/PixelVRPlayer/run.sh"
cp tools/install.sh "${stage}/PixelVRPlayer/install.sh"
if [[ -n "${VERSION}" ]]; then
printf '%s\n' "${VERSION}" > "${stage}/PixelVRPlayer/VERSION"
fi
chmod +x "${stage}/PixelVRPlayer/pixelvr" \
"${stage}/PixelVRPlayer/run.sh" \
"${stage}/PixelVRPlayer/install.sh"
rm -f "${OUT_TAR}"
tar -C "${stage}" -czf "${OUT_TAR}" PixelVRPlayer
echo "Packaged ${OUT_TAR} ($(du -h "${OUT_TAR}" | cut -f1)):"
tar -tzf "${OUT_TAR}"
Regular → Executable
View File
File mode changed.
Executable
+19
View File
@@ -0,0 +1,19 @@
#!/bin/sh
# Pixel VR Player launcher (Steam Frame). Logs to ~/pixelvr-run.log.
#
# This is the launcher shipped inside the release tarball as
# PixelVRPlayer/run.sh. It runs the app directly on the SteamOS host.
set -eu
here=$(cd "$(dirname "$0")" && pwd)
export PIXELVR_SHADER_DIR="$here/shaders"
export PIXELVR_LOG=debug
# Optional: use a locally built patched FFmpeg for zero-copy dma-buf decode.
if [ -d "$HOME/ffbuild/build/libavcodec" ]; then
export LD_LIBRARY_PATH="$HOME/ffbuild/build/libavcodec:$HOME/ffbuild/build/libavutil:$HOME/ffbuild/build/libswresample${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
export PIXELVR_DRM_PRIME=1
fi
exec "$here/pixelvr" "$@" >>"$HOME/pixelvr-run.log" 2>&1
Regular → Executable
View File
File mode changed.