Compare commits

..
8 Commits
Author SHA1 Message Date
spoopyghosty0 ba68dc76c8 Self-update for the app and the CLI
FramePort finds new GitHub releases by itself and updates in one click: sidebar card + Library bar, a dialog with
the release notes, "Update and restart" (download, SHA256SUMS check, Windows signer check, swap script, relaunch),
optional automatic installs at the next start. CLI: --version, `frameport update [--check] [--yes]` and a
once-a-day hint. One version source (_version.py); releases also ship the CLI wheel and "What's new" from the
annotated tag; CI runs an update smoke test with each OS's archive.
2026-10-01 22:59:56 -04:00
spoopyghosty0 22205d17a4 One REPO_URL for the project link; project identity and no-trailer rule in CLAUDE.md 2026-10-01 21:53:06 -04:00
spoopyghosty0 2e5fcd9860 360° layers, per-game session fixes, video players, library tools
FrameBridge (all new behaviour per game, off by default; hooks installed only when on):
- equirect_emul (GLES only): 360° equirect/equirect2 layers, which the Frame runtime
  lacks, are drawn into one adapter projection layer by a worker thread with a shared
  EGL context. Each 360° image becomes a cube map only when it changes; the view is
  drawn early (from the app's xrLocateViews) with the frame's exact views. Write-once
  360° picture swapchains are served by the adapter (frees runtime swapchain slots).
  Learned: the Frame draws quad layers above all projection layers, and doesn't
  reproject a projection layer from its own pose.
- session_fixes: layer_debug diagnostics, stable_local, focus_hold, aim correction,
  refresh_rate.
- Agent v26: link_media (files sent to shared folders also appear in a player's own
  folder), app media folder detection, launcher creates Android/data/<pkg>/{files,cache}.

App: "Add videos" for players, Update all, Rescan folders (only new games), Install
anyway for "Can't run" games, launch-test toggle, triage `unless`, generic source hints.

Catalog: 4XVR, NEX Player, Deadpool VR (working, owner-confirmed).
2026-10-01 14:19:08 -04:00
spoopyghosty0 428e8ffe05 Quest binary fixes, PC VR launch modes + SteamVR tuning, file sending, GUI scaling
Quest (Frame):
- frame.swapchain_limit (default on): overport's dispatcher aborted on swapchains
  > 4096 px (4XVR's 7680x3840 theatre textures); guard raised to 16384.
- frame.vk_sanitize (default on, Unreal): Vulkan shim (native/vkshim) that drops
  invalid render-pass pNext pointers; Lepton's Fossilize layer crashed Deadpool VR on them.
- FrameBridge: cylinder layers (curved menus / movie screens) shown as flat quad
  strips (setting cylinder_strips). Equirect (360°) layers still can't be shown.
- Launch tests read Lepton's crash logcat (agent v24); triage signatures for both crashes.
- Send files to Lepton apps (frameport frame send/storage, GUI "Send files"):
  ~/Videos, ~/Downloads, ~/Documents = /sdcard/Movies, Download, Documents in every app.

PC VR:
- Launch modes from the game files (repack with bundled Revive -> run directly,
  dual-API builds -> launch args, Oculus-only -> Revive); patches pcvr.repack_launcher,
  pcvr.launch_args; Platform SDK games routed to the PC.
- pcvr.steamvr_tuning (default on): reads SteamVR's session summary (dropped frames
  + compositor timeouts, fpsVR if installed) and sets per-app refresh rate / motion
  smoothing via fp_vrsettings.exe (OpenVR IVRSettings).

GUI: upload speed / ETA, UI scale (auto from Windows DPI under WSL, Settings ->
Appearance), fixed grey box in Problems & feedback.
2026-09-30 21:51:37 -04:00
spoopyghosty0 dfb4fc4ffd Share working configs and diagnostics bundles via GitHub issues
- "Share working config…" (game menu, `frameport share-recipe`): saves the recipe as known-good and opens a
  prefilled working-config issue form; labelling it `catalog-accepted` runs catalog-from-issue.yml, which
  validates the YAML (scripts/catalog_from_issue.py) and opens a PR adding catalog/games/<pkg>.yaml
- "Collect logs" / "Report a problem…" (game menu, Settings, failure pop-up, `frameport diag collect|report`):
  redacted diagnostics zip (app + job logs, library entry, recipe, launch logs + re-triage, APK/ELF/PE listings
  instead of game files, Frame launcher/settings/Lepton/logcat/XRService logs via agent v21 `collect_diag`) and
  a prefilled bug-report issue to attach it to; `frameport diag inspect <zip>` re-triages a bundle offline
- diag/redact.py scrubs IPs, MACs, host/user names, home dirs, Steam ids, data and dump folders
- App log (<data>/logs/app.log) and saved GUI job logs (<data>/logs/jobs/)
- catalog.entry_from_library shared by "Save as known-good" and sharing; docs/DIAGNOSTICS.md
2026-09-30 14:14:00 -04:00
spoopyghosty0 fc4aa9c8e5 Steam Frame controller models via XR_FB_render_model (adapter controller_models)
Games that ask the runtime for controller models (Meta's runtime controller
models) get the Steam Frame controllers instead of Quest Touch ones:

- adapter (render_model.c): emulates XR_FB_render_model when the runtime lacks
  it and serves files/framebridge/controller_{left,right}.glb. Off by default;
  suggested for games declaring the RENDER_MODEL permission/feature (none of
  the 34 catalog games do).
- agent v20: converts the Frame's own SteamVR render models (frame_controller
  driver, OBJ+PNG, openxr_grip -> grip space) to glb on the device at install /
  set_settings; Valve's models never leave the Frame. `frameport frame
  controller-models` lists what it finds.
- xrshim: overport's dispatcher only forwards functions in its own table
  ("Unknown proc addr"), so OVRPlugin's dlopen("libopenxr_loader.so") string
  is pointed at libframe_xrshim.so, which serves the emulated functions and
  forwards everything else to overport. Only added with controller_models=1;
  other builds differ from known-good only in the adapter binary.

Verified on the device with Toy Master: models converted, adapter emulation on,
all three render-model functions resolved through FrameBridge; launches match
the known-good build. Not yet seen rendering in a game (none requests a model).
2026-09-30 12:58:52 -04:00
spoopyghosty0 1d83eae3ed libovr_redirect: also place next to OVRPlugin.dll (agent v19)
The Oculus SDK's LibOVRRT search differs by engine: monolithic builds (Lone Echo)
use the standard DLL search (exe dir), but Unreal's OVRPlugin shim searches its
own module dir. set_libovr_redirect now symlinks LibOVRRT{64,32}_1.dll in the exe
dir AND next to every OVRPlugin.dll in the game tree.

Verified on-device: with the redirect, Lone Echo now loads Revive's runtime and
reaches Oculus API init (-3021) instead of "Unable to load LibOVRRT DLL" — the
substitution works; the -3021 is the downstream signature/runtime-init stage,
which this redirect deliberately does not touch (no signature bypass).

135 tests pass.
2026-09-30 10:38:52 -04:00
spoopyghosty0 c1c33d8482 LibOVRRT LoadLibrary redirect (pcvr.libovr_redirect) — runtime substitution only
On the Frame, place Revive's runtime where an Oculus game's SDK looks for it, so
the game can load a VR runtime — the filesystem equivalent of Revive's LoadLibrary
redirect, without the inline hooking that fails under Proton-arm64 (ARM64EC).

- agent v18 set_libovr_redirect: symlinks LibOVRRT{64,32}_1.dll in the exe dir to
  Revive's LibReviveXR runtime (kept in revive/ so its deps still resolve); only
  ever creates/removes its own symlink, never a real game-shipped DLL.
- patch pcvr.libovr_redirect (requires pcvr.revive, on by default for Oculus Rift
  games, ignored on PC); installer + deployment.json wiring; migration
  rift_libovr_redirect for existing entries.

This is pure runtime substitution. It does NOT touch the game's Oculus runtime
signature check: a build that verifies LibOVRRT's signature still rejects Revive's
unsigned runtime (-3021). It only helps builds that don't verify it, and gets the
rest from "can't load runtime" (-3001) to the (intact) signature check.

135 tests pass. Not yet demonstrated on-device (Frame was off).
2026-09-30 10:21:52 -04:00
143 changed files with 8783 additions and 399 deletions

No files matched your search

+44
View File
@@ -0,0 +1,44 @@
name: Problem report
description: A game or FramePort doesn't work (FramePort → "Report a problem…" fills this in and saves a diagnostics zip).
title: "[Problem] "
labels: ["bug"]
body:
- type: markdown
attributes:
value: |
Please attach the **diagnostics zip** FramePort saved (drag it into the "Diagnostics" box below). It contains
logs, the recipe and device details with personal data removed — no game files. Without the app, it can be
read with `frameport diag inspect <zip>`.
- type: input
id: game
attributes:
label: Game
description: Title — package id (version, engine / XR API); empty for app problems
- type: textarea
id: description
attributes:
label: What happens?
description: What you did, what you expected, what you saw (in the headset, if it started)
validations:
required: true
- type: textarea
id: findings
attributes:
label: Launch test / triage
description: Filled in by FramePort from the last launch test
- type: textarea
id: recipe
attributes:
label: Recipe
render: yaml
- type: textarea
id: environment
attributes:
label: Environment
- type: textarea
id: logs
attributes:
label: Diagnostics
description: Drag the FramePort-diag-*.zip here (max 25 MB)
validations:
required: true
+1
View File
@@ -0,0 +1 @@
blank_issues_enabled: true
+49
View File
@@ -0,0 +1,49 @@
name: Working configuration
description: Submit a recipe that works on the Steam Frame (FramePort → game menu → "Share working config…" fills this in).
title: "[Working config] "
labels: ["working-config"]
body:
- type: markdown
attributes:
value: |
Thanks! A maintainer reviews the recipe; once it's labelled `catalog-accepted`, a pull request adding it to
`catalog/games/` is opened automatically. Please don't paste game files or links to them.
- type: input
id: game
attributes:
label: Game
description: Title — package id (platform, version, engine / XR API)
validations:
required: true
- type: input
id: result
attributes:
label: Result
description: works or issues (+ the last headless launch test)
validations:
required: true
- type: textarea
id: recipe
attributes:
label: Recipe
description: The catalog entry (catalog/games/<package>.yaml). Don't edit the package line.
render: yaml
validations:
required: true
- type: textarea
id: environment
attributes:
label: Environment
description: FramePort, tool and SteamOS versions
- type: textarea
id: notes
attributes:
label: Notes
description: What you checked in the headset, known issues, anything unusual
- type: checkboxes
id: confirm
attributes:
label: Confirmation
options:
- label: I played the game in the headset with this recipe (headless launch tests can't check the picture).
required: true
+15 -1
View File
@@ -91,6 +91,9 @@ jobs:
- name: Package (Linux)
if: runner.os == 'Linux'
run: tar czf ${{ matrix.archive }} -C dist --transform 's,^linux,FramePort,' linux
# self-update with this archive: unpack, verify the layout (+ the signer on Windows), run the real swap script
- name: Update smoke test
run: uv run python scripts/update_smoke.py ${{ matrix.archive }}
- name: Attest build provenance
if: github.event_name != 'pull_request'
uses: actions/attest-build-provenance@v4
@@ -109,10 +112,13 @@ jobs:
contents: write
steps:
- uses: actions/checkout@v7
- uses: astral-sh/setup-uv@v10.2.0
- uses: actions/download-artifact@v8
with:
path: out
merge-multiple: true
- name: Wheel (CLI install via uv tool / pipx / pip, and its self-update)
run: uv build --wheel -o out && ls out
- name: Checksums
run: cd out && sha256sum * > SHA256SUMS.txt && cat SHA256SUMS.txt
- name: Publish release
@@ -121,7 +127,15 @@ jobs:
run: |
tag="${GITHUB_REF_NAME}"
notes=$(mktemp)
# "What's new" = the annotated tag's message (FramePort's update dialog shows it); checkout may leave the
# tag lightweight, so fetch the tag object itself
git fetch --force origin "refs/tags/${tag}:refs/tags/${tag}"
whatsnew=$(git tag -l --format='%(contents:body)' "$tag")
[ -n "$whatsnew" ] || whatsnew=$(git tag -l --format='%(contents:subject)' "$tag")
{ echo "FramePort ${tag}: Windows (x64), macOS (Apple Silicon) and Linux (x64)."; echo;
sed -n '/^## First launch/,$p' docs/INSTALL.md; } > "$notes"
if [ -n "$whatsnew" ] && [ "$(git cat-file -t "$tag")" = tag ]; then
echo "## What's new"; echo; echo "$whatsnew"; echo; fi
echo "Already have FramePort? It offers this update itself (Library → **Update now**, or \`frameport update\`)."
echo; sed -n '/^## First launch/,$p' docs/INSTALL.md; } > "$notes"
gh release delete "$tag" --yes 2>/dev/null || true
gh release create "$tag" out/* packaging/FramePort-selfsigned.cer --title "FramePort ${tag}" --notes-file "$notes"
+52
View File
@@ -0,0 +1,52 @@
name: catalog-from-issue
# A maintainer adds the label `catalog-accepted` to a "Working configuration" issue → this opens a PR adding the
# recipe to catalog/games/. Never runs for unlabelled issues; the issue text is only read by the validating script
# (never interpolated into shell commands). Needs Settings → Actions → "Allow GitHub Actions to create pull requests".
on:
issues:
types: [labeled]
permissions:
contents: write
pull-requests: write
issues: write
jobs:
recipe-pr:
if: github.event.label.name == 'catalog-accepted' && contains(github.event.issue.labels.*.name, 'working-config')
runs-on: ubuntu-latest
env:
GH_TOKEN: ${{ github.token }}
ISSUE: ${{ github.event.issue.number }}
steps:
- uses: actions/checkout@v7
- uses: astral-sh/setup-uv@v10.2.0
- run: uv sync
- name: Write the recipe
id: recipe
run: |
gh issue view "$ISSUE" --json body -q .body > "$RUNNER_TEMP/body.md"
uv run python scripts/catalog_from_issue.py "$RUNNER_TEMP/body.md" --issue "$ISSUE" | tee "$RUNNER_TEMP/out.txt"
grep '^package=' "$RUNNER_TEMP/out.txt" >> "$GITHUB_OUTPUT"
- name: Check it loads
env:
PKG: ${{ steps.recipe.outputs.package }}
run: uv run python -c "import os, sys; from frameport.recommend import catalog; sys.exit(os.environ['PKG'] not in catalog.load(refresh=True))"
- name: Open the pull request
env:
PKG: ${{ steps.recipe.outputs.package }}
run: |
branch="catalog/issue-$ISSUE"
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git checkout -b "$branch"
git add "catalog/games/$PKG.yaml"
git commit -m "catalog: $PKG (from #$ISSUE)"
git push --force origin "$branch"
if ! gh pr view "$branch" >/dev/null 2>&1; then
gh pr create --head "$branch" --title "catalog: $PKG" \
--body "Recipe submitted in #$ISSUE (working configuration). Closes #$ISSUE."
fi
- name: Report a failure on the issue
if: failure()
run: gh issue comment "$ISSUE" --body "Couldn't turn this into a catalog recipe — see the workflow run ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}."
+2
View File
@@ -11,3 +11,5 @@ parity-report.md
.pytest_cache/
native/.cache/
native/**/build/
# per-machine Claude Code settings (contain home paths)
.claude/settings.local.json
+106 -6
View File
@@ -54,7 +54,15 @@ Read `docs/PLAYBOOK.md` (symptom → fix) before debugging a game, and `docs/FRA
universal-in-Unreal `IVRSystem`/`VR_InitInternal` strings). `frame_native = (openxr or openvr) and not libovr` =
confidently runs on the Frame via wineopenxr (SteamVR), no Revive. Any LibOVR game → `needs_revive` → **PC only**
on the Frame (Revive's ARM64EC hooks don't work under Proton-arm64, and FramePort does **not** defeat the Oculus
runtime Authenticode signature check). Rick and Morty runs on the Frame via its catalog recipe (OpenVR, no Revive),
runtime Authenticode signature check). Patch `pcvr.libovr_redirect` (Frame, default on for Revive games, agent v19 `set_libovr_redirect`) symlinks Revive's
runtime as `LibOVRRT{64,32}_1.dll` in the game's exe dir **and next to every OVRPlugin.dll** (Unreal's OVR shim
searches its own module dir, not the exe dir) — the LoadLibrary redirect (pure runtime substitution), which
does NOT touch the game's runtime signature check (a checking build still fails at `-3021`; only non-checking builds
run). PoC verified on-device (2026-09-30): with the redirect, Lone Echo's Oculus SDK now loads Revive's runtime and
reaches Oculus API init (`-3021`) instead of failing to load a runtime at all — i.e. the substitution works; `-3021`
is the downstream signature/runtime-init stage the redirect doesn't touch. (OVRPlugin/Unreal builds use a more
restrictive LibOVRRT search; the next-to-OVRPlugin placement covers the common case.)
Rick and Morty runs on the Frame via its catalog recipe (OpenVR, no Revive),
not via static detection. PC installs default to Revive's **OpenVR** backend (`pcvr.revive_openvr` on) and
auto-start SteamVR on Play (`winhost.start_steamvr`); the Frame launcher always uses `/openxr`. UI (`game.py`
where()) states per-game where it runs; installing an Oculus game on the Frame shows a warning. Migration
@@ -97,10 +105,35 @@ Read `docs/PLAYBOOK.md` (symptom → fix) before debugging a game, and `docs/FRA
release matching the DLL build date, since Revive's version resources are stale) > portable copy unpacked from
ReviveInstaller.exe in pure Python; never replaces the user's install). Library ids `rift.<slug>`, entries have `kind: rift`.
- `parity.py` — rebuild catalog games from dumps and classify every APK entry difference vs known-good builds.
- `diag/` — user feedback without tokens (docs/DIAGNOSTICS.md): `redact.py` (every file/issue text: IPs, hosts,
home dirs, Steam ids, dump folders → placeholders), `bundle.py` (redacted diagnostics zip; agent v21
`collect_diag`; `frameport diag collect|inspect|report`), `issue.py` (prefilled GitHub issue-form links, ≤7.5k
chars). "Share working config" → `working-config.yml` issue → maintainer label `catalog-accepted` →
`catalog-from-issue.yml` workflow (`scripts/catalog_from_issue.py` validates) opens a catalog PR. App log:
`core/applog.py` (`<data>/logs/app.log`, finished GUI jobs in `<data>/logs/jobs/`).
- Self-update (docs/ARCHITECTURE.md "Self-update", docs/INSTALL.md "Updating"): `_version.py` = the only version
(`frameport.__version__`; pyproject reads it via hatch `dynamic`; app log, diagnostics, User-Agent, Settings use
it — never `importlib.metadata`, bundles have no dist-info). `updates.py` (no Flet): `check()` = GitHub
releases/latest via `cached_json("app-release.json")`, 6 h, skips drafts/prereleases and the user's skipped version
(settings `update.last_check`/`skipped`/`auto_check`/`auto_install`/`cli_hint`; env `FRAMEPORT_NO_UPDATE_CHECK`);
`install_kind()` = `bundle` (psutil exe path → FramePort.exe's folder / FramePort.app / FramePort/FramePort),
`source` (`.git` checkout: `git pull --ff-only` + `uv sync`, refused on a dirty tree), `wheel` (`uv tool`/pipx/pip
reinstall of the release's `.whl`); `prepare()` → `<data>/updates/<ver>/` (SHA256SUMS.txt required + checked,
layout checked, Windows: the new FramePort.exe must have the running exe's Authenticode signer when that one is
signed, `ready.json`); `apply()` writes + starts detached `apply.ps1`/`apply.sh` (wait for pid → Windows: copy over,
replaced files kept in `updates/<ver>/previous` because the zip has no top folder; macOS/Linux: mv to `.old` + swap,
rollback, `xattr -dr` quarantine → relaunch; `<data>/logs/update.log`). `ui/updater.py`: background check (10 s,
then 6 h), sidebar card (hidden control, toggled), Library bar (`library_bar`), notes dialog (`ft.Markdown`), job
`app-update` that restarts only when no other job is active, `apply_pending_at_start()` in `main()` for
"Install updates automatically"; Settings → Updates. CLI: `--version`, `frameport update [--check (exit 10)]
[--yes]`, once-a-day stderr hint read from the cache only (`refresh_cache()` in a daemon thread writes no
settings, to avoid read-modify-write races). `scripts/update_smoke.py <archive>` runs the real extract + swap script
(no relaunch) — CI runs it on all three OS with the archive it just built.
Verified: Linux + Windows (native, signer check) smoke with the v0.2.0 bundles; macOS only via the CI smoke.
- `agent/frameport_agent.py` — runs **on the Frame** (python3 stdlib only), JSON over SSH. Owns the install layout,
launch.sh template, Steam shortcuts (binary VDF), launch tests. Bump `AGENT_VERSION` when changing it.
- `bootstrap/bootstrap.sh` — one-time Frame setup served by the pairing server (sshd, app key, avahi service, Lepton).
- `catalog/games/<package>.yaml` — 34 recipes verified 2026-09-28; `catalog/triage.yaml` — log signatures → fixes.
- `catalog/games/<package>.yaml` — 34 recipes verified 2026-09-28 + Deadpool VR (2026-10-01, owner-confirmed); `catalog/triage.yaml` — log signatures → fixes.
- `native/` — sources of the prebuilt binaries in `artifacts/` (adapter, VrApi bridge patches, GL shim, stubs).
`native/build.py` rebuilds them with NDK r27c (downloaded on demand into `native/.cache`, git-ignored; uses
`-ffile-prefix-map` so no local paths get embedded; zip symlinks are restored as copies). Users never need the NDK.
@@ -124,10 +157,15 @@ Repo is on an NTFS drive (`core.fileMode=false`); line endings are LF (`.gitattr
- Device checks: `frameport test <pkg>` / `frameport parity-device --results <parity.json> --baseline <launch.txt>
[--test-only]`; the pre-FramePort baseline is `PATCHED/_known-good-2026-09-28/_frame-state/baseline-launch.txt`.
- GUI smoke test: `uv pip install flet-web playwright && playwright install chromium`, then
`FRAMEPORT_HOME=<test dir> python scripts/ui_smoke.py --out <dir> [--game <pkg>] [--frame steamos@<host>]` and look
`FRAMEPORT_HOME=<test dir> python scripts/ui_smoke.py --out <dir> [--game <pkg>] [--frame steamos@<host>] [--update]` (`--update` = fake release: banner, dialog, Settings → Updates) and look
at the PNGs. Flet 1.0 notes: `ft.run` must own the main thread; background work via `page.run_thread`; FilePicker is
awaited (`await ft.FilePicker().get_directory_path()`); dialogs via `page.show_dialog/pop_dialog`; running from
source needs `flet-desktop` (declared) and web mode needs `flet-web`.
- GUI scale: `theme.set_scale()` (library setting `ui.scale`, "auto" = halfway to Windows' AppliedDPI/96 under WSL (150 % → 125 %; full was too large), where the
Linux window gets no Windows scaling; Settings → Appearance; applied at start). Sizes go through tokens or
`T.px(n)`, Material defaults through the theme's text_theme; never hardcode a bare pixel number in ui/.
`scripts/ui_smoke.py --scale 1.5 --viewport 2560x1440` renders it. Flet draws a grey box for invalid layouts (e.g.
an `expand` child in a `wrap=True` Row).
- Stopping the GUI: `pkill -f` patterns match your own shell — use `pgrep -f "[b]in/frameport-gui|[f]let-desktop-light"`.
## Hard-won facts (don't re-learn these)
@@ -230,6 +268,56 @@ Output is deterministic (same input + runtime → same bytes), which is what mak
- VrApi-direct engines (CryEngine Climb 2, POTW) need the VrApi bridge; the bridge drops whole frames on unknown layer
types (→ black screen with audio).
**Steam Frame controller models (2026-09-30, not yet seen in a game):** adapter setting `controller_models`
(`native/adapter/render_model.c`) emulates XR_FB_render_model and serves `files/framebridge/controller_{left,right}.glb`;
agent v20 (`install_controller_models`, command `controller_models`) converts the Frame's SteamVR render models
(folder name matching "frame" + left/right, OBJ+PNG, `openxr_grip` component → grip space) at finalize/set_settings.
Valve's models are never committed or copied off the Frame. Only games that use Meta's runtime controller models
benefit (manifest `RENDER_MODEL` permission/feature → suggested); **none of the 34 catalog games do** (they ship their
own meshes: that would need per-game asset replacement). Model discovery and conversion
checked on the device 2026-09-30: `/opt/steamvr/drivers/frame_controller/resources/rendermodels/frame_controller_{left,right}`
(component OBJs in model space = the whole `<name>.obj`, one `_color.png` 2048² near-black, `openxr_grip` rotates about
X only; hidden-by-default components like `status` are skipped) → ~2 MB glb each, ~1 s. Not yet seen in a game (none
of the installed builds has the new adapter, and none requests runtime models), so whether Meta's SDK attaches runtime models at the grip pose is unverified.
**overport's dispatcher (`libopenxr_loader.so`) only forwards functions in its own table** (`overportOXR: Unknown
proc addr: …`), so adapter emulations of functions it doesn't know are unreachable. For XR_FB_render_model,
`native/xrshim` fills the gap: OVRPlugin's `dlopen("libopenxr_loader.so")` string is rewritten to the shim (see
native/README). Verified on the device with Toy Master (2026-09-30): `extension shim: xrLoadRenderModelFB -> FrameBridge`.
Toy Master doesn't request a model after that (it uses its own), so the glb loading path is only unit-tested.
**Crash backtraces (2026-09-30):** Lepton writes tombstones only to `lepton-logcats/steamlaunch-<appid>/logcat-crash.log` (after "Dumping logcat"), not launch.log; agent v23 launch tests wait for it and return `crash_log`, triage gets it via `triage(..., crash=)` (not pid-filtered: tombstones come from crash_dump's pid). The guest is `userdebug` (`ro.debuggable=1`), so Lepton's Fossilize layer loads into every app whatever the APK's debuggable flag; it has no off switch. Fossilize crashed Deadpool VR on uninitialized attachment-reference pNexts (several, in FVulkanRenderPass and the render-target layout) → `frame.vk_sanitize` = `native/vkshim` (engine's `dlopen("libvulkan.so")` string → `libfp_vk.so`, wraps vkCreateRenderPass2/KHR, drops unreadable/wrong-sType pNexts; verified: game runs). overport's dispatcher aborts on swapchains > 4096 px (`cmp wN,#4096` in xrCreateSwapchain) → `frame.swapchain_limit` (verified with 4XVR, 7680×3840 accepted by the runtime). Both are default-on (parity classifies their rewrites as
"expected"; library migration `quest_binary_fixes_v2`). The adapter shows cylinder layers (4XVR's movie screen) as ~15° quad strips (`cylinder_strips`, setting
`cylinder_strips`); the runtime composites them at full resolution. Equirect (360°) layers are dropped: drawing
them ourselves (GLES renderer in xrEndFrame: stutter, never showed 4XVR's VR video; Vulkan renderer: hung the
Frame's GPU in AC Nexus; reading the newest *released* image broke 4XVR's theatre) was removed again on the owner's
request — don't retry without a new approach. Converted layers must count as "swapped" or the original layer list
is submitted (runtime returns -2 for every frame). A focus debounce (hiding the Frame's brief
FOCUSED→VISIBLE→SYNCHRONIZED dips, which make 4XVR recenter) was also removed: AC Nexus stayed black with it (it
hid 521 ms focus changes at start). The new approach (below) is per-game, off the app's render thread, GLES-only.
**360° layers / 4XVR (2026-09-30):** the Frame's Android SteamVR runtime (`/opt/steamvr/bin/androidarm64/vrclient.so`,
mounted in Lepton as `/data/steamvr/runtime`) only composites quad + projection layers (cube/cylinder/equirect(2)
are enum names only) — nothing to unlock. Per-game adapter settings (off by default, hooks installed only when on):
`equirect_emul` (GLES only: a worker thread with a shared EGL context converts each 360° image to a cube map when it
changes and draws one adapter projection layer from it for every frame with exactly that frame's views (the app's own
projection views, else xrLocateViews at displayTime); xrEndFrame waits ≤6 ms for the worker's CPU submit, never the
GPU. Learned in the headset: quads can't be a background (the Frame draws quad layers above all projection layers
whatever the order: hid 4XVR's balcony/controllers), and the Frame doesn't reproject a projection layer from its own
pose (images drawn only after head turns, or ahead from xrWaitFrame and sometimes late, wobbled);
`equirect_flip/face/res/fps/stereo`), `stable_local`, `focus_hold` (only after 3 s FOCUSED, dips <600 ms),
`aim_pitch/aim_yaw/aim_forward`, `refresh_rate`, `layer_debug` (diagnostics). 4XVR re-creates LOCAL spaces every 2–4 s
(menu recentring suspect); its theatres are baked 7680×3840 equirect2 images (`assets/100.png` …). Test 360° videos
(NASA, public domain) are in the Frame's ~/Videos; copies in `~/Downloads/frameport-360`. 4XVR's "Internal Storage"
lists its own `/sdcard/4XPlayer`, not Movies: agent v25 `link_media` hard-links sent files into an app's own top-level
folder (`app_media_dirs`), `frameport frame send --app <pkg>`, GUI game page "Add videos" (players) / "Add videos &
files…". A 4XVR webm stereo swapchain was refused with XR_ERROR_LIMIT_REACHED (-10) → right eye grey; our projection
swapchain was halved (1536/eye) in case memory is the limit (unverified). Frame data snapshot
(SteamVR runtimes, Lepton scripts, logs; never commit Valve binaries): `~/frameport-research/frame-data-2026-09-30/`.
Not yet verified in the headset.
**Lepton storage (2026-09-30):** each app's /sdcard (= /storage/emulated/0 → `<base>/lepton-data/external`) has `Movies`/`Download`/`Documents` symlinked to the Frame's `~/Videos`/`~/Downloads`/`~/Documents` (liblepton/mounting.sh, only if they exist at start); agent v24 `storage_targets` reads that mapping. Android's MediaProvider canonicalises paths to /home/steamos/... and rejects every file ("doesn't appear under [/system/media...]"), `sm list-volumes` is empty: the media index never works, apps must browse folders. Lepton installs with `adb install -g` (runtime permissions granted, MANAGE_EXTERNAL_STORAGE too). Send files: `install/files.py`, `frameport frame send|storage`, GUI Frame → Send files.
**SteamVR per-app settings (2026-09-30):** editing steamvr.vrsettings while SteamVR runs is lost; the web API (127.0.0.1:27062 /app/setsettings) needs `x-steamvr-secret`. `native/vrsettings` = `fp_vrsettings.exe` (freestanding, OpenVR `FnTable:IVRSettings_003` as a Utility app, loads SteamVR's bin/win64/openvr_api.dll) sets them live and SteamVR persists them: section `steam.app.<shortcut appid>`, keys `preferredRefreshRate` (float) and `motionSmoothingOverride` (0 global, 1 on, 2 off, 3 always). Steam Link (vrlink) lists the Frame's rates 72/80/90/96/108/120/144 in vrserver.txt and follows the per-app preference ("host preferred N Hz"; whether the key is honoured is unverified in-headset yet). Judder metric: vrcompositor.txt session summary dropped + "Timed out. N total" (Stormland: 0 dropped but 313 timeouts in 2 min); fpsVR (`%LOCALAPPDATA%\fpsVR\*.json`, 0.1 ms histograms) gives p99 CPU/GPU ms. `pcvr.steamvr_tuning` (default on, PC only) applies on Play: highest rate whose budget ≥ p99×1.05, at least one step down, smoothing on.
**Unresolved (as of 2026-09-28):** Arcsmith (right-eye distortion) and Time Stall (both eyes) — swap, tracking, Valve
layers, depth, pacing ruled out. Sniper Elite VR (DEVICE LOST), Espire 1 (Mesa GL upload crash), HITMAN 3 (freedreno
crash): use PC versions.
@@ -237,7 +325,13 @@ crash): use PC versions.
## Releases, CI, GitHub
Public repo `github.com/spoopyghosty0/frameport` (branch `main`). Push a `v*` tag → CI (`.github/workflows/build.yml`)
tests, builds Windows x64 / macOS arm64 / Linux x64 bundles, signs, attests and publishes a GitHub Release
(`FramePort-*.zip/.tar.gz`, `SHA256SUMS.txt`, `FramePort-selfsigned.cer`, notes from `docs/INSTALL.md`). v0.1.0 exists.
(`FramePort-*.zip/.tar.gz`, the CLI wheel `frameport-<ver>-py3-none-any.whl`, `SHA256SUMS.txt`,
`FramePort-selfsigned.cer`; notes = "What's new" from the annotated tag message + `docs/INSTALL.md` from "First launch").
Installed apps find the release themselves (self-update), so the notes are what users see in the update dialog.
- **Release checklist:** bump `src/frameport/_version.py` (the only version; `scripts/package.py` fails a tag build
whose tag ≠ `v<_version>`), commit, `git tag -a vX.Y.Z -m "FramePort X.Y.Z" -m "<What's new, Markdown bullets>"`,
push the commit and the tag. Never publish a release without its `SHA256SUMS.txt` (the updater refuses it) and keep
the asset names (`updates.ASSETS`) — renaming them breaks updating for every installed copy.
- Signing is **free/self-signed by the owner's choice** (no paid certs, no SignPath): Windows binaries are signed with
a self-signed "FramePort (self-signed)" code-signing cert (RSA 3072, valid to 2031, SHA-256
`4E:12:98:91:62:C0:E4:50:FB:65:1D:34:BB:73:00:09:7B:78:BE:88:5C:A7:6C:42:23:46:9B:92:A1:59:A7:6E`); secrets
@@ -249,8 +343,14 @@ tests, builds Windows x64 / macOS arm64 / Linux x64 bundles, signs, attests and
Windows console) plus PYTHONUTF8; macOS builds need `--python-version 3.12 --arch arm64` (cryptography has no wheels
for flet's default Python / x86_64 cross-build), with a PyInstaller fallback step; `astral-sh/setup-uv` has no
floating major tags after v7 → pin the exact version; force-moving a tag starts duplicate runs (cancel one).
- `gh` is a local install at `~/.local/bin/gh` (logged in as spoopyghosty0 with `workflow` scope; token in
`~/.config/gh/hosts.yml`). Commit as `spoopyghosty0 <336754034+spoopyghosty0@users.noreply.github.com>` (set in the repo config).
- **This project's GitHub identity is `spoopyghosty0`** (a dedicated account; the machine's default gh/git login is a
different, personal account that must never touch this repo). `gh` (`~/.local/bin/gh`) uses it through
`GH_CONFIG_DIR=~/.config/gh-spoopyghosty0` (set for Claude Code in the git-ignored `.claude/settings.local.json`);
git pushes from this folder authenticate as it through a repo-local credential helper, and commits use the repo-local
identity `spoopyghosty0 <336754034+spoopyghosty0@users.noreply.github.com>`. Check with `gh api user --jq .login`
before any GitHub action.
- **No Claude trailers** (`Co-Authored-By: Claude …`, `Claude-Session: …`) in commits or PR descriptions — the owner's
rule; history was rewritten to remove them.
- **The repo is public: never commit personal data** — the Frame's IP address, the Steam user id, the owner's email,
local home paths (native builds use `-ffile-prefix-map`). History was rewritten once to remove them.
+3 -1
View File
@@ -18,7 +18,9 @@ apksigner). Nothing is installed system-wide, and no Android SDK/NDK is needed.
## Install
- **App bundles**: download from [Releases](https://github.com/spoopyghosty0/frameport/releases) (Windows x64, macOS
Apple Silicon, Linux x64); see `docs/INSTALL.md` for the first-launch warning (self-signed / ad-hoc signed) and
how to verify a download. Built by CI (`.github/workflows/build.yml`, `flet build`).
how to verify a download. Built by CI (`.github/workflows/build.yml`, `flet build`). FramePort **updates itself**:
when a new release is out, click **Update now** in the Library (or run `frameport update`).
- **Command line only**: `uv tool install <the release's frameport-*.whl link>` (or pipx / pip), then `frameport --help`.
- **From source**: `uv sync && uv run frameport-gui` (CLI: `uv run frameport --help`).
## Status of tested games
+542 -6
View File
@@ -5,7 +5,8 @@ The PC app uploads this file to ~/.local/share/frameport/agent/ and calls:
python3 frameport_agent.py <command> (JSON arguments on stdin, one JSON object on stdout)
Commands: info, prepare, finalize, shortcuts, shortcut_status, launch_test, stop, set_settings, uninstall,
install_lepton, list_installed, proton_status, install_proton, prepare_pcvr, finalize_pcvr.
install_lepton, list_installed, proton_status, install_proton, prepare_pcvr, finalize_pcvr,
controller_models.
Install layout (one Lepton container per game; same as the manual installs from 2026-09):
~/Applications/quest-frame/<pkg>/ anchor: launch.sh, deployment.json, artwork/ (always internal storage)
@@ -32,7 +33,7 @@ import sys
import time
import zlib
AGENT_VERSION = 17
AGENT_VERSION = 26
HOME = os.path.expanduser("~")
STEAM = os.path.join(HOME, ".local/share/Steam")
ANCHORS = os.path.join(HOME, "Applications/quest-frame")
@@ -879,6 +880,108 @@ def cmd_launch(args):
return {"package": pkg, "gameid": gid, "title": dep.get("title")}
LEPTON_LINK = re.compile(r'ln -s "\$\{HOME\}/([^"/]+)" "\$\{TARGET_PATH\}/([^"/]+)"')
SHARED_DEFAULT = (("Documents", "Documents"), ("Downloads", "Download"), ("Videos", "Movies"))
def lepton_shared_folders():
"""(home folder, Android folder) pairs Lepton links into every app's storage (read from Lepton's mounting.sh;
it only links folders that exist when an app starts)."""
lepton, _app = lepton_path()
text = ""
if lepton:
try:
text = open(os.path.join(os.path.dirname(lepton), "liblepton", "mounting.sh"), errors="replace").read()
except OSError:
pass
pairs = LEPTON_LINK.findall(text)
return pairs or list(SHARED_DEFAULT)
# Folders Android itself creates in every app's /sdcard; anything else at the top level was made by the app.
ANDROID_STORAGE_DIRS = {"alarms", "android", "audiobooks", "dcim", "documents", "download", "movies", "music",
"notifications", "pictures", "podcasts", "recordings", "ringtones", "screenshots"}
def app_media_dirs(ext):
"""The app's own top-level folders in its /sdcard (e.g. 4XVR's 4XPlayer, which its "Internal Storage" list shows
instead of /sdcard/Movies): real folders only (not Lepton's links to the shared folders), not hidden."""
try:
names = sorted(os.listdir(ext))
except OSError:
return []
return [n for n in names if not n.startswith(".") and n.lower() not in ANDROID_STORAGE_DIRS
and os.path.isdir(os.path.join(ext, n)) and not os.path.islink(os.path.join(ext, n))]
def lepton_external(pkg):
dep = deployment(pkg)
if not dep or dep.get("kind") == "pcvr":
raise AgentError(f"{pkg} is not an installed Quest (Lepton) game")
return os.path.join(dep["base"], "lepton-data", "external")
def cmd_storage_targets(args):
"""Where files for Lepton apps go: shared folders (seen by every app, e.g. ~/Videos = /sdcard/Movies) and, with a
package, that app's own storage (/sdcard) and its files folder. Creates missing shared folders (Lepton links only
existing ones). Android's media index doesn't work in Lepton, so apps must browse folders to find files."""
out = []
for home_name, android in lepton_shared_folders():
path = os.path.join(HOME, home_name)
os.makedirs(path, exist_ok=True)
out.append({"id": home_name.lower(), "path": path, "android": "/sdcard/" + android, "shared": True})
pkg = args.get("package")
if pkg:
pkg = check_pkg(pkg)
ext = lepton_external(pkg)
files = os.path.join(ext, "Android", "data", pkg, "files")
os.makedirs(files, exist_ok=True)
out.append({"id": "app", "path": ext, "android": "/sdcard", "shared": False})
out.append({"id": "app-files", "path": files, "android": f"/sdcard/Android/data/{pkg}/files", "shared": False})
for i, name in enumerate(app_media_dirs(ext)): # the app's own folders (e.g. a video player's library)
out.append({"id": "app-media" if i == 0 else f"app-media:{name}", "path": os.path.join(ext, name),
"android": f"/sdcard/{name}", "shared": False, "folder": name})
return {"targets": out}
def cmd_link_media(args):
"""Make files from the shared folders (e.g. ~/Videos) appear in an app's own folder too, as hard links (no copy,
no extra space). For players that list their own folder rather than /sdcard/Movies (4XVR: 4XPlayer). args:
package, files (paths under ~/Videos, ~/Downloads, ~/Documents), folder (optional; default: the app's first own
folder, see app_media_dirs). Returns {folder, android, linked, existing, missing}; folder None when the app has no
own folder (it then finds the files in the shared folders)."""
pkg = check_pkg(args["package"])
ext = lepton_external(pkg)
folder = args.get("folder") or next(iter(app_media_dirs(ext)), None)
if not folder:
return {"folder": None, "android": None, "linked": [], "existing": [], "missing": []}
if "/" in folder or folder in (".", ".."):
raise AgentError(f"bad folder {folder!r}")
dest = os.path.join(ext, folder)
os.makedirs(dest, exist_ok=True)
shared = [os.path.realpath(os.path.join(HOME, h)) for h, _a in lepton_shared_folders()]
linked, existing, missing = [], [], []
for path in args.get("files") or []:
real = os.path.realpath(path)
if not any(real == s or real.startswith(s + os.sep) for s in shared):
raise AgentError(f"{path} is not in a shared folder ({', '.join(shared)})")
if not os.path.isfile(real):
missing.append(path)
continue
target = os.path.join(dest, os.path.basename(real))
if os.path.exists(target):
if os.path.samefile(target, real):
existing.append(os.path.basename(real))
continue
os.remove(target) # an older file of the same name: show the one just sent
try:
os.link(real, target)
except OSError:
shutil.copy2(real, target) # different file system (not the case with Lepton's layout)
linked.append(os.path.basename(real))
return {"folder": folder, "android": f"/sdcard/{folder}", "linked": linked, "existing": existing, "missing": missing}
def cmd_list_files(args):
"""Every file of an installed game on the Frame, for the PC's file browser: {roots: [{name, path, files:
[[rel, size], ...]}], missing: [[rel, expected size, actual size or None], ...], truncated}. Roots are the install
@@ -961,6 +1064,9 @@ app_dir={base_q}
# Some games (Unreal cloud saves) create folders without write/search permission inside Lepton,
# which silently breaks saving. Repair them before and during every launch.
fix_perms() {{ find "$app_dir/lepton-data/external" -type d ! -perm -u+rwx -exec chmod u+rwx {{}} + 2>/dev/null || true; }}
# Android can't create an app's external files/cache folders inside Lepton ("Invalid mkdirs path ... not a known app
# path"): getExternalCacheDir() then returns nothing, which breaks e.g. Whirligig's video player cache. Create them here.
mkdir -p "$app_dir/lepton-data/external/Android/data/{pkg}/files" "$app_dir/lepton-data/external/Android/data/{pkg}/cache" 2>/dev/null || true
fix_perms
( while sleep 2 && kill -0 $$ 2>/dev/null; do fix_perms; done ) & permfix=$!
export SteamAppId={appid}
@@ -1069,6 +1175,7 @@ def cmd_finalize(args):
os.makedirs(os.path.dirname(target), exist_ok=True)
with open(target, "w") as f:
f.write(content)
models = install_controller_models(files_dir, str(settings.get("controller_models", 0)) not in ("0", "0.0"))
write_launcher(anchor, base, pkg, title, appid, lepton, args.get("env"))
art_in = os.path.join(base, "incoming-artwork")
if os.path.isdir(art_in):
@@ -1080,7 +1187,306 @@ def cmd_finalize(args):
"agent_version": AGENT_VERSION, "time": time.time()}
with open(os.path.join(anchor, "deployment.json"), "w") as f:
json.dump(dep, f, indent=2)
return {"ok": True, "base": base, "appid": appid, "moved_data_files": moved}
return {"ok": True, "base": base, "appid": appid, "moved_data_files": moved, "controller_models": models}
# ------------------------------------------------------------------ Steam Frame controller models (XR_FB_render_model)
# The FrameBridge adapter (setting controller_models=1) serves these to games that ask the runtime for controller models.
# They are converted here, on the Frame, from the SteamVR render models the Frame already has (OBJ + PNG) into glTF
# binaries, so Valve's models never leave the device.
MODELS_CACHE = os.path.join(HOME, ".local/share/frameport/controller-models")
FRAME_MODEL_RE = re.compile(r"frame", re.I)
SKIP_COMPONENTS = ("status", "led", "scroll_wheel_touch")
def steamvr_roots():
roots = []
rt = openxr_runtime()
if rt and rt.get("path"):
roots.append(os.path.dirname(rt["path"]))
roots += [os.path.join(lib, "steamapps/common/SteamVR") for lib in steam_libraries()]
roots += ["/opt/steamvr", os.path.join(STEAM, "steamapps/common/SteamVR")]
out = []
for r in roots:
r = os.path.realpath(r)
if os.path.isdir(r) and r not in out:
out.append(r)
return out
def render_model_dirs(roots=None):
"""name -> directory of every SteamVR render model (a folder with .obj files)."""
found = {}
for root in roots if roots is not None else steamvr_roots():
for pattern in ("resources/rendermodels/*", "drivers/*/resources/rendermodels/*"):
for d in sorted(glob.glob(os.path.join(root, pattern))):
if os.path.isdir(d) and glob.glob(os.path.join(d, "*.obj")):
found.setdefault(os.path.basename(d), d)
return found
def model_side(name):
n = name.lower()
for side in ("left", "right"):
if side in n:
return side
for side in ("left", "right"): # e.g. controller_l / controller-r
if re.search(rf"(^|[_\-. ]){side[0]}([_\-. ]|$)", n):
return side
return None
def pick_controller_models(dirs, pattern=FRAME_MODEL_RE):
"""{'left': dir, 'right': dir} for the Steam Frame controllers (names matching `pattern`), or {}."""
best = {}
for name, d in dirs.items():
side = model_side(name)
if not side or not pattern.search(name):
continue
score = ("controller" in name.lower()) * 10 - len(name)
if side not in best or score > best[side][0]:
best[side] = (score, d)
return {s: d for s, (_, d) in best.items()} if len(best) == 2 else {}
def _rotation_xyz(deg):
"""3x3 rotation for SteamVR's rotate_xyz (degrees; applied about X, then Y, then Z)."""
import math
rx, ry, rz = (math.radians(float(v)) for v in (list(deg) + [0, 0, 0])[:3])
cx, sx, cy, sy, cz, sz = math.cos(rx), math.sin(rx), math.cos(ry), math.sin(ry), math.cos(rz), math.sin(rz)
X = [[1, 0, 0], [0, cx, -sx], [0, sx, cx]]
Y = [[cy, 0, sy], [0, 1, 0], [-sy, 0, cy]]
Z = [[cz, -sz, 0], [sz, cz, 0], [0, 0, 1]]
mul = lambda a, b: [[sum(a[i][k] * b[k][j] for k in range(3)) for j in range(3)] for i in range(3)]
return mul(Z, mul(Y, X))
def model_description(model_dir):
"""(obj files, grip transform or None) from the model's JSON (components) or the folder's .obj files."""
name = os.path.basename(model_dir)
desc = {}
for cand in (os.path.join(model_dir, name + ".json"), *sorted(glob.glob(os.path.join(model_dir, "*.json")))):
try:
desc = json.load(open(cand))
if isinstance(desc, dict) and "components" in desc:
break
except (OSError, ValueError):
desc = {}
objs, grip = [], None
for cname, comp in (desc.get("components") or {}).items():
if not isinstance(comp, dict):
continue
if cname == "openxr_grip" and isinstance(comp.get("component_local"), dict):
local = comp["component_local"]
grip = (list(local.get("origin") or [0, 0, 0]), _rotation_xyz(local.get("rotate_xyz") or [0, 0, 0]))
fn = comp.get("filename")
hidden = (comp.get("visibility") or {}).get("default") is False # e.g. status LEDs
if fn and not hidden and not any(s in cname.lower() for s in SKIP_COMPONENTS):
p = os.path.join(model_dir, fn)
if os.path.exists(p):
objs.append(p)
if not objs:
whole = os.path.join(model_dir, name + ".obj")
objs = [whole] if os.path.exists(whole) else sorted(glob.glob(os.path.join(model_dir, "*.obj")))
return objs, grip
def parse_mtl(path):
"""material name -> texture file (map_Kd)."""
out, cur = {}, None
try:
for line in open(path, errors="replace"):
parts = line.strip().split(None, 1)
if not parts:
continue
if parts[0] == "newmtl" and len(parts) > 1:
cur = parts[1].strip()
elif parts[0] == "map_Kd" and cur and len(parts) > 1:
out[cur] = os.path.join(os.path.dirname(path), parts[1].strip().split()[-1])
except OSError:
pass
return out
def parse_obj(path):
"""-> list of (texture path or None, positions, normals, uvs, triangles as (v, vt, vn) index triples)."""
pos, nrm, uv = [], [], []
groups = {} # texture -> list of corner triples
mats, tex = {}, None
for line in open(path, errors="replace"):
parts = line.split()
if not parts:
continue
tag = parts[0]
if tag == "v":
pos.append(tuple(float(x) for x in parts[1:4]))
elif tag == "vn":
nrm.append(tuple(float(x) for x in parts[1:4]))
elif tag == "vt":
uv.append((float(parts[1]), float(parts[2]) if len(parts) > 2 else 0.0))
elif tag == "mtllib":
mats.update(parse_mtl(os.path.join(os.path.dirname(path), " ".join(parts[1:]))))
elif tag == "usemtl":
tex = mats.get(" ".join(parts[1:]))
elif tag == "f":
corners = []
for c in parts[1:]:
idx = (c.split("/") + ["", ""])[:3]
ref = []
for i, n in zip(idx, (len(pos), len(uv), len(nrm))):
ref.append(None if not i else (int(i) - 1 if int(i) > 0 else n + int(i)))
corners.append(tuple(ref))
for i in range(1, len(corners) - 1): # fan triangulation
groups.setdefault(tex, []).extend((corners[0], corners[i], corners[i + 1]))
return pos, nrm, uv, groups
def controller_glb(model_dir):
"""glTF binary (one mesh, one primitive per texture, PNG/JPEG textures, in the controller's OpenXR grip space
when the model defines openxr_grip) for a SteamVR render model folder."""
objs, grip = model_description(model_dir)
if not objs:
raise AgentError(f"no .obj files in {model_dir}")
# texture -> (positions, normals, uvs, indices), vertices de-duplicated per corner triple
prims = {}
for obj in objs:
pos, nrm, uv, groups = parse_obj(obj)
for tex, corners in groups.items():
if tex and os.path.splitext(tex)[1].lower() not in (".png", ".jpg", ".jpeg"):
tex = None
p = prims.setdefault(tex, {"pos": [], "nrm": [], "uv": [], "idx": [], "map": {}})
for c in corners:
key = (obj, c)
if key not in p["map"]:
p["map"][key] = len(p["pos"])
v = pos[c[0]]
n = nrm[c[2]] if c[2] is not None and c[2] < len(nrm) else (0.0, 0.0, 1.0)
t = uv[c[1]] if c[1] is not None and c[1] < len(uv) else (0.0, 0.0)
if grip: # raw device space -> grip space: R^T (v - origin)
o, r = grip
d = [v[k] - float(o[k]) for k in range(3)]
v = tuple(sum(r[k][j] * d[k] for k in range(3)) for j in range(3))
n = tuple(sum(r[k][j] * n[k] for k in range(3)) for j in range(3))
p["pos"].append(v)
p["nrm"].append(n)
p["uv"].append((t[0], 1.0 - t[1])) # OBJ origin bottom-left, glTF top-left
p["idx"].append(p["map"][key])
blob = bytearray()
views, accessors, images, textures, materials, primitives = [], [], [], [], [], []
def add_view(data, target=None):
while len(blob) % 4:
blob.append(0)
view = {"buffer": 0, "byteOffset": len(blob), "byteLength": len(data)}
if target:
view["target"] = target
blob.extend(data)
views.append(view)
return len(views) - 1
def add_accessor(values, width, ctype, kind, target, minmax=False):
fmt = {5126: "f", 5125: "I"}[ctype]
flat = [x for v in values for x in (v if width > 1 else (v,))]
acc = {"bufferView": add_view(struct.pack(f"<{len(flat)}{fmt}", *flat), target), "componentType": ctype,
"count": len(values), "type": kind}
if minmax:
acc["min"] = [min(v[k] for v in values) for k in range(width)]
acc["max"] = [max(v[k] for v in values) for k in range(width)]
accessors.append(acc)
return len(accessors) - 1
for tex, p in prims.items():
if not p["idx"]:
continue
attrs = {"POSITION": add_accessor(p["pos"], 3, 5126, "VEC3", 34962, minmax=True),
"NORMAL": add_accessor(p["nrm"], 3, 5126, "VEC3", 34962),
"TEXCOORD_0": add_accessor(p["uv"], 2, 5126, "VEC2", 34962)}
indices = add_accessor(p["idx"], 1, 5125, "SCALAR", 34963)
mat = {"pbrMetallicRoughness": {"metallicFactor": 0.0, "roughnessFactor": 0.8}}
if tex and os.path.exists(tex):
mime = "image/png" if tex.lower().endswith(".png") else "image/jpeg"
images.append({"bufferView": add_view(open(tex, "rb").read()), "mimeType": mime})
textures.append({"source": len(images) - 1})
mat["pbrMetallicRoughness"]["baseColorTexture"] = {"index": len(textures) - 1}
else:
mat["pbrMetallicRoughness"]["baseColorFactor"] = [0.1, 0.1, 0.1, 1.0]
materials.append(mat)
primitives.append({"attributes": attrs, "indices": indices, "material": len(materials) - 1})
if not primitives:
raise AgentError(f"no triangles in {model_dir}")
while len(blob) % 4:
blob.append(0)
gltf = {"asset": {"version": "2.0", "generator": "FramePort agent"}, "scene": 0, "scenes": [{"nodes": [0]}],
"nodes": [{"name": os.path.basename(model_dir), "mesh": 0}],
"meshes": [{"primitives": primitives}], "materials": materials, "accessors": accessors,
"bufferViews": views, "buffers": [{"byteLength": len(blob)}]}
if images:
gltf.update(images=images, textures=textures, samplers=[{}])
for t in textures:
t["sampler"] = 0
js = json.dumps(gltf, separators=(",", ":")).encode()
js += b" " * (-len(js) % 4)
total = 12 + 8 + len(js) + 8 + len(blob)
return (struct.pack("<III", 0x46546C67, 2, total) + struct.pack("<I4s", len(js), b"JSON") + js
+ struct.pack("<I4s", len(blob), b"BIN\x00") + bytes(blob))
def _tree_stamp(d):
h = hashlib.sha256()
for p in sorted(glob.glob(os.path.join(d, "*"))):
st = os.stat(p)
h.update(f"{os.path.basename(p)}:{st.st_size}:{int(st.st_mtime)}\n".encode())
return h.hexdigest()[:16]
def frame_controller_models():
"""Converted (cached) glb paths for the Frame controllers: {'left': path, 'right': path, 'sources': {...}}."""
picked = pick_controller_models(render_model_dirs())
if not picked:
raise AgentError("no Steam Frame controller render models found in SteamVR (looked in: "
+ ", ".join(steamvr_roots() or ["no SteamVR install"]) + ")")
os.makedirs(MODELS_CACHE, exist_ok=True)
out = {"sources": picked}
for side, d in picked.items():
cached = os.path.join(MODELS_CACHE, f"{os.path.basename(d)}-{_tree_stamp(d)}.glb")
if not os.path.exists(cached):
data = controller_glb(d)
with open(cached + ".tmp", "wb") as f:
f.write(data)
os.replace(cached + ".tmp", cached)
out[side] = cached
return out
def install_controller_models(files_dir, enabled):
"""Put (or remove) framebridge/controller_{left,right}.glb in a game's files dir. Never fails the install."""
target = os.path.join(files_dir, "framebridge")
if not enabled:
for side in ("left", "right"):
p = os.path.join(target, f"controller_{side}.glb")
if os.path.exists(p):
os.remove(p)
return None
try:
models = frame_controller_models()
except (AgentError, OSError, ValueError, IndexError) as e:
return {"ok": False, "error": str(e)}
os.makedirs(target, exist_ok=True)
for side in ("left", "right"):
shutil.copyfile(models[side], os.path.join(target, f"controller_{side}.glb"))
return {"ok": True, "sources": models["sources"]}
def cmd_controller_models(args):
"""Diagnostics: SteamVR roots, every render model found, and which ones are used as the Frame controllers."""
dirs = render_model_dirs()
result = {"roots": steamvr_roots(), "render_models": dirs, "picked": pick_controller_models(dirs)}
if args.get("convert"):
try:
result["converted"] = frame_controller_models()
except (AgentError, OSError, ValueError, IndexError) as e:
result["error"] = str(e)
return result
# ------------------------------------------------------------------------------------------ PC VR (Rift) under Proton
@@ -1218,7 +1624,7 @@ def write_proton_launcher(anchor, base, pkg, title, appid, tool, exe_rel, revive
argv = prefix + [injector, "/openxr", windows_path(exe)]
else:
argv = prefix + [exe]
argv += [a for a in game_args or () if re.fullmatch(r"-[A-Za-z0-9_=.:-]+", a)]
argv += [a for a in game_args or () if re.fullmatch(r"[A-Za-z0-9_=.:/+-]+", a)] # e.g. -hmd=OpenXR, -vrmode OpenVR
extra = "".join(f"export {k}={shlex.quote(str(v))}\n" for k, v in (env or {}).items()
if re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", k))
workdir = os.path.dirname(exe_rel)
@@ -1248,6 +1654,41 @@ def set_crash_reporter(base, enabled):
os.replace(p, p[:-len(".disabled")])
def set_libovr_redirect(base, exe_rel, enabled, bundled=False):
"""LoadLibrary redirect (pure runtime substitution): put LibOVRRT{64,32}_1.dll in the game's own DLL search dir as
a symlink to Revive's LibReviveXR runtime, so the game's Oculus SDK finds a runtime to load. The symlink keeps the
DLL in the revive/ folder, so its sibling dependencies still resolve. This does NOT touch the game's runtime
signature check — a build that verifies the Oculus signature of LibOVRRT will still reject Revive's (unsigned)
runtime; this only helps builds that don't verify it. We only ever create/remove our own symlink, never a real
DLL the game shipped. Removed when disabled."""
game = os.path.join(base, "game")
exe_dir = os.path.dirname(os.path.join(game, exe_rel))
# the runtime: FramePort's Revive (revive/LibReviveXR*), or with bundled=True the repack's own LibRevive*.dll
# next to the exe (a repack set up for SteamVR, whose Windows loader hook doesn't take effect under Proton)
runtimes = {bits: (os.path.join(exe_dir, "LibRevive%s.dll" % bits) if bundled else
os.path.join(base, "revive", "LibReviveXR%s.dll" % bits)) for bits in ("64", "32")}
# where the Oculus SDK looks for LibOVRRT: the game exe's dir (monolithic engines carry the shim in the exe) AND
# next to every OVRPlugin.dll (Unreal's shim searches its own module dir).
dirs = {os.path.dirname(os.path.join(game, exe_rel))}
for root, _, files in os.walk(game):
for n in files:
if n.lower() == "ovrplugin.dll":
dirs.add(root)
for d in dirs:
for bits, target in runtimes.items():
link = os.path.join(d, "LibOVRRT%s_1.dll" % bits)
ours = os.path.islink(link) and os.path.basename(os.path.realpath(link)).lower().startswith("librevive")
if ours and os.path.realpath(link) != os.path.realpath(target):
os.remove(link) # switched between FramePort's and the bundled Revive
if enabled and os.path.isfile(target):
if os.path.islink(link) or not os.path.exists(link): # never clobber a real game-shipped DLL
if os.path.lexists(link):
os.remove(link)
os.symlink(target, link)
elif ours:
os.remove(link)
def cmd_finalize_pcvr(args):
"""Move uploaded game/Revive files into place, delete files the new version no longer has, write the Proton
launcher and deployment.json. The Proton prefix (saves) is kept."""
@@ -1298,6 +1739,7 @@ def cmd_finalize_pcvr(args):
if oculus_hmd and not os.path.isfile(os.path.join(base, "helpers", OCULUS_HMD_HELPER)):
raise AgentError(f"{OCULUS_HMD_HELPER} missing")
set_crash_reporter(base, enabled=not args.get("no_crash_reporter"))
set_libovr_redirect(base, exe_rel, enabled=bool(args.get("libovr_redirect")), bundled=not revive)
write_proton_launcher(anchor, base, pkg, title, appid, tool, exe_rel, revive, args.get("env"), xr_layer,
args.get("game_args") or [], oculus_hmd)
art_in = os.path.join(base, "incoming-artwork")
@@ -1307,7 +1749,8 @@ def cmd_finalize_pcvr(args):
dep = {"package": pkg, "kind": "pcvr", "appid": int(appid), "base": base, "title": title, "exe": exe_rel,
"tags": args.get("tags") or [],
"sha256": args.get("exe_sha256"), "revive": revive, "revive_version": args.get("revive_version"),
"proton": tool["name"], "xr_layer": xr_layer, "oculus_hmd": oculus_hmd, "recipe": args.get("recipe"),
"proton": tool["name"], "xr_layer": xr_layer, "oculus_hmd": oculus_hmd, "libovr_redirect": bool(args.get("libovr_redirect")),
"recipe": args.get("recipe"),
"installed_by": "frameport",
"files": {t: manifests.get(t) or {} for t in PCVR_TREES},
"agent_version": AGENT_VERSION, "time": time.time()}
@@ -1340,7 +1783,8 @@ def cmd_set_settings(args):
os.makedirs(files_dir, exist_ok=True)
with open(os.path.join(files_dir, "framebridge.conf"), "w") as f:
f.write(text)
return {"settings": current}
models = install_controller_models(files_dir, current.get("controller_models", "0") not in ("0", "0.0"))
return {"settings": current, "controller_models": models}
def cmd_uninstall(args):
@@ -1465,10 +1909,18 @@ def cmd_launch_test(args):
state = "NEVER_STARTED"
break
elapsed = round(time.time() - start)
if state == "EXITED": # Lepton dumps the container's logcat buffers (crash backtraces) after "Exited!"
until = time.time() + 15
while time.time() < until and "Dumping logcat" not in (open(log, errors="replace").read() if os.path.exists(log) else ""):
time.sleep(1)
time.sleep(2)
run(["systemctl", "--user", "stop", unit])
run(["podman", "kill", f"lepton-steamlaunch-{appid}"])
time.sleep(3)
crash = os.path.join(STEAM, "logs", "lepton-logcats", f"steamlaunch-{appid}", "logcat-crash.log")
fresh = os.path.exists(crash) and os.path.getmtime(crash) >= start - 1 and os.path.getsize(crash) > 0
return {"state": state, "elapsed": elapsed, "log": log, "log_size": os.path.getsize(log) if os.path.exists(log) else 0,
"crash_log": crash if fresh else None,
"kernel_keys_before": keys, "kernel_keys_after": key_usage()}
@@ -1516,6 +1968,90 @@ def launch_test_pcvr(dep, anchor, log, seconds):
"kind": "pcvr", "game_process": bool(game_seen)}
def _tail(path, max_bytes):
try:
size = os.path.getsize(path)
with open(path, "rb") as f:
if size > max_bytes:
f.seek(size - max_bytes)
data = f.read()
text = data.decode("utf-8", "replace")
return (f"[... first {size - max_bytes} bytes cut ...]\n" if size > max_bytes else "") + text
except OSError:
return None
def cmd_collect_diag(args):
"""Everything useful for debugging without the game or the PC app: host runtime facts and, with a package, the
game's launcher, settings, deployment, logs (launch, Lepton logcat, Proton/Revive/Unreal) and its file listing.
Returns {"host": {...}, "files": {name: text}, "listing": ...}; the PC redacts and zips it."""
max_bytes = int(args.get("max_bytes", 2 << 20))
files, host = {}, {}
host["openxr_runtime"] = openxr_runtime()
layers = os.path.join(HOME, ".local/share/openxr/1/api_layers/explicit.d")
host["openxr_layers"] = sorted(os.listdir(layers)) if os.path.isdir(layers) else []
host["kernel_keys"] = key_usage()
host["containers_conf"] = _tail(CONTAINERS_CONF, 20000)
host["podman"] = run(["podman", "ps", "-a", "--filter", "name=lepton", "--format",
"{{.Names}} {{.Status}}"]).stdout[-20000:]
host["steam_running"] = run(["pgrep", "-x", "steam"]).returncode == 0
host["uptime"] = _tail("/proc/uptime", 200)
host["installed"] = [{k: g.get(k) for k in ("package", "title", "kind", "appid", "version", "agent_version")}
for g in cmd_list_installed({})["games"]]
out = {"agent_version": AGENT_VERSION, "host": host, "files": files}
pkg = args.get("package")
if not pkg:
# the OpenXR runtime's own log (XRService-<date>_<time>.log): the newest one
xr = [p for p in glob.glob(os.path.join(STEAM, "logs/XRService-*.log")) +
glob.glob(os.path.join(STEAM, "logs/XRService-*/XRService-*.log")) if os.path.isfile(p)]
for p in sorted(xr, key=os.path.getmtime, reverse=True)[:1]:
files[os.path.basename(p)] = _tail(p, max_bytes)
return out
pkg = check_pkg(pkg)
dep = deployment(pkg)
anchor = os.path.join(ANCHORS, pkg)
if not dep:
out["installed"] = False
return out
out["installed"] = True
base, appid = dep["base"], dep.get("appid")
dep = dict(dep)
dep.pop("files", None) # the install manifest is large; `listing` below has the real files
files["deployment.json"] = json.dumps(dep, indent=1)
for name, path in (("launch.sh", os.path.join(anchor, "launch.sh")),
("settings.conf", os.path.join(base, "settings.conf")),
("launch.log", os.path.join(base, "launch.log")),
("launch-test.log", os.path.join(base, "launch-test.log"))):
text = _tail(path, max_bytes)
if text is not None:
files[name] = text
for rel in PCVR_LOGS + (f"steam-{appid}.log",):
text = _tail(os.path.join(base, rel), max_bytes)
if text is not None:
files[os.path.basename(rel)] = text
if dep.get("kind") == "pcvr":
for i, part in enumerate(game_logs(base)):
files[f"game-log-{i}.txt"] = part[-max_bytes:]
logs = os.path.join(STEAM, "logs")
text = _tail(os.path.join(logs, f"lepton-steamlaunch-{appid}.log"), max_bytes) # Lepton's launcher log
if text is not None:
files[f"lepton-steamlaunch-{appid}.log"] = text
logcats = os.path.join(logs, "lepton-logcats")
# the container's logcat buffers: lepton-logcats/steamlaunch-<appid>/logcat-{main,crash,system,kernel,radio}.log
order = ("main", "crash", "system", "kernel", "radio")
cands = [p for p in glob.glob(os.path.join(logcats, f"steamlaunch-{appid}", "*")) if os.path.isfile(p)]
for p in sorted(cands, key=lambda p: next((i for i, k in enumerate(order) if k in os.path.basename(p)), 9)):
name = os.path.basename(p)
files[name if name.startswith("logcat") else "logcat-" + name] = _tail(p, max_bytes)
try:
listing = cmd_list_files({"package": pkg, "limit": 20000})
out["listing"] = {"missing": listing["missing"], "truncated": listing["truncated"],
"roots": [{"name": r["name"], "files": r["files"]} for r in listing["roots"]]}
except AgentError:
pass
return out
AGENT_HOME = os.path.join(HOME, ".local/share/frameport")
+5 -2
View File
@@ -1,9 +1,12 @@
0f681f54b59cfad2efc8883aee5a0971c2fba09d9ba2dca15a136b0ac74a59b8 ./arm64-v8a/libfp_vk.so
8e00552d1ab90f82749db3caad4f773351fa8a28edcc5ea5cbd1b31c434ff32a ./arm64-v8a/libframe_xrshim.so
3dfcb0f2bec47857bcecc7261c58e076d872d4649718c40850f29e10c75477dd ./arm64-v8a/libglshim.so
ca27ffa2122def910697ddcaff64f25cfdbc63e2017c738155866ff2fcdb5e12 ./arm64-v8a/libopenxr_loader_generic.so
dc62857b4f7a23b194060599339dfe72b38c16cdf4a9eb1b1f3b4d1fb9071a6d ./arm64-v8a/libopenxr_loader_generic.so
1feaeafad467c4cafdf2b018a4d84b0bee200c3f711697b4ce97e66a3ba256ca ./arm64-v8a/libovrplatformcompat.so
32525cd0a9ee3d9993d8871cd6905bdcf22cde4f4ba28f5db6434ce7d6554758 ./arm64-v8a/libvrapi.so
f3aa9419155b8970617fc0d68527a73c39abc82303214c159194c439bb776fd6 ./armeabi-v7a/libopenxr_loader_generic.so
a79c598744b98b9bf581664a80bcee1a0d11a62fdcdb99f05a0f6f381b6498cd ./armeabi-v7a/libopenxr_loader_generic.so
1871eae093432d277da4bc751bf5f3269dfcf11f9168260b0c3caadb0dedb19d ./dex/oculusos-stubs.dex
1aa733117cf57ccff7cf23f0425dbfd73b0332a3ef1c905ceeca0ccd0449c4e0 ./linux-arm64/XR_APILAYER_FRAMEPORT_timefix.json
28c2430a02bbd8902c5bfb9562c6fd0e318654f9e05c095bfeb94b0450ab1b07 ./linux-arm64/libxr_frameport_timefix.so
c2c70f4af1a5c3e6089dff1130161dd417f8044f99ec639eeecf1083930aab16 ./win-x64/fp_oculushmd.exe
60ebc5fea05b8945082e2ca8b9f2eb74616012a26eb50133af273dff0fcddc42 ./win-x64/fp_vrsettings.exe
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,20 @@
package: cn.vr4p.oculus4xvrplayerov
title: 4XVR Video Player
status: works
notes: 'Native OpenXR GLES video player. 360 theatres/videos (equirect2 layers, which the Frame lacks) are drawn
by FrameBridge''s equirect_emul; stable_local/focus_hold stop the menu recentring; scale 0.75 keeps the menu screen
at 72 fps (the runtime asks for 4536 px per eye). Confirmed in the headset by the owner (2026-10-01). Its "Internal
Storage" list is /sdcard/4XPlayer: send videos with the game page''s "Add videos".'
details: 'Settings: equirect_emul (GLES worker draws 360 layers into a projection layer), stable_local, focus_hold,
scale 0.75; frame.swapchain_limit for its 7680x3840 theatre swapchains.'
tested_version: 2.0.22
engine: Other
xr: OpenXR
adapter:
equirect_emul: 1
stable_local: 1
focus_hold: 1
scale: 0.75
verified:
date: '2026-10-01'
source_hint: 4XVR Video Player
@@ -1,7 +1,7 @@
package: com.Armature.SportsScramble
title: Sports Scramble (Santa Cruz)
tested_version: '1.0'
source_hint: Sports Scramble v88+1.0
source_hint: Sports Scramble
engine: Unreal
xr: VrApi
status: unsupported
+1 -1
View File
@@ -1,7 +1,7 @@
package: com.Astrea.Gundam
title: 'Mobile Suit Gundam: Silver Phantom'
tested_version: 1.1.58.402
source_hint: Mobile Suit Gundam- Silver Phantom v868+1.1.58.402
source_hint: 'Mobile Suit Gundam- Silver Phantom'
engine: Unity
xr: OpenXR
status: works
+1 -1
View File
@@ -1,7 +1,7 @@
package: com.BithellGames.Arcsmith
title: Arcsmith
tested_version: '1.128'
source_hint: Arcsmith v128+1.128
source_hint: Arcsmith
engine: Unity
xr: VrApi
status: issues
@@ -1,7 +1,7 @@
package: com.BolverkGames.GenotypeGame
title: Genotype
tested_version: '1.8'
source_hint: Genotype v922+1.8
source_hint: Genotype
engine: Unity
xr: OpenXR
status: works
+1 -1
View File
@@ -1,7 +1,7 @@
package: com.DigitalLode.Espire1
title: 'Espire 1: VR Operative (Quest Edition)'
tested_version: 1.13.36
source_hint: Espire 1- VR Operative v2025+1.13.36
source_hint: 'Espire 1- VR Operative'
engine: Unreal
xr: VrApi
status: unsupported
+1 -1
View File
@@ -1,7 +1,7 @@
package: com.DigitalLode.Espire2
title: Espire 2
tested_version: 1.7.13
source_hint: Espire 2- Stealth Operatives v9187+1.7.13
source_hint: 'Espire 2- Stealth Operatives'
engine: Unreal
xr: OpenXR
status: works
@@ -1,7 +1,7 @@
package: com.FuturLab.PowerWashSimulator
title: PowerWash Simulator VR
tested_version: 2.5.0
source_hint: PowerWash Simulator VR v3055+2.5.0
source_hint: PowerWash Simulator VR
engine: Unity
xr: OpenXR
status: works
@@ -1,7 +1,7 @@
package: com.JustAddWater.SniperEliteVR
title: Sniper Elite VR
tested_version: '1.03'
source_hint: Sniper Elite VR v35713+1.03
source_hint: Sniper Elite VR
engine: Unity
xr: VrApi
status: unsupported
@@ -1,7 +1,7 @@
package: com.JustAddWater.SniperEliteVR_EN
title: 'Sniper Elite VR: Winter Warrior'
tested_version: 1.0.1
source_hint: Sniper Elite VR- Winter Warrior v125+1.0.1
source_hint: 'Sniper Elite VR- Winter Warrior'
engine: Unity
xr: OpenXR
status: works
+1 -1
View File
@@ -1,7 +1,7 @@
package: com.Novelab.Demeter
title: Demeter
tested_version: 1.1.0
source_hint: Demeter v53+1.1.0
source_hint: Demeter
engine: Unity
xr: OpenXR
status: works
+1 -1
View File
@@ -1,7 +1,7 @@
package: com.Sanzaru.Wrath2
title: Asgard's Wrath 2
tested_version: 12.1.1689309
source_hint: Asgards Wrath 2 v5513+12.1.1689309
source_hint: Asgards Wrath 2
engine: Unreal
xr: OpenXR
status: works
+1 -1
View File
@@ -1,7 +1,7 @@
package: com.Solfar.InDeath
title: 'In Death: Unchained'
tested_version: 1.8.0
source_hint: In Death- Unchained v123248087+1.8.0
source_hint: 'In Death- Unchained'
engine: Unreal
xr: OpenXR
status: works
@@ -1,7 +1,7 @@
package: com.TeamPanoptes.SilhouetteVR
title: Silhouette
tested_version: 1.3.0
source_hint: Silhouette v200090+1.3.0
source_hint: Silhouette
engine: Unity
xr: OpenXR
status: issues
+1 -1
View File
@@ -1,7 +1,7 @@
package: com.Ubisoft.ACNexusVR
title: Assassin's Creed Nexus
tested_version: MAIN.450412.207706.final
source_hint: Assassins Creed Nexus VR v207706+MAIN.450412.207706.final
source_hint: Assassins Creed Nexus VR
engine: Unity
xr: OpenXR
status: issues
+1 -1
View File
@@ -1,7 +1,7 @@
package: com.VRFactory.VRBartender
title: BARTENDER VR SIMULATOR
tested_version: 1.9.2.7
source_hint: BARTENDER VR SIMULATOR v1338+1.9.2.7
source_hint: BARTENDER VR SIMULATOR
engine: Unreal
xr: OpenXR
status: works
+1 -1
View File
@@ -1,7 +1,7 @@
package: com.ViteiBackroom.Powder
title: Carve Snowboarding
tested_version: '1.09'
source_hint: Carve Snowboarding v585+1.09
source_hint: Carve Snowboarding
engine: Unreal
xr: VrApi
status: works
@@ -1,7 +1,7 @@
package: com.YourCompany.RoboRecall
title: Robo Recall
tested_version: '1.0'
source_hint: Robo Recall- Unplugged v47091+1.0
source_hint: 'Robo Recall- Unplugged'
engine: Unreal
xr: VrApi
status: works
+1 -1
View File
@@ -1,7 +1,7 @@
package: com.camouflaj.manta
title: 'Batman: Arkham Shadow'
tested_version: 1.4.1-350961
source_hint: Batman- Arkham Shadow (Inc Lang Packs) v350961+1.4.1-350961
source_hint: 'Batman- Arkham Shadow'
engine: Unity
xr: OpenXR
status: works
+1 -1
View File
@@ -1,7 +1,7 @@
package: com.coatsink.nexus
title: Shadow Point
tested_version: '1.4'
source_hint: Shadow Point v47+1.4
source_hint: Shadow Point
engine: Unity
xr: VrApi
status: unsupported
@@ -1,7 +1,7 @@
package: com.com.spectralgames.Medieval
title: Medieval Dynasty New Settlement
tested_version: '2.4'
source_hint: Medieval Dynasty New Settlement v233+2.4
source_hint: Medieval Dynasty New Settlement
engine: Unity
xr: OpenXR
status: works
+1 -1
View File
@@ -1,7 +1,7 @@
package: com.crytek.climb2
title: The Climb 2
tested_version: '2.2'
source_hint: The Climb 2 v974+2.2
source_hint: The Climb 2
engine: CryEngine
xr: VrApi
status: works
@@ -1,7 +1,7 @@
package: com.forcefieldxr.timestall
title: Time Stall
tested_version: '1.0'
source_hint: Time Stall v631960+1.0
source_hint: Time Stall
engine: Unreal
xr: VrApi
status: issues
+1 -1
View File
@@ -1,7 +1,7 @@
package: com.gritGames.Nope
title: NOPE CHALLENGE
tested_version: 1.0.964.7166
source_hint: NOPE CHALLENGE v964+1.0.964.7166
source_hint: NOPE CHALLENGE
engine: Unreal
xr: OpenXR
status: works
+1 -1
View File
@@ -1,7 +1,7 @@
package: com.iillusions.bamgame
title: BAM
tested_version: '1.2'
source_hint: BAM v2786+1.2
source_hint: BAM
engine: Unity
xr: OpenXR
status: works
+1 -1
View File
@@ -1,7 +1,7 @@
package: com.nDreams.PhantomQuest
title: 'Phantom: Covert Ops'
tested_version: '1.2'
source_hint: Phantom- Covert Ops v498003+1.2
source_hint: 'Phantom- Covert Ops'
engine: Unreal
xr: VrApi
status: issues
+11
View File
@@ -0,0 +1,11 @@
package: com.nexxr.nexplayer
title: NEX Player
status: works
notes: 'Confirmed in the headset by the owner (2026-10-01): 72 fps, local 2D/360/3D videos play (it browses /sdcard/Movies
itself). USB-drive browsing can''t work in Lepton.'
tested_version: 1.3.1.0
engine: Unity
xr: OpenXR
verified:
date: '2026-10-01'
source_hint: NEX - NEXt-Gen Video Player
@@ -1,7 +1,7 @@
package: com.noghost.thegrandgetaway
title: Wallace & Gromit in The Grand Getaway
tested_version: 1.0.34
source_hint: Wallace & Gromit in The Grand Getaway v141+1.0.34
source_hint: Wallace & Gromit in The Grand Getaway
engine: Unreal
xr: OpenXR
status: works
@@ -1,7 +1,7 @@
package: com.sigtrapgames.undercover
title: Under Cover
tested_version: 1.1.3r2
source_hint: Under Cover v10147+1.1.3r2
source_hint: Under Cover
engine: Unity
xr: OpenXR
status: works
@@ -1,7 +1,7 @@
package: com.thunderful.legobricktales
title: LEGO® Bricktales
tested_version: '2.1'
source_hint: LEGO Bricktales v201449+2.1
source_hint: LEGO Bricktales
engine: Unity
xr: OpenXR
status: works
@@ -0,0 +1,17 @@
package: com.twistedpixelgames.PILO
title: Marvel's Deadpool VR
status: works
notes: 'Unreal (Vulkan): Lepton''s Fossilize layer crashed on uninitialized render-pass pNexts; frame.vk_sanitize
fixes it. Confirmed working in the headset by the owner (2026-10-01).'
details: Needs frame.vk_sanitize (native/vkshim) and frame.swapchain_limit; space warp disabled (32 GiB OVRPlugin
game).
tested_version: 1.0.40.356975.Quest
engine: Unreal
xr: OpenXR
overport_extra:
- patch_disable_space_warp
alt_overport:
- patch_remove_unreal_force_quit
verified:
date: '2026-10-01'
source_hint: Marvels Deadpool VR
@@ -1,7 +1,7 @@
package: com.twistedpixelgames.POTW_App
title: Path of the Warrior
tested_version: 21.11.10.358057
source_hint: Path of the Warrior v498+21.11.10.358057
source_hint: Path of the Warrior
engine: Other
xr: VrApi
status: works
@@ -1,7 +1,7 @@
package: com.xrgames.hitman3reloaded
title: 'HITMAN 3 VR: Reloaded'
tested_version: 0.0.3469 main-14813cc56
source_hint: HITMAN 3 VR- Reloaded v3469+0.0.3469
source_hint: 'HITMAN 3 VR- Reloaded'
engine: Other
xr: OpenXR
status: unsupported
+1 -1
View File
@@ -1,7 +1,7 @@
package: gg.trs.grappa
title: Journey of the Gods
tested_version: 1.0.479431
source_hint: Journey of the Gods v479431+1.0.479431
source_hint: Journey of the Gods
engine: Unreal
xr: VrApi
status: unsupported
@@ -2,7 +2,7 @@ package: rift.rick_and_morty_virtual_rick_ality
title: 'Rick and Morty: Virtual Rick-ality'
kind: rift
tested_version: v2288226
source_hint: Rick and Morty - Virtual Rick-ality v2288226
source_hint: 'Rick and Morty - Virtual Rick-ality'
engine: Unity
xr: OpenVR
status: works
@@ -1,7 +1,7 @@
package: studio.NewFolderGames.ToyMaster
title: Toy Master
tested_version: 1.1.2
source_hint: Toy Master v6+1.1.2
source_hint: Toy Master
engine: Unity
xr: OpenXR
status: works
+1 -1
View File
@@ -1,7 +1,7 @@
package: us.lighthaus.nanocellx
title: Nano
tested_version: '1.711'
source_hint: Nano v334+1.711
source_hint: Nano
engine: Unity
xr: OpenXR
status: works
+1 -1
View File
@@ -1,7 +1,7 @@
package: xyz.muware.hunt.vr
title: H.U.N.T
tested_version: 0.1.2
source_hint: H.U.N.T v11+0.1.2
source_hint: H.U.N.T
engine: Unity
xr: OpenXR
status: works
+39
View File
@@ -36,6 +36,7 @@ signatures:
use_alt: true
- id: swapchain-format
pattern: 'xrCreateSwapchain.*(-26|FORMAT_UNSUPPORTED)|swapchain format .* rejected'
unless: 'FrameBridge:\s+retry (samples=1|format=\d+) result=0' # the adapter's fallback worked
severity: error
diagnosis: The Frame rejected the swapchain format (GLES games must use sRGB formats, no MSAA).
suggest: [adapter.swapchain_fix]
@@ -64,6 +65,19 @@ signatures:
severity: error
diagnosis: The game needs Meta passthrough; the adapter emulates it.
suggest: [adapter.passthrough_emul, patch_force_passthrough]
- id: render-model-requested
pattern: 'dropped unsupported extension XR_FB_render_model'
severity: info
diagnosis: The game asks the headset for its controller models (XR_FB_render_model), which the Frame lacks, so it
shows its own (Quest) controllers or none. The adapter can serve the Steam Frame controllers instead.
suggest: [adapter.controller_models]
- id: controller-models-missing
pattern: 'FrameBridge: controller models not found'
severity: warning
diagnosis: Steam Frame controller models are on, but the converted models aren't in the game's files dir (the
agent found no Frame controller render models in SteamVR at install time; see the install log, or run the
agent's controller_models command).
suggest: []
- id: scene-missing
pattern: 'XR_FB_scene|XR_FB_spatial_entity.*(not supported|UNSUPPORTED)|xrQuerySpacesFB'
severity: warning
@@ -74,6 +88,30 @@ signatures:
severity: warning
diagnosis: Runtime lacks timespec time conversion (emulated by the current adapter build).
suggest: [frame.adapter]
- id: fossilize-renderpass
pattern: '#0\d pc [^\n]*libVkLayer_fossilize\.so[\s\S]{0,4000}?FVulkanRenderPass::FVulkanRenderPass'
severity: fatal
diagnosis: Lepton's Fossilize layer crashed while recording a render pass (the engine leaves an attachment reference's pNext uninitialized).
suggest: [frame.vk_sanitize]
supersedes: [native-crash]
- id: equirect-layers-dropped
pattern: 'new layer: type=100009100\d [^\n]*usable=0|new layer: type=1000018000 [^\n]*usable=0'
severity: warning
diagnosis: The game shows 360° (equirect) layers, e.g. a video player's theatre or 360° videos, which the Frame's
runtime can't composite, so they are missing. GLES games can get them back as panels around the player.
suggest: [adapter.equirect_emul]
- id: equirect-emul-disabled
pattern: 'equirect_emul: (disabled|drawing failed|not a GLES session)'
severity: warning
diagnosis: The 360° layer emulation switched itself off for this session (no shared GLES context, or drawing
failed); the 360° layers are dropped as without it. See the lines before it in the log.
suggest: []
- id: swapchain-size-abort
pattern: '#01 pc [^\n]*libopenxr_loader\.so \(xrCreateSwapchain\+|Wrong createInfo size'
severity: fatal
diagnosis: overport's OpenXR dispatcher aborted on a swapchain larger than 4096 px (video players, big textures).
suggest: [frame.swapchain_limit]
supersedes: [native-crash]
- id: native-crash
pattern: 'Fatal signal (\d+) \(SIG[A-Z]+\)'
severity: fatal
@@ -156,6 +194,7 @@ signatures:
severity: fatal
diagnosis: A DLL the game loads on demand is missing (Windows delay-load error). For Oculus Store games this is usually LibOVRPlatform64_1.dll, the Oculus Platform SDK that the Oculus app installs for the licence check; FramePort doesn't replace it, so such games need the Oculus app (PC mode).
suggest: []
supersedes: [unreal-crash, wine-crash] # the crash is this missing DLL; don't send the user after other fixes
- id: oculus-entitlement
kind: pcvr
pattern: '(?i)entitlement (check )?fail|ovr_PlatformInitialize.*(fail|error)|ovrPlatformInitialize_(NotEntitled|Uninitialized|PreLoaded|FileInvalid|SignatureInvalid|UnableToVerify)'
+21
View File
@@ -58,6 +58,27 @@ apart. "Build" = `pipeline.prepare_rift` (checks + Revive). Revive is a portable
- **Native binaries** (`artifacts/`): edit `native/…`, run `native/build.sh`, commit the new artifacts + SHA256SUMS,
run `frameport parity` to see which games change.
## Self-update (`updates.py`, `ui/updater.py`, `cli.py update`)
```
check() GitHub releases/latest (cached 6 h, drafts/prereleases skipped, "skipped" version remembered)
│ → Update(version, notes = release body incl. "What's new" from the annotated tag, asset for this OS, sums, wheel)
▼
install_kind() bundle (running exe inside FramePort.exe's folder / FramePort.app / FramePort/FramePort)
│ source (git checkout) → git pull --ff-only + uv sync wheel (uv tool / pipx / pip) → reinstall wheel
▼ bundle
prepare() <data>/updates/<ver>/: download → SHA256SUMS.txt check → extract to staged/ (ditto on macOS) → layout check
│ → Windows: same Authenticode signer as the running exe → ready.json
▼
apply() writes <data>/updates/apply.{ps1,sh}, starts it detached; FramePort quits. The script waits for the pid,
Windows: backs up the files it replaces (updates/<ver>/previous) and copies over the folder (the zip has
no folder of its own); macOS/Linux: mv target → .old, staged → target, rollback on failure, clears the
quarantine; then relaunches. Log: <data>/logs/update.log.
```
GUI: background check 10 s after start + every 6 h → sidebar card + Library bar → dialog with notes → job
`app-update` (waits for other jobs) → restart. "Install updates automatically": prepare in the background, apply in
`main()` before the window opens. CLI: once-a-day hint from the cached result (a daemon thread refreshes it), `frameport
update [--check] [--yes]`. CI runs `scripts/update_smoke.py` on every OS with the archive it just built.
## Dynamic data (fetched live, cached, bundled fallback)
overport release + patch list + patch titles (GitHub), Temurin JRE (Adoptium API), apksigner (Google repository index),
store artwork/titles (overport image API), catalog (optional remote), Lepton location/appid (Frame appmanifests),
+63
View File
@@ -0,0 +1,63 @@
# Diagnostics bundles and shared recipes
Two ways users feed results back, both without a GitHub token:
- **Share working config** (game menu, `frameport share-recipe <pkg>`): saves the recipe as a user catalog entry and
opens a prefilled issue from `.github/ISSUE_TEMPLATE/working-config.yml`. A maintainer checks it and adds the label
`catalog-accepted`. Then `.github/workflows/catalog-from-issue.yml` runs `scripts/catalog_from_issue.py`, which reads
only the YAML block, validates it, and writes `catalog/games/<pkg>.yaml`, and the workflow opens a PR.
- The PR step needs Settings → Actions → "Allow GitHub Actions to create and approve pull requests".
- Create the labels `working-config`, `catalog-accepted` and `bug` once.
- **Report a problem / Collect logs** (game menu, Settings, the failure pop-up, `frameport diag report|collect`): writes
a redacted zip and opens a prefilled `bug-report.yml` issue.
- GitHub has no API for issue attachments, so the user drags the zip in (25 MB max; the bundle stays under 24 MB).
- Prefilled links are capped at about 7.5k characters. Free text is trimmed first; the recipe is never cut.
Code: `src/frameport/diag/` (`redact.py`, `bundle.py`, `issue.py`), agent command `collect_diag` (agent ≥ 21),
`Target.collect_diag`, `core/applog.py` (app log + saved job logs).
## Bundle layout (schema 1)
```
README.md what's where (for whoever opens it)
manifest.json versions (app, agent, tools, SteamOS build, Proton), games, warnings, redaction counts
app/app.log the app's log (<data>/logs/app.log, rotated 2 MB × 3)
app/jobs/*.log saved GUI job logs (<data>/logs/jobs, last 30): build, install, test, ...
app/settings.json library settings, catalog sources
frame/info.json agent `info` (SteamOS build, Lepton, Proton, installed games, kernel keys)
frame/host.json OpenXR runtime + explicit layers, podman containers, containers.conf, uptime
frame/XRService-*.log the Frame's OpenXR runtime (SteamVR XRService) log, newest
games/<pkg>/entry.json library entry: analysis, recipe, build checks, installs, last_test (store text dropped)
games/<pkg>/recipe.yaml the recipe in catalog form; catalog-<origin>.yaml = the catalog entry it came from
games/<pkg>/triage.json newest local launch log re-triaged with the bundling app's signatures
games/<pkg>/logs/*.log launch-test logs kept on the PC (last 5)
games/<pkg>/package/ stand-in for the game files (no content):
apk_files.json every APK entry + size
AndroidManifest.xml decoded manifest
elf.json per lib/*.so: DT_NEEDED, ovr*/xr*/vrapi_/gl*/JNI exports + imports
files.json, pe.json Rift: file list; PE imports / delay imports of the exe and VR DLLs
games/<pkg>/target/ from the Frame (or the PC): launch.sh, settings.conf, deployment.json, launch.log,
launch-test.log (PC VR), lepton-steamlaunch-<appid>.log, logcat-{main,crash,system,...}.log,
ReviveInjector.txt / steam-<appid>.log / game-log-N.txt (PC VR), files.json (+ missing)
```
Each log keeps at most its last 4 MB (2 MB per file from the Frame).
## Redaction
`diag/redact.py` runs on every file and on the issue text.
- **Exact values:** the data dir → `<data>`, home dirs → `<home>`, user names → `<user>`, PC and Frame host names and
saved Frame addresses → `<host>`, Steam account ids from the Frame's `info` and the PC's Steam → `<steam-id>`, the
folders holding the user's game dumps → `<source>`.
- **Patterns:** IPv4 addresses (first octet ≥ 10, so version numbers survive), IPv6, MAC, SteamID64, `userdata/<id>`,
e-mail addresses (file names like `x@123.txt` excluded), and any `/home/<u>`, `/Users/<u>`, `C:\Users\<u>` or
`/mnt/c/Users/<u>`.
- **Kept:** generic accounts that identify no one: `steamos`, `steamuser` (Proton), `root`, `deck`.
## Debugging from a bundle (no game, no Frame, no GUI)
1. `frameport diag inspect <zip>` (`--json` for everything). It prints the versions and warnings, the last launch
test, and a fresh triage of the newest launch log with the current `catalog/triage.yaml`.
2. Match the findings and log lines against `docs/PLAYBOOK.md` (symptom → fix) and `docs/FRAME_RUNTIME.md`.
3. Check the analysis in `entry.json` (engine, XR API, `extra`: missing ovr symbols, features, Unreal version) and
`package/elf.json` against the heuristics in CLAUDE.md. Compare `recipe.yaml` with catalog games that use the same
engine and API.
4. Compare `manifest.json → env.frame.build_id` with the build the docs describe: SteamOS updates change the runtime.
5. A new failure signature means adding a patch module, a `triage.yaml` signature, a PLAYBOOK row and a unit test (see
Conventions). Then `diag inspect` on the same zip should report it.
+9 -1
View File
@@ -22,8 +22,16 @@
FB_swapchain_update_state, FB_space_warp, EXT_frame_synthesis, … (full list in any launch.log, tag overportOXR).
- Missing (emulated by the adapter): XR_FB_passthrough, XR_FB_scene / spatial_entity(_query/_storage/_container) /
scene_capture, XR_FB_composition_layer_image_layout (flip), XR_KHR_convert_timespec_time (returns
FUNCTION_UNSUPPORTED). Missing (dropped): XR_KHR_composition_layer_equirect2, XR_KHR_composition_layer_cylinder
FUNCTION_UNSUPPORTED). XR_FB_render_model is presumably missing too (not checked on the device yet); the adapter
emulates it only with `controller_models=1` and uses a native one if the runtime ever has it. Missing (dropped): XR_KHR_composition_layer_equirect2, XR_KHR_composition_layer_cylinder
(the VrApi bridge converts cylinders to quads).
- Layer types (checked 2026-09-30 in `/opt/steamvr/bin/androidarm64/vrclient.so`, the Android-side runtime Lepton
mounts at `/data/steamvr/runtime`): its compositors (`CSxrCompositorPrism`, `CSxrCompositorOpenVR`) only have
`ComposeLayerQuad` and `ComposeLayerProjection`; cube/cylinder/equirect/equirect2 exist only as enum names, so
there is nothing to switch on. It has a layer limit ("Exceeded the layer limit"; the value is logged by
`layer_debug` from `maxLayerCount`). The adapter emulates cylinders (strips) and, per game, equirect layers
(`equirect_emul`, an adapter projection layer). Quad layers are drawn above every projection layer regardless of
submission order (seen 2026-10-01: quads placed before 4XVR's projection layer covered it).
- Swapchain formats: GLES `GL_SRGB8_ALPHA8` (35907) / `GL_SRGB8` (35905) only, samples = 1. Vulkan: 43 (R8G8B8A8_SRGB)
and 50, not 37/44 (UNORM).
- Environment blend: ALPHA_BLEND available (greyscale passthrough cameras).
+49 -1
View File
@@ -9,6 +9,11 @@ missing** once: FramePort downloads its own Java runtime, the overport CLI and a
| Windows 10/11 (x64) | `FramePort-windows-x64.zip` | `FramePort.exe` |
| macOS (Apple Silicon) | `FramePort-macos-arm64.zip` | `FramePort.app` |
| Linux (x64) | `FramePort-linux-x64.tar.gz` | `FramePort/FramePort` (needs GTK 3) |
| Command line only (any OS with Python 3.11+) | `frameport-<version>-py3-none-any.whl` | `frameport --help` |
The command-line version installs with [uv](https://docs.astral.sh/uv/) (or pipx / pip) straight from a release, e.g.
`uv tool install https://github.com/spoopyghosty0/frameport/releases/download/v0.3.0/frameport-0.3.0-py3-none-any.whl`
(copy the wheel's link from the release page). `frameport --version` shows the installed version.
## First launch
@@ -25,6 +30,26 @@ not a paid one, so your OS warns the first time:
`xattr -dr com.apple.quarantine FramePort.app`.
- **Linux:** `tar xzf FramePort-linux-x64.tar.gz && ./FramePort/FramePort`.
## Updating
FramePort checks GitHub for a new release when it starts and every 6 hours (only the release information, nothing about
you is sent). When there is one, a **Update available** card appears in the sidebar and a bar at the top of the Library:
click **Update now** (or the card → **Update and restart**). FramePort downloads the new version, checks it against the
release's `SHA256SUMS.txt` (on Windows also that it carries the same signature as the running copy), closes, replaces
its program folder / `FramePort.app` and opens again as the new version. Your games, settings, signing keys and Frame
connection live in FramePort's data folder and are kept. If installs or uploads are running, the update waits until
they finish. **Later** hides that version (Settings → Updates → **Check for updates** still finds it).
Settings → **Updates**: switch off the automatic check, or turn on **Install updates automatically** (downloads new
versions in the background and installs them the next time FramePort starts — no clicks at all). If FramePort's folder
isn't writable (e.g. under Program Files), Update now opens the release page instead; download and extract it as
above. The update's log is `logs/update.log` in FramePort's data folder; the replaced files of a Windows update are kept
in `updates/<version>/previous` until the next update.
Command line: commands mention a new version at most once a day (on stderr). `frameport update` shows what's new and
updates (a bundle the same way as the app; a `uv tool`/pipx/pip install by reinstalling the release's wheel; a source
checkout with `git pull` + `uv sync`). `frameport update --check` only checks (exit code 10 = an update exists),
`--yes` skips the question. `FRAMEPORT_NO_UPDATE_CHECK=1` turns all checks off.
## Oculus Rift (PC VR) games
Scan a folder of Rift games (one folder per game; the game may sit a few levels down, next to installers and archives)
the same way as Quest dumps, or use **Add games → Add one game folder…**. FramePort finds the program that starts
@@ -35,12 +60,35 @@ Quest APKs are installed unchanged, Rift games start without Revive. If you inst
yourself (official installer), FramePort uses that one; otherwise it downloads its own portable copy (Tools shows which;
nothing is installed system-wide).
- **Play from this PC:** needs Windows with Steam and SteamVR. "Install on this PC" adds the game to your Steam
library (Steam closes and reopens once); stream it to the Frame with Steam Link / SteamVR.
library (Steam closes and reopens once); stream it to the Frame with Steam Link / SteamVR. If a game stutters
because it can't keep up with the headset's refresh rate, FramePort notices from SteamVR's records and, the next
time you press Play, lowers that game's refresh rate (e.g. 96 → 80 Hz) and turns on motion smoothing in SteamVR's
per-game settings (patch "Automatic SteamVR performance settings" on the game page, where you can also pick a
rate yourself).
- **Play on the Frame (experimental):** Frame → "Install Proton" (confirm the download in the headset), then "Install
on Frame (Proton)" on the game page.
- Games that use the Oculus Platform SDK (FramePort shows a note) check your Oculus license: they need the Oculus app
installed on the PC with a license you own, so they can't run on the headset.
## Videos, documents and mods for Quest games
Frame → **Send files** (or a game's menu → **Send files to this game…**) copies files or whole folders from this PC to
the Frame. **Videos**, **Downloads** and **Documents** are shared by every Quest game: they appear inside each game as
`/sdcard/Movies`, `/sdcard/Download` and `/sdcard/Documents` (they are the Frame's own `~/Videos`, `~/Downloads`,
`~/Documents`). A game's own storage (`/sdcard` of that game only) is for mods and saves. Apps find the files by
**browsing folders** (e.g. in a video player: local storage → Movies); their "all videos" lists stay empty because
Android's media index doesn't work on the Frame. Command line: `frameport frame send <files> --to videos` (see
`frameport frame storage`).
## Sharing a working game, reporting a problem
- **A game works?** Game menu (right-click in the Library, or "…" on its page) → **Share working config…**. FramePort
opens a prefilled GitHub issue with the game's recipe (patches and settings); check it and submit. Once accepted it
becomes a built-in recipe for everyone. No GitHub token and no game files are involved.
- **Something doesn't work?** Game menu → **Report a problem…** (or Settings → Problems & feedback for app issues).
FramePort saves a diagnostics zip to your Documents folder (logs, recipe, device details; IP addresses, user and
host names, home folders and Steam ids replaced by placeholders; no game files), shows it in a folder window and
opens a prefilled GitHub issue: drag the zip into the "Diagnostics" box and submit. **Collect logs** only saves the
zip. Command line: `frameport diag report <game>`, `frameport diag collect <game>`, `frameport share-recipe <game>`.
## Uninstalling
Settings → **Uninstall FramePort…** (or `frameport uninstall-app`) removes everything FramePort created: its data
folder (tools, library, artwork, cache, builds), the Steam shortcuts it added on this PC and, optionally, its games and
+18
View File
@@ -19,6 +19,7 @@ version is `catalog/triage.yaml` (used by `frameport test` / the Job screen); ke
| Unreal PC VR game on the Frame runs as a flat window although OpenXR works (no `LogHMD` OVRPlugin lines; Unreal logs nothing when it skips the Oculus plugin) / launch.log: `FramePort oculushmd: could not create the OculusHMDConnected event` | UE's OculusHMD (and LibOVR's `ovr_Detect`) only start when the Windows event `OculusHMDConnected` exists and is signalled; on a PC the Oculus service creates it. Revive hooks `OpenEventW` for it, but that relies on Detours patching Wine's (ARM64EC) kernelbase | `pcvr.oculus_unreal` (default for Unreal Rift games; PC VR counterpart of overport's `patch_oculus_unreal`): launch.sh runs the injector through `fp_oculushmd.exe`, which provides the real event until the game exits |
| PC VR game runs as a flat 2D window (no VR) | SteamVR was not running, so Revive/LibOVR had no runtime to bind to | FramePort now auto-starts SteamVR on Play; make sure your headset/SteamVR come up before the game |
| PC VR game crashed launching via Steam on the OpenXR backend | Revive's newer OpenXR backend was less reliable | PC now defaults to Revive's OpenVR (SteamVR) backend; reinstall to apply |
| Oculus PC VR game: `Unable to load LibOVRRT DLL` / `-3001` on the Frame | The game can't find a VR runtime (Revive's LoadLibrary hook doesn't work under Proton-arm64) | `pcvr.libovr_redirect` (default on) symlinks Revive's runtime as `LibOVRRT{64,32}_1.dll` in the exe dir — pure substitution; a build that checks the runtime signature then hits `-3021` (not bypassed) |
| Oculus Rift game won't run on the Steam Frame | Oculus/LibOVR game: needs Revive, whose hooks don't work under Proton-arm64, and FramePort won't defeat the Oculus runtime signature check | Play it on this PC (SteamVR + Revive). Only OpenVR/OpenXR-native Rift games run on the Frame |
| Un-cracked Oculus PC VR game: "Initializing OVR session" then exits / signature check on the runtime | Revive's hooks don't install on Proton-arm64; the Oculus shim rejects the unsigned Revive runtime | Not runnable on the Frame without the repack's crack extracted (not done by FramePort); use the PC version |
| PC VR game: `Failed to initialize Oculus API (-3001)` / `Unable to load LibOVRRT DLL` | Revive's LoadLibrary hook doesn't work under Proton arm64 (ARM64EC kernelbase); the game's LibOVR shim finds no runtime DLL | Symlink `LibOVRRT64_1.dll` → Revive's DLL in the prefix's system32 (manual so far) → then -3021 (runtime signature check; open) |
@@ -34,6 +35,19 @@ version is `catalog/triage.yaml` (used by `frameport test` / the Job screen); ke
| `xrCreateSwapchain` -26 / format unsupported (GLES) | Frame takes only sRGB formats, no MSAA | adapter `swapchain_fix` (default on) |
| Frames rejected, "Waiting…" forever | a layer uses a failed swapchain or an extension that isn't enabled (e.g. equirect2) | adapter `layer_fix` (default on) |
| `xrConvert…TimeKHR` FUNCTION_UNSUPPORTED spam; VrApi bridge stalls before recenter | runtime lacks timespec conversion | current adapter emulates it |
| Crash on the first frame, backtrace `libVkLayer_fossilize.so` ← `FVulkanRenderPass::FVulkanRenderPass` (crash logcat) | the engine leaves the pNext of unused Vulkan attachment references uninitialized; Lepton always loads Steam's Fossilize layer (guest is userdebug, so even a non-debuggable APK gets it), which follows the pointer | `frame.vk_sanitize` (default on for Unreal; Vulkan shim `libfp_vk.so`; triage `fossilize-renderpass`), e.g. Deadpool VR |
| SIGABRT right after start, backtrace `libopenxr_loader.so (xrCreateSwapchain+…)` | overport's dispatcher aborts on swapchains > 4096 px ("Wrong createInfo size"); video players use 7680×3840 theatre textures | `frame.swapchain_limit` (default on; guard → 16384 px; triage `swapchain-size-abort`), e.g. 4XVR |
| Video/menu panel missing, log `dropped N unusable layer(s)` with cylinder (1000017000) or equirect2 (1000091000) layers | the Frame runtime lacks XR_KHR_composition_layer_cylinder/equirect(2)/cube (its SteamVR runtime only composites quad + projection layers) | adapter shows cylinders as flat strips (setting `cylinder_strips`, default on); 360° equirect layers (theatres, 360° videos): `adapter.equirect_emul` (GLES only, per game) |
| 360° theatre / 360° video black or missing (e.g. 4XVR) | equirect layers dropped | `adapter.equirect_emul=1`: a worker thread with a shared GLES context converts each 360° image to a cube map when it changes and draws one adapter projection layer from it for every frame with exactly that frame's views; it replaces the 360° layers in place, so the game's own projection layer (balcony, controllers, 360° videos it draws itself) stays on top. Quads can't be used: the Frame draws quad layers above every projection layer whatever the order. Log: `first 360 view ready`, `in 5 s: N 360 image update(s) … M view redraw(s)`. Upside down / mirrored / behind you: `equirect_flip` 1/2/4 (`frameport settings <pkg> equirect_flip=1`, no rebuild). Never Vulkan (a Vulkan renderer hung the Frame's GPU in AC Nexus) |
| Unity game hangs right after its first frames, no `pacing:` lines; SIGQUIT dump shows UnityMain in a game library's `JNI_OnLoad` → `usleep` (e.g. SKYBOX: `libskybox.so`, `SignatureChecker`) | the game checks its APK signing certificate; every port is re-signed | can't be fixed without defeating anti-tamper (FramePort doesn't): mark "Can't run". Diagnose hangs: `podman exec <container> kill -3 <pid>` writes all thread stacks to launch.log |
| Video player doesn't list sent videos (e.g. 4XVR "Internal Storage" only shows some) | the player lists its own /sdcard folder (4XVR: /sdcard/4XPlayer), not /sdcard/Movies; Android's media index doesn't work in Lepton | GUI game page "Add videos" / "Add videos & files…" (Videos + the app's own folder, hard links) or `frameport frame send <files> --app <pkg>` |
| One eye grey in a stereo video, log `xrCreateSwapchain … result=-10` | the runtime refused a swapchain (XR_ERROR_LIMIT_REACHED) | fewer/smaller swapchains: lower `equirect_res`; unresolved |
| Menu/screen jumps to where you look (e.g. 4XVR) | the app re-creates LOCAL spaces (4XVR: every 2–4 s) and the Frame places them at the current head yaw, or the app recentres after the Frame's brief focus dips | turn on `adapter.layer_debug`, check `that LOCAL space sits at … deg` vs `focus_hold: hid a … ms focus dip`; fixes: `adapter.stable_local` (new LOCAL spaces line up with the first) / `adapter.focus_hold` (hides dips < 600 ms after 3 s focused; never at start-up: a global debounce broke AC Nexus) |
| Pointer misses menu items | the Frame's aim pose differs from Touch's | `adapter.layer_debug` logs `aim in grip … pitch/yaw`; correct with `aim_pitch`/`aim_yaw`/`aim_forward` (`frameport settings`, no rebuild) |
| Video stutters although fps is steady | video frame rate doesn't divide the refresh rate (30 fps at 72 Hz) | `adapter.refresh_rate` (e.g. 90 for 30 fps, 72 for 24 fps); `layer_debug` logs the offered rates and the app's own requests |
| PC VR game judders/stutters although the GPU keeps up; vrcompositor.txt "Timed out. N total" high or frames dropped | the game misses the headset's refresh (e.g. 96 Hz = 10.4 ms; Stormland's slow frames take 10.7 ms) | `pcvr.steamvr_tuning` (default on): next Play sets SteamVR per-app `preferredRefreshRate` + `motionSmoothingOverride` via `fp_vrsettings.exe` |
| Quest app keeps recentering / snapping the view when you turn your head; log shows session state 5→4→3→4→5 within a second | the Frame briefly takes focus; the app recenters on focus changes | unfixed: hiding the dips (debounce) made AC Nexus stay black, so it was removed |
| Video player / app finds no local videos; MediaProvider "Requested path /home/steamos/... doesn't appear under ..." | Lepton's /sdcard is a symlink to a host path, so Android's media index rejects every file | send files with Frame → Send files (~/Videos = /sdcard/Movies) and browse folders in the app |
| Game (Unity, GLES) freezes, `zink: DEVICE LOST` | multisampled render-to-texture hangs the GPU | `frame.unity_no_msaa`; if it persists: unfixable → PC version |
| Setup/intro loops every launch (Espire 2) | save folders created without write permission | launcher repairs permissions every 2 s (built in) |
| VrApi bridge: never enters VR | Frame reaches FOCUSED later than Quest; tracking only when worn | bridge waits 30 s; test in the headset |
@@ -47,11 +61,15 @@ version is `catalog/triage.yaml` (used by `frameport test` / the Job screen); ke
| Upside-down image in a GL bridge game | GL images start at the bottom row | fixed in the bridge (swap angleUp/Down for GL chains) |
| UI panels upside down (AC Nexus) | XrCompositionLayerImageLayoutFB VERTICAL_FLIP unsupported | adapter `flip_emul=1` (default); rotating quads makes them vanish |
| Passthrough black (BAM) | XR_FB_passthrough missing | adapter `passthrough_emul=1` (default) + `patch_force_passthrough` for MR-only games |
| Quest Touch controllers (or none) shown in a game that uses Meta's runtime controller models | XR_FB_render_model missing on the Frame | adapter `controller_models=1`: the agent converts the Frame's SteamVR controller models to glb at install, the adapter serves them. Games with their own controller meshes aren't affected (none of the 34 catalog games use runtime models) |
| `overportOXR: Unknown proc addr: xr…` for a function the adapter emulates | overport's dispatcher only forwards functions in its own table | route the plugin's lookups through `native/xrshim` (done for XR_FB_render_model when `controller_models=1`) |
| MR game stuck waiting for room data (Demeter) | no Meta scene API | adapter `scene_emul=1` (+ `frame.meta_permissions`) |
| Hand-tracking game janky (Silhouette) | Frame synthesizes hands from controllers | `controller_fix=0` passes hands through; not really fixable |
| Eye distortion while moving (Arcsmith, Time Stall) | unknown (not eye swap, tracking, Valve layers, depth or pacing) | unresolved |
## Debugging techniques that worked
- A user's problem report: `frameport diag inspect <FramePort-diag-*.zip>` re-triages its launch log with the current
signatures; the zip has the recipe, analysis, ELF/PE imports, Frame logs and versions (docs/DIAGNOSTICS.md).
- Read `<base>/launch.log` (logcat mirror). Filter the game's pid: `Start proc <pid>:<package>`.
- The adapter logs as `FrameBridge` (settings, xrCreateInstance result, swapchain retries, pacing fps).
- For GLES/GLAD engines, wrap `eglGetProcAddress` to see shader compile errors (build the shim with `-DGLSHIM_TRACE`
+2 -1
View File
@@ -7,12 +7,13 @@ embeds debug paths (`-g`) and the dex depends on the d8 version, so those differ
| Dir | Artifact | What / why |
|---|---|---|
| `adapter/` | `{arm64-v8a,armeabi-v7a}/libopenxr_loader_generic.so` | **FrameBridge**: replaces overport's generic loader (which is renamed `libopenxr_loader_original.so`) and fixes Steam Frame runtime gaps. Hooks xrCreateInstance, swapchains, xrEndFrame, spaces, xrPollEvent, … everything else is forwarded by `gen_forwarders.py`-generated tail calls. `scene_emu.c` = Meta scene/spatial-entity emulation; `flip_vk.c` = Vulkan blit for VERTICAL_FLIP quads. Settings: `libframe_settings.so` in the APK + `settings.conf`/`framebridge.conf` on the Frame. Hook technique from Quest2Frame's `frame_bridge.c` (GPL-3.0). |
| `adapter/` | `{arm64-v8a,armeabi-v7a}/libopenxr_loader_generic.so` | **FrameBridge**: replaces overport's generic loader (which is renamed `libopenxr_loader_original.so`) and fixes Steam Frame runtime gaps. Hooks xrCreateInstance, swapchains, xrEndFrame, spaces, xrPollEvent, … everything else is forwarded by `gen_forwarders.py`-generated tail calls. `scene_emu.c` = Meta scene/spatial-entity emulation; `flip_vk.c` = Vulkan blit for VERTICAL_FLIP quads. `session_fixes.c` = per-game session fixes, all off by default and hooked only when on (`layer_debug` diagnostics, `stable_local`, `focus_hold`, aim correction `aim_pitch/aim_yaw/aim_forward`, `refresh_rate`); `layer_emul_gl.c` = `equirect_emul` (GLES sessions only): 360° equirect/equirect2 layers become one adapter projection layer, drawn by a worker thread with its own EGL context shared with the app's: each 360° image is converted to a cube map only when it changes, and the view is redrawn only after a 4° head turn (GL/EGL resolved with dlopen, so Vulkan games never load them); `layer_math.h` = their pose/face math, tested on the host by `tests/test_layer_emul.py`. `render_model.c` = XR_FB_render_model emulation (setting `controller_models`, off by default): serves `files/framebridge/controller_{left,right}.glb`, which the agent converts on the Frame from SteamVR's own Frame controller render models (never shipped by FramePort); tested on the host by `tests/test_render_model.py`. Settings: `libframe_settings.so` in the APK + `settings.conf`/`framebridge.conf` on the Frame. Hook technique from Quest2Frame's `frame_bridge.c` (GPL-3.0). |
| `vrapi-bridge/` | `arm64-v8a/libvrapi.so` | VrApi → OpenXR bridge from [Android-XR-Bridge/OVRPort](https://github.com/Android-XR-Bridge/OVRPort) `native/vrapi` at 5e7df52 (GPL-3.0, `LICENSE.upstream`), with our changes in `upstream-patches/`: GLES sessions + GL texture swapchains, cylinder→quad layers, GL vertical flip, UNORM↔sRGB format twins, 30 s VR-mode deadline, VALID-only recenter, loading-icon layers skipped, diagnostics behind `-DOVP_GL_DIAG`. |
| `platformcompat/` | `arm64-v8a/libovrplatformcompat.so` | Real `ovrMessageType_ToString` (same fork, `native/platform`). |
| `glshim/` | `arm64-v8a/libglshim.so` | Mesa GLSL compatibility for GLAD engines (hooks eglGetProcAddress): comments out `#pragma` before `#extension`, enables `GL_EXT_shader_implicit_conversions`, hides GL_OVR_multiview (`gl_hide_multiview`, default 1) and logs failed shaders. `-DGLSHIM_TRACE` adds per-FBO draw/error tracing. |
| `xrlayer/` | `linux-arm64/libxr_frameport_timefix.so` + `XR_APILAYER_FRAMEPORT_timefix.json` | OpenXR API layer for Windows PC VR games under Proton on the Frame (glibc aarch64, built freestanding with the NDK's clang), on by default (patch `pcvr.xr_timefix`). Retries `xrCreateInstance` as an OpenXR 1.0 app when the runtime rejects 1.1 (the Frame's SteamVR runtime does, and Proton 11's VR helper asks for 1.1). Also emulates `xrConvertTimespecTimeToTimeKHR`/`xrConvertTimeToTimespecTimeKHR` if the runtime refuses them (the Frame's Android runtime does; its Linux runtime, used by Proton, supports them as of 2026-09-29 — so this part is only a fallback; Proton's wineopenxr needs them for `XR_KHR_win32_convert_performance_counter_time`, which Revive requires) with the adapter's xrWaitFrame-calibrated offset, and drops the extension from xrCreateInstance if the runtime rejects it. Enabled per game by the Proton launch.sh (`XR_API_LAYER_PATH`, `XR_ENABLE_API_LAYERS`). `tests/test_xrlayer.py` builds it for x86_64 and drives it via ctypes. |
| `oculushmd/` | `win-x64/fp_oculushmd.exe` | PC VR counterpart of overport's `patch_oculus_unreal` (patch `pcvr.oculus_unreal`, default for Unreal Rift games on the Frame). Unreal's OculusHMD and LibOVR's `ovr_Detect` only start when the Windows named event `OculusHMDConnected` exists and is signalled (the Oculus service creates it). `fp_oculushmd.exe <command line>` creates it (manual reset, signalled), runs the command (Revive's injector) in a job object and keeps the event until every process in the job — the game and its children — has exited (fallback without job support: 3 minutes); returns the command's exit code and logs `FramePort oculushmd: …` to stderr (launch.log). Freestanding Windows x64 console exe (no CRT, no Windows SDK): the NDK's clang + `lld-link /Brepro` with a kernel32 import library generated by `llvm-dlltool`, so it's byte-reproducible. Tested on Windows from WSL with a build whose event name is `-DEVENT_NAME=L"…"` (the Oculus service owns the real event on a PC with the Oculus app). |
| `xrshim/` | `arm64-v8a/libframe_xrshim.so` | FrameBridge extension shim, only in builds with `controller_models=1`. overport's dispatcher (`libopenxr_loader.so`) answers `xrGetInstanceProcAddr` from a fixed table and refuses everything else (`overportOXR: Unknown proc addr: xrLoadRenderModelFB`), so the adapter never sees XR_FB_render_model lookups. Meta's OVRPlugin gets the function with `dlopen("libopenxr_loader.so")` + `dlsym`, so FramePort rewrites that `.rodata` string in `libOVRPlugin.so` (same length, in place) to `libframe_xrshim.so`. The shim returns the adapter's emulated functions (`framebridge_extension_proc`) and forwards every other name to overport. A DT_NEEDED interposer does not work here (dlsym on a handle searches that library first); tried and dropped. |
| `java-stubs/` | `dex/oculusos-stubs.dex` | No-op `com.oculus.os.AnalyticsEvent` / `UnifiedTelemetryLogger` for native code that looks them up. |
The ovr_* stub library is *not* prebuilt: `src/frameport/analysis/stubgen.py` generates it per game from the exact
+272 -23
View File
@@ -23,7 +23,13 @@
// (passthrough_emul);
// * optionally tells the app its reference spaces changed once the session is focused, so apps that
// created them before tracking started recreate them (respace_kick);
// * optionally flips quad layers vertically for apps whose UI panels show upside down (flip_quads).
// * optionally flips quad layers vertically for apps whose UI panels show upside down (flip_quads);
// * optionally serves Steam Frame controller models through XR_FB_render_model (controller_models,
// render_model.c);
// * per-game session fixes (session_fixes.c, all off by default): layer_debug diagnostics, stable_local,
// focus_hold, aim pose correction (aim_pitch/aim_yaw/aim_forward), refresh_rate;
// * optionally shows 360° (equirect/equirect2) layers as cube-face quads drawn by a worker thread with a shared
// GLES context (equirect_emul, layer_emul_gl.c; GLES sessions only, off by default).
//
// Settings (key=value lines), later sources override earlier ones:
// <libdir>/libframe_settings.so
@@ -34,6 +40,7 @@
#include <openxr/openxr.h>
#include <android/log.h>
#include <dlfcn.h>
#include <math.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
@@ -59,6 +66,7 @@ static int respace_kick = 0;
static int strip_depth = 0;
static int flip_quads = 0;
static int flip_emul_setting = 1;
static int cylinder_strips_on = 1; // show cylinder layers as flat quad strips (cylinder_strips)
static int scene_emul; // scene emulation setting (per game)
static float scene_height = 2.5f; // scene emulation ceiling height (m)
static float scene_width, scene_depth; // optional room size override (m)
@@ -68,6 +76,21 @@ static int runtime_has_image_layout; // runtime supports XR_FB_composition_laye
// Layer types whose extension the runtime lacks (dropped at xrCreateInstance) are removed from frames.
static int no_equirect, no_equirect2, no_cylinder, no_cube;
static int runtime_has_fb_passthrough, emulate_passthrough, alpha_blend_failed;
static int controller_models; // serve Frame controller models via XR_FB_render_model (render_model.c)
// Per-game settings, all off by default (session_fixes.c, layer_emul_gl.c).
static int layer_debug; // diagnostics: layers, swapchains, session states, spaces, aim/grip, refresh rates
static int stable_local; // keep every LOCAL space the app creates on the session-start origin
static int focus_hold; // hide brief focus dips once the session has been focused for a while
static float aim_pitch, aim_yaw, aim_forward; // aim pose correction (degrees, degrees, metres)
static float refresh_rate; // requested display refresh rate (Hz), 0 = the app's choice
static int equirect_emul; // show 360 layers as cube faces (GLES)
static int equirect_face = 1536; // max cube map face size (px)
static int equirect_res = 1536; // projection image size per eye (px)
static int equirect_flip; // source orientation fix: 1 upside down, 2 mirrored, 4 turned 180 degrees
static float equirect_fps = 60; // max redraws per second per 360 layer (0 = no limit)
static int equirect_stereo; // 0 auto (mono if the layer limit can't hold both eyes), 1 stereo, 2 mono
static XrTime last_predicted_time;
static void render_model_init(const char *package);
static void read_settings(const char *path) {
FILE *f = fopen(path, "r");
@@ -87,10 +110,25 @@ static void read_settings(const char *path) {
if (sscanf(line, "strip_depth=%f", &value) == 1) strip_depth = value != 0;
if (sscanf(line, "flip_quads=%f", &value) == 1) flip_quads = value != 0;
if (sscanf(line, "flip_emul=%f", &value) == 1) flip_emul_setting = value != 0;
if (sscanf(line, "cylinder_strips=%f", &value) == 1) cylinder_strips_on = value != 0;
if (sscanf(line, "scene_emul=%f", &value) == 1) scene_emul = value != 0;
if (sscanf(line, "scene_height=%f", &value) == 1 && value > 1.5f && value < 5.0f) scene_height = value;
if (sscanf(line, "scene_width=%f", &value) == 1 && value > 0.5f && value < 20.0f) scene_width = value;
if (sscanf(line, "scene_depth=%f", &value) == 1 && value > 0.5f && value < 20.0f) scene_depth = value;
if (sscanf(line, "controller_models=%f", &value) == 1) controller_models = value != 0;
if (sscanf(line, "layer_debug=%f", &value) == 1) layer_debug = value != 0;
if (sscanf(line, "stable_local=%f", &value) == 1) stable_local = value != 0;
if (sscanf(line, "focus_hold=%f", &value) == 1) focus_hold = value != 0;
if (sscanf(line, "aim_pitch=%f", &value) == 1 && fabsf(value) <= 90) aim_pitch = value;
if (sscanf(line, "aim_yaw=%f", &value) == 1 && fabsf(value) <= 90) aim_yaw = value;
if (sscanf(line, "aim_forward=%f", &value) == 1 && fabsf(value) <= 0.5f) aim_forward = value;
if (sscanf(line, "refresh_rate=%f", &value) == 1 && (value == 0 || (value >= 60 && value <= 144))) refresh_rate = value;
if (sscanf(line, "equirect_emul=%f", &value) == 1) equirect_emul = value != 0;
if (sscanf(line, "equirect_face=%f", &value) == 1 && value >= 256 && value <= 2730) equirect_face = (int)value;
if (sscanf(line, "equirect_res=%f", &value) == 1 && value >= 512 && value <= 4096) equirect_res = (int)value;
if (sscanf(line, "equirect_flip=%f", &value) == 1 && value >= 0 && value <= 7) equirect_flip = (int)value;
if (sscanf(line, "equirect_fps=%f", &value) == 1 && value >= 0 && value <= 144) equirect_fps = value;
if (sscanf(line, "equirect_stereo=%f", &value) == 1 && value >= 0 && value <= 2) equirect_stereo = (int)value;
}
fclose(f);
LOG("settings read from %s", path);
@@ -127,10 +165,16 @@ static void initialize(void) {
}
const char *env = getenv("FRAMEBRIDGE_CONFIG");
if (env && *env) read_settings(env);
if (controller_models && *process && !strchr(process, '/')) render_model_init(process);
LOG("scale=%.2f foveation_fix=%d controller_fix=%d swapchain_fix=%d layer_fix=%d mutable_fix=%d swap_eyes=%d passthrough_emul=%d respace_kick=%d flip_quads=%d loader=%s",
LOG("scale=%.2f foveation_fix=%d controller_fix=%d swapchain_fix=%d layer_fix=%d mutable_fix=%d swap_eyes=%d passthrough_emul=%d respace_kick=%d flip_quads=%d controller_models=%d loader=%s",
scale, foveation_fix, controller_fix, swapchain_fix, layer_fix, mutable_fix, swap_eyes, passthrough_emul,
respace_kick, flip_quads, next_gipa ? "OK" : (dlerror() ?: "FAILED"));
respace_kick, flip_quads, controller_models, next_gipa ? "OK" : (dlerror() ?: "FAILED"));
if (layer_debug || stable_local || focus_hold || aim_pitch || aim_yaw || aim_forward || refresh_rate || equirect_emul)
LOG("per-game: layer_debug=%d stable_local=%d focus_hold=%d aim=%.1f/%.1f/%.3f refresh_rate=%.0f equirect_emul=%d "
"(face %d, res %d, flip %d, fps %.0f, stereo %d)", layer_debug, stable_local, focus_hold, aim_pitch, aim_yaw,
aim_forward, refresh_rate, equirect_emul, equirect_face, equirect_res, equirect_flip, equirect_fps,
equirect_stereo);
}
static PFN_xrVoidFunction lookup(XrInstance instance, const char *name) {
@@ -142,6 +186,7 @@ static PFN_xrVoidFunction lookup(XrInstance instance, const char *name) {
}
#include "scene_emu.c"
#include "render_model.c"
XRAPI_ATTR XrResult XRAPI_CALL xrCreateInstance(const XrInstanceCreateInfo *info, XrInstance *instance) {
PFN_xrCreateInstance fn = (PFN_xrCreateInstance)lookup(XR_NULL_HANDLE, "xrCreateInstance");
@@ -172,7 +217,7 @@ XRAPI_ATTR XrResult XRAPI_CALL xrCreateInstance(const XrInstanceCreateInfo *info
}
XrInstanceCreateInfo fixed = *info;
const char **names = calloc(info->enabledExtensionCount + 1, sizeof(*names));
const char **names = calloc(info->enabledExtensionCount + 2, sizeof(*names));
if (!names) { free(available); return XR_ERROR_OUT_OF_MEMORY; }
uint32_t kept = 0;
for (uint32_t i = 0; i < info->enabledExtensionCount; ++i) {
@@ -184,6 +229,9 @@ XRAPI_ATTR XrResult XRAPI_CALL xrCreateInstance(const XrInstanceCreateInfo *info
else if (scene_emul && is_scene_extension(ext)) {
if (!emulate_scene) LOG("emulating Meta scene/spatial-entity extensions from the guardian bounds");
emulate_scene = 1;
} else if (controller_models && render_models_available && !strcmp(ext, XR_FB_RENDER_MODEL_EXTENSION_NAME)) {
emulate_render_model = 1;
LOG("emulating XR_FB_render_model with Steam Frame controller models");
} else if (passthrough_emul && !strcmp(ext, "XR_FB_passthrough")) {
emulate_passthrough = 1;
LOG("emulating XR_FB_passthrough with alpha-blended environment");
@@ -193,6 +241,12 @@ XRAPI_ATTR XrResult XRAPI_CALL xrCreateInstance(const XrInstanceCreateInfo *info
names[kept++] = "XR_KHR_android_create_instance";
LOG("added %s", "XR_KHR_android_create_instance");
}
if (refresh_rate > 0) { // the refresh_rate setting needs XR_FB_display_refresh_rate even if the app doesn't use it
int requested = 0, offered = 0;
for (uint32_t i = 0; i < kept; ++i) requested |= !strcmp(names[i], "XR_FB_display_refresh_rate");
for (uint32_t j = 0; available && j < available_count; ++j) offered |= !strcmp(available[j].extensionName, "XR_FB_display_refresh_rate");
if (!requested && offered) { names[kept++] = "XR_FB_display_refresh_rate"; LOG("added XR_FB_display_refresh_rate (refresh_rate)"); }
}
fixed.enabledExtensionNames = names;
fixed.enabledExtensionCount = kept;
for (uint32_t j = 0; available && j < available_count; ++j)
@@ -290,6 +344,13 @@ static void forget_swapchain(XrSwapchain handle) {
static void flip_on_create_swapchain(XrSwapchain handle, const XrSwapchainCreateInfo *info);
static void flip_on_destroy(XrSwapchain handle);
static void emul_on_create_swapchain(XrSwapchain handle, const XrSwapchainCreateInfo *info);
static void emul_on_destroy_swapchain(XrSwapchain handle);
static int emul_virtual_create(XrSession session, const XrSwapchainCreateInfo *info, XrSwapchain *out);
static int emul_is_virtual(XrSwapchain handle);
static void emul_virtual_destroy(XrSwapchain handle);
static XrResult emul_virtual_enumerate(XrSwapchain handle, uint32_t capacity, uint32_t *count, XrSwapchainImageBaseHeader *images);
static void emul_on_acquire(XrSwapchain handle, uint32_t index);
static int known_swapchain(XrSwapchain handle) {
int found = 0;
@@ -312,11 +373,21 @@ XRAPI_ATTR XrResult XRAPI_CALL xrCreateSwapchain(XrSession session, const XrSwap
fixed.next = p;
}
if (mutable_fix) fixed.usageFlags |= XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT;
if (equirect_emul && swapchain && emul_virtual_create(session, &fixed, swapchain)) {
remember_swapchain(*swapchain);
emul_on_create_swapchain(*swapchain, &fixed);
return XR_SUCCESS;
}
XrResult result = fn(session, &fixed, swapchain);
LOG("xrCreateSwapchain %ux%u format=%lld samples=%u array=%u faces=%u usage=0x%llx result=%d", fixed.width,
fixed.height, (long long)fixed.format, fixed.sampleCount, fixed.arraySize, fixed.faceCount,
(unsigned long long)fixed.usageFlags, result);
if (XR_SUCCEEDED(result)) { remember_swapchain(*swapchain); flip_on_create_swapchain(*swapchain, &fixed); return result; }
LOG("xrCreateSwapchain %ux%u format=%lld samples=%u array=%u faces=%u usage=0x%llx flags=0x%llx result=%d",
fixed.width, fixed.height, (long long)fixed.format, fixed.sampleCount, fixed.arraySize, fixed.faceCount,
(unsigned long long)fixed.usageFlags, (unsigned long long)fixed.createFlags, result);
if (XR_SUCCEEDED(result)) {
remember_swapchain(*swapchain);
flip_on_create_swapchain(*swapchain, &fixed);
emul_on_create_swapchain(*swapchain, &fixed);
return result;
}
if (!swapchain_fix) return result;
// Frame's runtime rejects some GLES formats (GL_RGBA8) and MSAA swapchains (overport #71).
@@ -333,7 +404,11 @@ XRAPI_ATTR XrResult XRAPI_CALL xrCreateSwapchain(XrSession session, const XrSwap
LOG(" retry format=%lld result=%d", (long long)replacement, result);
}
}
if (XR_SUCCEEDED(result)) { remember_swapchain(*swapchain); flip_on_create_swapchain(*swapchain, &fixed); }
if (XR_SUCCEEDED(result)) {
remember_swapchain(*swapchain);
flip_on_create_swapchain(*swapchain, &fixed);
emul_on_create_swapchain(*swapchain, &fixed);
}
return result;
}
@@ -342,23 +417,73 @@ XRAPI_ATTR XrResult XRAPI_CALL xrDestroySwapchain(XrSwapchain swapchain) {
if (!fn) return XR_ERROR_FUNCTION_UNSUPPORTED;
forget_swapchain(swapchain);
flip_on_destroy(swapchain);
emul_on_destroy_swapchain(swapchain);
if (equirect_emul && emul_is_virtual(swapchain)) { emul_virtual_destroy(swapchain); return XR_SUCCESS; }
return fn(swapchain);
}
// ---- cylinder layers (XR_KHR_composition_layer_cylinder), which the Frame runtime lacks: shown as a few flat quads
// (chords of the arc), each showing its share of the image. The runtime composites them from the app's own image at
// full resolution, and they stay within centimetres of where the app aims its pointer at the curved surface.
static XrVector3f strip_rotate(XrQuaternionf q, XrVector3f v) { // v' = v + 2w(u x v) + 2 u x (u x v)
XrVector3f u = {q.x, q.y, q.z}, t = {2 * (u.y * v.z - u.z * v.y), 2 * (u.z * v.x - u.x * v.z), 2 * (u.x * v.y - u.y * v.x)};
return (XrVector3f){v.x + q.w * t.x + (u.y * t.z - u.z * t.y), v.y + q.w * t.y + (u.z * t.x - u.x * t.z),
v.z + q.w * t.z + (u.x * t.y - u.y * t.x)};
}
static XrQuaternionf strip_mul(XrQuaternionf a, XrQuaternionf b) {
return (XrQuaternionf){a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y, a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x,
a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w, a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z};
}
// Returns the number of quads written to out (0 = not possible). budget = layers still allowed in the frame.
static int cylinder_strips(const XrCompositionLayerCylinderKHR *c, XrCompositionLayerQuad *out, int budget) {
if (c->centralAngle <= 0 || c->aspectRatio <= 0) return 0;
float r = c->radius > 0 && c->radius < 1e4f ? c->radius : 3.0f;
int n = (int)ceilf(c->centralAngle / 0.26f); // ~15 degrees per strip
if (n > 8) n = 8;
if (n > budget) n = budget;
if (n < 1) return 0;
float a = c->centralAngle / (float)n, height = r * c->centralAngle / c->aspectRatio;
const XrRect2Di rect = c->subImage.imageRect;
for (int i = 0; i < n; ++i) {
float phi = -c->centralAngle / 2 + (i + 0.5f) * a; // + = towards +X (the image's right)
XrQuaternionf yaw = {0, sinf(-phi / 2), 0, cosf(-phi / 2)};
XrPosef pose;
pose.orientation = strip_mul(c->pose.orientation, yaw);
XrVector3f d = strip_rotate(pose.orientation, (XrVector3f){0, 0, -r * cosf(a / 2)});
pose.position = (XrVector3f){c->pose.position.x + d.x, c->pose.position.y + d.y, c->pose.position.z + d.z};
int32_t x0 = rect.offset.x + (int32_t)((int64_t)rect.extent.width * i / n);
int32_t x1 = rect.offset.x + (int32_t)((int64_t)rect.extent.width * (i + 1) / n);
XrSwapchainSubImage sub = c->subImage;
sub.imageRect = (XrRect2Di){{x0, rect.offset.y}, {x1 - x0, rect.extent.height}};
out[i] = (XrCompositionLayerQuad){XR_TYPE_COMPOSITION_LAYER_QUAD, c->next, c->layerFlags, c->space,
c->eyeVisibility, sub, pose, {2 * r * sinf(a / 2), height}};
}
static int logged;
if (logged++ < 3) LOG("cylinder layer -> %d quad strips (r=%.2f angle=%.2f)", n, r, c->centralAngle);
return n;
}
// A layer is usable if every swapchain it references was created successfully.
// Swapchains the runtime can show: created by it (adapter-served 360 pictures only feed the adapter's own drawing).
static int runtime_swapchain(XrSwapchain handle) {
return known_swapchain(handle) && !(equirect_emul && emul_is_virtual(handle));
}
static int layer_usable(const XrCompositionLayerBaseHeader *layer) {
switch (layer->type) {
case XR_TYPE_COMPOSITION_LAYER_PROJECTION: {
const XrCompositionLayerProjection *p = (const XrCompositionLayerProjection *)layer;
for (uint32_t v = 0; v < p->viewCount; ++v)
if (!known_swapchain(p->views[v].subImage.swapchain)) return 0;
if (!runtime_swapchain(p->views[v].subImage.swapchain)) return 0;
return 1;
}
case XR_TYPE_COMPOSITION_LAYER_QUAD:
return known_swapchain(((const XrCompositionLayerQuad *)layer)->subImage.swapchain);
return runtime_swapchain(((const XrCompositionLayerQuad *)layer)->subImage.swapchain);
case XR_TYPE_COMPOSITION_LAYER_CYLINDER_KHR:
if (no_cylinder) return 0;
return known_swapchain(((const XrCompositionLayerCylinderKHR *)layer)->subImage.swapchain);
return runtime_swapchain(((const XrCompositionLayerCylinderKHR *)layer)->subImage.swapchain);
case XR_TYPE_COMPOSITION_LAYER_EQUIRECT_KHR:
if (no_equirect) return 0;
return known_swapchain(((const XrCompositionLayerEquirectKHR *)layer)->subImage.swapchain);
@@ -367,7 +492,7 @@ static int layer_usable(const XrCompositionLayerBaseHeader *layer) {
return known_swapchain(((const XrCompositionLayerEquirect2KHR *)layer)->subImage.swapchain);
case XR_TYPE_COMPOSITION_LAYER_CUBE_KHR:
if (no_cube) return 0;
return known_swapchain(((const XrCompositionLayerCubeKHR *)layer)->swapchain);
return runtime_swapchain(((const XrCompositionLayerCubeKHR *)layer)->swapchain);
default:
return 1; // layer types without swapchains (e.g. passthrough) or unknown: pass through
}
@@ -450,7 +575,11 @@ XRAPI_ATTR XrResult XRAPI_CALL xrGetSystemProperties(XrInstance instance, XrSyst
PFN_xrGetSystemProperties fn = (PFN_xrGetSystemProperties)lookup(instance, "xrGetSystemProperties");
if (!fn) return XR_ERROR_FUNCTION_UNSUPPORTED;
XrResult result = fn(instance, system, properties);
if (XR_SUCCEEDED(result) && (emulate_passthrough || emulate_scene) && properties)
if (XR_SUCCEEDED(result) && properties && layer_debug)
LOG("layer_debug: system '%s' maxLayerCount=%u max swapchain %ux%u", properties->systemName,
properties->graphicsProperties.maxLayerCount, properties->graphicsProperties.maxSwapchainImageWidth,
properties->graphicsProperties.maxSwapchainImageHeight);
if (XR_SUCCEEDED(result) && (emulate_passthrough || emulate_scene || emulate_render_model) && properties)
for (XrBaseOutStructure *p = (XrBaseOutStructure *)properties->next; p; p = p->next) {
if (p->type == XR_TYPE_SYSTEM_PASSTHROUGH_PROPERTIES_FB)
((XrSystemPassthroughPropertiesFB *)p)->supportsPassthrough = XR_TRUE;
@@ -458,6 +587,8 @@ XRAPI_ATTR XrResult XRAPI_CALL xrGetSystemProperties(XrInstance instance, XrSyst
((XrSystemSpatialEntityPropertiesFB *)p)->supportsSpatialEntity = XR_TRUE;
if (p->type == XR_TYPE_SYSTEM_PASSTHROUGH_PROPERTIES2_FB)
((XrSystemPassthroughProperties2FB *)p)->capabilities = XR_PASSTHROUGH_CAPABILITY_BIT_FB;
if (p->type == XR_TYPE_SYSTEM_RENDER_MODEL_PROPERTIES_FB && emulate_render_model)
((XrSystemRenderModelPropertiesFB *)p)->supportsRenderModelLoading = XR_TRUE;
}
return result;
}
@@ -536,11 +667,20 @@ XRAPI_ATTR XrResult XRAPI_CALL xrDestroySpace(XrSpace space) {
return fn ? fn(space) : XR_ERROR_FUNCTION_UNSUPPORTED;
}
#include "session_fixes.c"
#include "layer_emul_gl.c"
XRAPI_ATTR XrResult XRAPI_CALL xrCreateSession(XrInstance instance, const XrSessionCreateInfo *info, XrSession *session) {
PFN_xrCreateSession fn = (PFN_xrCreateSession)lookup(instance, "xrCreateSession");
if (!fn) return XR_ERROR_FUNCTION_UNSUPPORTED;
XrResult result = fn(instance, info, session);
if (XR_SUCCEEDED(result)) { flip_emul = flip_emul_setting; flip_on_create_session(info); scene_on_create_session(*session); }
if (XR_SUCCEEDED(result)) {
flip_emul = flip_emul_setting;
flip_on_create_session(info);
scene_on_create_session(*session);
session_fixes_on_create_session(*session);
emul_on_create_session(*session, info);
}
return result;
}
@@ -548,8 +688,12 @@ XRAPI_ATTR XrResult XRAPI_CALL xrEnumerateSwapchainImages(XrSwapchain swapchain,
XrSwapchainImageBaseHeader *images) {
PFN_xrEnumerateSwapchainImages fn = (PFN_xrEnumerateSwapchainImages)lookup(active_instance, "xrEnumerateSwapchainImages");
if (!fn) return XR_ERROR_FUNCTION_UNSUPPORTED;
XrResult result = fn(swapchain, capacity, count, images);
if (XR_SUCCEEDED(result) && images && capacity && count) flip_on_enumerate_images(swapchain, *count, images);
XrResult result = equirect_emul && emul_is_virtual(swapchain) ? emul_virtual_enumerate(swapchain, capacity, count, images)
: fn(swapchain, capacity, count, images);
if (XR_SUCCEEDED(result) && images && capacity && count) {
flip_on_enumerate_images(swapchain, *count, images);
emul_on_enumerate(swapchain, *count < capacity ? *count : capacity, images);
}
return result;
}
@@ -557,8 +701,14 @@ XRAPI_ATTR XrResult XRAPI_CALL xrAcquireSwapchainImage(XrSwapchain swapchain, co
uint32_t *index) {
PFN_xrAcquireSwapchainImage fn = (PFN_xrAcquireSwapchainImage)lookup(active_instance, "xrAcquireSwapchainImage");
if (!fn) return XR_ERROR_FUNCTION_UNSUPPORTED;
if (equirect_emul && emul_is_virtual(swapchain)) { // adapter-served write-once picture: one image
if (!index) return XR_ERROR_VALIDATION_FAILURE;
*index = 0;
emul_on_acquire(swapchain, 0);
return XR_SUCCESS;
}
XrResult result = fn(swapchain, info, index);
if (XR_SUCCEEDED(result) && index) flip_on_acquire(swapchain, *index);
if (XR_SUCCEEDED(result) && index) { flip_on_acquire(swapchain, *index); emul_on_acquire(swapchain, *index); }
return result;
}
@@ -580,7 +730,17 @@ XRAPI_ATTR XrResult XRAPI_CALL xrPollEvent(XrInstance instance, XrEventDataBuffe
pthread_mutex_unlock(&scene_lock);
if (got) return XR_SUCCESS;
}
XrResult result = fn(instance, event);
XrResult result = focus_hold && event ? focus_hold_poll(fn, instance, event) : fn(instance, event);
if (result == XR_SUCCESS && event && (layer_debug || stable_local)) {
if (event->type == XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED && layer_debug)
LOG("layer_debug: session state %d at %.3f", ((const XrEventDataSessionStateChanged *)event)->state,
monotonic_ns() / 1e9);
if (event->type == XR_TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING) {
const XrEventDataReferenceSpaceChangePending *e = (const XrEventDataReferenceSpaceChangePending *)event;
if (layer_debug) LOG("layer_debug: runtime reference space change pending type=%d", e->referenceSpaceType);
if (e->referenceSpaceType == XR_REFERENCE_SPACE_TYPE_LOCAL) local_anchor_stale = 1;
}
}
if (!respace_kick || !event) return result;
if (result == XR_SUCCESS && event->type == XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED) {
const XrEventDataSessionStateChanged *e = (const XrEventDataSessionStateChanged *)event;
@@ -611,17 +771,22 @@ XRAPI_ATTR XrResult XRAPI_CALL xrCreateReferenceSpace(XrSession session, const X
XrSpace *space) {
PFN_xrCreateReferenceSpace fn = (PFN_xrCreateReferenceSpace)lookup(active_instance, "xrCreateReferenceSpace");
if (!fn) return XR_ERROR_FUNCTION_UNSUPPORTED;
XrReferenceSpaceCreateInfo fixed;
if (stable_local && info && info->referenceSpaceType == XR_REFERENCE_SPACE_TYPE_LOCAL) {
fixed = *info;
fixed.poseInReferenceSpace = stable_local_pose(session, info->poseInReferenceSpace);
info = &fixed;
}
XrResult result = fn(session, info, space);
if (info && space) {
LOG("xrCreateReferenceSpace type=%d result=%d space=%p", info->referenceSpaceType, result,
(void *)(uintptr_t)*space);
if (layer_debug && XR_SUCCEEDED(result)) debug_reference_space(session, info, *space);
if (XR_SUCCEEDED(result) && info->referenceSpaceType == XR_REFERENCE_SPACE_TYPE_VIEW) view_space_handle = *space;
}
return result;
}
static XrTime last_predicted_time;
XRAPI_ATTR XrResult XRAPI_CALL xrWaitFrame(XrSession session, const XrFrameWaitInfo *info, XrFrameState *state) {
PFN_xrWaitFrame fn = (PFN_xrWaitFrame)lookup(active_instance, "xrWaitFrame");
if (!fn) return XR_ERROR_FUNCTION_UNSUPPORTED;
@@ -634,6 +799,7 @@ XRAPI_ATTR XrResult XRAPI_CALL xrWaitFrame(XrSession session, const XrFrameWaitI
// predictedDisplayTime is about one display period ahead of "now".
xr_time_offset = (int64_t)(state->predictedDisplayTime - state->predictedDisplayPeriod) - mono;
xr_time_calibrated = 1;
if (layer_debug) debug_aim_vs_grip(state->predictedDisplayTime);
}
return result;
}
@@ -643,6 +809,9 @@ XRAPI_ATTR XrResult XRAPI_CALL xrLocateViews(XrSession session, const XrViewLoca
PFN_xrLocateViews fn = (PFN_xrLocateViews)lookup(active_instance, "xrLocateViews");
if (!fn) return XR_ERROR_FUNCTION_UNSUPPORTED;
XrResult result = fn(session, info, state, capacity, count, views);
if (equirect_emul && XR_SUCCEEDED(result) && info && count && views && state &&
(state->viewStateFlags & XR_VIEW_STATE_ORIENTATION_VALID_BIT))
emul_on_locate_views(info->space, info->displayTime, *count < capacity ? *count : capacity, views);
// respace_kick trigger: ~90 consecutive untracked head poses in a non-VIEW space.
static int untracked;
if (respace_kick && XR_SUCCEEDED(result) && state && info && info->space != view_space_handle) {
@@ -706,6 +875,38 @@ XRAPI_ATTR XrResult XRAPI_CALL xrEndFrame(XrSession session, const XrFrameEndInf
if ((!layer_fix && !swap_eyes && !emulate_passthrough && !flip_quads && !flip_emul && !strip_depth) || !info || !info->layerCount ||
info->layerCount > 64)
return fn(session, info);
if (layer_debug) { // the submitted layer list (order, flags, eyes, chained structs) whenever its shape changes
static char last[1024];
char now[1024];
size_t used = 0;
for (uint32_t i = 0; i < info->layerCount && used < sizeof(now) - 64; ++i) {
const XrCompositionLayerBaseHeader *l = info->layers[i];
if (!l) continue;
int eye = -1;
if (l->type == XR_TYPE_COMPOSITION_LAYER_QUAD) eye = ((const XrCompositionLayerQuad *)l)->eyeVisibility;
if (l->type == XR_TYPE_COMPOSITION_LAYER_CYLINDER_KHR) eye = ((const XrCompositionLayerCylinderKHR *)l)->eyeVisibility;
if (l->type == XR_TYPE_COMPOSITION_LAYER_EQUIRECT2_KHR) eye = ((const XrCompositionLayerEquirect2KHR *)l)->eyeVisibility;
used += (size_t)snprintf(now + used, sizeof(now) - used, " [%d f=0x%llx e=%d", l->type,
(unsigned long long)l->layerFlags, eye);
if (l->type == XR_TYPE_COMPOSITION_LAYER_EQUIRECT2_KHR) { // mapping + source size: 360 vs 180, SBS halves
const XrCompositionLayerEquirect2KHR *q = (const XrCompositionLayerEquirect2KHR *)l;
used += (size_t)snprintf(now + used, sizeof(now) - used, " h=%.2f u=%.2f l=%.2f r=%.1f rect=%d,%d %dx%d",
q->centralHorizontalAngle, q->upperVerticalAngle, q->lowerVerticalAngle,
q->radius, q->subImage.imageRect.offset.x, q->subImage.imageRect.offset.y,
q->subImage.imageRect.extent.width, q->subImage.imageRect.extent.height);
}
for (const XrBaseInStructure *n = (const XrBaseInStructure *)l->next; n && used < sizeof(now) - 32; n = n->next)
used += (size_t)snprintf(now + used, sizeof(now) - used, " n=%d", n->type);
used += (size_t)snprintf(now + used, sizeof(now) - used, "]");
}
if (strcmp(now, last)) {
LOG("layer_debug: frame layers blend=%d:%s", info->environmentBlendMode, now);
snprintf(last, sizeof(last), "%s", now);
}
}
// equirect_emul: the frame's 360 layers are replaced by one emulated projection layer (at the first one's place)
const XrCompositionLayerBaseHeader *emul_layer_out = NULL;
int emul_first = layer_fix && emul_active() ? emul_prepare_frame(info, &emul_layer_out) : -1;
const XrCompositionLayerBaseHeader *kept[64];
XrCompositionLayerProjection projections[64];
XrCompositionLayerProjectionView views[64][2];
@@ -735,6 +936,23 @@ XRAPI_ATTR XrResult XRAPI_CALL xrEndFrame(XrSession session, const XrFrameEndInf
LOG("new layer: type=%d swapchain=%p flip_tag=%d usable=%d", layer->type, key, tagged, layer_usable(layer));
}
}
if (emul_first >= 0 && emul_layer_out && emul_is_equirect(layer)) {
if ((int)i == emul_first) kept[count++] = emul_layer_out; // all 360 layers are drawn into it
++swapped;
continue;
}
if (layer_fix && cylinder_strips_on && no_cylinder && layer->type == XR_TYPE_COMPOSITION_LAYER_CYLINDER_KHR &&
runtime_swapchain(((const XrCompositionLayerCylinderKHR *)layer)->subImage.swapchain)) {
// keep the whole frame within the runtime's layer limit: every later layer still needs a slot
int budget = 16 - (int)count - (int)(info->layerCount - i - 1);
int n = cylinder_strips((const XrCompositionLayerCylinderKHR *)layer, &quads[count], budget < 64 - (int)count ? budget : 64 - (int)count);
if (n > 0) {
for (int k = 0; k < n; ++k) kept[count + k] = (const XrCompositionLayerBaseHeader *)&quads[count + k];
count += (uint32_t)n;
++swapped;
continue;
}
}
if (!layer || (layer_fix && !layer_usable(layer))) { ++dropped; continue; }
if (layer->type == XR_TYPE_COMPOSITION_LAYER_QUAD) {
const XrCompositionLayerQuad *flipped = flip_quad(session, (const XrCompositionLayerQuad *)layer, &quads[count]);
@@ -882,12 +1100,13 @@ XRAPI_ATTR XrResult XRAPI_CALL xrEnumerateInstanceExtensionProperties(const char
XR_NULL_HANDLE, "xrEnumerateInstanceExtensionProperties");
if (!fn) return XR_ERROR_INITIALIZATION_FAILED;
if (!count) return XR_ERROR_VALIDATION_FAILURE;
if ((!foveation_fix && !passthrough_emul && !scene_emul) || layer) return fn(layer, capacity, count, properties);
if ((!foveation_fix && !passthrough_emul && !scene_emul && !controller_models) || layer)
return fn(layer, capacity, count, properties);
uint32_t total = 0;
XrResult result = fn(layer, 0, &total, NULL);
if (XR_FAILED(result)) return result;
XrExtensionProperties *all = calloc(total + 1 + SCENE_EXTENSION_COUNT, sizeof(*all));
XrExtensionProperties *all = calloc(total + 2 + SCENE_EXTENSION_COUNT, sizeof(*all));
if (!all) return XR_ERROR_OUT_OF_MEMORY;
for (uint32_t i = 0; i < total; ++i) all[i].type = XR_TYPE_EXTENSION_PROPERTIES;
result = fn(layer, total, &total, all);
@@ -896,6 +1115,7 @@ XRAPI_ATTR XrResult XRAPI_CALL xrEnumerateInstanceExtensionProperties(const char
uint32_t kept = 0;
for (uint32_t i = 0; i < total; ++i) {
if (!strcmp(all[i].extensionName, "XR_FB_passthrough")) runtime_has_fb_passthrough = 1;
if (!strcmp(all[i].extensionName, XR_FB_RENDER_MODEL_EXTENSION_NAME)) runtime_has_render_model = 1;
if (foveation_fix && strstr(all[i].extensionName, "foveation")) continue;
if (properties && kept < capacity) properties[kept] = all[i];
++kept;
@@ -916,6 +1136,12 @@ XRAPI_ATTR XrResult XRAPI_CALL xrEnumerateInstanceExtensionProperties(const char
if (properties && kept < capacity) properties[kept] = fake;
++kept;
}
if (controller_models && render_models_available && !runtime_has_render_model) {
XrExtensionProperties fake = {XR_TYPE_EXTENSION_PROPERTIES, NULL, XR_FB_RENDER_MODEL_EXTENSION_NAME,
XR_FB_render_model_SPEC_VERSION};
if (properties && kept < capacity) properties[kept] = fake;
++kept;
}
free(all);
*count = kept;
return (capacity && capacity < kept) ? XR_ERROR_SIZE_INSUFFICIENT : XR_SUCCESS;
@@ -928,6 +1154,12 @@ XRAPI_ATTR XrResult XRAPI_CALL xrEnumerateApiLayerProperties(uint32_t capacity,
return fn ? fn(capacity, count, properties) : XR_ERROR_INITIALIZATION_FAILED;
}
// For native/xrshim: emulated functions that overport's dispatcher doesn't know (it never asks us for them).
__attribute__((visibility("default"))) PFN_xrVoidFunction framebridge_extension_proc(const char *name) {
pthread_once(&init_once, initialize);
return name ? render_model_emulation(name) : NULL;
}
XRAPI_ATTR XrResult XRAPI_CALL xrGetInstanceProcAddr(XrInstance instance, const char *name,
PFN_xrVoidFunction *function) {
pthread_once(&init_once, initialize);
@@ -948,6 +1180,7 @@ XRAPI_ATTR XrResult XRAPI_CALL xrGetInstanceProcAddr(XrInstance instance, const
}
PFN_xrVoidFunction emulated = passthrough_emulation(name);
if (!emulated) emulated = scene_emulation(name);
if (!emulated) emulated = render_model_emulation(name);
if (!emulated && emulate_scene && !strcmp(name, "xrLocateSpacesKHR")) emulated = (PFN_xrVoidFunction)emu_locate_spaces_khr;
if (emulated) { *function = emulated; return XR_SUCCESS; }
HOOK(xrGetSystemProperties)
@@ -969,6 +1202,22 @@ XRAPI_ATTR XrResult XRAPI_CALL xrGetInstanceProcAddr(XrInstance instance, const
HOOK(xrLocateHandJointsEXT)
HOOK(xrGetCurrentInteractionProfile)
HOOK(xrEnumerateInstanceExtensionProperties)
// Per-game hooks: only installed when their setting is on, so other games run through exactly the same calls.
#define HOOK_AS(fn, impl) if (!strcmp(name, #fn)) { *function = (PFN_xrVoidFunction)impl; return XR_SUCCESS; }
if (equirect_emul) {
HOOK_AS(xrReleaseSwapchainImage, hook_xrReleaseSwapchainImage)
HOOK_AS(xrWaitSwapchainImage, hook_xrWaitSwapchainImage)
HOOK_AS(xrDestroySession, hook_xrDestroySession)
}
if (layer_debug || refresh_rate > 0 || equirect_emul) HOOK_AS(xrBeginSession, hook_xrBeginSession)
if (layer_debug || refresh_rate > 0) {
HOOK_AS(xrRequestDisplayRefreshRateFB, hook_request_refresh_rate)
}
if (layer_debug || aim_correction_on()) {
HOOK_AS(xrSuggestInteractionProfileBindings, hook_xrSuggestInteractionProfileBindings)
HOOK_AS(xrCreateActionSpace, hook_xrCreateActionSpace)
}
#undef HOOK_AS
#undef HOOK
return next_gipa(instance, name, function);
}
File diff suppressed because it is too large. Load diff
+129
View File
@@ -0,0 +1,129 @@
// SPDX-License-Identifier: GPL-3.0-only
// Pose / direction math shared by the adapter's per-game fixes (session_fixes.c, layer_emul_gl.c). Header-only and
// free of Android/GL dependencies so tests/test_layer_emul.py can compile it for the host.
#ifndef FRAMEBRIDGE_LAYER_MATH_H
#define FRAMEBRIDGE_LAYER_MATH_H
#include <math.h>
#include <openxr/openxr.h>
#define LM_PI 3.14159265358979323846f
static inline XrVector3f lm_rotate(XrQuaternionf q, XrVector3f v) { // v' = v + 2w(u x v) + 2 u x (u x v)
XrVector3f u = {q.x, q.y, q.z}, t = {2 * (u.y * v.z - u.z * v.y), 2 * (u.z * v.x - u.x * v.z), 2 * (u.x * v.y - u.y * v.x)};
return (XrVector3f){v.x + q.w * t.x + (u.y * t.z - u.z * t.y), v.y + q.w * t.y + (u.z * t.x - u.x * t.z),
v.z + q.w * t.z + (u.x * t.y - u.y * t.x)};
}
static inline XrQuaternionf lm_qmul(XrQuaternionf a, XrQuaternionf b) {
return (XrQuaternionf){a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y, a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x,
a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w, a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z};
}
static inline XrQuaternionf lm_qconj(XrQuaternionf q) { return (XrQuaternionf){-q.x, -q.y, -q.z, q.w}; }
static inline XrQuaternionf lm_axis_angle(float x, float y, float z, float radians) {
float s = sinf(radians / 2);
return (XrQuaternionf){x * s, y * s, z * s, cosf(radians / 2)};
}
// a∘b: the pose b (expressed in a's frame) expressed in a's parent frame.
static inline XrPosef lm_pose_mul(XrPosef a, XrPosef b) {
XrVector3f p = lm_rotate(a.orientation, b.position);
return (XrPosef){lm_qmul(a.orientation, b.orientation),
{a.position.x + p.x, a.position.y + p.y, a.position.z + p.z}};
}
static inline XrPosef lm_pose_inv(XrPosef a) {
XrQuaternionf q = lm_qconj(a.orientation);
XrVector3f p = lm_rotate(q, a.position);
return (XrPosef){q, {-p.x, -p.y, -p.z}};
}
// Rotation angle (radians) of a pose: how far it is from identity.
static inline float lm_angle(XrQuaternionf q) {
float w = fabsf(q.w) > 1 ? 1 : fabsf(q.w);
return 2 * acosf(w);
}
static inline float lm_length(XrVector3f v) { return sqrtf(v.x * v.x + v.y * v.y + v.z * v.z); }
static inline float lm_dot(XrVector3f a, XrVector3f b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
// ---- cube faces used to show 360° (equirect) layers as world-locked quads.
// Face f looks along lm_face_rotation(f) * (0,0,-1): 0 = -Z (front), 1 = +X (right), 2 = +Z (back), 3 = -X (left),
// 4 = +Y (up), 5 = -Y (down). The same rotation orients the face's quad (a quad faces +Z, so it faces the centre).
static inline XrQuaternionf lm_face_rotation(int face) {
switch (face) {
case 1: return lm_axis_angle(0, 1, 0, -LM_PI / 2);
case 2: return lm_axis_angle(0, 1, 0, LM_PI);
case 3: return lm_axis_angle(0, 1, 0, LM_PI / 2);
case 4: return lm_axis_angle(1, 0, 0, LM_PI / 2);
case 5: return lm_axis_angle(1, 0, 0, -LM_PI / 2);
default: return (XrQuaternionf){0, 0, 0, 1};
}
}
// Direction (layer space) of the point (u, v) in [-1, 1]² of face f (u = right, v = up on the face's quad).
static inline XrVector3f lm_face_dir(int face, float u, float v) {
return lm_rotate(lm_face_rotation(face), (XrVector3f){u, v, -1});
}
// Pose of face f's quad: `distance` metres from the layer's origin, facing it.
static inline XrPosef lm_face_pose(XrPosef layer, int face, float distance) {
XrPosef local = {lm_face_rotation(face), lm_face_dir(face, 0, 0)};
local.position.x *= distance; local.position.y *= distance; local.position.z *= distance;
return lm_pose_mul(layer, local);
}
// GL cube map convention (the equirect_emul shader's cube_dir): direction of texel (s, t) = ((u + 1) / 2, (v + 1) / 2)
// on face GL_TEXTURE_CUBE_MAP_POSITIVE_X + face.
static inline XrVector3f lm_glcube_dir(int face, float u, float v) {
switch (face) {
case 0: return (XrVector3f){1, -v, -u};
case 1: return (XrVector3f){-1, -v, u};
case 2: return (XrVector3f){u, 1, v};
case 3: return (XrVector3f){u, -1, -v};
case 4: return (XrVector3f){u, -v, 1};
default: return (XrVector3f){-u, -v, -1};
}
}
// GL's cube map lookup (OpenGL ES 3.0 spec, table 3.21): direction -> face and (s, t).
static inline int lm_glcube_lookup(XrVector3f d, float *s, float *t) {
float ax = fabsf(d.x), ay = fabsf(d.y), az = fabsf(d.z), sc, tc, ma;
int face;
if (ax >= ay && ax >= az) { face = d.x > 0 ? 0 : 1; ma = ax; sc = d.x > 0 ? -d.z : d.z; tc = -d.y; }
else if (ay >= az) { face = d.y > 0 ? 2 : 3; ma = ay; sc = d.x; tc = d.y > 0 ? d.z : -d.z; }
else { face = d.z > 0 ? 4 : 5; ma = az; sc = d.z > 0 ? d.x : -d.x; tc = -d.y; }
*s = (sc / ma + 1) / 2;
*t = (tc / ma + 1) / 2;
return face;
}
// Equirect2 mapping (XR_KHR_composition_layer_equirect2): direction (layer space) -> normalized image coordinates
// (u right, v up; v = 0 at lowerVerticalAngle). Longitude 0 is the -Z axis, growing towards +X.
// Returns 0 when the direction is outside the layer's angles.
static inline int lm_equirect2_uv(XrVector3f d, float central, float upper, float lower, float *u, float *v) {
float len = lm_length(d);
if (len <= 0 || central <= 0 || upper <= lower) return 0;
float lon = atan2f(d.x, -d.z), lat = asinf(fmaxf(-1.0f, fminf(1.0f, d.y / len)));
*u = lon / central + 0.5f;
*v = (lat - lower) / (upper - lower);
return *u >= 0 && *u <= 1 && *v >= 0 && *v <= 1;
}
// Is any part of face f within `cos_limit` (cosine of the angle) of `forward` (unit, layer space)? Samples a grid on
// the face, so it is conservative up to the grid spacing (the caller adds a margin to cos_limit for that).
static inline int lm_face_visible(int face, XrVector3f forward, float cos_limit) {
for (int i = 0; i <= 4; ++i)
for (int j = 0; j <= 4; ++j) {
XrVector3f d = lm_face_dir(face, -1 + 0.5f * i, -1 + 0.5f * j);
if (lm_dot(d, forward) / lm_length(d) >= cos_limit) return 1;
}
return 0;
}
// Cosine of the angle between the face's centre direction and `forward` (unit): sort key, larger = closer to view.
static inline float lm_face_score(int face, XrVector3f forward) { return lm_dot(lm_face_dir(face, 0, 0), forward); }
#endif
+122
View File
@@ -0,0 +1,122 @@
// SPDX-License-Identifier: GPL-3.0-only
// XR_FB_render_model emulation (controller_models): serves Steam Frame controller models to games that ask the
// runtime for controller models (Meta XR SDK "runtime controller" / OVRRuntimeController, Unreal OculusXR), so they
// show the controllers in your hands instead of Quest Touch controllers. Games that ship their own controller meshes
// don't use this extension and are not affected.
//
// The models are glTF binaries converted on the Frame from its own SteamVR render models by the FramePort agent:
// /sdcard/Android/data/<package>/files/framebridge/controller_{left,right}.glb
// Only active when both files exist and the runtime lacks XR_FB_render_model (a native one is used as is).
// Included by frame_adapter.c.
static int render_models_available; // both .glb files present
static int runtime_has_render_model;
static int emulate_render_model;
static char render_model_dir[512];
static const char *const render_model_paths[2] = {"/model_fb/controller/left", "/model_fb/controller/right"};
static const char *const render_model_files[2] = {"controller_left.glb", "controller_right.glb"};
static const char *const render_model_names[2] = {"Steam Frame Controller Left", "Steam Frame Controller Right"};
#define RENDER_MODEL_VENDOR_VALVE 0x28DE
#define RENDER_MODEL_KEY_BASE 0x46500000u // keys: base + 1 (left), base + 2 (right)
static void render_model_scan(const char *dir) {
snprintf(render_model_dir, sizeof(render_model_dir), "%s", dir);
char path[640];
int found = 0;
for (int i = 0; i < 2; ++i) {
snprintf(path, sizeof(path), "%s/%s", render_model_dir, render_model_files[i]);
FILE *f = fopen(path, "rb");
if (f) { ++found; fclose(f); }
}
render_models_available = found == 2;
LOG("controller models %s in %s", render_models_available ? "found" : "not found", render_model_dir);
}
static void render_model_init(const char *package) {
if (!package || !*package) return;
char dir[512];
snprintf(dir, sizeof(dir), "/sdcard/Android/data/%s/files/framebridge", package);
render_model_scan(dir);
}
static int render_model_index(XrPath path) {
PFN_xrStringToPath to_path = (PFN_xrStringToPath)lookup(active_instance, "xrStringToPath");
if (!to_path || !active_instance) return -1;
for (int i = 0; i < 2; ++i) {
XrPath p = XR_NULL_PATH;
if (XR_SUCCEEDED(to_path(active_instance, render_model_paths[i], &p)) && p == path) return i;
}
return -1;
}
static XRAPI_ATTR XrResult XRAPI_CALL emu_enumerate_render_model_paths(XrSession session, uint32_t capacity,
uint32_t *count, XrRenderModelPathInfoFB *paths) {
(void)session;
if (!count) return XR_ERROR_VALIDATION_FAILURE;
*count = 2;
if (!capacity) return XR_SUCCESS;
if (capacity < 2 || !paths) return XR_ERROR_SIZE_INSUFFICIENT;
PFN_xrStringToPath to_path = (PFN_xrStringToPath)lookup(active_instance, "xrStringToPath");
if (!to_path) return XR_ERROR_RUNTIME_FAILURE;
for (int i = 0; i < 2; ++i) {
XrResult r = to_path(active_instance, render_model_paths[i], &paths[i].path);
if (XR_FAILED(r)) return r;
}
return XR_SUCCESS;
}
static XRAPI_ATTR XrResult XRAPI_CALL emu_get_render_model_properties(XrSession session, XrPath path,
XrRenderModelPropertiesFB *properties) {
(void)session;
if (!properties) return XR_ERROR_VALIDATION_FAILURE;
XrRenderModelFlagsFB requested = XR_RENDER_MODEL_SUPPORTS_GLTF_2_0_SUBSET_1_BIT_FB;
for (const XrBaseInStructure *p = (const XrBaseInStructure *)properties->next; p; p = p->next)
if (p->type == XR_TYPE_RENDER_MODEL_CAPABILITIES_REQUEST_FB)
requested = ((const XrRenderModelCapabilitiesRequestFB *)p)->flags;
int i = render_model_index(path);
if (i < 0) {
properties->modelKey = XR_NULL_RENDER_MODEL_KEY_FB;
return XR_ERROR_PATH_UNSUPPORTED;
}
properties->vendorId = RENDER_MODEL_VENDOR_VALVE;
snprintf(properties->modelName, sizeof(properties->modelName), "%s", render_model_names[i]);
properties->modelKey = (XrRenderModelKeyFB)(RENDER_MODEL_KEY_BASE + 1 + i);
properties->modelVersion = 1;
// One mesh, one PNG texture, no animation: fits subset 1 and therefore every subset an app can ask for.
properties->flags = requested & XR_RENDER_MODEL_SUPPORTS_GLTF_2_0_SUBSET_2_BIT_FB
? XR_RENDER_MODEL_SUPPORTS_GLTF_2_0_SUBSET_2_BIT_FB : XR_RENDER_MODEL_SUPPORTS_GLTF_2_0_SUBSET_1_BIT_FB;
static int logged[2];
if (!logged[i]++) LOG("render model %s -> %s/%s", render_model_paths[i], render_model_dir, render_model_files[i]);
return XR_SUCCESS;
}
static XRAPI_ATTR XrResult XRAPI_CALL emu_load_render_model(XrSession session, const XrRenderModelLoadInfoFB *info,
XrRenderModelBufferFB *buffer) {
(void)session;
if (!info || !buffer) return XR_ERROR_VALIDATION_FAILURE;
uint64_t key = (uint64_t)info->modelKey;
if (key != RENDER_MODEL_KEY_BASE + 1 && key != RENDER_MODEL_KEY_BASE + 2) return XR_ERROR_RENDER_MODEL_KEY_INVALID_FB;
int i = (int)(key - RENDER_MODEL_KEY_BASE - 1);
char path[640];
snprintf(path, sizeof(path), "%s/%s", render_model_dir, render_model_files[i]);
FILE *f = fopen(path, "rb");
if (!f) { LOG("render model %s missing", path); return XR_ERROR_RENDER_MODEL_KEY_INVALID_FB; }
long size = -1;
if (!fseek(f, 0, SEEK_END)) size = ftell(f);
if (size <= 0 || size > 0x7fffffffL || fseek(f, 0, SEEK_SET)) { fclose(f); return XR_ERROR_RUNTIME_FAILURE; }
buffer->bufferCountOutput = (uint32_t)size;
if (!buffer->bufferCapacityInput) { fclose(f); return XR_SUCCESS; }
if (buffer->bufferCapacityInput < (uint32_t)size || !buffer->buffer) { fclose(f); return XR_ERROR_SIZE_INSUFFICIENT; }
size_t got = fread(buffer->buffer, 1, (size_t)size, f);
fclose(f);
return got == (size_t)size ? XR_SUCCESS : XR_ERROR_RUNTIME_FAILURE;
}
static PFN_xrVoidFunction render_model_emulation(const char *name) {
if (!emulate_render_model) return NULL;
if (!strcmp(name, "xrEnumerateRenderModelPathsFB")) return (PFN_xrVoidFunction)emu_enumerate_render_model_paths;
if (!strcmp(name, "xrGetRenderModelPropertiesFB")) return (PFN_xrVoidFunction)emu_get_render_model_properties;
if (!strcmp(name, "xrLoadRenderModelFB")) return (PFN_xrVoidFunction)emu_load_render_model;
return NULL;
}
+313
View File
@@ -0,0 +1,313 @@
// SPDX-License-Identifier: GPL-3.0-only
// Included by frame_adapter.c. Per-game session fixes, all off by default (enabled in a game's recipe):
// * layer_debug: diagnostics only — layer/swapchain details, session-state timing, reference-space creation (and how
// far each new LOCAL space is from the session's first one), aim vs grip poses, refresh-rate calls;
// * stable_local: every LOCAL reference space the app creates coincides with the one at session start (for runtimes
// that place each new LOCAL space at the current head yaw, which makes menus jump to where you look);
// * focus_hold: hides brief FOCUSED -> VISIBLE -> (SYNCHRONIZED) dips once the session has been focused for a while
// (apps that recentre on regaining focus);
// * aim_pitch / aim_yaw / aim_forward: correct the aim pose of controllers (pointer rays) by a fixed offset;
// * refresh_rate: display refresh rate requested at session start (and instead of the app's own requests).
#include "layer_math.h"
static void emul_on_begin_session(const XrSessionBeginInfo *info); // layer_emul_gl.c
static int64_t monotonic_ns(void) {
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
return (int64_t)now.tv_sec * 1000000000ll + now.tv_nsec;
}
// ---------------------------------------------------------------- stable_local
static XrSpace local_anchor = XR_NULL_HANDLE; // private LOCAL space created right after xrCreateSession
static int local_anchor_stale; // runtime announced a LOCAL change (user recentre): re-anchor
static XrSpace debug_first_local = XR_NULL_HANDLE; // layer_debug: first LOCAL space, to measure later ones against
static XrSpace create_local(XrSession session) {
PFN_xrCreateReferenceSpace create = (PFN_xrCreateReferenceSpace)lookup(active_instance, "xrCreateReferenceSpace");
XrReferenceSpaceCreateInfo ci = {XR_TYPE_REFERENCE_SPACE_CREATE_INFO, NULL, XR_REFERENCE_SPACE_TYPE_LOCAL,
{{0, 0, 0, 1}, {0, 0, 0}}};
XrSpace space = XR_NULL_HANDLE;
if (!create || XR_FAILED(create(session, &ci, &space))) return XR_NULL_HANDLE;
return space;
}
static void destroy_space(XrSpace space) {
PFN_xrDestroySpace destroy = (PFN_xrDestroySpace)lookup(active_instance, "xrDestroySpace");
if (destroy && space) destroy(space);
}
// Pose of `space` in `base` at the latest predicted display time; 0 if not (yet) known.
static int locate_pose(XrSpace space, XrSpace base, XrPosef *pose) {
PFN_xrLocateSpace locate = (PFN_xrLocateSpace)lookup(active_instance, "xrLocateSpace");
if (!locate || !space || !base || !last_predicted_time) return 0;
XrSpaceLocation loc = {XR_TYPE_SPACE_LOCATION, NULL, 0, {{0, 0, 0, 1}, {0, 0, 0}}};
if (XR_FAILED(locate(space, base, last_predicted_time, &loc))) return 0;
const XrSpaceLocationFlags valid = XR_SPACE_LOCATION_ORIENTATION_VALID_BIT | XR_SPACE_LOCATION_POSITION_VALID_BIT;
if ((loc.locationFlags & valid) != valid) return 0;
*pose = loc.pose;
return 1;
}
static void session_fixes_on_create_session(XrSession session) {
if (stable_local) {
local_anchor = create_local(session);
LOG("stable_local: session anchor %s", local_anchor ? "created" : "FAILED");
}
}
// The pose to create an app LOCAL space with, so that it coincides with the session-start LOCAL space.
static XrPosef stable_local_pose(XrSession session, XrPosef app_pose) {
if (!local_anchor) return app_pose;
XrSpace fresh = create_local(session);
if (!fresh) return app_pose;
XrPosef anchor_in_fresh;
int known = locate_pose(local_anchor, fresh, &anchor_in_fresh);
if (known && local_anchor_stale) { // the user recentred: from now on the new LOCAL origin is the anchor
destroy_space(local_anchor);
local_anchor = fresh;
local_anchor_stale = 0;
LOG("stable_local: re-anchored after a runtime recentre");
return app_pose;
}
destroy_space(fresh);
if (!known) return app_pose;
float moved = lm_length(anchor_in_fresh.position), turned = lm_angle(anchor_in_fresh.orientation);
if (moved < 0.01f && turned < 0.01f) return app_pose; // runtime kept LOCAL stable: nothing to correct
LOG("stable_local: new LOCAL space is %.3f m / %.1f deg from the session's, compensating", moved,
turned * 180 / LM_PI);
return lm_pose_mul(anchor_in_fresh, app_pose);
}
static void debug_reference_space(XrSession session, const XrReferenceSpaceCreateInfo *info, XrSpace space) {
const XrPosef *p = &info->poseInReferenceSpace;
LOG("layer_debug: space created type=%d space=%p pose=(%.3f,%.3f,%.3f | %.3f,%.3f,%.3f,%.3f) t=%.3f",
info->referenceSpaceType, (void *)(uintptr_t)space, p->position.x, p->position.y, p->position.z,
p->orientation.x, p->orientation.y, p->orientation.z, p->orientation.w, monotonic_ns() / 1e9);
if (info->referenceSpaceType != XR_REFERENCE_SPACE_TYPE_LOCAL) return;
if (!debug_first_local) { debug_first_local = create_local(session); return; }
XrPosef rel;
if (locate_pose(space, debug_first_local, &rel))
LOG("layer_debug: that LOCAL space sits at %.3f m / %.1f deg (yaw %.1f) from the session's first LOCAL space",
lm_length(rel.position), lm_angle(rel.orientation) * 180 / LM_PI,
2 * atan2f(rel.orientation.y, rel.orientation.w) * 180 / LM_PI);
else
LOG("layer_debug: that LOCAL space can't be located yet (no tracking)");
}
// ---------------------------------------------------------------- focus_hold
#define FOCUS_HOLD_MIN_FOCUSED_NS 3000000000ll // only after this long in FOCUSED (start-up transitions untouched)
#define FOCUS_HOLD_MAX_DIP_NS 600000000ll // dips longer than this are delivered (late, in order)
static struct {
XrEventDataBuffer events[6];
int count, holding, delivering;
int64_t since;
} held;
static int is_focused;
static int64_t focused_since;
static int session_state_of(const XrEventDataBuffer *event) {
return event->type == XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED ? (int)((const XrEventDataSessionStateChanged *)event)->state : -1;
}
static void focus_hold_note(int state) {
if (state == XR_SESSION_STATE_FOCUSED && !is_focused) { is_focused = 1; focused_since = monotonic_ns(); }
else if (state >= 0 && state != XR_SESSION_STATE_FOCUSED) is_focused = 0;
}
static XrResult focus_hold_poll(PFN_xrPollEvent fn, XrInstance instance, XrEventDataBuffer *event) {
for (;;) {
if (held.delivering) { // hand held events to the app, oldest first
if (held.count) {
*event = held.events[0];
memmove(&held.events[0], &held.events[1], (size_t)--held.count * sizeof(held.events[0]));
focus_hold_note(session_state_of(event));
return XR_SUCCESS;
}
held.delivering = 0;
}
XrResult result = fn(instance, event);
int64_t now = monotonic_ns();
if (result != XR_SUCCESS) {
if (held.holding && now - held.since > FOCUS_HOLD_MAX_DIP_NS) {
LOG("focus_hold: focus lost for > %lld ms, delivering %d state change(s)",
FOCUS_HOLD_MAX_DIP_NS / 1000000, held.count);
held.holding = 0; held.delivering = 1;
continue;
}
return result;
}
int state = session_state_of(event);
if (state < 0) return result; // other events pass straight through
if (held.holding) {
if (state == XR_SESSION_STATE_FOCUSED) {
LOG("focus_hold: hid a %.0f ms focus dip (%d state change(s))", (now - held.since) / 1e6, held.count);
held.count = 0; held.holding = 0;
continue; // the app never saw it leave FOCUSED
}
if (held.count < 6) held.events[held.count++] = *event;
if (state != XR_SESSION_STATE_VISIBLE && state != XR_SESSION_STATE_SYNCHRONIZED) {
held.holding = 0; held.delivering = 1; // stopping, loss pending, exiting: deliver everything now
}
continue;
}
if (state == XR_SESSION_STATE_VISIBLE && is_focused && now - focused_since >= FOCUS_HOLD_MIN_FOCUSED_NS) {
held.holding = 1; held.since = now; held.count = 0;
held.events[held.count++] = *event;
continue;
}
focus_hold_note(state);
return result;
}
}
// ---------------------------------------------------------------- aim pose correction + aim/grip diagnostics
#define MAX_POSE_ACTIONS 64
static struct { XrAction action; int aim; } pose_actions[MAX_POSE_ACTIONS];
static int pose_action_count;
static struct { XrSpace space; XrPath subaction; int aim; } pose_spaces[MAX_POSE_ACTIONS];
static int pose_space_count;
static pthread_mutex_t pose_lock = PTHREAD_MUTEX_INITIALIZER;
static int aim_correction_on(void) { return aim_pitch != 0 || aim_yaw != 0 || aim_forward != 0; }
static void note_pose_binding(XrAction action, const char *path) {
size_t n = strlen(path);
int aim = n >= 9 && !strcmp(path + n - 9, "/aim/pose");
int grip = n >= 10 && !strcmp(path + n - 10, "/grip/pose");
if (!aim && !grip) return;
pthread_mutex_lock(&pose_lock);
int known = 0;
for (int i = 0; i < pose_action_count; ++i) known |= pose_actions[i].action == action;
if (!known && pose_action_count < MAX_POSE_ACTIONS) {
pose_actions[pose_action_count].action = action;
pose_actions[pose_action_count++].aim = aim;
}
pthread_mutex_unlock(&pose_lock);
}
static int pose_action_kind(XrAction action) { // 1 aim, 0 grip, -1 unknown
int kind = -1;
pthread_mutex_lock(&pose_lock);
for (int i = 0; i < pose_action_count && kind < 0; ++i)
if (pose_actions[i].action == action) kind = pose_actions[i].aim;
pthread_mutex_unlock(&pose_lock);
return kind;
}
static XRAPI_ATTR XrResult XRAPI_CALL hook_xrSuggestInteractionProfileBindings(XrInstance instance,
const XrInteractionProfileSuggestedBinding *suggested) {
PFN_xrSuggestInteractionProfileBindings fn =
(PFN_xrSuggestInteractionProfileBindings)lookup(instance, "xrSuggestInteractionProfileBindings");
if (!fn) return XR_ERROR_FUNCTION_UNSUPPORTED;
PFN_xrPathToString to_string = (PFN_xrPathToString)lookup(instance, "xrPathToString");
if (suggested && to_string)
for (uint32_t i = 0; i < suggested->countSuggestedBindings; ++i) {
char path[XR_MAX_PATH_LENGTH];
uint32_t size = 0;
if (XR_SUCCEEDED(to_string(instance, suggested->suggestedBindings[i].binding, sizeof(path), &size, path)))
note_pose_binding(suggested->suggestedBindings[i].action, path);
}
return fn(instance, suggested);
}
static XRAPI_ATTR XrResult XRAPI_CALL hook_xrCreateActionSpace(XrSession session, const XrActionSpaceCreateInfo *info,
XrSpace *space) {
PFN_xrCreateActionSpace fn = (PFN_xrCreateActionSpace)lookup(active_instance, "xrCreateActionSpace");
if (!fn) return XR_ERROR_FUNCTION_UNSUPPORTED;
if (!info) return fn(session, info, space);
int kind = pose_action_kind(info->action);
XrActionSpaceCreateInfo fixed = *info;
if (kind == 1 && aim_correction_on()) {
XrQuaternionf q = lm_qmul(lm_axis_angle(0, 1, 0, aim_yaw * LM_PI / 180), lm_axis_angle(1, 0, 0, aim_pitch * LM_PI / 180));
XrPosef correction = {q, {0, 0, -aim_forward}};
fixed.poseInActionSpace = lm_pose_mul(correction, info->poseInActionSpace);
static int logged;
if (logged++ < 4) LOG("aim correction: pitch %.1f deg, yaw %.1f deg, forward %.3f m", aim_pitch, aim_yaw, aim_forward);
}
XrResult result = fn(session, &fixed, space);
if (layer_debug && XR_SUCCEEDED(result) && space && kind >= 0) {
pthread_mutex_lock(&pose_lock);
if (pose_space_count < MAX_POSE_ACTIONS) {
pose_spaces[pose_space_count].space = *space;
pose_spaces[pose_space_count].subaction = info->subactionPath;
pose_spaces[pose_space_count++].aim = kind;
}
pthread_mutex_unlock(&pose_lock);
LOG("layer_debug: %s action space %p (subaction %llu)", kind ? "aim" : "grip", (void *)(uintptr_t)*space,
(unsigned long long)info->subactionPath);
}
return result;
}
// layer_debug: about once a second, the aim pose of each hand expressed in its grip pose.
static void debug_aim_vs_grip(XrTime time) {
static int64_t last;
int64_t now = monotonic_ns();
if (!layer_debug || !time || now - last < 1000000000ll) return;
last = now;
PFN_xrLocateSpace locate = (PFN_xrLocateSpace)lookup(active_instance, "xrLocateSpace");
if (!locate) return;
pthread_mutex_lock(&pose_lock);
for (int a = 0; a < pose_space_count; ++a) {
if (!pose_spaces[a].aim) continue;
for (int g = 0; g < pose_space_count; ++g) {
if (pose_spaces[g].aim || pose_spaces[g].subaction != pose_spaces[a].subaction) continue;
XrSpaceLocation loc = {XR_TYPE_SPACE_LOCATION, NULL, 0, {{0, 0, 0, 1}, {0, 0, 0}}};
if (XR_SUCCEEDED(locate(pose_spaces[a].space, pose_spaces[g].space, time, &loc)) &&
(loc.locationFlags & XR_SPACE_LOCATION_ORIENTATION_VALID_BIT)) {
XrQuaternionf q = loc.pose.orientation;
float pitch = asinf(fmaxf(-1, fminf(1, 2 * (q.w * q.x - q.y * q.z)))) * 180 / LM_PI;
float yaw = atan2f(2 * (q.w * q.y + q.x * q.z), 1 - 2 * (q.x * q.x + q.y * q.y)) * 180 / LM_PI;
LOG("layer_debug: aim in grip (subaction %llu): pos %.3f,%.3f,%.3f pitch %.1f yaw %.1f flags 0x%llx",
(unsigned long long)pose_spaces[a].subaction, loc.pose.position.x, loc.pose.position.y,
loc.pose.position.z, pitch, yaw, (unsigned long long)loc.locationFlags);
}
break;
}
}
pthread_mutex_unlock(&pose_lock);
}
// ---------------------------------------------------------------- refresh rate
static void debug_refresh_rates(XrSession session) {
PFN_xrEnumerateDisplayRefreshRatesFB enumerate =
(PFN_xrEnumerateDisplayRefreshRatesFB)lookup(active_instance, "xrEnumerateDisplayRefreshRatesFB");
PFN_xrGetDisplayRefreshRateFB get = (PFN_xrGetDisplayRefreshRateFB)lookup(active_instance, "xrGetDisplayRefreshRateFB");
float rates[32], current = 0;
uint32_t n = 0;
char text[256] = "";
if (enumerate && XR_SUCCEEDED(enumerate(session, 32, &n, rates)))
for (uint32_t i = 0, used = 0; i < n && i < 32 && used < sizeof(text) - 8; ++i)
used += (uint32_t)snprintf(text + used, sizeof(text) - used, " %.0f", rates[i]);
if (get) get(session, &current);
LOG("layer_debug: refresh rates offered:%s; current %.1f Hz", *text ? text : " (unknown)", current);
}
static void refresh_on_begin_session(XrSession session) {
if (layer_debug) debug_refresh_rates(session);
if (refresh_rate <= 0) return;
PFN_xrRequestDisplayRefreshRateFB request =
(PFN_xrRequestDisplayRefreshRateFB)lookup(active_instance, "xrRequestDisplayRefreshRateFB");
XrResult result = request ? request(session, refresh_rate) : XR_ERROR_FUNCTION_UNSUPPORTED;
LOG("refresh_rate: requested %.1f Hz at session start: result %d", refresh_rate, result);
}
static XRAPI_ATTR XrResult XRAPI_CALL hook_request_refresh_rate(XrSession session, float rate) {
PFN_xrRequestDisplayRefreshRateFB fn =
(PFN_xrRequestDisplayRefreshRateFB)lookup(active_instance, "xrRequestDisplayRefreshRateFB");
if (!fn) return XR_ERROR_FUNCTION_UNSUPPORTED;
float wanted = refresh_rate > 0 ? refresh_rate : rate;
XrResult result = fn(session, wanted);
LOG("refresh rate: app asked for %.1f Hz, requested %.1f Hz: result %d", rate, wanted, result);
// A refused override keeps the current rate (as frame-control's compat layer does) instead of failing the app.
return XR_FAILED(result) && refresh_rate > 0 ? XR_SUCCESS : result;
}
static XRAPI_ATTR XrResult XRAPI_CALL hook_xrBeginSession(XrSession session, const XrSessionBeginInfo *info) {
PFN_xrBeginSession fn = (PFN_xrBeginSession)lookup(active_instance, "xrBeginSession");
if (!fn) return XR_ERROR_FUNCTION_UNSUPPORTED;
XrResult result = fn(session, info);
if (XR_SUCCEEDED(result)) { emul_on_begin_session(info); refresh_on_begin_session(session); }
return result;
}
+45 -7
View File
@@ -10,7 +10,7 @@ timefix OpenXR layer for Proton games (linux-arm64, glibc; the NDK's clang build
OculusHMDConnected helper for Rift games under Proton (win-x64 PE; the NDK's clang + lld-link, no Windows SDK), and
rewrites artifacts/SHA256SUMS. Run `frameport parity` afterwards to see which games change.
python native/build.py [--only adapter,bridge,compat,glshim,dex,xrlayer,oculushmd] [--ndk PATH]
python native/build.py [--only adapter,bridge,compat,glshim,dex,xrlayer,oculushmd,xrshim,vkshim,vrsettings] [--ndk PATH]
"""
from __future__ import annotations
@@ -138,8 +138,8 @@ def build_adapter(tc: Path):
common = ["-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror", "-Wno-gnu-conditional-omitted-operand",
"-Wno-missing-field-initializers", "-Wl,-Bsymbolic", "-Wl,-soname,libopenxr_loader_generic.so", "-I", inc]
run([exe(tc, "aarch64-linux-android29-clang"), *common, "-Wl,-z,max-page-size=16384", "frame_adapter.c", "forwarders.S",
"-ldl", "-llog", "-o", ART / "arm64-v8a/libopenxr_loader_generic.so"], cwd=src)
run([exe(tc, "armv7a-linux-androideabi29-clang"), *common, "frame_adapter.c", "forwarders_arm32.S", "-ldl", "-llog",
"-ldl", "-llog", "-lm", "-o", ART / "arm64-v8a/libopenxr_loader_generic.so"], cwd=src)
run([exe(tc, "armv7a-linux-androideabi29-clang"), *common, "frame_adapter.c", "forwarders_arm32.S", "-ldl", "-llog", "-lm",
"-o", ART / "armeabi-v7a/libopenxr_loader_generic.so"], cwd=src)
@@ -181,6 +181,26 @@ def build_oculushmd(tc: Path, out: Path | None = None, defines=()):
f"/out:{out / 'fp_oculushmd.exe'}"])
VRSETTINGS_IMPORTS = ("LoadLibraryA", "GetProcAddress", "GetCommandLineA", "GetStdHandle", "WriteFile", "ExitProcess")
def build_vrsettings(tc: Path):
"""fp_vrsettings.exe (Windows x64, run on the PC): SteamVR settings through OpenVR's IVRSettings (see the source)."""
src = HERE / "vrsettings"
out = ART / "win-x64"
out.mkdir(parents=True, exist_ok=True)
work = CACHE / "vrsettings"
work.mkdir(parents=True, exist_ok=True)
(work / "kernel32.def").write_text("LIBRARY kernel32.dll\nEXPORTS\n" + "".join(f" {n}\n" for n in VRSETTINGS_IMPORTS))
run([tc / "bin/llvm-dlltool", "-m", "i386:x86-64", "-d", work / "kernel32.def", "-l", work / "kernel32.lib"])
run([tc / "bin/clang", "--target=x86_64-pc-windows-msvc", "-ffreestanding", "-nostdlibinc", "-fno-stack-protector",
"-fno-builtin", "-O2", "-Wall", "-Wextra", "-Werror", f"-ffile-prefix-map={HERE}=native", "-c",
"fp_vrsettings.c", "-o", work / "fp_vrsettings.obj"], cwd=src)
run([tc / "bin/lld-link", "/nologo", "/Brepro", "/nodefaultlib", "/entry:start", "/subsystem:console",
"/dynamicbase", "/highentropyva", "/nxcompat", work / "fp_vrsettings.obj", work / "kernel32.lib",
f"/out:{out / 'fp_vrsettings.exe'}"])
def build_bridge(tc: Path):
src = HERE / "vrapi-bridge"
inc = openxr_include("bridge")
@@ -210,6 +230,23 @@ def build_glshim(tc: Path):
"-Wl,-z,max-page-size=16384", "glshim.c", "-ldl", "-llog", "-o", ART / "arm64-v8a/libglshim.so"], cwd=src)
def build_xrshim(tc: Path):
"""FrameBridge extension shim (see xrshim/xrshim.c): DT_NEEDED-injected in front of overport's libopenxr_loader.so."""
src = HERE / "xrshim"
run([exe(tc, "aarch64-linux-android29-clang"), "-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror",
"-fvisibility=hidden", "-I", openxr_include("adapter"), "-Wl,-soname,libframe_xrshim.so",
"-Wl,-z,max-page-size=16384", "xrshim.c", "-ldl", "-llog", "-o", ART / "arm64-v8a/libframe_xrshim.so"], cwd=src)
def build_vkshim(tc: Path):
"""Vulkan shim (see vkshim/vkshim.c): the engine's dlopen("libvulkan.so") string is pointed at it."""
src = HERE / "vkshim"
run([exe(tc, "aarch64-linux-android29-clang"), "-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror",
"-fvisibility=hidden", "-Wl,-soname,libfp_vk.so", "-Wl,-z,max-page-size=16384", "vkshim.c",
"-Wl,--no-as-needed", "-lvulkan", "-Wl,--as-needed", "-ldl", "-llog", "-o", ART / "arm64-v8a/libfp_vk.so"],
cwd=src)
def build_dex():
javac = shutil.which("javac")
if not javac:
@@ -254,7 +291,7 @@ def write_sums():
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--only", default="adapter,bridge,compat,glshim,dex,xrlayer,oculushmd")
ap.add_argument("--only", default="adapter,bridge,compat,glshim,dex,xrlayer,oculushmd,xrshim,vkshim,vrsettings")
ap.add_argument("--ndk")
args = ap.parse_args()
parts = set(args.only.split(","))
@@ -262,9 +299,10 @@ def main():
(ART / d).mkdir(parents=True, exist_ok=True)
tc = clang_dir(ndk(args.ndk)) if parts - {"dex"} else None
steps = {"adapter": lambda: build_adapter(tc), "bridge": lambda: build_bridge(tc), "compat": lambda: build_compat(tc),
"glshim": lambda: build_glshim(tc), "dex": build_dex, "xrlayer": lambda: build_xrlayer(tc),
"oculushmd": lambda: build_oculushmd(tc)}
for name in ("adapter", "bridge", "compat", "glshim", "dex", "xrlayer", "oculushmd"):
"glshim": lambda: build_glshim(tc), "xrshim": lambda: build_xrshim(tc), "dex": build_dex, "xrlayer": lambda: build_xrlayer(tc),
"oculushmd": lambda: build_oculushmd(tc), "vkshim": lambda: build_vkshim(tc),
"vrsettings": lambda: build_vrsettings(tc)}
for name in ("adapter", "bridge", "compat", "glshim", "xrshim", "vkshim", "dex", "xrlayer", "oculushmd", "vrsettings"):
if name in parts:
log(f"build {name}")
steps[name]()
+286
View File
@@ -0,0 +1,286 @@
// SPDX-License-Identifier: GPL-3.0-only
// FramePort Vulkan shim: drops invalid pNext pointers from render-pass create infos before they reach the Vulkan
// loader. Some engines (e.g. Unreal builds such as Deadpool VR) leave the pNext of unused attachment references
// uninitialized. The Frame's driver never reads it, but Lepton always loads Steam's Fossilize layer, which records
// every render pass, follows the garbage pointer and crashes (SIGSEGV in libVkLayer_fossilize.so).
//
// The engine finds Vulkan with dlopen("libvulkan.so") + dlsym, so FramePort points that string in the engine library
// at this shim (patches/frame/vk_sanitize.py). dlsym on the shim finds the functions below first and every other
// symbol in its dependency, the real libvulkan.so. Valid pointers are kept; a pointer is dropped only when it isn't
// readable memory or doesn't point at a structure type the parent may chain.
#define _GNU_SOURCE
#include <vulkan/vulkan.h>
#include <android/log.h>
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define TAG "FrameBridge"
#define EXPORT __attribute__((visibility("default")))
#define LOG(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
static void *real_vk;
static PFN_vkGetInstanceProcAddr real_gipa;
static PFN_vkGetDeviceProcAddr real_gdpa;
static PFN_vkCreateRenderPass2 real_rp2_trampoline;
static pthread_once_t once = PTHREAD_ONCE_INIT;
static void init(void) {
real_vk = dlopen("libvulkan.so", RTLD_NOW | RTLD_LOCAL);
if (real_vk) {
real_gipa = (PFN_vkGetInstanceProcAddr)dlsym(real_vk, "vkGetInstanceProcAddr");
real_gdpa = (PFN_vkGetDeviceProcAddr)dlsym(real_vk, "vkGetDeviceProcAddr");
real_rp2_trampoline = (PFN_vkCreateRenderPass2)dlsym(real_vk, "vkCreateRenderPass2");
}
LOG("vk shim: libvulkan.so %s", real_gipa && real_gdpa ? "OK" : "MISSING");
}
// ---------------------------------------------------------------- pointer checks
static pthread_mutex_t probe_lock = PTHREAD_MUTEX_INITIALIZER;
static int probe_fd[2] = {-1, -1};
// readable(p, n): the kernel copies from p without faulting (write to a pipe fails with EFAULT otherwise)
static int readable(const void *p, size_t n) {
if (!p || ((uintptr_t)p & 7)) return 0;
pthread_mutex_lock(&probe_lock);
if (probe_fd[0] < 0 && pipe2(probe_fd, O_CLOEXEC | O_NONBLOCK)) {
pthread_mutex_unlock(&probe_lock);
return 1; // can't check: trust the pointer (the previous behaviour)
}
ssize_t w = write(probe_fd[1], p, n);
int ok = w == (ssize_t)n;
char sink[64];
while (w > 0) {
ssize_t r = read(probe_fd[0], sink, w < (ssize_t)sizeof sink ? (size_t)w : sizeof sink);
if (r <= 0) break;
w -= r;
}
pthread_mutex_unlock(&probe_lock);
return ok;
}
static int valid_next(const void *p, const VkStructureType *allowed, int n) {
if (!readable(p, sizeof(VkBaseInStructure))) return 0;
VkStructureType s = ((const VkBaseInStructure *)p)->sType;
for (int i = 0; i < n; i++)
if (allowed[i] == s) return 1;
return 0;
}
// ---------------------------------------------------------------- scratch memory for the cleaned copies
typedef struct { void *blocks[64]; int n; } Arena;
static void *arena_dup(Arena *a, const void *src, size_t size) {
if (a->n >= 64) return NULL;
void *p = malloc(size ? size : 1);
if (!p) return NULL;
memcpy(p, src, size);
a->blocks[a->n++] = p;
return p;
}
static void arena_free(Arena *a) {
for (int i = 0; i < a->n; i++) free(a->blocks[i]);
a->n = 0;
}
static int fixes_logged;
static const VkStructureType REF_NEXT[] = {VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_STENCIL_LAYOUT};
static const VkStructureType DESC_NEXT[] = {VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_STENCIL_LAYOUT};
static const VkStructureType DEP_NEXT[] = {VK_STRUCTURE_TYPE_MEMORY_BARRIER_2};
// A copy of `refs` whose pNext pointers are valid (or NULL); the original when nothing needed fixing.
static const VkAttachmentReference2 *clean_refs(Arena *a, const VkAttachmentReference2 *refs, uint32_t count, int *fixes) {
if (!refs || !count) return refs;
VkAttachmentReference2 *copy = NULL;
for (uint32_t i = 0; i < count; i++) {
if (refs[i].pNext && !valid_next(refs[i].pNext, REF_NEXT, 1)) {
if (!copy && !(copy = arena_dup(a, refs, sizeof *refs * count))) return refs;
copy[i].pNext = NULL;
(*fixes)++;
}
}
return copy ? copy : refs;
}
// Structures that may be chained to a subpass or to the create info, with their size (so a chain can be cut after
// them) and whether they hold an attachment reference to clean.
static size_t chain_size(VkStructureType s) {
switch (s) {
case VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE: return sizeof(VkSubpassDescriptionDepthStencilResolve);
case VK_STRUCTURE_TYPE_FRAGMENT_SHADING_RATE_ATTACHMENT_INFO_KHR: return sizeof(VkFragmentShadingRateAttachmentInfoKHR);
case VK_STRUCTURE_TYPE_MULTISAMPLED_RENDER_TO_SINGLE_SAMPLED_INFO_EXT: return sizeof(VkMultisampledRenderToSingleSampledInfoEXT);
case VK_STRUCTURE_TYPE_RENDER_PASS_FRAGMENT_DENSITY_MAP_CREATE_INFO_EXT: return sizeof(VkRenderPassFragmentDensityMapCreateInfoEXT);
case VK_STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO: return sizeof(VkRenderPassMultiviewCreateInfo);
case VK_STRUCTURE_TYPE_RENDER_PASS_INPUT_ATTACHMENT_ASPECT_CREATE_INFO: return sizeof(VkRenderPassInputAttachmentAspectCreateInfo);
case VK_STRUCTURE_TYPE_RENDER_PASS_CREATION_CONTROL_EXT: return sizeof(VkRenderPassCreationControlEXT);
case VK_STRUCTURE_TYPE_RENDER_PASS_CREATION_FEEDBACK_CREATE_INFO_EXT: return sizeof(VkRenderPassCreationFeedbackCreateInfoEXT);
case VK_STRUCTURE_TYPE_RENDER_PASS_SUBPASS_FEEDBACK_CREATE_INFO_EXT: return sizeof(VkRenderPassSubpassFeedbackCreateInfoEXT);
case VK_STRUCTURE_TYPE_RENDER_PASS_STRIPE_BEGIN_INFO_ARM: return 0; // not a create-info chain member
default: return 0;
}
}
// Walk a pNext chain from `head` (the pNext value of a structure we own a copy of); returns the new head. Known
// members are copied so a bad link after them can be cut; an unknown but valid member ends the checks (it can't be
// copied without knowing its size, so what follows it stays as is).
static const void *clean_chain(Arena *a, const void *head, int *fixes) {
const void *first = head;
VkBaseOutStructure *prev = NULL; // our copy of the previous member
const void *cur = head;
while (cur) {
if (!readable(cur, sizeof(VkBaseInStructure))) {
if (prev) prev->pNext = NULL; else first = NULL;
(*fixes)++;
break;
}
VkStructureType s = ((const VkBaseInStructure *)cur)->sType;
size_t size = chain_size(s);
if (!size || !readable(cur, size)) {
if (!size && s < 1100000000u && (s < 1000u || s >= 1000000000u)) break; // plausible unknown member: keep
if (prev) prev->pNext = NULL; else first = NULL;
(*fixes)++;
break;
}
VkBaseOutStructure *copy = arena_dup(a, cur, size);
if (!copy) break;
if (s == VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE) {
VkSubpassDescriptionDepthStencilResolve *r = (void *)copy;
r->pDepthStencilResolveAttachment = clean_refs(a, r->pDepthStencilResolveAttachment, 1, fixes);
} else if (s == VK_STRUCTURE_TYPE_FRAGMENT_SHADING_RATE_ATTACHMENT_INFO_KHR) {
VkFragmentShadingRateAttachmentInfoKHR *r = (void *)copy;
r->pFragmentShadingRateAttachment = clean_refs(a, r->pFragmentShadingRateAttachment, 1, fixes);
}
if (prev) prev->pNext = copy; else first = copy;
prev = copy;
cur = copy->pNext;
}
return first;
}
static VkRenderPassCreateInfo2 clean_create_info(Arena *a, const VkRenderPassCreateInfo2 *ci, int *fixes) {
VkRenderPassCreateInfo2 out = *ci;
out.pNext = clean_chain(a, ci->pNext, fixes);
if (ci->pAttachments && ci->attachmentCount) {
VkAttachmentDescription2 *d = arena_dup(a, ci->pAttachments, sizeof *d * ci->attachmentCount);
if (d) {
for (uint32_t i = 0; i < ci->attachmentCount; i++)
if (d[i].pNext && !valid_next(d[i].pNext, DESC_NEXT, 1)) { d[i].pNext = NULL; (*fixes)++; }
out.pAttachments = d;
}
}
if (ci->pSubpasses && ci->subpassCount) {
VkSubpassDescription2 *sp = arena_dup(a, ci->pSubpasses, sizeof *sp * ci->subpassCount);
if (sp) {
for (uint32_t i = 0; i < ci->subpassCount; i++) {
sp[i].pNext = clean_chain(a, sp[i].pNext, fixes);
sp[i].pInputAttachments = clean_refs(a, sp[i].pInputAttachments, sp[i].inputAttachmentCount, fixes);
sp[i].pColorAttachments = clean_refs(a, sp[i].pColorAttachments, sp[i].colorAttachmentCount, fixes);
sp[i].pResolveAttachments = clean_refs(a, sp[i].pResolveAttachments, sp[i].colorAttachmentCount, fixes);
sp[i].pDepthStencilAttachment = clean_refs(a, sp[i].pDepthStencilAttachment, 1, fixes);
}
out.pSubpasses = sp;
}
}
if (ci->pDependencies && ci->dependencyCount) {
VkSubpassDependency2 *dep = arena_dup(a, ci->pDependencies, sizeof *dep * ci->dependencyCount);
if (dep) {
for (uint32_t i = 0; i < ci->dependencyCount; i++)
if (dep[i].pNext && !valid_next(dep[i].pNext, DEP_NEXT, 1)) { dep[i].pNext = NULL; (*fixes)++; }
out.pDependencies = dep;
}
}
return out;
}
// ---------------------------------------------------------------- entry points
#define MAX_DEVICES 8
static struct { VkDevice device; PFN_vkCreateRenderPass2 rp2, rp2khr; } devices[MAX_DEVICES];
static PFN_vkCreateRenderPass2 fallback_rp2khr; // from vkGetInstanceProcAddr
static pthread_mutex_t dev_lock = PTHREAD_MUTEX_INITIALIZER;
static PFN_vkCreateRenderPass2 real_for(VkDevice device, int khr) {
PFN_vkCreateRenderPass2 fn = NULL;
pthread_mutex_lock(&dev_lock);
for (int i = 0; i < MAX_DEVICES; i++)
if (devices[i].device == device) { fn = khr ? devices[i].rp2khr : devices[i].rp2; break; }
pthread_mutex_unlock(&dev_lock);
if (!fn && real_gdpa) fn = (PFN_vkCreateRenderPass2)real_gdpa(device, khr ? "vkCreateRenderPass2KHR" : "vkCreateRenderPass2");
if (!fn) fn = khr ? fallback_rp2khr : real_rp2_trampoline;
return fn;
}
static VkResult create_render_pass2(VkDevice device, const VkRenderPassCreateInfo2 *ci, const VkAllocationCallbacks *alloc,
VkRenderPass *rp, int khr) {
PFN_vkCreateRenderPass2 real = real_for(device, khr);
if (!real) return VK_ERROR_INITIALIZATION_FAILED;
if (!ci) return real(device, ci, alloc, rp);
Arena a = {0};
int fixes = 0;
VkRenderPassCreateInfo2 clean = clean_create_info(&a, ci, &fixes);
if (fixes && fixes_logged < 5) {
fixes_logged++;
LOG("vk shim: dropped %d invalid pNext pointer(s) in vkCreateRenderPass2%s", fixes, khr ? "KHR" : "");
}
VkResult r = real(device, fixes ? &clean : ci, alloc, rp);
arena_free(&a);
return r;
}
EXPORT VKAPI_ATTR VkResult VKAPI_CALL vkCreateRenderPass2(VkDevice device, const VkRenderPassCreateInfo2 *ci,
const VkAllocationCallbacks *alloc, VkRenderPass *rp) {
pthread_once(&once, init);
return create_render_pass2(device, ci, alloc, rp, 0);
}
static VKAPI_ATTR VkResult VKAPI_CALL create_render_pass2_khr(VkDevice device, const VkRenderPassCreateInfo2 *ci,
const VkAllocationCallbacks *alloc, VkRenderPass *rp) {
return create_render_pass2(device, ci, alloc, rp, 1);
}
static PFN_vkVoidFunction wrap(const char *name) {
if (!strcmp(name, "vkCreateRenderPass2")) return (PFN_vkVoidFunction)vkCreateRenderPass2;
if (!strcmp(name, "vkCreateRenderPass2KHR")) return (PFN_vkVoidFunction)create_render_pass2_khr;
return NULL;
}
EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetDeviceProcAddr(VkDevice device, const char *name) {
pthread_once(&once, init);
if (!real_gdpa || !name) return NULL;
PFN_vkVoidFunction fn = real_gdpa(device, name);
PFN_vkVoidFunction w = fn ? wrap(name) : NULL;
if (!w) return fn;
int khr = name[strlen(name) - 1] == 'R';
pthread_mutex_lock(&dev_lock);
int slot = -1;
for (int i = 0; i < MAX_DEVICES; i++) {
if (devices[i].device == device) { slot = i; break; }
if (slot < 0 && !devices[i].device) slot = i;
}
if (slot >= 0) {
devices[slot].device = device;
if (khr) devices[slot].rp2khr = (PFN_vkCreateRenderPass2)fn; else devices[slot].rp2 = (PFN_vkCreateRenderPass2)fn;
}
pthread_mutex_unlock(&dev_lock);
return w;
}
EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetInstanceProcAddr(VkInstance instance, const char *name) {
pthread_once(&once, init);
if (!real_gipa || !name) return NULL;
if (!strcmp(name, "vkGetDeviceProcAddr")) return (PFN_vkVoidFunction)vkGetDeviceProcAddr;
if (!strcmp(name, "vkGetInstanceProcAddr")) return (PFN_vkVoidFunction)vkGetInstanceProcAddr;
PFN_vkVoidFunction fn = real_gipa(instance, name);
PFN_vkVoidFunction w = fn ? wrap(name) : NULL;
if (!w) return fn;
if (!strcmp(name, "vkCreateRenderPass2KHR")) fallback_rp2khr = (PFN_vkCreateRenderPass2)fn;
return w;
}
+189
View File
@@ -0,0 +1,189 @@
/* fp_vrsettings.exe — read/write SteamVR settings through OpenVR's IVRSettings (Windows x64, run on the PC).
*
* SteamVR keeps its settings in memory and rewrites steamvr.vrsettings on exit, so editing the file while SteamVR runs
* is lost. This helper connects as a utility application (no rendering, no hardware), which works whether SteamVR is
* running or not, and changes settings the supported way; SteamVR applies and persists them.
*
* fp_vrsettings.exe <openvr_api.dll> (get|set) <section> <key> <b|i|f|s> [value] [(get|set) ...]
*
* Prints one line per operation: "ok <section> <key> <value>" or "error <section> <key> <SteamVR error>".
* Exit code 0 when every operation succeeded, 1 on an error, 2 on bad usage / OpenVR init failure.
* Freestanding (no CRT, no Windows SDK headers): built by native/build.py with the NDK's clang + lld-link.
*/
typedef void *HANDLE;
typedef unsigned long DWORD;
typedef int BOOL;
#define WINAPI __attribute__((ms_abi))
#define IMPORT __declspec(dllimport)
IMPORT HANDLE WINAPI LoadLibraryA(const char *);
IMPORT void *WINAPI GetProcAddress(HANDLE, const char *);
IMPORT char *WINAPI GetCommandLineA(void);
IMPORT HANDLE WINAPI GetStdHandle(DWORD);
IMPORT BOOL WINAPI WriteFile(HANDLE, const void *, DWORD, DWORD *, void *);
IMPORT __attribute__((noreturn)) void WINAPI ExitProcess(unsigned);
#define STD_OUTPUT_HANDLE ((DWORD)-11)
#define VRApplication_Utility 4
int _fltused = 1; /* MSVC ABI marker the compiler emits for float code (normally from the CRT) */
/* openvr_capi.h: struct VR_IVRSettings_FnTable (IVRSettings_003) */
typedef int EVRSettingsError;
typedef struct {
char *(*GetSettingsErrorNameFromEnum)(EVRSettingsError);
void (*SetBool)(const char *, const char *, int, EVRSettingsError *);
void (*SetInt32)(const char *, const char *, int, EVRSettingsError *);
void (*SetFloat)(const char *, const char *, float, EVRSettingsError *);
void (*SetString)(const char *, const char *, const char *, EVRSettingsError *);
int (*GetBool)(const char *, const char *, EVRSettingsError *);
int (*GetInt32)(const char *, const char *, EVRSettingsError *);
float (*GetFloat)(const char *, const char *, EVRSettingsError *);
void (*GetString)(const char *, const char *, char *, unsigned, EVRSettingsError *);
void (*RemoveSection)(const char *, EVRSettingsError *);
void (*RemoveKeyInSection)(const char *, const char *, EVRSettingsError *);
} SettingsFnTable;
typedef unsigned (*PFN_InitInternal2)(int *, int, const char *);
typedef void (*PFN_ShutdownInternal)(void);
typedef void *(*PFN_GetGenericInterface)(const char *, int *);
static void out(const char *s) {
DWORD n = 0, len = 0;
while (s[len]) len++;
WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), s, len, &n, 0);
}
static void out_int(long long v) {
char buf[24], *p = buf + sizeof buf;
int neg = v < 0;
unsigned long long u = neg ? (unsigned long long)-v : (unsigned long long)v;
*--p = 0;
do *--p = (char)('0' + u % 10); while (u /= 10);
if (neg) *--p = '-';
out(p);
}
static void out_float(float f) { /* 3 decimals is plenty for refresh rates / scales */
long long milli = (long long)(f * 1000.0f + (f < 0 ? -0.5f : 0.5f));
if (milli < 0) { out("-"); milli = -milli; }
out_int(milli / 1000);
char frac[5] = {'.', (char)('0' + milli / 100 % 10), (char)('0' + milli / 10 % 10), (char)('0' + milli % 10), 0};
out(frac);
}
static long long parse_int(const char *s) {
long long v = 0;
int neg = *s == '-';
if (neg || *s == '+') s++;
while (*s >= '0' && *s <= '9') v = v * 10 + (*s++ - '0');
return neg ? -v : v;
}
static float parse_float(const char *s) {
int neg = *s == '-';
if (neg || *s == '+') s++;
float v = 0, scale = 1;
while (*s >= '0' && *s <= '9') v = v * 10 + (float)(*s++ - '0');
if (*s == '.')
for (s++; *s >= '0' && *s <= '9'; s++) v += (float)(*s - '0') * (scale /= 10);
return neg ? -v : v;
}
/* Split the command line in place into argv (double quotes group; no escapes needed for our arguments). */
static int split(char *p, char **argv, int max) {
int n = 0;
while (*p && n < max) {
while (*p == ' ' || *p == '\t') p++;
if (!*p) break;
if (*p == '"') {
argv[n++] = ++p;
while (*p && *p != '"') p++;
} else {
argv[n++] = p;
while (*p && *p != ' ' && *p != '\t') p++;
}
if (*p) *p++ = 0;
}
return n;
}
static int streq(const char *a, const char *b) {
while (*a && *a == *b) a++, b++;
return *a == *b;
}
void start(void) {
static char *argv[128];
int argc = split(GetCommandLineA(), argv, 128);
if (argc < 6) {
out("usage: fp_vrsettings.exe <openvr_api.dll> (get|set) <section> <key> <b|i|f|s> [value] ...\n");
ExitProcess(2);
}
HANDLE lib = LoadLibraryA(argv[1]);
PFN_InitInternal2 init = lib ? (PFN_InitInternal2)GetProcAddress(lib, "VR_InitInternal2") : 0;
PFN_ShutdownInternal shutdown = lib ? (PFN_ShutdownInternal)GetProcAddress(lib, "VR_ShutdownInternal") : 0;
PFN_GetGenericInterface iface = lib ? (PFN_GetGenericInterface)GetProcAddress(lib, "VR_GetGenericInterface") : 0;
if (!init || !shutdown || !iface) {
out("error could not load openvr_api.dll\n");
ExitProcess(2);
}
int err = 0;
init(&err, VRApplication_Utility, 0);
if (err) {
out("error VR_Init failed: ");
out_int(err);
out("\n");
ExitProcess(2);
}
SettingsFnTable *s = (SettingsFnTable *)iface("FnTable:IVRSettings_003", &err);
if (!s || err) {
out("error no IVRSettings_003\n");
shutdown();
ExitProcess(2);
}
int failed = 0;
for (int i = 2; i + 3 < argc;) {
const char *op = argv[i], *section = argv[i + 1], *key = argv[i + 2], *type = argv[i + 3];
int set = streq(op, "set");
if (set && i + 4 >= argc) { out("error missing value\n"); failed = 1; break; }
const char *value = set ? argv[i + 4] : 0;
i += set ? 5 : 4;
EVRSettingsError e = 0;
char buf[512];
buf[0] = 0;
if (set) {
if (type[0] == 'b') s->SetBool(section, key, streq(value, "true") || streq(value, "1"), &e);
else if (type[0] == 'i') s->SetInt32(section, key, (int)parse_int(value), &e);
else if (type[0] == 'f') s->SetFloat(section, key, parse_float(value), &e);
else s->SetString(section, key, value, &e);
}
/* read back (also the result of "get") */
EVRSettingsError ge = 0;
long long iv = 0;
float fv = 0;
if (type[0] == 'b') iv = s->GetBool(section, key, &ge);
else if (type[0] == 'i') iv = s->GetInt32(section, key, &ge);
else if (type[0] == 'f') fv = s->GetFloat(section, key, &ge);
else s->GetString(section, key, buf, sizeof buf, &ge);
EVRSettingsError report = e ? e : ge;
out(report ? "error " : "ok ");
out(section);
out(" ");
out(key);
out(" ");
if (report) {
const char *name = s->GetSettingsErrorNameFromEnum(report);
out(name ? name : "?");
if (set || report != 5 /* UnsetSettingHasNoDefault: "get" of an unset key */) failed = 1;
} else if (type[0] == 'f') {
out_float(fv);
} else if (type[0] == 's') {
out(buf);
} else {
out_int(iv);
}
out("\n");
}
shutdown();
ExitProcess(failed);
}
+56
View File
@@ -0,0 +1,56 @@
// SPDX-License-Identifier: GPL-3.0-only
// FrameBridge extension shim: lets engine plugins reach OpenXR functions that FrameBridge emulates but overport's
// dispatcher (libopenxr_loader.so) doesn't know. overport answers xrGetInstanceProcAddr from a fixed table and returns
// "Unknown proc addr" for anything else (e.g. the XR_FB_render_model functions), so the adapter underneath never sees
// the request.
//
// Meta's OVRPlugin finds xrGetInstanceProcAddr with dlopen("libopenxr_loader.so") + dlsym, so FramePort points that
// string in libOVRPlugin.so at this library instead (patches/frame/adapter.py). Names the adapter emulates are served
// by the adapter (framebridge_extension_proc); everything else goes to overport's xrGetInstanceProcAddr unchanged.
#include <openxr/openxr.h>
#include <android/log.h>
#include <dlfcn.h>
#include <pthread.h>
#include <stddef.h>
#define TAG "FrameBridge"
#define EXPORT __attribute__((visibility("default")))
typedef PFN_xrVoidFunction (*PFN_extension_proc)(const char *name);
static PFN_xrGetInstanceProcAddr overport_gipa;
static pthread_once_t once = PTHREAD_ONCE_INIT;
static void resolve_overport(void) {
void *h = dlopen("libopenxr_loader.so", RTLD_NOW | RTLD_NOLOAD);
if (!h) h = dlopen("libopenxr_loader.so", RTLD_NOW);
if (h) overport_gipa = (PFN_xrGetInstanceProcAddr)dlsym(h, "xrGetInstanceProcAddr");
__android_log_print(ANDROID_LOG_INFO, TAG, "extension shim: overport xrGetInstanceProcAddr %s",
overport_gipa ? "OK" : "MISSING");
}
static PFN_xrVoidFunction adapter_proc(const char *name) {
static PFN_extension_proc fn;
if (!fn) {
// Loaded by overport's dispatcher once an instance exists; NOLOAD so the shim never loads it by itself.
void *h = dlopen("libopenxr_loader_generic.so", RTLD_NOW | RTLD_NOLOAD);
if (h) fn = (PFN_extension_proc)dlsym(h, "framebridge_extension_proc");
if (!fn) return NULL;
}
return fn(name);
}
EXPORT XRAPI_ATTR XrResult XRAPI_CALL xrGetInstanceProcAddr(XrInstance instance, const char *name,
PFN_xrVoidFunction *function) {
pthread_once(&once, resolve_overport);
if (name && function && instance != XR_NULL_HANDLE) {
PFN_xrVoidFunction emulated = adapter_proc(name);
if (emulated) {
__android_log_print(ANDROID_LOG_INFO, TAG, "extension shim: %s -> FrameBridge", name);
*function = emulated;
return XR_SUCCESS;
}
}
if (!overport_gipa) return XR_ERROR_INITIALIZATION_FAILED;
return overport_gipa(instance, name, function);
}
+4 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "frameport"
version = "0.2.0"
dynamic = ["version"]
description = "Port Meta Quest standalone games to the Valve Steam Frame (Lepton): suggested patches, automated validation, one-click install."
readme = "README.md"
license = { text = "GPL-3.0-only" }
@@ -31,6 +31,9 @@ frameport-gui = "frameport.ui.app:main"
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.hatch.version]
path = "src/frameport/_version.py" # the single source of the version
[tool.hatch.build.targets.wheel]
packages = ["src/frameport"]
+101
View File
@@ -0,0 +1,101 @@
"""Turn a "Working configuration" issue (.github/ISSUE_TEMPLATE/working-config.yml) into catalog/games/<pkg>.yaml.
Used by .github/workflows/catalog-from-issue.yml after a maintainer labels the issue `catalog-accepted`; can also be
run by hand: gh issue view 12 --json body -q .body | python scripts/catalog_from_issue.py --issue 12
The issue text is untrusted: only the YAML block of the "Recipe" section is read, parsed with yaml.safe_load, reduced
to known catalog fields and checked (package id, status, types) before anything is written.
"""
from __future__ import annotations
import argparse
import re
import sys
from pathlib import Path
import yaml
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
from frameport.recommend.catalog import CatalogEntry, to_yaml # noqa: E402
PKG_RE = re.compile(r"^(rift\.[a-z0-9_]{1,80}|[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z0-9_]+){1,8})$")
STATUSES = {"works", "issues", "unsupported", "unknown"}
LIST_FIELDS = {"overport_extra", "overport_remove", "alt_overport", "frame", "frame_remove", "pcvr", "pcvr_remove"}
DICT_FIELDS = {"adapter", "device_files", "lepton_env", "proton_env", "verified"}
ID_RE = re.compile(r"^[A-Za-z0-9_.\-]{1,80}$")
class Invalid(ValueError):
pass
def section(body: str, heading: str) -> str:
m = re.search(r"^###\s+" + re.escape(heading) + r"\s*$(.*?)(?=^###\s|\Z)", body, re.M | re.S)
if not m:
raise Invalid(f"no '{heading}' section")
return m.group(1).strip()
def recipe_from_body(body: str) -> dict:
text = section(body, "Recipe")
m = re.search(r"```(?:ya?ml)?\s*\n(.*?)```", text, re.S)
raw = m.group(1) if m else text
try:
d = yaml.safe_load(raw)
except yaml.YAMLError as exc:
raise Invalid(f"recipe isn't valid YAML: {exc}") from None
if not isinstance(d, dict):
raise Invalid("recipe must be a YAML mapping")
return d
def validate(d: dict) -> CatalogEntry:
pkg = d.get("package")
if not isinstance(pkg, str) or not PKG_RE.match(pkg):
raise Invalid(f"bad package id {pkg!r}")
if not isinstance(d.get("title"), str) or not d["title"].strip():
raise Invalid("missing title")
if d.get("status", "unknown") not in STATUSES:
raise Invalid(f"bad status {d.get('status')!r}")
unknown = sorted(set(d) - set(CatalogEntry.__dataclass_fields__) - {"origin"})
if unknown:
raise Invalid(f"unknown fields: {', '.join(unknown)}")
for k in LIST_FIELDS & set(d):
if not isinstance(d[k], list) or not all(isinstance(x, str) and ID_RE.match(x) for x in d[k]):
raise Invalid(f"{k} must be a list of patch ids")
for k in DICT_FIELDS & set(d):
if not isinstance(d[k], dict):
raise Invalid(f"{k} must be a mapping")
for k in ("device_files",):
for path in (d.get(k) or {}):
if not isinstance(path, str) or path.startswith("/") or ".." in Path(path).parts:
raise Invalid(f"{k}: bad path {path!r}")
d = {k: v for k, v in d.items() if k != "origin"}
return CatalogEntry.from_dict(d, "bundled")
def main(argv=None) -> int:
ap = argparse.ArgumentParser()
ap.add_argument("body", nargs="?", help="file with the issue body (default: stdin)")
ap.add_argument("--issue", type=int, help="issue number (recorded in verified.issue)")
ap.add_argument("--out", type=Path, default=ROOT / "catalog" / "games")
a = ap.parse_args(argv)
body = Path(a.body).read_text(encoding="utf-8") if a.body else sys.stdin.read()
try:
entry = validate(recipe_from_body(body))
except Invalid as exc:
print(f"error: {exc}", file=sys.stderr)
return 1
if a.issue:
entry.verified = {**entry.verified, "issue": a.issue}
path = a.out / f"{entry.package}.yaml"
existed = path.exists()
path.write_text(to_yaml(entry), encoding="utf-8")
print(f"{'updated' if existed else 'added'} {path.relative_to(ROOT) if path.is_relative_to(ROOT) else path}")
print(f"package={entry.package}")
return 0
if __name__ == "__main__":
sys.exit(main())
+16
View File
@@ -11,7 +11,9 @@ downloads and manages them on first run (Tools page), so bundles stay small and
from __future__ import annotations
import argparse
import os
import platform
import re
import shutil
import subprocess
import sys
@@ -22,6 +24,18 @@ DATA = ROOT / "src/frameport/_data"
TARGET = {"Windows": "windows", "Darwin": "macos", "Linux": "linux"}[platform.system()]
def version() -> str:
text = (ROOT / "src/frameport/_version.py").read_text(encoding="utf-8")
return re.search(r'__version__\s*=\s*"([^"]+)"', text).group(1)
def check_tag() -> None:
"""A release build (tag vX.Y.Z) must carry that version, or the app's update check would compare wrongly."""
ref = os.environ.get("GITHUB_REF_NAME", "")
if os.environ.get("GITHUB_REF_TYPE") == "tag" and ref.startswith("v") and ref[1:] != version():
raise SystemExit(f"tag {ref} doesn't match src/frameport/_version.py ({version()}): bump it first")
def stage_data():
shutil.rmtree(DATA, ignore_errors=True)
for name in ("catalog", "artifacts", "agent", "bootstrap"):
@@ -34,6 +48,8 @@ def main() -> int:
ap.add_argument("--pyinstaller", action="store_true")
ap.add_argument("--keep-data", action="store_true", help="leave src/frameport/_data after building")
args = ap.parse_args()
check_tag()
print(f"FramePort {version()}")
stage_data()
try:
if args.pyinstaller:
+21 -2
View File
@@ -42,15 +42,34 @@ def main() -> int:
ap.add_argument("--game", default=None)
ap.add_argument("--frame", default=None, help="steamos@host: also connect and run a launch-test job for --game")
ap.add_argument("--no-test", action="store_true", help="with --frame: skip the launch-test job")
ap.add_argument("--scale", type=float, default=1.0, help="UI scale to render at (e.g. 1.5)")
ap.add_argument("--viewport", default="1280x820", help="browser size, e.g. 2560x1440")
ap.add_argument("--update", action="store_true", help="pretend a new FramePort release exists (update UI)")
args = ap.parse_args()
from frameport.ui import theme
theme.set_scale(args.scale)
vw, vh = (int(x) for x in args.viewport.split("x"))
args.out.mkdir(parents=True, exist_ok=True)
game = args.game or (library.games()[0]["package"] if library.games() else None)
steps = [("library", lambda a: a.navigate(0)), ("frame", lambda a: a.navigate(1)), ("tools", lambda a: a.navigate(2))]
if game:
steps.insert(1, ("game", lambda a: a.open_game(game)))
steps.insert(2, ("game-customize", lambda a: a.open_game(game, advanced=True)))
steps += [("share-dialog", lambda a: a.share_config_dialog(game)),
("report-dialog", lambda a: (a.page.pop_dialog(), a.report_problem_dialog(game)))]
# last: the right-click menu stays open over whatever comes next
steps.append(("library-menu", lambda a: (a.navigate(0), time.sleep(3), a.library_view.open_menu(game))))
steps.append(("library-menu", lambda a: (a.page.pop_dialog(), a.navigate(0), time.sleep(3),
a.library_view.open_menu(game))))
if args.update:
from frameport import updates
fake = updates.Update(version="9.9.9", tag="v9.9.9", page="https://example.invalid", asset=None, asset_url=None,
sums_url=None, wheel_url=None,
notes="## What's new\n- Self-update test release\n- **Bold** and `code` in notes")
steps += [("update-banner", lambda a: (a.updater._set(fake), a.navigate(0))),
("update-dialog", lambda a: a.updater.show_dialog()),
("update-settings", lambda a: (a.page.pop_dialog(), a.navigate(2)))]
if args.frame:
from frameport.frame.connection import parse_target
@@ -90,7 +109,7 @@ def main() -> int:
try:
with sync_playwright() as p:
browser = p.chromium.launch(args=["--use-gl=swiftshader", "--enable-unsafe-swiftshader"])
page = browser.new_page(viewport={"width": 1280, "height": 820})
page = browser.new_page(viewport={"width": vw, "height": vh})
page.goto(f"http://127.0.0.1:{PORT}", wait_until="networkidle", timeout=120_000)
shot = 0
deadline = time.time() + 240 + 8 * len(steps)
+63
View File
@@ -0,0 +1,63 @@
#!/usr/bin/env python3
"""CI smoke test of FramePort's self-update on this OS, with the archive this job just built:
python scripts/update_smoke.py FramePort-<os>.<zip|tar.gz>
It unpacks the archive twice (an "installed" copy, plus an older-looking copy of it with a stale marker file), then
runs the real update path: frameport.updates._extract (ditto on macOS) + the real swap script (PowerShell on Windows,
/bin/sh elsewhere), without relaunching. It checks the installed copy now has the new files, and on Windows that the
signer check sees the same certificate on both copies. Exits non-zero on any failure.
"""
from __future__ import annotations
import os
import shutil
import sys
import tempfile
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
def main() -> int:
archive = Path(sys.argv[1]).resolve()
home = Path(tempfile.mkdtemp(prefix="fp-update-smoke-"))
os.environ["FRAMEPORT_HOME"] = str(home / "data")
from frameport import updates
platform = sys.platform
new = updates._extract(archive, home / "staged", platform)
installed_parent = home / "Programs"
installed_parent.mkdir()
installed = installed_parent / new.name
old = updates._extract(archive, home / "old", platform)
shutil.move(str(old), str(installed))
stale = installed / ("Contents/stale.txt" if platform == "darwin" else "stale.txt")
stale.write_text("from the old version")
marker = new / ("Contents/new-version.txt" if platform == "darwin" else "new-version.txt")
marker.write_text("new")
sub = next(p for p in sorted(marker.parent.iterdir()) if p.is_dir() and not p.is_symlink())
nested = sub / "new-version.txt" # files in existing subfolders must be replaced too (Windows merges folders)
nested.write_text("new")
if platform == "win32" and os.environ.get("HAS_CERT") == "true":
a, b = updates._signer_thumbprint(installed / "FramePort.exe"), updates._signer_thumbprint(new / "FramePort.exe")
print(f"signer thumbprints: installed {a} new {b}")
assert a and a == b, "signature check failed"
script = updates.apply(new, installed, relaunch=False, pid=999999, platform=platform, wait=True)
log = (home / "data/logs/update.log").read_text()
print(script.read_text()[:400], "...\n--- update.log ---\n" + log)
installed_marker = installed / marker.relative_to(new)
assert installed_marker.read_text() == "new", "the new files weren't installed"
assert (installed / nested.relative_to(new)).read_text() == "new", "a subfolder wasn't updated"
assert "installed" in log and "FAILED" not in log, "the update script reported a failure"
exe = {"win32": installed / "FramePort.exe", "darwin": installed / "Contents/MacOS"}.get(platform,
installed / "FramePort")
assert exe.exists(), f"{exe} missing after the update"
if platform != "win32": # Windows copies over the old files (the zip has no folder of its own); others swap
assert not stale.exists(), "the old version's files are still there"
print("update smoke test passed")
return 0
if __name__ == "__main__":
sys.exit(main())
+4 -1
View File
@@ -1,3 +1,6 @@
"""FramePort: port Meta Quest standalone games to the Valve Steam Frame."""
__version__ = "0.1.0"
from ._version import __version__ # noqa: F401 (single source of the version)
# Where the project lives (Settings → About, problem reports). Change it here if the repo moves.
REPO_URL = "https://github.com/spoopyghosty0/frameport"
+2
View File
@@ -0,0 +1,2 @@
# The FramePort version: the single source (pyproject reads it via hatch; CI checks a release tag matches it).
__version__ = "0.3.0"
+9
View File
@@ -56,6 +56,11 @@ def _features(manifest: bytes) -> dict[str, bool]:
return out
# OpenXR composition-layer extensions the Frame runtime lacks (see docs/FRAME_RUNTIME.md).
LAYER_EXTENSIONS = ("XR_KHR_composition_layer_cylinder", "XR_KHR_composition_layer_equirect",
"XR_KHR_composition_layer_equirect2", "XR_KHR_composition_layer_cube")
def analyze(path: Path, deep: bool = True, data_bytes: int | None = None) -> Analysis:
path = Path(path)
with zipfile.ZipFile(path) as z:
@@ -100,11 +105,14 @@ def analyze(path: Path, deep: bool = True, data_bytes: int | None = None) -> Ana
uses_glad = False
oculus_os_refs = []
layer_exts = set()
for name, data in lib_bytes.items():
if not elf.is_elf(data):
continue
if b"com/oculus/os/AnalyticsEvent" in data:
oculus_os_refs.append(name)
if name != "libOVRPlugin.so": # OVRPlugin lists every layer extension; only the game's own requests count
layer_exts |= {ext for ext in LAYER_EXTENSIONS if ext.encode() + b"\0" in data}
if name not in ("libvrapi.so", "libOVRPlugin.so") and b"GLAD_GL_" in data and "eglGetProcAddress" in elf.dyn_symbols(data, False):
uses_glad = True
@@ -149,6 +157,7 @@ def analyze(path: Path, deep: bool = True, data_bytes: int | None = None) -> Ana
"hand_tracking_only": features.get("oculus.software.handtracking", False),
"unreal_version": unreal_version,
"oculus_os_refs": sorted(oculus_os_refs),
"xr_layer_exts": sorted(layer_exts), # composition-layer extensions the game's own libraries request
},
)
+19
View File
@@ -87,6 +87,25 @@ def text_instructions(data: bytes):
yield ins[0], ins[2], ins[3]
def replace_rodata_string(data: bytes, old: str, new: str) -> tuple[bytes, int]:
"""Replace NUL-terminated `old` with `new` (not longer; NUL-padded) inside .rodata only, in place (nothing moves;
.dynstr, e.g. DT_NEEDED names, is untouched). Returns (data, number of replacements)."""
if len(new) > len(old):
raise ValueError("replacement must not be longer")
sec = _elf(data).get_section_by_name(".rodata")
if sec is None:
return data, 0
start, end = sec["sh_offset"], sec["sh_offset"] + sec["sh_size"]
needle, repl = old.encode() + b"\0", new.encode().ljust(len(old) + 1, b"\0")
buf, count, i = bytearray(data), 0, start
while (i := buf.find(needle, i, end)) != -1:
if i == start or buf[i - 1] == 0: # a whole string, not the tail of a longer one
buf[i:i + len(needle)] = repl
count += 1
i += len(needle)
return bytes(buf), count
def add_needed(data: bytes, library: str) -> bytes:
"""Add a DT_NEEDED entry in front of the existing ones (same effect as `patchelf --add-needed`; being first matters
for symbol interposition, e.g. the GL shim must precede libEGL).
+65 -4
View File
@@ -40,6 +40,9 @@ PLATFORM_DLLS = ("libovrplatform64_1.dll", "libovrplatform32_1.dll")
PLATFORM_WRAPPERS = ("pnsovr.dll",)
GRAPHICS = (("d3d12.dll", "D3D12"), ("d3d11.dll", "D3D11"), ("vulkan-1.dll", "Vulkan"), ("opengl32.dll", "OpenGL"))
AMBIGUITY = 15 # a runner-up within this many points means "ask the user"
# repacks start their bundled Revive through a proxy DLL next to the exe (Windows loads DLLs from the exe's folder first)
LOADER_DLLS = ("xinput1_3.dll", "xinput1_4.dll", "xinput9_1_0.dll", "dinput8.dll", "version.dll", "winmm.dll")
REVIVE_DLLS = ("librevive64.dll", "librevive32.dll", "librevivexr64.dll", "librevivexr32.dll")
class PEError(Exception):
@@ -330,6 +333,13 @@ def rank_exes(folder: Path, cands: list[Path], manifest: dict | None = None,
if machine == "x86_64":
score += 5
reasons.append("64-bit")
try:
sib = {x.name.lower() for x in p.parent.iterdir()}
except OSError:
sib = set()
if sib & set(REVIVE_DLLS) and sib & set(LOADER_DLLS):
score += 40
reasons.append("set up for SteamVR by the repack (bundled Revive + loader)")
parts = [x.lower() for x in p.relative_to(folder).parts[:-1]]
if any("steam" in x for x in parts):
score -= 10
@@ -424,6 +434,13 @@ def analyze(folder: Path, exe: str | None = None, tree: Tree | None = None) -> A
pass
platform_sdk = any(n in names for n in PLATFORM_DLLS + PLATFORM_WRAPPERS) or bool(platform_imports & set(PLATFORM_DLLS)) or \
b"ovr_PlatformInitializeWindows" in blob or b"ovr_Entitlement_GetIsViewerEntitled" in blob
# how to start it with VR on SteamVR / the Frame (see launch_mode())
try:
exe_dir = {p.name.lower() for p in exe_path.parent.iterdir()}
except OSError:
exe_dir = set()
loader = sorted(n for n in exe_dir if n in LOADER_DLLS) if exe_dir & set(REVIVE_DLLS) else []
mode, args, args_from = launch_mode(folder, chosen, engine, libovr, openxr, openvr, loader)
canonical_hint = next((part for part in exe_path.relative_to(folder).parts[:-1]
if re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+){2,}", part)), None) # Oculus Software dir name
title = (manifest or {}).get("displayName") or clean_title(folder.name)
@@ -440,11 +457,13 @@ def analyze(folder: Path, exe: str | None = None, tree: Tree | None = None) -> A
# is NO Oculus/LibOVR code (pure OpenXR or pure OpenVR). A LibOVR game is treated as Oculus (needs
# Revive, PC only) unless a known-good catalog recipe overrides it (e.g. Rick and Morty, verified on
# the Frame) — static analysis can't tell which runtime a dual-API Unreal build picks at runtime.
"frame_native": (openxr or openvr) and not libovr,
"needs_revive": libovr,
# launch: "repack" (bundled Revive, started by its loader DLL: run the exe directly), "native"
# (SteamVR/OpenXR: run the exe directly, with launch_args) or "revive" (inject FramePort's Revive)
"launch": mode, "loader_dlls": loader, "launch_args": args, "launch_args_from": args_from,
"frame_native": mode == "native",
"needs_revive": mode == "revive",
"vr_found": xr != "?", "data_bytes": tree.size, "files": tree.files,
# repacks ship a LibRevive64.dll for their own (Virtual Desktop) setup; nothing loads it on its own, so
# this is informational only — the game still needs FramePort's Revive for LibOVR → OpenXR
# a LibRevive*.dll anywhere in the folder (see "launch" for whether the game actually starts it)
"revive_bundled": any(n in names for n in ("librevive64.dll", "librevive32.dll", "librevivexr64.dll",
"librevivexr32.dll")),
"oculus_app_id": (manifest or {}).get("appId"),
@@ -452,6 +471,48 @@ def analyze(folder: Path, exe: str | None = None, tree: Tree | None = None) -> A
)
def _vd_to_steamvr(args: str) -> str:
"""Virtual Desktop launcher arguments → the SteamVR/OpenXR equivalent (Unreal's Oculus HMD module → OpenXR)."""
return re.sub(r"(?i)(-hmd=)Oculus(XR)?HMD\b", r"\1OpenXR", args).strip()
def vd_args(folder: Path, exe_rel: str) -> str | None:
"""Arguments the repack's Virtual Desktop launcher (VD.bat next to the exe) passes to the game."""
try:
text = ((folder / exe_rel).parent / "VD.bat").read_text(errors="replace")
except OSError:
return None
m = re.search(r'"?' + re.escape(Path(exe_rel).name) + r'"?[ \t]*([^\r\n]*)', text, re.I)
return m.group(1).strip() if m else None
def launch_mode(folder: Path, exe_rel: str, engine: str, libovr: bool, openxr: bool, openvr: bool,
loader: list[str]) -> tuple[str, str, str]:
"""(mode, game arguments, where the arguments come from), from the game files alone.
repack: the exe's folder has a bundled Revive and a proxy DLL (xinput*.dll) that starts it — the repack is
already set up for SteamVR; launching it through another Revive breaks it (two Revives; e.g. the Oculus
Platform entitlement check then fails). Run the exe directly.
native: no Oculus code, or a dual-API build that also ships SteamVR/OpenXR support (Unreal's OpenVR/OpenXR
plugin under Engine/Binaries/ThirdParty, Unity's openvr_api plugin): run the exe directly with the
SteamVR/OpenXR runtime selected by arguments — the repack's VD.bat arguments with the Oculus module
swapped for OpenXR, else Unreal's -hmd= / Unity's -vrmode.
revive: Oculus-only (LibOVR/OVRPlugin): FramePort's Revive injector translates it."""
if loader:
return "repack", "", "the repack's own launcher (bundled Revive)"
if not libovr and (openxr or openvr):
return "native", "", ""
if engine in ("Unreal", "Unity") and (openxr or openvr):
vd = vd_args(folder, exe_rel)
if vd:
return "native", _vd_to_steamvr(vd), "VD.bat (Oculus HMD module → OpenXR)"
if engine == "Unity":
return "native", "-vrmode OpenVR", "Unity build with SteamVR support"
return ("native", "-hmd=OpenXR", "Unreal build with the OpenXR plugin") if openxr else \
("native", "-hmd=SteamVR", "Unreal build with the SteamVR plugin")
return "revive", "", ""
def is_rift(analysis: Analysis | dict) -> bool:
extra = analysis.get("extra", {}) if isinstance(analysis, dict) else analysis.extra
return (extra or {}).get("kind") == "rift"
+229
View File
@@ -12,6 +12,10 @@
frameport install rift.<game> --to pc|frame # Rift games: this PC (Revive + Steam) or the Frame (Proton)
frameport pc info # Windows Steam / SteamVR / Revive on this PC
frameport parity --known-good <PATCHED dir> # rebuild everything and diff against known-good APKs
frameport diag collect <pkg>|--all [--no-frame] # redacted diagnostics zip (attach it to a GitHub issue)
frameport diag inspect <zip> # re-triage a diagnostics zip (no game files or Frame needed)
frameport diag report <pkg> # zip + prefilled GitHub problem report
frameport share-recipe <pkg> --status works # prefilled GitHub issue submitting a working recipe
"""
from __future__ import annotations
@@ -31,9 +35,102 @@ app = typer.Typer(add_completion=False, no_args_is_help=True, help="Port Meta Qu
tools_app = typer.Typer(help="Manage the portable toolchain.")
frame_app = typer.Typer(help="Find and connect to a Steam Frame.")
pc_app = typer.Typer(help="This PC as a target for Oculus Rift (PC VR) games via Revive.")
diag_app = typer.Typer(help="Diagnostics bundles and problem reports.")
app.add_typer(tools_app, name="tools")
app.add_typer(frame_app, name="frame")
app.add_typer(pc_app, name="pc")
app.add_typer(diag_app, name="diag")
def _show_version(value: bool):
if value:
from . import __version__
typer.echo(f"FramePort {__version__}")
raise typer.Exit()
@app.callback()
def _setup(ctx: typer.Context,
version: bool = typer.Option(False, "--version", is_eager=True, callback=_show_version,
help="Show the FramePort version and exit.")):
from .core import applog
applog.setup("cli")
if ctx.invoked_subcommand != "update":
_update_hint()
def _update_hint() -> None:
"""At most once a day: a one-line note when a newer FramePort release exists. Never waits for the network: it
reads what the last check cached and refreshes a stale cache in the background for next time."""
import threading
import time
from . import updates
if updates.checks_disabled():
return
age = updates.cache_age()
if age is None or age > updates.CHECK_EVERY:
threading.Thread(target=updates.refresh_cache, daemon=True).start()
up = updates.cached_update()
today = time.strftime("%Y-%m-%d")
if up and library.setting("update.cli_hint") != today:
library.set_setting("update.cli_hint", today)
typer.echo(f"FramePort {up.version} is available (you have {_version()}): run \"frameport update\"", err=True)
def _version() -> str:
from . import __version__
return __version__
@app.command("update")
def update_cmd(check: bool = typer.Option(False, "--check", help="Only say whether a newer version exists."),
yes: bool = typer.Option(False, "--yes", "-y", help="Don't ask before updating.")):
"""Update FramePort to the latest release (the app, a `uv tool`/pip install, or a source checkout)."""
import subprocess
from . import updates
up = updates.check(force=True)
if not up:
typer.echo(f"FramePort {_version()} is the latest version.")
return
typer.echo(f"FramePort {up.version} is available (you have {_version()}). {up.page}")
notes = [line for line in up.notes.strip().splitlines()][:25]
if notes:
typer.echo("\n" + "\n".join(" " + line for line in notes) + "\n")
if check:
raise typer.Exit(10) # scripts: 10 = an update is available
kind = updates.install_kind()
if kind == "source" and updates.source_is_dirty():
typer.echo("This source checkout has uncommitted changes: commit or stash them first.", err=True)
raise typer.Exit(1)
if not yes and not typer.confirm(f"Update now ({kind})?", default=True):
raise typer.Exit()
if kind == "bundle":
rep = printing_reporter()
app_dir = updates.prepare(up, rep)
updates.apply(app_dir, relaunch=False)
typer.echo(f"FramePort {up.version} installs as soon as this command exits.")
return
cmds = updates.upgrade_commands(up, kind)
if kind == "wheel" and sys.platform == "win32":
# the running frameport.exe can't be replaced while it runs: finish the upgrade right after this exits
line = " && ".join(subprocess.list2cmdline(c) for c in cmds)
subprocess.Popen(f'cmd /c "timeout /t 2 /nobreak >nul && {line}"', creationflags=0x00000008 | 0x00000200,
close_fds=True)
typer.echo(f"Updating to FramePort {up.version} in the background: run `frameport --version` in a few seconds.")
return
for cmd in cmds:
typer.echo("$ " + " ".join(cmd))
if subprocess.call(cmd):
typer.echo("Update failed.", err=True)
raise typer.Exit(1)
typer.echo(f"Updated to FramePort {up.version}.")
def _target(frame: Optional[str], password: Optional[str] = None, to: str = "frame"):
@@ -310,11 +407,45 @@ def frame_cleanup(frame: Optional[str] = None, keep_rollback: bool = typer.Optio
typer.echo(f"removed {len(r['removed'])} item(s), freed {r['freed_bytes'] / 2**30:.1f} GiB")
@frame_app.command("send")
def frame_send(paths: list[Path] = typer.Argument(..., help="files or folders to send"),
to: str = typer.Option("videos", help="destination: videos, downloads, documents, app, app-files"),
game: Optional[str] = typer.Option(None, help="package of the game, for --to app / app-files"),
folder: str = typer.Option("", help="sub-folder inside the destination"),
app: Optional[str] = typer.Option(None, help="package of a player: also add the files to its own folder "
"(e.g. 4XVR lists /sdcard/4XPlayer, not Movies)"),
frame: Optional[str] = None):
"""Send files to apps on the Frame. videos/downloads/documents are shared by every Quest game (they appear as
/sdcard/Movies, /sdcard/Download, /sdcard/Documents); app/app-files are one game's own storage. Apps find the
files by browsing folders (Android's media index doesn't work in Lepton)."""
from .install import files
r = files.send_files(_target(frame).frame, paths, to, game, folder, printing_reporter(), link_app=app)
typer.echo(f"sent {r['files']} file(s) ({r['bytes'] / 2**20:.0f} MiB, {r['skipped']} already there); "
f"in the app: {r['android']}")
@frame_app.command("storage")
def frame_storage(game: Optional[str] = None, frame: Optional[str] = None):
"""Where files for Lepton apps go on the Frame (and where the apps see them)."""
from .install import files
for t in files.storage_targets(_target(frame).frame, game):
typer.echo(f"{t['id']:10} {t['android']:45} {t['path']}" + (" (every app)" if t["shared"] else ""))
@frame_app.command("info")
def frame_info(frame: Optional[str] = None):
typer.echo(json.dumps(_target(frame).describe(), indent=1, default=str))
@frame_app.command("controller-models")
def frame_controller_models(frame: Optional[str] = None,
convert: bool = typer.Option(False, help="also convert them (cached on the Frame)")):
"""SteamVR render models on the Frame and which ones serve as Steam Frame controller models (controller_models)."""
typer.echo(json.dumps(_target(frame).frame.agent("controller_models", convert=convert), indent=1))
@frame_app.command("proton")
def frame_proton(frame: Optional[str] = None,
install_: bool = typer.Option(False, "--install", help="install it (Steam on the Frame restarts once "
@@ -421,6 +552,104 @@ def uninstall_app(frame: bool = typer.Option(False, help="also remove FramePort'
" Delete the FramePort program folder to finish (or `uv tool uninstall frameport`).")
# ------------------------------------------------------------------------------------------ diagnostics / sharing
def _diag_target(no_frame: bool, frame: Optional[str], to: str):
if no_frame:
return None
try:
return _target(frame, to=to)
except Exception as exc: # noqa: BLE001 (offline Frame: PC-side data only)
typer.echo(f"({to} not reachable: {exc}; collecting the PC side only)")
return None
def _open(url: str, browser: bool) -> None:
from .core import winhost
typer.echo(url)
if browser and not winhost.open_url(url):
typer.echo("(couldn't open a browser: open the link above)")
@diag_app.command("collect")
def diag_collect(package: Optional[str] = typer.Argument(None, help="a game (omit for app-wide logs only)"),
all_: bool = typer.Option(False, "--all"), frame: Optional[str] = None,
no_frame: bool = typer.Option(False, "--no-frame", help="don't contact the Frame"),
to: str = typer.Option("frame", help="where the game is installed: frame or pc"),
out: Optional[Path] = typer.Option(None, help="folder or .zip path (default: Documents)")):
"""Write a redacted diagnostics zip: logs, recipe, analysis, device info (no game files, no personal data)."""
pkgs = _pkgs(package, all_) if (package or all_) else []
path = pipeline.collect_diagnostics(pkgs, _diag_target(no_frame, frame, to), printing_reporter(False), out)
typer.echo(f"wrote {path}")
@diag_app.command("inspect")
def diag_inspect(bundle: Path, as_json: bool = typer.Option(False, "--json")):
"""Summarize a diagnostics zip and re-triage its launch logs with this version's signatures."""
from .diag import bundle as b
res = b.read(bundle)
if as_json:
typer.echo(json.dumps(res, indent=1, default=str))
return
m = res["manifest"]
env = m.get("env", {})
typer.echo(f"created {m.get('created')} by FramePort {env.get('app')}; {env.get('os')}; "
f"Frame: {(env.get('frame') or {}).get('build_id') or '-'}")
for w in m.get("warnings", []):
typer.echo(f" warning: {w}")
for pkg, g in res["games"].items():
typer.echo(f"\n{pkg} — {g.get('title')} [{g.get('status')}]")
last = g.get("last_test") or {}
if last:
typer.echo(f" last test: {last.get('state')} ({last.get('verdict')}) furthest: {last.get('milestone')}")
t = g.get("triage")
if t:
typer.echo(f" re-triage of {g['log']}: {t['verdict']}, furthest: {t['milestone']}")
for f in t["findings"]:
typer.echo(f" {f['severity']:7} {f['id']}: {f['diagnosis']}\n {f['evidence'][:200]}")
if t["suggestions"]:
typer.echo(f" suggested patches: {', '.join(t['suggestions'])}")
@diag_app.command("report")
def diag_report(package: Optional[str] = typer.Argument(None), description: str = typer.Option("", "--text"),
frame: Optional[str] = None, no_frame: bool = typer.Option(False, "--no-frame"),
to: str = typer.Option("frame"), out: Optional[Path] = None,
browser: bool = typer.Option(True, "--browser/--no-browser")):
"""Collect a diagnostics zip and open a prefilled GitHub problem report (attach the zip there)."""
from .core import winhost
pkgs = _pkgs(package, False) if package else []
target = _diag_target(no_frame, frame, to)
info = None
if target is not None:
try:
info = target.describe()
except Exception: # noqa: BLE001
target = None
path = pipeline.collect_diagnostics(pkgs, target, printing_reporter(False), out)
typer.echo(f"wrote {path} — attach it to the issue")
if browser:
winhost.open_folder(path, select=True)
_open(pipeline.problem_report(pkgs[0] if pkgs else None, description, path, info), browser)
@app.command("share-recipe")
def share_recipe(package: str, status: str = typer.Option("works", help="works or issues"),
notes: str = typer.Option("", help="what you checked in the headset, known issues"),
frame: Optional[str] = typer.Option(None, help="include the Frame's SteamOS build"),
browser: bool = typer.Option(True, "--browser/--no-browser")):
"""Submit a working configuration: saves it as a known-good recipe and opens a prefilled GitHub issue."""
if status not in ("works", "issues"):
raise typer.BadParameter("--status must be works or issues")
pkg = _pkgs(package, False)[0]
info = None
if frame:
info = _target(frame).describe()
_open(pipeline.share_working_config(pkg, status, notes, info), browser)
def main(): # pragma: no cover
app()
+72
View File
@@ -0,0 +1,72 @@
"""The app's own log (<data>/logs/app.log, rotated) and saved job logs (<data>/logs/jobs/), for diagnostics bundles."""
from __future__ import annotations
import logging
import logging.handlers
import re
import sys
import time
from pathlib import Path
from .paths import user_data_dir
log = logging.getLogger("frameport")
KEEP_JOB_LOGS = 30
def logs_dir() -> Path:
path = user_data_dir() / "logs"
path.mkdir(parents=True, exist_ok=True)
return path
def jobs_dir() -> Path:
path = logs_dir() / "jobs"
path.mkdir(parents=True, exist_ok=True)
return path
def app_log_path() -> Path:
return logs_dir() / "app.log"
def setup(component: str = "app") -> None:
"""Log to <data>/logs/app.log (2 MB × 3). Safe to call more than once; also records uncaught exceptions."""
if any(getattr(h, "_frameport", False) for h in log.handlers):
return
try:
handler = logging.handlers.RotatingFileHandler(app_log_path(), maxBytes=2 << 20, backupCount=3,
encoding="utf-8")
except OSError:
return
handler._frameport = True
handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s"))
log.addHandler(handler)
log.setLevel(logging.INFO)
log.info("start %s: %s (python %s, %s)", component, _version(), sys.version.split()[0], sys.platform)
previous = sys.excepthook
def hook(kind, exc, tb):
log.error("uncaught exception", exc_info=(kind, exc, tb))
previous(kind, exc, tb)
sys.excepthook = hook
def _version() -> str:
from .. import __version__
return __version__
def save_job_log(kind: str, package: str | None, state: str, text: str) -> Path | None:
"""Keep a finished job's log (the GUI only holds it in memory); the last KEEP_JOB_LOGS are kept."""
try:
d = jobs_dir()
name = re.sub(r"[^A-Za-z0-9._-]+", "_", f"{kind}-{package or 'app'}-{state}")[:120]
path = d / f"{time.strftime('%Y%m%d-%H%M%S')}-{name}.log"
path.write_text(text, encoding="utf-8", errors="replace")
for old in sorted(d.glob("*.log"))[:-KEEP_JOB_LOGS]:
old.unlink(missing_ok=True)
return path
except OSError:
return None
+3 -1
View File
@@ -13,7 +13,9 @@ import requests
from .paths import user_data_dir
USER_AGENT = "FramePort/0.1 (+https://github.com/ovrport/app compatible)"
from .. import REPO_URL, __version__
USER_AGENT = f"FramePort/{__version__} (+{REPO_URL})"
_session = requests.Session()
_session.headers["User-Agent"] = USER_AGENT
+5 -3
View File
@@ -47,8 +47,9 @@ class Reporter:
self.stage_name = name
self.emit(Event("stage", message or name, name))
def progress(self, fraction: float, message: str = "") -> None:
self.emit(Event("progress", message, self.stage_name, fraction=max(0.0, min(1.0, fraction))))
def progress(self, fraction: float, message: str = "", **data) -> None:
"""`data` may carry `speed` (e.g. "42.1 MB/s · ~3 min left") for transfers."""
self.emit(Event("progress", message, self.stage_name, fraction=max(0.0, min(1.0, fraction)), data=data))
def check(self, name: str, ok: bool | None, detail: str = "") -> None:
self.emit(Event("check", detail, self.stage_name, data={"name": name, "ok": ok}))
@@ -72,7 +73,8 @@ def printing_reporter(verbose: bool = True) -> Reporter:
print(f"{stamp} [{mark}] {e.data.get('name')}: {e.message}", flush=True)
elif e.kind == "progress":
if verbose and e.message:
print(f"{stamp} {e.fraction:.0%} {e.message}", flush=True)
speed = f" · {e.data['speed']}" if e.data.get("speed") else ""
print(f"{stamp} {e.fraction:.0%} {e.message}{speed}", flush=True)
elif verbose or e.kind == "error":
print(f"{stamp} {e.message}", flush=True)
+63
View File
@@ -103,6 +103,69 @@ def _migrate(data: dict) -> bool:
continue
done.append("rift_frame_native")
changed = True
if "rift_libovr_redirect" not in done:
# Oculus Rift recipes gain the LoadLibrary redirect (provide Revive's runtime where the game looks for LibOVRRT)
for g in (data.get("games") or {}).values():
a, r = g.get("analysis") or {}, g.get("recipe")
if (isinstance(r, dict) and (a.get("extra") or {}).get("kind") == "rift"
and "pcvr.revive" in (r.get("patches") or {})):
r.setdefault("patches", {}).setdefault("pcvr.libovr_redirect", {})
r.setdefault("reasons", {}).setdefault(
"pcvr.libovr_redirect", "Lets the game find Revive's runtime on the Frame.")
done.append("rift_libovr_redirect")
changed = True
if "rift_launch_modes" not in done:
# Rift games get a launch mode from their files (repack with bundled Revive → run directly; SteamVR/OpenXR-
# capable → run directly with arguments; Oculus-only → FramePort's Revive). Re-analyze (keeping the chosen
# exe) and re-derive the recipe; a repack launched through a second Revive failed (e.g. its entitlement check).
from ..analysis import rift
from ..recommend import engine
for pkg, g in (data.get("games") or {}).items():
a = g.get("analysis") or {}
if not (isinstance(g.get("recipe"), dict) and (a.get("extra") or {}).get("kind") == "rift"):
continue
gd = g.get("game_dir") or (a.get("extra") or {}).get("folder")
try:
if not (gd and Path(gd).is_dir()):
continue
an = rift.analyze(Path(gd), exe=g.get("exe") or (a.get("extra") or {}).get("exe"))
g["analysis"] = asdict(an)
g["recipe"] = recipe_to_dict(engine.suggest(an))
except Exception: # noqa: BLE001
continue
done.append("rift_launch_modes")
changed = True
if "quest_binary_fixes_v2" not in done:
# Quest recipes gain the default-on binary fixes: the swapchain size guard (every overport build) and the
# Vulkan shim (Unreal)
from ..patches import base
for g in (data.get("games") or {}).values():
a, r = g.get("analysis") or {}, g.get("recipe")
if not isinstance(r, dict) or (a.get("extra") or {}).get("kind") == "rift" or r.get("as_is"):
continue
try:
an = analysis_from_dict(a)
except Exception: # noqa: BLE001
continue
for pid in ("frame.swapchain_limit", "frame.vk_sanitize"):
s = base.get(pid).detect(an)
if s and s.recommended:
r.setdefault("patches", {}).setdefault(pid, {})
r.setdefault("reasons", {}).setdefault(pid, s.reason)
done.append("quest_binary_fixes_v2")
changed = True
if "rift_steamvr_tuning" not in done:
# PC VR recipes gain automatic SteamVR performance settings (refresh rate / motion smoothing on frame drops)
for g in (data.get("games") or {}).values():
a, r = g.get("analysis") or {}, g.get("recipe")
if isinstance(r, dict) and (a.get("extra") or {}).get("kind") == "rift":
r.setdefault("patches", {}).setdefault("pcvr.steamvr_tuning", {})
r.setdefault("reasons", {}).setdefault(
"pcvr.steamvr_tuning", "Adjusts the refresh rate / motion smoothing when the game can't keep up.")
done.append("rift_steamvr_tuning")
changed = True
return changed
+220
View File
@@ -0,0 +1,220 @@
"""Automatic SteamVR performance settings for PC VR games (patch pcvr.steamvr_tuning).
After a play session FramePort reads what SteamVR already records: the compositor's per-session summary
(vrcompositor.txt: presents / dropped / reprojected) and, when fpsVR is installed, its CPU/GPU frame-time histograms.
If the game dropped frames, the next Play picks the highest refresh rate the headset offers whose frame budget covers
the game's slow frames (99th percentile) and turns motion smoothing on, through SteamVR's own per-application settings
(fp_vrsettings.exe = OpenVR IVRSettings; SteamVR applies and keeps them). Nothing changes for games that keep up.
"""
from __future__ import annotations
import json
import re
import shutil
import subprocess
from dataclasses import dataclass
from pathlib import Path
from . import winhost
DROP_LIMIT = 0.01 # more than 1 % of frames dropped: tune
HEADROOM = 1.05
# Rates SteamVR headsets commonly offer; used when the headset's own list isn't in the logs (only Steam Link prints it).
# SteamVR snaps a preferred rate to the nearest one the headset supports.
COMMON_RATES = (60.0, 72.0, 80.0, 90.0, 96.0, 100.0, 108.0, 120.0, 144.0)
SMOOTHING_FORCE_ON = 1 # SteamVR per-app motion smoothing: 0 global, 1 force on, 2 force off, 3 force always on
KEY_REFRESH = "preferredRefreshRate"
KEY_SMOOTHING = "motionSmoothingOverride"
_CONNECT = re.compile(r"External connection from (.+?) (\d+)\s*$")
_TOTAL = re.compile(r"- Total\.+\s*(\d+) presents\.\s*(\d+) dropped\.\s*(\d+) reprojected")
_TIMED_OUT = re.compile(r"- Timed out\.\s*(\d+) total")
_RATE = re.compile(r"vrlink: \t([0-9.]+) Hz")
_PREFERRED = re.compile(r"host preferred ([0-9.]+) Hz")
@dataclass
class Session:
presents: int
dropped: int
reprojected: int
timed_out: int = 0 # the compositor gave up waiting for the game's frame and showed the previous one again
hz: float | None = None
frame_ms_p99: float | None = None # max(CPU, GPU) 99th percentile (fpsVR)
@property
def drop_ratio(self) -> float:
"""Frames that weren't new on time: dropped plus compositor timeouts (both show as judder)."""
return (self.dropped + self.timed_out) / self.presents if self.presents else 0.0
def logs_dir(root: Path) -> Path:
return root / "logs"
def _read(path: Path) -> str:
try:
return path.read_text(encoding="utf-8", errors="replace")
except OSError:
return ""
def compositor_session(text: str, exe_name: str) -> Session | None:
"""The last session of `exe_name` in a vrcompositor log (its "Total" line after the game's connection)."""
last, current, cur = None, False, None
for line in text.splitlines():
m = _CONNECT.search(line)
if m:
current = Path(m.group(1).replace("\\", "/")).name.lower() == exe_name.lower()
cur = None
continue
t = _TOTAL.search(line)
if t and current:
cur = last = Session(int(t.group(1)), int(t.group(2)), int(t.group(3)))
continue
o = _TIMED_OUT.search(line)
if o and cur is not None:
cur.timed_out = int(o.group(1))
cur, current = None, False
return last
def last_session(root: Path, exe_name: str) -> Session | None:
for name in ("vrcompositor.txt", "vrcompositor.previous.txt"):
s = compositor_session(_read(logs_dir(root) / name), exe_name)
if s:
return s
return None
def _p99_ms(hist: list[int]) -> float | None:
total = sum(hist)
if not total:
return None
acc = 0
for i, n in enumerate(hist):
acc += n
if acc >= total * 0.99:
return i / 10.0 # fpsVR bins are 0.1 ms
return None
def fpsvr_session(app_key: str, folder: Path | None = None, app_name: str | None = None) -> dict | None:
"""fpsVR's summary of the newest session of this app (hz, p99 frame time), if fpsVR is installed (optional).
Matched by SteamVR app key, or by the program's name (the key changes when the Steam shortcut does)."""
folder = folder or (winhost.env_path("LOCALAPPDATA") or Path("/nonexistent")) / "fpsVR"
best = None
for f in sorted(folder.glob("*.json"), key=lambda p: p.stat().st_mtime, reverse=True) if folder.is_dir() else []:
try:
d = json.loads(f.read_text(encoding="utf-8", errors="replace"))
except (OSError, ValueError):
continue
if d.get("AppKey") == app_key or (app_name and str(d.get("app", "")).lower() == app_name.lower()):
best = d
break
if not best:
return None
ms = [x for x in (_p99_ms(best.get("gputimes") or []), _p99_ms(best.get("cputimes") or [])) if x is not None]
return {"hz": best.get("hz"), "frame_ms_p99": max(ms) if ms else None, "date": best.get("DateEnd")}
def available_rates(root: Path) -> tuple[float, ...]:
"""Refresh rates the headset offers (Steam Link lists them in vrserver.txt), else the common SteamVR rates."""
rates = sorted({round(float(r)) for r in _RATE.findall(_read(logs_dir(root) / "vrserver.txt"))})
return tuple(float(r) for r in rates) or COMMON_RATES
def current_rate(root: Path) -> float | None:
"""The rate the headset runs at: Steam Link's choice, else SteamVR's global preferredRefreshRate setting."""
found = _PREFERRED.findall(_read(logs_dir(root) / "vrserver.txt"))
if found:
return float(found[-1])
try:
rate = json.loads(_read(root / "config" / "steamvr.vrsettings") or "{}").get("steamvr", {}).get(
"preferredRefreshRate")
except ValueError:
rate = None
return float(rate) if rate else None
def recommend(session: Session | None, rates: tuple[float, ...], current: float | None) -> dict | None:
"""{refresh, smoothing, reason} when the last session dropped frames, else None."""
if not session or session.drop_ratio <= DROP_LIMIT:
return None
hz = session.hz or current or max(rates)
lower = [r for r in rates if r < hz - 0.5] or [min(rates)]
if session.frame_ms_p99:
fits = [r for r in rates if 1000.0 / r >= session.frame_ms_p99 * HEADROOM]
refresh = max(fits) if fits else min(rates)
refresh = min(refresh, max(lower)) # always at least one step down from the rate that dropped frames
else:
refresh = max(lower)
why = (f"{session.dropped + session.timed_out} of {session.presents} frames late or dropped "
f"({session.drop_ratio:.1%}) at {hz:.0f} Hz"
+ (f"; slow frames take {session.frame_ms_p99:.1f} ms" if session.frame_ms_p99 else ""))
return {"refresh": refresh, "smoothing": SMOOTHING_FORCE_ON, "reason": why}
def helper() -> Path | None:
"""fp_vrsettings.exe, copied next to FramePort's other Windows files (Windows programs run from Windows paths)."""
from .paths import artifacts_dir
src = artifacts_dir() / "win-x64" / "fp_vrsettings.exe"
base = winhost.env_path("LOCALAPPDATA")
if not src.exists() or not base:
return None
dst = base / "FramePort" / "fp_vrsettings.exe"
try:
if not dst.exists() or dst.read_bytes() != src.read_bytes():
dst.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(src, dst)
except OSError:
return None
return dst
def openvr_dll(root: Path) -> Path | None:
for lib in winhost.steam_libraries(root): # the libraries' steamapps folders
p = lib / "common" / "SteamVR" / "bin" / "win64" / "openvr_api.dll"
if p.exists():
return p
return None
def vrsettings(root: Path, ops: list[tuple[str, str, str, str, str | None]]) -> list[str]:
"""Run fp_vrsettings.exe with (op, section, key, type, value) operations; returns its output lines."""
exe, dll = helper(), openvr_dll(root)
if not exe or not dll:
raise RuntimeError("SteamVR's openvr_api.dll or FramePort's settings helper is missing")
args = [str(exe), winhost.to_windows(dll)]
for op, section, key, kind, value in ops:
args += [op, section, key, kind] + ([value] if op == "set" else [])
p = subprocess.run(args, capture_output=True, text=True, timeout=60, **winhost._no_window())
return [l.strip() for l in (p.stdout or "").splitlines() if l.strip()]
def apply(root: Path, app_key: str, refresh: float | None, smoothing: int | None) -> list[str]:
ops = []
if refresh:
ops.append(("set", app_key, KEY_REFRESH, "f", f"{refresh:.3f}"))
if smoothing is not None:
ops.append(("set", app_key, KEY_SMOOTHING, "i", str(smoothing)))
return vrsettings(root, ops) if ops else []
def tune(root: Path, app_key: str, exe_name: str, params: dict) -> dict:
"""Decide and apply this game's SteamVR settings before it starts. Returns what was done (for the log/UI)."""
fixed_rate = float(params.get("refresh") or 0)
smoothing = params.get("smoothing", "auto")
if fixed_rate or smoothing not in ("auto", None, ""):
sm = {"on": SMOOTHING_FORCE_ON, "off": 2, "always": 3, "global": 0}.get(str(smoothing))
return {"applied": apply(root, app_key, fixed_rate or None, sm), "reason": "set in the patch options"}
session = last_session(root, exe_name)
fps = fpsvr_session(app_key, app_name=Path(exe_name).stem)
if session and fps:
session.hz = fps.get("hz")
session.frame_ms_p99 = fps.get("frame_ms_p99")
rec = recommend(session, available_rates(root), current_rate(root))
if not rec:
return {"applied": [], "reason": "last session kept up" if session else "no session recorded yet"}
return {"applied": apply(root, app_key, rec["refresh"], rec["smoothing"]), **rec}
+51
View File
@@ -223,3 +223,54 @@ def start_steamvr(root: Path, wait: float = 25) -> bool:
time.sleep(2) # let vrserver finish coming up before the game connects
return True
return False
def open_url(url: str) -> bool:
"""Open a link in the user's browser (the Windows browser under WSL)."""
try:
if is_wsl():
# rundll32 passes the URL through untouched (cmd.exe /c start would split it at every '&')
run_win([system32("rundll32.exe"), "url.dll,FileProtocolHandler", url], timeout=15)
return True
import webbrowser
return webbrowser.open(url)
except (OSError, subprocess.SubprocessError):
return False
def open_folder(path: Path | str, select: bool = False) -> bool:
"""Show a folder (or, with select, a file inside its folder) in the file manager."""
path = Path(path)
try:
if is_windows() or is_wsl():
target = to_windows(path)
exe = next((p for p in ("/mnt/c/Windows/explorer.exe",) if is_wsl() and Path(p).exists()), "explorer.exe")
args = [exe] + ([f"/select,{target}"] if select else [target])
subprocess.Popen(args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, **_no_window())
return True
folder = path.parent if select or path.is_file() else path
cmd = ["open", "-R", str(path)] if sys.platform == "darwin" and select else \
["open" if sys.platform == "darwin" else "xdg-open", str(folder)]
subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
return True
except (OSError, ValueError, subprocess.SubprocessError):
return False
PLATFORM_DIRS = ("Meta Horizon/Support/oculus-runtime", "Oculus/Support/oculus-runtime")
@lru_cache(maxsize=1)
def oculus_platform_dir() -> Path | None:
"""Where this PC's Meta Horizon / Oculus app keeps the Oculus Platform SDK runtime (LibOVRPlatform64_1.dll, used
by Oculus Store games for their licence check), or None."""
if not available():
return None
roots = [env_path("ProgramFiles"), env_path("ProgramW6432")] + ([Path("/mnt/c/Program Files")] if is_wsl() else [])
for root in [r for r in roots if r]:
for sub in PLATFORM_DIRS:
d = root / sub
if (d / "LibOVRPlatform64_1.dll").is_file():
return d
return None
+1
View File
@@ -0,0 +1 @@
"""Diagnostics: redacted log bundles and GitHub issue links (working configs, problem reports)."""
+401
View File
@@ -0,0 +1,401 @@
"""Diagnostics bundle: one redacted zip with everything needed to debug a game later, without the game files, the
Frame or this app (see docs/DIAGNOSTICS.md for the layout). Users attach it to a GitHub issue."""
from __future__ import annotations
import contextlib
import io
import json
import platform
import sys
import time
import zipfile
from pathlib import Path
from ..core import applog, library
from ..core.events import Reporter
from ..core.paths import user_data_dir
from . import redact
SCHEMA = 1
MAX_LOG = 4 << 20 # per log file (tail kept)
MAX_TOTAL = 24 << 20 # GitHub's attachment limit is 25 MB
ENTRY_DROP = ("details", "art_source", "artwork", "art") # store metadata: public, big, no debug value
ELF_SYMBOL_PREFIXES = ("ovr", "xr", "vrapi_", "OVR", "Java_", "JNI_", "eglGetProcAddress", "gl")
README = """# FramePort diagnostics bundle
Created by FramePort {version} on {created}. Personal data was replaced by placeholders such as `<ip>`, `<home>`,
`<user>`, `<data>` (FramePort's data folder), `<frame>` and `<steam-id>` (counts in manifest.json → redactions).
| Path | What |
|---|---|
| manifest.json | app / agent / tool versions, OS, which games are included, warnings |
| app/app.log, app/jobs/*.log | the app's log and recent GUI job logs (build, install, launch test, ...) |
| app/settings.json | library settings and catalog sources |
| frame/info.json, frame/host.json | the Frame: SteamOS build, Lepton/Proton, OpenXR runtime + layers, podman, kernel keys |
| games/<pkg>/entry.json | the library entry: analysis, recipe, build checks, installs, last launch test |
| games/<pkg>/recipe.yaml | the recipe in catalog form (catalog/games/<pkg>.yaml) |
| games/<pkg>/triage.json | the newest launch log re-triaged with the triage signatures of this app version |
| games/<pkg>/package/ | stand-in for the game files: file list, AndroidManifest.xml, ELF imports/exports / PE imports |
| games/<pkg>/logs/ | launch-test logs saved on the PC |
| games/<pkg>/target/ | from the Frame (or PC): launch.sh, settings.conf, deployment.json, launch/logcat/Proton/game logs, file list |
## Debugging from this bundle
1. `frameport diag inspect <this zip>` re-runs triage with the current signatures (catalog/triage.yaml).
2. Look up symptoms in docs/PLAYBOOK.md; runtime facts are in docs/FRAME_RUNTIME.md.
3. Compare `recipe.yaml` with `catalog/games/` recipes of games using the same engine / XR API (entry.json → analysis).
4. Headless launch tests can't show the picture: "RUNNING" only proves startup (see FRAME_RUNTIME.md).
"""
def _tail(text: str, limit: int = MAX_LOG) -> str:
if len(text) <= limit:
return text
return f"[... first {len(text) - limit} characters cut ...]\n" + text[-limit:]
def _read_tail(path: Path, limit: int = MAX_LOG) -> str:
try:
size = path.stat().st_size
with path.open("rb") as f:
if size > limit:
f.seek(size - limit)
data = f.read().decode("utf-8", "replace")
return (f"[... first {size - limit} bytes cut ...]\n" if size > limit else "") + data
except OSError as exc:
return f"(unreadable: {exc})"
def _version() -> str:
from .. import __version__
return __version__
class _Writer:
"""Collects redacted files; enforces the total size cap (drops the biggest logs first)."""
def __init__(self, red: redact.Redactor):
self.red = red
self.files: dict[str, bytes] = {}
self.warnings: list[str] = []
def text(self, name: str, text: str, limit: int = MAX_LOG) -> None:
self.files[name] = self.red.text(_tail(text or "", limit)).encode("utf-8", "replace")
def json(self, name: str, obj) -> None:
self.files[name] = self.red.json(obj).encode("utf-8")
def fit(self, limit: int = MAX_TOTAL) -> None:
def zipped():
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
for n, d in self.files.items():
z.writestr(n, d)
return buf.tell()
size = zipped()
while size > limit:
logs = sorted((n for n in self.files if n.endswith((".log", ".txt")) and len(self.files[n]) > 64 << 10),
key=lambda n: -len(self.files[n]))
if not logs:
break
n = logs[0]
self.files[n] = b"[... cut to fit the 25 MB attachment limit ...]\n" + self.files[n][-(len(self.files[n]) // 4):]
self.warnings.append(f"{n} was cut to fit the size limit")
size = zipped()
# ------------------------------------------------------------------------------------------ pieces
def env_info(target_info: dict | None = None) -> dict:
"""Versions and platform facts (manifest.json and the "environment" of GitHub issues)."""
from ..frame.connection import bundled_agent_version
out = {"app": _version(), "agent_bundled": bundled_agent_version(), "python": sys.version.split()[0],
"os": f"{platform.system()} {platform.release()}", "machine": platform.machine()}
try:
from ..core import winhost
out["wsl"] = winhost.is_wsl()
except Exception: # noqa: BLE001
pass
try:
from ..tools import toolchain
out["tools"] = {s.name: s.version for s in toolchain.status(False) if s.installed}
except Exception: # noqa: BLE001
pass
try:
from ..tools import revive
out["revive"] = revive.installed_version()
except Exception: # noqa: BLE001
pass
if target_info:
out["frame"] = {k: target_info.get(k) for k in ("os", "os_version", "build_id", "agent_version", "arch")}
proton = target_info.get("proton") or {}
if isinstance(proton, dict):
ready = proton.get("ready")
out["frame"]["proton"] = ready.get("display_name") or ready.get("name") if isinstance(ready, dict) else ready
return out
def package_listing(g: dict) -> dict[str, object]:
"""A stand-in for the game files: what's in the APK (or Rift folder) and what its binaries link against."""
out: dict[str, object] = {}
if g.get("kind") == "rift":
root = Path(g.get("game_dir") or "")
if root.is_dir():
files = []
for p in sorted(root.rglob("*")):
if p.is_file():
files.append([p.relative_to(root).as_posix(), p.stat().st_size])
if len(files) >= 20000:
break
out["files.json"] = files
from ..analysis import rift
pe = {}
exes = [g.get("exe")] + [p for p, _ in files if p.lower().endswith((".exe", ".dll"))
and any(k in p.lower() for k in ("ovr", "openxr", "openvr", "revive", "oculus"))]
for rel in [e for e in exes if e][:40]:
try:
info, _ = rift.read_pe(root / rel, limit=64 << 20)
pe[rel] = {"machine": info.machine, "subsystem": info.subsystem, "imports": info.imports,
"delay_imports": info.delay_imports}
except Exception as exc: # noqa: BLE001
pe[rel] = {"error": str(exc)}
out["pe.json"] = pe
return out
apk = Path(g.get("apk") or "")
if not apk.is_file():
return out
with zipfile.ZipFile(apk) as z:
infos = z.infolist()
out["apk_files.json"] = [[i.filename, i.file_size] for i in infos[:20000]]
try:
from pyaxmlparser.axmlprinter import AXMLPrinter
out["AndroidManifest.xml"] = AXMLPrinter(z.read("AndroidManifest.xml")).get_xml().decode("utf-8", "replace")
except Exception as exc: # noqa: BLE001
out["AndroidManifest.xml"] = f"(could not decode: {exc})"
elf = {}
for i in infos:
if not (i.filename.startswith("lib/") and i.filename.endswith(".so")):
continue
elf[i.filename] = _elf_summary(z, i)
out["elf.json"] = elf
return out
def _elf_summary(z: zipfile.ZipFile, info: zipfile.ZipInfo) -> dict:
from elftools.elf.dynamic import DynamicSection
from elftools.elf.elffile import ELFFile
from elftools.elf.sections import SymbolTableSection
import shutil
import tempfile
try:
with contextlib.ExitStack() as stack:
f = stack.enter_context(z.open(info))
if info.compress_type != zipfile.ZIP_STORED:
# seeking in a deflated member re-decompresses from the start: unpack once (libs can be > 1 GB)
tmp = stack.enter_context(tempfile.TemporaryFile())
shutil.copyfileobj(f, tmp, 1 << 20)
tmp.seek(0)
f = tmp
elf = ELFFile(f)
res: dict = {"size": info.file_size, "needed": [], "exports": [], "imports": []}
for sec in elf.iter_sections():
if isinstance(sec, DynamicSection):
res["needed"] = [t.needed for t in sec.iter_tags() if t.entry.d_tag == "DT_NEEDED"]
elif isinstance(sec, SymbolTableSection) and sec.name == ".dynsym":
for sym in sec.iter_symbols():
name = sym.name.split("@")[0]
if not name.startswith(ELF_SYMBOL_PREFIXES):
continue
(res["imports"] if sym["st_shndx"] == "SHN_UNDEF" else res["exports"]).append(name)
for k in ("exports", "imports"):
res[k] = sorted(set(res[k]))[:3000]
return res
except Exception as exc: # noqa: BLE001
return {"size": info.file_size, "error": str(exc)[:300]}
def retriage(package: str, log: str, state: str = "UNKNOWN") -> dict:
from ..validate.triage import triage
r = triage(log, state, package)
return {"state": r.state, "verdict": r.verdict, "milestone": r.milestone, "milestones": r.milestones, "fps": r.fps,
"findings": [f.__dict__ for f in r.findings], "suggestions": r.suggestions()}
SOURCE_KEYS = ("apk", "origin", "data_dir", "game_dir") # where the user keeps game dumps: not shared, only names
def source_dirs(g: dict) -> list[str]:
"""Folders of the user's game dumps named by a library entry (redacted as <source>)."""
out = []
for k in SOURCE_KEYS:
v = g.get(k)
if isinstance(v, str) and v:
p = Path(v)
out.append(str(p.parent if k in ("apk",) or p.suffix else p))
ex = (g.get("analysis") or {}).get("extra") or {}
if isinstance(ex.get("folder"), str):
out.append(ex["folder"])
return [d for d in out if d not in ("", ".", "/")]
def _game(w: _Writer, g: dict, target, reporter: Reporter) -> dict:
from ..recommend import catalog
pkg = g["package"]
d = f"games/{pkg}/"
entry = {k: v for k, v in g.items() if k not in ENTRY_DROP}
w.json(d + "entry.json", entry)
try:
w.text(d + "recipe.yaml", catalog.to_yaml(catalog.entry_from_library(g, status=g.get("status") or "unknown")))
except Exception as exc: # noqa: BLE001
w.warnings.append(f"{pkg}: recipe: {exc}")
cat = catalog.lookup(pkg)
if cat:
w.text(d + f"catalog-{cat.origin}.yaml", catalog.to_yaml(cat))
logs = sorted((user_data_dir() / "logs").glob(f"{pkg}-*.log"))
for p in logs:
w.text(d + "logs/" + p.name, _read_tail(p))
if logs:
last = g.get("last_test") or {}
w.json(d + "triage.json", retriage(pkg, _read_tail(logs[-1]), last.get("state") or "UNKNOWN"))
reporter.log(f"{pkg}: game file listing")
try:
for name, data in package_listing(g).items():
if isinstance(data, str):
w.text(d + "package/" + name, data)
else:
w.json(d + "package/" + name, data)
except Exception as exc: # noqa: BLE001
w.warnings.append(f"{pkg}: package listing: {exc}")
remote = None
if target is not None:
reporter.log(f"{pkg}: logs from {target.label}")
try:
remote = target.collect_diag(pkg)
except Exception as exc: # noqa: BLE001
w.warnings.append(f"{pkg}: {target.label}: {exc}")
if remote:
for name, text in (remote.get("files") or {}).items():
w.text(d + "target/" + name.replace("/", "_"), text or "")
if remote.get("listing"):
w.json(d + "target/files.json", remote["listing"])
if not remote.get("installed", True):
w.warnings.append(f"{pkg}: not installed on {target.label}")
return {"package": pkg, "title": g.get("title"), "kind": g.get("kind", "quest"), "status": g.get("status"),
"from_target": bool(remote and remote.get("installed"))}
def collect(packages: list[str] | None, target=None, reporter: Reporter | None = None,
dest: Path | None = None, extra: dict[str, str] | None = None) -> Path:
"""Write the bundle; packages None/[] = app-wide only. target: a connected Target (None = PC-side data only).
extra: more text files to include (e.g. {"report.md": ...})."""
reporter = reporter or Reporter()
reporter.stage("Collecting diagnostics")
info = None
if target is not None:
try:
info = target.describe()
except Exception as exc: # noqa: BLE001
reporter.log(f"{target.label} not reachable: {exc}")
target = None
red = redact.default(info)
for pkg in packages or []:
for d in source_dirs(library.game(pkg) or {}):
red.add("source", d)
w = _Writer(red)
# app-wide
for p in sorted(applog.logs_dir().glob("app.log*"))[:2]:
w.text("app/" + p.name, _read_tail(p, 2 << 20))
jobs = sorted(applog.jobs_dir().glob("*.log"))
wanted = [p for p in jobs if not packages or any(pkg in p.name for pkg in packages)][-15:]
for p in sorted(set(wanted + jobs[-5:])):
w.text("app/jobs/" + p.name, _read_tail(p, 1 << 20))
try:
from ..recommend import catalog
entries = catalog.load()
origins: dict[str, int] = {}
for e in entries.values():
origins[e.origin] = origins.get(e.origin, 0) + 1
w.json("app/settings.json", {"settings": library.load().get("settings", {}), "catalog": origins,
"games": len(library.games())})
except Exception as exc: # noqa: BLE001
w.warnings.append(f"settings: {exc}")
if info:
w.json("frame/info.json", info)
if target is not None:
try:
host = target.collect_diag(None)
if host:
w.json("frame/host.json", host.get("host") or host)
for name, text in (host.get("files") or {}).items():
w.text("frame/" + name, text or "")
except Exception as exc: # noqa: BLE001
w.warnings.append(f"{target.label}: host info: {exc}")
games = []
for pkg in packages or []:
reporter.check_cancel()
g = library.game(pkg)
if not g:
w.warnings.append(f"{pkg}: not in the library")
continue
games.append(_game(w, g, target, reporter))
for name, text in (extra or {}).items():
w.text(name, text)
w.fit()
created = time.strftime("%Y-%m-%d %H:%M:%S")
manifest = {"schema": SCHEMA, "created": created, "env": env_info(info),
"target": target.kind if target is not None else None, "games": games,
"warnings": w.warnings}
w.json("manifest.json", manifest)
manifest["redactions"] = red.summary() # after the last redaction
w.json("manifest.json", manifest)
w.files["README.md"] = README.format(version=_version(), created=created).encode()
if dest is None:
from ..uninstall import default_backup_dir
dest = default_backup_dir()
dest = Path(dest)
if dest.suffix.lower() != ".zip":
dest.mkdir(parents=True, exist_ok=True)
tag = packages[0] if packages and len(packages) == 1 else ("games" if packages else "app")
dest = dest / f"FramePort-diag-{tag}-{time.strftime('%Y%m%d-%H%M%S')}.zip"
with zipfile.ZipFile(dest, "w", zipfile.ZIP_DEFLATED) as z:
for name in ["README.md", "manifest.json"] + sorted(n for n in w.files if n not in ("README.md", "manifest.json")):
z.writestr(name, w.files[name])
reporter.check("Diagnostics bundle", True, f"{dest.name} ({dest.stat().st_size / 2**20:.1f} MB)")
applog.log.info("diagnostics bundle %s", dest)
return dest
def read(zip_path: Path) -> dict:
"""manifest + per-game summary of a bundle (for `frameport diag inspect`)."""
with zipfile.ZipFile(zip_path) as z:
names = z.namelist()
manifest = json.loads(z.read("manifest.json"))
out = {"manifest": manifest, "games": {}}
for g in manifest.get("games", []):
pkg = g["package"]
d = f"games/{pkg}/"
logs = sorted(n for n in names if n.startswith(d + "logs/"))
target_logs = [n for n in names if n.startswith(d + "target/")
and n.rsplit("/", 1)[1] in ("launch.log", "launch-test.log")]
entry = json.loads(z.read(d + "entry.json")) if d + "entry.json" in names else {}
last = entry.get("last_test") or {}
log_name = (logs or target_logs or [None])[-1]
res = {"title": g.get("title"), "status": g.get("status"), "last_test": last, "log": log_name,
"files": [n[len(d):] for n in names if n.startswith(d)]}
if log_name:
res["triage"] = retriage(pkg, z.read(log_name).decode("utf-8", "replace"),
last.get("state") or "UNKNOWN")
out["games"][pkg] = res
return out
+110
View File
@@ -0,0 +1,110 @@
"""Prefilled GitHub "new issue" links (issue forms in .github/ISSUE_TEMPLATE; field ids match the query keys).
No token: the browser opens the form, the user reviews it, drags the diagnostics zip in (GitHub has no API for issue
attachments) and submits. Everything is redacted; URLs stay under ~7.5k characters (longer ones get cut by
browsers/GitHub), trimming free text first and never the recipe.
"""
from __future__ import annotations
from urllib.parse import urlencode
from . import redact
from .. import REPO_URL as REPO
MAX_URL = 7500
def _env_text(env: dict) -> str:
lines = [f"- FramePort {env.get('app')} (agent {env.get('agent_bundled')}), {env.get('os')} {env.get('machine')}"
+ (" (WSL)" if env.get("wsl") else "")]
if env.get("tools"):
lines.append("- tools: " + ", ".join(f"{k} {v}" for k, v in env["tools"].items()))
if env.get("revive") and "revive" not in (env.get("tools") or {}):
lines.append(f"- Revive {env['revive']}")
fr = env.get("frame")
if fr:
lines.append(f"- Frame: {fr.get('os')} {fr.get('os_version')} build {fr.get('build_id')}, "
f"agent {fr.get('agent_version')}" + (f", Proton: {fr['proton']}" if fr.get("proton") else ""))
return "\n".join(lines)
CUT = "\n[... cut; the full text is in the diagnostics zip]"
def _url(template: str, fields: dict[str, str], trim: list[str]) -> str:
"""fields in order; the keys in `trim` are shortened (in that order) until the URL fits."""
fields = {k: v for k, v in fields.items() if v}
while True:
url = f"{REPO}/issues/new?" + urlencode({"template": template, **fields})
over = len(url) - MAX_URL
if over <= 0:
return url
key = next((k for k in trim if k in fields), None)
if key is None:
return url # only untrimmable fields left (e.g. a huge recipe): let GitHub cut it
text = fields[key].removesuffix(CUT)
# encoded text is 1-3x longer than raw text: cutting `over` raw characters (+ slack) always makes progress
keep = len(text) - over - 100
if keep < 40:
fields.pop(key)
else:
fields[key] = text[:keep].rstrip() + CUT
def working_config_url(g: dict, recipe_yaml: str, status: str, notes: str, env: dict,
red: redact.Redactor | None = None) -> str:
red = red or redact.Redactor()
title = g.get("title") or g["package"]
kind = "Oculus Rift (PC VR)" if g.get("kind") == "rift" else "Meta Quest"
a = g.get("analysis") or {}
game = f"{title} — {g['package']} ({kind}, version {a.get('version') or '?'}, {a.get('engine') or '?'} / " \
f"{a.get('xr') or '?'})"
last = g.get("last_test") or {}
result = f"{status}" + (f"; last launch test: {last.get('state')} ({last.get('verdict')}), furthest: "
f"{last.get('milestone') or '-'}" if last else "")
return _url("working-config.yml", {
"title": red.text(f"[Working config] {title}"),
"labels": "working-config",
"game": red.text(game),
"result": red.text(result),
"recipe": red.text(recipe_yaml),
"environment": red.text(_env_text(env)),
"notes": red.text(notes or ""),
}, trim=["notes", "environment", "result"])
def findings_text(summary: dict | None, limit: int = 8) -> str:
if not summary:
return ""
lines = [f"Launch test: {summary.get('state')} ({summary.get('verdict')}), furthest milestone: "
f"{summary.get('milestone') or '-'}" + (f", {summary['fps']:.0f} fps" if summary.get("fps") else "")]
for f in (summary.get("findings") or [])[:limit]:
lines.append(f"- {f.get('severity')} `{f.get('id')}`: {f.get('diagnosis')}")
if f.get("evidence"):
lines.append(f" `{str(f['evidence'])[:200]}`")
if summary.get("suggestions"):
lines.append("Suggested patches: " + ", ".join(summary["suggestions"]))
return "\n".join(lines)
def problem_url(g: dict | None, description: str, env: dict, bundle_name: str | None,
recipe_yaml: str = "", red: redact.Redactor | None = None) -> str:
red = red or redact.Redactor()
title = (g.get("title") or g["package"]) if g else "FramePort"
game = ""
if g:
a = g.get("analysis") or {}
game = f"{title} — {g['package']} (version {a.get('version') or '?'}, {a.get('engine') or '?'} / " \
f"{a.get('xr') or '?'})"
logs = f"⬇ Drag and drop {bundle_name} (the diagnostics zip FramePort just saved) into this box." \
if bundle_name else ""
return _url("bug-report.yml", {
"title": red.text(f"[Problem] {title}"),
"labels": "bug",
"game": red.text(game),
"description": red.text(description or ""),
"findings": red.text(findings_text(g.get("last_test") if g else None)),
"recipe": red.text(recipe_yaml),
"environment": red.text(_env_text(env)),
"logs": logs,
}, trim=["findings", "description", "recipe", "environment"])
+171
View File
@@ -0,0 +1,171 @@
"""Scrub personal data from everything that leaves this PC (diagnostics bundles, GitHub issue text).
Literal values known at runtime (the data dir, home dirs, Frame hosts, Steam account ids, user names) are replaced
exactly; patterns catch the rest (IP/MAC addresses, SteamID64s, e-mail addresses, home paths of any user).
Generic names that carry debug value and no identity (the Frame's `steamos` user, `root`) are kept.
"""
from __future__ import annotations
import getpass
import json
import os
import re
from collections import Counter
from functools import lru_cache
from pathlib import Path
KEEP_USERS = {"steamos", "steamuser", "root", "user", "public", "default", "deck"} # steamuser = Proton prefix user
KEEP_WORDS = KEEP_USERS | {"localhost", "steam", "frame", "steamframe", "windows", "linux"}
MAC = re.compile(r"\b(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\b")
IPV4 = re.compile(r"(?<![\w.])(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?![\w.]*\d)")
IPV6 = re.compile(r"(?<![\w:])(?:[0-9A-Fa-f]{1,4}:){1,7}(?::|(?::[0-9A-Fa-f]{1,4}){1,7}|[0-9A-Fa-f]{1,4})(?![\w:])")
STEAMID64 = re.compile(r"\b7656119\d{10}\b")
USERDATA = re.compile(r"(userdata[\\/]+)(\d+)")
EMAIL = re.compile(r"\b[A-Za-z0-9._%+-]+@(?:[A-Za-z][A-Za-z0-9-]*\.)+"
r"(?!(?:txt|log|gz|xz|zip|tmp|xml|json|png|jpg|dat|bin|so|dll|exe|conf)\b)[A-Za-z]{2,}\b")
# home folders of any user: /home/<u>, /Users/<u>, C:\Users\<u> (also JSON-escaped \\), /mnt/c/Users/<u>
HOME_PATHS = [
re.compile(r"(/home/)([^/\s'\"\\:]+)"),
re.compile(r"(/Users/)([^/\s'\"\\:]+)"),
re.compile(r"(/mnt/[A-Za-z]/Users/)([^/\s'\"\\:]+)", re.I),
re.compile(r"([A-Za-z]:\\{1,2}Users\\{1,2})([^\\/\s'\":]+)", re.I),
re.compile(r"([A-Za-z]:/Users/)([^/\s'\":]+)", re.I),
]
def _ipv4_ok(m: re.Match) -> bool:
"""True if this looks like a real, identifying IPv4 address (not loopback, a netmask or a version number)."""
octets = [int(x) for x in m.groups()]
if any(o > 255 for o in octets) or any(len(x) > 1 and x.startswith("0") for x in m.groups()):
return False
first = octets[0]
return first >= 10 and first != 127 and first != 255 and octets != [0, 0, 0, 0]
def _ipv6_ok(s: str) -> bool:
if s in ("::", "::1") or s.count(":") < 2:
return False
groups = [g for g in s.split(":") if g]
# needs a compressed "::" or all 8 groups, and some hex letter or "::" (timestamps are 12:34:56)
if "::" not in s and len(groups) != 8:
return False
return "::" in s or any(re.search(r"[a-fA-F]", g) for g in groups)
class Redactor:
def __init__(self, known: dict[str, list[str]] | None = None):
self.counts: Counter = Counter()
self.literals: list[tuple[str, str]] = [] # (value, placeholder), longest first
for kind, values in (known or {}).items():
for v in values or []:
self.add(kind, v)
def add(self, kind: str, value) -> None:
v = str(value or "").strip().rstrip("/\\")
if not v or v.lower() in KEEP_WORDS or v in ("/", "~"):
return
if kind == "steam-id" and (not v.isdigit() or len(v) < 6):
return
if kind in ("user", "host") and len(v) < 3:
return
variants = {v}
if kind in ("data", "home"):
variants |= {v.replace("\\", "/"), v.replace("/", "\\"), v.replace("\\", "\\\\")}
for x in variants:
if (x, f"<{kind}>") not in self.literals:
self.literals.append((x, f"<{kind}>"))
self.literals.sort(key=lambda p: -len(p[0]))
def _sub(self, kind: str, pattern: re.Pattern, s: str, repl) -> str:
def f(m):
out = repl(m)
if out != m.group(0):
self.counts[kind] += 1
return out
return pattern.sub(f, s)
def text(self, s: str) -> str:
if not s:
return s
for value, ph in self.literals:
if value in s:
kind = ph.strip("<>")
if kind in ("user", "host", "steam-id"): # whole words only (short values)
s, n = re.subn(r"(?<![\w.-])" + re.escape(value) + r"(?![\w-])", ph, s)
else:
n = s.count(value)
s = s.replace(value, ph)
self.counts[kind] += n
s = self._sub("email", EMAIL, s, lambda m: "<email>")
s = self._sub("mac", MAC, s, lambda m: "<mac>")
s = self._sub("ip", IPV4, s, lambda m: "<ip>" if _ipv4_ok(m) else m.group(0))
s = self._sub("ip", IPV6, s, lambda m: "<ip>" if _ipv6_ok(m.group(0)) else m.group(0))
s = self._sub("steam-id", STEAMID64, s, lambda m: "<steam-id>")
s = self._sub("steam-id", USERDATA, s, lambda m: m.group(1) + "<steam-id>")
for p in HOME_PATHS:
s = self._sub("home", p, s,
lambda m: m.group(0) if m.group(2).lower() in KEEP_USERS or m.group(2).startswith("<")
else m.group(1) + "<user>")
return s
def obj(self, o):
if isinstance(o, str):
return self.text(o)
if isinstance(o, dict):
return {self.text(str(k)) if isinstance(k, str) else k: self.obj(v) for k, v in o.items()}
if isinstance(o, (list, tuple)):
return [self.obj(v) for v in o]
return o
def json(self, o, **kw) -> str:
return json.dumps(self.obj(o), indent=1, default=str, **kw)
def summary(self) -> dict[str, int]:
return dict(sorted(self.counts.items()))
def default(frame_info: dict | None = None) -> Redactor:
"""A Redactor that knows this PC's personal values (and the Frame's, from agent `info`)."""
from ..core.paths import user_data_dir
known: dict[str, list[str]] = {"data": [str(user_data_dir())], "home": [str(Path.home())], "user": [],
"host": [], "steam-id": []}
for name in ("USER", "USERNAME", "LOGNAME"):
known["user"].append(os.environ.get(name, ""))
try:
known["user"].append(getpass.getuser())
except Exception: # noqa: BLE001
pass
for name in ("USERPROFILE", "HOMEPATH"):
if os.environ.get(name):
known["home"].append(os.environ[name])
try:
known["host"].append(os.uname().nodename)
except AttributeError:
known["host"].append(os.environ.get("COMPUTERNAME", ""))
try:
from ..frame.connection import saved_targets
for t in saved_targets():
known["host"] += [t.host, t.name]
except Exception: # noqa: BLE001
pass
if frame_info:
known["host"].append(frame_info.get("hostname", ""))
known["steam-id"] += [str(u) for u in frame_info.get("steam_users") or []]
known["steam-id"].append(pc_steam_user() or "")
return Redactor(known)
@lru_cache(maxsize=1)
def pc_steam_user() -> str | None:
"""This PC's Steam account id (Windows Steam; a few seconds under WSL, so cached)."""
try:
from ..core import winhost
root = winhost.steam_root() if winhost.available() else None
uid = winhost.steam_user(root) if root else None
return str(uid) if uid else None
except Exception: # noqa: BLE001
return None
+91
View File
@@ -0,0 +1,91 @@
"""Send files (videos, documents, mods, saves, ...) to Lepton apps on the Frame.
Lepton gives every app the Frame's ~/Videos, ~/Downloads and ~/Documents as /sdcard/Movies, /sdcard/Download and
/sdcard/Documents (shared by all apps), and each app its own /sdcard (<install>/lepton-data/external). The agent reports
these destinations (`storage_targets`, read from Lepton itself). Android's media index doesn't work inside Lepton, so
media apps find these files by browsing folders, not in "all videos" lists. Some players only list their own folder
in /sdcard (4XVR: "Internal Storage" = /sdcard/4XPlayer): `link_app` hard-links what was sent to the shared folders into
that app's own folder too (agent `link_media`; no copy, no extra space). Uploads are resumable and use the fast link
(USB / the Frame's hotspot) like game installs.
"""
from __future__ import annotations
import posixpath
from pathlib import Path
from ..core.events import Reporter
from ..frame.connection import Frame
from . import installer
TARGETS_HELP = ("videos (/sdcard/Movies in every app), downloads (/sdcard/Download), documents (/sdcard/Documents), "
"app (the game's own /sdcard; needs a game), app-files (/sdcard/Android/data/<package>/files)")
def storage_targets(frame: Frame, package: str | None = None) -> list[dict]:
args = {"package": package} if package else {}
return frame.agent("storage_targets", **args)["targets"]
def _items(paths: list[Path], subdir: str) -> list[tuple[Path, str, int]]:
"""(local file, relative remote path, size); folders keep their structure under their own name."""
items = []
for p in paths:
p = Path(p)
if p.is_dir():
for f in sorted(x for x in p.rglob("*") if x.is_file()):
items.append((f, posixpath.join(subdir, p.name, f.relative_to(p).as_posix()), f.stat().st_size))
elif p.is_file():
items.append((p, posixpath.join(subdir, p.name), p.stat().st_size))
else:
raise FileNotFoundError(f"not found: {p}")
return items
def _remote_size(frame: Frame, path: str) -> int | None:
try:
return frame.sftp.stat(path).st_size
except OSError:
return None
def _safe_subdir(subdir: str) -> str:
parts = [x for x in (subdir or "").replace("\\", "/").split("/") if x and x != "."]
if any(x == ".." for x in parts):
raise ValueError("the folder must stay inside the destination (no '..')")
return "/".join(parts)
def send_files(frame: Frame, paths: list[Path], target: str = "videos", package: str | None = None,
subdir: str = "", reporter: Reporter | None = None, link_app: str | None = None) -> dict:
"""Upload to `target`. With link_app (a shared target only): the files also appear in that app's own folder."""
reporter = reporter or Reporter()
reporter.stage("Prepare the Frame")
dests = {t["id"]: t for t in storage_targets(frame, package if target.startswith("app") else None)}
if target not in dests:
raise ValueError(f"unknown destination {target!r}; choose one of: {', '.join(dests) or TARGETS_HELP}")
dest = dests[target]
sub = _safe_subdir(subdir)
items = _items(paths, sub)
have = [i for i in items if _remote_size(frame, posixpath.join(dest["path"], i[1])) == i[2]]
if have:
reporter.log(f"{len(have)} file(s) already on the Frame; not re-sending")
items = [i for i in items if i not in have]
total = sum(i[2] for i in items)
reporter.log(f"{len(items)} file(s), {total / 2**20:.0f} MiB → {dest['path']} (apps see {dest['android']})")
with installer.transfer_link(frame, reporter, total) as xfer:
reporter.stage(f"Upload {len(items)} file(s)")
installer.upload_files(xfer, items, dest["path"], reporter, max(total, 1))
where = posixpath.join(dest["android"], sub) if sub else dest["android"]
linked = None
if link_app and dest["shared"]:
remote = [posixpath.join(dest["path"], i[1]) for i in items + have]
linked = frame.agent("link_media", package=link_app, files=remote)
if linked.get("folder"):
reporter.log(f"added {len(linked['linked']) + len(linked['existing'])} file(s) to the game's own folder "
f"{linked['android']}")
where = linked["android"]
else:
reporter.log("the game has no folder of its own yet (start it once); it finds the files in " + where)
reporter.log(f"done: in the app, open {where}")
return {"files": len(items), "skipped": len(have), "bytes": total, "path": posixpath.join(dest["path"], sub), "android": where,
"shared": dest["shared"], "linked": linked}
+41 -4
View File
@@ -4,6 +4,7 @@ from __future__ import annotations
import contextlib
import posixpath
import time
from dataclasses import dataclass
from pathlib import Path
@@ -43,6 +44,28 @@ def local_data_manifest(data_dir: Path | None) -> dict[str, int]:
return {p.relative_to(data_dir).as_posix(): p.stat().st_size for p in sorted(data_dir.rglob("*")) if p.is_file()}
class Speed:
"""Upload speed over the last few seconds (a sliding window, so it follows link changes) + time left."""
def __init__(self, total: int, window: float = 5.0, clock=time.monotonic):
self.total, self.window, self.clock, self.samples = total, window, clock, []
def text(self, done: int) -> str:
""""42.1 MB/s · ~3 min left", or "" until there is a second of samples."""
now = self.clock()
self.samples.append((now, done))
while len(self.samples) > 2 and now - self.samples[1][0] >= self.window:
self.samples.pop(0)
(t0, d0) = self.samples[0]
if now - t0 < 1.0 or done <= d0:
return ""
rate = (done - d0) / (now - t0)
left = max(self.total - done, 0) / rate
eta = f"{left / 3600:.0f} h {left % 3600 / 60:02.0f} min" if left >= 3600 else (
f"{left / 60:.0f} min" if left >= 90 else f"{left:.0f} s")
return f"{rate / 1e6:.1f} MB/s · ~{eta} left"
def install(frame: Frame, plan: InstallPlan, reporter: Reporter) -> dict:
reporter.stage("Prepare Frame")
apk_sha = sha256(plan.apk)
@@ -60,6 +83,7 @@ def install(frame: Frame, plan: InstallPlan, reporter: Reporter) -> dict:
f"have {prep['free_bytes'] / 2**30:.1f} GiB")
total = max(need, 1)
sent = 0
speed = Speed(total)
with transfer_link(frame, reporter, need) as xfer:
reporter.stage("Upload APK")
@@ -68,13 +92,13 @@ def install(frame: Frame, plan: InstallPlan, reporter: Reporter) -> dict:
else:
def apk_cb(done, size):
reporter.check_cancel()
reporter.progress(done / total, f"APK {done / 2**20:.0f}/{size / 2**20:.0f} MiB")
reporter.progress(done / total, f"APK {done / 2**20:.0f}/{size / 2**20:.0f} MiB", speed=speed.text(done))
xfer.put(plan.apk, posixpath.join(incoming, "game.apk"), apk_cb)
sent += plan.apk.stat().st_size
if to_send:
reporter.stage(f"Upload data ({len(to_send)} files)")
upload_files(xfer, [(plan.data_dir / rel, f"obb/{rel}", manifest[rel]) for rel in to_send], incoming,
reporter, total, sent)
reporter, total, sent, speed)
elif manifest:
reporter.log("game data already on the Frame; not re-sending")
@@ -91,9 +115,19 @@ def install(frame: Frame, plan: InstallPlan, reporter: Reporter) -> dict:
recipe={"patches": sorted(plan.recipe.patches), "source": plan.recipe.source, "alt": plan.recipe.use_alt},
)
reporter.log(f"installed at {result['base']} (Steam shortcut id {result['appid']})")
log_controller_models(result.get("controller_models"), reporter)
return result
def log_controller_models(models: dict | None, reporter: Reporter) -> None:
"""Outcome of the agent's Steam Frame controller model conversion (adapter setting controller_models)."""
if not models:
return
names = ", ".join(posixpath.basename(v) for v in (models.get("sources") or {}).values())
reporter.check("Steam Frame controller models", bool(models.get("ok")),
f"from SteamVR: {names}" if models.get("ok") else str(models.get("error")))
@dataclass
class PcvrPlan:
package: str # "rift.<slug>"
@@ -175,6 +209,7 @@ def install_pcvr(frame: Frame, plan: PcvrPlan, reporter: Reporter) -> dict:
manifests=manifests, revive=plan.revive_dir is not None, xr_layer=xr_layer, oculus_hmd=oculus_hmd,
env=launch_env(plan.recipe),
game_args=game_args(plan.recipe), no_crash_reporter="pcvr.no_crash_reporter" in plan.recipe.patches,
libovr_redirect="pcvr.libovr_redirect" in plan.recipe.patches,
exe_sha256=plan.exe_sha256, revive_version=plan.revive_version,
recipe={"patches": sorted(plan.recipe.patches), "source": plan.recipe.source},
)
@@ -243,7 +278,7 @@ def transfer_link(frame: Frame, reporter: Reporter, need: int):
def upload_files(frame: Frame, items: list[tuple[Path, str, int]], remote_root: str, reporter: Reporter,
total: int, sent: int = 0) -> int:
total: int, sent: int = 0, speed: Speed | None = None) -> int:
"""Upload (local, relative path, size) items under remote_root. Interruptible (Cancel, dropped connection) and
resumable: finished files are skipped next time (the agent counts files already in incoming/), a cut-off big file
continues from its .part. Returns bytes sent."""
@@ -251,10 +286,12 @@ def upload_files(frame: Frame, items: list[tuple[Path, str, int]], remote_root:
small = [i for i in items if i[2] < BIG_FILE]
frame.mkdirs(posixpath.dirname(posixpath.join(remote_root, rel)) for _, rel, _ in big)
state = {"sent": sent}
speed = speed or Speed(total)
def show(extra: int, label: str):
reporter.check_cancel()
reporter.progress((state["sent"] + extra) / total, label)
done = state["sent"] + extra
reporter.progress(done / total, label, speed=speed.text(done))
for local, rel, size in big:
reporter.check_cancel()
frame.put(local, posixpath.join(remote_root, rel),
+34 -5
View File
@@ -26,7 +26,24 @@ from .recommend import catalog, engine
from .sources import quest_dump
OWNED = {"libopenxr_loader_generic.so": "FrameBridge adapter", "libvrapi.so": "VrApi bridge", "libglshim.so": "GL shim",
"libovrplatformcompat.so": "platform compat"}
"libovrplatformcompat.so": "platform compat", "libfp_vk.so": "Vulkan shim"}
def _default_rewrites(base: str, old: bytes) -> list[tuple[bytes, str]]:
"""In-place rewrites that default-on Frame patches make to a game's own libraries (newer than the known-good
builds): the result of applying them to the known-good bytes."""
from .patches.frame import swapchain_limit, vk_sanitize
out = []
if base == swapchain_limit.DISPATCHER:
fixed, n = swapchain_limit.raise_swapchain_limit(old)
if fixed:
out.append((fixed, f"frame.swapchain_limit: swapchain size guard raised ({n} checks)"))
if base in vk_sanitize.ENGINE_LIBS:
fixed, n = elf.replace_rodata_string(old, vk_sanitize.VULKAN, vk_sanitize.SHIM)
if n:
out.append((fixed, f"frame.vk_sanitize: Vulkan loaded through {vk_sanitize.SHIM}"))
return out
def _entries(apk: Path) -> dict[str, bytes]:
@@ -54,6 +71,9 @@ def classify(name: str, new: bytes, old: bytes) -> tuple[str, str]:
is_current = current is not None and current.exists() and current.read_bytes() == new
return ("expected", f"{OWNED[base]} updated to the current build") if is_current else \
("UNEXPLAINED", f"{OWNED[base]} differs but is not the current artifact")
for fixed, why in _default_rewrites(base, old):
if fixed == new:
return "expected", why
if base == "libframe_settings.so":
def kv(b):
return dict(l.split("=", 1) for l in b.decode().split("\n") if "=" in l)
@@ -100,7 +120,12 @@ def compare(new_apk: Path, old_apk: Path) -> dict:
b.pop(n)
for n in sorted(set(a) | set(b)):
if n not in b:
rows.append((n, "UNEXPLAINED", "only in the new build"))
base = n.rsplit("/", 1)[-1]
current = artifacts_dir() / n.split("/")[1] / base if n.startswith("lib/") and base in OWNED else None
if current is not None and current.exists() and current.read_bytes() == _read(new_apk, n):
rows.append((n, "expected", f"{OWNED[base]} added (current build)"))
else:
rows.append((n, "UNEXPLAINED", "only in the new build"))
elif n not in a:
rows.append((n, "UNEXPLAINED", "missing from the new build"))
elif a[n] != b[n]:
@@ -115,9 +140,13 @@ def compare(new_apk: Path, old_apk: Path) -> dict:
def find_source(sources: Path, hint: str, package: str) -> quest_dump.SourceGame | None:
for d in sorted(sources.iterdir()):
if d.is_dir() and quest_dump.display_name(d.name) == hint:
return quest_dump.from_path(d)
from .recommend.catalog import source_hint_matches
for d in sorted(sources.iterdir()): # by name (loosely: releases name their folders differently)
if d.is_dir() and hint and source_hint_matches(hint, d.name):
g = quest_dump.from_path(d)
if g and quest_dump._package_of(g.apk) == package:
return g
for d in sorted(sources.iterdir()): # slow path: look inside
g = quest_dump.from_path(d) if d.is_dir() else None
if g and quest_dump._package_of(g.apk) == package:
+18
View File
@@ -50,3 +50,21 @@ def unreal_version(a: Analysis) -> tuple[int, int] | None:
return int(major), int(minor)
except (AttributeError, ValueError):
return None
def uses_render_models(a: Analysis) -> bool:
"""The game declares Meta's runtime controller models (XR_FB_render_model): permission or feature RENDER_MODEL."""
perms = a.extra.get("meta_permissions_used") or a.meta_permissions
return any(p.endswith("RENDER_MODEL") for p in perms) or "com.oculus.feature.RENDER_MODEL" in (a.extra.get("features") or {})
def may_use_render_models(a: Analysis) -> bool:
"""Could ask for runtime controller models at all: declares them, or ships Meta's OVRPlugin (Unity/Unreal)."""
return uses_render_models(a) or "libOVRPlugin.so" in a.libs
def uses_equirect_layers(a: Analysis) -> bool:
"""The game's own native code (not Meta's OVRPlugin, which lists every layer type) requests 360° composition
layers, which the Frame runtime lacks; only GLES games can get them back (equirect_emul)."""
exts = a.extra.get("xr_layer_exts") or []
return is_gles(a) and any(e.startswith("XR_KHR_composition_layer_equirect") for e in exts)
+36 -1
View File
@@ -1,12 +1,16 @@
"""FrameBridge: wraps overport's generic OpenXR loader to paper over Steam Frame runtime gaps."""
from __future__ import annotations
from ...analysis import elf
from ..base import ApkContext, Patch, Suggestion, register
from . import artifact
GENERIC = "libopenxr_loader_generic.so"
ORIGINAL = "libopenxr_loader_original.so"
SETTINGS = "libframe_settings.so"
XRSHIM = "libframe_xrshim.so"
OVERPORT_LOADER = "libopenxr_loader.so"
OVRPLUGIN = "libOVRPlugin.so"
def settings_text(recipe_patches: dict) -> bytes:
@@ -22,7 +26,8 @@ class FrameBridgeAdapter(Patch):
"Wraps overport's generic OpenXR loader (renamed libopenxr_loader_original.so). Fixes the Frame runtime's gaps: "
"retries rejected GLES swapchain formats/MSAA (Frame takes sRGB only), drops unsupported instance extensions "
"and layers, emulates XR_FB_passthrough (ALPHA_BLEND), Meta scene/spatial entities (guardian-sized room), "
"XR_KHR_convert_timespec_time, and vertically flipped quad layers; maps Frame controllers to Touch. "
"XR_KHR_convert_timespec_time, and vertically flipped quad layers; maps Frame controllers to Touch; optionally "
"serves Steam Frame controller models (XR_FB_render_model). "
"Settings are in the Adapter settings group."
)
category = "frame"
@@ -49,6 +54,8 @@ class FrameBridgeAdapter(Patch):
if not ws.has(ws.lib(SETTINGS)) or ws.read_lib(SETTINGS) != settings:
ws.put(ws.lib(SETTINGS), settings)
changed = True
if needs_xrshim(ctx.recipe_patches) and ws.abi == "arm64-v8a":
changed |= add_xrshim(ctx)
return changed
def validate(self, ctx: ApkContext):
@@ -57,4 +64,32 @@ class FrameBridgeAdapter(Patch):
return [("FrameBridge adapter present", ok, "adapter, original loader and settings library")]
def needs_xrshim(recipe_patches: dict) -> bool:
"""Adapter features whose functions overport's dispatcher doesn't forward (it only knows a fixed table)."""
from ..settings import adapter_settings
return bool(adapter_settings(recipe_patches).get("controller_models"))
def add_xrshim(ctx: ApkContext) -> bool:
"""Route Meta OVRPlugin's OpenXR lookups through native/xrshim so XR_FB_render_model reaches the adapter.
OVRPlugin gets xrGetInstanceProcAddr with dlopen("libopenxr_loader.so") + dlsym (checked in Toy Master's
OVRPlugin), so the loader name string it dlopens is pointed at the shim instead (same length, in place); the shim
forwards every other lookup to overport's dispatcher."""
ws = ctx.ws
shim = artifact(ws.abi, XRSHIM)
changed = False
if not ws.has(ws.lib(XRSHIM)) or ws.read_lib(XRSHIM) != shim:
ws.put(ws.lib(XRSHIM), shim)
changed = True
if ws.has(ws.lib(OVRPLUGIN)):
data, count = elf.replace_rodata_string(ws.read_lib(OVRPLUGIN), OVERPORT_LOADER, XRSHIM)
if count:
ws.put(ws.lib(OVRPLUGIN), data)
ctx.notes.append(f"{OVRPLUGIN} looks up OpenXR functions through {XRSHIM}")
changed = True
return changed
register(FrameBridgeAdapter)
@@ -0,0 +1,71 @@
"""overport's dispatcher aborts on swapchains wider or taller than 4096 px; raise that guard so the runtime decides."""
from __future__ import annotations
from ...analysis import elf
from ..base import ApkContext, Patch, Suggestion, register
DISPATCHER = "libopenxr_loader.so" # overport's dispatcher (the runtime-specific loader is libopenxr_loader_generic.so)
FUNCS = ("xrCreateSwapchain", "xrCreateSwapchainAndroidSurfaceKHR")
CMP_4096 = 0x7140041F # cmp wN, #1, lsl #12 (subs wzr, wN, #0x1000)
CMP_MASK = 0xFFFFFC1F # everything but Rn
LIMIT_UNITS = 4 # 4 << 12 = 16384 (the Frame's runtime reports 8192 max and rejects larger sizes itself)
VIDEO_LIBS = ("libavcodec", "libffmpeg", "libvlc", "libmpv", "libijkffmpeg")
def raise_swapchain_limit(data: bytes) -> tuple[bytes | None, int]:
"""Rewrite the `cmp wN, #4096` size guards at the start of overport's swapchain entry points."""
try:
dynsym = elf._elf(data).get_section_by_name(".dynsym")
except Exception: # noqa: BLE001
return None, 0
if dynsym is None:
return None, 0
segs, out, n = elf.load_segments(data), bytearray(data), 0
for name in FUNCS:
found = dynsym.get_symbol_by_name(name)
if not found or not found[0]["st_value"]:
continue
off = elf.vaddr_to_offset(segs, found[0]["st_value"])
if off is None:
continue
for at in range(off, off + min(found[0]["st_size"] or 256, 256), 4): # the guard sits in the prologue
word = int.from_bytes(out[at:at + 4], "little")
if word & CMP_MASK == CMP_4096:
out[at:at + 4] = ((word & ~(0xFFF << 10)) | (LIMIT_UNITS << 10)).to_bytes(4, "little")
n += 1
return (bytes(out) if n else None), n
class SwapchainLimit(Patch):
id = "frame.swapchain_limit"
title = "Allow swapchains larger than 4096 px"
description = ("overport's OpenXR dispatcher aborts the app ('Wrong createInfo size', SIGABRT in "
"libopenxr_loader.so xrCreateSwapchain) when a swapchain is wider or taller than 4096 px, which "
"video players do for 8K video or big theatre textures (e.g. 4XVR). Raises the guard to 16384 px so "
"the Frame's runtime (8192 px max) decides instead.")
order = 45
default_on = True
def detect(self, a):
video = sorted(l for l in a.libs if l.lower().startswith(VIDEO_LIBS))
if video:
return Suggestion(True, f"Video player ({', '.join(video[:2])}): creates swapchains larger than 4096 px "
"(8K video, theatre textures), which overport's dispatcher aborts on.")
return Suggestion(True, "Recommended for every game: overport aborts on swapchains larger than 4096 px; "
"the Frame's runtime handles them.")
def applies(self, a):
return a.xr == "OpenXR"
def apply(self, ctx: ApkContext) -> bool:
ws = ctx.ws
if not ws.has(ws.lib(DISPATCHER)):
return False
fixed, n = raise_swapchain_limit(ws.read_lib(DISPATCHER))
if fixed:
ws.put(ws.lib(DISPATCHER), fixed)
ctx.notes.append(f"{DISPATCHER}: swapchain size guard raised to 16384 px ({n} check(s))")
return bool(fixed)
register(SwapchainLimit)
@@ -0,0 +1,57 @@
"""Vulkan shim that drops invalid pNext pointers from render-pass create infos (native/vkshim)."""
from __future__ import annotations
from ...analysis import elf
from ..base import ApkContext, Patch, Suggestion, register
from . import artifact
SHIM = "libfp_vk.so" # not longer than "libvulkan.so": the engine's dlopen string is rewritten in place
VULKAN = "libvulkan.so"
ENGINE_LIBS = ("libUE4.so", "libUnreal.so")
class VulkanSanitize(Patch):
id = "frame.vk_sanitize"
title = "Vulkan: drop invalid render-pass pointers"
description = ("Some engines leave the pNext of unused Vulkan attachment references uninitialized. The Frame's "
"driver never reads it, but Lepton always loads Steam's Fossilize shader-cache layer, which follows "
"it and crashes on the first frame (SIGSEGV in libVkLayer_fossilize.so from FVulkanRenderPass, "
"e.g. Deadpool VR). Loads Vulkan through a small shim that keeps valid pointers and drops only "
"unreadable ones or ones pointing at the wrong structure type.")
order = 72
default_on = True
def detect(self, a):
if a.engine == "Unreal":
return Suggestion(True, "Unreal game: applied automatically when the engine loads Vulkan by name; keeps "
"Lepton's Fossilize layer from crashing on uninitialized pointers (e.g. Deadpool VR).")
return None
def applies(self, a):
return a.engine == "Unreal"
def apply(self, ctx: ApkContext) -> bool:
ws = ctx.ws
if ws.abi != "arm64-v8a":
return False
changed = False
for lib in ENGINE_LIBS:
if not ws.has(ws.lib(lib)):
continue
data, count = elf.replace_rodata_string(ws.read_lib(lib), VULKAN, SHIM)
if count:
ws.put(ws.lib(lib), data)
ctx.notes.append(f"{lib} loads Vulkan through {SHIM}")
changed = True
if changed:
shim = artifact(ws.abi, SHIM)
if not ws.has(ws.lib(SHIM)) or ws.read_lib(SHIM) != shim:
ws.put(ws.lib(SHIM), shim)
return changed
def validate(self, ctx: ApkContext):
ws = ctx.ws
return [("Vulkan shim present", ws.has(ws.lib(SHIM)), SHIM)]
register(VulkanSanitize)
+136 -12
View File
@@ -1,8 +1,12 @@
"""PC VR (Oculus Rift) options, shown in the UI as patches like the overport ones.
They don't edit the game: they decide how FramePort launches it. On this PC the Steam shortcut runs
ReviveInjector.exe (Revive's OpenXR backend by default); on the Frame the launcher runs the same injector under
Proton (ARM64, x86 emulated by FEX inside Proton), which bridges OpenXR to the Frame runtime via wineopenxr.
They don't edit the game: they decide how FramePort launches it. The analysis (analysis/rift.py launch_mode)
picks one of three ways, and the patches below follow it (the user can change each one):
repack pcvr.repack_launcher: the folder is already set up for SteamVR (bundled Revive + its loader DLL) → run
the exe directly (on the Frame, Wine is told to load the loader DLL from the game folder)
native pcvr.launch_args: SteamVR/OpenXR-capable build → run the exe directly with the arguments that select it
revive pcvr.revive: Oculus-only → the Steam shortcut runs ReviveInjector.exe (on the Frame: under Proton, OpenXR
bridged to the Frame runtime via wineopenxr)
"""
from __future__ import annotations
@@ -13,6 +17,14 @@ def _rift(analysis) -> bool:
return (analysis.extra or {}).get("kind") == "rift"
def _mode(analysis) -> str:
"""repack | native | revive (older analyses without "launch": from their flags)."""
x = analysis.extra or {}
if x.get("launch"):
return x["launch"]
return "native" if x.get("frame_native") else "revive"
class _PcvrPatch(Patch):
category = "pcvr"
stage = "install"
@@ -27,14 +39,19 @@ class Revive(_PcvrPatch):
description = ("Launch the game through Revive's injector, which translates the Oculus PC SDK (LibOVR) to OpenXR. "
"Needed by every Oculus Rift game that isn't OpenXR-native. FramePort downloads Revive itself.")
order = 10
conflicts = ("pcvr.repack_launcher",)
def detect(self, analysis):
# Oculus/LibOVR games need Revive to get VR (the bare exe runs flat). Off for games with no Oculus code, which
# SteamVR (PC) and the Frame's wineopenxr run directly (e.g. Rick and Morty, handled by its catalog recipe).
if not _rift(analysis):
return None
if analysis.extra.get("frame_native"):
return Suggestion(False, "No Oculus code: SteamVR / the Frame run it directly, without Revive.")
mode = _mode(analysis)
if mode == "repack":
return Suggestion(False, "The game folder already has its own Revive set up (see 'Use the repack's "
"launcher'); a second Revive breaks it.")
if mode == "native":
return Suggestion(False, "Supports SteamVR/OpenXR itself: SteamVR / the Frame run it directly.")
return Suggestion(True, "Oculus/LibOVR game: Revive translates it to SteamVR/OpenXR (without it it runs flat).")
@@ -50,11 +67,74 @@ class ReviveOpenVR(_PcvrPatch):
def detect(self, analysis):
if not _rift(analysis):
return None
if analysis.extra.get("frame_native"):
return Suggestion(False, "Runs on SteamVR directly; no Revive needed.")
if _mode(analysis) != "revive":
return Suggestion(False, "Not launched through FramePort's Revive.")
return Suggestion(True, "PC: Revive's SteamVR/OpenVR backend is the most reliable path.")
class LibovrRedirect(_PcvrPatch):
id = "pcvr.libovr_redirect"
title = "Provide the Oculus runtime from Revive (Frame)"
description = ("On the Frame, place Revive's runtime (FramePort's Revive, or the repack's bundled LibRevive) where "
"the game's Oculus SDK looks for LibOVRRT so it can load a VR runtime (pure runtime substitution — "
"what Revive's LoadLibrary hook does on Windows; that hook doesn't work under Proton on the Frame). "
"It does NOT bypass the Oculus runtime signature check: a game that verifies the runtime's "
"signature will still refuse it. Ignored on this PC (Revive's hook handles it there).")
order = 12
def detect(self, analysis):
if not _rift(analysis):
return None
if _mode(analysis) == "native":
return Suggestion(False, "Supports SteamVR/OpenXR itself: no Oculus runtime needed.")
return Suggestion(True, "Lets the game find Revive's runtime on the Frame (doesn't bypass its signature check).")
class RepackLauncher(_PcvrPatch):
id = "pcvr.repack_launcher"
title = "Use the repack's launcher (bundled Revive)"
description = ("Some game folders are already set up for SteamVR: a Revive copy (LibRevive64.dll) next to the "
"game, started by a small loader DLL (e.g. xinput1_3.dll) that Windows loads from the game's "
"folder. Then FramePort starts the game program directly — like double-clicking it — instead of "
"through its own Revive (two Revives conflict; e.g. the Oculus Platform check then fails). On the "
"Frame, Wine is told to use those loader DLLs from the game folder instead of its own.")
order = 8
conflicts = ("pcvr.revive",)
params = [Param("dlls", "str", "", "loader DLLs next to the exe (comma-separated)")]
def detect(self, analysis):
if not _rift(analysis):
return None
if _mode(analysis) == "repack":
dlls = ",".join((analysis.extra.get("loader_dlls") or []))
return Suggestion(True, f"The game folder has its own Revive and loader ({dlls}): run the game directly.",
{"dlls": dlls})
return None
def applies(self, analysis) -> bool:
return _rift(analysis) and bool((analysis.extra or {}).get("loader_dlls"))
class LaunchArgs(_PcvrPatch):
id = "pcvr.launch_args"
title = "Game arguments (select SteamVR / OpenXR)"
description = ("Command-line arguments for the game program. Games that support several VR runtimes pick one "
"with an argument, e.g. Unreal's -hmd=OpenXR or -hmd=SteamVR, Unity's -vrmode OpenVR, or a "
"game's own switch (-Runtime=OpenXRHMD). FramePort fills them in from the game files (the "
"repack's VD.bat with the Oculus module swapped for OpenXR, else the engine's usual switch).")
order = 9
params = [Param("args", "str", "", "arguments, e.g. -hmd=OpenXR")]
def detect(self, analysis):
if not _rift(analysis):
return None
args = (analysis.extra or {}).get("launch_args") or ""
if args:
src = (analysis.extra or {}).get("launch_args_from") or "the game files"
return Suggestion(True, f"Selects SteamVR/OpenXR ({src}).", {"args": args})
return None
class XrTimefix(_PcvrPatch):
id = "pcvr.xr_timefix"
title = "Frame OpenXR compatibility layer"
@@ -102,8 +182,8 @@ class OculusUnreal(_PcvrPatch):
def detect(self, analysis):
if not (_rift(analysis) and analysis.engine == "Unreal"):
return None
if analysis.extra.get("frame_native"):
return Suggestion(False, "No Oculus plugin in use: runs directly.")
if _mode(analysis) == "native":
return Suggestion(False, "Uses SteamVR/OpenXR, not its Oculus plugin.")
return Suggestion(True, "Unreal game: its Oculus plugin checks for the Oculus service before it starts VR.")
def applies(self, analysis) -> bool:
@@ -135,13 +215,53 @@ class ProtonEnv(_PcvrPatch):
params = [Param("env", "text", "", "KEY=value lines")]
for _cls in (Revive, ReviveOpenVR, NoCrashReporter, OculusUnreal, XrTimefix, ProtonLog, ProtonTool, ProtonEnv):
class SteamvrTuning(_PcvrPatch):
id = "pcvr.steamvr_tuning"
title = "Automatic SteamVR performance settings (this PC)"
description = ("Before each Play on this PC, FramePort reads SteamVR's record of the game's last session (frames "
"dropped; frame times from fpsVR if installed). If it dropped frames, it lowers the game's refresh "
"rate to one whose frame budget fits (e.g. 96 → 90 Hz) and turns motion smoothing on, through "
"SteamVR's per-application settings; each later session can step down again. Set a refresh rate "
"or smoothing mode here to choose yourself. Ignored on the Frame.")
order = 45
params = [Param("refresh", "float", 0.0, "refresh rate in Hz (0 = automatic)", 0, 144),
Param("smoothing", "str", "auto", "motion smoothing: auto, on, off, always or global")]
def detect(self, analysis):
if _rift(analysis):
return Suggestion(True, "Adjusts the refresh rate / motion smoothing when the game can't keep up.")
return None
for _cls in (RepackLauncher, LaunchArgs, Revive, ReviveOpenVR, LibovrRedirect, NoCrashReporter, OculusUnreal, XrTimefix, ProtonLog,
ProtonTool, ProtonEnv, SteamvrTuning):
register(_cls)
def game_args(recipe) -> list[str]:
"""Extra command-line arguments for the game itself."""
return ["-nocrashreports"] if "pcvr.no_crash_reporter" in recipe.patches else []
import shlex
out = []
if "pcvr.launch_args" in recipe.patches:
raw = str(recipe.params("pcvr.launch_args").get("args") or "")
try:
out += shlex.split(raw, posix=True)
except ValueError:
out += raw.split()
if "pcvr.no_crash_reporter" in recipe.patches and "-nocrashreports" not in out:
out.append("-nocrashreports")
return out
def loader_overrides(recipe) -> str:
"""WINEDLLOVERRIDES entry for the repack's loader DLLs (native first, then Wine's builtin)."""
if "pcvr.repack_launcher" not in recipe.patches:
return ""
raw = str(recipe.params("pcvr.repack_launcher").get("dlls") or "")
names = [n.strip().lower().removesuffix(".dll") for n in raw.replace(";", ",").split(",") if n.strip()]
names = [n for n in names if n.replace("_", "").isalnum()]
return f"{','.join(names)}=n,b" if names else ""
def launch_env(recipe) -> dict[str, str]:
@@ -149,10 +269,14 @@ def launch_env(recipe) -> dict[str, str]:
env = {}
if "pcvr.proton_log" in recipe.patches:
env["PROTON_LOG"] = "1"
if loader_overrides(recipe):
env["WINEDLLOVERRIDES"] = loader_overrides(recipe)
raw = recipe.params("pcvr.proton_env").get("env") or ""
items = raw.items() if isinstance(raw, dict) else (line.partition("=")[::2] for line in str(raw).splitlines())
for k, v in items:
k = k.strip()
if k:
if k == "WINEDLLOVERRIDES" and env.get(k): # the user's overrides extend the loader's
env[k] = env[k] + ";" + str(v).strip()
elif k:
env[k] = str(v).strip()
return env
+52 -1
View File
@@ -25,9 +25,51 @@ SETTINGS = [
("flip_emul", "int", 1, "Emulate flipped quads",
"Blit quads flagged XrCompositionLayerImageLayoutFB VERTICAL_FLIP upside down (Vulkan). Fixes UI panels and "
"text that show upside down (e.g. Assassin's Creed Nexus)."),
("cylinder_strips", "int", 1, "Show curved panels",
"Cylinder layers (curved menus and movie screens, e.g. 4XVR), which the Frame's runtime lacks, are shown as a "
"few flat strips along the curve. 0 = drop them. 360° (equirect) layers can't be shown on the Frame."),
("equirect_emul", "int", 0, "Show 360° layers",
"360° (equirect) layers, e.g. a video player's virtual theatre or 360° videos (e.g. 4XVR), which the Frame's "
"runtime lacks, are drawn by a background thread into a layer behind the game's own picture: the 360° image is "
"converted only when it changes (a theatre once, a 360° video once per video frame) and the view is drawn for each "
"frame's head pose. GLES games only; without it these layers are missing (black)."),
("equirect_face", "int", 1536, "360° detail",
"Maximum size in pixels of each face of the cube the 360° image is converted to (256–2730). Higher is sharper "
"but uses more GPU memory."),
("equirect_res", "int", 1536, "360° view resolution",
"Size in pixels per eye of the 360° background, redrawn every frame on a background thread (512–4096). Higher is "
"sharper but costs more GPU time per frame."),
("equirect_flip", "int", 0, "360° picture orientation",
"Only if 360° pictures show wrongly: 1 = upside down, 2 = mirrored, 4 = turned around (add values to combine)."),
("equirect_fps", "float", 60.0, "360° redraw limit (per second)",
"At most this many redraws per second of a 360° layer (0 = no limit). Video players need at least the video's "
"frame rate."),
("equirect_stereo", "int", 0, "360° stereo",
"Stereo (3D) 360° layers: 0 = as the game sends them, 2 = flat (the left image to both eyes)."),
("stable_local", "int", 0, "Keep the play space still",
"Every 'local' play space the game creates lines up with the one at the start. For games whose menus or screens "
"jump to where you look on the Frame."),
("focus_hold", "int", 0, "Ignore brief focus dips",
"Hides the Frame's brief focus dips (well under a second) once the game has been focused for a few seconds. For "
"games that recentre or pause every time focus returns."),
("aim_pitch", "float", 0.0, "Pointer tilt (degrees)",
"Tilts the controllers' pointing ray up (+) or down (−), for games whose pointer doesn't hit what you aim at."),
("aim_yaw", "float", 0.0, "Pointer turn (degrees)", "Turns the controllers' pointing ray left (+) or right (−)."),
("aim_forward", "float", 0.0, "Pointer origin forward (m)", "Moves where the pointing ray starts forward (+) or back (−)."),
("refresh_rate", "float", 0.0, "Refresh rate (Hz)",
"Display refresh rate for this game (72, 80, 90, 96, 108, 120 or 144; 0 = the game's choice). A video's frame "
"rate that divides the refresh rate plays smoothest (e.g. 30 fps at 90 Hz, 24 fps at 72 Hz)."),
("layer_debug", "int", 0, "Extra diagnostics (log)",
"Logs details for debugging: composition layers and swapchains, focus changes, play-space creation, pointer vs "
"grip poses, refresh rates. No effect on the game."),
("scene_emul", "int", 0, "Emulate Meta scene (room)",
"Fake XR_FB_scene/spatial entities: a guardian-sized room with floor, ceiling and four walls, for mixed-reality "
"games that build their level from the room (e.g. Demeter)."),
("controller_models", "int", 0, "Steam Frame controller models",
"Games that ask the headset for its controller models (Meta's runtime controller models, XR_FB_render_model) get "
"the Steam Frame controllers instead of Quest Touch controllers. The models come from the Frame's own SteamVR and "
"are converted on the Frame at install time. Games that ship their own controller meshes aren't affected. Turning "
"it on needs a rebuild (it adds a small library in front of overport's loader)."),
("scene_height", "float", 2.5, "Emulated room height (m)", "Ceiling height for scene_emul."),
("scene_width", "float", 0.0, "Emulated room width (m)", "Override the guardian width (0 = use guardian, min 1.5 m)."),
("scene_depth", "float", 0.0, "Emulated room depth (m)", "Override the guardian depth (0 = use guardian, min 1.5 m)."),
@@ -56,11 +98,17 @@ class AdapterSetting(Patch):
self.default = default
def detect(self, a):
from .applicability import needs_scene
from .applicability import needs_scene, uses_equirect_layers, uses_render_models
if self.key == "controller_fix" and a.extra.get("hand_tracking_only"):
return Suggestion(True, "Hand tracking is required by the game: pass hands through instead of reporting "
"Touch controllers (e.g. Silhouette).", {"value": 0})
if self.key == "controller_models" and uses_render_models(a):
return Suggestion(True, "The game asks the headset for its controller models: show Steam Frame controllers "
"instead of Quest Touch controllers.", {"value": 1})
if self.key == "equirect_emul" and uses_equirect_layers(a):
return Suggestion(True, "The game draws 360° layers (e.g. a video player's theatre or 360° videos), which "
"the Frame's runtime can't show: show them as panels around you.", {"value": 1})
if self.key == "scene_emul" and needs_scene(a):
return Suggestion(True, "Mixed-reality game that builds its level from the room model: emulate a "
"guardian-sized room (e.g. Demeter).", {"value": 1})
@@ -80,6 +128,9 @@ class AdapterSetting(Patch):
"mutable_fix": ap.is_vulkan,
"swapchain_fix": ap.is_gles,
"gl_hide_multiview": lambda a: a.direct_vrapi and ap.is_gles(a),
"controller_models": ap.may_use_render_models,
**{k: ap.is_gles for k in ("equirect_emul", "equirect_face", "equirect_res", "equirect_flip", "equirect_fps",
"equirect_stereo")},
}
rule = rules.get(self.key)
return bool(rule(a)) if rule else True
+79 -3
View File
@@ -25,14 +25,20 @@ from .targets.base import Target
def add_path(path: Path, reporter: Reporter | None = None, on_added=None, force_rift: bool = False,
art: bool = False) -> list[dict]:
art: bool = False, only_new: bool = False) -> list[dict]:
"""Scan a file/folder (recursively), analyze every game found (Quest APKs and Rift game folders) and store it with
a suggested recipe. on_added(entry) is called as each game lands in the library (the GUI streams cards in).
force_rift: `path` is one Rift game folder (added even if no VR runtime is detected). art: fetch artwork too."""
force_rift: `path` is one Rift game folder (added even if no VR runtime is detected). art: fetch artwork too.
only_new: skip Quest APKs already in the library (a rescan for games added since; Rift folders already skip
unchanged games)."""
path = Path(path)
added = []
known_apks = {str(Path(g["apk"]).resolve()) for g in library.games() if g.get("apk")} if only_new else set()
known_packages = {g["package"] for g in library.games()} if only_new else set()
def done(entry):
if only_new and entry["package"] in known_packages: # already in the library (e.g. an unchanged Rift folder)
return
added.append(entry)
if on_added:
on_added(entry)
@@ -40,6 +46,14 @@ def add_path(path: Path, reporter: Reporter | None = None, on_added=None, force_
for src in quest_dump.scan(path):
if reporter:
reporter.check_cancel()
if only_new and str(Path(src.apk).resolve()) in known_apks:
continue
if only_new: # another copy of a game already in the library (e.g. a patched build): leave it alone
try:
if quest_dump._package_of(src.apk) in known_packages:
continue
except Exception: # noqa: BLE001
pass
try:
entry = add_game(src, reporter)
if art:
@@ -421,12 +435,29 @@ def test_game(package: str, target: Target, reporter: Reporter, seconds: int = 4
old.unlink(missing_ok=True)
reporter.log(f"full launch log ({len((log or '').splitlines())} lines): {log_path}")
summary = {"state": result.state, "verdict": result.verdict, "milestone": result.milestone, "fps": result.fps,
"findings": [f.__dict__ for f in result.findings], "suggestions": result.suggestions(),
"findings": [f.__dict__ for f in result.findings],
"suggestions": useful_suggestions(package, result.suggestions()),
"time": time.time(), "target": target.label, "log_path": str(log_path)}
library.upsert_game(package, last_test=summary)
return summary
def useful_suggestions(package: str, suggestions: list[str]) -> list[str]:
"""Triage suggestions that would change something: not already on, and not conflicting with the recipe (e.g. no
Revive for a repack that runs its own)."""
from .patches.base import REGISTRY
entry = library.game(package) or {}
on = set(((entry.get("recipe") or {}).get("patches") or {}))
out = []
for pid in suggestions:
p = REGISTRY.get(pid)
if pid in on or (p and any(c in on for c in p.conflicts)):
continue
out.append(pid)
return out
def apply_suggestions(package: str, suggestions: list[str]) -> Recipe:
"""Add triage-suggested patches to the game's recipe (the user confirms in the UI before rebuilding)."""
entry = library.game(package)
@@ -446,3 +477,48 @@ def apply_suggestions(package: str, suggestions: list[str]) -> Recipe:
recipe.patches.pop(pid, None)
set_recipe(package, recipe)
return recipe
# ------------------------------------------------------------------------------------------ sharing / diagnostics
def collect_diagnostics(packages: list[str] | None, target: Target | None, reporter: Reporter,
dest: Path | None = None, extra: dict[str, str] | None = None) -> Path:
"""Redacted diagnostics zip (docs/DIAGNOSTICS.md) for some games (None = app-wide only)."""
from .diag import bundle
return bundle.collect(packages, target, reporter, dest, extra)
def share_working_config(package: str, status: str = "works", notes: str = "",
frame_info: dict | None = None) -> str:
"""Save the game's recipe as a known-good user recipe and return a prefilled GitHub issue link that submits it
to the catalog (a maintainer turns accepted ones into a PR)."""
from .diag import bundle, issue, redact
from .recommend import catalog
g = library.game(package)
if not g or not g.get("recipe"):
raise ValueError(f"{package} has no recipe")
env = bundle.env_info(frame_info)
verified = {"app": env.get("app"), "overport_cli": (env.get("tools") or {}).get("overport"),
"frame_build": (env.get("frame") or {}).get("build_id"),
"agent": (env.get("frame") or {}).get("agent_version")}
entry = catalog.entry_from_library(g, status=status, notes=notes or None, verified=verified)
catalog.save_user_entry(entry)
return issue.working_config_url(g, catalog.to_yaml(entry), status, notes, env, redact.default(frame_info))
def problem_report(package: str | None, description: str, bundle_path: Path | None,
frame_info: dict | None = None) -> str:
"""A prefilled GitHub bug-report link (the user attaches the diagnostics zip)."""
from .diag import bundle, issue, redact
from .recommend import catalog
g = library.game(package) if package else None
recipe = ""
if g and g.get("recipe"):
try:
recipe = catalog.to_yaml(catalog.entry_from_library(g, status=g.get("status") or "unknown"))
except Exception: # noqa: BLE001
recipe = ""
return issue.problem_url(g, description, bundle.env_info(frame_info),
bundle_path.name if bundle_path else None, recipe, redact.default(frame_info))
Loaded 100 of 143 files, more files were not shown because too many files have changed in this diff. Show more