Compare commits

..
649 changed files with 2908 additions and 57952 deletions

No files matched your search

-1
View File
@@ -9,4 +9,3 @@ tools/linuxfs/desktop/** text eol=lf
tools/mangoapp/mangoapp text eol=lf tools/mangoapp/mangoapp text eol=lf
app/src/main/assets/desktop-removal/*.json text eol=lf app/src/main/assets/desktop-removal/*.json text eol=lf
app/src/main/assets/desktop-removal/*.txt text eol=lf app/src/main/assets/desktop-removal/*.txt text eol=lf
*.pdf binary
+1 -5
View File
@@ -64,7 +64,6 @@ jobs:
KDE_KWIN_OVERRIDE="$PWD/out/kwin" tools/desktop-kde/build.sh out KDE_KWIN_OVERRIDE="$PWD/out/kwin" tools/desktop-kde/build.sh out
cp out/kwin/desktop-kde.kwin.txt out/ cp out/kwin/desktop-kde.kwin.txt out/
echo "size $(stat -c %s out/desktop-kde.tar.zst) sha256 $(cat out/desktop-kde.sha256)" echo "size $(stat -c %s out/desktop-kde.tar.zst) sha256 $(cat out/desktop-kde.sha256)"
echo "language packs $(ls out/desktop-kde-i18n-*.tar.zst | wc -l)"
- uses: actions/upload-artifact@v4 - uses: actions/upload-artifact@v4
with: with:
name: desktop-kde name: desktop-kde
@@ -75,8 +74,6 @@ jobs:
out/desktop-kde.packages.txt out/desktop-kde.packages.txt
out/desktop-kde.kwin.txt out/desktop-kde.kwin.txt
out/desktop-kde.sha256 out/desktop-kde.sha256
out/desktop-kde.i18n.txt
out/desktop-kde-i18n-*.tar.zst
- name: Publish - name: Publish
if: github.event_name == 'workflow_dispatch' && inputs.tag != '' if: github.event_name == 'workflow_dispatch' && inputs.tag != ''
env: env:
@@ -91,6 +88,5 @@ jobs:
fi fi
gh release create "$TAG" --latest=false --prerelease=false --title "$TAG" \ gh release create "$TAG" --latest=false --prerelease=false --title "$TAG" \
--notes "KDE Plasma desktop package for DroidDeck's Linux runtime ($GITHUB_REPOSITORY tools/desktop-kde, $GITHUB_SHA). size $(stat -c %s out/desktop-kde.tar.zst), sha256 $(cat out/desktop-kde.sha256). desktop-kde.packages.txt lists the signature-checked Arch Linux ARM packages it was built from." \ --notes "KDE Plasma desktop package for DroidDeck's Linux runtime ($GITHUB_REPOSITORY tools/desktop-kde, $GITHUB_SHA). size $(stat -c %s out/desktop-kde.tar.zst), sha256 $(cat out/desktop-kde.sha256). desktop-kde.packages.txt lists the signature-checked Arch Linux ARM packages it was built from." \
out/desktop-kde.tar.zst out/desktop-kde.sha256 out/desktop-kde.packages.txt out/desktop-kde.kwin.txt \ out/desktop-kde.tar.zst out/desktop-kde.sha256 out/desktop-kde.packages.txt out/desktop-kde.kwin.txt
out/desktop-kde.i18n.txt out/desktop-kde-i18n-*.tar.zst
gh release edit "$TAG" --latest=false --prerelease=false gh release edit "$TAG" --latest=false --prerelease=false
-49
View File
@@ -1,49 +0,0 @@
name: Build FEX (x86-64 Steam client)
# Checks tools/fex: the same build DroidDeck-Components' build-fex.yml runs from this repository to publish FEX
# (its single `fex` release and fex.json, which the app follows). Nothing is published from here.
on:
push:
paths:
- 'tools/fex/**'
- '.github/workflows/build-fex.yml'
workflow_dispatch:
inputs:
thunks:
description: 'Build the host thunks (Vulkan/GL/X11/... to the runtime arm64 libraries)'
required: false
default: 'false'
cxxflags:
description: 'Extra CXXFLAGS for a diagnostic build (e.g. -DDEBUG_STRACE)'
required: false
default: ''
permissions:
contents: read
jobs:
build:
runs-on: ubuntu-24.04-arm
timeout-minutes: 120
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- name: Build in Arch Linux ARM
# Inputs reach the shell as environment variables, never pasted into the script.
env:
FEX_EXTRA_CXXFLAGS: ${{ inputs.cxxflags }}
FEX_THUNKS: ${{ inputs.thunks == 'true' && '1' || '0' }}
run: |
set -euo pipefail
docker run --rm -e FEX_EXTRA_CXXFLAGS="$FEX_EXTRA_CXXFLAGS" -e FEX_THUNKS="$FEX_THUNKS" -v "$PWD:/work" -w /work menci/archlinuxarm:base-devel bash tools/fex/build-in-arch.sh
sudo chown -R "$(id -u):$(id -g)" .
- uses: actions/upload-artifact@v4
with:
name: fex
path: |
fex.tzst
fex.tzst.sha256
fex-needed.txt
fex-files.txt
+16 -116
View File
@@ -26,67 +26,10 @@ concurrency:
cancel-in-progress: ${{ github.event_name == 'pull_request' }} cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env: env:
PRELOAD_CACHE_VERSION: v6 PRELOAD_CACHE_VERSION: v3
jobs: jobs:
xbox:
name: Xbox ARM64 backend
if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }}
runs-on: ubuntu-24.04-arm
timeout-minutes: 30
outputs:
base-sha: ${{ steps.merge.outputs.base-sha }}
tree-sha: ${{ steps.source.outputs.tree-sha }}
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
fetch-depth: 0
persist-credentials: false
- name: Pin and merge the APK source
id: merge
if: github.event_name == 'pull_request'
run: |
set -euo pipefail
git fetch --no-tags origin main
echo "base-sha=$(git rev-parse origin/main)" >> "$GITHUB_OUTPUT"
git config user.name "ci"
git config user.email "ci@users.noreply.github.com"
git merge --no-ff --no-edit origin/main
- name: Record backend source tree
id: source
run: echo "tree-sha=$(git rev-parse 'HEAD^{tree}')" >> "$GITHUB_OUTPUT"
- uses: actions/cache@v4
id: xbox-cache
with:
path: |
app/src/main/assets/linuxfs/usr/local/lib/droiddeck-xbox
app/build/xbox/xodus-droiddeck-source.tar.xz
app/build/xbox/runtime/*-source.tar.xz
key: xbox-arm64-${{ hashFiles('tools/xbox/**') }}
- name: Build Xbox backend
if: steps.xbox-cache.outputs.cache-hit != 'true'
run: |
rustup toolchain install 1.99.0 --profile minimal
sudo apt-get update -qq
sudo apt-get install -y build-essential pkg-config libssl-dev protobuf-compiler cmake xz-utils
bash tools/xbox/build.sh
- uses: actions/upload-artifact@v4
with:
name: xbox-arm64
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-xbox
retention-days: 14
- uses: actions/upload-artifact@v4
with:
name: xbox-corresponding-source
path: |
app/build/xbox/xodus-droiddeck-source.tar.xz
app/build/xbox/runtime/*-source.tar.xz
if-no-files-found: error
retention-days: 14
build: build:
needs: xbox
name: Build APK name: Build APK
if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }} if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }}
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
@@ -98,7 +41,6 @@ jobs:
with: with:
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
fetch-depth: 0 fetch-depth: 0
persist-credentials: false
- name: Check co-authors - name: Check co-authors
if: github.event_name == 'pull_request' if: github.event_name == 'pull_request'
@@ -144,17 +86,14 @@ jobs:
- name: Merge onto main, or say what conflicts - name: Merge onto main, or say what conflicts
if: github.event_name == 'pull_request' if: github.event_name == 'pull_request'
env:
BUILD_BASE_SHA: ${{ needs.xbox.outputs.base-sha }}
run: | run: |
set -uo pipefail set -uo pipefail
git config user.name "ci" git config user.name "ci"
git config user.email "ci@users.noreply.github.com" git config user.email "ci@users.noreply.github.com"
git fetch --no-tags origin main git fetch --no-tags origin main
git fetch --no-tags origin "$BUILD_BASE_SHA" BASE=$(git rev-parse --short origin/main)
BASE=$(git rev-parse --short FETCH_HEAD)
HEAD=$(git rev-parse --short HEAD) HEAD=$(git rev-parse --short HEAD)
if git merge --no-ff --no-edit FETCH_HEAD >/tmp/merge.out 2>&1; then if git merge --no-ff --no-edit origin/main >/tmp/merge.out 2>&1; then
{ {
echo "### Mergeable" echo "### Mergeable"
echo echo
@@ -201,11 +140,6 @@ jobs:
echo "::error::the pull request conflicts with main: $(echo $FILES | tr '\n' ' ')" echo "::error::the pull request conflicts with main: $(echo $FILES | tr '\n' ' ')"
exit 1 exit 1
- name: Verify backend and APK source match
env:
XBOX_SOURCE_TREE: ${{ needs.xbox.outputs.tree-sha }}
run: test "$(git rev-parse 'HEAD^{tree}')" = "$XBOX_SOURCE_TREE"
- uses: actions/setup-java@v4 - uses: actions/setup-java@v4
with: with:
distribution: temurin distribution: temurin
@@ -250,14 +184,15 @@ jobs:
uses: actions/cache@v4 uses: actions/cache@v4
with: with:
path: app/src/main/assets/linuxfs path: app/src/main/assets/linuxfs
key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'app/src/main/cpp/adrenotools/src/hook/kgsl.h', 'tools/quest/*', 'tools/linuxfs/preload/*.c', 'tools/linuxfs/build-x86-preloads.sh', 'tools/linuxfs/fex/*', 'tools/linuxfs/clipboard/*.c', 'tools/linuxfs/ssbs/*.c', 'tools/proot/fastpath/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/wlroots/release.env', 'tools/linuxfs/uruntime.env', 'tools/linuxfs/licenses/*', 'tools/mangoapp/*', 'tools/msitools/**', 'tools/comet/**', 'tools/xbox/**', 'tools/linuxfs/debian-image.env', 'tools/vr/**') }} key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'app/src/main/cpp/adrenotools/src/hook/kgsl.h', 'tools/quest/*', 'tools/linuxfs/preload/*.c', 'tools/linuxfs/build-x86-preloads.sh', 'tools/linuxfs/fex/*', 'tools/linuxfs/clipboard/*.c', 'tools/linuxfs/ssbs/*.c', 'tools/proot/fastpath/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/wlroots/release.env', 'tools/linuxfs/uruntime.env', 'tools/linuxfs/licenses/*', 'tools/mangoapp/*', 'tools/msitools/**', 'tools/comet/**', 'tools/linuxfs/debian-image.env', 'tools/vr/**') }}
- name: Build libfakeinput.so and libblsession.so (glibc aarch64) - name: Build libfakeinput.so and libblsession.so (glibc aarch64)
if: steps.preloads.outputs.cache-hit != 'true' if: steps.preloads.outputs.cache-hit != 'true'
env:
GH_TOKEN: ${{ github.token }}
run: | run: |
set -euo pipefail set -euo pipefail
sudo apt-get -o Dir::Etc::sourcelist=sources.list.d/ubuntu.sources \ sudo apt-get update -qq
-o Dir::Etc::sourceparts=- -o Acquire::Retries=3 update -qq
sudo apt-get install -y -qq gcc-aarch64-linux-gnu g++-aarch64-linux-gnu libvulkan1 mesa-vulkan-drivers >/dev/null sudo apt-get install -y -qq gcc-aarch64-linux-gnu g++-aarch64-linux-gnu libvulkan1 mesa-vulkan-drivers >/dev/null
D=app/src/main/assets/linuxfs D=app/src/main/assets/linuxfs
mkdir -p "$D" mkdir -p "$D"
@@ -290,7 +225,7 @@ jobs:
done done
if [ -f tools/gamescope/release.env ]; then if [ -f tools/gamescope/release.env ]; then
. tools/gamescope/release.env . tools/gamescope/release.env
curl -fsSL --retry 3 -o gamescope.tzst "https://github.com/${GAMESCOPE_REPO:-${GITHUB_REPOSITORY}}/releases/download/${GAMESCOPE_TAG}/gamescope.tzst" gh release download "${GAMESCOPE_TAG}" -R "${GAMESCOPE_REPO:-${GITHUB_REPOSITORY}}" -p gamescope.tzst -O gamescope.tzst
echo "${GAMESCOPE_SHA256} gamescope.tzst" | sha256sum -c - echo "${GAMESCOPE_SHA256} gamescope.tzst" | sha256sum -c -
tar --use-compress-program=unzstd -xf gamescope.tzst -C "$D" tar --use-compress-program=unzstd -xf gamescope.tzst -C "$D"
test -f "$D/usr/local/bin/gamescope" test -f "$D/usr/local/bin/gamescope"
@@ -378,32 +313,27 @@ jobs:
set -euo pipefail set -euo pipefail
docker run --rm -v "$PWD:/src" -w /src public.ecr.aws/docker/library/debian:bullseye bash -c ' docker run --rm -v "$PWD:/src" -w /src public.ecr.aws/docker/library/debian:bullseye bash -c '
set -euo pipefail set -euo pipefail
install_compilers() { printf "deb http://archive.debian.org/debian bullseye main\ndeb http://archive.debian.org/debian-security bullseye-security main\n" > /etc/apt/sources.list
apt-get -o Acquire::Check-Valid-Until=false update -qq && apt-get -o Acquire::Check-Valid-Until=false update -qq
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends gcc g++ gcc-multilib g++-multilib binutils >/dev/null DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends gcc g++ gcc-multilib g++-multilib binutils >/dev/null
}
printf "deb http://deb.debian.org/debian bullseye main\ndeb http://security.debian.org/debian-security bullseye-security main\n" > /etc/apt/sources.list
if ! install_compilers; then
printf "deb http://archive.debian.org/debian bullseye main\ndeb http://archive.debian.org/debian-security bullseye-security main\n" > /etc/apt/sources.list
install_compilers
fi
tools/linuxfs/build-x86-preloads.sh app/src/main/assets/linuxfs tools/linuxfs/build-x86-preloads.sh app/src/main/assets/linuxfs
' '
sudo chown -R "$(id -u):$(id -g)" app/src/main/assets/linuxfs sudo chown -R "$(id -u):$(id -g)" app/src/main/assets/linuxfs
ls -l app/src/main/assets/linuxfs/x86_64 app/src/main/assets/linuxfs/i386 ls -l app/src/main/assets/linuxfs/x86_64 app/src/main/assets/linuxfs/i386
- name: Bundle the droiddeck-esync packs - name: Bundle the droiddeck-esync packs
env:
GH_TOKEN: ${{ github.token }}
run: | run: |
set -euo pipefail set -euo pipefail
if [ -f tools/droiddeck-esync/release.env ]; then if [ -f tools/droiddeck-esync/release.env ]; then
. tools/droiddeck-esync/release.env . tools/droiddeck-esync/release.env
release_url="https://github.com/${SYNC_BUNDLE_REPO}/releases/download/${SYNC_BUNDLE_TAG}" gh release download "$SYNC_BUNDLE_TAG" -R "$SYNC_BUNDLE_REPO" -p "$SYNC_BUNDLE_ASSET" -O sync-bundle.tzst
curl -fsSL --retry 3 -o sync-bundle.tzst "$release_url/$SYNC_BUNDLE_ASSET"
echo "$SYNC_BUNDLE_SHA256 sync-bundle.tzst" | sha256sum -c - echo "$SYNC_BUNDLE_SHA256 sync-bundle.tzst" | sha256sum -c -
mkdir -p app/src/main/assets/droiddeck-esync mkdir -p app/src/main/assets/droiddeck-esync
tar --use-compress-program=unzstd -xf sync-bundle.tzst -C app/src/main/assets/droiddeck-esync tar --use-compress-program=unzstd -xf sync-bundle.tzst -C app/src/main/assets/droiddeck-esync
rm sync-bundle.tzst rm sync-bundle.tzst
curl -fsSL --retry 3 -o sync-index.json "$release_url/index.json" gh release download "$SYNC_BUNDLE_TAG" -R "$SYNC_BUNDLE_REPO" -p index.json -O sync-index.json
revoked=$(python3 -c 'import json, sys; print(" ".join(p["id"] for p in json.load(open(sys.argv[1]))["packs"] if p.get("revoked") is True))' sync-index.json) revoked=$(python3 -c 'import json, sys; print(" ".join(p["id"] for p in json.load(open(sys.argv[1]))["packs"] if p.get("revoked") is True))' sync-index.json)
for id in $revoked; do for id in $revoked; do
if [ -e "app/src/main/assets/droiddeck-esync/packs/$id.tzst" ]; then if [ -e "app/src/main/assets/droiddeck-esync/packs/$id.tzst" ]; then
@@ -527,11 +457,6 @@ jobs:
restore-keys: | restore-keys: |
cxx-${{ env.NDK_VERSION }}- cxx-${{ env.NDK_VERSION }}-
- uses: actions/download-artifact@v4
with:
name: xbox-arm64
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-xbox
- name: Build GOG Galaxy companion - name: Build GOG Galaxy companion
if: steps.preloads.outputs.cache-hit != 'true' if: steps.preloads.outputs.cache-hit != 'true'
run: | run: |
@@ -539,9 +464,6 @@ jobs:
rustup target add --toolchain 1.90.0 aarch64-unknown-linux-gnu rustup target add --toolchain 1.90.0 aarch64-unknown-linux-gnu
RUSTUP_TOOLCHAIN=1.90.0 bash tools/comet/build.sh RUSTUP_TOOLCHAIN=1.90.0 bash tools/comet/build.sh
- name: Build the add-on packs
run: bash tools/packs/build.sh app/build/packs
- name: Build - name: Build
id: build id: build
env: env:
@@ -580,11 +502,6 @@ jobs:
path: app/src/main/rust/stores/Cargo.lock path: app/src/main/rust/stores/Cargo.lock
if-no-files-found: ignore if-no-files-found: ignore
- name: Install Python test dependencies
run: |
sudo apt-get update -qq
sudo apt-get install -y -qq python3-yaml
- name: Steam import and game environment tests - name: Steam import and game environment tests
run: python3 -m unittest discover -s tools/tests -p 'test_*.py' run: python3 -m unittest discover -s tools/tests -p 'test_*.py'
@@ -645,14 +562,6 @@ jobs:
retention-days: 30 retention-days: 30
compression-level: 0 compression-level: 0
- uses: actions/upload-artifact@v4
with:
name: droiddeck-packs
path: app/build/packs/*.tar.zst
if-no-files-found: error
retention-days: 30
compression-level: 0
- name: Report on the pull request - name: Report on the pull request
if: always() && github.event_name == 'pull_request' if: always() && github.event_name == 'pull_request'
continue-on-error: true continue-on-error: true
@@ -755,17 +664,8 @@ jobs:
variants: ${{ needs.build.outputs.variants }} variants: ${{ needs.build.outputs.variants }}
secrets: inherit secrets: inherit
packs:
needs: build
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
permissions:
contents: read
actions: read
uses: ./.github/workflows/publish-packs.yml
secrets: inherit
announce: announce:
needs: [build, sign, packs] needs: [build, sign]
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
timeout-minutes: 10 timeout-minutes: 10
-22
View File
@@ -176,27 +176,6 @@ jobs:
pattern: droiddeck-pr-signed-* pattern: droiddeck-pr-signed-*
merge-multiple: true merge-multiple: true
path: signed path: signed
- name: The add-on packs main has not published
env:
GH_TOKEN: ${{ github.token }}
RUN: ${{ needs.authorize.outputs.run_id }}
run: |
set -euo pipefail
gh run download "$RUN" -R "$GITHUB_REPOSITORY" -n droiddeck-packs -D packs
mkdir -p pr-packs
for file in packs/*.tar.zst; do
name=$(basename "$file" .tar.zst)
sha=$(sha256sum "$file" | cut -d' ' -f1)
tag="pack-$name-${sha:0:16}"
digest=$({ gh api "repos/Droid-Deck/DroidDeck-Components/releases/tags/$tag" 2>/dev/null || echo '{}'; } |
jq -r --arg n "$name.tar.zst" '.assets // [] | .[] | select(.name == $n) | .digest // empty')
if [ "$digest" = "sha256:$sha" ]; then
echo "$name: served from DroidDeck-Components $tag"
else
cp "$file" "pr-packs/$tag.tar.zst"
echo "$name: attached to the PR release as $tag.tar.zst"
fi
done
- name: Describe the change - name: Describe the change
env: env:
GH_TOKEN: ${{ github.token }} GH_TOKEN: ${{ github.token }}
@@ -254,7 +233,6 @@ jobs:
first=true first=true
fi fi
echo "first=$first" >> "$GITHUB_OUTPUT" echo "first=$first" >> "$GITHUB_OUTPUT"
cp pr-packs/* signed/ 2>/dev/null || true
gh release upload "$tag" signed/* -R "$repo" --clobber gh release upload "$tag" signed/* -R "$repo" --clobber
gh release edit "$tag" -R "$repo" --title "PR #$PR_NUMBER" --notes "$notes" --prerelease gh release edit "$tag" -R "$repo" --title "PR #$PR_NUMBER" --notes "$notes" --prerelease
keep=$(cd signed && ls | jq -R . | jq -sc .) keep=$(cd signed && ls | jq -R . | jq -sc .)
-83
View File
@@ -1,83 +0,0 @@
name: Publish add-on packs
# The add-on packs (tools/packs/build.sh) a Build APK run made, published to DroidDeck-Components under
# content-addressed tags (pack-<name>-<first 16 hex of sha256>). The APK from that run pins each pack's
# SHA-256 and downloads it from that tag. A tag is created once and never replaced.
# Only main and release builds publish here; a PR test build attaches the packs main has not published
# to its pr-N release on DroidDeck-CI (pr-release-publish.yml), which is deleted when the PR closes.
on:
workflow_call:
inputs:
run_id:
description: The Build APK run whose packs to publish; empty for the calling run's own
type: string
default: ''
permissions:
contents: read
actions: read
jobs:
publish:
name: publish add-on packs
runs-on: ubuntu-24.04
timeout-minutes: 15
concurrency:
group: publish-packs
cancel-in-progress: false
steps:
- name: The packs (this run's build)
if: inputs.run_id == ''
uses: actions/download-artifact@v4
with:
name: droiddeck-packs
path: packs
- name: The packs (another Build APK run)
if: inputs.run_id != ''
env:
GH_TOKEN: ${{ github.token }}
RUN: ${{ inputs.run_id }}
run: gh run download "$RUN" -R "$GITHUB_REPOSITORY" -n droiddeck-packs -D packs
- uses: actions/create-github-app-token@v2
id: components-token
with:
app-id: ${{ vars.DROIDDECK_CI_APP_ID }}
private-key: ${{ secrets.DROIDDECK_CI_APP_KEY }}
owner: Droid-Deck
repositories: DroidDeck-Components
- name: Publish
env:
GH_TOKEN: ${{ steps.components-token.outputs.token }}
REPO: Droid-Deck/DroidDeck-Components
BUILD_RUN: ${{ inputs.run_id || github.run_id }}
run: |
set -euo pipefail
published_digest() {
{ gh api "repos/$REPO/releases/tags/$1" 2>/dev/null || echo '{}'; } |
jq -r --arg n "$2" '.assets // [] | .[] | select(.name == $n) | .digest // empty'
}
commit=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$BUILD_RUN" --jq .head_sha 2>/dev/null || echo "$GITHUB_SHA")
for name in proot directaudio tracking xbox comet; do
file="packs/$name.tar.zst"
[ -f "$file" ] || { echo "::error::$name.tar.zst is missing from Build APK run $BUILD_RUN"; exit 1; }
sha=$(sha256sum "$file" | cut -d' ' -f1)
tag="pack-$name-${sha:0:16}"
digest=$(published_digest "$tag" "$name.tar.zst")
if [ -z "$digest" ]; then
notes="DroidDeck add-on pack \`$name\`, built by [Build APK run $BUILD_RUN]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$BUILD_RUN) from \`$commit\` with tools/packs/build.sh and published by [run $GITHUB_RUN_ID]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID).
Size: $(stat -c %s "$file") bytes. SHA-256: $sha. APKs built in the same run pin this digest."
gh release create "$tag" -R "$REPO" --title "$tag" --notes "$notes" --latest=false "$file" \
|| echo "::warning::creating $tag failed; checking whether another run published it"
digest=$(published_digest "$tag" "$name.tar.zst")
fi
if [ "$digest" != "sha256:$sha" ]; then
echo "::error::$tag holds ${digest:-nothing} for $name.tar.zst, not sha256:$sha"
exit 1
fi
echo "- \`$name\`: [$tag]($GITHUB_SERVER_URL/$REPO/releases/tag/$tag) \`$sha\`" >> "$GITHUB_STEP_SUMMARY"
done
+1 -11
View File
@@ -63,19 +63,9 @@ jobs:
artifact: droiddeck-release artifact: droiddeck-release
secrets: inherit secrets: inherit
packs:
needs: find
permissions:
contents: read
actions: read
uses: ./.github/workflows/publish-packs.yml
with:
run_id: ${{ needs.find.outputs.run_id }}
secrets: inherit
publish: publish:
name: publish the release name: publish the release
needs: [find, sign, packs] needs: [find, sign]
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
timeout-minutes: 10 timeout-minutes: 10
permissions: permissions:
+1 -7
View File
@@ -19,10 +19,6 @@ Use Android 9 or newer on a supported Adreno device (730 or newer, or 8xx). Adre
On Android 14 and newer, before Steam launches, you must turn on **Disable child process restrictions** in Developer options. If this option is not available in developer settings (Android 12 and 13 devices), first launch of Steam will present a "Fix it for me" button, which will help automate the setup process. On Android 14 and newer, before Steam launches, you must turn on **Disable child process restrictions** in Developer options. If this option is not available in developer settings (Android 12 and 13 devices), first launch of Steam will present a "Fix it for me" button, which will help automate the setup process.
## Smart glasses
Use **Setup → Smart glasses** for app-wide virtual-screen settings across DroidDeck menus, launchers, desktop sessions, and games. Supported VITURE, RayNeo, and XREAL connections provide 3DoF; Luma Ultra adds optional experimental 6DoF and stereo-assisted hand/Joy-Con tracking. Model support and SDK requirements differ: see the [smart-glasses support matrix](docs/smart-glasses-support.md) for supported devices, controls, setup, and limitations.
## Community ## Community
Join the [DroidDeck Discord](https://discord.gg/JRGAvawjsm) for help, Preview builds, and device reports. Bug reports go in its **#bug-reports** forum; attach the zip from **Share logs** (Setup, or the session drawer) so the logs come with it. Join the [DroidDeck Discord](https://discord.gg/JRGAvawjsm) for help, Preview builds, and device reports. Bug reports go in its **#bug-reports** forum; attach the zip from **Share logs** (Setup, or the session drawer) so the logs come with it.
@@ -47,12 +43,10 @@ Compatibility and performance vary by device; hardware validation is limited. De
## Credits and licence ## Credits and licence
GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). Epic Games and GOG support build on [Phobos’s](https://github.com/phobos665) adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl), respectively. The registry entries a GOG game's install script (`goggame-<id>.script`) sets are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher)'s GOG setup (GPL-3.0) reads them. LSFG frame generation is from the work of Camille LaVey and the [Eden](https://eden-emu.dev) emulator project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported to WinNative and DroidDeck by [@maxjivi05](https://github.com/maxjivi05); it needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. x86 AppImages, and any whose own runtime cannot unpack them, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence, which also starts the arm64 emulator AppImages whose own runtime cannot run its extractor on Android. The Steam client's audio goes through [@The412Banner](https://github.com/The412Banner)'s [DirectAudio](https://github.com/The412Banner/directaudio) PulseAudio sink (LGPL-2.1-or-later), built from `tools/directaudio/sink` with its request size kept to its ring so clients are not asked to queue 100 ms ahead. mmap ring-buffer controller input was developed by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). Why the x86-64 Steam client refused the arm64 client's sign-in was checked by reading Steam's saved token with the `ConnectCache` format from [deadlock-api-ingest](https://github.com/deadlock-api/deadlock-api-ingest). x86 programs that link OpenSSL 3 under FEX use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt) platform. Hooks written with `WriteProcessMemory` into code [FEX](https://github.com/FEX-Emu/FEX) has translated go through `/proc/<pid>/mem` again when the kernel refuses `process_vm_writev`, as [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` wrote them before Wine 11. x86 Linux games under FEX get the same `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes into the Steam Linux Runtime, so ALSA plays through PulseAudio. Games render with [Mesa](https://gitlab.freedesktop.org/mesa/mesa) Turnip's own per-render-pass choice between tile memory and system memory, while the Steam client keeps `TU_DEBUG=sysmem`; [FEX](https://github.com/FEX-Emu/FEX)'s code disk cache was checked in its source and is already on through Proton. See [LICENSE](LICENSE). Steam and Proton belong to Valve Corporation; this project is not affiliated with Valve. GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). Epic Games and GOG support build on [Phobos’s](https://github.com/phobos665) adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl), respectively. LSFG frame generation is from the work of Camille LaVey and the [Eden](https://eden-emu.dev) emulator project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported to WinNative and DroidDeck by [@maxjivi05](https://github.com/maxjivi05); it needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. x86 AppImages, and any whose own runtime cannot unpack them, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence. mmap ring-buffer controller input was developed by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). See [LICENSE](LICENSE). Steam and Proton belong to Valve Corporation; this project is not affiliated with Valve.
XR glasses support builds on WinNative's VITURE glasses work. VITURE protocol details were checked against [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) by [@wheaney](https://github.com/wheaney), including the VITURE protocol header it ships, [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) by [@badicsalex](https://github.com/badicsalex) and the [go-macos/iokit VITURE package](https://pkg.go.dev/github.com/go-macos/iokit/viture); the optional VITURE SDK belongs to VITURE and is not included. RayNeo support adapts [@informalTechCode](https://github.com/informalTechCode)'s [RayNeo-Air-Series-3DoF-Scaffold](https://github.com/informalTechCode/RayNeo-Air-Series-3DoF-Scaffold) (Apache-2.0) and references [@verncat](https://github.com/verncat)'s [RayNeo-Air-3S-Pro-OpenVR](https://github.com/verncat/RayNeo-Air-3S-Pro-OpenVR) (MIT) and [Monado](https://gitlab.freedesktop.org/monado/monado) (BSL-1.0); see [docs/third-party/rayneo](docs/third-party/rayneo/README.md). XREAL 1S support references [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) and [xrealOneDeviceKit](https://github.com/wheaney/xrealOneDeviceKit) by @wheaney, [xreal_one_driver](https://github.com/rohitsangwan01/xreal_one_driver) by [@rohitsangwan01](https://github.com/rohitsangwan01) (MIT) and [xr-tools](https://github.com/0xcaff/xr-tools) by [@0xcaff](https://github.com/0xcaff). The REDMAGIC glasses-display findings draw on [@mekhontsev](https://github.com/mekhontsev)'s [MagicDesk investigation](https://github.com/mekhontsev/magicdesk/blob/main/docs/xr-resolution-fix.md) and [@Coding-BR](https://github.com/Coding-BR)'s [decompiled Nubia kernel](https://github.com/Coding-BR/android_kernel_nubia_sm8850_qwjujube). VITURE, RayNeo, XREAL and REDMAGIC are trademarks of their owners; this project is not affiliated with them. XR glasses support builds on WinNative's VITURE glasses work. VITURE protocol details were checked against [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) by [@wheaney](https://github.com/wheaney), including the VITURE protocol header it ships, [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) by [@badicsalex](https://github.com/badicsalex) and the [go-macos/iokit VITURE package](https://pkg.go.dev/github.com/go-macos/iokit/viture); the optional VITURE SDK belongs to VITURE and is not included. RayNeo support adapts [@informalTechCode](https://github.com/informalTechCode)'s [RayNeo-Air-Series-3DoF-Scaffold](https://github.com/informalTechCode/RayNeo-Air-Series-3DoF-Scaffold) (Apache-2.0) and references [@verncat](https://github.com/verncat)'s [RayNeo-Air-3S-Pro-OpenVR](https://github.com/verncat/RayNeo-Air-3S-Pro-OpenVR) (MIT) and [Monado](https://gitlab.freedesktop.org/monado/monado) (BSL-1.0); see [docs/third-party/rayneo](docs/third-party/rayneo/README.md). XREAL 1S support references [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) and [xrealOneDeviceKit](https://github.com/wheaney/xrealOneDeviceKit) by @wheaney, [xreal_one_driver](https://github.com/rohitsangwan01/xreal_one_driver) by [@rohitsangwan01](https://github.com/rohitsangwan01) (MIT) and [xr-tools](https://github.com/0xcaff/xr-tools) by [@0xcaff](https://github.com/0xcaff). The REDMAGIC glasses-display findings draw on [@mekhontsev](https://github.com/mekhontsev)'s [MagicDesk investigation](https://github.com/mekhontsev/magicdesk/blob/main/docs/xr-resolution-fix.md) and [@Coding-BR](https://github.com/Coding-BR)'s [decompiled Nubia kernel](https://github.com/Coding-BR/android_kernel_nubia_sm8850_qwjujube). VITURE, RayNeo, XREAL and REDMAGIC are trademarks of their owners; this project is not affiliated with them.
Joy-Con VR controllers port the arm model of Google's [Google VR SDK for Unity](https://github.com/googlevr/gvr-unity-sdk) (Apache-2.0), adapt the hand skeleton of Valve's [OpenVR](https://github.com/ValveSoftware/openvr) `handskeletonsimulation` sample (BSD-3-Clause), which follows Moshi Turner's hand simulation in [Monado](https://gitlab.freedesktop.org/monado/monado), and use the Index controller offsets from Monado's `vive_poses.c` (BSL-1.0). Joy-Con behaviour was researched in Linux's [hid-nintendo](https://github.com/torvalds/linux/blob/master/drivers/hid/hid-nintendo.c) driver by Daniel J. Ogorchock, [@dekuNukem](https://github.com/dekuNukem)'s [Nintendo_Switch_Reverse_Engineering](https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering), [SDL](https://github.com/libsdl-org/SDL) and the Android Open Source Project, and checked against [ALVR](https://github.com/alvr-org/ALVR), [OpenComposite](https://gitlab.com/znixian/OpenOVR), [PSMoveSteamVRBridge](https://github.com/HipsterSloth/PSMoveSteamVRBridge), [@F8LEFT](https://github.com/F8LEFT)'s [JoyConVr](https://github.com/F8LEFT/JoyConVr), [@krnelpan1c](https://github.com/krnelpan1c)'s [Daydream-Controller-SteamVR](https://github.com/krnelpan1c/Daydream-Controller-SteamVR), [@yoyobuae](https://github.com/yoyobuae)'s [joyconvr](https://github.com/yoyobuae/joyconvr), [Moonlight](https://github.com/moonlight-stream/moonlight-android) and [Dolphin](https://github.com/dolphin-emu/dolphin); see [docs/third-party/joycon](docs/third-party/joycon/README.md). Nintendo Switch and Joy-Con are trademarks of Nintendo; this project is not affiliated with Nintendo. Joy-Con VR controllers port the arm model of Google's [Google VR SDK for Unity](https://github.com/googlevr/gvr-unity-sdk) (Apache-2.0), adapt the hand skeleton of Valve's [OpenVR](https://github.com/ValveSoftware/openvr) `handskeletonsimulation` sample (BSD-3-Clause), which follows Moshi Turner's hand simulation in [Monado](https://gitlab.freedesktop.org/monado/monado), and use the Index controller offsets from Monado's `vive_poses.c` (BSL-1.0). Joy-Con behaviour was researched in Linux's [hid-nintendo](https://github.com/torvalds/linux/blob/master/drivers/hid/hid-nintendo.c) driver by Daniel J. Ogorchock, [@dekuNukem](https://github.com/dekuNukem)'s [Nintendo_Switch_Reverse_Engineering](https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering), [SDL](https://github.com/libsdl-org/SDL) and the Android Open Source Project, and checked against [ALVR](https://github.com/alvr-org/ALVR), [OpenComposite](https://gitlab.com/znixian/OpenOVR), [PSMoveSteamVRBridge](https://github.com/HipsterSloth/PSMoveSteamVRBridge), [@F8LEFT](https://github.com/F8LEFT)'s [JoyConVr](https://github.com/F8LEFT/JoyConVr), [@krnelpan1c](https://github.com/krnelpan1c)'s [Daydream-Controller-SteamVR](https://github.com/krnelpan1c/Daydream-Controller-SteamVR), [@yoyobuae](https://github.com/yoyobuae)'s [joyconvr](https://github.com/yoyobuae/joyconvr), [Moonlight](https://github.com/moonlight-stream/moonlight-android) and [Dolphin](https://github.com/dolphin-emu/dolphin); see [docs/third-party/joycon](docs/third-party/joycon/README.md). Nintendo Switch and Joy-Con are trademarks of Nintendo; this project is not affiliated with Nintendo.
Camera hand tracking runs Google's [MediaPipe](https://github.com/google-ai-edge/mediapipe) Tasks Vision library with its Pose Landmarker (Lite) model, BlazePose GHUM 3D, and its Hand Landmarker model (all Apache-2.0), on frames from AndroidX [CameraX](https://developer.android.com/jetpack/androidx/releases/camera) (Apache-2.0); MediaPipe's usage reports are switched off. The design was checked against [@F8LEFT](https://github.com/F8LEFT)'s [JoyConVr](https://github.com/F8LEFT/JoyConVr) camera app (MIT), and the short Joy-Con movements follow the accelerometer mode of the [Google VR SDK for Unity](https://github.com/googlevr/gvr-unity-sdk)'s arm model, Eric Foxlin's zero-velocity updates and Frosio, Pedersini and Borghese's accelerometer autocalibration, and the camera and Joy-Con are joined by a Kalman filter (R. E. Kalman, 1960). Bare camera hands take their gestures after [ALVR](https://github.com/alvr-org/ALVR)'s `hand_gestures.rs` (MIT) and Meta Quest's menu pinch, with distances checked on photos from the [HaGRID](https://github.com/hukenovs/hagrid) gesture set (CC BY-SA 4.0, not included), fit the palm with Horn's quaternion method (1987) and smooth it with the 1€ filter (Casiez, Roussel and Vogel, 2012); the white glove model follows Valve's OpenVR render model reference and Index controller poses, is meshed with surface nets (Gibson, 1998; Mikola Lysenko) and blends and shades it with Inigo Quilez's smooth minimum and distance-field ambient occlusion, porting his polygon distance (MIT); see [docs/third-party/handtracking](docs/third-party/handtracking/README.md). Camera hand tracking runs Google's [MediaPipe](https://github.com/google-ai-edge/mediapipe) Tasks Vision library with its Pose Landmarker (Lite) model, BlazePose GHUM 3D, and its Hand Landmarker model (all Apache-2.0), on frames from AndroidX [CameraX](https://developer.android.com/jetpack/androidx/releases/camera) (Apache-2.0); MediaPipe's usage reports are switched off. The design was checked against [@F8LEFT](https://github.com/F8LEFT)'s [JoyConVr](https://github.com/F8LEFT/JoyConVr) camera app (MIT), and the short Joy-Con movements follow the accelerometer mode of the [Google VR SDK for Unity](https://github.com/googlevr/gvr-unity-sdk)'s arm model, Eric Foxlin's zero-velocity updates and Frosio, Pedersini and Borghese's accelerometer autocalibration, and the camera and Joy-Con are joined by a Kalman filter (R. E. Kalman, 1960). Bare camera hands take their gestures after [ALVR](https://github.com/alvr-org/ALVR)'s `hand_gestures.rs` (MIT) and Meta Quest's menu pinch, with distances checked on photos from the [HaGRID](https://github.com/hukenovs/hagrid) gesture set (CC BY-SA 4.0, not included), fit the palm with Horn's quaternion method (1987) and smooth it with the 1€ filter (Casiez, Roussel and Vogel, 2012); the white glove model follows Valve's OpenVR render model reference and Index controller poses, is meshed with surface nets (Gibson, 1998; Mikola Lysenko) and blends and shades it with Inigo Quilez's smooth minimum and distance-field ambient occlusion, porting his polygon distance (MIT); see [docs/third-party/handtracking](docs/third-party/handtracking/README.md).
The Store installs and runs apps with [Flatpak](https://github.com/flatpak/flatpak) (LGPL-2.1). Its sandbox goes through DroidDeck's own bubblewrap shim, which follows how Flatpak hands bwrap its environment.
+4 -52
View File
@@ -12,14 +12,7 @@ if (localBuildOptionsFile.asFile.exists()) {
} }
def pythonExecutable = project.findProperty('pythonExecutable') def pythonExecutable = project.findProperty('pythonExecutable')
?: localBuildOptions.getProperty('droiddeck.python', 'python3') ?: localBuildOptions.getProperty('droiddeck.python', 'python3')
def vitureSdkDir = project.hasProperty('vitureSdkDir') ? project.property('vitureSdkDir') : localBuildOptions.getProperty('droiddeck.vitureSdk', '') def vitureSdkDir = project.findProperty('vitureSdkDir') ?: localBuildOptions.getProperty('droiddeck.vitureSdk', '')
def uvcDir = project.hasProperty('uvcDir') ? project.property('uvcDir') : localBuildOptions.getProperty('droiddeck.uvcDir', '')
if (uvcDir) {
['arm64-v8a/libusb.so', 'arm64-v8a/libuvc.a', 'include/libusb.h', 'include/libuvc/libuvc.h',
'licenses/libusb-COPYING', 'licenses/libuvc-LICENSE.txt'].each { required ->
if (!new File(uvcDir, required).isFile()) throw new GradleException("Incomplete UVC build: missing ${required}")
}
}
if (vitureSdkDir) { if (vitureSdkDir) {
['android/arm64-v8a/libglasses.so', 'android/arm64-v8a/libcarina_vio.so', ['android/arm64-v8a/libglasses.so', 'android/arm64-v8a/libcarina_vio.so',
'android/arm64-v8a/libcloud_protocol.so', 'include/viture_glasses_provider.h', 'android/arm64-v8a/libcloud_protocol.so', 'include/viture_glasses_provider.h',
@@ -84,23 +77,6 @@ def commitTime = (gitValue(['show', '-s', '--format=%ct', 'HEAD']) ?: '0').with
def desktopKde = rootProject.file('tools/desktop-kde/release.env').readLines() def desktopKde = rootProject.file('tools/desktop-kde/release.env').readLines()
.findAll { it.contains('=') && !it.startsWith('#') } .findAll { it.contains('=') && !it.startsWith('#') }
.collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] } .collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] }
def trackingPack = rootProject.file('tools/packs/tracking/release.env').readLines()
.findAll { it.contains('=') && !it.startsWith('#') }
.collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] }
def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet'].collectEntries { name ->
def pack = file("build/packs/${name}.tar.zst")
if (!pack.isFile()) {
if (ciBuild) throw new GradleException("Add-on pack ${pack} is missing: run tools/packs/build.sh app/build/packs")
return [(name): [sha256: '', size: 0L]]
}
def digest = java.security.MessageDigest.getInstance('SHA-256')
pack.withInputStream { input ->
byte[] buffer = new byte[1 << 20]
int n
while ((n = input.read(buffer)) > 0) digest.update(buffer, 0, n)
}
[(name): [sha256: digest.digest().encodeHex().toString(), size: pack.length()]]
}
def desktopRemovalSources = new groovy.json.JsonSlurper().parse(file('src/main/assets/desktop-removal/sources.json')) def desktopRemovalSources = new groovy.json.JsonSlurper().parse(file('src/main/assets/desktop-removal/sources.json'))
if (desktopRemovalSources.archives[desktopKde.DESKTOP_KDE_TAG] != desktopKde.DESKTOP_KDE_SHA256) { if (desktopRemovalSources.archives[desktopKde.DESKTOP_KDE_TAG] != desktopKde.DESKTOP_KDE_SHA256) {
throw new GradleException('Desktop removal inventories do not match the pinned archive') throw new GradleException('Desktop removal inventories do not match the pinned archive')
@@ -122,8 +98,8 @@ android {
applicationId "com.droiddeck.launcher" applicationId "com.droiddeck.launcher"
minSdkVersion 26 minSdkVersion 26
targetSdkVersion 28 targetSdkVersion 28
versionCode 14 versionCode 13
versionName "0.5.0" versionName "0.4.0"
buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\"" buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\""
buildConfigField "String", "SOURCE_COMMIT", "\"${sourceCommit}\"" buildConfigField "String", "SOURCE_COMMIT", "\"${sourceCommit}\""
buildConfigField "int", "PR_NUMBER", "${prNumber}" buildConfigField "int", "PR_NUMBER", "${prNumber}"
@@ -136,10 +112,6 @@ android {
buildConfigField "String", "DESKTOP_KDE_URL", "\"https://github.com/${desktopKde.DESKTOP_KDE_REPO}/releases/download/${desktopKde.DESKTOP_KDE_TAG}/desktop-kde.tar.zst\"" buildConfigField "String", "DESKTOP_KDE_URL", "\"https://github.com/${desktopKde.DESKTOP_KDE_REPO}/releases/download/${desktopKde.DESKTOP_KDE_TAG}/desktop-kde.tar.zst\""
buildConfigField "String", "DESKTOP_KDE_SHA256", "\"${desktopKde.DESKTOP_KDE_SHA256}\"" buildConfigField "String", "DESKTOP_KDE_SHA256", "\"${desktopKde.DESKTOP_KDE_SHA256}\""
buildConfigField "long", "DESKTOP_KDE_SIZE", "${desktopKde.DESKTOP_KDE_SIZE}L" buildConfigField "long", "DESKTOP_KDE_SIZE", "${desktopKde.DESKTOP_KDE_SIZE}L"
addonPacks.each { name, pack ->
buildConfigField "String", "PACK_${name.toUpperCase()}_SHA256", "\"${pack.sha256}\""
buildConfigField "long", "PACK_${name.toUpperCase()}_SIZE", "${pack.size}L"
}
ndk { ndk {
abiFilters 'arm64-v8a' abiFilters 'arm64-v8a'
@@ -148,7 +120,6 @@ android {
cmake { cmake {
arguments '-DANDROID_STL=c++_shared' arguments '-DANDROID_STL=c++_shared'
arguments "-DDROIDDECK_VITURE_SDK_DIR=${vitureSdkDir.toString().replace('\\', '/')}" arguments "-DDROIDDECK_VITURE_SDK_DIR=${vitureSdkDir.toString().replace('\\', '/')}"
arguments "-DDROIDDECK_UVC_DIR=${uvcDir.toString().replace('\\', '/')}"
} }
} }
} }
@@ -193,11 +164,6 @@ android {
disable 'ExpiredTargetSdkVersion' disable 'ExpiredTargetSdkVersion'
} }
androidResources {
// aapt's default ignore list, plus the trees shipped as add-on packs (tools/packs).
ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:<dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~:<dir>droiddeck-xbox:<dir>droiddeck-comet:<dir>directaudio'
}
packagingOptions { packagingOptions {
resources { resources {
excludes += ['META-INF/versions/9/OSGI-INF/MANIFEST.MF'] excludes += ['META-INF/versions/9/OSGI-INF/MANIFEST.MF']
@@ -205,8 +171,6 @@ android {
jniLibs { jniLibs {
useLegacyPackaging = true useLegacyPackaging = true
pickFirsts += ['**/libtermux.so'] pickFirsts += ['**/libtermux.so']
// Shipped in the proot and tracking packs (tools/packs) and run or loaded from there.
excludes += ['**/libproot.so', '**/libproot-loader.so', '**/libopencv_java4.so', '**/libmediapipe_tasks_jni.so']
} }
} }
@@ -220,8 +184,6 @@ android {
unitTests.returnDefaultValues = true unitTests.returnDefaultValues = true
unitTests.includeAndroidResources = true unitTests.includeAndroidResources = true
unitTests.all { unitTests.all {
// Robolectric keeps a sandbox per SDK level the tests ask for; seven no longer fit in Gradle's default 512 MB.
maxHeapSize = '2g'
def logTarget = providers.systemProperty('robolectric.logging').orNull def logTarget = providers.systemProperty('robolectric.logging').orNull
if (logTarget != null) systemProperty 'robolectric.logging', logTarget if (logTarget != null) systemProperty 'robolectric.logging', logTarget
} }
@@ -263,14 +225,6 @@ def stageRuntimeAssets = tasks.register('stageRuntimeAssets', Sync) {
} }
android.sourceSets.main.assets.setSrcDirs([runtimeAssetsDir]) android.sourceSets.main.assets.setSrcDirs([runtimeAssetsDir])
if (vitureSdkDir) android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('vitureAssets')) if (vitureSdkDir) android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('vitureAssets'))
if (uvcDir) {
def stageUvcNotices = tasks.register('stageUvcNotices', Copy) {
from(new File(uvcDir, 'licenses'))
into(layout.buildDirectory.dir('uvcAssets/licenses/uvc'))
}
tasks.named('preBuild').configure { dependsOn(stageUvcNotices) }
android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('uvcAssets'))
}
tasks.named('preBuild').configure { dependsOn(stageRuntimeAssets) } tasks.named('preBuild').configure { dependsOn(stageRuntimeAssets) }
def verifyRuntimeInputs = tasks.register('verifyRuntimeInputs', Exec) { def verifyRuntimeInputs = tasks.register('verifyRuntimeInputs', Exec) {
@@ -313,7 +267,6 @@ if (!skipRust) android.sourceSets.main.jniLibs.srcDir(rustJniLibsDir)
tasks.named('preBuild').configure { dependsOn(buildRustStores) } tasks.named('preBuild').configure { dependsOn(buildRustStores) }
dependencies { dependencies {
implementation "org.opencv:opencv:${trackingPack.OPENCV_VERSION}"
implementation 'org.khronos.openxr:openxr_loader_for_android:1.1.49' implementation 'org.khronos.openxr:openxr_loader_for_android:1.1.49'
implementation 'com.github.luben:zstd-jni:1.5.7-4@aar' implementation 'com.github.luben:zstd-jni:1.5.7-4@aar'
implementation 'org.apache.commons:commons-compress:1.27.1' implementation 'org.apache.commons:commons-compress:1.27.1'
@@ -332,8 +285,7 @@ dependencies {
implementation 'com.termux.termux-app:terminal-view:0.118.0' implementation 'com.termux.termux-app:terminal-view:0.118.0'
implementation 'androidx.camera:camera-camera2:1.4.2' implementation 'androidx.camera:camera-camera2:1.4.2'
implementation 'androidx.camera:camera-lifecycle:1.4.2' implementation 'androidx.camera:camera-lifecycle:1.4.2'
implementation 'androidx.webkit:webkit:1.12.1' implementation('com.google.mediapipe:tasks-vision:0.10.21') {
implementation("com.google.mediapipe:tasks-vision:${trackingPack.MEDIAPIPE_VERSION}") {
exclude group: 'com.google.auto.value', module: 'auto-value' exclude group: 'com.google.auto.value', module: 'auto-value'
} }
+5 -32
View File
@@ -44,8 +44,6 @@
android:isGame="true"> android:isGame="true">
<meta-data android:name="android.game_mode_config" android:resource="@xml/game_mode_config" /> <meta-data android:name="android.game_mode_config" android:resource="@xml/game_mode_config" />
<service android:name=".glasses.LumaRgbCaptureService" android:exported="false"
android:process=":rgb_diagnostic" />
<meta-data android:name="com.oculus.supportedDevices" android:value="quest2|quest3|quest3s" /> <meta-data android:name="com.oculus.supportedDevices" android:value="quest2|quest3|quest3s" />
<activity android:name=".QuestXrActivity" android:exported="true" android:launchMode="singleTask" <activity android:name=".QuestXrActivity" android:exported="true" android:launchMode="singleTask"
android:permission="android.permission.DUMP" android:permission="android.permission.DUMP"
@@ -65,6 +63,11 @@
android:exported="true" android:exported="true"
android:screenOrientation="sensorLandscape" android:screenOrientation="sensorLandscape"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density|keyboard|keyboardHidden|navigation"> android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density|keyboard|keyboardHidden|navigation">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.CAR_LAUNCHER" />
</intent-filter>
<intent-filter> <intent-filter>
<action android:name="android.intent.action.VIEW" /> <action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.DEFAULT" />
@@ -83,31 +86,6 @@
</intent-filter> </intent-filter>
</activity> </activity>
<activity-alias
android:name=".LauncherDark"
android:targetActivity=".MainActivity"
android:icon="@mipmap/ic_launcher"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.CAR_LAUNCHER" />
</intent-filter>
</activity-alias>
<activity-alias
android:name=".LauncherLight"
android:targetActivity=".MainActivity"
android:icon="@mipmap/ic_launcher_light"
android:enabled="false"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.CAR_LAUNCHER" />
</intent-filter>
</activity-alias>
<activity <activity
android:name=".HomeActivity" android:name=".HomeActivity"
android:enabled="false" android:enabled="false"
@@ -147,10 +125,6 @@
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density" android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
android:theme="@style/AppTheme" /> android:theme="@style/AppTheme" />
<activity android:name=".stores.xbox.XboxLoginActivity" android:exported="false"
android:process=":xboxlogin" android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
android:theme="@style/AppTheme" />
<activity <activity
android:name=".stores.StoreLoginActivity" android:name=".stores.StoreLoginActivity"
android:exported="false" android:exported="false"
@@ -235,7 +209,6 @@
android:exported="true" android:exported="true"
android:permission="android.permission.DUMP" android:permission="android.permission.DUMP"
android:grantUriPermissions="false" /> android:grantUriPermissions="false" />
<activity android:name=".ui.SpatialTrackingActivity" android:exported="false" />
<service <service
android:name="com.google.android.datatransport.runtime.backends.TransportBackendDiscovery" android:name="com.google.android.datatransport.runtime.backends.TransportBackendDiscovery"
tools:node="merge"> tools:node="merge">
@@ -1,102 +0,0 @@
{
"version": 1,
"identity": "luma-ultra-base-v1",
"width": 640,
"height": 480,
"fisheye": false,
"error": 1.1209395390660726,
"verified": false,
"k1": {
"rows": 3,
"cols": 3,
"data": [
226.0499636040297,
0,
321.62348950766386,
0,
228.36987999988767,
242.2674105020684,
0,
0,
1
]
},
"d1": {
"rows": 5,
"cols": 1,
"data": [
-0.28622915867944043,
0.1194613930041054,
0.007984341063494766,
-0.0008220922923559441,
-0.025579805296512992
]
},
"k2": {
"rows": 3,
"cols": 3,
"data": [
240.3338202496282,
0,
320.8790079027563,
0,
241.14047924325277,
260.45566640784716,
0,
0,
1
]
},
"d2": {
"rows": 5,
"cols": 1,
"data": [
-0.27073208928390136,
0.08065508519805098,
-0.001460778493930769,
-0.0003694718992635806,
-0.011452505620454932
]
},
"r": {
"rows": 3,
"cols": 3,
"data": [
0.900501479835182,
0.04473903344740378,
-0.43254537762047496,
-0.08255720039597626,
0.9941919046988283,
-0.06904176485356042,
0.4269442510181227,
0.0978819468416306,
0.8989648107712929
]
},
"t": {
"rows": 3,
"cols": 1,
"data": [
-0.14117171913441395,
0.0014051874404824838,
-0.007555740272006347
]
},
"cameraToHead": [
-0.05607918,
0.023585627,
-0.07998472,
0.01024512,
0.9945703,
0.005859665,
-0.10339546
],
"deviceModel": "VITURE Luma Ultra",
"cameraPair": "left0-right0",
"sourceValidation": {
"exportDate": "2026-10-16",
"sourceDeviceVerified": true,
"capturedViews": 25,
"scope": "Starting geometry from one calibrated Luma Ultra; other units have not been individually validated."
}
}
+14 -26
View File
@@ -11,23 +11,23 @@ add_subdirectory(adrenotools)
# DXVK's DXBC->SPIR-V translator is zlib licensed (vendored under thirdparty/dxbc). # DXVK's DXBC->SPIR-V translator is zlib licensed (vendored under thirdparty/dxbc).
add_subdirectory(thirdparty/dxbc) add_subdirectory(thirdparty/dxbc)
set(DDFG_UPSTREAM "v0.3.0") set(WINFG_UPSTREAM "v0.3.0")
set(DDFG_CHAIN_SRC set(WINFG_CHAIN_SRC
framegen/ddfg/framegen.cpp framegen/winfg/framegen.cpp
framegen/ddfg/framegen.hpp framegen/winfg/framegen.hpp
framegen/ddfg/record_impl.inc framegen/winfg/record_impl.inc
framegen/ddfg/config.hpp framegen/winfg/config.hpp
framegen/ddfg/embedded_shaders.hpp framegen/winfg/embedded_shaders.hpp
framegen/ddfg/ddfg_engine.cpp framegen/winfg/winfg_engine.cpp
) )
set(DDFG_HASH_INPUT "") set(WINFG_HASH_INPUT "")
foreach(f ${DDFG_CHAIN_SRC}) foreach(f ${WINFG_CHAIN_SRC})
file(SHA256 "${CMAKE_CURRENT_SOURCE_DIR}/${f}" _h) file(SHA256 "${CMAKE_CURRENT_SOURCE_DIR}/${f}" _h)
string(APPEND DDFG_HASH_INPUT "${_h}") string(APPEND WINFG_HASH_INPUT "${_h}")
endforeach() endforeach()
string(SHA256 DDFG_CHAIN_HASH_FULL "${DDFG_HASH_INPUT}") string(SHA256 WINFG_CHAIN_HASH_FULL "${WINFG_HASH_INPUT}")
string(SUBSTRING "${DDFG_CHAIN_HASH_FULL}" 0 12 DDFG_CHAIN_HASH) string(SUBSTRING "${WINFG_CHAIN_HASH_FULL}" 0 12 WINFG_CHAIN_HASH)
message(STATUS "dd-fg chain: win-fg ${DDFG_UPSTREAM} (src ${DDFG_CHAIN_HASH})") message(STATUS "win-fg chain: ${WINFG_UPSTREAM} (src ${WINFG_CHAIN_HASH})")
add_subdirectory(waylandcomp) add_subdirectory(waylandcomp)
add_subdirectory(questxr) add_subdirectory(questxr)
@@ -47,15 +47,3 @@ if(DROIDDECK_VITURE_SDK_DIR)
target_link_directories(droiddeck_viture PRIVATE "${DROIDDECK_VITURE_SDK_DIR}/android/${ANDROID_ABI}") target_link_directories(droiddeck_viture PRIVATE "${DROIDDECK_VITURE_SDK_DIR}/android/${ANDROID_ABI}")
target_link_libraries(droiddeck_viture PRIVATE glasses log) target_link_libraries(droiddeck_viture PRIVATE glasses log)
endif() endif()
if(DROIDDECK_UVC_DIR)
add_library(rgb_usb SHARED IMPORTED)
set_target_properties(rgb_usb PROPERTIES IMPORTED_LOCATION "${DROIDDECK_UVC_DIR}/${ANDROID_ABI}/libusb.so")
add_library(rgb_uvc STATIC IMPORTED)
set_target_properties(rgb_uvc PROPERTIES IMPORTED_LOCATION "${DROIDDECK_UVC_DIR}/${ANDROID_ABI}/libuvc.a")
add_library(droiddeck_uvc SHARED viture/uvc_bridge.cpp)
target_compile_features(droiddeck_uvc PRIVATE cxx_std_17)
target_include_directories(droiddeck_uvc PRIVATE "${DROIDDECK_UVC_DIR}/include")
target_link_libraries(droiddeck_uvc PRIVATE rgb_uvc rgb_usb log)
target_link_options(droiddeck_uvc PRIVATE -Wl,-z,max-page-size=16384)
endif()
+21 -192
View File
@@ -21,9 +21,6 @@
#include <dirent.h> #include <dirent.h>
#include <dlfcn.h> #include <dlfcn.h>
#ifdef __GLIBC__
#include <gnu/lib-names.h>
#endif
#include <fcntl.h> #include <fcntl.h>
#include <linux/input.h> #include <linux/input.h>
#include <linux/joystick.h> #include <linux/joystick.h>
@@ -78,16 +75,7 @@ static constexpr uint8_t GAMEPAD_AXIS_COUNT = 8;
static constexpr uint8_t GAMEPAD_BUTTON_COUNT = 11; static constexpr uint8_t GAMEPAD_BUTTON_COUNT = 11;
static constexpr uint32_t FAKE_INPUT_RING_MAGIC = 0x46494252; static constexpr uint32_t FAKE_INPUT_RING_MAGIC = 0x46494252;
static constexpr uint32_t FAKE_INPUT_RING_VERSION = 2; static constexpr uint32_t FAKE_INPUT_RING_VERSION = 2;
// Rings hold the 64-bit input_event layout that the arm64 writers use; 32-bit guests convert on read. static constexpr uint32_t FAKE_INPUT_EVENT_SIZE = sizeof(struct input_event);
struct RingEvent {
int64_t sec;
int64_t usec;
uint16_t type;
uint16_t code;
int32_t value;
};
static_assert(sizeof(RingEvent) == 24, "ring events must stay ABI-stable");
static constexpr uint32_t FAKE_INPUT_EVENT_SIZE = sizeof(RingEvent);
static constexpr uint32_t FAKE_INPUT_RING_CAPACITY = 4096; static constexpr uint32_t FAKE_INPUT_RING_CAPACITY = 4096;
static constexpr unsigned int FAKE_INPUT_MAJOR = 13; static constexpr unsigned int FAKE_INPUT_MAJOR = 13;
static constexpr unsigned int FAKE_INPUT_EVENT_MINOR_BASE = 64; static constexpr unsigned int FAKE_INPUT_EVENT_MINOR_BASE = 64;
@@ -940,13 +928,14 @@ __attribute__((visibility("hidden"))) static void flush_uinput(UinputWriter &w)
return; return;
} }
FakeInputRingHeader *ring = w.ring; FakeInputRingHeader *ring = w.ring;
auto *events = reinterpret_cast<RingEvent *>(reinterpret_cast<uint8_t *>(ring) + auto *events = reinterpret_cast<struct input_event *>(reinterpret_cast<uint8_t *>(ring) +
FAKE_INPUT_RING_HEADER_SIZE); FAKE_INPUT_RING_HEADER_SIZE);
uint64_t write_seq = __atomic_load_n(&ring->write_seq, __ATOMIC_RELAXED); uint64_t write_seq = __atomic_load_n(&ring->write_seq, __ATOMIC_RELAXED);
struct timeval now = {}; struct timeval now = {};
gettimeofday(&now, nullptr); gettimeofday(&now, nullptr);
for (const struct input_event &ev : w.pending) { for (struct input_event ev : w.pending) {
events[write_seq % FAKE_INPUT_RING_CAPACITY] = {now.tv_sec, now.tv_usec, ev.type, ev.code, ev.value}; ev.time = now;
events[write_seq % FAKE_INPUT_RING_CAPACITY] = ev;
write_seq++; write_seq++;
if (ev.type == EV_KEY) { if (ev.type == EV_KEY) {
for (size_t i = 0; i < kSnapshotButtonCount; i++) for (size_t i = 0; i < kSnapshotButtonCount; i++)
@@ -3522,12 +3511,6 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
} else if (type == 0x45 && number == 0x90) { } else if (type == 0x45 && number == 0x90) {
Logger::log("Hooking ioctl EVIOCGRAB for event %s\n", event); Logger::log("Hooking ioctl EVIOCGRAB for event %s\n", event);
return 0; return 0;
} else if (type == 0x6A && !strncmp(event, "event", 5)) {
// Older SDL2 builds treat any JSIOCGNAME answer as a joydev node and skip EVIOCGID, then drop the pad as 0000:0000.
Logger::log("Rejecting joydev ioctl %d for event %s\n", number, event);
guard.unlock();
errno = EINVAL;
return -1;
} else if (type == 0x6A && number == 0x1) { } else if (type == 0x6A && number == 0x1) {
Logger::log("Hooking ioctl JSIOCGVERSION for event %s\n", event); Logger::log("Hooking ioctl JSIOCGVERSION for event %s\n", event);
int version = JS_VERSION; int version = JS_VERSION;
@@ -3580,21 +3563,7 @@ EXPORT int close(int fd) {
static constexpr int kMaxRingWaitMs = 2; static constexpr int kMaxRingWaitMs = 2;
static constexpr int kLowLatencyRingWaitUs = 250; static constexpr int kLowLatencyRingWaitUs = 250;
static ssize_t copy_input_events(void *buf, const struct input_event *events, size_t count) { EXPORT ssize_t read(int fd, void *buf, size_t count) {
size_t bytes = count * sizeof(struct input_event);
struct iovec local = {const_cast<struct input_event *>(events), bytes};
struct iovec remote = {buf, bytes};
ssize_t copied = syscall(SYS_process_vm_writev, getpid(), &local, 1, &remote, 1, 0);
if (copied < 0) return -1;
if (copied != static_cast<ssize_t>(bytes)) {
errno = EFAULT;
copied -= copied % sizeof(struct input_event);
if (!copied) return -1;
}
return copied;
}
static ssize_t read_input(int fd, void *buf, size_t count) {
if (!watched(fd)) return syscall(SYS_read, fd, buf, count); if (!watched(fd)) return syscall(SYS_read, fd, buf, count);
std::unique_lock<std::recursive_mutex> guard(controller_mutex()); std::unique_lock<std::recursive_mutex> guard(controller_mutex());
auto controller = controller_map().find(fd); auto controller = controller_map().find(fd);
@@ -3604,7 +3573,7 @@ static ssize_t read_input(int fd, void *buf, size_t count) {
} }
auto handle = controller->second; auto handle = controller->second;
FakeController &fake = *handle; FakeController &fake = *handle;
if (count < sizeof(struct input_event)) { if (count < FAKE_INPUT_EVENT_SIZE) {
errno = EINVAL; errno = EINVAL;
return -1; return -1;
} }
@@ -3622,7 +3591,7 @@ static ssize_t read_input(int fd, void *buf, size_t count) {
return -1; return -1;
} }
for (int attempt = 0; attempt < 8; ++attempt) { for (int attempt = 0; attempt < 8; ++attempt) {
size_t requested = count / sizeof(struct input_event); size_t requested = count / FAKE_INPUT_EVENT_SIZE;
if (fake.keyframe_remaining == 0) { if (fake.keyframe_remaining == 0) {
SnapshotState snap; SnapshotState snap;
if (!read_snapshot(fake.ring, snap)) break; if (!read_snapshot(fake.ring, snap)) break;
@@ -3639,44 +3608,38 @@ static ssize_t read_input(int fd, void *buf, size_t count) {
if (events == 0) break; if (events == 0) break;
const uint8_t *ring_events = reinterpret_cast<const uint8_t *>(fake.ring) + const uint8_t *ring_events = reinterpret_cast<const uint8_t *>(fake.ring) +
FAKE_INPUT_RING_HEADER_SIZE; FAKE_INPUT_RING_HEADER_SIZE;
std::vector<struct input_event> input_events(events);
for (size_t i = 0; i < events; ++i) { for (size_t i = 0; i < events; ++i) {
size_t index = (fake.read_seq + i) % FAKE_INPUT_RING_CAPACITY; size_t index = (fake.read_seq + i) % FAKE_INPUT_RING_CAPACITY;
RingEvent stored; struct input_event ev;
memcpy(&stored, ring_events + index * FAKE_INPUT_EVENT_SIZE, FAKE_INPUT_EVENT_SIZE); memcpy(&ev, ring_events + index * FAKE_INPUT_EVENT_SIZE, FAKE_INPUT_EVENT_SIZE);
struct input_event &ev = input_events[i];
ev.time.tv_sec = stored.sec;
ev.time.tv_usec = stored.usec;
ev.type = stored.type;
ev.code = stored.code;
ev.value = stored.value;
if (ev.type == EV_ABS) ev.code = presented_abs_code(fake, ev.code); if (ev.type == EV_ABS) ev.code = presented_abs_code(fake, ev.code);
memcpy(static_cast<uint8_t *>(buf) + i * FAKE_INPUT_EVENT_SIZE, &ev,
FAKE_INPUT_EVENT_SIZE);
} }
__atomic_thread_fence(__ATOMIC_ACQUIRE); __atomic_thread_fence(__ATOMIC_ACQUIRE);
if (snap.sequence != __atomic_load_n(&fake.ring->snapshot_seq, __ATOMIC_RELAXED)) if (snap.sequence != __atomic_load_n(&fake.ring->snapshot_seq, __ATOMIC_RELAXED))
continue; continue;
ssize_t copied = copy_input_events(buf, input_events.data(), events); fake.read_seq += events;
if (copied > 0) fake.read_seq += copied / sizeof(struct input_event); return static_cast<ssize_t>(events * FAKE_INPUT_EVENT_SIZE);
return copied;
} }
} }
size_t events = std::min(requested, fake.keyframe_remaining); size_t events = std::min(requested, fake.keyframe_remaining);
struct input_event input_events[kNeutralEventCount] = {};
struct timeval now = {}; struct timeval now = {};
gettimeofday(&now, nullptr); gettimeofday(&now, nullptr);
for (size_t i = 0; i < events; ++i) { for (size_t i = 0; i < events; ++i) {
size_t index = kNeutralEventCount - fake.keyframe_remaining + i; size_t index = kNeutralEventCount - fake.keyframe_remaining;
struct input_event &ev = input_events[i]; struct input_event ev = {};
ev.time = now; ev.time = now;
ev.type = kNeutralEvents[index].type; ev.type = kNeutralEvents[index].type;
ev.code = kNeutralEvents[index].code; ev.code = kNeutralEvents[index].code;
ev.value = keyframe_value(fake, ev.type, ev.code); ev.value = keyframe_value(fake, ev.type, ev.code);
if (ev.type == EV_ABS) ev.code = presented_abs_code(fake, ev.code); if (ev.type == EV_ABS) ev.code = presented_abs_code(fake, ev.code);
memcpy(static_cast<uint8_t *>(buf) + i * FAKE_INPUT_EVENT_SIZE,
&ev, FAKE_INPUT_EVENT_SIZE);
--fake.keyframe_remaining;
} }
ssize_t copied = copy_input_events(buf, input_events, events); return static_cast<ssize_t>(events * FAKE_INPUT_EVENT_SIZE);
if (copied > 0) fake.keyframe_remaining -= copied / sizeof(struct input_event);
return copied;
} }
if (nonblock) { if (nonblock) {
errno = EAGAIN; errno = EAGAIN;
@@ -3692,52 +3655,6 @@ static ssize_t read_input(int fd, void *buf, size_t count) {
} }
} }
EXPORT ssize_t read(int fd, void *buf, size_t count) {
return read_input(fd, buf, count);
}
EXPORT ssize_t readv(int fd, const struct iovec *iov, int iovcnt) {
if (!is_fake_input_fd(fd)) return syscall(SYS_readv, fd, iov, iovcnt);
if (iovcnt < 0 || iovcnt > IOV_MAX) {
errno = EINVAL;
return -1;
}
if (iovcnt && !iov) {
errno = EFAULT;
return -1;
}
std::vector<struct iovec> copied_iov(static_cast<size_t>(iovcnt));
if (iovcnt) {
size_t bytes = copied_iov.size() * sizeof(struct iovec);
struct iovec local = {copied_iov.data(), bytes};
struct iovec remote = {const_cast<struct iovec *>(iov), bytes};
ssize_t copied = syscall(SYS_process_vm_readv, getpid(), &local, 1, &remote, 1, 0);
if (copied != static_cast<ssize_t>(bytes)) {
errno = EFAULT;
return -1;
}
}
iov = copied_iov.data();
size_t size = 0;
for (int i = 0; i < iovcnt; ++i) {
if (iov[i].iov_len > static_cast<size_t>(SSIZE_MAX) - size) {
errno = EINVAL;
return -1;
}
size += iov[i].iov_len;
}
ssize_t total = 0;
for (int i = 0; i < iovcnt; ++i) {
if (!iov[i].iov_len) continue;
ssize_t got = read_input(fd, iov[i].iov_base, iov[i].iov_len);
if (got < 0) return total ? total : -1;
total += got;
if (static_cast<size_t>(got) != iov[i].iov_len) break;
}
return total;
}
EXPORT ssize_t write(int fd, const void *buf, size_t count) { EXPORT ssize_t write(int fd, const void *buf, size_t count) {
static auto my_write = reinterpret_cast<decltype(&::write)>(dlsym(RTLD_NEXT, "write")); static auto my_write = reinterpret_cast<decltype(&::write)>(dlsym(RTLD_NEXT, "write"));
@@ -4168,92 +4085,4 @@ EXPORT int __fxstat64(int version, int fd, struct stat64 *buf) {
if (!real) return fstat64(fd, buf); if (!real) return fstat64(fd, buf);
return fake_stat_fd(fd, buf, [version](int f, struct stat64 *b) { return real(version, f, b); }); return fake_stat_fd(fd, buf, [version](int f, struct stat64 *b) { return real(version, f, b); });
} }
#if defined(__x86_64__) || defined(__i386__)
using dlsym_fn = void *(*)(void *, const char *);
static const char *const interposed_names[] = {
"open", "open64", "openat", "openat64", "close", "read", "readv", "write", "writev", "ioctl",
"poll", "ppoll", "select", "stat", "stat64", "fstat", "fstat64", "__xstat", "__xstat64",
"__fxstat", "__fxstat64", "statx", "statfs", "statfs64", "fstatfs", "fstatfs64", "access",
"faccessat", "opendir", "scandir", "inotify_add_watch",
};
static dlsym_fn next_dlsym() {
static const dlsym_fn fn = [] {
#ifdef __x86_64__
const char *base = "GLIBC_2.2.5";
#else
const char *base = "GLIBC_2.0";
#endif
for (const char *version : {base, "GLIBC_2.34"}) {
if (auto found = reinterpret_cast<dlsym_fn>(dlvsym(RTLD_NEXT, "dlsym", version))) return found;
}
return dlsym_fn{};
}();
return fn;
}
static void *global_dlsym(void *, const char *name) { return next_dlsym()(RTLD_DEFAULT, name); }
static void *missing_dlsym(void *, const char *) { return nullptr; }
static bool interposed(const char *name) {
for (const char *interposed_name : interposed_names) {
if (strcmp(interposed_name, name) == 0) return true;
}
return false;
}
extern "C" __attribute__((visibility("hidden"), used)) void *fakeinput_dlsym_target(void *handle, const char *name) {
dlsym_fn next = next_dlsym();
if (!next) return reinterpret_cast<void *>(missing_dlsym);
if (handle == RTLD_DEFAULT || handle == RTLD_NEXT || name == nullptr) return reinterpret_cast<void *>(next);
static void *const libc = dlopen(LIBC_SO, RTLD_LAZY | RTLD_NOLOAD);
if (handle != libc || !interposed(name)) return reinterpret_cast<void *>(next);
return reinterpret_cast<void *>(global_dlsym);
}
#ifdef __x86_64__
__asm__(".text\n"
".globl dlsym\n"
".type dlsym, @function\n"
"dlsym:\n"
".cfi_startproc\n"
"pushq %rdi\n"
".cfi_adjust_cfa_offset 8\n"
"pushq %rsi\n"
".cfi_adjust_cfa_offset 8\n"
"subq $8, %rsp\n"
".cfi_adjust_cfa_offset 8\n"
"call fakeinput_dlsym_target\n"
"addq $8, %rsp\n"
".cfi_adjust_cfa_offset -8\n"
"popq %rsi\n"
".cfi_adjust_cfa_offset -8\n"
"popq %rdi\n"
".cfi_adjust_cfa_offset -8\n"
"jmp *%rax\n"
".cfi_endproc\n"
".size dlsym, .-dlsym\n");
#else
__asm__(".text\n"
".globl dlsym\n"
".type dlsym, @function\n"
"dlsym:\n"
".cfi_startproc\n"
"subl $12, %esp\n"
".cfi_adjust_cfa_offset 12\n"
"movl 20(%esp), %eax\n"
"movl %eax, 4(%esp)\n"
"movl 16(%esp), %eax\n"
"movl %eax, (%esp)\n"
"call fakeinput_dlsym_target\n"
"addl $12, %esp\n"
".cfi_adjust_cfa_offset -12\n"
"jmp *%eax\n"
".cfi_endproc\n"
".size dlsym, .-dlsym\n");
#endif
#endif
#endif #endif
@@ -131,7 +131,7 @@ struct VkTable {
#include <string> #include <string>
namespace lsfg { class Engine; } namespace lsfg { class Engine; }
namespace ddfg { class Engine; } namespace winfg { class Engine; }
static constexpr uint32_t MAX_FRAMES_IN_FLIGHT = 2; static constexpr uint32_t MAX_FRAMES_IN_FLIGHT = 2;
@@ -280,7 +280,7 @@ public:
static constexpr int32_t kFgCaptureGame = -1; static constexpr int32_t kFgCaptureGame = -1;
void setFrameGenTuning(float flowScale, float refreshHz, int32_t captureHeight = 0); void setFrameGenTuning(float flowScale, float refreshHz, int32_t captureHeight = 0);
void setFrameGenEngine(int kind); void setFrameGenEngine(int kind);
void setDdFgTuning(int model, int perfPreset); void setWinFgTuning(int model, int perfPreset);
private: private:
struct WinTex { struct WinTex {
@@ -468,12 +468,12 @@ private:
uint64_t fgSourceFrames_ = 0; uint64_t fgSourceFrames_ = 0;
std::string lsfgCachePath_; std::string lsfgCachePath_;
bool lsfgEngineTried_ = false; bool lsfgEngineTried_ = false;
std::unique_ptr<ddfg::Engine> ddfgEngine_; std::unique_ptr<winfg::Engine> winfgEngine_;
bool ddfgEngineTried_ = false; bool winfgEngineTried_ = false;
std::atomic<int> fgEngineKind_{0}; std::atomic<int> fgEngineKind_{0};
std::atomic<int> fgModel_{4}; std::atomic<int> fgModel_{4};
std::atomic<int> fgPerfPreset_{1}; std::atomic<int> fgPerfPreset_{1};
bool ensureDdFgEngine(); bool ensureWinFgEngine();
bool fgCapsOk() const; bool fgCapsOk() const;
uint32_t syncSlot(uint32_t k) const { return currentFrame * kMaxPresentsPerFrame + k; } uint32_t syncSlot(uint32_t k) const { return currentFrame * kMaxPresentsPerFrame + k; }
@@ -1,4 +0,0 @@
#pragma once
#include "vk_dispatch.hpp"
struct VkTable;
bool ddfgVkdInit(const VkTable& table, ddfg::DeviceDispatch& dd, ddfg::InstanceDispatch& id);
-12
View File
@@ -1,12 +0,0 @@
#pragma once
#if defined(__ANDROID__)
#include <android/log.h>
#define DDFG_LOGI(...) __android_log_print(ANDROID_LOG_INFO, "dd-fg", __VA_ARGS__)
#define DDFG_LOGE(...) __android_log_print(ANDROID_LOG_ERROR, "dd-fg", __VA_ARGS__)
#else
#include <cstdio>
#define DDFG_LOGI(...) do { std::fprintf(stderr, "[dd-fg] " __VA_ARGS__); std::fprintf(stderr, "\n"); } while(0)
#define DDFG_LOGE(...) do { std::fprintf(stderr, "[dd-fg][E] " __VA_ARGS__); std::fprintf(stderr, "\n"); } while(0)
#endif
#define DDFG_LOGD(cond, ...) do { if (cond) DDFG_LOGI(__VA_ARGS__); } while(0)
@@ -6,7 +6,7 @@
#include <fstream> #include <fstream>
#include <sstream> #include <sstream>
namespace ddfg { namespace winfg {
struct Config { struct Config {
bool enabled = false; bool enabled = false;
@@ -213,48 +213,48 @@ static inline void apply_toml(Config& c, const std::string& path) {
} }
static inline std::string conf_path() { static inline std::string conf_path() {
if (const char* p = std::getenv("DD_FG_CONF")) return p; if (const char* p = std::getenv("WIN_FG_CONF")) return p;
const char* home = std::getenv("HOME"); const char* home = std::getenv("HOME");
return home ? std::string(home) + "/.config/dd-fg/conf.toml" : std::string(); return home ? std::string(home) + "/.config/win-fg/conf.toml" : std::string();
} }
static inline std::string capture_root(const Config& c) { static inline std::string capture_root(const Config& c) {
if (!c.capDir.empty()) return c.capDir; if (!c.capDir.empty()) return c.capDir;
if (const char* home = std::getenv("HOME")) return std::string(home) + "/.cache/ddfg-capture"; if (const char* home = std::getenv("HOME")) return std::string(home) + "/.cache/winfg-capture";
return std::string("/tmp/ddfg-capture"); return std::string("/tmp/winfg-capture");
} }
static inline Config load_config() { static inline Config load_config() {
Config c; Config c;
c.enabled = envi("DD_FG_ENABLE", 0) != 0; c.enabled = envi("WIN_FG_ENABLE", 0) != 0;
if (const char* d = std::getenv("DD_FG_DEBUG")) c.debug = parse_bool(d, c.debug); if (const char* d = std::getenv("WIN_FG_DEBUG")) c.debug = parse_bool(d, c.debug);
if (const char* pc = std::getenv("DD_FG_PACING")) c.pacing = parse_bool(pc, c.pacing); if (const char* pc = std::getenv("WIN_FG_PACING")) c.pacing = parse_bool(pc, c.pacing);
c.model = envi("DD_FG_MODEL", c.model); c.model = envi("WIN_FG_MODEL", c.model);
c.multiplier = envi("DD_FG_MULT", c.multiplier); c.multiplier = envi("WIN_FG_MULT", c.multiplier);
c.extraImages = envi("DD_FG_EXTRA_IMAGES", c.extraImages); c.extraImages = envi("WIN_FG_EXTRA_IMAGES", c.extraImages);
c.perfPreset = envi("DD_FG_PERF_PRESET", c.perfPreset); c.perfPreset = envi("WIN_FG_PERF_PRESET", c.perfPreset);
if (const char* g = std::getenv("DD_FG_GM")) c.gmMode = parse_tristate(g, c.gmMode); if (const char* g = std::getenv("WIN_FG_GM")) c.gmMode = parse_tristate(g, c.gmMode);
if (const char* r = std::getenv("DD_FG_FLOWREG")) c.frMode = parse_tristate(r, c.frMode); if (const char* r = std::getenv("WIN_FG_FLOWREG")) c.frMode = parse_tristate(r, c.frMode);
c.frIters = envi("DD_FG_FR_ITERS", c.frIters); c.frIters = envi("WIN_FG_FR_ITERS", c.frIters);
c.frLambda = envf("DD_FG_FR_LAMBDA", c.frLambda); c.frLambda = envf("WIN_FG_FR_LAMBDA", c.frLambda);
c.frDt = envf("DD_FG_FR_DT", c.frDt); c.frDt = envf("WIN_FG_FR_DT", c.frDt);
c.frEdge = envf("DD_FG_FR_EDGE", c.frEdge); c.frEdge = envf("WIN_FG_FR_EDGE", c.frEdge);
c.frEps = envf("DD_FG_FR_EPS", c.frEps); c.frEps = envf("WIN_FG_FR_EPS", c.frEps);
c.flowScale = envf("DD_FG_FLOWSCALE", c.flowScale); c.flowScale = envf("WIN_FG_FLOWSCALE", c.flowScale);
c.beta = envf("DD_FG_BETA", c.beta); c.beta = envf("WIN_FG_BETA", c.beta);
c.lambda = envf("DD_FG_LAMBDA", c.lambda); c.lambda = envf("WIN_FG_LAMBDA", c.lambda);
c.epsilon = envf("DD_FG_EPSILON", c.epsilon); c.epsilon = envf("WIN_FG_EPSILON", c.epsilon);
c.photoScale = envf("DD_FG_PHOTOSCALE", c.photoScale); c.photoScale = envf("WIN_FG_PHOTOSCALE", c.photoScale);
if (const char* cc = std::getenv("DD_FG_CAPTURE")) c.capture = parse_bool(cc, c.capture); if (const char* cc = std::getenv("WIN_FG_CAPTURE")) c.capture = parse_bool(cc, c.capture);
c.captureW = envi("DD_FG_CAPTURE_W", c.captureW); c.captureW = envi("WIN_FG_CAPTURE_W", c.captureW);
c.captureH = envi("DD_FG_CAPTURE_H", c.captureH); c.captureH = envi("WIN_FG_CAPTURE_H", c.captureH);
if (const char* cm = std::getenv("DD_FG_CAPTURE_MODE")) c.capMode = parse_capmode(cm, c.capMode); if (const char* cm = std::getenv("WIN_FG_CAPTURE_MODE")) c.capMode = parse_capmode(cm, c.capMode);
c.capPatches = envi("DD_FG_CAPTURE_PATCHES", c.capPatches); c.capPatches = envi("WIN_FG_CAPTURE_PATCHES", c.capPatches);
c.capPatchSize = envi("DD_FG_CAPTURE_PATCH", c.capPatchSize); c.capPatchSize = envi("WIN_FG_CAPTURE_PATCH", c.capPatchSize);
c.capMotion = envf("DD_FG_CAPTURE_MOTION", c.capMotion); c.capMotion = envf("WIN_FG_CAPTURE_MOTION", c.capMotion);
c.capShardMB = envi("DD_FG_CAPTURE_SHARD_MB", c.capShardMB); c.capShardMB = envi("WIN_FG_CAPTURE_SHARD_MB", c.capShardMB);
if (const char* cd = std::getenv("DD_FG_CAPTURE_DIR")) c.capDir = cd; if (const char* cd = std::getenv("WIN_FG_CAPTURE_DIR")) c.capDir = cd;
if (const char* h = std::getenv("DD_FG_HUD_RECT")) { if (const char* h = std::getenv("WIN_FG_HUD_RECT")) {
float r[4] = {0,0,0,0}; int n = 0; float r[4] = {0,0,0,0}; int n = 0;
std::string s = h; size_t start = 0; std::string s = h; size_t start = 0;
for (; n < 4; ++n) { for (; n < 4; ++n) {
@@ -266,8 +266,8 @@ static inline Config load_config() {
c.hudX0 = r[0]; c.hudY0 = r[1]; c.hudX1 = r[2]; c.hudY1 = r[3]; c.hudX0 = r[0]; c.hudY0 = r[1]; c.hudX1 = r[2]; c.hudY1 = r[3];
} }
const char* home = std::getenv("HOME"); const char* home = std::getenv("HOME");
if (home) apply_toml(c, std::string(home) + "/.config/dd-fg/conf.toml"); if (home) apply_toml(c, std::string(home) + "/.config/win-fg/conf.toml");
if (const char* p = std::getenv("DD_FG_CONF")) apply_toml(c, p); if (const char* p = std::getenv("WIN_FG_CONF")) apply_toml(c, p);
c.sanitize(); c.sanitize();
return c; return c;
} }
@@ -1,7 +1,7 @@
#pragma once #pragma once
#include <cstdint> #include <cstdint>
#include <cstddef> #include <cstddef>
namespace ddfg { namespace embedded { namespace winfg { namespace embedded {
static const uint32_t OF3_LUMA_SPV[] = {0x07230203u,0x00010300u,0x0008000bu,0x00000054u,0x00000000u,0x00020011u,0x00000001u,0x00020011u,0x00000032u,0x0006000bu,0x00000001u,0x4c534c47u,0x6474732eu,0x3035342eu,0x00000000u,0x0003000eu,0x00000000u,0x00000001u,0x0006000fu,0x00000005u,0x00000004u,0x6e69616du,0x00000000u,0x0000000du,0x00060010u,0x00000004u,0x00000011u,0x00000010u,0x00000010u,0x00000001u,0x00030003u,0x00000002u,0x000001c2u,0x00040005u,0x00000004u,0x6e69616du,0x00000000u,0x00030005u,0x00000009u,0x00646967u,0x00080005u,0x0000000du,0x475f6c67u,0x61626f6cu,0x766e496cu,0x7461636fu,0x496e6f69u,0x00000044u,0x00030005u,0x00000012u,0x006d6964u,0x00040005u,0x00000016u,0x74734475u,0x00000000u,0x00030005u,0x00000030u,0x00007675u,0x00030005u,0x0000003bu,0x00626772u,0x00040005u,0x0000003fu,0x63725375u,0x00000000u,0x00030005u,0x00000047u,0x00005966u,0x00040047u,0x0000000du,0x0000000bu,0x0000001cu,0x00030047u,0x00000016u,0x00000019u,0x00040047u,0x00000016u,0x00000021u,0x00000030u,0x00040047u,0x00000016u,0x00000022u,0x00000000u,0x00040047u,0x0000003fu,0x00000021u,0x00000020u,0x00040047u,0x0000003fu,0x00000022u,0x00000000u,0x00040047u,0x00000053u,0x0000000bu,0x00000019u,0x00020013u,0x00000002u,0x00030021u,0x00000003u,0x00000002u,0x00040015u,0x00000006u,0x00000020u,0x00000001u,0x00040017u,0x00000007u,0x00000006u,0x00000002u,0x00040020u,0x00000008u,0x00000007u,0x00000007u,0x00040015u,0x0000000au,0x00000020u,0x00000000u,0x00040017u,0x0000000bu,0x0000000au,0x00000003u,0x00040020u,0x0000000cu,0x00000001u,0x0000000bu,0x0004003bu,0x0000000cu,0x0000000du,0x00000001u,0x00040017u,0x0000000eu,0x0000000au,0x00000002u,0x00030016u,0x00000013u,0x00000020u,0x00090019u,0x00000014u,0x00000013u,0x00000001u,0x00000000u,0x00000000u,0x00000000u,0x00000002u,0x00000003u,0x00040020u,0x00000015u,0x00000000u,0x00000014u,0x0004003bu,0x00000015u,0x00000016u,0x00000000u,0x00020014u,0x00000019u,0x0004002bu,0x0000000au,0x0000001au,0x00000000u,0x00040020u,0x0000001bu,0x00000007u,0x00000006u,0x0004002bu,0x0000000au,0x00000024u,0x00000001u,0x00040017u,0x0000002eu,0x00000013u,0x00000002u,0x00040020u,0x0000002fu,0x00000007u,0x0000002eu,0x0004002bu,0x00000013u,0x00000033u,0x3f000000u,0x00040017u,0x00000039u,0x00000013u,0x00000003u,0x00040020u,0x0000003au,0x00000007u,0x00000039u,0x00090019u,0x0000003cu,0x00000013u,0x00000001u,0x00000000u,0x00000000u,0x00000000u,0x00000001u,0x00000000u,0x0003001bu,0x0000003du,0x0000003cu,0x00040020u,0x0000003eu,0x00000000u,0x0000003du,0x0004003bu,0x0000003eu,0x0000003fu,0x00000000u,0x0004002bu,0x00000013u,0x00000042u,0x00000000u,0x00040017u,0x00000043u,0x00000013u,0x00000004u,0x00040020u,0x00000046u,0x00000007u,0x00000013u,0x0004002bu,0x00000013u,0x00000049u,0x3e59b3d0u,0x0004002bu,0x00000013u,0x0000004au,0x3f371759u,0x0004002bu,0x00000013u,0x0000004bu,0x3d93dd98u,0x0006002cu,0x00000039u,0x0000004cu,0x00000049u,0x0000004au,0x0000004bu,0x0004002bu,0x0000000au,0x00000052u,0x00000010u,0x0006002cu,0x0000000bu,0x00000053u,0x00000052u,0x00000052u,0x00000024u,0x00050036u,0x00000002u,0x00000004u,0x00000000u,0x00000003u,0x000200f8u,0x00000005u,0x0004003bu,0x00000008u,0x00000009u,0x00000007u,0x0004003bu,0x00000008u,0x00000012u,0x00000007u,0x0004003bu,0x0000002fu,0x00000030u,0x00000007u,0x0004003bu,0x0000003au,0x0000003bu,0x00000007u,0x0004003bu,0x00000046u,0x00000047u,0x00000007u,0x0004003du,0x0000000bu,0x0000000fu,0x0000000du,0x0007004fu,0x0000000eu,0x00000010u,0x0000000fu,0x0000000fu,0x00000000u,0x00000001u,0x0004007cu,0x00000007u,0x00000011u,0x00000010u,0x0003003eu,0x00000009u,0x00000011u,0x0004003du,0x00000014u,0x00000017u,0x00000016u,0x00040068u,0x00000007u,0x00000018u,0x00000017u,0x0003003eu,0x00000012u,0x00000018u,0x00050041u,0x0000001bu,0x0000001cu,0x00000009u,0x0000001au,0x0004003du,0x00000006u,0x0000001du,0x0000001cu,0x00050041u,0x0000001bu,0x0000001eu,0x00000012u,0x0000001au,0x0004003du,0x00000006u,0x0000001fu,0x0000001eu,0x000500afu,0x00000019u,0x00000020u,0x0000001du,0x0000001fu,0x000400a8u,0x00000019u,0x00000021u,0x00000020u,0x000300f7u,0x00000023u,0x00000000u,0x000400fau,0x00000021u,0x00000022u,0x00000023u,0x000200f8u,0x00000022u,0x00050041u,0x0000001bu,0x00000025u,0x00000009u,0x00000024u,0x0004003du,0x00000006u,0x00000026u,0x00000025u,0x00050041u,0x0000001bu,0x00000027u,0x00000012u,0x00000024u,0x0004003du,0x00000006u,0x00000028u,0x00000027u,0x000500afu,0x00000019u,0x00000029u,0x00000026u,0x00000028u,0x000200f9u,0x00000023u,0x000200f8u,0x00000023u,0x000700f5u,0x00000019u,0x0000002au,0x00000020u,0x00000005u,0x00000029u,0x00000022u,0x000300f7u,0x0000002cu,0x00000000u,0x000400fau,0x0000002au,0x0000002bu,0x0000002cu,0x000200f8u,0x0000002bu,0x000100fdu,0x000200f8u,0x0000002cu,0x0004003du,0x00000007u,0x00000031u,0x00000009u,0x0004006fu,0x0000002eu,0x00000032u,0x00000031u,0x00050050u,0x0000002eu,0x00000034u,0x00000033u,0x00000033u,0x00050081u,0x0000002eu,0x00000035u,0x00000032u,0x00000034u,0x0004003du,0x00000007u,0x00000036u,0x00000012u,0x0004006fu,0x0000002eu,0x00000037u,0x00000036u,0x00050088u,0x0000002eu,0x00000038u,0x0Line truncated static const uint32_t OF3_LUMA_SPV[] = {0x07230203u,0x00010300u,0x0008000bu,0x00000054u,0x00000000u,0x00020011u,0x00000001u,0x00020011u,0x00000032u,0x0006000bu,0x00000001u,0x4c534c47u,0x6474732eu,0x3035342eu,0x00000000u,0x0003000eu,0x00000000u,0x00000001u,0x0006000fu,0x00000005u,0x00000004u,0x6e69616du,0x00000000u,0x0000000du,0x00060010u,0x00000004u,0x00000011u,0x00000010u,0x00000010u,0x00000001u,0x00030003u,0x00000002u,0x000001c2u,0x00040005u,0x00000004u,0x6e69616du,0x00000000u,0x00030005u,0x00000009u,0x00646967u,0x00080005u,0x0000000du,0x475f6c67u,0x61626f6cu,0x766e496cu,0x7461636fu,0x496e6f69u,0x00000044u,0x00030005u,0x00000012u,0x006d6964u,0x00040005u,0x00000016u,0x74734475u,0x00000000u,0x00030005u,0x00000030u,0x00007675u,0x00030005u,0x0000003bu,0x00626772u,0x00040005u,0x0000003fu,0x63725375u,0x00000000u,0x00030005u,0x00000047u,0x00005966u,0x00040047u,0x0000000du,0x0000000bu,0x0000001cu,0x00030047u,0x00000016u,0x00000019u,0x00040047u,0x00000016u,0x00000021u,0x00000030u,0x00040047u,0x00000016u,0x00000022u,0x00000000u,0x00040047u,0x0000003fu,0x00000021u,0x00000020u,0x00040047u,0x0000003fu,0x00000022u,0x00000000u,0x00040047u,0x00000053u,0x0000000bu,0x00000019u,0x00020013u,0x00000002u,0x00030021u,0x00000003u,0x00000002u,0x00040015u,0x00000006u,0x00000020u,0x00000001u,0x00040017u,0x00000007u,0x00000006u,0x00000002u,0x00040020u,0x00000008u,0x00000007u,0x00000007u,0x00040015u,0x0000000au,0x00000020u,0x00000000u,0x00040017u,0x0000000bu,0x0000000au,0x00000003u,0x00040020u,0x0000000cu,0x00000001u,0x0000000bu,0x0004003bu,0x0000000cu,0x0000000du,0x00000001u,0x00040017u,0x0000000eu,0x0000000au,0x00000002u,0x00030016u,0x00000013u,0x00000020u,0x00090019u,0x00000014u,0x00000013u,0x00000001u,0x00000000u,0x00000000u,0x00000000u,0x00000002u,0x00000003u,0x00040020u,0x00000015u,0x00000000u,0x00000014u,0x0004003bu,0x00000015u,0x00000016u,0x00000000u,0x00020014u,0x00000019u,0x0004002bu,0x0000000au,0x0000001au,0x00000000u,0x00040020u,0x0000001bu,0x00000007u,0x00000006u,0x0004002bu,0x0000000au,0x00000024u,0x00000001u,0x00040017u,0x0000002eu,0x00000013u,0x00000002u,0x00040020u,0x0000002fu,0x00000007u,0x0000002eu,0x0004002bu,0x00000013u,0x00000033u,0x3f000000u,0x00040017u,0x00000039u,0x00000013u,0x00000003u,0x00040020u,0x0000003au,0x00000007u,0x00000039u,0x00090019u,0x0000003cu,0x00000013u,0x00000001u,0x00000000u,0x00000000u,0x00000000u,0x00000001u,0x00000000u,0x0003001bu,0x0000003du,0x0000003cu,0x00040020u,0x0000003eu,0x00000000u,0x0000003du,0x0004003bu,0x0000003eu,0x0000003fu,0x00000000u,0x0004002bu,0x00000013u,0x00000042u,0x00000000u,0x00040017u,0x00000043u,0x00000013u,0x00000004u,0x00040020u,0x00000046u,0x00000007u,0x00000013u,0x0004002bu,0x00000013u,0x00000049u,0x3e59b3d0u,0x0004002bu,0x00000013u,0x0000004au,0x3f371759u,0x0004002bu,0x00000013u,0x0000004bu,0x3d93dd98u,0x0006002cu,0x00000039u,0x0000004cu,0x00000049u,0x0000004au,0x0000004bu,0x0004002bu,0x0000000au,0x00000052u,0x00000010u,0x0006002cu,0x0000000bu,0x00000053u,0x00000052u,0x00000052u,0x00000024u,0x00050036u,0x00000002u,0x00000004u,0x00000000u,0x00000003u,0x000200f8u,0x00000005u,0x0004003bu,0x00000008u,0x00000009u,0x00000007u,0x0004003bu,0x00000008u,0x00000012u,0x00000007u,0x0004003bu,0x0000002fu,0x00000030u,0x00000007u,0x0004003bu,0x0000003au,0x0000003bu,0x00000007u,0x0004003bu,0x00000046u,0x00000047u,0x00000007u,0x0004003du,0x0000000bu,0x0000000fu,0x0000000du,0x0007004fu,0x0000000eu,0x00000010u,0x0000000fu,0x0000000fu,0x00000000u,0x00000001u,0x0004007cu,0x00000007u,0x00000011u,0x00000010u,0x0003003eu,0x00000009u,0x00000011u,0x0004003du,0x00000014u,0x00000017u,0x00000016u,0x00040068u,0x00000007u,0x00000018u,0x00000017u,0x0003003eu,0x00000012u,0x00000018u,0x00050041u,0x0000001bu,0x0000001cu,0x00000009u,0x0000001au,0x0004003du,0x00000006u,0x0000001du,0x0000001cu,0x00050041u,0x0000001bu,0x0000001eu,0x00000012u,0x0000001au,0x0004003du,0x00000006u,0x0000001fu,0x0000001eu,0x000500afu,0x00000019u,0x00000020u,0x0000001du,0x0000001fu,0x000400a8u,0x00000019u,0x00000021u,0x00000020u,0x000300f7u,0x00000023u,0x00000000u,0x000400fau,0x00000021u,0x00000022u,0x00000023u,0x000200f8u,0x00000022u,0x00050041u,0x0000001bu,0x00000025u,0x00000009u,0x00000024u,0x0004003du,0x00000006u,0x00000026u,0x00000025u,0x00050041u,0x0000001bu,0x00000027u,0x00000012u,0x00000024u,0x0004003du,0x00000006u,0x00000028u,0x00000027u,0x000500afu,0x00000019u,0x00000029u,0x00000026u,0x00000028u,0x000200f9u,0x00000023u,0x000200f8u,0x00000023u,0x000700f5u,0x00000019u,0x0000002au,0x00000020u,0x00000005u,0x00000029u,0x00000022u,0x000300f7u,0x0000002cu,0x00000000u,0x000400fau,0x0000002au,0x0000002bu,0x0000002cu,0x000200f8u,0x0000002bu,0x000100fdu,0x000200f8u,0x0000002cu,0x0004003du,0x00000007u,0x00000031u,0x00000009u,0x0004006fu,0x0000002eu,0x00000032u,0x00000031u,0x00050050u,0x0000002eu,0x00000034u,0x00000033u,0x00000033u,0x00050081u,0x0000002eu,0x00000035u,0x00000032u,0x00000034u,0x0004003du,0x00000007u,0x00000036u,0x00000012u,0x0004006fu,0x0000002eu,0x00000037u,0x00000036u,0x00050088u,0x0000002eu,0x00000038u,0x0Line truncated
static const size_t OF3_LUMA_LEN = 481; static const size_t OF3_LUMA_LEN = 481;
static const uint32_t OF3_DOWNSAMPLE_SPV[] = {0x07230203u,0x00010300u,0x0008000bu,0x0000008au,0x00000000u,0x00020011u,0x00000001u,0x00020011u,0x00000032u,0x0006000bu,0x00000001u,0x4c534c47u,0x6474732eu,0x3035342eu,0x00000000u,0x0003000eu,0x00000000u,0x00000001u,0x0006000fu,0x00000005u,0x00000004u,0x6e69616du,0x00000000u,0x0000000du,0x00060010u,0x00000004u,0x00000011u,0x00000010u,0x00000010u,0x00000001u,0x00030003u,0x00000002u,0x000001c2u,0x00040005u,0x00000004u,0x6e69616du,0x00000000u,0x00030005u,0x00000009u,0x00646967u,0x00080005u,0x0000000du,0x475f6c67u,0x61626f6cu,0x766e496cu,0x7461636fu,0x496e6f69u,0x00000044u,0x00030005u,0x00000012u,0x006d6964u,0x00040005u,0x00000016u,0x74734475u,0x00000000u,0x00040005u,0x00000030u,0x44637273u,0x00006d69u,0x00040005u,0x00000034u,0x63725375u,0x00000000u,0x00040005u,0x0000003au,0x65736162u,0x00000000u,0x00030005u,0x00000044u,0x00000068u,0x00030005u,0x0000004au,0x00000061u,0x00030005u,0x00000059u,0x00000062u,0x00030005u,0x00000065u,0x00000063u,0x00030005u,0x00000071u,0x00000064u,0x00040047u,0x0000000du,0x0000000bu,0x0000001cu,0x00030047u,0x00000016u,0x00000019u,0x00040047u,0x00000016u,0x00000021u,0x00000030u,0x00040047u,0x00000016u,0x00000022u,0x00000000u,0x00040047u,0x00000034u,0x00000021u,0x00000020u,0x00040047u,0x00000034u,0x00000022u,0x00000000u,0x00040047u,0x00000089u,0x0000000bu,0x00000019u,0x00020013u,0x00000002u,0x00030021u,0x00000003u,0x00000002u,0x00040015u,0x00000006u,0x00000020u,0x00000001u,0x00040017u,0x00000007u,0x00000006u,0x00000002u,0x00040020u,0x00000008u,0x00000007u,0x00000007u,0x00040015u,0x0000000au,0x00000020u,0x00000000u,0x00040017u,0x0000000bu,0x0000000au,0x00000003u,0x00040020u,0x0000000cu,0x00000001u,0x0000000bu,0x0004003bu,0x0000000cu,0x0000000du,0x00000001u,0x00040017u,0x0000000eu,0x0000000au,0x00000002u,0x00030016u,0x00000013u,0x00000020u,0x00090019u,0x00000014u,0x00000013u,0x00000001u,0x00000000u,0x00000000u,0x00000000u,0x00000002u,0x00000003u,0x00040020u,0x00000015u,0x00000000u,0x00000014u,0x0004003bu,0x00000015u,0x00000016u,0x00000000u,0x00020014u,0x00000019u,0x0004002bu,0x0000000au,0x0000001au,0x00000000u,0x00040020u,0x0000001bu,0x00000007u,0x00000006u,0x0004002bu,0x0000000au,0x00000024u,0x00000001u,0x00040017u,0x0000002eu,0x00000013u,0x00000002u,0x00040020u,0x0000002fu,0x00000007u,0x0000002eu,0x00090019u,0x00000031u,0x00000013u,0x00000001u,0x00000000u,0x00000000u,0x00000000u,0x00000001u,0x00000000u,0x0003001bu,0x00000032u,0x00000031u,0x00040020u,0x00000033u,0x00000000u,0x00000032u,0x0004003bu,0x00000033u,0x00000034u,0x00000000u,0x0004002bu,0x00000006u,0x00000036u,0x00000000u,0x0004002bu,0x00000013u,0x0000003du,0x40000000u,0x0004002bu,0x00000013u,0x0000003fu,0x3f800000u,0x0004002bu,0x00000013u,0x00000045u,0x3f000000u,0x00040020u,0x00000049u,0x00000007u,0x00000013u,0x0004002bu,0x00000013u,0x00000055u,0x00000000u,0x00040017u,0x00000056u,0x00000013u,0x00000004u,0x0004002bu,0x00000013u,0x00000085u,0x3e800000u,0x0004002bu,0x0000000au,0x00000088u,0x00000010u,0x0006002cu,0x0000000bu,0x00000089u,0x00000088u,0x00000088u,0x00000024u,0x00050036u,0x00000002u,0x00000004u,0x00000000u,0x00000003u,0x000200f8u,0x00000005u,0x0004003bu,0x00000008u,0x00000009u,0x00000007u,0x0004003bu,0x00000008u,0x00000012u,0x00000007u,0x0004003bu,0x0000002fu,0x00000030u,0x00000007u,0x0004003bu,0x0000002fu,0x0000003au,0x00000007u,0x0004003bu,0x0000002fu,0x00000044u,0x00000007u,0x0004003bu,0x00000049u,0x0000004au,0x00000007u,0x0004003bu,0x00000049u,0x00000059u,0x00000007u,0x0004003bu,0x00000049u,0x00000065u,0x00000007u,0x0004003bu,0x00000049u,0x00000071u,0x00000007u,0x0004003du,0x0000000bu,0x0000000fu,0x0000000du,0x0007004fu,0x0000000eu,0x00000010u,0x0000000fu,0x0000000fu,0x00000000u,0x00000001u,0x0004007cu,0x00000007u,0x00000011u,0x00000010u,0x0003003eu,0x00000009u,0x00000011u,0x0004003du,0x00000014u,0x00000017u,0x00000016u,0x00040068u,0x00000007u,0x00000018u,0x00000017u,0x0003003eu,0x00000012u,0x00000018u,0x00050041u,0x0000001bu,0x0000001cu,0x00000009u,0x0000001au,0x0004003du,0x00000006u,0x0000001du,0x0000001cu,0x00050041u,0x0000001bu,0x0000001eu,0x00000012u,0x0000001au,0x0004003du,0x00000006u,0x0000001fu,0x0000001eu,0x000500afu,0x00000019u,0x00000020u,0x0000001du,0x0000001fu,0x000400a8u,0x00000019u,0x00000021u,0x00000020u,0x000300f7u,0x00000023u,0x00000000u,0x000400fau,0x00000021u,0x00000022u,0x00000023u,0x000200f8u,0x00000022u,0x00050041u,0x0000001bu,0x00000025u,0x00000009u,0x00000024u,0x0004003du,0x00000006u,0x00000026u,0x00000025u,0x00050041u,0x0000001bu,0x00000027u,0x00000012u,0x00000024u,0x0004003du,0x00000006u,0x00000028u,0x00000027u,0x000500afu,0x00000019u,0x00000029u,0x00000026u,0x00000028u,0x000200f9u,0x00000023u,0x000200f8u,0x00000023u,0x000700f5u,0x00000019u,0x0000002au,0x00000020u,0x00000005u,0x00000029u,0x00000022u,0x000300f7u,0x0000002cu,0x00000000u,0x000400fau,0x0000002au,0x0000002bu,0x0000002cu,0x000200f8u,0x0000002bu,0x000100fdu,0x000200f8u,0x0000002cu,0x0004003du,0x00000032u,0x00000035u,0x00000034u,0x00040064u,0x00000031u,0x00000037u,0x00000035u,0x0005006Line truncated static const uint32_t OF3_DOWNSAMPLE_SPV[] = {0x07230203u,0x00010300u,0x0008000bu,0x0000008au,0x00000000u,0x00020011u,0x00000001u,0x00020011u,0x00000032u,0x0006000bu,0x00000001u,0x4c534c47u,0x6474732eu,0x3035342eu,0x00000000u,0x0003000eu,0x00000000u,0x00000001u,0x0006000fu,0x00000005u,0x00000004u,0x6e69616du,0x00000000u,0x0000000du,0x00060010u,0x00000004u,0x00000011u,0x00000010u,0x00000010u,0x00000001u,0x00030003u,0x00000002u,0x000001c2u,0x00040005u,0x00000004u,0x6e69616du,0x00000000u,0x00030005u,0x00000009u,0x00646967u,0x00080005u,0x0000000du,0x475f6c67u,0x61626f6cu,0x766e496cu,0x7461636fu,0x496e6f69u,0x00000044u,0x00030005u,0x00000012u,0x006d6964u,0x00040005u,0x00000016u,0x74734475u,0x00000000u,0x00040005u,0x00000030u,0x44637273u,0x00006d69u,0x00040005u,0x00000034u,0x63725375u,0x00000000u,0x00040005u,0x0000003au,0x65736162u,0x00000000u,0x00030005u,0x00000044u,0x00000068u,0x00030005u,0x0000004au,0x00000061u,0x00030005u,0x00000059u,0x00000062u,0x00030005u,0x00000065u,0x00000063u,0x00030005u,0x00000071u,0x00000064u,0x00040047u,0x0000000du,0x0000000bu,0x0000001cu,0x00030047u,0x00000016u,0x00000019u,0x00040047u,0x00000016u,0x00000021u,0x00000030u,0x00040047u,0x00000016u,0x00000022u,0x00000000u,0x00040047u,0x00000034u,0x00000021u,0x00000020u,0x00040047u,0x00000034u,0x00000022u,0x00000000u,0x00040047u,0x00000089u,0x0000000bu,0x00000019u,0x00020013u,0x00000002u,0x00030021u,0x00000003u,0x00000002u,0x00040015u,0x00000006u,0x00000020u,0x00000001u,0x00040017u,0x00000007u,0x00000006u,0x00000002u,0x00040020u,0x00000008u,0x00000007u,0x00000007u,0x00040015u,0x0000000au,0x00000020u,0x00000000u,0x00040017u,0x0000000bu,0x0000000au,0x00000003u,0x00040020u,0x0000000cu,0x00000001u,0x0000000bu,0x0004003bu,0x0000000cu,0x0000000du,0x00000001u,0x00040017u,0x0000000eu,0x0000000au,0x00000002u,0x00030016u,0x00000013u,0x00000020u,0x00090019u,0x00000014u,0x00000013u,0x00000001u,0x00000000u,0x00000000u,0x00000000u,0x00000002u,0x00000003u,0x00040020u,0x00000015u,0x00000000u,0x00000014u,0x0004003bu,0x00000015u,0x00000016u,0x00000000u,0x00020014u,0x00000019u,0x0004002bu,0x0000000au,0x0000001au,0x00000000u,0x00040020u,0x0000001bu,0x00000007u,0x00000006u,0x0004002bu,0x0000000au,0x00000024u,0x00000001u,0x00040017u,0x0000002eu,0x00000013u,0x00000002u,0x00040020u,0x0000002fu,0x00000007u,0x0000002eu,0x00090019u,0x00000031u,0x00000013u,0x00000001u,0x00000000u,0x00000000u,0x00000000u,0x00000001u,0x00000000u,0x0003001bu,0x00000032u,0x00000031u,0x00040020u,0x00000033u,0x00000000u,0x00000032u,0x0004003bu,0x00000033u,0x00000034u,0x00000000u,0x0004002bu,0x00000006u,0x00000036u,0x00000000u,0x0004002bu,0x00000013u,0x0000003du,0x40000000u,0x0004002bu,0x00000013u,0x0000003fu,0x3f800000u,0x0004002bu,0x00000013u,0x00000045u,0x3f000000u,0x00040020u,0x00000049u,0x00000007u,0x00000013u,0x0004002bu,0x00000013u,0x00000055u,0x00000000u,0x00040017u,0x00000056u,0x00000013u,0x00000004u,0x0004002bu,0x00000013u,0x00000085u,0x3e800000u,0x0004002bu,0x0000000au,0x00000088u,0x00000010u,0x0006002cu,0x0000000bu,0x00000089u,0x00000088u,0x00000088u,0x00000024u,0x00050036u,0x00000002u,0x00000004u,0x00000000u,0x00000003u,0x000200f8u,0x00000005u,0x0004003bu,0x00000008u,0x00000009u,0x00000007u,0x0004003bu,0x00000008u,0x00000012u,0x00000007u,0x0004003bu,0x0000002fu,0x00000030u,0x00000007u,0x0004003bu,0x0000002fu,0x0000003au,0x00000007u,0x0004003bu,0x0000002fu,0x00000044u,0x00000007u,0x0004003bu,0x00000049u,0x0000004au,0x00000007u,0x0004003bu,0x00000049u,0x00000059u,0x00000007u,0x0004003bu,0x00000049u,0x00000065u,0x00000007u,0x0004003bu,0x00000049u,0x00000071u,0x00000007u,0x0004003du,0x0000000bu,0x0000000fu,0x0000000du,0x0007004fu,0x0000000eu,0x00000010u,0x0000000fu,0x0000000fu,0x00000000u,0x00000001u,0x0004007cu,0x00000007u,0x00000011u,0x00000010u,0x0003003eu,0x00000009u,0x00000011u,0x0004003du,0x00000014u,0x00000017u,0x00000016u,0x00040068u,0x00000007u,0x00000018u,0x00000017u,0x0003003eu,0x00000012u,0x00000018u,0x00050041u,0x0000001bu,0x0000001cu,0x00000009u,0x0000001au,0x0004003du,0x00000006u,0x0000001du,0x0000001cu,0x00050041u,0x0000001bu,0x0000001eu,0x00000012u,0x0000001au,0x0004003du,0x00000006u,0x0000001fu,0x0000001eu,0x000500afu,0x00000019u,0x00000020u,0x0000001du,0x0000001fu,0x000400a8u,0x00000019u,0x00000021u,0x00000020u,0x000300f7u,0x00000023u,0x00000000u,0x000400fau,0x00000021u,0x00000022u,0x00000023u,0x000200f8u,0x00000022u,0x00050041u,0x0000001bu,0x00000025u,0x00000009u,0x00000024u,0x0004003du,0x00000006u,0x00000026u,0x00000025u,0x00050041u,0x0000001bu,0x00000027u,0x00000012u,0x00000024u,0x0004003du,0x00000006u,0x00000028u,0x00000027u,0x000500afu,0x00000019u,0x00000029u,0x00000026u,0x00000028u,0x000200f9u,0x00000023u,0x000200f8u,0x00000023u,0x000700f5u,0x00000019u,0x0000002au,0x00000020u,0x00000005u,0x00000029u,0x00000022u,0x000300f7u,0x0000002cu,0x00000000u,0x000400fau,0x0000002au,0x0000002bu,0x0000002cu,0x000200f8u,0x0000002bu,0x000100fdu,0x000200f8u,0x0000002cu,0x0004003du,0x00000032u,0x00000035u,0x00000034u,0x00040064u,0x00000031u,0x00000037u,0x00000035u,0x0005006Line truncated
@@ -20,10 +20,10 @@ static const uint32_t OF3_GM_PREWARP_SPV[] = {0x07230203u,0x00010300u,0x0008000b
static const size_t OF3_GM_PREWARP_LEN = 706; static const size_t OF3_GM_PREWARP_LEN = 706;
static const uint32_t OF3_FLOWREG_SPV[] = {0x07230203u,0x00010300u,0x0008000bu,0x00000144u,0x00000000u,0x00020011u,0x00000001u,0x00020011u,0x00000032u,0x0006000bu,0x00000001u,0x4c534c47u,0x6474732eu,0x3035342eu,0x00000000u,0x0003000eu,0x00000000u,0x00000001u,0x0006000fu,0x00000005u,0x00000004u,0x6e69616du,0x00000000u,0x00000037u,0x00060010u,0x00000004u,0x00000011u,0x00000010u,0x00000010u,0x00000001u,0x00030003u,0x00000002u,0x000001c2u,0x00040005u,0x00000004u,0x6e69616du,0x00000000u,0x00060005u,0x0000000eu,0x63746566u,0x76285568u,0x763b3269u,0x003b3269u,0x00030005u,0x0000000cu,0x00000070u,0x00030005u,0x0000000du,0x006d6964u,0x00060005u,0x00000013u,0x63746566u,0x76284c68u,0x763b3269u,0x003b3269u,0x00030005u,0x00000011u,0x00000070u,0x00030005u,0x00000012u,0x006d6964u,0x00040005u,0x00000018u,0x6f6c4675u,0x006e4977u,0x00040005u,0x00000026u,0x6d754c75u,0x00000061u,0x00030005u,0x00000034u,0x00646967u,0x00080005u,0x00000037u,0x475f6c67u,0x61626f6cu,0x766e496cu,0x7461636fu,0x496e6f69u,0x00000044u,0x00030005u,0x0000003cu,0x006d6964u,0x00030005u,0x00000055u,0x00007464u,0x00030005u,0x00000056u,0x00000055u,0x00050006u,0x00000056u,0x00000000u,0x61726170u,0x0000736du,0x00030005u,0x00000058u,0x00000000u,0x00040005u,0x0000005cu,0x626d616cu,0x00006164u,0x00050005u,0x0000005fu,0x65676465u,0x68706c41u,0x00000061u,0x00040005u,0x00000063u,0x54737065u,0x00000056u,0x00030005u,0x00000068u,0x00004375u,0x00040005u,0x00000069u,0x61726170u,0x0000006du,0x00040005u,0x0000006bu,0x61726170u,0x0000006du,0x00030005u,0x0000006eu,0x00004c75u,0x00040005u,0x00000073u,0x61726170u,0x0000006du,0x00040005u,0x00000074u,0x61726170u,0x0000006du,0x00030005u,0x00000077u,0x00005275u,0x00040005u,0x0000007bu,0x61726170u,0x0000006du,0x00040005u,0x0000007cu,0x61726170u,0x0000006du,0x00030005u,0x0000007fu,0x00005575u,0x00040005u,0x00000083u,0x61726170u,0x0000006du,0x00040005u,0x00000084u,0x61726170u,0x0000006du,0x00030005u,0x00000087u,0x00004475u,0x00040005u,0x0000008bu,0x61726170u,0x0000006du,0x00040005u,0x0000008cu,0x61726170u,0x0000006du,0x00040005u,0x0000008fu,0x6d69646cu,0x00000000u,0x00030005u,0x00000093u,0x00004c6cu,0x00040005u,0x00000096u,0x61726170u,0x0000006du,0x00040005u,0x00000097u,0x61726170u,0x0000006du,0x00030005u,0x0000009au,0x0000526cu,0x00040005u,0x0000009du,0x61726170u,0x0000006du,0x00040005u,0x0000009eu,0x61726170u,0x0000006du,0x00030005u,0x000000a1u,0x0000556cu,0x00040005u,0x000000a4u,0x61726170u,0x0000006du,0x00040005u,0x000000a5u,0x61726170u,0x0000006du,0x00030005u,0x000000a8u,0x0000446cu,0x00040005u,0x000000abu,0x61726170u,0x0000006du,0x00040005u,0x000000acu,0x61726170u,0x0000006du,0x00040005u,0x000000afu,0x67616d67u,0x00000000u,0x00030005u,0x000000bbu,0x00000067u,0x00030005u,0x000000c4u,0x00004c64u,0x00030005u,0x000000c8u,0x00005264u,0x00030005u,0x000000ccu,0x00005564u,0x00030005u,0x000000d0u,0x00004464u,0x00030005u,0x000000d4u,0x00003265u,0x00030005u,0x000000d8u,0x00004c77u,0x00030005u,0x000000e1u,0x00005277u,0x00030005u,0x000000eau,0x00005577u,0x00030005u,0x000000f3u,0x00004477u,0x00040005u,0x000000fcu,0x576d7573u,0x00000000u,0x00040005u,0x00000104u,0x576d7573u,0x00000055u,0x00040005u,0x00000114u,0x66694475u,0x00000066u,0x00030005u,0x00000120u,0x00003066u,0x00050005u,0x00000121u,0x6f6c4675u,0x73624f77u,0x00000000u,0x00040005u,0x0000012au,0x74656874u,0x00000061u,0x00030005u,0x0000012eu,0x00000072u,0x00040005u,0x00000132u,0x77654e75u,0x00000000u,0x00050005u,0x0000013eu,0x6f6c4675u,0x74754f77u,0x00000000u,0x00040047u,0x00000018u,0x00000021u,0x00000020u,0x00040047u,0x00000018u,0x00000022u,0x00000000u,0x00040047u,0x00000026u,0x00000021u,0x00000022u,0x00040047u,0x00000026u,0x00000022u,0x00000000u,0x00040047u,0x00000037u,0x0000000bu,0x0000001cu,0x00030047u,0x00000056u,0x00000002u,0x00050048u,0x00000056u,0x00000000u,0x00000023u,0x00000000u,0x00040047u,0x00000058u,0x00000021u,0x00000000u,0x00040047u,0x00000058u,0x00000022u,0x00000000u,0x00040047u,0x00000121u,0x00000021u,0x00000021u,0x00040047u,0x00000121u,0x00000022u,0x00000000u,0x00030047u,0x0000013eu,0x00000019u,0x00040047u,0x0000013eu,0x00000021u,0x00000030u,0x00040047u,0x0000013eu,0x00000022u,0x00000000u,0x00040047u,0x00000143u,0x0000000bu,0x00000019u,0x00020013u,0x00000002u,0x00030021u,0x00000003u,0x00000002u,0x00040015u,0x00000006u,0x00000020u,0x00000001u,0x00040017u,0x00000007u,0x00000006u,0x00000002u,0x00040020u,0x00000008u,0x00000007u,0x00000007u,0x00030016u,0x00000009u,0x00000020u,0x00040017u,0x0000000au,0x00000009u,0x00000004u,0x00050021u,0x0000000bu,0x0000000au,0x00000008u,0x00000008u,0x00050021u,0x00000010u,0x00000009u,0x00000008u,0x00000008u,0x00090019u,0x00000015u,0x00000009u,0x00000001u,0x00000000u,0x00000000u,0x00000000u,0x00000001u,0x00000000u,0x0003001bu,0x00000016u,0x00000015u,0x00040020u,0x00000017u,0x00000000u,0x00000016u,0x0004003bu,0x00000017u,0x00000018u,0x00000000u,0x0004002bu,0x00000006u,0x0000001bu,0x00000000u,0x0005002cu,0x00000007u,0x0000001cu,0x0000001bu,0x0000001bu,0x0004002bu,0x00000006u,0x0000001eu,0x00000001u,0x0004003bu,0x00000017u,0x00000026u,0x00000000u,Line truncated static const uint32_t OF3_FLOWREG_SPV[] = {0x07230203u,0x00010300u,0x0008000bu,0x00000144u,0x00000000u,0x00020011u,0x00000001u,0x00020011u,0x00000032u,0x0006000bu,0x00000001u,0x4c534c47u,0x6474732eu,0x3035342eu,0x00000000u,0x0003000eu,0x00000000u,0x00000001u,0x0006000fu,0x00000005u,0x00000004u,0x6e69616du,0x00000000u,0x00000037u,0x00060010u,0x00000004u,0x00000011u,0x00000010u,0x00000010u,0x00000001u,0x00030003u,0x00000002u,0x000001c2u,0x00040005u,0x00000004u,0x6e69616du,0x00000000u,0x00060005u,0x0000000eu,0x63746566u,0x76285568u,0x763b3269u,0x003b3269u,0x00030005u,0x0000000cu,0x00000070u,0x00030005u,0x0000000du,0x006d6964u,0x00060005u,0x00000013u,0x63746566u,0x76284c68u,0x763b3269u,0x003b3269u,0x00030005u,0x00000011u,0x00000070u,0x00030005u,0x00000012u,0x006d6964u,0x00040005u,0x00000018u,0x6f6c4675u,0x006e4977u,0x00040005u,0x00000026u,0x6d754c75u,0x00000061u,0x00030005u,0x00000034u,0x00646967u,0x00080005u,0x00000037u,0x475f6c67u,0x61626f6cu,0x766e496cu,0x7461636fu,0x496e6f69u,0x00000044u,0x00030005u,0x0000003cu,0x006d6964u,0x00030005u,0x00000055u,0x00007464u,0x00030005u,0x00000056u,0x00000055u,0x00050006u,0x00000056u,0x00000000u,0x61726170u,0x0000736du,0x00030005u,0x00000058u,0x00000000u,0x00040005u,0x0000005cu,0x626d616cu,0x00006164u,0x00050005u,0x0000005fu,0x65676465u,0x68706c41u,0x00000061u,0x00040005u,0x00000063u,0x54737065u,0x00000056u,0x00030005u,0x00000068u,0x00004375u,0x00040005u,0x00000069u,0x61726170u,0x0000006du,0x00040005u,0x0000006bu,0x61726170u,0x0000006du,0x00030005u,0x0000006eu,0x00004c75u,0x00040005u,0x00000073u,0x61726170u,0x0000006du,0x00040005u,0x00000074u,0x61726170u,0x0000006du,0x00030005u,0x00000077u,0x00005275u,0x00040005u,0x0000007bu,0x61726170u,0x0000006du,0x00040005u,0x0000007cu,0x61726170u,0x0000006du,0x00030005u,0x0000007fu,0x00005575u,0x00040005u,0x00000083u,0x61726170u,0x0000006du,0x00040005u,0x00000084u,0x61726170u,0x0000006du,0x00030005u,0x00000087u,0x00004475u,0x00040005u,0x0000008bu,0x61726170u,0x0000006du,0x00040005u,0x0000008cu,0x61726170u,0x0000006du,0x00040005u,0x0000008fu,0x6d69646cu,0x00000000u,0x00030005u,0x00000093u,0x00004c6cu,0x00040005u,0x00000096u,0x61726170u,0x0000006du,0x00040005u,0x00000097u,0x61726170u,0x0000006du,0x00030005u,0x0000009au,0x0000526cu,0x00040005u,0x0000009du,0x61726170u,0x0000006du,0x00040005u,0x0000009eu,0x61726170u,0x0000006du,0x00030005u,0x000000a1u,0x0000556cu,0x00040005u,0x000000a4u,0x61726170u,0x0000006du,0x00040005u,0x000000a5u,0x61726170u,0x0000006du,0x00030005u,0x000000a8u,0x0000446cu,0x00040005u,0x000000abu,0x61726170u,0x0000006du,0x00040005u,0x000000acu,0x61726170u,0x0000006du,0x00040005u,0x000000afu,0x67616d67u,0x00000000u,0x00030005u,0x000000bbu,0x00000067u,0x00030005u,0x000000c4u,0x00004c64u,0x00030005u,0x000000c8u,0x00005264u,0x00030005u,0x000000ccu,0x00005564u,0x00030005u,0x000000d0u,0x00004464u,0x00030005u,0x000000d4u,0x00003265u,0x00030005u,0x000000d8u,0x00004c77u,0x00030005u,0x000000e1u,0x00005277u,0x00030005u,0x000000eau,0x00005577u,0x00030005u,0x000000f3u,0x00004477u,0x00040005u,0x000000fcu,0x576d7573u,0x00000000u,0x00040005u,0x00000104u,0x576d7573u,0x00000055u,0x00040005u,0x00000114u,0x66694475u,0x00000066u,0x00030005u,0x00000120u,0x00003066u,0x00050005u,0x00000121u,0x6f6c4675u,0x73624f77u,0x00000000u,0x00040005u,0x0000012au,0x74656874u,0x00000061u,0x00030005u,0x0000012eu,0x00000072u,0x00040005u,0x00000132u,0x77654e75u,0x00000000u,0x00050005u,0x0000013eu,0x6f6c4675u,0x74754f77u,0x00000000u,0x00040047u,0x00000018u,0x00000021u,0x00000020u,0x00040047u,0x00000018u,0x00000022u,0x00000000u,0x00040047u,0x00000026u,0x00000021u,0x00000022u,0x00040047u,0x00000026u,0x00000022u,0x00000000u,0x00040047u,0x00000037u,0x0000000bu,0x0000001cu,0x00030047u,0x00000056u,0x00000002u,0x00050048u,0x00000056u,0x00000000u,0x00000023u,0x00000000u,0x00040047u,0x00000058u,0x00000021u,0x00000000u,0x00040047u,0x00000058u,0x00000022u,0x00000000u,0x00040047u,0x00000121u,0x00000021u,0x00000021u,0x00040047u,0x00000121u,0x00000022u,0x00000000u,0x00030047u,0x0000013eu,0x00000019u,0x00040047u,0x0000013eu,0x00000021u,0x00000030u,0x00040047u,0x0000013eu,0x00000022u,0x00000000u,0x00040047u,0x00000143u,0x0000000bu,0x00000019u,0x00020013u,0x00000002u,0x00030021u,0x00000003u,0x00000002u,0x00040015u,0x00000006u,0x00000020u,0x00000001u,0x00040017u,0x00000007u,0x00000006u,0x00000002u,0x00040020u,0x00000008u,0x00000007u,0x00000007u,0x00030016u,0x00000009u,0x00000020u,0x00040017u,0x0000000au,0x00000009u,0x00000004u,0x00050021u,0x0000000bu,0x0000000au,0x00000008u,0x00000008u,0x00050021u,0x00000010u,0x00000009u,0x00000008u,0x00000008u,0x00090019u,0x00000015u,0x00000009u,0x00000001u,0x00000000u,0x00000000u,0x00000000u,0x00000001u,0x00000000u,0x0003001bu,0x00000016u,0x00000015u,0x00040020u,0x00000017u,0x00000000u,0x00000016u,0x0004003bu,0x00000017u,0x00000018u,0x00000000u,0x0004002bu,0x00000006u,0x0000001bu,0x00000000u,0x0005002cu,0x00000007u,0x0000001cu,0x0000001bu,0x0000001bu,0x0004002bu,0x00000006u,0x0000001eu,0x00000001u,0x0004003bu,0x00000017u,0x00000026u,0x00000000u,Line truncated
static const size_t OF3_FLOWREG_LEN = 1936; static const size_t OF3_FLOWREG_LEN = 1936;
static const uint32_t DDFG_SYNTH_SPV[] = {0x07230203u,0x00010300u,0x0008000bu,0x00000208u,0x00000000u,0x00020011u,0x00000001u,0x00020011u,0x00000032u,0x0006000bu,0x00000001u,0x4c534c47u,0x6474732eu,0x3035342eu,0x00000000u,0x0003000eu,0x00000000u,0x00000001u,0x0006000fu,0x00000005u,0x00000004u,0x6e69616du,0x00000000u,0x0000001cu,0x00060010u,0x00000004u,0x00000011u,0x00000010u,0x00000010u,0x00000001u,0x00030003u,0x00000002u,0x000001c2u,0x00040005u,0x00000004u,0x6e69616du,0x00000000u,0x00050005u,0x0000000bu,0x616d756cu,0x33667628u,0x0000003bu,0x00030005u,0x0000000au,0x00000063u,0x00030005u,0x00000018u,0x00646967u,0x00080005u,0x0000001cu,0x475f6c67u,0x61626f6cu,0x766e496cu,0x7461636fu,0x496e6f69u,0x00000044u,0x00030005u,0x00000021u,0x006d6964u,0x00040005u,0x00000024u,0x74754f75u,0x00000000u,0x00040005u,0x0000003eu,0x44766e69u,0x00006d69u,0x00030005u,0x00000044u,0x00007675u,0x00030005u,0x0000004du,0x00000055u,0x00060006u,0x0000004du,0x00000000u,0x776f6c66u,0x6c616353u,0x00000065u,0x00050006u,0x0000004du,0x00000001u,0x68706c61u,0x00000061u,0x00050006u,0x0000004du,0x00000002u,0x61746562u,0x00000000u,0x00050006u,0x0000004du,0x00000003u,0x626d616cu,0x00006164u,0x00050006u,0x0000004du,0x00000004u,0x69737065u,0x006e6f6cu,0x00060006u,0x0000004du,0x00000005u,0x746f6870u,0x6163536fu,0x0000656cu,0x00050006u,0x0000004du,0x00000006u,0x30646170u,0x00000000u,0x00050006u,0x0000004du,0x00000007u,0x31646170u,0x00000000u,0x00050006u,0x0000004du,0x00000008u,0x52647568u,0x00746365u,0x00030005u,0x0000004fu,0x00000000u,0x00040005u,0x0000008cu,0x72754375u,0x00000072u,0x00030005u,0x00000098u,0x00676264u,0x00030005u,0x0000009fu,0x00007366u,0x00040005u,0x000000a9u,0x64774273u,0x00000000u,0x00050005u,0x000000aau,0x6f6c4675u,0x64774277u,0x00000000u,0x00040005u,0x000000aeu,0x64774673u,0x00000000u,0x00050005u,0x000000afu,0x6f6c4675u,0x64774677u,0x00000000u,0x00030005u,0x000000b3u,0x00313046u,0x00030005u,0x000000bau,0x00303146u,0x00040005u,0x000000c1u,0x31306663u,0x00000000u,0x00040005u,0x000000c5u,0x30316663u,0x00000000u,0x00030005u,0x000000c9u,0x0031306du,0x00030005u,0x000000d5u,0x0030316du,0x00030005u,0x000000e0u,0x00004170u,0x00030005u,0x000000e8u,0x00004270u,0x00030005u,0x000000f0u,0x00003043u,0x00040005u,0x000000f1u,0x65725075u,0x00000076u,0x00030005u,0x000000f6u,0x00003143u,0x00030005u,0x000000fbu,0x00004165u,0x00040005u,0x000000fcu,0x61726170u,0x0000006du,0x00040005u,0x0000010cu,0x61726170u,0x0000006du,0x00030005u,0x00000111u,0x00004265u,0x00040005u,0x00000112u,0x61726170u,0x0000006du,0x00040005u,0x00000122u,0x61726170u,0x0000006du,0x00040005u,0x00000127u,0x76556266u,0x00000000u,0x00040005u,0x0000012bu,0x65526266u,0x00646973u,0x00040005u,0x00000138u,0x736e6f63u,0x00747369u,0x00030005u,0x00000149u,0x0000305au,0x00030005u,0x00000157u,0x0000315au,0x00040005u,0x00000163u,0x30756174u,0x00000000u,0x00040005u,0x00000167u,0x31756174u,0x00000000u,0x00040005u,0x0000016au,0x78616d7au,0x00000000u,0x00030005u,0x0000016eu,0x00003057u,0x00030005u,0x00000179u,0x00003157u,0x00040005u,0x00000183u,0x6d757357u,0x00000000u,0x00040005u,0x00000187u,0x70726177u,0x00006465u,0x00050005u,0x000001a0u,0x736f7263u,0x64616673u,0x00000065u,0x00050005u,0x000001adu,0x746f6870u,0x7272456fu,0x00000000u,0x00050005u,0x000001b1u,0x746f6870u,0x7572546fu,0x00007473u,0x00040005u,0x000001b7u,0x73757274u,0x00000074u,0x00040005u,0x000001c3u,0x76657270u,0x00000043u,0x00040005u,0x000001c8u,0x72727563u,0x00000043u,0x00050005u,0x000001cdu,0x746e6f63u,0x44746e65u,0x00666669u,0x00050005u,0x000001d2u,0x72746e75u,0x65747375u,0x00000064u,0x00040005u,0x000001d7u,0x44676962u,0x00666669u,0x00050005u,0x000001dcu,0x70616e73u,0x75436f54u,0x00007272u,0x00040005u,0x000001e5u,0x6374756fu,0x00000000u,0x00030005u,0x000001eeu,0x0067616du,0x00030005u,0x000001f2u,0x0000006eu,0x00030005u,0x000001f6u,0x00746173u,0x00040047u,0x0000001cu,0x0000000bu,0x0000001cu,0x00030047u,0x00000024u,0x00000019u,0x00040047u,0x00000024u,0x00000021u,0x00000030u,0x00040047u,0x00000024u,0x00000022u,0x00000000u,0x00030047u,0x0000004du,0x00000002u,0x00050048u,0x0000004du,0x00000000u,0x00000023u,0x00000000u,0x00050048u,0x0000004du,0x00000001u,0x00000023u,0x00000004u,0x00050048u,0x0000004du,0x00000002u,0x00000023u,0x00000008u,0x00050048u,0x0000004du,0x00000003u,0x00000023u,0x0000000cu,0x00050048u,0x0000004du,0x00000004u,0x00000023u,0x00000010u,0x00050048u,0x0000004du,0x00000005u,0x00000023u,0x00000014u,0x00050048u,0x0000004du,0x00000006u,0x00000023u,0x00000018u,0x00050048u,0x0000004du,0x00000007u,0x00000023u,0x0000001cu,0x00050048u,0x0000004du,0x00000008u,0x00000023u,0x00000020u,0x00040047u,0x0000004fu,0x00000021u,0x00000000u,0x00040047u,0x0000004fu,0x00000022u,0x00000000u,0x00040047u,0x0000008cu,0x00000021u,0x00000021u,0x00040047u,0x0000008cu,0x00000022u,0x00000000u,0x00040047u,0x000000aau,0x00000021u,0x00000023u,0x00040047u,0x000000aau,0x00000022u,0x00000000u,0x00040047u,0x000000afu,0x00000021u,0x00000022u,0x00040047u,0x000000afu,0x00000022u,0x00000000u,0x00040047u,0x000000f1u,0x00000021u,0x00000020u,0x00040047u,0x000000f1u,0Line truncated static const uint32_t WFG_SYNTH_SPV[] = {0x07230203u,0x00010300u,0x0008000bu,0x00000208u,0x00000000u,0x00020011u,0x00000001u,0x00020011u,0x00000032u,0x0006000bu,0x00000001u,0x4c534c47u,0x6474732eu,0x3035342eu,0x00000000u,0x0003000eu,0x00000000u,0x00000001u,0x0006000fu,0x00000005u,0x00000004u,0x6e69616du,0x00000000u,0x0000001cu,0x00060010u,0x00000004u,0x00000011u,0x00000010u,0x00000010u,0x00000001u,0x00030003u,0x00000002u,0x000001c2u,0x00040005u,0x00000004u,0x6e69616du,0x00000000u,0x00050005u,0x0000000bu,0x616d756cu,0x33667628u,0x0000003bu,0x00030005u,0x0000000au,0x00000063u,0x00030005u,0x00000018u,0x00646967u,0x00080005u,0x0000001cu,0x475f6c67u,0x61626f6cu,0x766e496cu,0x7461636fu,0x496e6f69u,0x00000044u,0x00030005u,0x00000021u,0x006d6964u,0x00040005u,0x00000024u,0x74754f75u,0x00000000u,0x00040005u,0x0000003eu,0x44766e69u,0x00006d69u,0x00030005u,0x00000044u,0x00007675u,0x00030005u,0x0000004du,0x00000055u,0x00060006u,0x0000004du,0x00000000u,0x776f6c66u,0x6c616353u,0x00000065u,0x00050006u,0x0000004du,0x00000001u,0x68706c61u,0x00000061u,0x00050006u,0x0000004du,0x00000002u,0x61746562u,0x00000000u,0x00050006u,0x0000004du,0x00000003u,0x626d616cu,0x00006164u,0x00050006u,0x0000004du,0x00000004u,0x69737065u,0x006e6f6cu,0x00060006u,0x0000004du,0x00000005u,0x746f6870u,0x6163536fu,0x0000656cu,0x00050006u,0x0000004du,0x00000006u,0x30646170u,0x00000000u,0x00050006u,0x0000004du,0x00000007u,0x31646170u,0x00000000u,0x00050006u,0x0000004du,0x00000008u,0x52647568u,0x00746365u,0x00030005u,0x0000004fu,0x00000000u,0x00040005u,0x0000008cu,0x72754375u,0x00000072u,0x00030005u,0x00000098u,0x00676264u,0x00030005u,0x0000009fu,0x00007366u,0x00040005u,0x000000a9u,0x64774273u,0x00000000u,0x00050005u,0x000000aau,0x6f6c4675u,0x64774277u,0x00000000u,0x00040005u,0x000000aeu,0x64774673u,0x00000000u,0x00050005u,0x000000afu,0x6f6c4675u,0x64774677u,0x00000000u,0x00030005u,0x000000b3u,0x00313046u,0x00030005u,0x000000bau,0x00303146u,0x00040005u,0x000000c1u,0x31306663u,0x00000000u,0x00040005u,0x000000c5u,0x30316663u,0x00000000u,0x00030005u,0x000000c9u,0x0031306du,0x00030005u,0x000000d5u,0x0030316du,0x00030005u,0x000000e0u,0x00004170u,0x00030005u,0x000000e8u,0x00004270u,0x00030005u,0x000000f0u,0x00003043u,0x00040005u,0x000000f1u,0x65725075u,0x00000076u,0x00030005u,0x000000f6u,0x00003143u,0x00030005u,0x000000fbu,0x00004165u,0x00040005u,0x000000fcu,0x61726170u,0x0000006du,0x00040005u,0x0000010cu,0x61726170u,0x0000006du,0x00030005u,0x00000111u,0x00004265u,0x00040005u,0x00000112u,0x61726170u,0x0000006du,0x00040005u,0x00000122u,0x61726170u,0x0000006du,0x00040005u,0x00000127u,0x76556266u,0x00000000u,0x00040005u,0x0000012bu,0x65526266u,0x00646973u,0x00040005u,0x00000138u,0x736e6f63u,0x00747369u,0x00030005u,0x00000149u,0x0000305au,0x00030005u,0x00000157u,0x0000315au,0x00040005u,0x00000163u,0x30756174u,0x00000000u,0x00040005u,0x00000167u,0x31756174u,0x00000000u,0x00040005u,0x0000016au,0x78616d7au,0x00000000u,0x00030005u,0x0000016eu,0x00003057u,0x00030005u,0x00000179u,0x00003157u,0x00040005u,0x00000183u,0x6d757357u,0x00000000u,0x00040005u,0x00000187u,0x70726177u,0x00006465u,0x00050005u,0x000001a0u,0x736f7263u,0x64616673u,0x00000065u,0x00050005u,0x000001adu,0x746f6870u,0x7272456fu,0x00000000u,0x00050005u,0x000001b1u,0x746f6870u,0x7572546fu,0x00007473u,0x00040005u,0x000001b7u,0x73757274u,0x00000074u,0x00040005u,0x000001c3u,0x76657270u,0x00000043u,0x00040005u,0x000001c8u,0x72727563u,0x00000043u,0x00050005u,0x000001cdu,0x746e6f63u,0x44746e65u,0x00666669u,0x00050005u,0x000001d2u,0x72746e75u,0x65747375u,0x00000064u,0x00040005u,0x000001d7u,0x44676962u,0x00666669u,0x00050005u,0x000001dcu,0x70616e73u,0x75436f54u,0x00007272u,0x00040005u,0x000001e5u,0x6374756fu,0x00000000u,0x00030005u,0x000001eeu,0x0067616du,0x00030005u,0x000001f2u,0x0000006eu,0x00030005u,0x000001f6u,0x00746173u,0x00040047u,0x0000001cu,0x0000000bu,0x0000001cu,0x00030047u,0x00000024u,0x00000019u,0x00040047u,0x00000024u,0x00000021u,0x00000030u,0x00040047u,0x00000024u,0x00000022u,0x00000000u,0x00030047u,0x0000004du,0x00000002u,0x00050048u,0x0000004du,0x00000000u,0x00000023u,0x00000000u,0x00050048u,0x0000004du,0x00000001u,0x00000023u,0x00000004u,0x00050048u,0x0000004du,0x00000002u,0x00000023u,0x00000008u,0x00050048u,0x0000004du,0x00000003u,0x00000023u,0x0000000cu,0x00050048u,0x0000004du,0x00000004u,0x00000023u,0x00000010u,0x00050048u,0x0000004du,0x00000005u,0x00000023u,0x00000014u,0x00050048u,0x0000004du,0x00000006u,0x00000023u,0x00000018u,0x00050048u,0x0000004du,0x00000007u,0x00000023u,0x0000001cu,0x00050048u,0x0000004du,0x00000008u,0x00000023u,0x00000020u,0x00040047u,0x0000004fu,0x00000021u,0x00000000u,0x00040047u,0x0000004fu,0x00000022u,0x00000000u,0x00040047u,0x0000008cu,0x00000021u,0x00000021u,0x00040047u,0x0000008cu,0x00000022u,0x00000000u,0x00040047u,0x000000aau,0x00000021u,0x00000023u,0x00040047u,0x000000aau,0x00000022u,0x00000000u,0x00040047u,0x000000afu,0x00000021u,0x00000022u,0x00040047u,0x000000afu,0x00000022u,0x00000000u,0x00040047u,0x000000f1u,0x00000021u,0x00000020u,0x00040047u,0x000000f1u,0xLine truncated
static const size_t DDFG_SYNTH_LEN = 3082; static const size_t WFG_SYNTH_LEN = 3082;
struct Blob { const uint32_t* code; size_t words; }; struct Blob { const uint32_t* code; size_t words; };
enum Shader { OF3_LUMA, OF3_DOWNSAMPLE, OF3_FLOW, OF3_EXPAND, OF3_FLOW_M4, OF3_EXPAND_M4, OF3_GM_REDUCE, OF3_GM_PREWARP, OF3_FLOWREG, DDFG_SYNTH, SHADER_COUNT }; enum Shader { OF3_LUMA, OF3_DOWNSAMPLE, OF3_FLOW, OF3_EXPAND, OF3_FLOW_M4, OF3_EXPAND_M4, OF3_GM_REDUCE, OF3_GM_PREWARP, OF3_FLOWREG, WFG_SYNTH, SHADER_COUNT };
static inline Blob blob(Shader s) { static inline Blob blob(Shader s) {
switch (s) { switch (s) {
case OF3_LUMA: return { OF3_LUMA_SPV, OF3_LUMA_LEN }; case OF3_LUMA: return { OF3_LUMA_SPV, OF3_LUMA_LEN };
@@ -35,7 +35,7 @@ static inline Blob blob(Shader s) {
case OF3_GM_REDUCE: return { OF3_GM_REDUCE_SPV, OF3_GM_REDUCE_LEN }; case OF3_GM_REDUCE: return { OF3_GM_REDUCE_SPV, OF3_GM_REDUCE_LEN };
case OF3_GM_PREWARP: return { OF3_GM_PREWARP_SPV, OF3_GM_PREWARP_LEN }; case OF3_GM_PREWARP: return { OF3_GM_PREWARP_SPV, OF3_GM_PREWARP_LEN };
case OF3_FLOWREG: return { OF3_FLOWREG_SPV, OF3_FLOWREG_LEN }; case OF3_FLOWREG: return { OF3_FLOWREG_SPV, OF3_FLOWREG_LEN };
case DDFG_SYNTH: return { DDFG_SYNTH_SPV, DDFG_SYNTH_LEN }; case WFG_SYNTH: return { WFG_SYNTH_SPV, WFG_SYNTH_LEN };
default: return { nullptr, 0 }; default: return { nullptr, 0 };
} }
} }
@@ -4,9 +4,9 @@
#include <cmath> #include <cmath>
#include <cstdio> #include <cstdio>
namespace ddfg { namespace winfg {
#define VKOK(x) do { if ((x) != VK_SUCCESS) { DDFG_LOGE("vk fail: %s", #x); return false; } } while (0) #define VKOK(x) do { if ((x) != VK_SUCCESS) { WFG_LOGE("vk fail: %s", #x); return false; } } while (0)
uint32_t FrameGen::findMemType(uint32_t bits, VkMemoryPropertyFlags props) const { uint32_t FrameGen::findMemType(uint32_t bits, VkMemoryPropertyFlags props) const {
for (uint32_t i = 0; i < memProps_.memoryTypeCount; ++i) for (uint32_t i = 0; i < memProps_.memoryTypeCount; ++i)
@@ -153,9 +153,9 @@ bool FrameGen::init(const DeviceDispatch* dd, const InstanceDispatch* id,
if (!makePipe(pGmReduce_, embedded::OF3_GM_REDUCE, unused)) return false; if (!makePipe(pGmReduce_, embedded::OF3_GM_REDUCE, unused)) return false;
if (!makePipe(pGmPrewarp_, embedded::OF3_GM_PREWARP, unused)) return false; if (!makePipe(pGmPrewarp_, embedded::OF3_GM_PREWARP, unused)) return false;
if (!makePipe(pFlowReg_, embedded::OF3_FLOWREG, unused)) return false; if (!makePipe(pFlowReg_, embedded::OF3_FLOWREG, unused)) return false;
if (!makePipe(pSynth_, embedded::DDFG_SYNTH, unused)) return false; if (!makePipe(pSynth_, embedded::WFG_SYNTH, unused)) return false;
if (!makeGmBuffers()) { DDFG_LOGE("framegen: GM SSBO alloc failed - C1 disabled"); } if (!makeGmBuffers()) { WFG_LOGE("framegen: GM SSBO alloc failed - C1 disabled"); }
DDFG_LOGI("framegen init ok (queueFamily=%u, 10 pipelines, model=%d, C1 gm=%d, C2 flow_reg=%d iters=%d)", WFG_LOGI("framegen init ok (queueFamily=%u, 10 pipelines, model=%d, C1 gm=%d, C2 flow_reg=%d iters=%d)",
queueFamily_, cfg_.model, cfg_.gmMode, cfg_.frMode, cfg_.frIters); queueFamily_, cfg_.model, cfg_.gmMode, cfg_.frMode, cfg_.frIters);
return true; return true;
} }
@@ -194,7 +194,7 @@ bool FrameGen::onResize(VkExtent2D extent, VkFormat , bool force) {
if (!makeImage(flowRegA_, levelExtent(extent, flowFinest_), VK_FORMAT_R16G16B16A16_SFLOAT, regUsage)) return false; if (!makeImage(flowRegA_, levelExtent(extent, flowFinest_), VK_FORMAT_R16G16B16A16_SFLOAT, regUsage)) return false;
if (!makeImage(flowRegB_, levelExtent(extent, flowFinest_), VK_FORMAT_R16G16B16A16_SFLOAT, regUsage)) return false; if (!makeImage(flowRegB_, levelExtent(extent, flowFinest_), VK_FORMAT_R16G16B16A16_SFLOAT, regUsage)) return false;
ready_ = true; ready_ = true;
DDFG_LOGI("framegen resized to %ux%u (%d pyramid levels, kFlowFinest=%d perf_preset=%d)", WFG_LOGI("framegen resized to %ux%u (%d pyramid levels, kFlowFinest=%d perf_preset=%d)",
extent.width, extent.height, kLevels, flowFinest_, cfg_.perfPreset); extent.width, extent.height, kLevels, flowFinest_, cfg_.perfPreset);
return true; return true;
} }
@@ -3,7 +3,7 @@
#include "config.hpp" #include "config.hpp"
#include <vector> #include <vector>
namespace ddfg { namespace winfg {
class FrameGen { class FrameGen {
public: public:
@@ -12,8 +12,7 @@ public:
void configure(const Config& c); void configure(const Config& c);
bool onResize(VkExtent2D extent, VkFormat colorFormat, bool force = false); bool onResize(VkExtent2D extent, VkFormat colorFormat, bool force = false);
void record(VkCommandBuffer cmd, VkImageView prevView, VkImageView currView, void record(VkCommandBuffer cmd, VkImageView prevView, VkImageView currView,
VkImageView outView, float alpha, uint32_t gmSlot = 0, VkImageView outView, float alpha, uint32_t gmSlot = 0);
uint32_t synthSlot = 0, bool reuseFlow = false);
void destroy(); void destroy();
bool valid() const { return device_ != VK_NULL_HANDLE && ready_; } bool valid() const { return device_ != VK_NULL_HANDLE && ready_; }
const Config& config() const { return cfg_; } const Config& config() const { return cfg_; }
@@ -26,7 +25,6 @@ public:
static constexpr int kGmSlots = 3; static constexpr int kGmSlots = 3;
static constexpr int kSynthSlots = 3;
static constexpr int kGmLevel = 3; static constexpr int kGmLevel = 3;
static constexpr int kGmThreads = 512; static constexpr int kGmThreads = 512;
static constexpr int kGmStride = 32; static constexpr int kGmStride = 32;
+12
View File
@@ -0,0 +1,12 @@
#pragma once
#if defined(__ANDROID__)
#include <android/log.h>
#define WFG_LOGI(...) __android_log_print(ANDROID_LOG_INFO, "win-fg", __VA_ARGS__)
#define WFG_LOGE(...) __android_log_print(ANDROID_LOG_ERROR, "win-fg", __VA_ARGS__)
#else
#include <cstdio>
#define WFG_LOGI(...) do { std::fprintf(stderr, "[win-fg] " __VA_ARGS__); std::fprintf(stderr, "\n"); } while(0)
#define WFG_LOGE(...) do { std::fprintf(stderr, "[win-fg][E] " __VA_ARGS__); std::fprintf(stderr, "\n"); } while(0)
#endif
#define WFG_LOGD(cond, ...) do { if (cond) WFG_LOGI(__VA_ARGS__); } while(0)
@@ -1,34 +1,31 @@
namespace { namespace {
struct ScratchState { struct ScratchState {
VkBuffer synthUbo[ddfg::FrameGen::kSynthSlots]{}; VkBuffer synthUbo = VK_NULL_HANDLE; VkDeviceMemory synthUboMem = VK_NULL_HANDLE; void* synthUboPtr = nullptr;
VkDeviceMemory synthUboMem[ddfg::FrameGen::kSynthSlots]{};
void* synthUboPtr[ddfg::FrameGen::kSynthSlots]{};
std::vector<VkBuffer> flowUbo; std::vector<VkDeviceMemory> flowUboMem; std::vector<void*> flowUboPtr; std::vector<VkBuffer> flowUbo; std::vector<VkDeviceMemory> flowUboMem; std::vector<void*> flowUboPtr;
VkBuffer expandUbo = VK_NULL_HANDLE; VkDeviceMemory expandUboMem = VK_NULL_HANDLE; void* expandUboPtr = nullptr; VkBuffer expandUbo = VK_NULL_HANDLE; VkDeviceMemory expandUboMem = VK_NULL_HANDLE; void* expandUboPtr = nullptr;
VkBuffer flowRegUbo = VK_NULL_HANDLE; VkDeviceMemory flowRegUboMem = VK_NULL_HANDLE; void* flowRegUboPtr = nullptr; VkBuffer flowRegUbo = VK_NULL_HANDLE; VkDeviceMemory flowRegUboMem = VK_NULL_HANDLE; void* flowRegUboPtr = nullptr;
VkBuffer gmUbo[ddfg::FrameGen::kGmSlots]{}; VkBuffer gmUbo[winfg::FrameGen::kGmSlots]{};
VkDeviceMemory gmUboMem[ddfg::FrameGen::kGmSlots]{}; VkDeviceMemory gmUboMem[winfg::FrameGen::kGmSlots]{};
void* gmUboPtr[ddfg::FrameGen::kGmSlots]{}; void* gmUboPtr[winfg::FrameGen::kGmSlots]{};
VkDescriptorSet sLumaCurr = VK_NULL_HANDLE, sLumaPrev = VK_NULL_HANDLE; VkDescriptorSet sLumaCurr = VK_NULL_HANDLE, sLumaPrev = VK_NULL_HANDLE;
std::vector<VkDescriptorSet> sDownA, sDownB, sFlow; std::vector<VkDescriptorSet> sDownA, sDownB, sFlow;
VkDescriptorSet sExpand[ddfg::FrameGen::kGmSlots]{}; VkDescriptorSet sExpand[winfg::FrameGen::kGmSlots]{};
VkDescriptorSet sFlowReg0 = VK_NULL_HANDLE, sFlowRegAB = VK_NULL_HANDLE, sFlowRegBA = VK_NULL_HANDLE; VkDescriptorSet sFlowReg0 = VK_NULL_HANDLE, sFlowRegAB = VK_NULL_HANDLE, sFlowRegBA = VK_NULL_HANDLE;
VkDescriptorSet sSynth[ddfg::FrameGen::kSynthSlots]{}; VkDescriptorSet sSynth = VK_NULL_HANDLE;
VkDescriptorSet sGmReduce[ddfg::FrameGen::kGmSlots]{}; VkDescriptorSet sGmReduce[winfg::FrameGen::kGmSlots]{};
std::vector<VkDescriptorSet> sGmPrewarp[ddfg::FrameGen::kGmSlots]; std::vector<VkDescriptorSet> sGmPrewarp[winfg::FrameGen::kGmSlots];
VkExtent2D builtFor{0,0}; VkExtent2D builtFor{0,0};
bool built = false; bool built = false;
bool flowInited = false; bool flowInited = false;
bool flowReady = false;
}; };
ScratchState g_scratch; ScratchState g_scratch;
} }
static bool makeUbo(const ddfg::DeviceDispatch* dd, VkDevice dev, static bool makeUbo(const winfg::DeviceDispatch* dd, VkDevice dev,
const VkPhysicalDeviceMemoryProperties& mp, const VkPhysicalDeviceMemoryProperties& mp,
VkDeviceSize size, VkBuffer& buf, VkDeviceMemory& mem, void*& ptr) { VkDeviceSize size, VkBuffer& buf, VkDeviceMemory& mem, void*& ptr) {
VkBufferCreateInfo bi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; VkBufferCreateInfo bi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
@@ -44,21 +41,21 @@ static bool makeUbo(const ddfg::DeviceDispatch* dd, VkDevice dev,
return dd->MapMemory(dev, mem, 0, size, 0, &ptr) == VK_SUCCESS; return dd->MapMemory(dev, mem, 0, size, 0, &ptr) == VK_SUCCESS;
} }
static VkDescriptorSet allocSet(const ddfg::DeviceDispatch* dd, VkDevice dev, static VkDescriptorSet allocSet(const winfg::DeviceDispatch* dd, VkDevice dev,
VkDescriptorPool pool, VkDescriptorSetLayout layout) { VkDescriptorPool pool, VkDescriptorSetLayout layout) {
VkDescriptorSetAllocateInfo ai{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; VkDescriptorSetAllocateInfo ai{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO};
ai.descriptorPool = pool; ai.descriptorSetCount = 1; ai.pSetLayouts = &layout; ai.descriptorPool = pool; ai.descriptorSetCount = 1; ai.pSetLayouts = &layout;
VkDescriptorSet s = VK_NULL_HANDLE; dd->AllocateDescriptorSets(dev, &ai, &s); return s; VkDescriptorSet s = VK_NULL_HANDLE; dd->AllocateDescriptorSets(dev, &ai, &s); return s;
} }
static void wImg(const ddfg::DeviceDispatch* dd, VkDevice dev, VkDescriptorSet set, uint32_t binding, static void wImg(const winfg::DeviceDispatch* dd, VkDevice dev, VkDescriptorSet set, uint32_t binding,
VkDescriptorType type, VkImageView view, VkSampler samp, VkImageLayout layout) { VkDescriptorType type, VkImageView view, VkSampler samp, VkImageLayout layout) {
VkDescriptorImageInfo ii{}; ii.imageView = view; ii.sampler = samp; ii.imageLayout = layout; VkDescriptorImageInfo ii{}; ii.imageView = view; ii.sampler = samp; ii.imageLayout = layout;
VkWriteDescriptorSet w{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; VkWriteDescriptorSet w{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET};
w.dstSet = set; w.dstBinding = binding; w.descriptorCount = 1; w.descriptorType = type; w.pImageInfo = &ii; w.dstSet = set; w.dstBinding = binding; w.descriptorCount = 1; w.descriptorType = type; w.pImageInfo = &ii;
dd->UpdateDescriptorSets(dev, 1, &w, 0, nullptr); dd->UpdateDescriptorSets(dev, 1, &w, 0, nullptr);
} }
static void wUbo(const ddfg::DeviceDispatch* dd, VkDevice dev, VkDescriptorSet set, uint32_t binding, static void wUbo(const winfg::DeviceDispatch* dd, VkDevice dev, VkDescriptorSet set, uint32_t binding,
VkBuffer buf, VkDeviceSize range) { VkBuffer buf, VkDeviceSize range) {
VkDescriptorBufferInfo bi{}; bi.buffer = buf; bi.range = range; VkDescriptorBufferInfo bi{}; bi.buffer = buf; bi.range = range;
VkWriteDescriptorSet w{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; VkWriteDescriptorSet w{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET};
@@ -66,7 +63,7 @@ static void wUbo(const ddfg::DeviceDispatch* dd, VkDevice dev, VkDescriptorSet s
w.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; w.pBufferInfo = &bi; w.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; w.pBufferInfo = &bi;
dd->UpdateDescriptorSets(dev, 1, &w, 0, nullptr); dd->UpdateDescriptorSets(dev, 1, &w, 0, nullptr);
} }
static void wSsbo(const ddfg::DeviceDispatch* dd, VkDevice dev, VkDescriptorSet set, uint32_t binding, static void wSsbo(const winfg::DeviceDispatch* dd, VkDevice dev, VkDescriptorSet set, uint32_t binding,
VkBuffer buf, VkDeviceSize range) { VkBuffer buf, VkDeviceSize range) {
VkDescriptorBufferInfo bi{}; bi.buffer = buf; bi.range = range; VkDescriptorBufferInfo bi{}; bi.buffer = buf; bi.range = range;
VkWriteDescriptorSet w{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; VkWriteDescriptorSet w{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET};
@@ -120,7 +117,7 @@ static void mulAff(const double A[3][3], const double B[3][3], double out[3][3])
out[2][0]=0.0; out[2][1]=0.0; out[2][2]=1.0; out[2][0]=0.0; out[2][1]=0.0; out[2][2]=1.0;
} }
namespace ddfg { namespace winfg {
static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev, static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
const VkPhysicalDeviceMemoryProperties& mp, VkDescriptorPool pool, const VkPhysicalDeviceMemoryProperties& mp, VkDescriptorPool pool,
@@ -143,7 +140,7 @@ static void destroyScratch(const DeviceDispatch* dd, VkDevice dev, VkDescriptorP
b = VK_NULL_HANDLE; m = VK_NULL_HANDLE; p = nullptr; b = VK_NULL_HANDLE; m = VK_NULL_HANDLE; p = nullptr;
}; };
auto& S = g_scratch; auto& S = g_scratch;
for (int s = 0; s < FrameGen::kSynthSlots; ++s) freeUbo(S.synthUbo[s], S.synthUboMem[s], S.synthUboPtr[s]); freeUbo(S.synthUbo, S.synthUboMem, S.synthUboPtr);
freeUbo(S.expandUbo, S.expandUboMem, S.expandUboPtr); freeUbo(S.expandUbo, S.expandUboMem, S.expandUboPtr);
freeUbo(S.flowRegUbo, S.flowRegUboMem, S.flowRegUboPtr); freeUbo(S.flowRegUbo, S.flowRegUboMem, S.flowRegUboPtr);
for (size_t i = 0; i < S.flowUbo.size(); ++i) freeUbo(S.flowUbo[i], S.flowUboMem[i], S.flowUboPtr[i]); for (size_t i = 0; i < S.flowUbo.size(); ++i) freeUbo(S.flowUbo[i], S.flowUboMem[i], S.flowUboPtr[i]);
@@ -157,7 +154,7 @@ void FrameGen::configure(const Config& c) {
int want = flowFinestForPreset(cfg_.perfPreset); int want = flowFinestForPreset(cfg_.perfPreset);
const int maxFinest = kLevels - 2; const int maxFinest = kLevels - 2;
if (want > maxFinest) { if (want > maxFinest) {
DDFG_LOGE("perf-preset=%d wants kFlowFinest=%d but only %d pyramid levels exist " WFG_LOGE("perf-preset=%d wants kFlowFinest=%d but only %d pyramid levels exist "
"(need >=2 solved) - clamping to %d", cfg_.perfPreset, want, kLevels, maxFinest); "(need >=2 solved) - clamping to %d", cfg_.perfPreset, want, kLevels, maxFinest);
want = maxFinest; want = maxFinest;
} }
@@ -166,7 +163,7 @@ void FrameGen::configure(const Config& c) {
const int prevFinest = flowFinest_; const int prevFinest = flowFinest_;
flowFinest_ = want; flowFinest_ = want;
const bool live = (flowFinest_ != prevFinest) && ready_; const bool live = (flowFinest_ != prevFinest) && ready_;
DDFG_LOGI("perf-preset=%d -> kFlowFinest=%d (was %d) live-rebuild=%d ready=%d", WFG_LOGI("perf-preset=%d -> kFlowFinest=%d (was %d) live-rebuild=%d ready=%d",
cfg_.perfPreset, flowFinest_, prevFinest, live ? 1 : 0, ready_ ? 1 : 0); cfg_.perfPreset, flowFinest_, prevFinest, live ? 1 : 0, ready_ ? 1 : 0);
if (!live) return; if (!live) return;
@@ -177,12 +174,12 @@ void FrameGen::configure(const Config& c) {
dd_->DeviceWaitIdle(device_); dd_->DeviceWaitIdle(device_);
destroyScratch(dd_, device_, descPool_); destroyScratch(dd_, device_, descPool_);
if (!onResize(extent_, VK_FORMAT_UNDEFINED, true)) if (!onResize(extent_, VK_FORMAT_UNDEFINED, true))
DDFG_LOGE("perf-preset live rebuild: onResize FAILED at %ux%u - FG disabled until next resize", WFG_LOGE("perf-preset live rebuild: onResize FAILED at %ux%u - FG disabled until next resize",
extent_.width, extent_.height); extent_.width, extent_.height);
for (int i = 0; i < 6; ++i) gmRun_[i] = 0.0; for (int i = 0; i < 6; ++i) gmRun_[i] = 0.0;
for (int s = 0; s < kGmSlots; ++s) { gmSlotValid_[s] = false; for (int i = 0; i < 6; ++i) gmLinAt_[s][i] = 0.0; } for (int s = 0; s < kGmSlots; ++s) { gmSlotValid_[s] = false; for (int i = 0; i < 6; ++i) gmLinAt_[s][i] = 0.0; }
gmHaveEst_ = false; gmEngaged_ = false; gmStableCount_ = 0; gmLastTransPx_ = 0.0f; gmHaveEst_ = false; gmEngaged_ = false; gmStableCount_ = 0; gmLastTransPx_ = 0.0f;
DDFG_LOGI("perf-preset live rebuild DONE (kFlowFinest=%d, flow predictor reset)", flowFinest_); WFG_LOGI("perf-preset live rebuild DONE (kFlowFinest=%d, flow predictor reset)", flowFinest_);
} }
bool FrameGen::updateGlobalMotion(uint32_t gmSlot, VkExtent2D fullExtent) { bool FrameGen::updateGlobalMotion(uint32_t gmSlot, VkExtent2D fullExtent) {
@@ -252,10 +249,9 @@ bool FrameGen::updateGlobalMotion(uint32_t gmSlot, VkExtent2D fullExtent) {
} }
void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView currView, void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView currView,
VkImageView outView, float alpha, uint32_t gmSlot, uint32_t synthSlot, bool reuseFlow) { VkImageView outView, float alpha, uint32_t gmSlot) {
if (!valid()) return; if (!valid()) return;
if (gmSlot >= (uint32_t)kGmSlots) gmSlot = 0; if (gmSlot >= (uint32_t)kGmSlots) gmSlot = 0;
if (synthSlot >= (uint32_t)kSynthSlots) synthSlot = 0;
const bool m4 = (cfg_.model == 4); const bool m4 = (cfg_.model == 4);
const Pipe& flowP = m4 ? pFlowM4_ : pFlow_; const Pipe& flowP = m4 ? pFlowM4_ : pFlow_;
const Pipe& expandP = m4 ? pExpandM4_ : pExpand_; const Pipe& expandP = m4 ? pExpandM4_ : pExpand_;
@@ -267,42 +263,35 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur
pFlowReg_, flowRegA_, flowRegB_, gmSsbo_, kLevels, cfg_); pFlowReg_, flowRegA_, flowRegB_, gmSsbo_, kLevels, cfg_);
} }
// Every generation of one real frame is recorded into the same command buffer, so the flow bool gmEngaged = updateGlobalMotion(gmSlot, extent_);
// between prev and curr is computed once and each generation gets its own synth UBO and set. if (g_scratch.gmUboPtr[gmSlot]) {
if (reuseFlow && !g_scratch.flowReady) return; GMUBO g{};
if (!reuseFlow) { g.lin[0]=(float)gmRun_[0]; g.lin[1]=(float)gmRun_[1]; g.lin[2]=(float)gmRun_[2]; g.lin[3]=(float)gmRun_[3];
bool gmEngaged = updateGlobalMotion(gmSlot, extent_); g.linT[0]=(float)gmRun_[4]; g.linT[1]=(float)gmRun_[5]; g.linT[2]=gmEngaged?1.0f:0.0f; g.linT[3]=0.0f;
if (g_scratch.gmUboPtr[gmSlot]) { if (gmEngaged) {
GMUBO g{}; g.app[0]=(float)gmRun_[0]; g.app[1]=(float)gmRun_[1]; g.app[2]=(float)gmRun_[2]; g.app[3]=(float)gmRun_[3];
g.lin[0]=(float)gmRun_[0]; g.lin[1]=(float)gmRun_[1]; g.lin[2]=(float)gmRun_[2]; g.lin[3]=(float)gmRun_[3]; g.appT[0]=(float)gmRun_[4]; g.appT[1]=(float)gmRun_[5];
g.linT[0]=(float)gmRun_[4]; g.linT[1]=(float)gmRun_[5]; g.linT[2]=gmEngaged?1.0f:0.0f; g.linT[3]=0.0f;
if (gmEngaged) {
g.app[0]=(float)gmRun_[0]; g.app[1]=(float)gmRun_[1]; g.app[2]=(float)gmRun_[2]; g.app[3]=(float)gmRun_[3];
g.appT[0]=(float)gmRun_[4]; g.appT[1]=(float)gmRun_[5];
}
std::memcpy(g_scratch.gmUboPtr[gmSlot], &g, sizeof(g));
} }
{ std::memcpy(g_scratch.gmUboPtr[gmSlot], &g, sizeof(g));
static int lastEng = -1; }
if (gmEngaged != (lastEng == 1) || (gmFrames_ % 300ull) == 0) { {
DDFG_LOGI("C1 global-motion: engaged=%d mode=%d stable=%d transPx=%.1f (model=%d)", static int lastEng = -1;
gmEngaged ? 1 : 0, cfg_.gmMode, gmStableCount_, gmLastTransPx_, cfg_.model); if (gmEngaged != (lastEng == 1) || (gmFrames_ % 300ull) == 0) {
lastEng = gmEngaged ? 1 : 0; WFG_LOGI("C1 global-motion: engaged=%d mode=%d stable=%d transPx=%.1f (model=%d)",
} gmEngaged ? 1 : 0, cfg_.gmMode, gmStableCount_, gmLastTransPx_, cfg_.model);
lastEng = gmEngaged ? 1 : 0;
} }
wImg(dd_, device_, g_scratch.sLumaCurr, 32, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, currView, linear_, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
wImg(dd_, device_, g_scratch.sLumaPrev, 32, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, prevView, linear_, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
} }
SynthUBO su{cfg_.flowScale, alpha, cfg_.beta, cfg_.lambda, cfg_.epsilon, cfg_.photoScale, 0, 0, SynthUBO su{cfg_.flowScale, alpha, cfg_.beta, cfg_.lambda, cfg_.epsilon, cfg_.photoScale, 0, 0,
cfg_.hudX0, cfg_.hudY0, cfg_.hudX1, cfg_.hudY1}; cfg_.hudX0, cfg_.hudY0, cfg_.hudX1, cfg_.hudY1};
if (g_scratch.synthUboPtr[synthSlot]) std::memcpy(g_scratch.synthUboPtr[synthSlot], &su, sizeof(su)); if (g_scratch.synthUboPtr) std::memcpy(g_scratch.synthUboPtr, &su, sizeof(su));
const VkDescriptorSet synthSet = g_scratch.sSynth[synthSlot]; wImg(dd_, device_, g_scratch.sLumaCurr, 32, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, currView, linear_, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
wImg(dd_, device_, synthSet, 32, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, prevView, linear_, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); wImg(dd_, device_, g_scratch.sLumaPrev, 32, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, prevView, linear_, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
wImg(dd_, device_, synthSet, 33, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, currView, linear_, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); wImg(dd_, device_, g_scratch.sSynth, 32, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, prevView, linear_, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
wImg(dd_, device_, synthSet, 48, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, outView, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL); wImg(dd_, device_, g_scratch.sSynth, 33, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, currView, linear_, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
wImg(dd_, device_, g_scratch.sSynth, 48, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, outView, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL);
auto disp = [&](const Pipe& p, VkDescriptorSet set, VkExtent2D e) { auto disp = [&](const Pipe& p, VkDescriptorSet set, VkExtent2D e) {
dd_->CmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, p.pipeline); dd_->CmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, p.pipeline);
@@ -311,109 +300,106 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur
}; };
auto bar = [&](FrameGen::Img& i){ barrier(cmd, i.image, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL); }; auto bar = [&](FrameGen::Img& i){ barrier(cmd, i.image, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL); };
if (!reuseFlow) { for (auto& i : pyrA_) barrier(cmd, i.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
for (auto& i : pyrA_) barrier(cmd, i.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL); for (auto& i : pyrB_) barrier(cmd, i.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
for (auto& i : pyrB_) barrier(cmd, i.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL); for (int l = flowFinest_; l < kLevels; ++l) barrier(cmd, pyrAs_[l].image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
for (int l = flowFinest_; l < kLevels; ++l) barrier(cmd, pyrAs_[l].image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL); barrier(cmd, flowExpA_.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
barrier(cmd, flowExpA_.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL); barrier(cmd, flowExpB_.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
barrier(cmd, flowExpB_.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL); barrier(cmd, flowRegA_.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
barrier(cmd, flowRegA_.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL); barrier(cmd, flowRegB_.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
barrier(cmd, flowRegB_.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL); {
{ VkClearColorValue zero{};
VkClearColorValue zero{}; VkImageSubresourceRange rng{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
VkImageSubresourceRange rng{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
for (int l = flowFinest_; l < kLevels; ++l) {
VkImageMemoryBarrier b{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
b.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; b.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
b.srcAccessMask = 0; b.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
b.image = flowLvl_[l].image; b.subresourceRange = rng;
b.srcQueueFamilyIndex = b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
dd_->CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &b);
dd_->CmdClearColorImage(cmd, flowLvl_[l].image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &zero, 1, &rng);
b.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; b.newLayout = VK_IMAGE_LAYOUT_GENERAL;
b.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; b.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
dd_->CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &b);
}
}
disp(pLuma_, g_scratch.sLumaCurr, levelExtent(extent_, 0));
disp(pLuma_, g_scratch.sLumaPrev, levelExtent(extent_, 0));
bar(pyrA_[0]); bar(pyrB_[0]);
for (int l = 1; l < kLevels; ++l) {
disp(pDown_, g_scratch.sDownA[l - 1], levelExtent(extent_, l));
disp(pDown_, g_scratch.sDownB[l - 1], levelExtent(extent_, l));
bar(pyrA_[l]); bar(pyrB_[l]);
}
if (gmBuffersReady_ && g_scratch.sGmReduce[gmSlot]) {
dd_->CmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pGmReduce_.pipeline);
dd_->CmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pGmReduce_.layout, 0, 1, &g_scratch.sGmReduce[gmSlot], 0, nullptr);
dd_->CmdDispatch(cmd, (uint32_t)(kGmThreads / 64), 1, 1);
VkMemoryBarrier mb{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
mb.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; mb.dstAccessMask = VK_ACCESS_HOST_READ_BIT;
dd_->CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_HOST_BIT,
0, 1, &mb, 0, nullptr, 0, nullptr);
}
for (int l = flowFinest_; l < kLevels; ++l) { for (int l = flowFinest_; l < kLevels; ++l) {
disp(pGmPrewarp_, g_scratch.sGmPrewarp[gmSlot][l], levelExtent(extent_, l)); VkImageMemoryBarrier b{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
bar(pyrAs_[l]); b.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; b.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
b.srcAccessMask = 0; b.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
b.image = flowLvl_[l].image; b.subresourceRange = rng;
b.srcQueueFamilyIndex = b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
dd_->CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &b);
dd_->CmdClearColorImage(cmd, flowLvl_[l].image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &zero, 1, &rng);
b.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; b.newLayout = VK_IMAGE_LAYOUT_GENERAL;
b.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; b.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
dd_->CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &b);
} }
for (int l = kLevels - 1; l >= flowFinest_; --l) {
disp(flowP, g_scratch.sFlow[l], levelExtent(extent_, l));
bar(flowLvl_[l]);
}
const bool frEngaged = (cfg_.frMode != 2) && (cfg_.frIters > 0);
if (frEngaged) {
const int F = flowFinest_;
const VkExtent2D fe = levelExtent(extent_, F);
if (g_scratch.flowRegUboPtr) {
FlowRegUBO fu{cfg_.frDt, cfg_.frLambda, cfg_.frEdge, cfg_.frEps};
std::memcpy(g_scratch.flowRegUboPtr, &fu, sizeof(fu));
}
FrameGen::Img* last = nullptr;
for (int it = 0; it < cfg_.frIters; ++it) {
VkDescriptorSet set; FrameGen::Img* outImg;
if (it == 0) { set = g_scratch.sFlowReg0; outImg = &flowRegA_; }
else if (it % 2 == 1) { set = g_scratch.sFlowRegAB; outImg = &flowRegB_; }
else { set = g_scratch.sFlowRegBA; outImg = &flowRegA_; }
dd_->CmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pFlowReg_.pipeline);
dd_->CmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pFlowReg_.layout, 0, 1, &set, 0, nullptr);
dd_->CmdDispatch(cmd, (fe.width + 15) / 16, (fe.height + 15) / 16, 1);
bar(*outImg);
last = outImg;
}
VkMemoryBarrier mb{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
mb.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
mb.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT;
dd_->CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
0, 1, &mb, 0, nullptr, 0, nullptr);
VkImageCopy region{};
region.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
region.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
region.extent = {fe.width, fe.height, 1};
dd_->CmdCopyImage(cmd, last->image, VK_IMAGE_LAYOUT_GENERAL,
flowLvl_[F].image, VK_IMAGE_LAYOUT_GENERAL, 1, &region);
VkMemoryBarrier mb2{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
mb2.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
mb2.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
dd_->CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
0, 1, &mb2, 0, nullptr, 0, nullptr);
}
{
static int lastFr = -1;
int fe = frEngaged ? 1 : 0;
if (fe != lastFr || (gmFrames_ % 300ull) == 0) {
DDFG_LOGI("C2 flow-reg: engaged=%d mode=%d iters=%d lambda=%.2f dt=%.2f edge=%.1f eps=%.3f (model=%d)",
fe, cfg_.frMode, cfg_.frIters, cfg_.frLambda, cfg_.frDt, cfg_.frEdge, cfg_.frEps, cfg_.model);
lastFr = fe;
}
}
disp(expandP, g_scratch.sExpand[gmSlot], levelExtent(extent_, 0));
bar(flowExpA_); bar(flowExpB_);
g_scratch.flowReady = true;
} }
disp(pSynth_, synthSet, levelExtent(extent_, 0));
disp(pLuma_, g_scratch.sLumaCurr, levelExtent(extent_, 0));
disp(pLuma_, g_scratch.sLumaPrev, levelExtent(extent_, 0));
bar(pyrA_[0]); bar(pyrB_[0]);
for (int l = 1; l < kLevels; ++l) {
disp(pDown_, g_scratch.sDownA[l - 1], levelExtent(extent_, l));
disp(pDown_, g_scratch.sDownB[l - 1], levelExtent(extent_, l));
bar(pyrA_[l]); bar(pyrB_[l]);
}
if (gmBuffersReady_ && g_scratch.sGmReduce[gmSlot]) {
dd_->CmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pGmReduce_.pipeline);
dd_->CmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pGmReduce_.layout, 0, 1, &g_scratch.sGmReduce[gmSlot], 0, nullptr);
dd_->CmdDispatch(cmd, (uint32_t)(kGmThreads / 64), 1, 1);
VkMemoryBarrier mb{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
mb.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; mb.dstAccessMask = VK_ACCESS_HOST_READ_BIT;
dd_->CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_HOST_BIT,
0, 1, &mb, 0, nullptr, 0, nullptr);
}
for (int l = flowFinest_; l < kLevels; ++l) {
disp(pGmPrewarp_, g_scratch.sGmPrewarp[gmSlot][l], levelExtent(extent_, l));
bar(pyrAs_[l]);
}
for (int l = kLevels - 1; l >= flowFinest_; --l) {
disp(flowP, g_scratch.sFlow[l], levelExtent(extent_, l));
bar(flowLvl_[l]);
}
const bool frEngaged = (cfg_.frMode != 2) && (cfg_.frIters > 0);
if (frEngaged) {
const int F = flowFinest_;
const VkExtent2D fe = levelExtent(extent_, F);
if (g_scratch.flowRegUboPtr) {
FlowRegUBO fu{cfg_.frDt, cfg_.frLambda, cfg_.frEdge, cfg_.frEps};
std::memcpy(g_scratch.flowRegUboPtr, &fu, sizeof(fu));
}
FrameGen::Img* last = nullptr;
for (int it = 0; it < cfg_.frIters; ++it) {
VkDescriptorSet set; FrameGen::Img* outImg;
if (it == 0) { set = g_scratch.sFlowReg0; outImg = &flowRegA_; }
else if (it % 2 == 1) { set = g_scratch.sFlowRegAB; outImg = &flowRegB_; }
else { set = g_scratch.sFlowRegBA; outImg = &flowRegA_; }
dd_->CmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pFlowReg_.pipeline);
dd_->CmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pFlowReg_.layout, 0, 1, &set, 0, nullptr);
dd_->CmdDispatch(cmd, (fe.width + 15) / 16, (fe.height + 15) / 16, 1);
bar(*outImg);
last = outImg;
}
VkMemoryBarrier mb{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
mb.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
mb.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT;
dd_->CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
0, 1, &mb, 0, nullptr, 0, nullptr);
VkImageCopy region{};
region.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
region.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
region.extent = {fe.width, fe.height, 1};
dd_->CmdCopyImage(cmd, last->image, VK_IMAGE_LAYOUT_GENERAL,
flowLvl_[F].image, VK_IMAGE_LAYOUT_GENERAL, 1, &region);
VkMemoryBarrier mb2{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
mb2.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
mb2.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
dd_->CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
0, 1, &mb2, 0, nullptr, 0, nullptr);
}
{
static int lastFr = -1;
int fe = frEngaged ? 1 : 0;
if (fe != lastFr || (gmFrames_ % 300ull) == 0) {
WFG_LOGI("C2 flow-reg: engaged=%d mode=%d iters=%d lambda=%.2f dt=%.2f edge=%.1f eps=%.3f (model=%d)",
fe, cfg_.frMode, cfg_.frIters, cfg_.frLambda, cfg_.frDt, cfg_.frEdge, cfg_.frEps, cfg_.model);
lastFr = fe;
}
}
disp(expandP, g_scratch.sExpand[gmSlot], levelExtent(extent_, 0));
bar(flowExpA_); bar(flowExpB_);
disp(pSynth_, g_scratch.sSynth, levelExtent(extent_, 0));
} }
static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev, static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
@@ -432,8 +418,7 @@ static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
S = ScratchState{}; S = ScratchState{};
const auto GEN = VK_IMAGE_LAYOUT_GENERAL; const auto GEN = VK_IMAGE_LAYOUT_GENERAL;
for (int s = 0; s < FrameGen::kSynthSlots; ++s) makeUbo(dd, dev, mp, sizeof(SynthUBO), S.synthUbo, S.synthUboMem, S.synthUboPtr);
makeUbo(dd, dev, mp, sizeof(SynthUBO), S.synthUbo[s], S.synthUboMem[s], S.synthUboPtr[s]);
makeUbo(dd, dev, mp, sizeof(FlowUBO), S.expandUbo, S.expandUboMem, S.expandUboPtr); makeUbo(dd, dev, mp, sizeof(FlowUBO), S.expandUbo, S.expandUboMem, S.expandUboPtr);
if (S.expandUboPtr) { FlowUBO u{cfg.flowScale, 0, 0.6f, 1.6f}; std::memcpy(S.expandUboPtr, &u, sizeof(u)); } if (S.expandUboPtr) { FlowUBO u{cfg.flowScale, 0, 0.6f, 1.6f}; std::memcpy(S.expandUboPtr, &u, sizeof(u)); }
makeUbo(dd, dev, mp, sizeof(FlowRegUBO), S.flowRegUbo, S.flowRegUboMem, S.flowRegUboPtr); makeUbo(dd, dev, mp, sizeof(FlowRegUBO), S.flowRegUbo, S.flowRegUboMem, S.flowRegUboPtr);
@@ -524,12 +509,10 @@ static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
wImg(dd, dev, S.sFlowRegBA, 48, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, flowRegA.view, VK_NULL_HANDLE, GEN); wImg(dd, dev, S.sFlowRegBA, 48, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, flowRegA.view, VK_NULL_HANDLE, GEN);
} }
for (int s = 0; s < FrameGen::kSynthSlots; ++s) { S.sSynth = allocSet(dd, dev, pool, pSynth.setLayout);
S.sSynth[s] = allocSet(dd, dev, pool, pSynth.setLayout); wUbo(dd, dev, S.sSynth, 0, S.synthUbo, sizeof(SynthUBO));
wUbo(dd, dev, S.sSynth[s], 0, S.synthUbo[s], sizeof(SynthUBO)); wImg(dd, dev, S.sSynth, 34, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, expA.view, samp, GEN);
wImg(dd, dev, S.sSynth[s], 34, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, expA.view, samp, GEN); wImg(dd, dev, S.sSynth, 35, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, expB.view, samp, GEN);
wImg(dd, dev, S.sSynth[s], 35, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, expB.view, samp, GEN);
}
S.builtFor = ext; S.built = true; S.builtFor = ext; S.built = true;
return true; return true;
@@ -3,7 +3,7 @@
#include <vulkan/vk_layer.h> #include <vulkan/vk_layer.h>
#include <cstring> #include <cstring>
namespace ddfg { namespace winfg {
static inline void* dispatch_key(void* handle) { return *reinterpret_cast<void**>(handle); } static inline void* dispatch_key(void* handle) { return *reinterpret_cast<void**>(handle); }
@@ -1,10 +1,10 @@
#include "ddfg_engine.h" #include "winfg_engine.h"
#include "ddfg_vkd.h" #include "winfg_vkd.h"
#include "log.hpp" #include "log.hpp"
#include <algorithm> #include <algorithm>
#include <cstring> #include <cstring>
namespace ddfg { namespace winfg {
namespace { namespace {
float alphaFor(uint32_t k, uint32_t n) { float alphaFor(uint32_t k, uint32_t n) {
@@ -31,18 +31,18 @@ Engine::~Engine() { destroyRing(); fg_.destroy(); }
bool Engine::init(const VkTable& table, VkPhysicalDevice phys, VkDevice dev, bool Engine::init(const VkTable& table, VkPhysicalDevice phys, VkDevice dev,
uint32_t queueFamily, VkQueue queue) { uint32_t queueFamily, VkQueue queue) {
if (!ddfgVkdInit(table, dd_, id_)) { if (!winfgVkdInit(table, dd_, id_)) {
DDFG_LOGE("native: dispatch incomplete; frame generation unavailable"); WFG_LOGE("native: dispatch incomplete; frame generation unavailable");
return false; return false;
} }
phys_ = phys; dev_ = dev; qf_ = queueFamily; queue_ = queue; phys_ = phys; dev_ = dev; qf_ = queueFamily; queue_ = queue;
id_.GetPhysicalDeviceMemoryProperties(phys_, &memProps_); id_.GetPhysicalDeviceMemoryProperties(phys_, &memProps_);
if (!fg_.init(&dd_, &id_, phys_, dev_, qf_, queue_)) { if (!fg_.init(&dd_, &id_, phys_, dev_, qf_, queue_)) {
DDFG_LOGE("native: FrameGen::init failed"); WFG_LOGE("native: FrameGen::init failed");
unavailable_ = true; unavailable_ = true;
return false; return false;
} }
DDFG_LOGI("native: chain ready (10 pipelines, embedded shaders)"); WFG_LOGI("native: chain ready (10 pipelines, embedded shaders)");
return true; return true;
} }
@@ -61,7 +61,7 @@ bool Engine::prepare(uint32_t w, uint32_t h, VkFormat fmt) {
if (!fg_.onResize(VkExtent2D{w, h}, fmt, false)) { if (!fg_.onResize(VkExtent2D{w, h}, fmt, false)) {
DDFG_LOGE("native: onResize %ux%u failed; frame generation unavailable", w, h); WFG_LOGE("native: onResize %ux%u failed; frame generation unavailable", w, h);
unavailable_ = true; unavailable_ = true;
return false; return false;
} }
@@ -71,13 +71,11 @@ bool Engine::prepare(uint32_t w, uint32_t h, VkFormat fmt) {
} }
builtW_ = w; builtH_ = h; builtFmt_ = fmt; builtW_ = w; builtH_ = h; builtFmt_ = fmt;
history_ = 0; curr_ = 0; frames_ = 0; history_ = 0; curr_ = 0; frames_ = 0;
DDFG_LOGI("native: built %ux%u fmt=%d model=%d preset=%d flow=%.2f", WFG_LOGI("native: built %ux%u fmt=%d model=%d preset=%d flow=%.2f",
w, h, (int)fmt, cfg_.model, cfg_.perfPreset, (double)cfg_.flowScale); w, h, (int)fmt, cfg_.model, cfg_.perfPreset, (double)cfg_.flowScale);
return true; return true;
} }
static_assert(kMaxGenerations <= (uint32_t)FrameGen::kSynthSlots, "each generation needs its own synth slot");
uint32_t Engine::plan(uint32_t capacity) const { uint32_t Engine::plan(uint32_t capacity) const {
if (!valid() || history_ < 2) return 0; if (!valid() || history_ < 2) return 0;
const uint32_t want = (uint32_t)std::max(cfg_.multiplier - 1, 0); const uint32_t want = (uint32_t)std::max(cfg_.multiplier - 1, 0);
@@ -133,8 +131,7 @@ void Engine::generateInto(VkCommandBuffer cmd, uint32_t generation, uint32_t cou
dd_.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, dd_.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &toWrite); VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &toWrite);
fg_.record(cmd, prev.view, curr.view, targetView, alphaFor(generation, count), gmSlot_, fg_.record(cmd, prev.view, curr.view, targetView, alphaFor(generation, count), gmSlot_);
generation, generation > 0);
if (generation + 1 == count) gmSlot_ = (gmSlot_ + 1) % (uint32_t)FrameGen::kGmSlots; if (generation + 1 == count) gmSlot_ = (gmSlot_ + 1) % (uint32_t)FrameGen::kGmSlots;
(void)w; (void)h; (void)w; (void)h;
@@ -6,7 +6,7 @@
struct VkTable; struct VkTable;
namespace ddfg { namespace winfg {
constexpr uint32_t kMaxGenerations = 3; constexpr uint32_t kMaxGenerations = 3;
@@ -1,14 +1,14 @@
#include "ddfg_vkd.h" #include "winfg_vkd.h"
#include "../VulkanRendererContext.h" #include "../VulkanRendererContext.h"
#include <android/log.h> #include <android/log.h>
bool ddfgVkdInit(const VkTable& table, ddfg::DeviceDispatch& dd, ddfg::InstanceDispatch& id) { bool winfgVkdInit(const VkTable& table, winfg::DeviceDispatch& dd, winfg::InstanceDispatch& id) {
bool ok = true; bool ok = true;
#define COPY(dst, fn) \ #define COPY(dst, fn) \
do { \ do { \
dst.fn = table.fn; \ dst.fn = table.fn; \
if (!dst.fn) { \ if (!dst.fn) { \
__android_log_print(ANDROID_LOG_ERROR, "DdFgVkd", \ __android_log_print(ANDROID_LOG_ERROR, "WinFgVkd", \
"entry point vk" #fn " did not resolve"); \ "entry point vk" #fn " did not resolve"); \
ok = false; \ ok = false; \
} \ } \
@@ -0,0 +1,4 @@
#pragma once
#include "vk_dispatch.hpp"
struct VkTable;
bool winfgVkdInit(const VkTable& table, winfg::DeviceDispatch& dd, winfg::InstanceDispatch& id);
-10
View File
@@ -1,8 +1,5 @@
#include <errno.h>
#include <jni.h> #include <jni.h>
#include <stdatomic.h> #include <stdatomic.h>
#include <sys/syscall.h>
#include <unistd.h>
JNIEXPORT void JNICALL JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_input_FakeInputWriter_nativeStoreFence(JNIEnv *env, jclass clazz) { Java_com_droiddeck_launcher_input_FakeInputWriter_nativeStoreFence(JNIEnv *env, jclass clazz) {
@@ -10,10 +7,3 @@ Java_com_droiddeck_launcher_input_FakeInputWriter_nativeStoreFence(JNIEnv *env,
(void)clazz; (void)clazz;
atomic_thread_fence(memory_order_release); atomic_thread_fence(memory_order_release);
} }
JNIEXPORT jint JNICALL
Java_com_droiddeck_launcher_session_ThreadSignals_tgkill(JNIEnv *env, jclass clazz, jint tgid, jint tid, jint signal) {
(void)env;
(void)clazz;
return syscall(SYS_tgkill, tgid, tid, signal) == 0 ? 0 : errno;
}
-11
View File
@@ -1,11 +0,0 @@
#pragma once
#include <cstddef>
#include <cstdint>
inline std::size_t mjpeg_payload_size(const uint8_t* bytes, std::size_t size) {
if (!bytes || size < 4 || size > 4*1024*1024 || bytes[0] != 0xff || bytes[1] != 0xd8) return 0;
std::size_t end = size;
// Luma Ultra UVC frames can pad the JPEG to an eight-byte boundary with zeros.
while (end > 4 && size-end < 7 && bytes[end-1] == 0) --end;
return bytes[end-2] == 0xff && bytes[end-1] == 0xd9 ? end : 0;
}
+2 -250
View File
@@ -2,32 +2,17 @@
#include <android/log.h> #include <android/log.h>
#include <algorithm> #include <algorithm>
#include <array> #include <array>
#include <vector>
#include <deque>
#include <cmath>
#include <cstring>
#include <cstdint> #include <cstdint>
#include <memory> #include <memory>
#include <mutex> #include <mutex>
#include <condition_variable>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cerrno>
#include <string>
#include <unistd.h>
#include <sys/ioctl.h>
#include <linux/usbdevice_fs.h>
#include <time.h> #include <time.h>
#include "viture_glasses_provider.h" #include "viture_glasses_provider.h"
#include "viture_device.h" #include "viture_device.h"
#include "viture_device_carina.h" #include "viture_device_carina.h"
#include "viture_camera_provider.h"
#include "viture_protocol_public.h" #include "viture_protocol_public.h"
#include "viture_result.h" #include "viture_result.h"
#include "viture_version.h" #include "viture_version.h"
#include "display_modes.h" #include "display_modes.h"
#include "stereo_frame_gate.h"
namespace { namespace {
// SDK callbacks have no user-data parameter. Only one provider may exist at a time. // SDK callbacks have no user-data parameter. Only one provider may exist at a time.
@@ -74,61 +59,6 @@ void clear_pose(bool accept) {
latest_time = 0; latest_time = 0;
} }
int64_t monotonic_ns() {
timespec ts{}; clock_gettime(CLOCK_MONOTONIC, &ts);
return int64_t(ts.tv_sec) * 1000000000LL + ts.tv_nsec;
}
struct CameraPose { double time; std::array<float, 7> pose; };
std::mutex camera_mutex;
std::deque<CameraPose> camera_poses;
std::vector<uint8_t> camera_left, camera_right;
bool camera_accepting = false, camera_wanted = false;
int camera_width = 0, camera_height = 0;
uint64_t camera_sequence = 0, camera_consumed = 0;
StereoFrameGate camera_gate;
uint64_t camera_input_sequence = 0;
int64_t camera_receipt = 0;
int64_t camera_pose_receipt = 0;
double camera_source = 0;
const CameraPose *matched_camera_pose(double source) {
const CameraPose *best = nullptr;
double distance = 0.005;
for (const auto &p : camera_poses) if (std::abs(p.time-source) < distance) {
best = &p; distance = std::abs(p.time-source);
}
return best;
}
void on_carina_pose(float *pose, double stamp) {
if (!pose || !std::isfinite(stamp)) return;
std::lock_guard<std::mutex> lock(camera_mutex);
if (!camera_accepting) return;
camera_pose_receipt = monotonic_ns();
CameraPose p{stamp, {}}; std::copy_n(pose, 7, p.pose.begin());
camera_poses.push_back(p);
while (camera_poses.size() > 64) camera_poses.pop_front();
}
void on_camera(char *left, char *right, char *, char *, double stamp, int width, int height) {
if (!left || !right || width <= 0 || height <= 0 || width > 2048 || height > 2048 || !std::isfinite(stamp)) return;
const auto received = monotonic_ns();
std::lock_guard<std::mutex> lock(camera_mutex);
if (!camera_accepting || !camera_wanted) return;
if (!camera_gate.Accept(stamp)) return;
const size_t size = size_t(width) * height;
camera_left.resize(size); camera_right.resize(size);
memcpy(camera_left.data(), left, size); memcpy(camera_right.data(), right, size);
camera_width = width; camera_height = height; camera_source = stamp; camera_receipt = received;
camera_input_sequence = camera_gate.received;
++camera_sequence;
}
void clear_camera(bool enabled) {
std::lock_guard<std::mutex> lock(camera_mutex);
camera_accepting = enabled; camera_wanted = false;
camera_poses.clear(); camera_left.clear(); camera_right.clear();
camera_sequence = camera_consumed = 0;
camera_gate = {}; camera_input_sequence = 0;
camera_pose_receipt = 0;
}
struct Session { struct Session {
XRDeviceProviderHandle device = nullptr; XRDeviceProviderHandle device = nullptr;
int pid = 0; int pid = 0;
@@ -142,7 +72,6 @@ struct Session {
int saved_dof = -1; int saved_dof = -1;
int64_t consumed_time = 0; int64_t consumed_time = 0;
jlong token = 0; jlong token = 0;
int spatial_status = 1;
}; };
std::unique_ptr<Session> session; std::unique_ptr<Session> session;
jlong next_token = 0; jlong next_token = 0;
@@ -198,7 +127,6 @@ int tracking(Session& s, bool enabled) {
} }
void destroy(Session& s) { void destroy(Session& s) {
clear_camera(false);
clear_pose(false); clear_pose(false);
clear_state(false); clear_state(false);
if (s.device) { if (s.device) {
@@ -277,7 +205,7 @@ extern "C" JNIEXPORT jstring JNICALL JNI_METHOD(nativeMarketName)(JNIEnv* env, j
return env->NewStringUTF(name); return env->NewStringUTF(name);
} }
extern "C" JNIEXPORT jlong JNICALL JNI_METHOD(nativeOpen)(JNIEnv* env, jobject, jint pid, jint fd, jstring cache, jboolean spatial) { extern "C" JNIEXPORT jlong JNICALL JNI_METHOD(nativeOpen)(JNIEnv* env, jobject, jint pid, jint fd, jstring cache) {
std::lock_guard<std::mutex> lock(api_mutex); std::lock_guard<std::mutex> lock(api_mutex);
if (session || fd < 0 || !cache || !xr_device_provider_is_product_id_valid(pid)) return 0; if (session || fd < 0 || !cache || !xr_device_provider_is_product_id_valid(pid)) return 0;
auto s = std::make_unique<Session>(); auto s = std::make_unique<Session>();
@@ -293,7 +221,7 @@ extern "C" JNIEXPORT jlong JNICALL JNI_METHOD(nativeOpen)(JNIEnv* env, jobject,
} }
if (rc == 0) { if (rc == 0) {
rc = s->type == XR_DEVICE_TYPE_VITURE_CARINA ? rc = s->type == XR_DEVICE_TYPE_VITURE_CARINA ?
xr_device_provider_set_dof_type_carina(s->device, spatial ? 1 : 0) : xr_device_provider_set_dof_type_carina(s->device, 0) :
xr_device_provider_register_imu_pose_callback(s->device, on_pose); xr_device_provider_register_imu_pose_callback(s->device, on_pose);
} }
if (rc == 0) { if (rc == 0) {
@@ -303,10 +231,6 @@ extern "C" JNIEXPORT jlong JNICALL JNI_METHOD(nativeOpen)(JNIEnv* env, jobject,
env->ReleaseStringUTFChars(cache, directory); env->ReleaseStringUTFChars(cache, directory);
s->initialized = rc == 0; s->initialized = rc == 0;
} }
if (rc == 0 && s->type == XR_DEVICE_TYPE_VITURE_CARINA && spatial) {
clear_camera(true);
rc = xr_device_provider_register_callbacks_carina(s->device, on_carina_pose, nullptr, nullptr, on_camera);
}
if (rc == 0) { if (rc == 0) {
rc = xr_device_provider_start(s->device); rc = xr_device_provider_start(s->device);
s->started = rc == 0; s->started = rc == 0;
@@ -382,175 +306,3 @@ extern "C" JNIEXPORT void JNICALL JNI_METHOD(nativeClose)(JNIEnv*, jobject, jlon
std::lock_guard<std::mutex> lock(api_mutex); std::lock_guard<std::mutex> lock(api_mutex);
if (session && session->token == token) { destroy(*session); session.reset(); } if (session && session->token == token) { destroy(*session); session.reset(); }
} }
extern "C" JNIEXPORT jlong JNICALL JNI_METHOD(nativeSpatialPose)(JNIEnv* env, jobject, jlong token,
jfloatArray output, jintArray state) {
std::lock_guard<std::mutex> lock(api_mutex);
if (!session || session->token != token || !session->tracking || session->type != XR_DEVICE_TYPE_VITURE_CARINA ||
!output || !state || env->GetArrayLength(output) != 7 || env->GetArrayLength(state) != 1) return 0;
float pose[7]{}; int status = 1;
int rc = xr_device_provider_get_gl_pose_carina(session->device, pose, 0.0, &status);
session->spatial_status = rc == 0 ? status : rc;
jint valid = rc == 0 ? status : rc;
if (valid == 0) {
std::lock_guard<std::mutex> lock(camera_mutex);
if (monotonic_ns()-camera_pose_receipt > 100000000LL) valid = 1;
}
env->SetIntArrayRegion(state, 0, 1, &valid);
env->SetFloatArrayRegion(output, 0, 7, pose);
return monotonic_ns();
}
extern "C" JNIEXPORT void JNICALL JNI_METHOD(nativeCapture)(JNIEnv*, jobject, jlong token, jboolean wanted, jint ratePermille) {
std::lock_guard<std::mutex> api(api_mutex);
if (!session || session->token != token) return;
std::lock_guard<std::mutex> lock(camera_mutex);
camera_wanted = wanted;
camera_gate.SetRatePermille(wanted ? ratePermille : 1000);
if (!wanted) camera_consumed = camera_sequence;
}
extern "C" JNIEXPORT jstring JNICALL JNI_METHOD(nativeFirmware)(JNIEnv* env, jobject, jlong token) {
std::lock_guard<std::mutex> api(api_mutex);
if (!session || session->token != token) return nullptr;
char value[256]{}; int length = 255;
if (xr_device_provider_get_glasses_version(session->device, value, &length) != 0) return nullptr;
value[255] = 0;
return env->NewStringUTF(value);
}
extern "C" JNIEXPORT jbyteArray JNICALL JNI_METHOD(nativeSerialHash)(JNIEnv* env, jobject, jlong token) {
std::lock_guard<std::mutex> api(api_mutex);
if (!session || session->token != token) return nullptr;
uint8_t hash[32]{};
const int rc = xr_device_provider_get_sn_hash(session->device, hash);
if (rc != 0) { report("read device identity", rc); return nullptr; }
auto result = env->NewByteArray(32);
if (result) env->SetByteArrayRegion(result, 0, 32, reinterpret_cast<const jbyte*>(hash));
return result;
}
extern "C" JNIEXPORT jdoubleArray JNICALL JNI_METHOD(nativeSpatialDiagnostics)(JNIEnv* env, jobject, jlong token) {
std::lock_guard<std::mutex> api(api_mutex);
if (!session || session->token != token) return nullptr;
std::lock_guard<std::mutex> lock(camera_mutex);
double values[3] = {double(session->spatial_status), camera_pose_receipt ? (monotonic_ns()-camera_pose_receipt)/1e6 : -1.0,
camera_poses.empty() ? -1.0 : (camera_poses.back().time-camera_source)*1000.0};
auto result=env->NewDoubleArray(3);
if(result)env->SetDoubleArrayRegion(result,0,3,values);
return result;
}
extern "C" JNIEXPORT jlong JNICALL JNI_METHOD(nativeStereo)(JNIEnv* env, jobject, jlong token,
jobject left, jobject right, jdoubleArray metadata, jfloatArray head, jboolean waitForPose) {
std::lock_guard<std::mutex> api(api_mutex);
if (!session || session->token != token || !left || !right || !metadata || !head ||
env->GetArrayLength(metadata) != 9 || env->GetArrayLength(head) != 7) return 0;
std::lock_guard<std::mutex> lock(camera_mutex);
if (!camera_wanted || camera_sequence == camera_consumed || camera_left.empty()) return 0;
const auto size = camera_left.size();
if (env->GetDirectBufferCapacity(left) < jlong(size) || env->GetDirectBufferCapacity(right) < jlong(size)) return -1;
auto l = env->GetDirectBufferAddress(left), r = env->GetDirectBufferAddress(right);
if (!l || !r) return -1;
const CameraPose *best = matched_camera_pose(camera_source);
if (waitForPose && !best && monotonic_ns()-camera_receipt < 35000000LL) return 0;
memcpy(l, camera_left.data(), size); memcpy(r, camera_right.data(), size);
double meta[9] = {double(camera_width), double(camera_height), camera_source, double(camera_receipt),
double(token), double(camera_sequence), best ? 1.0 : 0.0,
double(camera_input_sequence), double(camera_gate.skipped)};
env->SetDoubleArrayRegion(metadata, 0, 9, meta);
if (best) env->SetFloatArrayRegion(head, 0, 7, best->pose.data());
camera_consumed = camera_sequence;
return jlong(camera_sequence);
}
extern "C" JNIEXPORT jboolean JNICALL JNI_METHOD(nativeCameraSynchronized)(JNIEnv*, jobject, jlong token, jdouble source) {
std::lock_guard<std::mutex> api(api_mutex);
if (!session || session->token != token || !std::isfinite(source)) return JNI_FALSE;
std::lock_guard<std::mutex> lock(camera_mutex);
return camera_accepting && matched_camera_pose(source) != nullptr;
}
namespace {
struct RgbUsbLog {
int savedStderr;
bool hadLevel;
std::string oldLevel;
explicit RgbUsbLog(int fd) : savedStderr(dup(STDERR_FILENO)),
hadLevel(getenv("LIBUSB_DEBUG") != nullptr), oldLevel(hadLevel ? getenv("LIBUSB_DEBUG") : "") {
fflush(stderr);
if (savedStderr >= 0) dup2(fd, STDERR_FILENO);
setenv("LIBUSB_DEBUG", "4", 1);
}
~RgbUsbLog() {
fflush(stderr);
if (savedStderr >= 0) { dup2(savedStderr, STDERR_FILENO); close(savedStderr); }
if (hadLevel) setenv("LIBUSB_DEBUG", oldLevel.c_str(), 1); else unsetenv("LIBUSB_DEBUG");
}
};
void rgb_usb_state(int fd, const char* stage) {
uint8_t alternate = 0;
usbdevfs_ctrltransfer request{};
request.bRequestType=0x81; request.bRequest=0x0a; request.wIndex=1;
request.wLength=1; request.timeout=200; request.data=&alternate;
int result=ioctl(fd, USBDEVFS_CONTROL, &request);
fprintf(stderr,"RGB %s GET_INTERFACE result=%d errno=%d alternate=%u\n",stage,result,result<0 ? errno : 0,alternate);
for (int selector : {1, 2}) {
uint8_t size[2]{};
request.bRequestType=0xa1; request.bRequest=0x85; request.wValue=selector << 8;
request.wLength=2; request.data=size;
result=ioctl(fd,USBDEVFS_CONTROL,&request);
const unsigned length=result==2 ? unsigned(size[0]) | unsigned(size[1]) << 8 : 26;
uint8_t bytes[64]{};
request.bRequest=0x81; request.wLength=std::clamp(length,26u,64u); request.data=bytes;
result=ioctl(fd,USBDEVFS_CONTROL,&request);
fprintf(stderr,"RGB %s %s result=%d errno=%d bytes=",stage,selector==1 ? "PROBE" : "COMMIT",result,result<0 ? errno : 0);
for (int i=0;i<std::max(0,result);++i) fprintf(stderr,"%02x",bytes[i]);
fprintf(stderr,"\n");
}
fflush(stderr);
}
}
extern "C" JNIEXPORT jbyteArray JNICALL JNI_METHOD(nativeRgbSnapshot)(JNIEnv* env, jobject,
jint vid, jint pid, jint fd, jlongArray metadata, jint logFd) {
if (fd < 0 || !metadata || env->GetArrayLength(metadata) != 7 ||
!xr_camera_provider_is_valid_camera(vid, pid)) return nullptr;
RgbUsbLog usbLog(logFd);
rgb_usb_state(fd,"before-create");
struct Capture {
std::mutex mutex;
std::condition_variable ready;
std::vector<uint8_t> jpeg;
unsigned frames = 0;
jlong values[7]{};
} capture;
auto camera = xr_camera_provider_create(vid, pid, fd);
if (!camera) { fprintf(stderr,"RGB provider create failed\n"); return nullptr; }
const int result = xr_camera_provider_start(camera, [](const XRCameraFrame* frame, void* data) {
auto& c = *static_cast<Capture*>(data);
std::lock_guard<std::mutex> lock(c.mutex);
++c.frames;
if (!frame || !frame->data || frame->format != XR_CAMERA_FORMAT_MJPEG ||
frame->size < 4 || frame->size > 4 * 1024 * 1024) return;
c.jpeg.assign(frame->data, frame->data + frame->size);
c.values[0] = frame->width; c.values[1] = frame->height;
c.values[2] = frame->timestamp; c.values[3] = frame->sequence;
c.values[6] = monotonic_ns();
c.ready.notify_one();
}, &capture);
fprintf(stderr,"RGB start result=%d streaming=%d\n",result,xr_camera_provider_is_streaming(camera));
rgb_usb_state(fd,"after-start");
if (result == 0) {
{
std::unique_lock<std::mutex> lock(capture.mutex);
capture.ready.wait_for(lock, std::chrono::seconds(5), [&] { return capture.frames >= 10 && !capture.jpeg.empty(); });
}
fprintf(stderr,"RGB stop result=%d\n",xr_camera_provider_stop(camera));
}
xr_camera_provider_destroy(camera);
rgb_usb_state(fd,"after-destroy");
capture.values[4] = result;
capture.values[5] = capture.frames;
env->SetLongArrayRegion(metadata, 0, 7, capture.values);
if (capture.jpeg.empty()) return nullptr;
auto bytes = env->NewByteArray(static_cast<jsize>(capture.jpeg.size()));
if (bytes) env->SetByteArrayRegion(bytes, 0, static_cast<jsize>(capture.jpeg.size()),
reinterpret_cast<const jbyte*>(capture.jpeg.data()));
return bytes;
}
@@ -1,29 +0,0 @@
#pragma once
#include <cmath>
#include <cstdint>
struct StereoFrameGate {
uint64_t received = 0, skipped = 0;
void SetRatePermille(int rate) {
if (rate != 500 && rate != 600 && rate != 800 && rate != 1000) rate = 500;
if (ratePermille_ != rate) phase_ = 1000-rate;
ratePermille_ = rate;
}
void SetHalfRate(bool enabled) {
SetRatePermille(enabled ? 500 : 1000);
}
bool Accept(double source) {
if (!std::isfinite(source) || source <= 0) return false;
++received;
if (source <= lastSource_) phase_ = 1000-ratePermille_;
lastSource_ = source;
phase_ += ratePermille_;
const bool copy = phase_ >= 1000;
if (copy) phase_ -= 1000;
if (!copy) ++skipped;
return copy;
}
private:
int ratePermille_ = 1000, phase_ = 0;
double lastSource_ = 0;
};
-134
View File
@@ -1,134 +0,0 @@
#include <jni.h>
#include <libusb.h>
#include <libuvc/libuvc.h>
#include "mjpeg_payload.h"
#include <algorithm>
#include <chrono>
#include <condition_variable>
#include <cstdio>
#include <cstdlib>
#include <mutex>
#include <string>
#include <vector>
#include <time.h>
#include <unistd.h>
namespace {
struct UsbLog {
int saved;
bool hadLevel;
std::string level;
explicit UsbLog(int fd) : saved(dup(STDERR_FILENO)), hadLevel(getenv("LIBUSB_DEBUG") != nullptr),
level(hadLevel ? getenv("LIBUSB_DEBUG") : "") {
fflush(stderr);
if (saved >= 0) dup2(fd, STDERR_FILENO);
setenv("LIBUSB_DEBUG", "3", 1);
libusb_set_log_cb(nullptr, [](libusb_context*, libusb_log_level, const char* text) {
fputs(text, stderr);
}, LIBUSB_LOG_CB_GLOBAL);
}
~UsbLog() {
libusb_set_log_cb(nullptr, nullptr, LIBUSB_LOG_CB_GLOBAL);
fflush(stderr);
if (saved >= 0) { dup2(saved, STDERR_FILENO); close(saved); }
if (hadLevel) setenv("LIBUSB_DEBUG", level.c_str(), 1); else unsetenv("LIBUSB_DEBUG");
}
};
struct Capture {
std::mutex mutex;
std::condition_variable ready;
std::vector<uint8_t> jpeg;
jlong values[14]{};
bool accepting = true;
};
jlong monotonic_ns() {
timespec now{};
clock_gettime(CLOCK_MONOTONIC, &now);
return now.tv_sec*1000000000LL+now.tv_nsec;
}
void finish_observation(Capture& capture) {
std::lock_guard<std::mutex> lock(capture.mutex);
if (!capture.accepting) return;
capture.accepting = false;
capture.values[12] = monotonic_ns();
if (capture.values[6]) capture.values[13] = capture.values[12]-capture.values[6];
capture.values[8] = std::max(capture.values[8],capture.values[13]);
}
void frame_received(uvc_frame_t* frame, void* user) {
auto& capture = *static_cast<Capture*>(user);
std::lock_guard<std::mutex> lock(capture.mutex);
if (!capture.accepting) return;
++capture.values[5];
const auto* bytes = frame ? static_cast<const uint8_t*>(frame->data) : nullptr;
const size_t size = frame ? frame->data_bytes : 0;
const size_t jpegSize = frame && frame->frame_format == UVC_FRAME_FORMAT_MJPEG ? mjpeg_payload_size(bytes,size) : 0;
if (!jpegSize) {
++capture.values[10];
return;
}
const jlong time = monotonic_ns();
capture.values[0]=frame->width; capture.values[1]=frame->height; capture.values[3]=frame->sequence;
if (!capture.values[7]) capture.values[7]=time;
if (capture.values[6]) capture.values[8]=std::max(capture.values[8],time-capture.values[6]);
capture.values[6]=time;
++capture.values[9];
capture.values[11]+=jpegSize;
capture.jpeg.assign(bytes,bytes+jpegSize);
capture.ready.notify_one();
}
}
extern "C" JNIEXPORT jbyteArray JNICALL
Java_com_droiddeck_launcher_glasses_UvcRgbDiagnostic_nativeSnapshot(JNIEnv* env, jobject,
jint fd, jint width, jint height, jint fps, jint durationMs, jlongArray metadata, jint logFd) {
if (fd<0 || logFd<0 || !metadata || env->GetArrayLength(metadata)!=14 || width<160 || width>1920 ||
height<120 || height>1080 || fps<5 || fps>30 || durationMs<1000 || durationMs>30000) return nullptr;
UsbLog log(logFd);
Capture capture;
uvc_context_t* context=nullptr;
uvc_device_handle_t* camera=nullptr;
libusb_set_option(nullptr,LIBUSB_OPTION_NO_DEVICE_DISCOVERY);
int result=uvc_init(&context,nullptr);
fprintf(stderr,"UVC init=%d\n",result);
if (result==0) {
result=uvc_wrap(fd,context,&camera);
fprintf(stderr,"UVC wrap=%d\n",result);
}
if (result==0) {
uvc_print_diag(camera,stderr);
uvc_stream_ctrl_t control{};
result=uvc_get_stream_ctrl_format_size(camera,&control,UVC_FRAME_FORMAT_MJPEG,width,height,fps);
fprintf(stderr,"UVC negotiate=%d requested=%dx%d@%d\n",result,width,height,fps);
if (result==0) {
uvc_print_stream_ctrl(&control,stderr);
result=uvc_start_streaming(camera,&control,frame_received,&capture,0);
fprintf(stderr,"UVC start=%d\n",result);
if (result==0) {
{
std::unique_lock<std::mutex> lock(capture.mutex);
if (capture.ready.wait_for(lock,std::chrono::seconds(5),[&] { return !capture.jpeg.empty(); }))
capture.ready.wait_for(lock,std::chrono::milliseconds(durationMs),[] { return false; });
}
finish_observation(capture);
uvc_stop_streaming(camera);
}
}
}
finish_observation(capture);
if (camera) uvc_close(camera);
if (context) uvc_exit(context);
capture.values[4]=result;
fprintf(stderr,"UVC result=%d callbacks=%lld complete=%lld invalid=%lld maxGapMs=%.3f tailMs=%.3f\n",result,
static_cast<long long>(capture.values[5]),static_cast<long long>(capture.values[9]),
static_cast<long long>(capture.values[10]),capture.values[8]/1e6,capture.values[13]/1e6);
env->SetLongArrayRegion(metadata,0,14,capture.values);
if (result!=0 || capture.jpeg.empty()) return nullptr;
auto bytes=env->NewByteArray(static_cast<jsize>(capture.jpeg.size()));
if (bytes) env->SetByteArrayRegion(bytes,0,static_cast<jsize>(capture.jpeg.size()),
reinterpret_cast<const jbyte*>(capture.jpeg.data()));
return bytes;
}
+8 -9
View File
@@ -3,7 +3,6 @@ add_library(droiddeckwayland SHARED
src/vk_present.c src/vk_present.c
src/effects_chain.c src/effects_chain.c
src/cardboard.c src/cardboard.c
src/spatialpose.c
src/vk_loader.c src/vk_loader.c
src/sc_layer.c src/sc_layer.c
src/ahb_swapchain.c src/ahb_swapchain.c
@@ -43,10 +42,10 @@ target_include_directories(droiddeckwayland PRIVATE
) )
set(DROIDDECK_FRAMEGEN_LSFG_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../framegen/lsfg) set(DROIDDECK_FRAMEGEN_LSFG_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../framegen/lsfg)
set(DROIDDECK_FRAMEGEN_DDFG_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../framegen/ddfg) set(DROIDDECK_FRAMEGEN_WINFG_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../framegen/winfg)
if (TARGET dxbc AND EXISTS ${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_engine.cpp if (TARGET dxbc AND EXISTS ${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_engine.cpp
AND EXISTS ${DROIDDECK_FRAMEGEN_DDFG_DIR}/ddfg_engine.cpp) AND EXISTS ${DROIDDECK_FRAMEGEN_WINFG_DIR}/winfg_engine.cpp)
message(STATUS "droiddeckwayland: frame-generation engines built in (LSFG Native, DD-FG Native)") message(STATUS "droiddeckwayland: frame-generation engines built in (LSFG Native, Win-FG Native)")
target_sources(droiddeckwayland PRIVATE target_sources(droiddeckwayland PRIVATE
src/framegen_engine.cpp src/framegen_engine.cpp
${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_probe.cpp ${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_probe.cpp
@@ -66,9 +65,9 @@ if (TARGET dxbc AND EXISTS ${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_engine.cpp
${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_engine.cpp ${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_engine.cpp
${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_governor.cpp ${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_governor.cpp
${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_jni.cpp ${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_jni.cpp
${DROIDDECK_FRAMEGEN_DDFG_DIR}/framegen.cpp ${DROIDDECK_FRAMEGEN_WINFG_DIR}/framegen.cpp
${DROIDDECK_FRAMEGEN_DDFG_DIR}/ddfg_vkd.cpp ${DROIDDECK_FRAMEGEN_WINFG_DIR}/winfg_vkd.cpp
${DROIDDECK_FRAMEGEN_DDFG_DIR}/ddfg_engine.cpp ${DROIDDECK_FRAMEGEN_WINFG_DIR}/winfg_engine.cpp
) )
target_include_directories(droiddeckwayland PRIVATE target_include_directories(droiddeckwayland PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/.. ${CMAKE_CURRENT_SOURCE_DIR}/..
@@ -77,8 +76,8 @@ if (TARGET dxbc AND EXISTS ${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_engine.cpp
target_compile_options(droiddeckwayland PRIVATE target_compile_options(droiddeckwayland PRIVATE
$<$<COMPILE_LANGUAGE:CXX>:-std=c++17 -fvisibility=hidden>) $<$<COMPILE_LANGUAGE:CXX>:-std=c++17 -fvisibility=hidden>)
target_compile_definitions(droiddeckwayland PRIVATE target_compile_definitions(droiddeckwayland PRIVATE
DDFG_UPSTREAM="${DDFG_UPSTREAM}" WINFG_UPSTREAM="${WINFG_UPSTREAM}"
DDFG_CHAIN_HASH="${DDFG_CHAIN_HASH}" WINFG_CHAIN_HASH="${WINFG_CHAIN_HASH}"
) )
target_link_libraries(droiddeckwayland dxbc atomic) target_link_libraries(droiddeckwayland dxbc atomic)
else() else()
+4 -19
View File
@@ -28,7 +28,7 @@ static float clampf(float v, float lo, float hi) { return v < lo ? lo : v > hi ?
void cardboard_clamp(struct cardboard_params *p) { void cardboard_clamp(struct cardboard_params *p) {
p->enabled = p->enabled ? 1 : 0; p->enabled = p->enabled ? 1 : 0;
if (p->source < CARDBOARD_SOURCE_SCREEN || p->source > CARDBOARD_SOURCE_FLAT) p->source = CARDBOARD_SOURCE_SCREEN; p->source = p->source == CARDBOARD_SOURCE_SBS ? CARDBOARD_SOURCE_SBS : CARDBOARD_SOURCE_SCREEN;
p->ipd_m = clampf(p->ipd_m, 0.0f, 0.1f); p->ipd_m = clampf(p->ipd_m, 0.0f, 0.1f);
p->screen_dist_m = clampf(p->screen_dist_m, 0.5f, 50.0f); p->screen_dist_m = clampf(p->screen_dist_m, 0.5f, 50.0f);
p->screen_width_m = clampf(p->screen_width_m, 0.2f, 60.0f); p->screen_width_m = clampf(p->screen_width_m, 0.2f, 60.0f);
@@ -62,12 +62,9 @@ void cardboard_push_constants(const struct cardboard_params *p, const float pose
out[21] = out[22] = out[23] = 0.0f; out[21] = out[22] = out[23] = 0.0f;
} }
void cardboard_push_translation(const struct cardboard_params *p, const float position[3], float out[24]) {
for (int i = 0; i < 3; ++i) out[21+i] = p->source == CARDBOARD_SOURCE_SCREEN && isfinite(position[i]) ? position[i] : 0.0f;
}
#ifndef CARDBOARD_HOST_TEST #ifndef CARDBOARD_HOST_TEST
static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
static struct cardboard_params g_set = { static struct cardboard_params g_set = {
.enabled = 0, .source = CARDBOARD_SOURCE_SCREEN, .ipd_m = 0.064f, .screen_dist_m = 3.0f, .enabled = 0, .source = CARDBOARD_SOURCE_SCREEN, .ipd_m = 0.064f, .screen_dist_m = 3.0f,
@@ -75,7 +72,6 @@ static struct cardboard_params g_set = {
static float g_pose[9] = {1, 0, 0, 0, 1, 0, 0, 0, 1}; static float g_pose[9] = {1, 0, 0, 0, 1, 0, 0, 0, 1};
static volatile int g_changed = 1; static volatile int g_changed = 1;
static float g_position[3];
static int g_live; static int g_live;
static void shm_publish(int live); static void shm_publish(int live);
@@ -90,8 +86,7 @@ void vkp_cardboard_set(const struct cardboard_params *p) {
pthread_mutex_unlock(&g_lock); pthread_mutex_unlock(&g_lock);
if (was != c.enabled || c.enabled) if (was != c.enabled || c.enabled)
droiddeck_log("cardboard", "%s: %s%s, ipd %.0f mm, screen %.1f m wide at %.1f m, lens k1 %.2f k2 %.2f, fov %.0f, inset %.3f, chroma %.3f", droiddeck_log("cardboard", "%s: %s%s, ipd %.0f mm, screen %.1f m wide at %.1f m, lens k1 %.2f k2 %.2f, fov %.0f, inset %.3f, chroma %.3f",
c.enabled ? "on" : "off", c.source == CARDBOARD_SOURCE_SBS ? "side-by-side source" : c.enabled ? "on" : "off", c.source == CARDBOARD_SOURCE_SBS ? "side-by-side source" : "virtual screen",
c.source == CARDBOARD_SOURCE_FLAT ? "flat image in both eyes" : "virtual screen",
c.mono ? " (one eye)" : "", c.ipd_m * 1000.0f, c.screen_width_m, c.screen_dist_m, c.k1, c.k2, c.fov_deg, c.lens_inset, c.chroma); c.mono ? " (one eye)" : "", c.ipd_m * 1000.0f, c.screen_width_m, c.screen_dist_m, c.k1, c.k2, c.fov_deg, c.lens_inset, c.chroma);
} }
@@ -151,31 +146,22 @@ static void shm_publish(int live) {
} }
void vkp_cardboard_set_spatial_pose(const float m[9], const float position[3], int live) { void vkp_cardboard_set_pose(const float m[9], int live) {
pthread_mutex_lock(&g_lock); pthread_mutex_lock(&g_lock);
memcpy(g_pose, m, sizeof(g_pose)); memcpy(g_pose, m, sizeof(g_pose));
memcpy(g_position, position, sizeof(g_position));
g_live = live; g_live = live;
if (g_set.enabled && g_set.source == CARDBOARD_SOURCE_SCREEN) g_changed = 1; if (g_set.enabled && g_set.source == CARDBOARD_SOURCE_SCREEN) g_changed = 1;
shm_publish(live); shm_publish(live);
pthread_mutex_unlock(&g_lock); pthread_mutex_unlock(&g_lock);
} }
void vkp_cardboard_set_pose(const float m[9], int live) {
const float zero[3] = {0};
vkp_cardboard_set_spatial_pose(m, zero, live);
}
static struct cardboard_params g_cur; static struct cardboard_params g_cur;
static float g_cur_pose[9]; static float g_cur_pose[9];
static float g_cur_position[3];
static void snapshot(void) { static void snapshot(void) {
pthread_mutex_lock(&g_lock); pthread_mutex_lock(&g_lock);
g_cur = g_set; g_cur = g_set;
memcpy(g_cur_pose, g_pose, sizeof(g_cur_pose)); memcpy(g_cur_pose, g_pose, sizeof(g_cur_pose));
memcpy(g_cur_position, g_position, sizeof(g_cur_position));
pthread_mutex_unlock(&g_lock); pthread_mutex_unlock(&g_lock);
} }
@@ -442,7 +428,6 @@ VkImage vkp_cardboard_run(VkCommandBuffer cmd, VkImage src, int src_w, int src_h
} }
struct { float ndc[4]; float rest[24]; } pc = {{-1.0f, -1.0f, 1.0f, 1.0f}, {0}}; struct { float ndc[4]; float rest[24]; } pc = {{-1.0f, -1.0f, 1.0f, 1.0f}, {0}};
cardboard_push_constants(&g_cur, g_cur_pose, src_w, src_h, out_w, out_h, pc.rest); cardboard_push_constants(&g_cur, g_cur_pose, src_w, src_h, out_w, out_h, pc.rest);
cardboard_push_translation(&g_cur, g_cur_position, pc.rest);
VkRenderPassBeginInfo rpi = {.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, .renderPass = g_rp, VkRenderPassBeginInfo rpi = {.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, .renderPass = g_rp,
.framebuffer = g_t.fb, .renderArea = {{0, 0}, {(uint32_t)out_w, (uint32_t)out_h}}}; .framebuffer = g_t.fb, .renderArea = {{0, 0}, {(uint32_t)out_w, (uint32_t)out_h}}};
@@ -24,21 +24,14 @@ vec3 eyeSample(vec2 tan, float eye) {
if (pc.view.z > 0.5) { if (pc.view.z > 0.5) {
float tanH = pc.lens.z; float tanH = pc.lens.z;
vec2 s = vec2(tan.x / (tanH * pc.view.w), tan.y / tanH) * 0.5 + 0.5; vec2 s = vec2(tan.x / (tanH * pc.view.w), tan.y / tanH) * 0.5 + 0.5;
if (pc.view.z > 1.5) {
vec2 fit = max(vec2(pc.view.w / pc.view.y, pc.view.y / pc.view.w), vec2(1.0));
s = (s - 0.5) * fit + 0.5;
if (any(lessThan(s, vec2(0.0))) || any(greaterThan(s, vec2(1.0)))) return vec3(0.0);
return texture(Source, s).rgb;
}
if (any(lessThan(s, vec2(0.0))) || any(greaterThan(s, vec2(1.0)))) return vec3(0.0); if (any(lessThan(s, vec2(0.0))) || any(greaterThan(s, vec2(1.0)))) return vec3(0.0);
return texture(Source, vec2((s.x + eye) * 0.5, s.y)).rgb; return texture(Source, vec2((s.x + eye) * 0.5, s.y)).rgb;
} }
mat3 R = transpose(mat3(pc.rot0.xyz, pc.rot1.xyz, pc.rot2.xyz)); mat3 R = transpose(mat3(pc.rot0.xyz, pc.rot1.xyz, pc.rot2.xyz));
vec3 d = R * normalize(vec3(tan.x, -tan.y, -1.0)); vec3 d = R * normalize(vec3(tan.x, -tan.y, -1.0));
vec3 o = pc.extra.yzw + R * vec3((eye < 0.5 ? -1.0 : 1.0) * pc.rot0.w, 0.0, 0.0); vec3 o = R * vec3((eye < 0.5 ? -1.0 : 1.0) * pc.rot0.w, 0.0, 0.0);
if (d.z > -1e-4) return BACKDROP; if (d.z > -1e-4) return BACKDROP;
float t = (-pc.rot1.w - o.z) / d.z; float t = (-pc.rot1.w - o.z) / d.z;
if (t <= 0.0) return BACKDROP;
vec3 hit = o + d * t; vec3 hit = o + d * t;
float halfW = pc.rot2.w, halfH = halfW / pc.view.y; float halfW = pc.rot2.w, halfH = halfW / pc.view.y;
vec2 s = vec2(hit.x / halfW, -hit.y / halfH) * 0.5 + 0.5; vec2 s = vec2(hit.x / halfW, -hit.y / halfH) * 0.5 + 0.5;
+1 -3
View File
@@ -3,7 +3,7 @@
#define VK_USE_PLATFORM_ANDROID_KHR #define VK_USE_PLATFORM_ANDROID_KHR
#include <vulkan/vulkan.h> #include <vulkan/vulkan.h>
enum { CARDBOARD_SOURCE_SCREEN = 0, CARDBOARD_SOURCE_SBS = 1, CARDBOARD_SOURCE_FLAT = 2 }; enum { CARDBOARD_SOURCE_SCREEN = 0, CARDBOARD_SOURCE_SBS = 1 };
struct cardboard_params { struct cardboard_params {
int enabled; int enabled;
@@ -21,7 +21,6 @@ struct cardboard_params {
void vkp_cardboard_set(const struct cardboard_params *p); void vkp_cardboard_set(const struct cardboard_params *p);
void vkp_cardboard_set_pose(const float m[9], int live); void vkp_cardboard_set_pose(const float m[9], int live);
void vkp_cardboard_set_spatial_pose(const float m[9], const float position[3], int live);
void vkp_cardboard_set_pose_file(const char *path); void vkp_cardboard_set_pose_file(const char *path);
void vkp_cardboard_set_render_height(int height); void vkp_cardboard_set_render_height(int height);
@@ -34,6 +33,5 @@ VkImage vkp_cardboard_run(VkCommandBuffer cmd, VkImage src, int src_w, int src_h
void cardboard_clamp(struct cardboard_params *p); void cardboard_clamp(struct cardboard_params *p);
void cardboard_push_constants(const struct cardboard_params *p, const float pose[9], void cardboard_push_constants(const struct cardboard_params *p, const float pose[9],
int src_w, int src_h, int out_w, int out_h, float out[24]); int src_w, int src_h, int out_w, int out_h, float out[24]);
void cardboard_push_translation(const struct cardboard_params *p, const float position[3], float out[24]);
#endif #endif
+269 -303
View File
@@ -1,9 +1,8 @@
// 1115.1.0
#pragma once #pragma once
const uint32_t cardboard_frag_code[] = { const uint32_t cardboard_frag_code[] = {
0x07230203,0x00010000,0x0008000b,0x000001ba,0x00000000,0x00020011,0x00000001,0x0006000b, 0x07230203,0x00010000,0x0008000b,0x00000185,0x00000000,0x00020011,0x00000001,0x0006000b,
0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001, 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001,
0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x0000012d,0x000001b2,0x00030010, 0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x000000f8,0x0000017d,0x00030010,
0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d, 0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d,
0x00000000,0x00070005,0x0000000d,0x69646e75,0x726f7473,0x66762874,0x31663b32,0x0000003b, 0x00000000,0x00070005,0x0000000d,0x69646e75,0x726f7473,0x66762874,0x31663b32,0x0000003b,
0x00030005,0x0000000b,0x00000074,0x00040005,0x0000000c,0x6c616373,0x00000065,0x00070005, 0x00030005,0x0000000b,0x00000074,0x00040005,0x0000000c,0x6c616373,0x00000065,0x00070005,
@@ -14,304 +13,271 @@ const uint32_t cardboard_frag_code[] = {
0x00050006,0x0000001e,0x00000003,0x32746f72,0x00000000,0x00050006,0x0000001e,0x00000004, 0x00050006,0x0000001e,0x00000003,0x32746f72,0x00000000,0x00050006,0x0000001e,0x00000004,
0x736e656c,0x00000000,0x00050006,0x0000001e,0x00000005,0x77656976,0x00000000,0x00050006, 0x736e656c,0x00000000,0x00050006,0x0000001e,0x00000005,0x77656976,0x00000000,0x00050006,
0x0000001e,0x00000006,0x72747865,0x00000061,0x00030005,0x00000020,0x00006370,0x00040005, 0x0000001e,0x00000006,0x72747865,0x00000061,0x00030005,0x00000020,0x00006370,0x00040005,
0x0000003f,0x486e6174,0x00000000,0x00030005,0x00000042,0x00000073,0x00030005,0x00000059, 0x0000003f,0x486e6174,0x00000000,0x00030005,0x00000042,0x00000073,0x00040005,0x00000068,
0x00746966,0x00040005,0x00000082,0x72756f53,0x00006563,0x00030005,0x000000a3,0x00000052, 0x72756f53,0x00006563,0x00030005,0x00000077,0x00000052,0x00030005,0x00000094,0x00000064,
0x00030005,0x000000c0,0x00000064,0x00030005,0x000000cb,0x0000006f,0x00030005,0x000000e4, 0x00030005,0x0000009f,0x0000006f,0x00030005,0x000000b3,0x00000074,0x00030005,0x000000bd,
0x00000074,0x00030005,0x000000f3,0x00746968,0x00040005,0x000000f9,0x666c6168,0x00000057, 0x00746968,0x00040005,0x000000c3,0x666c6168,0x00000057,0x00040005,0x000000c6,0x666c6168,
0x00040005,0x000000fc,0x666c6168,0x00000048,0x00030005,0x00000101,0x00000073,0x00040005, 0x00000048,0x00030005,0x000000cb,0x00000073,0x00040005,0x000000ed,0x6f6e6f6d,0x00000000,
0x00000123,0x6f6e6f6d,0x00000000,0x00030005,0x00000127,0x00657965,0x00030005,0x0000012d, 0x00030005,0x000000f2,0x00657965,0x00030005,0x000000f8,0x00007675,0x00040005,0x000000ff,
0x00007675,0x00040005,0x00000134,0x61636f6c,0x0000006c,0x00030005,0x00000145,0x00007863, 0x61636f6c,0x0000006c,0x00030005,0x00000110,0x00007863,0x00030005,0x00000124,0x00000070,
0x00030005,0x00000159,0x00000070,0x00040005,0x0000015e,0x486e6174,0x00000000,0x00030005, 0x00040005,0x00000129,0x486e6174,0x00000000,0x00030005,0x0000012c,0x00000074,0x00030005,
0x00000161,0x00000074,0x00030005,0x00000172,0x00000063,0x00040005,0x00000176,0x61726170, 0x0000013d,0x00000063,0x00040005,0x00000141,0x61726170,0x0000006d,0x00040005,0x00000143,
0x0000006d,0x00040005,0x00000178,0x61726170,0x0000006d,0x00040005,0x0000017a,0x61726170, 0x61726170,0x0000006d,0x00040005,0x00000145,0x61726170,0x0000006d,0x00040005,0x00000146,
0x0000006d,0x00040005,0x0000017b,0x61726170,0x0000006d,0x00040005,0x00000180,0x61726170, 0x61726170,0x0000006d,0x00040005,0x0000014b,0x61726170,0x0000006d,0x00040005,0x0000014d,
0x0000006d,0x00040005,0x00000182,0x61726170,0x0000006d,0x00040005,0x00000184,0x61726170, 0x61726170,0x0000006d,0x00040005,0x0000014f,0x61726170,0x0000006d,0x00040005,0x00000150,
0x0000006d,0x00040005,0x00000185,0x61726170,0x0000006d,0x00040005,0x0000018d,0x61726170, 0x61726170,0x0000006d,0x00040005,0x00000158,0x61726170,0x0000006d,0x00040005,0x0000015a,
0x0000006d,0x00040005,0x0000018f,0x61726170,0x0000006d,0x00040005,0x00000191,0x61726170, 0x61726170,0x0000006d,0x00040005,0x0000015c,0x61726170,0x0000006d,0x00040005,0x0000015d,
0x0000006d,0x00040005,0x00000192,0x61726170,0x0000006d,0x00040005,0x00000198,0x61726170, 0x61726170,0x0000006d,0x00040005,0x00000163,0x61726170,0x0000006d,0x00040005,0x00000165,
0x0000006d,0x00040005,0x0000019a,0x61726170,0x0000006d,0x00040005,0x0000019c,0x61726170, 0x61726170,0x0000006d,0x00040005,0x00000167,0x61726170,0x0000006d,0x00040005,0x00000168,
0x0000006d,0x00040005,0x0000019d,0x61726170,0x0000006d,0x00030005,0x000001a0,0x00000065, 0x61726170,0x0000006d,0x00030005,0x0000016b,0x00000065,0x00040005,0x00000171,0x65646166,
0x00040005,0x000001a6,0x65646166,0x00000000,0x00050005,0x000001b2,0x4374756f,0x726f6c6f, 0x00000000,0x00050005,0x0000017d,0x4374756f,0x726f6c6f,0x00000000,0x00030047,0x0000001e,
0x00000000,0x00030047,0x0000001e,0x00000002,0x00050048,0x0000001e,0x00000000,0x00000023, 0x00000002,0x00050048,0x0000001e,0x00000000,0x00000023,0x00000000,0x00050048,0x0000001e,
0x00000000,0x00050048,0x0000001e,0x00000001,0x00000023,0x00000010,0x00050048,0x0000001e, 0x00000001,0x00000023,0x00000010,0x00050048,0x0000001e,0x00000002,0x00000023,0x00000020,
0x00000002,0x00000023,0x00000020,0x00050048,0x0000001e,0x00000003,0x00000023,0x00000030, 0x00050048,0x0000001e,0x00000003,0x00000023,0x00000030,0x00050048,0x0000001e,0x00000004,
0x00050048,0x0000001e,0x00000004,0x00000023,0x00000040,0x00050048,0x0000001e,0x00000005, 0x00000023,0x00000040,0x00050048,0x0000001e,0x00000005,0x00000023,0x00000050,0x00050048,
0x00000023,0x00000050,0x00050048,0x0000001e,0x00000006,0x00000023,0x00000060,0x00040047, 0x0000001e,0x00000006,0x00000023,0x00000060,0x00040047,0x00000068,0x00000021,0x00000000,
0x00000082,0x00000021,0x00000000,0x00040047,0x00000082,0x00000022,0x00000000,0x00040047, 0x00040047,0x00000068,0x00000022,0x00000000,0x00040047,0x000000f8,0x0000001e,0x00000000,
0x0000012d,0x0000001e,0x00000000,0x00040047,0x000001b2,0x0000001e,0x00000000,0x00020013, 0x00040047,0x0000017d,0x0000001e,0x00000000,0x00020013,0x00000002,0x00030021,0x00000003,
0x00000002,0x00030021,0x00000003,0x00000002,0x00030016,0x00000006,0x00000020,0x00040017, 0x00000002,0x00030016,0x00000006,0x00000020,0x00040017,0x00000007,0x00000006,0x00000002,
0x00000007,0x00000006,0x00000002,0x00040020,0x00000008,0x00000007,0x00000007,0x00040020, 0x00040020,0x00000008,0x00000007,0x00000007,0x00040020,0x00000009,0x00000007,0x00000006,
0x00000009,0x00000007,0x00000006,0x00050021,0x0000000a,0x00000007,0x00000008,0x00000009, 0x00050021,0x0000000a,0x00000007,0x00000008,0x00000009,0x00040017,0x0000000f,0x00000006,
0x00040017,0x0000000f,0x00000006,0x00000003,0x00050021,0x00000010,0x0000000f,0x00000008, 0x00000003,0x00050021,0x00000010,0x0000000f,0x00000008,0x00000009,0x0004002b,0x00000006,
0x00000009,0x0004002b,0x00000006,0x0000001c,0x3f800000,0x00040017,0x0000001d,0x00000006, 0x0000001c,0x3f800000,0x00040017,0x0000001d,0x00000006,0x00000004,0x0009001e,0x0000001e,
0x00000004,0x0009001e,0x0000001e,0x0000001d,0x0000001d,0x0000001d,0x0000001d,0x0000001d, 0x0000001d,0x0000001d,0x0000001d,0x0000001d,0x0000001d,0x0000001d,0x0000001d,0x00040020,
0x0000001d,0x0000001d,0x00040020,0x0000001f,0x00000009,0x0000001e,0x0004003b,0x0000001f, 0x0000001f,0x00000009,0x0000001e,0x0004003b,0x0000001f,0x00000020,0x00000009,0x00040015,
0x00000020,0x00000009,0x00040015,0x00000021,0x00000020,0x00000001,0x0004002b,0x00000021, 0x00000021,0x00000020,0x00000001,0x0004002b,0x00000021,0x00000022,0x00000004,0x00040015,
0x00000022,0x00000004,0x00040015,0x00000023,0x00000020,0x00000000,0x0004002b,0x00000023, 0x00000023,0x00000020,0x00000000,0x0004002b,0x00000023,0x00000024,0x00000000,0x00040020,
0x00000024,0x00000000,0x00040020,0x00000025,0x00000009,0x00000006,0x0004002b,0x00000023, 0x00000025,0x00000009,0x00000006,0x0004002b,0x00000023,0x0000002b,0x00000001,0x0004002b,
0x0000002b,0x00000001,0x0004002b,0x00000021,0x00000036,0x00000005,0x0004002b,0x00000023, 0x00000021,0x00000036,0x00000005,0x0004002b,0x00000023,0x00000037,0x00000002,0x0004002b,
0x00000037,0x00000002,0x0004002b,0x00000006,0x0000003a,0x3f000000,0x00020014,0x0000003b, 0x00000006,0x0000003a,0x3f000000,0x00020014,0x0000003b,0x0004002b,0x00000023,0x00000046,
0x0004002b,0x00000023,0x00000046,0x00000003,0x0004002b,0x00000006,0x00000055,0x3fc00000, 0x00000003,0x0004002b,0x00000006,0x00000054,0x00000000,0x0005002c,0x00000007,0x00000055,
0x0005002c,0x00000007,0x00000065,0x0000001c,0x0000001c,0x0004002b,0x00000006,0x0000006f, 0x00000054,0x00000054,0x00040017,0x00000056,0x0000003b,0x00000002,0x0005002c,0x00000007,
0x00000000,0x0005002c,0x00000007,0x00000070,0x0000006f,0x0000006f,0x00040017,0x00000071, 0x0000005d,0x0000001c,0x0000001c,0x0006002c,0x0000000f,0x00000063,0x00000054,0x00000054,
0x0000003b,0x00000002,0x0006002c,0x0000000f,0x0000007d,0x0000006f,0x0000006f,0x0000006f, 0x00000054,0x00090019,0x00000065,0x00000006,0x00000001,0x00000000,0x00000000,0x00000000,
0x00090019,0x0000007f,0x00000006,0x00000001,0x00000000,0x00000000,0x00000000,0x00000001, 0x00000001,0x00000000,0x0003001b,0x00000066,0x00000065,0x00040020,0x00000067,0x00000000,
0x00000000,0x0003001b,0x00000080,0x0000007f,0x00040020,0x00000081,0x00000000,0x00000080, 0x00000066,0x0004003b,0x00000067,0x00000068,0x00000000,0x00040018,0x00000075,0x0000000f,
0x0004003b,0x00000081,0x00000082,0x00000000,0x00040018,0x000000a1,0x0000000f,0x00000003, 0x00000003,0x00040020,0x00000076,0x00000007,0x00000075,0x0004002b,0x00000021,0x00000078,
0x00040020,0x000000a2,0x00000007,0x000000a1,0x0004002b,0x00000021,0x000000a4,0x00000001, 0x00000001,0x00040020,0x00000079,0x00000009,0x0000001d,0x0004002b,0x00000021,0x0000007d,
0x00040020,0x000000a5,0x00000009,0x0000001d,0x0004002b,0x00000021,0x000000a9,0x00000002, 0x00000002,0x0004002b,0x00000021,0x00000081,0x00000003,0x00040020,0x00000093,0x00000007,
0x0004002b,0x00000021,0x000000ad,0x00000003,0x00040020,0x000000bf,0x00000007,0x0000000f, 0x0000000f,0x0004002b,0x00000006,0x0000009b,0xbf800000,0x0004002b,0x00000006,0x000000ab,
0x0004002b,0x00000006,0x000000c7,0xbf800000,0x0004002b,0x00000021,0x000000cc,0x00000006, 0xb8d1b717,0x0004002b,0x00000006,0x000000af,0x3c75c28f,0x0004002b,0x00000006,0x000000b0,
0x0004002b,0x00000006,0x000000dc,0xb8d1b717,0x0004002b,0x00000006,0x000000e0,0x3c75c28f, 0x3ca3d70a,0x0006002c,0x0000000f,0x000000b1,0x000000af,0x000000af,0x000000b0,0x00040020,
0x0004002b,0x00000006,0x000000e1,0x3ca3d70a,0x0006002c,0x0000000f,0x000000e2,0x000000e0, 0x000000ec,0x00000007,0x0000003b,0x0004002b,0x00000021,0x000000ee,0x00000006,0x00040020,
0x000000e0,0x000000e1,0x00040020,0x00000122,0x00000007,0x0000003b,0x00040020,0x0000012c, 0x000000f7,0x00000001,0x00000007,0x0004003b,0x000000f7,0x000000f8,0x00000001,0x00040020,
0x00000001,0x00000007,0x0004003b,0x0000012c,0x0000012d,0x00000001,0x00040020,0x0000012e, 0x000000f9,0x00000001,0x00000006,0x0004002b,0x00000006,0x00000108,0x40000000,0x0004002b,
0x00000001,0x00000006,0x0004002b,0x00000006,0x0000013d,0x40000000,0x0004002b,0x00000006, 0x00000006,0x00000172,0x3cf5c28f,0x00040020,0x0000017c,0x00000003,0x0000001d,0x0004003b,
0x000001a7,0x3cf5c28f,0x00040020,0x000001b1,0x00000003,0x0000001d,0x0004003b,0x000001b1, 0x0000017c,0x0000017d,0x00000003,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,
0x000001b2,0x00000003,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8, 0x000200f8,0x00000005,0x0004003b,0x000000ec,0x000000ed,0x00000007,0x0004003b,0x00000009,
0x00000005,0x0004003b,0x00000122,0x00000123,0x00000007,0x0004003b,0x00000009,0x00000127, 0x000000f2,0x00000007,0x0004003b,0x00000008,0x000000ff,0x00000007,0x0004003b,0x00000008,
0x00000007,0x0004003b,0x00000008,0x00000134,0x00000007,0x0004003b,0x00000008,0x00000136, 0x00000101,0x00000007,0x0004003b,0x00000009,0x00000110,0x00000007,0x0004003b,0x00000009,
0x00000007,0x0004003b,0x00000009,0x00000145,0x00000007,0x0004003b,0x00000009,0x00000147, 0x00000112,0x00000007,0x0004003b,0x00000009,0x00000118,0x00000007,0x0004003b,0x00000008,
0x00000007,0x0004003b,0x00000009,0x0000014d,0x00000007,0x0004003b,0x00000008,0x00000159, 0x00000124,0x00000007,0x0004003b,0x00000009,0x00000129,0x00000007,0x0004003b,0x00000008,
0x00000007,0x0004003b,0x00000009,0x0000015e,0x00000007,0x0004003b,0x00000008,0x00000161, 0x0000012c,0x00000007,0x0004003b,0x00000093,0x0000013d,0x00000007,0x0004003b,0x00000008,
0x00000007,0x0004003b,0x000000bf,0x00000172,0x00000007,0x0004003b,0x00000008,0x00000176, 0x00000141,0x00000007,0x0004003b,0x00000009,0x00000143,0x00000007,0x0004003b,0x00000008,
0x00000007,0x0004003b,0x00000009,0x00000178,0x00000007,0x0004003b,0x00000008,0x0000017a, 0x00000145,0x00000007,0x0004003b,0x00000009,0x00000146,0x00000007,0x0004003b,0x00000008,
0x00000007,0x0004003b,0x00000009,0x0000017b,0x00000007,0x0004003b,0x00000008,0x00000180, 0x0000014b,0x00000007,0x0004003b,0x00000009,0x0000014d,0x00000007,0x0004003b,0x00000008,
0x00000007,0x0004003b,0x00000009,0x00000182,0x00000007,0x0004003b,0x00000008,0x00000184, 0x0000014f,0x00000007,0x0004003b,0x00000009,0x00000150,0x00000007,0x0004003b,0x00000008,
0x00000007,0x0004003b,0x00000009,0x00000185,0x00000007,0x0004003b,0x00000008,0x0000018d, 0x00000158,0x00000007,0x0004003b,0x00000009,0x0000015a,0x00000007,0x0004003b,0x00000008,
0x00000007,0x0004003b,0x00000009,0x0000018f,0x00000007,0x0004003b,0x00000008,0x00000191, 0x0000015c,0x00000007,0x0004003b,0x00000009,0x0000015d,0x00000007,0x0004003b,0x00000008,
0x00000007,0x0004003b,0x00000009,0x00000192,0x00000007,0x0004003b,0x00000008,0x00000198, 0x00000163,0x00000007,0x0004003b,0x00000009,0x00000165,0x00000007,0x0004003b,0x00000008,
0x00000007,0x0004003b,0x00000009,0x0000019a,0x00000007,0x0004003b,0x00000008,0x0000019c, 0x00000167,0x00000007,0x0004003b,0x00000009,0x00000168,0x00000007,0x0004003b,0x00000008,
0x00000007,0x0004003b,0x00000009,0x0000019d,0x00000007,0x0004003b,0x00000008,0x000001a0, 0x0000016b,0x00000007,0x0004003b,0x00000009,0x00000171,0x00000007,0x00060041,0x00000025,
0x00000007,0x0004003b,0x00000009,0x000001a6,0x00000007,0x00060041,0x00000025,0x00000124, 0x000000ef,0x00000020,0x000000ee,0x00000024,0x0004003d,0x00000006,0x000000f0,0x000000ef,
0x00000020,0x000000cc,0x00000024,0x0004003d,0x00000006,0x00000125,0x00000124,0x000500ba, 0x000500ba,0x0000003b,0x000000f1,0x000000f0,0x0000003a,0x0003003e,0x000000ed,0x000000f1,
0x0000003b,0x00000126,0x00000125,0x0000003a,0x0003003e,0x00000123,0x00000126,0x0004003d, 0x0004003d,0x0000003b,0x000000f3,0x000000ed,0x000400a8,0x0000003b,0x000000f4,0x000000f3,
0x0000003b,0x00000128,0x00000123,0x000400a8,0x0000003b,0x00000129,0x00000128,0x000300f7, 0x000300f7,0x000000f6,0x00000000,0x000400fa,0x000000f4,0x000000f5,0x000000f6,0x000200f8,
0x0000012b,0x00000000,0x000400fa,0x00000129,0x0000012a,0x0000012b,0x000200f8,0x0000012a, 0x000000f5,0x00050041,0x000000f9,0x000000fa,0x000000f8,0x00000024,0x0004003d,0x00000006,
0x00050041,0x0000012e,0x0000012f,0x0000012d,0x00000024,0x0004003d,0x00000006,0x00000130, 0x000000fb,0x000000fa,0x000500b8,0x0000003b,0x000000fc,0x000000fb,0x0000003a,0x000200f9,
0x0000012f,0x000500b8,0x0000003b,0x00000131,0x00000130,0x0000003a,0x000200f9,0x0000012b, 0x000000f6,0x000200f8,0x000000f6,0x000700f5,0x0000003b,0x000000fd,0x000000f3,0x00000005,
0x000200f8,0x0000012b,0x000700f5,0x0000003b,0x00000132,0x00000128,0x00000005,0x00000131, 0x000000fc,0x000000f5,0x000600a9,0x00000006,0x000000fe,0x000000fd,0x00000054,0x0000001c,
0x0000012a,0x000600a9,0x00000006,0x00000133,0x00000132,0x0000006f,0x0000001c,0x0003003e, 0x0003003e,0x000000f2,0x000000fe,0x0004003d,0x0000003b,0x00000100,0x000000ed,0x000300f7,
0x00000127,0x00000133,0x0004003d,0x0000003b,0x00000135,0x00000123,0x000300f7,0x00000138, 0x00000103,0x00000000,0x000400fa,0x00000100,0x00000102,0x00000105,0x000200f8,0x00000102,
0x00000000,0x000400fa,0x00000135,0x00000137,0x0000013a,0x000200f8,0x00000137,0x0004003d, 0x0004003d,0x00000007,0x00000104,0x000000f8,0x0003003e,0x00000101,0x00000104,0x000200f9,
0x00000007,0x00000139,0x0000012d,0x0003003e,0x00000136,0x00000139,0x000200f9,0x00000138, 0x00000103,0x000200f8,0x00000105,0x00050041,0x000000f9,0x00000106,0x000000f8,0x00000024,
0x000200f8,0x0000013a,0x00050041,0x0000012e,0x0000013b,0x0000012d,0x00000024,0x0004003d, 0x0004003d,0x00000006,0x00000107,0x00000106,0x00050085,0x00000006,0x00000109,0x00000107,
0x00000006,0x0000013c,0x0000013b,0x00050085,0x00000006,0x0000013e,0x0000013c,0x0000013d, 0x00000108,0x0004003d,0x00000006,0x0000010a,0x000000f2,0x00050083,0x00000006,0x0000010b,
0x0004003d,0x00000006,0x0000013f,0x00000127,0x00050083,0x00000006,0x00000140,0x0000013e, 0x00000109,0x0000010a,0x00050041,0x000000f9,0x0000010c,0x000000f8,0x0000002b,0x0004003d,
0x0000013f,0x00050041,0x0000012e,0x00000141,0x0000012d,0x0000002b,0x0004003d,0x00000006, 0x00000006,0x0000010d,0x0000010c,0x00050050,0x00000007,0x0000010e,0x0000010b,0x0000010d,
0x00000142,0x00000141,0x00050050,0x00000007,0x00000143,0x00000140,0x00000142,0x0003003e, 0x0003003e,0x00000101,0x0000010e,0x000200f9,0x00000103,0x000200f8,0x00000103,0x0004003d,
0x00000136,0x00000143,0x000200f9,0x00000138,0x000200f8,0x00000138,0x0004003d,0x00000007, 0x00000007,0x0000010f,0x00000101,0x0003003e,0x000000ff,0x0000010f,0x0004003d,0x0000003b,
0x00000144,0x00000136,0x0003003e,0x00000134,0x00000144,0x0004003d,0x0000003b,0x00000146, 0x00000111,0x000000ed,0x000300f7,0x00000114,0x00000000,0x000400fa,0x00000111,0x00000113,
0x00000123,0x000300f7,0x00000149,0x00000000,0x000400fa,0x00000146,0x00000148,0x0000014a, 0x00000115,0x000200f8,0x00000113,0x0003003e,0x00000112,0x0000003a,0x000200f9,0x00000114,
0x000200f8,0x00000148,0x0003003e,0x00000147,0x0000003a,0x000200f9,0x00000149,0x000200f8, 0x000200f8,0x00000115,0x0004003d,0x00000006,0x00000116,0x000000f2,0x000500b8,0x0000003b,
0x0000014a,0x0004003d,0x00000006,0x0000014b,0x00000127,0x000500b8,0x0000003b,0x0000014c, 0x00000117,0x00000116,0x0000003a,0x000300f7,0x0000011a,0x00000000,0x000400fa,0x00000117,
0x0000014b,0x0000003a,0x000300f7,0x0000014f,0x00000000,0x000400fa,0x0000014c,0x0000014e, 0x00000119,0x0000011d,0x000200f8,0x00000119,0x00060041,0x00000025,0x0000011b,0x00000020,
0x00000152,0x000200f8,0x0000014e,0x00060041,0x00000025,0x00000150,0x00000020,0x00000036, 0x00000036,0x00000024,0x0004003d,0x00000006,0x0000011c,0x0000011b,0x0003003e,0x00000118,
0x00000024,0x0004003d,0x00000006,0x00000151,0x00000150,0x0003003e,0x0000014d,0x00000151, 0x0000011c,0x000200f9,0x0000011a,0x000200f8,0x0000011d,0x00060041,0x00000025,0x0000011e,
0x000200f9,0x0000014f,0x000200f8,0x00000152,0x00060041,0x00000025,0x00000153,0x00000020, 0x00000020,0x00000036,0x00000024,0x0004003d,0x00000006,0x0000011f,0x0000011e,0x0004007f,
0x00000036,0x00000024,0x0004003d,0x00000006,0x00000154,0x00000153,0x0004007f,0x00000006, 0x00000006,0x00000120,0x0000011f,0x0003003e,0x00000118,0x00000120,0x000200f9,0x0000011a,
0x00000155,0x00000154,0x0003003e,0x0000014d,0x00000155,0x000200f9,0x0000014f,0x000200f8, 0x000200f8,0x0000011a,0x0004003d,0x00000006,0x00000121,0x00000118,0x00050081,0x00000006,
0x0000014f,0x0004003d,0x00000006,0x00000156,0x0000014d,0x00050081,0x00000006,0x00000157, 0x00000122,0x0000003a,0x00000121,0x0003003e,0x00000112,0x00000122,0x000200f9,0x00000114,
0x0000003a,0x00000156,0x0003003e,0x00000147,0x00000157,0x000200f9,0x00000149,0x000200f8, 0x000200f8,0x00000114,0x0004003d,0x00000006,0x00000123,0x00000112,0x0003003e,0x00000110,
0x00000149,0x0004003d,0x00000006,0x00000158,0x00000147,0x0003003e,0x00000145,0x00000158, 0x00000123,0x0004003d,0x00000007,0x00000125,0x000000ff,0x0004003d,0x00000006,0x00000126,
0x0004003d,0x00000007,0x0000015a,0x00000134,0x0004003d,0x00000006,0x0000015b,0x00000145, 0x00000110,0x00050050,0x00000007,0x00000127,0x00000126,0x0000003a,0x00050083,0x00000007,
0x00050050,0x00000007,0x0000015c,0x0000015b,0x0000003a,0x00050083,0x00000007,0x0000015d, 0x00000128,0x00000125,0x00000127,0x0003003e,0x00000124,0x00000128,0x00060041,0x00000025,
0x0000015a,0x0000015c,0x0003003e,0x00000159,0x0000015d,0x00060041,0x00000025,0x0000015f, 0x0000012a,0x00000020,0x00000022,0x00000037,0x0004003d,0x00000006,0x0000012b,0x0000012a,
0x00000020,0x00000022,0x00000037,0x0004003d,0x00000006,0x00000160,0x0000015f,0x0003003e, 0x0003003e,0x00000129,0x0000012b,0x00050041,0x00000009,0x0000012d,0x00000124,0x00000024,
0x0000015e,0x00000160,0x00050041,0x00000009,0x00000162,0x00000159,0x00000024,0x0004003d, 0x0004003d,0x00000006,0x0000012e,0x0000012d,0x00060041,0x00000025,0x0000012f,0x00000020,
0x00000006,0x00000163,0x00000162,0x00060041,0x00000025,0x00000164,0x00000020,0x00000036, 0x00000036,0x00000046,0x0004003d,0x00000006,0x00000130,0x0000012f,0x00050085,0x00000006,
0x00000046,0x0004003d,0x00000006,0x00000165,0x00000164,0x00050085,0x00000006,0x00000166, 0x00000131,0x0000012e,0x00000130,0x00050041,0x00000009,0x00000132,0x00000124,0x0000002b,
0x00000163,0x00000165,0x00050041,0x00000009,0x00000167,0x00000159,0x0000002b,0x0004003d, 0x0004003d,0x00000006,0x00000133,0x00000132,0x00050050,0x00000007,0x00000134,0x00000131,
0x00000006,0x00000168,0x00000167,0x00050050,0x00000007,0x00000169,0x00000166,0x00000168, 0x00000133,0x0005008e,0x00000007,0x00000135,0x00000134,0x00000108,0x0004003d,0x00000006,
0x0005008e,0x00000007,0x0000016a,0x00000169,0x0000013d,0x0004003d,0x00000006,0x0000016b, 0x00000136,0x00000129,0x0005008e,0x00000007,0x00000137,0x00000135,0x00000136,0x0003003e,
0x0000015e,0x0005008e,0x00000007,0x0000016c,0x0000016a,0x0000016b,0x0003003e,0x00000161, 0x0000012c,0x00000137,0x00060041,0x00000025,0x00000138,0x00000020,0x00000022,0x00000046,
0x0000016c,0x00060041,0x00000025,0x0000016d,0x00000020,0x00000022,0x00000046,0x0004003d, 0x0004003d,0x00000006,0x00000139,0x00000138,0x000500ba,0x0000003b,0x0000013a,0x00000139,
0x00000006,0x0000016e,0x0000016d,0x000500ba,0x0000003b,0x0000016f,0x0000016e,0x0000006f, 0x00000054,0x000300f7,0x0000013c,0x00000000,0x000400fa,0x0000013a,0x0000013b,0x00000162,
0x000300f7,0x00000171,0x00000000,0x000400fa,0x0000016f,0x00000170,0x00000197,0x000200f8, 0x000200f8,0x0000013b,0x00060041,0x00000025,0x0000013e,0x00000020,0x00000022,0x00000046,
0x00000170,0x00060041,0x00000025,0x00000173,0x00000020,0x00000022,0x00000046,0x0004003d, 0x0004003d,0x00000006,0x0000013f,0x0000013e,0x00050083,0x00000006,0x00000140,0x0000001c,
0x00000006,0x00000174,0x00000173,0x00050083,0x00000006,0x00000175,0x0000001c,0x00000174, 0x0000013f,0x0004003d,0x00000007,0x00000142,0x0000012c,0x0003003e,0x00000141,0x00000142,
0x0004003d,0x00000007,0x00000177,0x00000161,0x0003003e,0x00000176,0x00000177,0x0003003e, 0x0003003e,0x00000143,0x00000140,0x00060039,0x00000007,0x00000144,0x0000000d,0x00000141,
0x00000178,0x00000175,0x00060039,0x00000007,0x00000179,0x0000000d,0x00000176,0x00000178, 0x00000143,0x0003003e,0x00000145,0x00000144,0x0004003d,0x00000006,0x00000147,0x000000f2,
0x0003003e,0x0000017a,0x00000179,0x0004003d,0x00000006,0x0000017c,0x00000127,0x0003003e, 0x0003003e,0x00000146,0x00000147,0x00060039,0x0000000f,0x00000148,0x00000013,0x00000145,
0x0000017b,0x0000017c,0x00060039,0x0000000f,0x0000017d,0x00000013,0x0000017a,0x0000017b, 0x00000146,0x00050051,0x00000006,0x00000149,0x00000148,0x00000000,0x00050041,0x00000009,
0x00050051,0x00000006,0x0000017e,0x0000017d,0x00000000,0x00050041,0x00000009,0x0000017f, 0x0000014a,0x0000013d,0x00000024,0x0003003e,0x0000014a,0x00000149,0x0004003d,0x00000007,
0x00000172,0x00000024,0x0003003e,0x0000017f,0x0000017e,0x0004003d,0x00000007,0x00000181, 0x0000014c,0x0000012c,0x0003003e,0x0000014b,0x0000014c,0x0003003e,0x0000014d,0x0000001c,
0x00000161,0x0003003e,0x00000180,0x00000181,0x0003003e,0x00000182,0x0000001c,0x00060039, 0x00060039,0x00000007,0x0000014e,0x0000000d,0x0000014b,0x0000014d,0x0003003e,0x0000014f,
0x00000007,0x00000183,0x0000000d,0x00000180,0x00000182,0x0003003e,0x00000184,0x00000183, 0x0000014e,0x0004003d,0x00000006,0x00000151,0x000000f2,0x0003003e,0x00000150,0x00000151,
0x0004003d,0x00000006,0x00000186,0x00000127,0x0003003e,0x00000185,0x00000186,0x00060039, 0x00060039,0x0000000f,0x00000152,0x00000013,0x0000014f,0x00000150,0x00050051,0x00000006,
0x0000000f,0x00000187,0x00000013,0x00000184,0x00000185,0x00050051,0x00000006,0x00000188, 0x00000153,0x00000152,0x00000001,0x00050041,0x00000009,0x00000154,0x0000013d,0x0000002b,
0x00000187,0x00000001,0x00050041,0x00000009,0x00000189,0x00000172,0x0000002b,0x0003003e, 0x0003003e,0x00000154,0x00000153,0x00060041,0x00000025,0x00000155,0x00000020,0x00000022,
0x00000189,0x00000188,0x00060041,0x00000025,0x0000018a,0x00000020,0x00000022,0x00000046, 0x00000046,0x0004003d,0x00000006,0x00000156,0x00000155,0x00050081,0x00000006,0x00000157,
0x0004003d,0x00000006,0x0000018b,0x0000018a,0x00050081,0x00000006,0x0000018c,0x0000001c, 0x0000001c,0x00000156,0x0004003d,0x00000007,0x00000159,0x0000012c,0x0003003e,0x00000158,
0x0000018b,0x0004003d,0x00000007,0x0000018e,0x00000161,0x0003003e,0x0000018d,0x0000018e, 0x00000159,0x0003003e,0x0000015a,0x00000157,0x00060039,0x00000007,0x0000015b,0x0000000d,
0x0003003e,0x0000018f,0x0000018c,0x00060039,0x00000007,0x00000190,0x0000000d,0x0000018d, 0x00000158,0x0000015a,0x0003003e,0x0000015c,0x0000015b,0x0004003d,0x00000006,0x0000015e,
0x0000018f,0x0003003e,0x00000191,0x00000190,0x0004003d,0x00000006,0x00000193,0x00000127, 0x000000f2,0x0003003e,0x0000015d,0x0000015e,0x00060039,0x0000000f,0x0000015f,0x00000013,
0x0003003e,0x00000192,0x00000193,0x00060039,0x0000000f,0x00000194,0x00000013,0x00000191, 0x0000015c,0x0000015d,0x00050051,0x00000006,0x00000160,0x0000015f,0x00000002,0x00050041,
0x00000192,0x00050051,0x00000006,0x00000195,0x00000194,0x00000002,0x00050041,0x00000009, 0x00000009,0x00000161,0x0000013d,0x00000037,0x0003003e,0x00000161,0x00000160,0x000200f9,
0x00000196,0x00000172,0x00000037,0x0003003e,0x00000196,0x00000195,0x000200f9,0x00000171, 0x0000013c,0x000200f8,0x00000162,0x0004003d,0x00000007,0x00000164,0x0000012c,0x0003003e,
0x000200f8,0x00000197,0x0004003d,0x00000007,0x00000199,0x00000161,0x0003003e,0x00000198, 0x00000163,0x00000164,0x0003003e,0x00000165,0x0000001c,0x00060039,0x00000007,0x00000166,
0x00000199,0x0003003e,0x0000019a,0x0000001c,0x00060039,0x00000007,0x0000019b,0x0000000d, 0x0000000d,0x00000163,0x00000165,0x0003003e,0x00000167,0x00000166,0x0004003d,0x00000006,
0x00000198,0x0000019a,0x0003003e,0x0000019c,0x0000019b,0x0004003d,0x00000006,0x0000019e, 0x00000169,0x000000f2,0x0003003e,0x00000168,0x00000169,0x00060039,0x0000000f,0x0000016a,
0x00000127,0x0003003e,0x0000019d,0x0000019e,0x00060039,0x0000000f,0x0000019f,0x00000013, 0x00000013,0x00000167,0x00000168,0x0003003e,0x0000013d,0x0000016a,0x000200f9,0x0000013c,
0x0000019c,0x0000019d,0x0003003e,0x00000172,0x0000019f,0x000200f9,0x00000171,0x000200f8, 0x000200f8,0x0000013c,0x0004003d,0x00000007,0x0000016c,0x000000ff,0x0004003d,0x00000007,
0x00000171,0x0004003d,0x00000007,0x000001a1,0x00000134,0x0004003d,0x00000007,0x000001a2, 0x0000016d,0x000000ff,0x00050050,0x00000007,0x0000016e,0x0000001c,0x0000001c,0x00050083,
0x00000134,0x00050050,0x00000007,0x000001a3,0x0000001c,0x0000001c,0x00050083,0x00000007, 0x00000007,0x0000016f,0x0000016e,0x0000016d,0x0007000c,0x00000007,0x00000170,0x00000001,
0x000001a4,0x000001a3,0x000001a2,0x0007000c,0x00000007,0x000001a5,0x00000001,0x00000025, 0x00000025,0x0000016c,0x0000016f,0x0003003e,0x0000016b,0x00000170,0x00050041,0x00000009,
0x000001a1,0x000001a4,0x0003003e,0x000001a0,0x000001a5,0x00050041,0x00000009,0x000001a8, 0x00000173,0x0000016b,0x00000024,0x0004003d,0x00000006,0x00000174,0x00000173,0x00060041,
0x000001a0,0x00000024,0x0004003d,0x00000006,0x000001a9,0x000001a8,0x00060041,0x00000025, 0x00000025,0x00000175,0x00000020,0x00000036,0x00000046,0x0004003d,0x00000006,0x00000176,
0x000001aa,0x00000020,0x00000036,0x00000046,0x0004003d,0x00000006,0x000001ab,0x000001aa, 0x00000175,0x00050085,0x00000006,0x00000177,0x00000174,0x00000176,0x00050041,0x00000009,
0x00050085,0x00000006,0x000001ac,0x000001a9,0x000001ab,0x00050041,0x00000009,0x000001ad, 0x00000178,0x0000016b,0x0000002b,0x0004003d,0x00000006,0x00000179,0x00000178,0x0007000c,
0x000001a0,0x0000002b,0x0004003d,0x00000006,0x000001ae,0x000001ad,0x0007000c,0x00000006, 0x00000006,0x0000017a,0x00000001,0x00000025,0x00000177,0x00000179,0x0008000c,0x00000006,
0x000001af,0x00000001,0x00000025,0x000001ac,0x000001ae,0x0008000c,0x00000006,0x000001b0, 0x0000017b,0x00000001,0x00000031,0x00000054,0x00000172,0x0000017a,0x0003003e,0x00000171,
0x00000001,0x00000031,0x0000006f,0x000001a7,0x000001af,0x0003003e,0x000001a6,0x000001b0, 0x0000017b,0x0004003d,0x0000000f,0x0000017e,0x0000013d,0x0004003d,0x00000006,0x0000017f,
0x0004003d,0x0000000f,0x000001b3,0x00000172,0x0004003d,0x00000006,0x000001b4,0x000001a6, 0x00000171,0x0005008e,0x0000000f,0x00000180,0x0000017e,0x0000017f,0x00050051,0x00000006,
0x0005008e,0x0000000f,0x000001b5,0x000001b3,0x000001b4,0x00050051,0x00000006,0x000001b6, 0x00000181,0x00000180,0x00000000,0x00050051,0x00000006,0x00000182,0x00000180,0x00000001,
0x000001b5,0x00000000,0x00050051,0x00000006,0x000001b7,0x000001b5,0x00000001,0x00050051, 0x00050051,0x00000006,0x00000183,0x00000180,0x00000002,0x00070050,0x0000001d,0x00000184,
0x00000006,0x000001b8,0x000001b5,0x00000002,0x00070050,0x0000001d,0x000001b9,0x000001b6, 0x00000181,0x00000182,0x00000183,0x0000001c,0x0003003e,0x0000017d,0x00000184,0x000100fd,
0x000001b7,0x000001b8,0x0000001c,0x0003003e,0x000001b2,0x000001b9,0x000100fd,0x00010038, 0x00010038,0x00050036,0x00000007,0x0000000d,0x00000000,0x0000000a,0x00030037,0x00000008,
0x00050036,0x00000007,0x0000000d,0x00000000,0x0000000a,0x00030037,0x00000008,0x0000000b, 0x0000000b,0x00030037,0x00000009,0x0000000c,0x000200f8,0x0000000e,0x0004003b,0x00000009,
0x00030037,0x00000009,0x0000000c,0x000200f8,0x0000000e,0x0004003b,0x00000009,0x00000015, 0x00000015,0x00000007,0x0004003d,0x00000007,0x00000016,0x0000000b,0x0004003d,0x00000007,
0x00000007,0x0004003d,0x00000007,0x00000016,0x0000000b,0x0004003d,0x00000007,0x00000017, 0x00000017,0x0000000b,0x00050094,0x00000006,0x00000018,0x00000016,0x00000017,0x0003003e,
0x0000000b,0x00050094,0x00000006,0x00000018,0x00000016,0x00000017,0x0003003e,0x00000015, 0x00000015,0x00000018,0x0004003d,0x00000007,0x00000019,0x0000000b,0x0004003d,0x00000006,
0x00000018,0x0004003d,0x00000007,0x00000019,0x0000000b,0x0004003d,0x00000006,0x0000001a, 0x0000001a,0x0000000c,0x0005008e,0x00000007,0x0000001b,0x00000019,0x0000001a,0x00060041,
0x0000000c,0x0005008e,0x00000007,0x0000001b,0x00000019,0x0000001a,0x00060041,0x00000025, 0x00000025,0x00000026,0x00000020,0x00000022,0x00000024,0x0004003d,0x00000006,0x00000027,
0x00000026,0x00000020,0x00000022,0x00000024,0x0004003d,0x00000006,0x00000027,0x00000026, 0x00000026,0x0004003d,0x00000006,0x00000028,0x00000015,0x00050085,0x00000006,0x00000029,
0x0004003d,0x00000006,0x00000028,0x00000015,0x00050085,0x00000006,0x00000029,0x00000027, 0x00000027,0x00000028,0x00050081,0x00000006,0x0000002a,0x0000001c,0x00000029,0x00060041,
0x00000028,0x00050081,0x00000006,0x0000002a,0x0000001c,0x00000029,0x00060041,0x00000025, 0x00000025,0x0000002c,0x00000020,0x00000022,0x0000002b,0x0004003d,0x00000006,0x0000002d,
0x0000002c,0x00000020,0x00000022,0x0000002b,0x0004003d,0x00000006,0x0000002d,0x0000002c, 0x0000002c,0x0004003d,0x00000006,0x0000002e,0x00000015,0x00050085,0x00000006,0x0000002f,
0x0004003d,0x00000006,0x0000002e,0x00000015,0x00050085,0x00000006,0x0000002f,0x0000002d, 0x0000002d,0x0000002e,0x0004003d,0x00000006,0x00000030,0x00000015,0x00050085,0x00000006,
0x0000002e,0x0004003d,0x00000006,0x00000030,0x00000015,0x00050085,0x00000006,0x00000031, 0x00000031,0x0000002f,0x00000030,0x00050081,0x00000006,0x00000032,0x0000002a,0x00000031,
0x0000002f,0x00000030,0x00050081,0x00000006,0x00000032,0x0000002a,0x00000031,0x0005008e, 0x0005008e,0x00000007,0x00000033,0x0000001b,0x00000032,0x000200fe,0x00000033,0x00010038,
0x00000007,0x00000033,0x0000001b,0x00000032,0x000200fe,0x00000033,0x00010038,0x00050036, 0x00050036,0x0000000f,0x00000013,0x00000000,0x00000010,0x00030037,0x00000008,0x00000011,
0x0000000f,0x00000013,0x00000000,0x00000010,0x00030037,0x00000008,0x00000011,0x00030037, 0x00030037,0x00000009,0x00000012,0x000200f8,0x00000014,0x0004003b,0x00000009,0x0000003f,
0x00000009,0x00000012,0x000200f8,0x00000014,0x0004003b,0x00000009,0x0000003f,0x00000007, 0x00000007,0x0004003b,0x00000008,0x00000042,0x00000007,0x0004003b,0x00000076,0x00000077,
0x0004003b,0x00000008,0x00000042,0x00000007,0x0004003b,0x00000008,0x00000059,0x00000007, 0x00000007,0x0004003b,0x00000093,0x00000094,0x00000007,0x0004003b,0x00000093,0x0000009f,
0x0004003b,0x000000a2,0x000000a3,0x00000007,0x0004003b,0x000000bf,0x000000c0,0x00000007, 0x00000007,0x0004003b,0x00000009,0x000000b3,0x00000007,0x0004003b,0x00000093,0x000000bd,
0x0004003b,0x000000bf,0x000000cb,0x00000007,0x0004003b,0x00000009,0x000000e4,0x00000007, 0x00000007,0x0004003b,0x00000009,0x000000c3,0x00000007,0x0004003b,0x00000009,0x000000c6,
0x0004003b,0x000000bf,0x000000f3,0x00000007,0x0004003b,0x00000009,0x000000f9,0x00000007, 0x00000007,0x0004003b,0x00000008,0x000000cb,0x00000007,0x00060041,0x00000025,0x00000038,
0x0004003b,0x00000009,0x000000fc,0x00000007,0x0004003b,0x00000008,0x00000101,0x00000007, 0x00000020,0x00000036,0x00000037,0x0004003d,0x00000006,0x00000039,0x00000038,0x000500ba,
0x00060041,0x00000025,0x00000038,0x00000020,0x00000036,0x00000037,0x0004003d,0x00000006, 0x0000003b,0x0000003c,0x00000039,0x0000003a,0x000300f7,0x0000003e,0x00000000,0x000400fa,
0x00000039,0x00000038,0x000500ba,0x0000003b,0x0000003c,0x00000039,0x0000003a,0x000300f7, 0x0000003c,0x0000003d,0x0000003e,0x000200f8,0x0000003d,0x00060041,0x00000025,0x00000040,
0x0000003e,0x00000000,0x000400fa,0x0000003c,0x0000003d,0x0000003e,0x000200f8,0x0000003d, 0x00000020,0x00000022,0x00000037,0x0004003d,0x00000006,0x00000041,0x00000040,0x0003003e,
0x00060041,0x00000025,0x00000040,0x00000020,0x00000022,0x00000037,0x0004003d,0x00000006, 0x0000003f,0x00000041,0x00050041,0x00000009,0x00000043,0x00000011,0x00000024,0x0004003d,
0x00000041,0x00000040,0x0003003e,0x0000003f,0x00000041,0x00050041,0x00000009,0x00000043, 0x00000006,0x00000044,0x00000043,0x0004003d,0x00000006,0x00000045,0x0000003f,0x00060041,
0x00000011,0x00000024,0x0004003d,0x00000006,0x00000044,0x00000043,0x0004003d,0x00000006, 0x00000025,0x00000047,0x00000020,0x00000036,0x00000046,0x0004003d,0x00000006,0x00000048,
0x00000045,0x0000003f,0x00060041,0x00000025,0x00000047,0x00000020,0x00000036,0x00000046, 0x00000047,0x00050085,0x00000006,0x00000049,0x00000045,0x00000048,0x00050088,0x00000006,
0x0004003d,0x00000006,0x00000048,0x00000047,0x00050085,0x00000006,0x00000049,0x00000045, 0x0000004a,0x00000044,0x00000049,0x00050041,0x00000009,0x0000004b,0x00000011,0x0000002b,
0x00000048,0x00050088,0x00000006,0x0000004a,0x00000044,0x00000049,0x00050041,0x00000009, 0x0004003d,0x00000006,0x0000004c,0x0000004b,0x0004003d,0x00000006,0x0000004d,0x0000003f,
0x0000004b,0x00000011,0x0000002b,0x0004003d,0x00000006,0x0000004c,0x0000004b,0x0004003d, 0x00050088,0x00000006,0x0000004e,0x0000004c,0x0000004d,0x00050050,0x00000007,0x0000004f,
0x00000006,0x0000004d,0x0000003f,0x00050088,0x00000006,0x0000004e,0x0000004c,0x0000004d, 0x0000004a,0x0000004e,0x0005008e,0x00000007,0x00000050,0x0000004f,0x0000003a,0x00050050,
0x00050050,0x00000007,0x0000004f,0x0000004a,0x0000004e,0x0005008e,0x00000007,0x00000050, 0x00000007,0x00000051,0x0000003a,0x0000003a,0x00050081,0x00000007,0x00000052,0x00000050,
0x0000004f,0x0000003a,0x00050050,0x00000007,0x00000051,0x0000003a,0x0000003a,0x00050081, 0x00000051,0x0003003e,0x00000042,0x00000052,0x0004003d,0x00000007,0x00000053,0x00000042,
0x00000007,0x00000052,0x00000050,0x00000051,0x0003003e,0x00000042,0x00000052,0x00060041, 0x000500b8,0x00000056,0x00000057,0x00000053,0x00000055,0x0004009a,0x0000003b,0x00000058,
0x00000025,0x00000053,0x00000020,0x00000036,0x00000037,0x0004003d,0x00000006,0x00000054, 0x00000057,0x000400a8,0x0000003b,0x00000059,0x00000058,0x000300f7,0x0000005b,0x00000000,
0x00000053,0x000500ba,0x0000003b,0x00000056,0x00000054,0x00000055,0x000300f7,0x00000058, 0x000400fa,0x00000059,0x0000005a,0x0000005b,0x000200f8,0x0000005a,0x0004003d,0x00000007,
0x00000000,0x000400fa,0x00000056,0x00000057,0x00000058,0x000200f8,0x00000057,0x00060041, 0x0000005c,0x00000042,0x000500ba,0x00000056,0x0000005e,0x0000005c,0x0000005d,0x0004009a,
0x00000025,0x0000005a,0x00000020,0x00000036,0x00000046,0x0004003d,0x00000006,0x0000005b, 0x0000003b,0x0000005f,0x0000005e,0x000200f9,0x0000005b,0x000200f8,0x0000005b,0x000700f5,
0x0000005a,0x00060041,0x00000025,0x0000005c,0x00000020,0x00000036,0x0000002b,0x0004003d, 0x0000003b,0x00000060,0x00000058,0x0000003d,0x0000005f,0x0000005a,0x000300f7,0x00000062,
0x00000006,0x0000005d,0x0000005c,0x00050088,0x00000006,0x0000005e,0x0000005b,0x0000005d, 0x00000000,0x000400fa,0x00000060,0x00000061,0x00000062,0x000200f8,0x00000061,0x000200fe,
0x00060041,0x00000025,0x0000005f,0x00000020,0x00000036,0x0000002b,0x0004003d,0x00000006, 0x00000063,0x000200f8,0x00000062,0x0004003d,0x00000066,0x00000069,0x00000068,0x00050041,
0x00000060,0x0000005f,0x00060041,0x00000025,0x00000061,0x00000020,0x00000036,0x00000046, 0x00000009,0x0000006a,0x00000042,0x00000024,0x0004003d,0x00000006,0x0000006b,0x0000006a,
0x0004003d,0x00000006,0x00000062,0x00000061,0x00050088,0x00000006,0x00000063,0x00000060, 0x0004003d,0x00000006,0x0000006c,0x00000012,0x00050081,0x00000006,0x0000006d,0x0000006b,
0x00000062,0x00050050,0x00000007,0x00000064,0x0000005e,0x00000063,0x0007000c,0x00000007, 0x0000006c,0x00050085,0x00000006,0x0000006e,0x0000006d,0x0000003a,0x00050041,0x00000009,
0x00000066,0x00000001,0x00000028,0x00000064,0x00000065,0x0003003e,0x00000059,0x00000066, 0x0000006f,0x00000042,0x0000002b,0x0004003d,0x00000006,0x00000070,0x0000006f,0x00050050,
0x0004003d,0x00000007,0x00000067,0x00000042,0x00050050,0x00000007,0x00000068,0x0000003a, 0x00000007,0x00000071,0x0000006e,0x00000070,0x00050057,0x0000001d,0x00000072,0x00000069,
0x0000003a,0x00050083,0x00000007,0x00000069,0x00000067,0x00000068,0x0004003d,0x00000007, 0x00000071,0x0008004f,0x0000000f,0x00000073,0x00000072,0x00000072,0x00000000,0x00000001,
0x0000006a,0x00000059,0x00050085,0x00000007,0x0000006b,0x00000069,0x0000006a,0x00050050, 0x00000002,0x000200fe,0x00000073,0x000200f8,0x0000003e,0x00050041,0x00000079,0x0000007a,
0x00000007,0x0000006c,0x0000003a,0x0000003a,0x00050081,0x00000007,0x0000006d,0x0000006b, 0x00000020,0x00000078,0x0004003d,0x0000001d,0x0000007b,0x0000007a,0x0008004f,0x0000000f,
0x0000006c,0x0003003e,0x00000042,0x0000006d,0x0004003d,0x00000007,0x0000006e,0x00000042, 0x0000007c,0x0000007b,0x0000007b,0x00000000,0x00000001,0x00000002,0x00050041,0x00000079,
0x000500b8,0x00000071,0x00000072,0x0000006e,0x00000070,0x0004009a,0x0000003b,0x00000073, 0x0000007e,0x00000020,0x0000007d,0x0004003d,0x0000001d,0x0000007f,0x0000007e,0x0008004f,
0x00000072,0x000400a8,0x0000003b,0x00000074,0x00000073,0x000300f7,0x00000076,0x00000000, 0x0000000f,0x00000080,0x0000007f,0x0000007f,0x00000000,0x00000001,0x00000002,0x00050041,
0x000400fa,0x00000074,0x00000075,0x00000076,0x000200f8,0x00000075,0x0004003d,0x00000007, 0x00000079,0x00000082,0x00000020,0x00000081,0x0004003d,0x0000001d,0x00000083,0x00000082,
0x00000077,0x00000042,0x000500ba,0x00000071,0x00000078,0x00000077,0x00000065,0x0004009a, 0x0008004f,0x0000000f,0x00000084,0x00000083,0x00000083,0x00000000,0x00000001,0x00000002,
0x0000003b,0x00000079,0x00000078,0x000200f9,0x00000076,0x000200f8,0x00000076,0x000700f5, 0x00050051,0x00000006,0x00000085,0x0000007c,0x00000000,0x00050051,0x00000006,0x00000086,
0x0000003b,0x0000007a,0x00000073,0x00000057,0x00000079,0x00000075,0x000300f7,0x0000007c, 0x0000007c,0x00000001,0x00050051,0x00000006,0x00000087,0x0000007c,0x00000002,0x00050051,
0x00000000,0x000400fa,0x0000007a,0x0000007b,0x0000007c,0x000200f8,0x0000007b,0x000200fe, 0x00000006,0x00000088,0x00000080,0x00000000,0x00050051,0x00000006,0x00000089,0x00000080,
0x0000007d,0x000200f8,0x0000007c,0x0004003d,0x00000080,0x00000083,0x00000082,0x0004003d, 0x00000001,0x00050051,0x00000006,0x0000008a,0x00000080,0x00000002,0x00050051,0x00000006,
0x00000007,0x00000084,0x00000042,0x00050057,0x0000001d,0x00000085,0x00000083,0x00000084, 0x0000008b,0x00000084,0x00000000,0x00050051,0x00000006,0x0000008c,0x00000084,0x00000001,
0x0008004f,0x0000000f,0x00000086,0x00000085,0x00000085,0x00000000,0x00000001,0x00000002, 0x00050051,0x00000006,0x0000008d,0x00000084,0x00000002,0x00060050,0x0000000f,0x0000008e,
0x000200fe,0x00000086,0x000200f8,0x00000058,0x0004003d,0x00000007,0x00000088,0x00000042, 0x00000085,0x00000086,0x00000087,0x00060050,0x0000000f,0x0000008f,0x00000088,0x00000089,
0x000500b8,0x00000071,0x00000089,0x00000088,0x00000070,0x0004009a,0x0000003b,0x0000008a, 0x0000008a,0x00060050,0x0000000f,0x00000090,0x0000008b,0x0000008c,0x0000008d,0x00060050,
0x00000089,0x000400a8,0x0000003b,0x0000008b,0x0000008a,0x000300f7,0x0000008d,0x00000000, 0x00000075,0x00000091,0x0000008e,0x0000008f,0x00000090,0x00040054,0x00000075,0x00000092,
0x000400fa,0x0000008b,0x0000008c,0x0000008d,0x000200f8,0x0000008c,0x0004003d,0x00000007, 0x00000091,0x0003003e,0x00000077,0x00000092,0x0004003d,0x00000075,0x00000095,0x00000077,
0x0000008e,0x00000042,0x000500ba,0x00000071,0x0000008f,0x0000008e,0x00000065,0x0004009a, 0x00050041,0x00000009,0x00000096,0x00000011,0x00000024,0x0004003d,0x00000006,0x00000097,
0x0000003b,0x00000090,0x0000008f,0x000200f9,0x0000008d,0x000200f8,0x0000008d,0x000700f5, 0x00000096,0x00050041,0x00000009,0x00000098,0x00000011,0x0000002b,0x0004003d,0x00000006,
0x0000003b,0x00000091,0x0000008a,0x00000058,0x00000090,0x0000008c,0x000300f7,0x00000093, 0x00000099,0x00000098,0x0004007f,0x00000006,0x0000009a,0x00000099,0x00060050,0x0000000f,
0x00000000,0x000400fa,0x00000091,0x00000092,0x00000093,0x000200f8,0x00000092,0x000200fe, 0x0000009c,0x00000097,0x0000009a,0x0000009b,0x0006000c,0x0000000f,0x0000009d,0x00000001,
0x0000007d,0x000200f8,0x00000093,0x0004003d,0x00000080,0x00000095,0x00000082,0x00050041, 0x00000045,0x0000009c,0x00050091,0x0000000f,0x0000009e,0x00000095,0x0000009d,0x0003003e,
0x00000009,0x00000096,0x00000042,0x00000024,0x0004003d,0x00000006,0x00000097,0x00000096, 0x00000094,0x0000009e,0x0004003d,0x00000075,0x000000a0,0x00000077,0x0004003d,0x00000006,
0x0004003d,0x00000006,0x00000098,0x00000012,0x00050081,0x00000006,0x00000099,0x00000097, 0x000000a1,0x00000012,0x000500b8,0x0000003b,0x000000a2,0x000000a1,0x0000003a,0x000600a9,
0x00000098,0x00050085,0x00000006,0x0000009a,0x00000099,0x0000003a,0x00050041,0x00000009, 0x00000006,0x000000a3,0x000000a2,0x0000009b,0x0000001c,0x00060041,0x00000025,0x000000a4,
0x0000009b,0x00000042,0x0000002b,0x0004003d,0x00000006,0x0000009c,0x0000009b,0x00050050, 0x00000020,0x00000078,0x00000046,0x0004003d,0x00000006,0x000000a5,0x000000a4,0x00050085,
0x00000007,0x0000009d,0x0000009a,0x0000009c,0x00050057,0x0000001d,0x0000009e,0x00000095, 0x00000006,0x000000a6,0x000000a3,0x000000a5,0x00060050,0x0000000f,0x000000a7,0x000000a6,
0x0000009d,0x0008004f,0x0000000f,0x0000009f,0x0000009e,0x0000009e,0x00000000,0x00000001, 0x00000054,0x00000054,0x00050091,0x0000000f,0x000000a8,0x000000a0,0x000000a7,0x0003003e,
0x00000002,0x000200fe,0x0000009f,0x000200f8,0x0000003e,0x00050041,0x000000a5,0x000000a6, 0x0000009f,0x000000a8,0x00050041,0x00000009,0x000000a9,0x00000094,0x00000037,0x0004003d,
0x00000020,0x000000a4,0x0004003d,0x0000001d,0x000000a7,0x000000a6,0x0008004f,0x0000000f, 0x00000006,0x000000aa,0x000000a9,0x000500ba,0x0000003b,0x000000ac,0x000000aa,0x000000ab,
0x000000a8,0x000000a7,0x000000a7,0x00000000,0x00000001,0x00000002,0x00050041,0x000000a5, 0x000300f7,0x000000ae,0x00000000,0x000400fa,0x000000ac,0x000000ad,0x000000ae,0x000200f8,
0x000000aa,0x00000020,0x000000a9,0x0004003d,0x0000001d,0x000000ab,0x000000aa,0x0008004f, 0x000000ad,0x000200fe,0x000000b1,0x000200f8,0x000000ae,0x00060041,0x00000025,0x000000b4,
0x0000000f,0x000000ac,0x000000ab,0x000000ab,0x00000000,0x00000001,0x00000002,0x00050041, 0x00000020,0x0000007d,0x00000046,0x0004003d,0x00000006,0x000000b5,0x000000b4,0x0004007f,
0x000000a5,0x000000ae,0x00000020,0x000000ad,0x0004003d,0x0000001d,0x000000af,0x000000ae, 0x00000006,0x000000b6,0x000000b5,0x00050041,0x00000009,0x000000b7,0x0000009f,0x00000037,
0x0008004f,0x0000000f,0x000000b0,0x000000af,0x000000af,0x00000000,0x00000001,0x00000002, 0x0004003d,0x00000006,0x000000b8,0x000000b7,0x00050083,0x00000006,0x000000b9,0x000000b6,
0x00050051,0x00000006,0x000000b1,0x000000a8,0x00000000,0x00050051,0x00000006,0x000000b2, 0x000000b8,0x00050041,0x00000009,0x000000ba,0x00000094,0x00000037,0x0004003d,0x00000006,
0x000000a8,0x00000001,0x00050051,0x00000006,0x000000b3,0x000000a8,0x00000002,0x00050051, 0x000000bb,0x000000ba,0x00050088,0x00000006,0x000000bc,0x000000b9,0x000000bb,0x0003003e,
0x00000006,0x000000b4,0x000000ac,0x00000000,0x00050051,0x00000006,0x000000b5,0x000000ac, 0x000000b3,0x000000bc,0x0004003d,0x0000000f,0x000000be,0x0000009f,0x0004003d,0x0000000f,
0x00000001,0x00050051,0x00000006,0x000000b6,0x000000ac,0x00000002,0x00050051,0x00000006, 0x000000bf,0x00000094,0x0004003d,0x00000006,0x000000c0,0x000000b3,0x0005008e,0x0000000f,
0x000000b7,0x000000b0,0x00000000,0x00050051,0x00000006,0x000000b8,0x000000b0,0x00000001, 0x000000c1,0x000000bf,0x000000c0,0x00050081,0x0000000f,0x000000c2,0x000000be,0x000000c1,
0x00050051,0x00000006,0x000000b9,0x000000b0,0x00000002,0x00060050,0x0000000f,0x000000ba, 0x0003003e,0x000000bd,0x000000c2,0x00060041,0x00000025,0x000000c4,0x00000020,0x00000081,
0x000000b1,0x000000b2,0x000000b3,0x00060050,0x0000000f,0x000000bb,0x000000b4,0x000000b5, 0x00000046,0x0004003d,0x00000006,0x000000c5,0x000000c4,0x0003003e,0x000000c3,0x000000c5,
0x000000b6,0x00060050,0x0000000f,0x000000bc,0x000000b7,0x000000b8,0x000000b9,0x00060050, 0x0004003d,0x00000006,0x000000c7,0x000000c3,0x00060041,0x00000025,0x000000c8,0x00000020,
0x000000a1,0x000000bd,0x000000ba,0x000000bb,0x000000bc,0x00040054,0x000000a1,0x000000be, 0x00000036,0x0000002b,0x0004003d,0x00000006,0x000000c9,0x000000c8,0x00050088,0x00000006,
0x000000bd,0x0003003e,0x000000a3,0x000000be,0x0004003d,0x000000a1,0x000000c1,0x000000a3, 0x000000ca,0x000000c7,0x000000c9,0x0003003e,0x000000c6,0x000000ca,0x00050041,0x00000009,
0x00050041,0x00000009,0x000000c2,0x00000011,0x00000024,0x0004003d,0x00000006,0x000000c3, 0x000000cc,0x000000bd,0x00000024,0x0004003d,0x00000006,0x000000cd,0x000000cc,0x0004003d,
0x000000c2,0x00050041,0x00000009,0x000000c4,0x00000011,0x0000002b,0x0004003d,0x00000006, 0x00000006,0x000000ce,0x000000c3,0x00050088,0x00000006,0x000000cf,0x000000cd,0x000000ce,
0x000000c5,0x000000c4,0x0004007f,0x00000006,0x000000c6,0x000000c5,0x00060050,0x0000000f, 0x00050041,0x00000009,0x000000d0,0x000000bd,0x0000002b,0x0004003d,0x00000006,0x000000d1,
0x000000c8,0x000000c3,0x000000c6,0x000000c7,0x0006000c,0x0000000f,0x000000c9,0x00000001, 0x000000d0,0x0004007f,0x00000006,0x000000d2,0x000000d1,0x0004003d,0x00000006,0x000000d3,
0x00000045,0x000000c8,0x00050091,0x0000000f,0x000000ca,0x000000c1,0x000000c9,0x0003003e, 0x000000c6,0x00050088,0x00000006,0x000000d4,0x000000d2,0x000000d3,0x00050050,0x00000007,
0x000000c0,0x000000ca,0x00050041,0x000000a5,0x000000cd,0x00000020,0x000000cc,0x0004003d, 0x000000d5,0x000000cf,0x000000d4,0x0005008e,0x00000007,0x000000d6,0x000000d5,0x0000003a,
0x0000001d,0x000000ce,0x000000cd,0x0008004f,0x0000000f,0x000000cf,0x000000ce,0x000000ce, 0x00050050,0x00000007,0x000000d7,0x0000003a,0x0000003a,0x00050081,0x00000007,0x000000d8,
0x00000001,0x00000002,0x00000003,0x0004003d,0x000000a1,0x000000d0,0x000000a3,0x0004003d, 0x000000d6,0x000000d7,0x0003003e,0x000000cb,0x000000d8,0x0004003d,0x00000007,0x000000d9,
0x00000006,0x000000d1,0x00000012,0x000500b8,0x0000003b,0x000000d2,0x000000d1,0x0000003a, 0x000000cb,0x000500b8,0x00000056,0x000000da,0x000000d9,0x00000055,0x0004009a,0x0000003b,
0x000600a9,0x00000006,0x000000d3,0x000000d2,0x000000c7,0x0000001c,0x00060041,0x00000025, 0x000000db,0x000000da,0x000400a8,0x0000003b,0x000000dc,0x000000db,0x000300f7,0x000000de,
0x000000d4,0x00000020,0x000000a4,0x00000046,0x0004003d,0x00000006,0x000000d5,0x000000d4, 0x00000000,0x000400fa,0x000000dc,0x000000dd,0x000000de,0x000200f8,0x000000dd,0x0004003d,
0x00050085,0x00000006,0x000000d6,0x000000d3,0x000000d5,0x00060050,0x0000000f,0x000000d7, 0x00000007,0x000000df,0x000000cb,0x000500ba,0x00000056,0x000000e0,0x000000df,0x0000005d,
0x000000d6,0x0000006f,0x0000006f,0x00050091,0x0000000f,0x000000d8,0x000000d0,0x000000d7, 0x0004009a,0x0000003b,0x000000e1,0x000000e0,0x000200f9,0x000000de,0x000200f8,0x000000de,
0x00050081,0x0000000f,0x000000d9,0x000000cf,0x000000d8,0x0003003e,0x000000cb,0x000000d9, 0x000700f5,0x0000003b,0x000000e2,0x000000db,0x000000ae,0x000000e1,0x000000dd,0x000300f7,
0x00050041,0x00000009,0x000000da,0x000000c0,0x00000037,0x0004003d,0x00000006,0x000000db, 0x000000e4,0x00000000,0x000400fa,0x000000e2,0x000000e3,0x000000e4,0x000200f8,0x000000e3,
0x000000da,0x000500ba,0x0000003b,0x000000dd,0x000000db,0x000000dc,0x000300f7,0x000000df, 0x000200fe,0x000000b1,0x000200f8,0x000000e4,0x0004003d,0x00000066,0x000000e6,0x00000068,
0x00000000,0x000400fa,0x000000dd,0x000000de,0x000000df,0x000200f8,0x000000de,0x000200fe, 0x0004003d,0x00000007,0x000000e7,0x000000cb,0x00050057,0x0000001d,0x000000e8,0x000000e6,
0x000000e2,0x000200f8,0x000000df,0x00060041,0x00000025,0x000000e5,0x00000020,0x000000a9, 0x000000e7,0x0008004f,0x0000000f,0x000000e9,0x000000e8,0x000000e8,0x00000000,0x00000001,
0x00000046,0x0004003d,0x00000006,0x000000e6,0x000000e5,0x0004007f,0x00000006,0x000000e7, 0x00000002,0x000200fe,0x000000e9,0x00010038
0x000000e6,0x00050041,0x00000009,0x000000e8,0x000000cb,0x00000037,0x0004003d,0x00000006,
0x000000e9,0x000000e8,0x00050083,0x00000006,0x000000ea,0x000000e7,0x000000e9,0x00050041,
0x00000009,0x000000eb,0x000000c0,0x00000037,0x0004003d,0x00000006,0x000000ec,0x000000eb,
0x00050088,0x00000006,0x000000ed,0x000000ea,0x000000ec,0x0003003e,0x000000e4,0x000000ed,
0x0004003d,0x00000006,0x000000ee,0x000000e4,0x000500bc,0x0000003b,0x000000ef,0x000000ee,
0x0000006f,0x000300f7,0x000000f1,0x00000000,0x000400fa,0x000000ef,0x000000f0,0x000000f1,
0x000200f8,0x000000f0,0x000200fe,0x000000e2,0x000200f8,0x000000f1,0x0004003d,0x0000000f,
0x000000f4,0x000000cb,0x0004003d,0x0000000f,0x000000f5,0x000000c0,0x0004003d,0x00000006,
0x000000f6,0x000000e4,0x0005008e,0x0000000f,0x000000f7,0x000000f5,0x000000f6,0x00050081,
0x0000000f,0x000000f8,0x000000f4,0x000000f7,0x0003003e,0x000000f3,0x000000f8,0x00060041,
0x00000025,0x000000fa,0x00000020,0x000000ad,0x00000046,0x0004003d,0x00000006,0x000000fb,
0x000000fa,0x0003003e,0x000000f9,0x000000fb,0x0004003d,0x00000006,0x000000fd,0x000000f9,
0x00060041,0x00000025,0x000000fe,0x00000020,0x00000036,0x0000002b,0x0004003d,0x00000006,
0x000000ff,0x000000fe,0x00050088,0x00000006,0x00000100,0x000000fd,0x000000ff,0x0003003e,
0x000000fc,0x00000100,0x00050041,0x00000009,0x00000102,0x000000f3,0x00000024,0x0004003d,
0x00000006,0x00000103,0x00000102,0x0004003d,0x00000006,0x00000104,0x000000f9,0x00050088,
0x00000006,0x00000105,0x00000103,0x00000104,0x00050041,0x00000009,0x00000106,0x000000f3,
0x0000002b,0x0004003d,0x00000006,0x00000107,0x00000106,0x0004007f,0x00000006,0x00000108,
0x00000107,0x0004003d,0x00000006,0x00000109,0x000000fc,0x00050088,0x00000006,0x0000010a,
0x00000108,0x00000109,0x00050050,0x00000007,0x0000010b,0x00000105,0x0000010a,0x0005008e,
0x00000007,0x0000010c,0x0000010b,0x0000003a,0x00050050,0x00000007,0x0000010d,0x0000003a,
0x0000003a,0x00050081,0x00000007,0x0000010e,0x0000010c,0x0000010d,0x0003003e,0x00000101,
0x0000010e,0x0004003d,0x00000007,0x0000010f,0x00000101,0x000500b8,0x00000071,0x00000110,
0x0000010f,0x00000070,0x0004009a,0x0000003b,0x00000111,0x00000110,0x000400a8,0x0000003b,
0x00000112,0x00000111,0x000300f7,0x00000114,0x00000000,0x000400fa,0x00000112,0x00000113,
0x00000114,0x000200f8,0x00000113,0x0004003d,0x00000007,0x00000115,0x00000101,0x000500ba,
0x00000071,0x00000116,0x00000115,0x00000065,0x0004009a,0x0000003b,0x00000117,0x00000116,
0x000200f9,0x00000114,0x000200f8,0x00000114,0x000700f5,0x0000003b,0x00000118,0x00000111,
0x000000f1,0x00000117,0x00000113,0x000300f7,0x0000011a,0x00000000,0x000400fa,0x00000118,
0x00000119,0x0000011a,0x000200f8,0x00000119,0x000200fe,0x000000e2,0x000200f8,0x0000011a,
0x0004003d,0x00000080,0x0000011c,0x00000082,0x0004003d,0x00000007,0x0000011d,0x00000101,
0x00050057,0x0000001d,0x0000011e,0x0000011c,0x0000011d,0x0008004f,0x0000000f,0x0000011f,
0x0000011e,0x0000011e,0x00000000,0x00000001,0x00000002,0x000200fe,0x0000011f,0x00010038
}; };
+1 -34
View File
@@ -218,8 +218,6 @@ struct surface {
enum surface_role role; enum surface_role role;
struct wl_resource *idle_buffer; struct wl_resource *idle_buffer;
struct wl_listener idle_buffer_destroy; struct wl_listener idle_buffer_destroy;
uint32_t *idle_px;
int idle_w, idle_h;
struct wl_resource *xdg_surface, *xdg_toplevel; struct wl_resource *xdg_surface, *xdg_toplevel;
struct wl_resource *viewport; struct wl_resource *viewport;
@@ -901,30 +899,8 @@ static void cursor_publish_buffer(struct surface *s, struct wl_resource *buffer)
g_cursor_shown = s; g_cursor_shown = s;
} }
static void surface_forget_idle_px(struct surface *s) {
free(s->idle_px);
s->idle_px = NULL;
s->idle_w = s->idle_h = 0;
}
static void on_idle_buffer_destroyed(struct wl_listener *l, void *data) { static void on_idle_buffer_destroyed(struct wl_listener *l, void *data) {
struct surface *s = wl_container_of(l, s, idle_buffer_destroy); struct surface *s = wl_container_of(l, s, idle_buffer_destroy);
struct wl_shm_buffer *shm = wl_shm_buffer_get(s->idle_buffer);
if (shm) {
int32_t w = wl_shm_buffer_get_width(shm), h = wl_shm_buffer_get_height(shm);
int32_t stride = wl_shm_buffer_get_stride(shm);
uint32_t *px = w > 0 && h > 0 && (int64_t)w * h <= CURSOR_MAX_PX && (int64_t)stride >= (int64_t)w * 4
? realloc(s->idle_px, (size_t)w * h * 4) : NULL;
if (px) {
wl_shm_buffer_begin_access(shm);
const uint8_t *src = wl_shm_buffer_get_data(shm);
for (int y = 0; y < h; y++) memcpy(&px[(size_t)y * w], src + (size_t)y * stride, (size_t)w * 4);
wl_shm_buffer_end_access(shm);
s->idle_px = px;
s->idle_w = w;
s->idle_h = h;
}
}
wl_list_remove(&s->idle_buffer_destroy.link); wl_list_remove(&s->idle_buffer_destroy.link);
wl_list_init(&s->idle_buffer_destroy.link); wl_list_init(&s->idle_buffer_destroy.link);
s->idle_buffer = NULL; s->idle_buffer = NULL;
@@ -951,7 +927,6 @@ static struct wl_resource *surface_take_idle(struct surface *s) {
} }
static void surface_drop_idle(struct surface *s) { static void surface_drop_idle(struct surface *s) {
surface_forget_idle_px(s);
struct wl_resource *buffer = surface_take_idle(s); struct wl_resource *buffer = surface_take_idle(s);
if (buffer) wl_buffer_send_release(buffer); if (buffer) wl_buffer_send_release(buffer);
} }
@@ -1080,7 +1055,6 @@ static void surface_resource_destroy(struct wl_resource *r) {
if (g_cursor_surface == s) { g_cursor_surface = NULL; cursor_publish_hidden(); } if (g_cursor_surface == s) { g_cursor_surface = NULL; cursor_publish_hidden(); }
if (g_cursor_shown == s) g_cursor_shown = NULL; if (g_cursor_shown == s) g_cursor_shown = NULL;
surface_take_idle(s); surface_take_idle(s);
surface_forget_idle_px(s);
if (g_grab == s) g_grab = NULL; if (g_grab == s) g_grab = NULL;
if (g_key_target == s) g_key_target = NULL; if (g_key_target == s) g_key_target = NULL;
if (g_ime_click == s) g_ime_click = NULL; if (g_ime_click == s) g_ime_click = NULL;
@@ -2068,9 +2042,6 @@ static void pointer_set_cursor(struct wl_client *c, struct wl_resource *r, uint3
wl_buffer_send_release(buffer); wl_buffer_send_release(buffer);
} else if (g_cursor_shown == s) { } else if (g_cursor_shown == s) {
cursor_publish_shown(); cursor_publish_shown();
} else if (s->idle_px) {
cursor_publish_pixels((const uint8_t *)s->idle_px, s->idle_w, s->idle_h, (size_t)s->idle_w * 4, hx, hy);
g_cursor_shown = s;
} }
} }
static void pointer_release(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); } static void pointer_release(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
@@ -2622,11 +2593,7 @@ static void pointer_input(double x, double y, int relative, uint32_t button, int
uint32_t t = now_ms(); uint32_t t = now_ms();
pointer_focus(target->resource, fx, fy); pointer_focus(target->resource, fx, fy);
// A button-only input must not replay a cached absolute position. A game if (!(k && k->is_lock))
// may have warped its cursor since the last motion (before taking lock,
// or while releasing it), so that replay can become an unintended pan.
// Absolute touch events still carry their position, including on clicks.
if (!(k && k->is_lock) && (!relative || dx != 0 || dy != 0))
for_each_pointer_of(client, sp) wl_pointer_send_motion(sp->ptr, t, fx, fy); for_each_pointer_of(client, sp) wl_pointer_send_motion(sp->ptr, t, fx, fy);
send_relative_motion(client, dx, dy); send_relative_motion(client, dx, dy);
for_each_pointer_of(client, sp) { for_each_pointer_of(client, sp) {
@@ -86,7 +86,7 @@ static int64_t now_ns(void) {
void vkp_framegen_set_engine(int kind) { void vkp_framegen_set_engine(int kind) {
if (kind != VKP_FG_ENGINE_LSFG && kind != VKP_FG_ENGINE_DDFG) kind = VKP_FG_ENGINE_LSFG; if (kind != VKP_FG_ENGINE_LSFG && kind != VKP_FG_ENGINE_WINFG) kind = VKP_FG_ENGINE_LSFG;
atomic_store(&g_kind, kind); atomic_store(&g_kind, kind);
atomic_store(&g_failed_kind, -1); atomic_store(&g_failed_kind, -1);
atomic_store(&g_cfg_dirty, 1); atomic_store(&g_cfg_dirty, 1);
@@ -125,7 +125,7 @@ void vkp_framegen_set_tuning(float flow_scale, float refresh_hz) {
atomic_store(&g_cfg_dirty, 1); atomic_store(&g_cfg_dirty, 1);
} }
void vkp_framegen_set_ddfg_tuning(int model, int perf_preset) { void vkp_framegen_set_winfg_tuning(int model, int perf_preset) {
atomic_store(&g_model, model == 3 ? 3 : 4); atomic_store(&g_model, model == 3 ? 3 : 4);
atomic_store(&g_preset, perf_preset < 0 ? 0 : perf_preset > 2 ? 2 : perf_preset); atomic_store(&g_preset, perf_preset < 0 ? 0 : perf_preset > 2 ? 2 : perf_preset);
atomic_store(&g_cfg_dirty, 1); atomic_store(&g_cfg_dirty, 1);
@@ -180,9 +180,9 @@ void vkp_framegen_device_ready(VkDevice dev, VkQueue queue, uint32_t qfam, int f
g_vk.GetPhysicalDeviceMemoryProperties(g_pd, &g_memprops); g_vk.GetPhysicalDeviceMemoryProperties(g_pd, &g_memprops);
fge_device_ready(g_gipa, g_inst, g_pd, dev, queue, qfam, features_enabled); fge_device_ready(g_gipa, g_inst, g_pd, dev, queue, qfam, features_enabled);
g_dev_ready = vk.CreateImage && vk.CreateImageView && vk.CmdPipelineBarrier; g_dev_ready = vk.CreateImage && vk.CreateImageView && vk.CmdPipelineBarrier;
FGLOG("engines ready on the compositor's device: LSFG Native %s (%s), DD-FG Native %s", FGLOG("engines ready on the compositor's device: LSFG Native %s (%s), Win-FG Native %s",
fge_caps_ok(VKP_FG_ENGINE_LSFG) ? "available" : "unavailable", fge_caps_reason(), fge_caps_ok(VKP_FG_ENGINE_LSFG) ? "available" : "unavailable", fge_caps_reason(),
fge_caps_ok(VKP_FG_ENGINE_DDFG) ? "available" : "unavailable"); fge_caps_ok(VKP_FG_ENGINE_WINFG) ? "available" : "unavailable");
} }
void vkp_framegen_device_lost(void) { g_dev_lost = 1; } void vkp_framegen_device_lost(void) { g_dev_lost = 1; }
@@ -6,14 +6,14 @@
#endif #endif
#include <vulkan/vulkan.h> #include <vulkan/vulkan.h>
enum { VKP_FG_ENGINE_LSFG = 0, VKP_FG_ENGINE_DDFG = 1 }; enum { VKP_FG_ENGINE_LSFG = 0, VKP_FG_ENGINE_WINFG = 1 };
#define VKP_FG_MAX_GENERATIONS 3 #define VKP_FG_MAX_GENERATIONS 3
void vkp_framegen_set_engine(int kind); void vkp_framegen_set_engine(int kind);
void vkp_framegen_set_armed(int armed, int multiplier, int target_fps); void vkp_framegen_set_armed(int armed, int multiplier, int target_fps);
void vkp_framegen_set_lsfg_cache_path(const char *path); void vkp_framegen_set_lsfg_cache_path(const char *path);
void vkp_framegen_set_tuning(float flow_scale, float refresh_hz); void vkp_framegen_set_tuning(float flow_scale, float refresh_hz);
void vkp_framegen_set_ddfg_tuning(int model, int perf_preset); void vkp_framegen_set_winfg_tuning(int model, int perf_preset);
int vkp_framegen_problem(void); int vkp_framegen_problem(void);
const char *vkp_framegen_caps_reason(void); const char *vkp_framegen_caps_reason(void);
void vkp_framegen_stats(float out[6]); void vkp_framegen_stats(float out[6]);
@@ -12,7 +12,7 @@
#include "lsfg/lsfg_engine.h" #include "lsfg/lsfg_engine.h"
#include "lsfg/lsfg_probe.h" #include "lsfg/lsfg_probe.h"
#include "lsfg/lsfg_vkd.h" #include "lsfg/lsfg_vkd.h"
#include "ddfg/ddfg_engine.h" #include "winfg/winfg_engine.h"
#define ELOG(...) __android_log_print(ANDROID_LOG_INFO, "DroidDeckWayland", "framegen: " __VA_ARGS__) #define ELOG(...) __android_log_print(ANDROID_LOG_INFO, "DroidDeckWayland", "framegen: " __VA_ARGS__)
#define ELOGE(...) __android_log_print(ANDROID_LOG_ERROR, "DroidDeckWayland", "framegen: " __VA_ARGS__) #define ELOGE(...) __android_log_print(ANDROID_LOG_ERROR, "DroidDeckWayland", "framegen: " __VA_ARGS__)
@@ -30,7 +30,7 @@ uint32_t g_qfam = 0;
bool g_probed = false, g_ready = false; bool g_probed = false, g_ready = false;
std::unique_ptr<lsfg::Engine> g_lsfg; std::unique_ptr<lsfg::Engine> g_lsfg;
std::unique_ptr<ddfg::Engine> g_ddfg; std::unique_ptr<winfg::Engine> g_winfg;
int g_kind = -1; int g_kind = -1;
char g_build[96] = ""; char g_build[96] = "";
@@ -143,15 +143,15 @@ int fge_start(int kind, const char *cache_path) {
fge_stop(); fge_stop();
if (!g_ready) return -1; if (!g_ready) return -1;
if (kind == 1) { if (kind == 1) {
auto e = std::make_unique<ddfg::Engine>(); auto e = std::make_unique<winfg::Engine>();
if (!e->init(g_table, g_pd, g_dev, g_qfam, g_queue)) { if (!e->init(g_table, g_pd, g_dev, g_qfam, g_queue)) {
ELOGE("ddfg-native: engine init failed"); ELOGE("winfg-native: engine init failed");
return -1; return -1;
} }
g_ddfg = std::move(e); g_winfg = std::move(e);
g_kind = 1; g_kind = 1;
#if defined(DDFG_UPSTREAM) && defined(DDFG_CHAIN_HASH) #if defined(WINFG_UPSTREAM) && defined(WINFG_CHAIN_HASH)
std::snprintf(g_build, sizeof(g_build), "chain %s, src %s", DDFG_UPSTREAM, DDFG_CHAIN_HASH); std::snprintf(g_build, sizeof(g_build), "chain %s, src %s", WINFG_UPSTREAM, WINFG_CHAIN_HASH);
#else #else
std::snprintf(g_build, sizeof(g_build), "embedded chain"); std::snprintf(g_build, sizeof(g_build), "embedded chain");
#endif #endif
@@ -176,46 +176,46 @@ int fge_start(int kind, const char *cache_path) {
} }
void fge_stop(void) { void fge_stop(void) {
if ((g_lsfg || g_ddfg) && g_table.DeviceWaitIdle && g_dev) g_table.DeviceWaitIdle(g_dev); if ((g_lsfg || g_winfg) && g_table.DeviceWaitIdle && g_dev) g_table.DeviceWaitIdle(g_dev);
g_lsfg.reset(); g_lsfg.reset();
g_ddfg.reset(); g_winfg.reset();
g_kind = -1; g_kind = -1;
} }
int fge_unavailable(void) { int fge_unavailable(void) {
if (g_kind == 1) return g_ddfg && g_ddfg->unavailable() ? 1 : 0; if (g_kind == 1) return g_winfg && g_winfg->unavailable() ? 1 : 0;
return g_lsfg && g_lsfg->unavailable() ? 1 : 0; return g_lsfg && g_lsfg->unavailable() ? 1 : 0;
} }
void fge_configure(uint32_t multiplier, uint32_t target_fps, float flow_scale, float refresh_hz, void fge_configure(uint32_t multiplier, uint32_t target_fps, float flow_scale, float refresh_hz,
int model, int perf_preset) { int model, int perf_preset) {
if (multiplier < 2) multiplier = 2; if (multiplier < 2) multiplier = 2;
if (g_kind == 1 && g_ddfg) g_ddfg->configure(multiplier, model, perf_preset, flow_scale); if (g_kind == 1 && g_winfg) g_winfg->configure(multiplier, model, perf_preset, flow_scale);
else if (g_lsfg) g_lsfg->configure(multiplier, target_fps, flow_scale, refresh_hz); else if (g_lsfg) g_lsfg->configure(multiplier, target_fps, flow_scale, refresh_hz);
} }
int fge_prepare(uint32_t w, uint32_t h, VkFormat fmt) { int fge_prepare(uint32_t w, uint32_t h, VkFormat fmt) {
if (g_kind == 1) return g_ddfg && g_ddfg->prepare(w, h, fmt) ? 1 : 0; if (g_kind == 1) return g_winfg && g_winfg->prepare(w, h, fmt) ? 1 : 0;
if (!g_lsfg) return 0; if (!g_lsfg) return 0;
g_lsfg->setGuestExtent(w, h); g_lsfg->setGuestExtent(w, h);
return g_lsfg->prepare(w, h, fmt) ? 1 : 0; return g_lsfg->prepare(w, h, fmt) ? 1 : 0;
} }
uint32_t fge_plan(uint32_t capacity, uint64_t source_frames, float presented_rate) { uint32_t fge_plan(uint32_t capacity, uint64_t source_frames, float presented_rate) {
if (g_kind == 1) return g_ddfg ? g_ddfg->plan(capacity) : 0; if (g_kind == 1) return g_winfg ? g_winfg->plan(capacity) : 0;
if (!g_lsfg) return 0; if (!g_lsfg) return 0;
g_lsfg->setPresentedRate(presented_rate); g_lsfg->setPresentedRate(presented_rate);
return g_lsfg->plan(capacity, source_frames); return g_lsfg->plan(capacity, source_frames);
} }
void fge_process(VkCommandBuffer cmd, VkImage source, uint32_t w, uint32_t h, uint32_t gens) { void fge_process(VkCommandBuffer cmd, VkImage source, uint32_t w, uint32_t h, uint32_t gens) {
if (g_kind == 1) { if (g_ddfg) g_ddfg->process(cmd, source, w, h, gens); return; } if (g_kind == 1) { if (g_winfg) g_winfg->process(cmd, source, w, h, gens); return; }
if (g_lsfg) g_lsfg->process(cmd, source, w, h, gens); if (g_lsfg) g_lsfg->process(cmd, source, w, h, gens);
} }
void fge_generate(VkCommandBuffer cmd, uint32_t g, uint32_t count, VkImage img, VkImageView view, void fge_generate(VkCommandBuffer cmd, uint32_t g, uint32_t count, VkImage img, VkImageView view,
uint32_t w, uint32_t h) { uint32_t w, uint32_t h) {
if (g_kind == 1) { if (g_ddfg) g_ddfg->generateInto(cmd, g, count, img, view, w, h); return; } if (g_kind == 1) { if (g_winfg) g_winfg->generateInto(cmd, g, count, img, view, w, h); return; }
if (g_lsfg) g_lsfg->generateInto(cmd, g, g, img, view, w, h); if (g_lsfg) g_lsfg->generateInto(cmd, g, g, img, view, w, h);
} }
@@ -232,7 +232,7 @@ void fge_telemetry(float *accepted, float *source_rate, float *thermal) {
} }
} }
const char *fge_engine_name(int kind) { return kind == 1 ? "DD-FG Native" : "LSFG Native"; } const char *fge_engine_name(int kind) { return kind == 1 ? "Win-FG Native" : "LSFG Native"; }
const char *fge_build_info(void) { return g_build; } const char *fge_build_info(void) { return g_build; }
} }
@@ -34,5 +34,5 @@ void fge_forget_targets(void) {}
void fge_telemetry(float *accepted, float *source_rate, float *thermal) { void fge_telemetry(float *accepted, float *source_rate, float *thermal) {
*accepted = 0.0f; *source_rate = 0.0f; *thermal = -1.0f; *accepted = 0.0f; *source_rate = 0.0f; *thermal = -1.0f;
} }
const char *fge_engine_name(int kind) { return kind == 1 ? "DD-FG Native" : "LSFG Native"; } const char *fge_engine_name(int kind) { return kind == 1 ? "Win-FG Native" : "LSFG Native"; }
const char *fge_build_info(void) { return "stub"; } const char *fge_build_info(void) { return "stub"; }
@@ -31,10 +31,10 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetFrameGenTuning(JN
} }
JNIEXPORT void JNICALL JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetDdFgTuning(JNIEnv *env, jclass clazz, Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetWinFgTuning(JNIEnv *env, jclass clazz,
jint model, jint perfPreset) { jint model, jint perfPreset) {
(void)env; (void)clazz; (void)env; (void)clazz;
vkp_framegen_set_ddfg_tuning((int)model, (int)perfPreset); vkp_framegen_set_winfg_tuning((int)model, (int)perfPreset);
} }
JNIEXPORT jint JNICALL JNIEXPORT jint JNICALL
@@ -1,59 +0,0 @@
#define _POSIX_C_SOURCE 200809L
#include "spatialpose_shm.h"
#include <jni.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdatomic.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
static pthread_mutex_t spatial_lock = PTHREAD_MUTEX_INITIALIZER;
static struct droiddeck_spatialpose *shared;
JNIEXPORT jboolean JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetSpatialFile(
JNIEnv *env, jclass clazz, jstring path) {
(void)clazz;
pthread_mutex_lock(&spatial_lock);
if (!shared && path) {
const char *name = (*env)->GetStringUTFChars(env, path, NULL);
if (name) {
int fd = open(name, O_RDWR | O_CREAT | O_CLOEXEC, 0600);
(*env)->ReleaseStringUTFChars(env, path, name);
if (fd >= 0) {
if (ftruncate(fd, sizeof(*shared)) == 0) {
void *p = mmap(NULL, sizeof(*shared), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (p != MAP_FAILED) {
shared = p;
memset(shared, 0, sizeof(*shared));
shared->magic = DROIDDECK_SPATIALPOSE_MAGIC;
shared->version = DROIDDECK_SPATIALPOSE_VERSION;
shared->size = sizeof(*shared);
}
}
close(fd);
}
}
}
jboolean ready = shared != NULL;
pthread_mutex_unlock(&spatial_lock);
return ready;
}
JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativePublishSpatial(
JNIEnv *env, jclass clazz, jobject buffer) {
(void)clazz;
if (!buffer || (*env)->GetDirectBufferCapacity(env, buffer) != sizeof(*shared)) return;
const struct droiddeck_spatialpose *src = (*env)->GetDirectBufferAddress(env, buffer);
if (!src || src->magic != DROIDDECK_SPATIALPOSE_MAGIC || src->version != DROIDDECK_SPATIALPOSE_VERSION ||
src->size != sizeof(*shared)) return;
pthread_mutex_lock(&spatial_lock);
if (shared) {
unsigned seq = __atomic_load_n(&shared->seq, __ATOMIC_RELAXED);
__atomic_store_n(&shared->seq, seq | 1u, __ATOMIC_RELAXED);
__atomic_thread_fence(__ATOMIC_RELEASE);
memcpy((char *)shared + 16, (const char *)src + 16, sizeof(*shared) - 16);
__atomic_store_n(&shared->seq, (seq | 1u) + 1u, __ATOMIC_RELEASE);
}
pthread_mutex_unlock(&spatial_lock);
}
@@ -1,33 +0,0 @@
#ifndef DROIDDECK_SPATIALPOSE_SHM_H
#define DROIDDECK_SPATIALPOSE_SHM_H
#include <stdint.h>
#define DROIDDECK_SPATIALPOSE_MAGIC 0x53504444u
#define DROIDDECK_SPATIALPOSE_VERSION 4u
#define DROIDDECK_SPATIALPOSE_FILE "droiddeck-spatialpose"
enum { DD_SPATIAL_ACTIVE = 1u, DD_SPATIAL_HANDS = 2u, DD_SPATIAL_JOYCONS = 4u, DD_SPATIAL_STEADY_AIM = 8u, DD_SPATIAL_VALID = 1u };
enum { DD_SPATIAL_TRIGGER_VALID = 2u, DD_SPATIAL_GRIP_VALID = 4u };
struct dd_spatial_pose {
int64_t time_ns;
float position[3];
float rotation[4];
uint32_t flags;
};
struct dd_spatial_hand {
struct dd_spatial_pose pose;
float trigger;
uint32_t grip;
};
struct droiddeck_spatialpose {
uint32_t magic, version, size, seq;
uint64_t connection, origin;
uint32_t flags, input_epochs;
struct dd_spatial_pose head;
struct dd_spatial_hand hands[2];
};
#ifdef __cplusplus
static_assert(sizeof(dd_spatial_pose) == 40, "spatial pose ABI");
static_assert(sizeof(droiddeck_spatialpose) == 176, "spatial snapshot ABI");
#else
_Static_assert(sizeof(struct droiddeck_spatialpose) == 176, "spatial snapshot ABI");
#endif
#endif
@@ -649,14 +649,3 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeRaisePriority(JNIEnv
int after = getpriority(PRIO_PROCESS, (id_t)tid); int after = getpriority(PRIO_PROCESS, (id_t)tid);
return after == -1 && errno != 0 ? 100 : after; return after == -1 && errno != 0 ? 100 : after;
} }
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetCardboardSpatialPose(JNIEnv *env, jclass clazz,
jfloatArray rot, jfloatArray pos, jboolean live) {
(void)clazz;
if (!rot || !pos || (*env)->GetArrayLength(env, rot) != 9 || (*env)->GetArrayLength(env, pos) != 3) return;
float m[9], p[3];
(*env)->GetFloatArrayRegion(env, rot, 0, 9, m);
(*env)->GetFloatArrayRegion(env, pos, 0, 3, p);
vkp_cardboard_set_spatial_pose(m, p, live ? 1 : 0);
}
@@ -16,48 +16,22 @@ class App : Application() {
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
// Helper processes must not initialize the main USB provider or guest graphics context. // The restart screen must not initialize USB, guest processes, or another graphics context.
val process = if (android.os.Build.VERSION.SDK_INT >= 28) Application.getProcessName() val process = (getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager)
else (getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager) .runningAppProcesses?.firstOrNull { it.pid == android.os.Process.myPid() }?.processName
.runningAppProcesses?.firstOrNull { it.pid == android.os.Process.myPid() }?.processName if (process == "$packageName:vr_recovery") return
if (process == "$packageName:xboxlogin") {
if (android.os.Build.VERSION.SDK_INT >= 28) android.webkit.WebView.setDataDirectorySuffix("xbox")
return
}
if (process == "$packageName:vr_recovery" || process == "$packageName:rgb_diagnostic") return
CrashHandler.install(this) CrashHandler.install(this)
com.droiddeck.launcher.session.QuestExperimental.initialize(this) com.droiddeck.launcher.session.QuestExperimental.initialize(this)
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this) com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
com.droiddeck.launcher.update.AppUpdates.init(this) com.droiddeck.launcher.update.AppUpdates.init(this)
com.droiddeck.launcher.core.DownloadSource.init(this) com.droiddeck.launcher.core.DownloadSource.init(this)
prefetchAddonPacks()
GpuClockPin.clearLeftover(this) GpuClockPin.clearLeftover(this)
com.droiddeck.launcher.glasses.Glasses.init(this) com.droiddeck.launcher.glasses.Glasses.init(this)
com.droiddeck.launcher.glasses.GlassesMenuMirror.initialize(this)
BwrapSpawner.start(this) BwrapSpawner.start(this)
com.droiddeck.launcher.frontend.GameFileSync.start(this) com.droiddeck.launcher.frontend.GameFileSync.start(this)
com.droiddeck.launcher.stores.StoresState.init(this) com.droiddeck.launcher.stores.StoresState.init(this)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.gog.GogBackend) com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.gog.GogBackend)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.epic.EpicBackend) com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.epic.EpicBackend)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.amazon.AmazonBackend) com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.amazon.AmazonBackend)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.itch.ItchBackend)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.xbox.XboxBackend)
}
/** Fetches the packs an existing setup already relies on, so the first use after an update does not wait. */
private fun prefetchAddonPacks() {
val app = this
Thread({
runCatching {
if (com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app).isDirectory) {
com.droiddeck.launcher.core.AddonPack.PROOT.ensure(app)
com.droiddeck.launcher.core.AddonPack.DIRECTAUDIO.ensure(app)
}
if (com.droiddeck.launcher.stores.gog.GogComet.enabled(app)) com.droiddeck.launcher.core.AddonPack.COMET.ensure(app)
if (com.droiddeck.launcher.stores.StoreAccounts.signedInAs(app, com.droiddeck.launcher.stores.Store.XBOX) != null)
com.droiddeck.launcher.core.AddonPack.XBOX.ensure(app)
com.droiddeck.launcher.handtracking.HandTracking.load(app)
}.onFailure { android.util.Log.w("App", "add-on pack prefetch failed", it) }
}, "addon-packs").start()
} }
} }
@@ -12,7 +12,6 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableIntStateOf
import com.droiddeck.launcher.gpu.AutoDriverTrial import com.droiddeck.launcher.gpu.AutoDriverTrial
import com.droiddeck.launcher.gpu.AutoPicks
import com.droiddeck.launcher.gpu.DriverBundle import com.droiddeck.launcher.gpu.DriverBundle
import com.droiddeck.launcher.gpu.DriverPairs import com.droiddeck.launcher.gpu.DriverPairs
import com.droiddeck.launcher.gpu.GpuInfo import com.droiddeck.launcher.gpu.GpuInfo
@@ -180,7 +179,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
val lm = LinuxVulkanDriverManager(activity) val lm = LinuxVulkanDriverManager(activity)
val td = TurnipDriver(activity) val td = TurnipDriver(activity)
val pairs = DriverPairs.from(TurnipReleases.cached(activity)) val pairs = DriverPairs.from(TurnipReleases.cached(activity))
val recommended = if (QuestExperimental.isSupported()) null else recommendedKey(pairs) val recommended = if (QuestExperimental.isSupported()) null else DriverPairs.recommendedKey(gpu, pairs)
pairRows = pairs.map { p -> pairRows = pairs.map { p ->
val bundle = p.bundle?.let { installedBundle(it) } val bundle = p.bundle?.let { installedBundle(it) }
val displayId = if (p.bundle != null) bundle?.androidId else p.display?.let { TurnipReleases.installedId(activity, it, td::isInstalled) } val displayId = if (p.bundle != null) bundle?.androidId else p.display?.let { TurnipReleases.installedId(activity, it, td::isInstalled) }
@@ -197,11 +196,6 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
}.sortedByDescending { it.recommended } }.sortedByDescending { it.recommended }
} }
private fun recommendedKey(pairs: List<DriverPairs.DriverPair>) = DriverPairs.recommendedKey(
gpu, pairs, TurnipReleases.autoPicks(activity), AutoDriverTrial.bad(activity),
blob = AutoPicks.blobVersion(com.droiddeck.launcher.gpu.VulkanInfo.cachedOrNull()?.get("driver_version")),
)
fun chooseMode(next: String) { fun chooseMode(next: String) {
pairModeOpen = next == GPU_MODE_PAIR pairModeOpen = next == GPU_MODE_PAIR
setMode(auto = next == GPU_MODE_AUTO, mix = next == GPU_MODE_MIX) setMode(auto = next == GPU_MODE_AUTO, mix = next == GPU_MODE_MIX)
@@ -261,13 +255,12 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
Thread({ Thread({
val problem = if (force || releasesStale()) runCatching { TurnipReleases.refresh(activity) }.exceptionOrNull()?.message else null val problem = if (force || releasesStale()) runCatching { TurnipReleases.refresh(activity) }.exceptionOrNull()?.message else null
val holdBack = !force && com.droiddeck.launcher.frontend.AutoComponents.constrained(activity) val holdBack = !force && com.droiddeck.launcher.frontend.AutoComponents.constrained(activity)
runCatching { com.droiddeck.launcher.gpu.VulkanInfo.query() }
ui.post { ui.post {
releaseChecking = false releaseChecking = false
refreshReleaseRows() refreshReleaseRows()
refreshPairs() refreshPairs()
val pairs = DriverPairs.from(TurnipReleases.cached(activity)) val pairs = DriverPairs.from(TurnipReleases.cached(activity))
val key = recommendedKey(pairs) val key = DriverPairs.recommendedKey(gpu, pairs)
val pair = pairs.firstOrNull { it.key == key } val pair = pairs.firstOrNull { it.key == key }
val row = pairRows.firstOrNull { it.key == key } val row = pairRows.firstOrNull { it.key == key }
when { when {
@@ -1,42 +0,0 @@
package com.droiddeck.launcher
import android.content.ComponentName
import android.content.Context
import android.content.pm.PackageManager
object LauncherIcon {
const val DARK = "dark"
const val LIGHT = "light"
private val aliases = linkedMapOf(DARK to "com.droiddeck.launcher.LauncherDark", LIGHT to "com.droiddeck.launcher.LauncherLight")
val options: List<Pair<String, Int>> = listOf(
DARK to R.string.setup_launcher_icon_dark,
LIGHT to R.string.setup_launcher_icon_light,
)
private fun component(context: Context, style: String) =
ComponentName(context, aliases.getValue(style))
private fun enabled(context: Context, style: String): Boolean =
when (context.packageManager.getComponentEnabledSetting(component(context, style))) {
PackageManager.COMPONENT_ENABLED_STATE_ENABLED -> true
PackageManager.COMPONENT_ENABLED_STATE_DEFAULT -> style == DARK
else -> false
}
fun current(context: Context): String = aliases.keys.firstOrNull { enabled(context, it) } ?: DARK
fun activity(context: Context): ComponentName = component(context, current(context))
fun set(context: Context, style: String) {
if (style !in aliases || style == current(context)) return
val pm = context.packageManager
pm.setComponentEnabledSetting(component(context, style),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP)
aliases.keys.filter { it != style }.forEach {
pm.setComponentEnabledSetting(component(context, it),
PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP)
}
}
}
@@ -109,7 +109,6 @@ class MainActivity : ComponentActivity() {
private var frameGenLabel by mutableStateOf("") private var frameGenLabel by mutableStateOf("")
private var lossless by mutableStateOf(Lossless.State.NONE) private var lossless by mutableStateOf(Lossless.State.NONE)
private var showRemove by mutableStateOf(false) private var showRemove by mutableStateOf(false)
private var showRuntimeActions by mutableStateOf<LinuxRuntimeInstaller.Release?>(null)
private var pendingSwitch by mutableStateOf<Intent?>(null) private var pendingSwitch by mutableStateOf<Intent?>(null)
private var switchingTo: Intent? = null private var switchingTo: Intent? = null
private var switchPoll: Runnable? = null private var switchPoll: Runnable? = null
@@ -124,7 +123,6 @@ class MainActivity : ComponentActivity() {
private var steamController by mutableStateOf(SessionPrefs.CONTROLLER_DECK) private var steamController by mutableStateOf(SessionPrefs.CONTROLLER_DECK)
private var showComponents by mutableStateOf(false) private var showComponents by mutableStateOf(false)
private var focusComponentsContent by mutableStateOf(true) private var focusComponentsContent by mutableStateOf(true)
private var componentsGameKey by mutableStateOf<String?>(null)
private var showMapping by mutableStateOf(false) private var showMapping by mutableStateOf(false)
private var saveBusy: String? = null private var saveBusy: String? = null
private var onSavePicked: ((File) -> Unit)? = null private var onSavePicked: ((File) -> Unit)? = null
@@ -166,7 +164,6 @@ class MainActivity : ComponentActivity() {
private var downloadMirror by mutableStateOf("") private var downloadMirror by mutableStateOf("")
private var downloadPrefix by mutableStateOf("") private var downloadPrefix by mutableStateOf("")
private var animationsEnabled by mutableStateOf(true) private var animationsEnabled by mutableStateOf(true)
private var launcherIcon by mutableStateOf(LauncherIcon.DARK)
private var gameStoresEnabled by mutableStateOf(true) private var gameStoresEnabled by mutableStateOf(true)
private var gameStoresSpeedTier by mutableStateOf("fast") private var gameStoresSpeedTier by mutableStateOf("fast")
private var storesOpenTab by mutableStateOf(SessionPrefs.STORES_OPEN_LIBRARY) private var storesOpenTab by mutableStateOf(SessionPrefs.STORES_OPEN_LIBRARY)
@@ -374,7 +371,6 @@ class MainActivity : ComponentActivity() {
private var resolution by mutableStateOf(com.droiddeck.launcher.session.SessionDisplay.DEFAULT_RESOLUTION) private var resolution by mutableStateOf(com.droiddeck.launcher.session.SessionDisplay.DEFAULT_RESOLUTION)
private var fexPreset by mutableStateOf("") private var fexPreset by mutableStateOf("")
private var forceSsbs by mutableStateOf(false) private var forceSsbs by mutableStateOf(false)
private var steamClientArch by mutableStateOf("arm64")
private var runSteamAtStartup by mutableStateOf(false) private var runSteamAtStartup by mutableStateOf(false)
private var bootMovie by mutableStateOf(com.droiddeck.launcher.session.BootMovie.DROIDDECK_30) private var bootMovie by mutableStateOf(com.droiddeck.launcher.session.BootMovie.DROIDDECK_30)
private var bootMovieSound by mutableStateOf(true) private var bootMovieSound by mutableStateOf(true)
@@ -403,13 +399,11 @@ class MainActivity : ComponentActivity() {
} }
private var romsDir by mutableStateOf<String?>(null) private var romsDir by mutableStateOf<String?>(null)
private var steamGames by mutableStateOf<List<Library.SteamGame>>(emptyList()) private var steamGames by mutableStateOf<List<Library.SteamGame>>(emptyList())
private var steamGamesX64 by mutableStateOf(false)
@Volatile private var componentSweepDone = false @Volatile private var componentSweepDone = false
@Volatile private var componentSweepSession: String? = null @Volatile private var componentSweepSession: String? = null
private var emulatorList by mutableStateOf<List<Library.Emulator>>(emptyList()) private var emulatorList by mutableStateOf<List<Library.Emulator>>(emptyList())
private var runningLabel by mutableStateOf<String?>(null) private var runningLabel by mutableStateOf<String?>(null)
private var logsEnabled by mutableStateOf(true) private var logsEnabled by mutableStateOf(true)
private var vacDiagnostics by mutableStateOf(false)
private var agentCommands by mutableStateOf(false) private var agentCommands by mutableStateOf(false)
private var showRoms by mutableStateOf(false) private var showRoms by mutableStateOf(false)
private var homeAppSelected by mutableStateOf(false) private var homeAppSelected by mutableStateOf(false)
@@ -487,20 +481,6 @@ class MainActivity : ComponentActivity() {
pickSaveDir.launch(InAppFilePicker.buildDirIntent(this, getString(R.string.game_file_folder), gameSyncFolder)) pickSaveDir.launch(InAppFilePicker.buildDirIntent(this, getString(R.string.game_file_folder), gameSyncFolder))
} }
private fun switchLauncherIcon(style: String): Boolean {
val before = LauncherIcon.current(this)
LauncherIcon.set(this, style)
launcherIcon = LauncherIcon.current(this)
if (launcherIcon == before) return false
// Android finishes activities started through the alias that was just disabled.
startActivity(Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
.setComponent(LauncherIcon.activity(this))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
.putExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV, "setup:launcher"))
finishAndRemoveTask()
return true
}
private fun readGameIntent(request: Intent) { private fun readGameIntent(request: Intent) {
request.getStringExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV)?.let { navRequest = it; request.removeExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV) } request.getStringExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV)?.let { navRequest = it; request.removeExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV) }
shortcutPicker = request.action == Intent.ACTION_CREATE_SHORTCUT shortcutPicker = request.action == Intent.ACTION_CREATE_SHORTCUT
@@ -744,9 +724,7 @@ class MainActivity : ComponentActivity() {
theme = SessionPrefs.theme(this) theme = SessionPrefs.theme(this)
frameGenLabel = getString(R.string.frame_gen_off) frameGenLabel = getString(R.string.frame_gen_off)
appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this) appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this)
val (cached, cachedX64) = com.droiddeck.launcher.frontend.LibraryCache.snapshot(this) steamGames = if (shortcutPicker) emptyList() else com.droiddeck.launcher.frontend.LibraryCache.load(this)
steamGames = if (shortcutPicker) emptyList() else cached
steamGamesX64 = cachedX64
backActionsInverted = SessionPrefs.backActionsInverted(this) backActionsInverted = SessionPrefs.backActionsInverted(this)
orientation = SessionPrefs.orientation(this) orientation = SessionPrefs.orientation(this)
requestedOrientation = orientation requestedOrientation = orientation
@@ -756,7 +734,6 @@ class MainActivity : ComponentActivity() {
downloadPrefix = DownloadSource.custom(this) downloadPrefix = DownloadSource.custom(this)
DownloadSource.probe() DownloadSource.probe()
animationsEnabled = SessionPrefs.animationsEnabled(this) animationsEnabled = SessionPrefs.animationsEnabled(this)
launcherIcon = LauncherIcon.current(this)
gameStoresEnabled = SessionPrefs.gameStoresEnabled(this) gameStoresEnabled = SessionPrefs.gameStoresEnabled(this)
gameStoresSpeedTier = SessionPrefs.gameStoresSpeedTier(this) gameStoresSpeedTier = SessionPrefs.gameStoresSpeedTier(this)
storesOpenTab = SessionPrefs.storesOpenTab(this) storesOpenTab = SessionPrefs.storesOpenTab(this)
@@ -784,9 +761,8 @@ class MainActivity : ComponentActivity() {
busy = busy, stage = stage, percent = percent, busy = busy, stage = stage, percent = percent,
desktopInstalled = desktopInstalled, desktopPresent = desktopPresent, desktopInstalled = desktopInstalled, desktopPresent = desktopPresent,
offlineAccount = offlineAccount, offline = offline, offlineAccount = offlineAccount, offline = offline,
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled, frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled, agentCommands = agentCommands,
vacDiagnostics = vacDiagnostics, agentCommands = agentCommands, steamGames = steamGames, emulators = emulatorList, running = runningLabel,
steamGames = steamGames, steamGamesX64 = steamGamesX64, emulators = emulatorList, running = runningLabel,
frameGen = FrameGen.mode(this), frameGen = FrameGen.mode(this),
lossless = lossless, lossless = lossless,
pageKey = if (showPerformance) "performance" else if (showComponents) "components" else if (showMapping) "controller-mapping" else null, pageKey = if (showPerformance) "performance" else if (showComponents) "components" else if (showMapping) "controller-mapping" else null,
@@ -817,7 +793,6 @@ class MainActivity : ComponentActivity() {
downloadMirror = downloadMirror, downloadMirror = downloadMirror,
downloadPrefix = downloadPrefix, downloadPrefix = downloadPrefix,
animationsEnabled = animationsEnabled, animationsEnabled = animationsEnabled,
launcherIcon = launcherIcon,
gameStoresEnabled = gameStoresEnabled, gameStoresEnabled = gameStoresEnabled,
gameStoresSpeedTier = gameStoresSpeedTier, gameStoresSpeedTier = gameStoresSpeedTier,
storesOpenTab = storesOpenTab, storesOpenTab = storesOpenTab,
@@ -861,7 +836,6 @@ class MainActivity : ComponentActivity() {
}, },
onSteamGameArtChanged = { appId -> refreshSteamGameArt(appId) }, onSteamGameArtChanged = { appId -> refreshSteamGameArt(appId) },
onAddedGameRemoved = { folder, appId, name -> removeAddedGame(folder, appId, name) }, onAddedGameRemoved = { folder, appId, name -> removeAddedGame(folder, appId, name) },
onGameRemoved = { g -> removeGame(g) },
onAddedGamesArt = { on -> SessionPrefs.setAddedGamesArt(this, on); addedGamesArt = on; if (on) refreshAddedGames() }, onAddedGamesArt = { on -> SessionPrefs.setAddedGamesArt(this, on); addedGamesArt = on; if (on) refreshAddedGames() },
onSgdbKey = { key -> onSgdbKey = { key ->
Thread({ Thread({
@@ -923,7 +897,6 @@ class MainActivity : ComponentActivity() {
}, },
onProtons = { openProtons() }, onProtons = { openProtons() },
onComponents = { focusContent -> openComponents(focusContent) }, onComponents = { focusContent -> openComponents(focusContent) },
onGameComponents = { game -> openComponents(gameKey = game.profileKey) },
onComponentsTab = { tab -> openComponents(focusContent = true, tab = tab) }, onComponentsTab = { tab -> openComponents(focusContent = true, tab = tab) },
onSaveImport = { sg -> importSaves(sg.name) { GameSaves.game(sg) } }, onSaveImport = { sg -> importSaves(sg.name) { GameSaves.game(sg) } },
onSaveExport = { sg, layout -> exportSaves(sg.name, layout) { GameSaves.game(sg) } }, onSaveExport = { sg, layout -> exportSaves(sg.name, layout) { GameSaves.game(sg) } },
@@ -938,10 +911,6 @@ class MainActivity : ComponentActivity() {
SessionPrefs.setLogsEnabled(this, !SessionPrefs.logsEnabled(this)) SessionPrefs.setLogsEnabled(this, !SessionPrefs.logsEnabled(this))
logsEnabled = SessionPrefs.logsEnabled(this) logsEnabled = SessionPrefs.logsEnabled(this)
}, },
onVacDiagnostics = {
SessionPrefs.setVacDiagnostics(this, !SessionPrefs.vacDiagnostics(this))
vacDiagnostics = SessionPrefs.vacDiagnostics(this)
},
onAgentCommands = { onAgentCommands = {
com.droiddeck.launcher.agent.AgentAccess.setCommandsEnabled(this, !com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)) com.droiddeck.launcher.agent.AgentAccess.setCommandsEnabled(this, !com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this))
agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this) agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)
@@ -973,7 +942,6 @@ class MainActivity : ComponentActivity() {
onPageBack = { showPerformance = false; showComponents = false; showMapping = false }, onPageBack = { showPerformance = false; showComponents = false; showMapping = false },
onGameStoresEnabled = { on -> SessionPrefs.setGameStoresEnabled(this, on); gameStoresEnabled = on }, onGameStoresEnabled = { on -> SessionPrefs.setGameStoresEnabled(this, on); gameStoresEnabled = on },
onTheme = { id -> SessionPrefs.setTheme(this, id); theme = id }, onTheme = { id -> SessionPrefs.setTheme(this, id); theme = id },
onLauncherIcon = { style -> switchLauncherIcon(style) },
onLanguage = { tag -> onLanguage = { tag ->
if (tag != com.droiddeck.launcher.core.AppLanguage.chosen(this)) { if (tag != com.droiddeck.launcher.core.AppLanguage.chosen(this)) {
com.droiddeck.launcher.core.AppLanguage.setChosen(this, tag) com.droiddeck.launcher.core.AppLanguage.setChosen(this, tag)
@@ -1128,13 +1096,6 @@ class MainActivity : ComponentActivity() {
onDismiss = { pendingSwitch = null }, onDismiss = { pendingSwitch = null },
) )
} }
showRuntimeActions?.let { release ->
com.droiddeck.launcher.ui.RuntimeActionsDialog(
onRepair = { showRuntimeActions = null; if (!runtimeChangesBlocked()) install(release) },
onRemove = { showRuntimeActions = null; showRemove = true },
onDismiss = { showRuntimeActions = null },
)
}
if (showRemove) ConfirmDialog( if (showRemove) ConfirmDialog(
title = androidx.compose.ui.res.stringResource(R.string.main_remove_runtime_title), title = androidx.compose.ui.res.stringResource(R.string.main_remove_runtime_title),
text = androidx.compose.ui.res.stringResource(R.string.main_remove_runtime_text), text = androidx.compose.ui.res.stringResource(R.string.main_remove_runtime_text),
@@ -1221,9 +1182,7 @@ class MainActivity : ComponentActivity() {
} }
private fun playSteamVr() { private fun playSteamVr() {
val tracking = com.droiddeck.launcher.glasses.Glasses.settings.value if (com.droiddeck.launcher.handtracking.HandTracking.wanted(this)) placementCheck = true
if (!com.droiddeck.launcher.glasses.Glasses.state.value.usesSpatialControllers(tracking) &&
com.droiddeck.launcher.handtracking.HandTracking.wanted(this)) placementCheck = true
else startSteamSession(steamVr = true) else startSteamSession(steamVr = true)
} }
@@ -1291,7 +1250,6 @@ class MainActivity : ComponentActivity() {
syncLossless() syncLossless()
updates.onResume() updates.onResume()
drivers.checkOnOpen() drivers.checkOnOpen()
resumeInterruptedPackages()
protons.checkUpdates() protons.checkUpdates()
if (!SessionState.running) Thread({ if (!SessionState.running) Thread({
val applied = runCatching { ComponentsManager.applyQueued(this) }.getOrDefault(emptyList()) val applied = runCatching { ComponentsManager.applyQueued(this) }.getOrDefault(emptyList())
@@ -1436,9 +1394,8 @@ class MainActivity : ComponentActivity() {
) )
} }
private fun openComponents(focusContent: Boolean = true, tab: String? = null, gameKey: String? = null) { private fun openComponents(focusContent: Boolean = true, tab: String? = null) {
focusComponentsContent = focusContent focusComponentsContent = focusContent
componentsGameKey = gameKey
if (tab != null) components.compComp = tab if (tab != null) components.compComp = tab
showPerformance = false showPerformance = false
showMapping = false showMapping = false
@@ -1487,7 +1444,6 @@ class MainActivity : ComponentActivity() {
onImport = { pickComponent.launch(InAppFilePicker.buildIntent(this, WCP_EXT, getString(R.string.comp_pick_wcp))) }, onImport = { pickComponent.launch(InAppFilePicker.buildIntent(this, WCP_EXT, getString(R.string.comp_pick_wcp))) },
onBack = { if (!com.droiddeck.launcher.ui.Hops.back { showComponents = false }) showComponents = false }, onBack = { if (!com.droiddeck.launcher.ui.Hops.back { showComponents = false }) showComponents = false },
games = steamGames, games = steamGames,
initialGameKey = componentsGameKey,
generalFexPreset = fexPreset, generalFexPreset = fexPreset,
onGeneralFexPreset = { id -> SessionPrefs.setFexPreset(this, id); fexPreset = id }, onGeneralFexPreset = { id -> SessionPrefs.setFexPreset(this, id); fexPreset = id },
gpu = drivers.state(), gpu = drivers.state(),
@@ -1547,27 +1503,6 @@ class MainActivity : ComponentActivity() {
.putExtra(SessionService.EXTRA_PROGRAM, path)) .putExtra(SessionService.EXTRA_PROGRAM, path))
} }
private fun resumeInterruptedPackages() {
if (runtimeChangesBlocked()) return
val first = DesktopCatalog.interrupted(this).firstOrNull()
if (first == null) {
Thread({ DesktopCatalog.pruneDownloads(this) }, "prune-pkg").start()
return
}
pkgId = first.id; pkgStage = getString(R.string.deskpkg_installing, first.name); pkgPercent = -1
Thread({
val problem = DesktopCatalog.resumeInterrupted(this) { stage, percent ->
ui.post { pkgStage = stage; pkgPercent = percent }
}
ui.post {
pkgStage = null; pkgId = null
if (problem != null) android.widget.Toast.makeText(this, getString(R.string.main_pkg_problem, first.name, problem), android.widget.Toast.LENGTH_LONG).show()
refreshPackages()
refresh()
}
}, "resume-pkg").start()
}
private fun installPackage(id: String) { private fun installPackage(id: String) {
val entry = catalog?.firstOrNull { it.id == id } ?: return val entry = catalog?.firstOrNull { it.id == id } ?: return
if (busy || LinuxRuntimeInstaller.isBusy() || pkgStage != null || SessionState.running) return if (busy || LinuxRuntimeInstaller.isBusy() || pkgStage != null || SessionState.running) return
@@ -1630,7 +1565,6 @@ class MainActivity : ComponentActivity() {
fexPreset = if (mode == SessionService.MODE_STEAM) fexPreset else null, fexPreset = if (mode == SessionService.MODE_STEAM) fexPreset else null,
forceSsbs = forceSsbs, forceSsbs = forceSsbs,
syncBackend = if (mode == SessionService.MODE_STEAM) SessionPrefs.syncBackendOf(fastSync, fsyncFirst, syncFallback) else null, syncBackend = if (mode == SessionService.MODE_STEAM) SessionPrefs.syncBackendOf(fastSync, fsyncFirst, syncFallback) else null,
steamClientArch = if (mode == SessionService.MODE_STEAM) steamClientArch else null,
steamRepairQueued = steamRepairQueued, steamRepairQueued = steamRepairQueued,
mangoapp = mangoapp, mangoapp = mangoapp,
steamController = if (mode == SessionService.MODE_STEAM) steamController else null, steamController = if (mode == SessionService.MODE_STEAM) steamController else null,
@@ -1714,19 +1648,18 @@ class MainActivity : ComponentActivity() {
syncFallback = SessionPrefs.syncFallback(this) syncFallback = SessionPrefs.syncFallback(this)
}, },
onSteamRepair = { steamRepairQueued = SteamRepair.queue(this) }, onSteamRepair = { steamRepairQueued = SteamRepair.queue(this) },
onSteamClientArch = { id -> SessionPrefs.setSteamClientArch(this, id); steamClientArch = id; refresh() },
onMangoapp = { on -> SessionPrefs.setMangoapp(this, on); mangoapp = on }, onMangoapp = { on -> SessionPrefs.setMangoapp(this, on); mangoapp = on },
onSteamController = { id -> SessionPrefs.setSteamController(this, id); steamController = id }, onSteamController = { id -> SessionPrefs.setSteamController(this, id); steamController = id },
onRunSteamAtStartup = { on -> onRunSteamAtStartup = { on ->
SessionPrefs.setRunSteamAtStartup(this, on) SessionPrefs.setRunSteamAtStartup(this, on)
runSteamAtStartup = on runSteamAtStartup = on
}, },
onBootMovie = { id -> com.droiddeck.launcher.session.BootMovie.select(this, id); loadBootMovie() }, onBootMovie = { id -> SessionPrefs.setBootMovie(this, id); loadBootMovie() },
onBootMovieSound = { on -> SessionPrefs.setBootMovieSound(this, on); bootMovieSound = on }, onBootMovieSound = { on -> SessionPrefs.setBootMovieSound(this, on); bootMovieSound = on },
onImportBootMovie = { onImportBootMovie = {
pickBootMovie.launch(InAppFilePicker.buildIntent(this, com.droiddeck.launcher.session.BootMovie.PICKER_EXTENSIONS, getString(R.string.boot_movie_pick))) pickBootMovie.launch(InAppFilePicker.buildIntent(this, com.droiddeck.launcher.session.BootMovie.PICKER_EXTENSIONS, getString(R.string.boot_movie_pick)))
}, },
onBootMovieChanged = { loadBootMovie() }, onRemoveBootMovie = { com.droiddeck.launcher.session.BootMovie.removeCustom(this); loadBootMovie() },
onDeckyInstall = { release -> decky.installDecky(release) }, onDeckyInstall = { release -> decky.installDecky(release) },
onDeckyCheck = { decky.refreshDecky() }, onDeckyCheck = { decky.refreshDecky() },
onDeckyEnabled = { enabled -> DeckyManager.setSupervisorEnabled(this, enabled); decky.deckySupervisor = enabled }, onDeckyEnabled = { enabled -> DeckyManager.setSupervisorEnabled(this, enabled); decky.deckySupervisor = enabled },
@@ -1811,30 +1744,6 @@ class MainActivity : ComponentActivity() {
}, "steam-art-update").start() }, "steam-art-update").start()
} }
private fun removeGame(g: Library.SteamGame) {
val folder = g.gameFiles ?: return
when (com.droiddeck.launcher.frontend.GameRemoval.kind(g)) {
com.droiddeck.launcher.frontend.GameRemoval.Kind.LAUNCHER -> Unit
com.droiddeck.launcher.frontend.GameRemoval.Kind.SHORTCUT -> removeAddedGame(folder.path, g.gameId, g.name)
com.droiddeck.launcher.frontend.GameRemoval.Kind.STORE -> {
val installed = com.droiddeck.launcher.frontend.GameRemoval.storeGame(g)
if (installed != null) {
com.droiddeck.launcher.stores.StoresState.uninstall(this, installed) { refreshAddedGames(); refresh() }
return
}
if (g.library == Library.ADDED) {
removeAddedGame(folder.path, g.gameId, g.name)
return
}
val target = com.droiddeck.launcher.frontend.GameRemoval.steamFiles(g) ?: return
Thread({
com.droiddeck.launcher.frontend.GameRemoval.delete(target)
ui.post { refreshAddedGames(); refresh() }
}, "game-remove").start()
}
}
}
private fun removeAddedGame(folder: String, appId: Long?, name: String) { private fun removeAddedGame(folder: String, appId: Long?, name: String) {
steamGames = steamGames.filterNot { it.library == Library.ADDED && it.gameFiles?.path == folder } steamGames = steamGames.filterNot { it.library == Library.ADDED && it.gameFiles?.path == folder }
Thread({ com.droiddeck.launcher.frontend.AddedGames.remove(this, java.io.File(folder), appId, name) }, "added-game-remove").start() Thread({ com.droiddeck.launcher.frontend.AddedGames.remove(this, java.io.File(folder), appId, name) }, "added-game-remove").start()
@@ -1878,7 +1787,6 @@ class MainActivity : ComponentActivity() {
fastSync = SessionPrefs.fastSync(this) fastSync = SessionPrefs.fastSync(this)
fsyncFirst = SessionPrefs.fsyncFirst(this) fsyncFirst = SessionPrefs.fsyncFirst(this)
syncFallback = SessionPrefs.syncFallback(this) syncFallback = SessionPrefs.syncFallback(this)
steamClientArch = SessionPrefs.steamClientArch(this)
steamRepairQueued = SteamRepair.queued(this) steamRepairQueued = SteamRepair.queued(this)
mangoapp = SessionPrefs.mangoapp(this) mangoapp = SessionPrefs.mangoapp(this)
steamController = SessionPrefs.steamController(this) steamController = SessionPrefs.steamController(this)
@@ -1955,12 +1863,6 @@ class MainActivity : ComponentActivity() {
} }
private fun refresh() { private fun refresh() {
// Until the scan finishes, the other client's games would launch in this one.
val listX64 = SessionPrefs.activeSteamClientArch(this) == "x86_64"
if (listX64 != steamGamesX64) {
steamGamesX64 = listX64
steamGames = steamGames.filterNot { Library.fromSteamClient(it) || (it.library == Library.ADDED && it.gameId in 1..0xFFFFFFFFL) }
}
if (!busy && LinuxRuntimeInstaller.isBusy()) followRuntimeOperation { LinuxRuntimeInstaller.attach(it) } if (!busy && LinuxRuntimeInstaller.isBusy()) followRuntimeOperation { LinuxRuntimeInstaller.attach(it) }
if (showComponents) drivers.refreshDrivers() if (showComponents) drivers.refreshDrivers()
addedGamesArt = SessionPrefs.addedGamesArt(this) addedGamesArt = SessionPrefs.addedGamesArt(this)
@@ -1974,7 +1876,6 @@ class MainActivity : ComponentActivity() {
frameGenLabel = FrameGen.label(this) frameGenLabel = FrameGen.label(this)
romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() } romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }
logsEnabled = SessionPrefs.logsEnabled(this) logsEnabled = SessionPrefs.logsEnabled(this)
vacDiagnostics = SessionPrefs.vacDiagnostics(this)
agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this) agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)
runningLabel = if (SessionState.running) when (SessionState.mode) { runningLabel = if (SessionState.running) when (SessionState.mode) {
SessionService.MODE_DESKTOP -> getString(R.string.rail_desktop) SessionService.MODE_DESKTOP -> getString(R.string.rail_desktop)
@@ -1985,31 +1886,25 @@ class MainActivity : ComponentActivity() {
val scanGeneration = ++libraryScanGeneration val scanGeneration = ++libraryScanGeneration
val artRefreshesAtStart = HashMap(steamArtRefreshes) val artRefreshesAtStart = HashMap(steamArtRefreshes)
if (shortcutPicker) shortcutLibraryScanning = true if (shortcutPicker) shortcutLibraryScanning = true
if (SessionPrefs.steamClientArch(this) == "x86_64" && !OfflineMode.enabled(this)) {
Thread({ com.droiddeck.launcher.session.FexCatalog.refresh(this) }, "fex-catalog").start()
}
Thread({ Thread({
val emus = Library.emulators(this) { id -> DesktopCatalog.installed(this, id) != null } val emus = Library.emulators(this) { id -> DesktopCatalog.installed(this, id) != null }
ui.post { if (scanGeneration == libraryScanGeneration) emulatorList = emus } ui.post { if (scanGeneration == libraryScanGeneration) emulatorList = emus }
if (ready) { if (ready) {
val quick = runCatching { Library.steamGames(this) }.getOrNull() val quick = runCatching { Library.steamGames(this) }.getOrNull()
val claimed = quick?.let { runCatching { Library.claimedFolders(it) }.getOrDefault(emptySet()) }.orEmpty()
if (quick != null) ui.post { if (quick != null) ui.post {
if (scanGeneration == libraryScanGeneration && steamGames.isNotEmpty()) { if (scanGeneration == libraryScanGeneration && steamGames.isNotEmpty()) {
val before = steamGames.map { it.gameId }.toSet() val before = steamGames.map { it.gameId }.toSet()
val fresh = quick.filter { it.gameId !in before } val fresh = quick.filter { it.gameId !in before }
if (fresh.isNotEmpty()) { if (fresh.isNotEmpty()) {
steamGames = (quick + steamGames.filter { it.library == Library.ADDED && it.gameFiles?.absolutePath.let { path -> path == null || path !in claimed } }).distinctBy { it.gameId } steamGames = (quick + steamGames.filter { it.library == Library.ADDED }).distinctBy { it.gameId }
fresh.forEach { com.droiddeck.launcher.frontend.AutoComponents.queueGame(this, it, asked = false) } fresh.forEach { com.droiddeck.launcher.frontend.AutoComponents.queueGame(this, it, asked = false) }
} }
} }
} }
} }
val scannedArch = SessionPrefs.activeSteamClientArch(this) val games = if (ready) Library.launchableGames(this) else emptyList()
val scannedX64 = scannedArch == "x86_64"
val games = if (ready) Library.launchableGames(this, arch = scannedArch) else emptyList()
val all = games.distinctBy { it.gameId } val all = games.distinctBy { it.gameId }
if (ready && scanGeneration == libraryScanGeneration) com.droiddeck.launcher.frontend.LibraryCache.save(this, all, scannedX64) if (ready) com.droiddeck.launcher.frontend.LibraryCache.save(this, all)
val endedSession = SessionState.sessionId.takeIf { !SessionState.running && it != null && it != componentSweepSession } val endedSession = SessionState.sessionId.takeIf { !SessionState.running && it != null && it != componentSweepSession }
if (ready && (!componentSweepDone || endedSession != null)) { if (ready && (!componentSweepDone || endedSession != null)) {
componentSweepDone = true componentSweepDone = true
@@ -2019,7 +1914,6 @@ class MainActivity : ComponentActivity() {
ui.post { ui.post {
if (scanGeneration == libraryScanGeneration) { if (scanGeneration == libraryScanGeneration) {
val current = steamGames.filter { it.library != Library.ADDED }.associateBy { it.appId } val current = steamGames.filter { it.library != Library.ADDED }.associateBy { it.appId }
steamGamesX64 = scannedX64
steamGames = all.map { g -> steamGames = all.map { g ->
val newer = current[g.appId] val newer = current[g.appId]
if (newer != null && g.library != Library.ADDED && steamArtRefreshes[g.appId] != artRefreshesAtStart[g.appId]) g.withArt(newer.art, newer.hero, newer.icon) else g if (newer != null && g.library != Library.ADDED && steamArtRefreshes[g.appId] != artRefreshesAtStart[g.appId]) g.withArt(newer.art, newer.hero, newer.icon) else g
@@ -2038,14 +1932,10 @@ class MainActivity : ComponentActivity() {
private fun onRuntimeButton() { private fun onRuntimeButton() {
if (runtimeChangesBlocked()) return if (runtimeChangesBlocked()) return
val release = available val release = available
if (removalPending) { if (removalPending || installed != null && release?.version == installed) {
showRemove = true showRemove = true
return return
} }
if (installed != null && release?.version == installed) {
showRuntimeActions = release
return
}
if (release == null) { if (release == null) {
Thread({ checkCatalog() }, "catalog").start() Thread({ checkCatalog() }, "catalog").start()
return return
@@ -2126,7 +2016,7 @@ class MainActivity : ComponentActivity() {
com.droiddeck.launcher.core.AppLanguage.setChosen(this, com.droiddeck.launcher.core.AppLanguage.SYSTEM) com.droiddeck.launcher.core.AppLanguage.setChosen(this, com.droiddeck.launcher.core.AppLanguage.SYSTEM)
if (!ok) android.widget.Toast.makeText(this, R.string.setup_reset_settings_partial, android.widget.Toast.LENGTH_LONG).show() if (!ok) android.widget.Toast.makeText(this, R.string.setup_reset_settings_partial, android.widget.Toast.LENGTH_LONG).show()
com.droiddeck.launcher.ui.Motion.refresh(this) com.droiddeck.launcher.ui.Motion.refresh(this)
if (!switchLauncherIcon(LauncherIcon.DARK)) recreate() recreate()
} }
}, "reset-settings").start() }, "reset-settings").start()
} }
@@ -56,8 +56,6 @@ import com.droiddeck.launcher.gpu.HeadTracker
import com.droiddeck.launcher.glasses.Glasses import com.droiddeck.launcher.glasses.Glasses
import com.droiddeck.launcher.glasses.GlassesScreen import com.droiddeck.launcher.glasses.GlassesScreen
import com.droiddeck.launcher.glasses.GlassesRendering import com.droiddeck.launcher.glasses.GlassesRendering
import com.droiddeck.launcher.glasses.SpatialTracking
import com.droiddeck.launcher.glasses.TrackingRecovery
import kotlinx.coroutines.cancel import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import com.droiddeck.launcher.gpu.SteamVr import com.droiddeck.launcher.gpu.SteamVr
@@ -75,13 +73,11 @@ import com.droiddeck.launcher.input.PadBridge
import com.droiddeck.launcher.input.PadMouse import com.droiddeck.launcher.input.PadMouse
import com.droiddeck.launcher.input.PadState import com.droiddeck.launcher.input.PadState
import com.droiddeck.launcher.input.SteamControllerBle import com.droiddeck.launcher.input.SteamControllerBle
import com.droiddeck.launcher.input.DirectTouchHold
import com.droiddeck.launcher.input.PointerGestures import com.droiddeck.launcher.input.PointerGestures
import com.droiddeck.launcher.input.SecondScreenDisplay import com.droiddeck.launcher.input.SecondScreenDisplay
import com.droiddeck.launcher.input.SecondScreenDisplays import com.droiddeck.launcher.input.SecondScreenDisplays
import com.droiddeck.launcher.input.SecondScreenMode import com.droiddeck.launcher.input.SecondScreenMode
import com.droiddeck.launcher.input.TouchpadGestures import com.droiddeck.launcher.input.TouchpadGestures
import com.droiddeck.launcher.input.TouchscreenGestures
import com.droiddeck.launcher.input.ScrollTouchGestures import com.droiddeck.launcher.input.ScrollTouchGestures
import com.droiddeck.launcher.runtime.LinuxRuntime import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.LoadingState import com.droiddeck.launcher.session.LoadingState
@@ -190,18 +186,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
} }
private var watching = true private var watching = true
private lateinit var touchpad: TouchpadGestures private lateinit var touchpad: TouchpadGestures
private lateinit var directTouchHold: DirectTouchHold
private lateinit var threeFingerTap: com.droiddeck.launcher.input.ThreeFingerTap private lateinit var threeFingerTap: com.droiddeck.launcher.input.ThreeFingerTap
private lateinit var touchscreenGestures: TouchscreenGestures
private var gestureConfig = com.droiddeck.launcher.input.TouchGestureConfig()
private var gestureGame: String? = null
private var gestureSettingsOpen by mutableStateOf(false)
private var recognizedGesture by mutableStateOf<TouchscreenGestures.Gesture?>(null)
private var gesturePointerX = 0f
private var gesturePointerY = 0f
private var gesturePointerReady = false
private val clearRecognizedGesture = Runnable { recognizedGesture = null }
private val gestureKeysDown = mutableSetOf<Int>()
private lateinit var scrollTouch: ScrollTouchGestures private lateinit var scrollTouch: ScrollTouchGestures
private lateinit var padMouse: PadMouse private lateinit var padMouse: PadMouse
@Volatile private var padMouseOn = false @Volatile private var padMouseOn = false
@@ -222,7 +207,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private val pointerLockListener = WaylandCompositor.PointerLockListener { locked, _, _ -> private val pointerLockListener = WaylandCompositor.PointerLockListener { locked, _, _ ->
uiHandler.post { uiHandler.post {
if (pointerLocked == locked) return@post if (pointerLocked == locked) return@post
gesturePointerReady = false
pointerLocked = locked pointerLocked = locked
Log.i(TAG, "pointer lock " + if (locked) "taken by a program" else "released") Log.i(TAG, "pointer lock " + if (locked) "taken by a program" else "released")
padMouseCheckedAt = 0L padMouseCheckedAt = 0L
@@ -322,13 +306,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var glassesSettings by mutableStateOf(Glasses.settings.value) private var glassesSettings by mutableStateOf(Glasses.settings.value)
private var glassesScreen: GlassesScreen? = null private var glassesScreen: GlassesScreen? = null
private var glassesOutputActive by mutableStateOf(false) private var glassesOutputActive by mutableStateOf(false)
private var trackingRecovery by mutableStateOf<TrackingRecovery?>(null)
private var glasses3dForVr = false private var glasses3dForVr = false
private var ended = false private var ended = false
private var glassesPresent = false private var glassesPresent = false
private var steamVrAutoTried = false private var steamVrAutoTried = false
private var steamVrInstallTried = false private var steamVrInstallTried = false
@Volatile private var steamVrRequestGeneration = 0L
private var headTracking by mutableStateOf(false) private var headTracking by mutableStateOf(false)
private var glassesSlot by mutableStateOf(0) private var glassesSlot by mutableStateOf(0)
private var glassesKey: List<Any?> = emptyList() private var glassesKey: List<Any?> = emptyList()
@@ -430,7 +412,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
} else if (intent.getBooleanExtra(EXTRA_STEAMVR, false) && SessionState.mode == SessionService.MODE_STEAM) { } else if (intent.getBooleanExtra(EXTRA_STEAMVR, false) && SessionState.mode == SessionService.MODE_STEAM) {
SessionState.steamVr = true SessionState.steamVr = true
} }
if (SessionState.steamVr) Glasses.prepareSteamVrStart()
if (intent.action == SessionService.ACTION_AGENT_START) { if (intent.action == SessionService.ACTION_AGENT_START) {
SessionEvents.record("agent.start_requested", mapOf("mode" to SessionState.mode)) SessionEvents.record("agent.start_requested", mapOf("mode" to SessionState.mode))
} }
@@ -497,20 +478,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
onScreenControls = OnScreenControls(this, bridge, onKeyboard = ::togglePcKeyboard).also { root.addView(it) } onScreenControls = OnScreenControls(this, bridge, onKeyboard = ::togglePcKeyboard).also { root.addView(it) }
keyboard = KeyboardHost(this).also { root.addView(it) } keyboard = KeyboardHost(this).also { root.addView(it) }
touchpad = TouchpadGestures(PointerGestures.slop(this), pointerListener) touchpad = TouchpadGestures(PointerGestures.slop(this), pointerListener)
directTouchHold = DirectTouchHold(PointerGestures.slop(this), pointerListener) {
WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
}
threeFingerTap = com.droiddeck.launcher.input.ThreeFingerTap(PointerGestures.slop(this) * 2) threeFingerTap = com.droiddeck.launcher.input.ThreeFingerTap(PointerGestures.slop(this) * 2)
touchscreenGestures = TouchscreenGestures(
ViewConfiguration.get(this).scaledTouchSlop.toFloat(), gestureOutput,
)
refreshGestureConfig()
// A real touch target lets FrameLayout split fingers between the
// game surface and on-screen buttons, in either finger-down order.
root.isMotionEventSplittingEnabled = true
surfaceView.setOnTouchListener { _, event ->
routedTouchMode == SessionPrefs.TOUCH_GESTURES && onTouchEvent(event)
}
padMouse = PadMouse(padMouseListener) padMouse = PadMouse(padMouseListener)
bridge.setTouchRoute(object : PadBridge.TouchRoute { bridge.setTouchRoute(object : PadBridge.TouchRoute {
override fun active(): Boolean = if (Looper.myLooper() == Looper.getMainLooper()) padMouseMode() else padMouseOn override fun active(): Boolean = if (Looper.myLooper() == Looper.getMainLooper()) padMouseMode() else padMouseOn
@@ -527,15 +495,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
loading = LoadingState(this, steam = loadingMode() == SessionService.MODE_STEAM) loading = LoadingState(this, steam = loadingMode() == SessionService.MODE_STEAM)
if (!SessionState.running) { if (!SessionState.running) {
val repair = intent.getBooleanExtra(EXTRA_REPAIR_RUNTIME, false) val needRuntime = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.installedVersion(this) == null
intent.removeExtra(EXTRA_REPAIR_RUNTIME)
val needRuntime = repair || com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.installedVersion(this) == null
val needResume = !needRuntime && com.droiddeck.launcher.runtime.DesktopCatalog.interrupted(this).isNotEmpty()
val needDesktop = intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_DESKTOP && val needDesktop = intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_DESKTOP &&
(repair || !com.droiddeck.launcher.runtime.DesktopCatalog.desktopInstalled(this)) !com.droiddeck.launcher.runtime.DesktopCatalog.desktopInstalled(this)
val needProton = (intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM) == SessionService.MODE_STEAM && val needProton = (intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM) == SessionService.MODE_STEAM &&
com.droiddeck.launcher.runtime.DesktopCatalog.protonSeedNeeded(this) com.droiddeck.launcher.runtime.DesktopCatalog.protonSeedNeeded(this)
if (needRuntime || needResume || needDesktop || needProton) installThenStart(needRuntime, needDesktop, needProton, needResume) if (needRuntime || needDesktop || needProton) installThenStart(needRuntime, needDesktop, needProton)
} }
hud = PerfHud(this) hud = PerfHud(this)
hud.onPresentingWindowChanged = { hud.onPresentingWindowChanged = {
@@ -554,25 +519,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
sessionOverlay = createSessionOverlay() sessionOverlay = createSessionOverlay()
root.addView(sessionOverlay) root.addView(sessionOverlay)
setContentView(root) setContentView(root)
glassesScope.launch { Glasses.state.collect { glassesScope.launch { Glasses.state.collect { glasses = it; onGlassesChanged() } }
glasses = it glassesScope.launch { Glasses.settings.collect { glassesSettings = it; onGlassesChanged() } }
onGlassesChanged()
updateJoyConTracking()
updateHandCamera()
} }
glassesScope.launch { Glasses.settings.collect {
glassesSettings = it
onGlassesChanged()
updateJoyConTracking()
updateHandCamera()
} }
glassesScope.launch { com.droiddeck.launcher.handtracking.HandTracking.settings.collect { updateHandCamera() } } glassesScope.launch { com.droiddeck.launcher.handtracking.HandTracking.settings.collect { updateHandCamera() } }
glassesScope.launch {
while (true) {
updateTrackingRecovery()
kotlinx.coroutines.delay(100)
}
}
glassesScope.launch { glassesScope.launch {
while (true) { while (true) {
if (SessionState.running && SessionState.mode == SessionService.MODE_STEAM && if (SessionState.running && SessionState.mode == SessionService.MODE_STEAM &&
@@ -615,15 +564,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
isFocusableInTouchMode = true isFocusableInTouchMode = true
defaultFocusHighlightEnabled = false defaultFocusHighlightEnabled = false
setContent { setContent {
androidx.compose.runtime.SideEffect {
com.droiddeck.launcher.glasses.GlassesMenuMirror.setSessionMenuVisible(this@SessionActivity,
(drawerOpen || achievementsOpen || pcKeyboardOpen) && !pipUi && steamVrStatus != SteamVr.Status.RUNNING)
}
androidx.compose.runtime.DisposableEffect(Unit) {
onDispose { com.droiddeck.launcher.glasses.GlassesMenuMirror.setSessionMenuVisible(this@SessionActivity, false) }
}
androidx.compose.runtime.LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, pipUi) { updatePointerCapture() } androidx.compose.runtime.LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, pipUi) { updatePointerCapture() }
androidx.compose.runtime.LaunchedEffect(AgentGuest.steamKeyboard) { updateOnScreenControls() }
androidx.compose.runtime.LaunchedEffect(picturePosition, SessionState.running, pipUi, cardboard.enabled) { applyGameAlignment() } androidx.compose.runtime.LaunchedEffect(picturePosition, SessionState.running, pipUi, cardboard.enabled) { applyGameAlignment() }
DroidDeckTheme { DroidDeckTheme {
if (pipUi) { if (pipUi) {
@@ -636,24 +577,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
} }
} else { } else {
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) { com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) {
CursorOverlay({ cursorPos }, cursorVisible, resources.displayMetrics.density, CursorOverlay(cursorPos, cursorVisible, resources.displayMetrics.density,
cursorImage, cursorHotX, cursorHotY, cursorImageScale) cursorImage, cursorHotX, cursorHotY, cursorImageScale)
if (hud.text.isNotEmpty()) HudText(hud.text) if (hud.text.isNotEmpty()) HudText(hud.text)
if (glassesOutputActive && !loading.visible) com.droiddeck.launcher.ui.GlassesPlayingHint(glasses.model) if (glassesOutputActive && !loading.visible) com.droiddeck.launcher.ui.GlassesPlayingHint(glasses.model)
if (trackingRecovery != null && !drawerOpen && !pcKeyboardOpen && !loading.visible) {
androidx.compose.ui.viewinterop.AndroidView(
factory = { com.droiddeck.launcher.ui.TrackingRecoveryView(it) },
modifier = Modifier.fillMaxSize(),
update = { it.update(trackingRecovery, !glassesOutputActive && glasses.usable && glasses.sbs) },
)
}
if (GlassesRendering.usesGlasses(glasses, glassesOutputActive, steamVrStatus == SteamVr.Status.RUNNING) && if (GlassesRendering.usesGlasses(glasses, glassesOutputActive, steamVrStatus == SteamVr.Status.RUNNING) &&
headTracking && !drawerOpen && !pcKeyboardOpen && !loading.visible) com.droiddeck.launcher.ui.GlassesRecenterButton( headTracking && !drawerOpen && !pcKeyboardOpen && !loading.visible) com.droiddeck.launcher.ui.GlassesRecenterButton(
controllerSettings?.tint ?: android.graphics.Color.rgb(90, 160, 255), controllerSettings?.opacity ?: 100, controllerSettings?.tint ?: android.graphics.Color.rgb(90, 160, 255), controllerSettings?.opacity ?: 100) { headTracker?.recenter() }
onRecenterJoyCons = if (steamVrStatus == SteamVr.Status.RUNNING &&
glasses.usesSpatialControllers(glassesSettings) && glassesSettings.joyConTracking)
joyConVr?.let { { it.recenter() } } else null,
) { headTracker?.recenter() }
if (glasses.present && !drawerOpen && !pcKeyboardOpen && !loading.visible) com.droiddeck.launcher.ui.GlassesCornerButton(glassesSlot, if (glasses.present && !drawerOpen && !pcKeyboardOpen && !loading.visible) com.droiddeck.launcher.ui.GlassesCornerButton(glassesSlot,
controllerSettings?.tint ?: android.graphics.Color.rgb(90, 160, 255), controllerSettings?.opacity ?: 100) { controllerSettings?.tint ?: android.graphics.Color.rgb(90, 160, 255), controllerSettings?.opacity ?: 100) {
drawerPage = com.droiddeck.launcher.ui.SessionDrawerPage.GLASSES drawerPage = com.droiddeck.launcher.ui.SessionDrawerPage.GLASSES
@@ -666,7 +596,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
onCancel = { SessionService.stop(this@SessionActivity); finish() }, onCancel = { SessionService.stop(this@SessionActivity); finish() },
endedDetail = loading.endedDetail, endedDetail = loading.endedDetail,
onRetry = { retrySession() }, onRetry = { retrySession() },
onRepair = if (repairOffered) ({ repairRuntime() }) else null,
onShareLogs = { shareCurrentSessionLogs() }, onShareLogs = { shareCurrentSessionLogs() },
onClose = { finish() }, onClose = { finish() },
flood = floodColor?.let { androidx.compose.ui.graphics.Color(it) }, flood = floodColor?.let { androidx.compose.ui.graphics.Color(it) },
@@ -675,32 +604,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(android.graphics.Color.BLACK)) window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(android.graphics.Color.BLACK))
}, },
) )
LaunchedEffect(AgentGuest.focusRevision) {
val nextGame = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
if (SessionState.mode == SessionService.MODE_RUN) SessionState.program?.let { "program:$it" }
else {
val snapshot = AgentGuest.focus(this@SessionActivity)
val focused = snapshot?.optLong("focusedApp")?.takeIf { it > 0 && it != 769L }
val windows = snapshot?.optJSONArray("focusableApps")
focused?.toString() ?: windows?.let { values ->
(0 until values.length()).map { values.optLong(it) }
.filter { it > 0 && it != 769L }.distinct().singleOrNull()?.toString()
}
}
}
if (nextGame != gestureGame) { gestureGame = nextGame; refreshGestureConfig() }
}
LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, pipUi, SessionState.suspended) {
if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || pipUi || SessionState.suspended) {
cancelTouchGestures()
}
}
com.droiddeck.launcher.ui.GestureFeedback(recognizedGesture)
if (gestureSettingsOpen) com.droiddeck.launcher.ui.TouchGestureDialog(
game = gestureGame,
onDismiss = { gestureSettingsOpen = false },
onSaved = { gestureSettingsOpen = false; refreshGestureConfig() },
)
androidx.compose.runtime.LaunchedEffect(drawerOpen) { androidx.compose.runtime.LaunchedEffect(drawerOpen) {
if (drawerOpen) { if (drawerOpen) {
syncLossless() syncLossless()
@@ -718,12 +621,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
steamVrSwitchedPicture, glassesVr, steamVrRequested) || (drawerOpen && drawerPage == SessionDrawerPage.VR) steamVrSwitchedPicture, glassesVr, steamVrRequested) || (drawerOpen && drawerPage == SessionDrawerPage.VR)
LaunchedEffect(pollSteamVr) { LaunchedEffect(pollSteamVr) {
while (pollSteamVr) { while (pollSteamVr) {
val request = steamVrRequestGeneration
val session = SessionState.sessionId
val now = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { val now = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
SteamVr.status(this@SessionActivity) SteamVr.status(this@SessionActivity)
} }
if (request == steamVrRequestGeneration && session == SessionState.sessionId) onSteamVrStatus(now) onSteamVrStatus(now)
kotlinx.coroutines.delay(3000) kotlinx.coroutines.delay(3000)
} }
} }
@@ -736,7 +637,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
achievementsInFront = found achievementsInFront = found
if (found == null) achievementsOpen = false if (found == null) achievementsOpen = false
} }
androidx.compose.runtime.LaunchedEffect(pcKeyboardOpen) { if (pcKeyboardOpen) releasePads(); updateOnScreenControls() } androidx.compose.runtime.LaunchedEffect(pcKeyboardOpen) { if (pcKeyboardOpen) releasePads() }
LaunchedEffect(pcKeyboardOpen, drawerOpen, achievementsOpen) { LaunchedEffect(pcKeyboardOpen, drawerOpen, achievementsOpen) {
if (pcKeyboardOpen || drawerOpen || achievementsOpen) padMouse.reset() if (pcKeyboardOpen || drawerOpen || achievementsOpen) padMouse.reset()
} }
@@ -760,10 +661,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
onCardboardRecenter = { headTracker?.recenter() }, onCardboardRecenter = { headTracker?.recenter() },
glassesPresent = glasses.present, glassesPresent = glasses.present,
glassesOutput = glassesOutputActive, glassesOutput = glassesOutputActive,
onGlassesRecenter = { onGlassesRecenter = { headTracker?.recenter() },
headTracker?.recenter()
com.droiddeck.launcher.glasses.GlassesMenuMirror.recenter()
},
steamVr = steamVrStatus, steamVr = steamVrStatus,
immersiveSteamVr = com.droiddeck.launcher.session.QuestExperimental.isSupported(), immersiveSteamVr = com.droiddeck.launcher.session.QuestExperimental.isSupported(),
onSteamVr = { action -> steamVrAction(action) }, onSteamVr = { action -> steamVrAction(action) },
@@ -835,7 +733,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionPrefs.setSteamController(this@SessionActivity, id) SessionPrefs.setSteamController(this@SessionActivity, id)
com.droiddeck.launcher.session.SteamDeckPad.showPad(SessionPrefs.padType(id)) com.droiddeck.launcher.session.SteamDeckPad.showPad(SessionPrefs.padType(id))
com.droiddeck.launcher.input.FakeInputWriter.setPadType(SessionPrefs.padType(id)) com.droiddeck.launcher.input.FakeInputWriter.setPadType(SessionPrefs.padType(id))
com.droiddeck.launcher.session.InputSysfsComponent.padTypeChanged(SessionPrefs.padType(id))
padType = id padType = id
}, },
backActionsInverted = backActionsInverted, backActionsInverted = backActionsInverted,
@@ -877,7 +774,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionService.suspendPolicyChanged(this@SessionActivity) SessionService.suspendPolicyChanged(this@SessionActivity)
}, },
onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() }, onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() },
onGestureSettings = { drawerOpen = false; gestureSettingsOpen = true },
onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() }, onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() },
onSecondScreenMode = ::selectSecondScreenMode, onSecondScreenMode = ::selectSecondScreenMode,
onSecondScreenDisplay = ::selectSecondScreenDisplay, onSecondScreenDisplay = ::selectSecondScreenDisplay,
@@ -1315,8 +1211,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
com.droiddeck.launcher.frontend.Library.nameForProgram(program)?.let { getString(R.string.session_starting_named, it) } com.droiddeck.launcher.frontend.Library.nameForProgram(program)?.let { getString(R.string.session_starting_named, it) }
?: getString(R.string.session_starting_program) ?: getString(R.string.session_starting_program)
} }
else -> if (com.droiddeck.launcher.session.SessionPrefs.activeSteamClientArch(this) == "x86_64") getString(R.string.load_starting_steam_x64) else -> getString(R.string.load_starting_steam)
else getString(R.string.load_starting_steam)
} }
private fun shareCurrentSessionLogs() { private fun shareCurrentSessionLogs() {
@@ -1356,7 +1251,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val nextTouchMode = SessionPrefs.touchMode(this) val nextTouchMode = SessionPrefs.touchMode(this)
if (touchMode != nextTouchMode) { if (touchMode != nextTouchMode) {
if (::touchpad.isInitialized) touchpad.cancel() if (::touchpad.isInitialized) touchpad.cancel()
if (::directTouchHold.isInitialized) directTouchHold.cancel()
if (::scrollTouch.isInitialized) scrollTouch.cancel() if (::scrollTouch.isInitialized) scrollTouch.cancel()
if (CompositorHost.isStarted) { if (CompositorHost.isStarted) {
WaylandCompositor.nativeSendTouch(3, -1, 0, 0) WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
@@ -1381,18 +1275,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
@Volatile private var installingRuntime = false @Volatile private var installingRuntime = false
private var repairOffered by mutableStateOf(false)
private fun installThenStart(runtime: Boolean, desktop: Boolean, proton: Boolean = false, resume: Boolean = false) { private fun installThenStart(runtime: Boolean, desktop: Boolean, proton: Boolean = false) {
if (SessionState.stopRequested) return if (SessionState.stopRequested) return
installingRuntime = true installingRuntime = true
SessionState.installing = if (runtime) "runtime" else if (resume) "package" else if (desktop) "desktop" else "proton" SessionState.installing = if (runtime) "runtime" else if (desktop) "desktop" else "proton"
SessionEvents.transition( SessionEvents.transition(
SessionPhase.INSTALLING_RUNTIME, SessionPhase.INSTALLING_RUNTIME,
"${SessionState.installing}.installing", "${SessionState.installing}.installing",
mapOf("component" to SessionState.installing), mapOf("component" to SessionState.installing),
) )
val first = if (runtime || resume) RUNTIME_LINES else if (desktop) DESKTOP_LINES else PROTON_LINES val first = if (runtime) RUNTIME_LINES else if (desktop) DESKTOP_LINES else PROTON_LINES
loading.say(getString(first.downloading), first.topic, readable = true) loading.say(getString(first.downloading), first.topic, readable = true)
loading.percent = -1 loading.percent = -1
Thread({ Thread({
@@ -1402,13 +1295,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
problem = installRuntime() problem = installRuntime()
if (problem == null) SessionEvents.record("runtime.ready") else failedComponent = "runtime" if (problem == null) SessionEvents.record("runtime.ready") else failedComponent = "runtime"
} }
if (problem == null && resume && !SessionState.stopRequested) {
SessionState.installing = "package"
SessionEvents.transition(SessionPhase.INSTALLING_RUNTIME, "package.resuming", mapOf("component" to "package"))
problem = com.droiddeck.launcher.runtime.DesktopCatalog.resumeInterrupted(this, progressAsIs())
?.let { getString(R.string.session_package_resume_failed, it) }
if (problem == null) SessionEvents.record("package.ready") else failedComponent = "package"
}
if (problem == null && desktop && !SessionState.stopRequested) { if (problem == null && desktop && !SessionState.stopRequested) {
SessionState.installing = "desktop" SessionState.installing = "desktop"
SessionEvents.transition(SessionPhase.INSTALLING_RUNTIME, "desktop.installing", mapOf("component" to "desktop")) SessionEvents.transition(SessionPhase.INSTALLING_RUNTIME, "desktop.installing", mapOf("component" to "desktop"))
@@ -1433,11 +1319,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return@post return@post
} }
if (problem != null) { if (problem != null) {
val code = when (failedComponent) { val code = if (failedComponent == "runtime") "RUNTIME_INSTALL_FAILED" else "DESKTOP_INSTALL_FAILED"
"runtime" -> "RUNTIME_INSTALL_FAILED"
"package" -> "PACKAGE_RESUME_FAILED"
else -> "DESKTOP_INSTALL_FAILED"
}
SessionEvents.fail(code, problem) SessionEvents.fail(code, problem)
collectStartArtifacts("session start failed") collectStartArtifacts("session start failed")
loading.showEnded(problem) loading.showEnded(problem)
@@ -1485,17 +1367,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
} }
} }
private fun progressAsIs() = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.ProgressListener { stage, percent ->
uiHandler.post {
loading.percent = percent
loading.say(stage, LoadingState.Topic.RUNTIME, readable = true)
}
}
private fun installRuntime(): String? { private fun installRuntime(): String? {
val release = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.fetchRelease() val release = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.fetchRelease()
?: return getString(R.string.session_runtime_catalog_unreachable) ?: return getString(R.string.session_runtime_catalog_unreachable)
runCatching { com.droiddeck.launcher.runtime.RuntimeInstallService.start(this, release) }
val ok = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.install(this, release, val ok = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.install(this, release,
progressFor(RUNTIME_LINES, release.size / 1_000_000)) progressFor(RUNTIME_LINES, release.size / 1_000_000))
return if (ok) null else getString(R.string.session_runtime_install_failed) return if (ok) null else getString(R.string.session_runtime_install_failed)
@@ -1551,7 +1425,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
activeCardboard = effectiveCardboard(SessionPrefs.cardboard(this)) activeCardboard = effectiveCardboard(SessionPrefs.cardboard(this))
pushCardboard(activeCardboard) pushCardboard(activeCardboard)
WaylandCompositor.nativeSetCardboardPoseFile(File(filesDir, ".wayland-rt/droiddeck-headpose").path) WaylandCompositor.nativeSetCardboardPoseFile(File(filesDir, ".wayland-rt/droiddeck-headpose").path)
com.droiddeck.launcher.glasses.SpatialTracking.attachPublisher(File(filesDir, ".wayland-rt/droiddeck-spatialpose").path)
if (!SessionState.running) { if (!SessionState.running) {
val waylandLog = File(SessionPaths.beginOrCurrent(this), "wayland.log") val waylandLog = File(SessionPaths.beginOrCurrent(this), "wayland.log")
WaylandCompositor.setSessionLogFile(waylandLog) WaylandCompositor.setSessionLogFile(waylandLog)
@@ -1603,7 +1476,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
intent.getStringExtra(SessionService.EXTRA_STEAM_UI), intent.getStringExtra(SessionService.EXTRA_STEAM_UI),
intent.getStringExtra(SessionService.EXTRA_STEAM_URL), intent.getStringExtra(SessionService.EXTRA_STEAM_URL),
intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS), intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS),
shownOnDisplayId,
) )
} }
applyFrameGen() applyFrameGen()
@@ -1619,7 +1491,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
surfaceW = width surfaceW = width
surfaceH = height surfaceH = height
if (resized) { if (resized) {
cancelTouchGestures()
Log.i(TAG, "surface resized to ${width}x$height - rebinding the compositor") Log.i(TAG, "surface resized to ${width}x$height - rebinding the compositor")
CompositorHost.resize(holder.surface) { applyFrameGen() } CompositorHost.resize(holder.surface) { applyFrameGen() }
followWindow(width, height) followWindow(width, height)
@@ -1638,7 +1509,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
} }
private fun followChoice(): Boolean { private fun followChoice(): Boolean {
val mode = displayMode() val mode = SessionPrefs.prefMode(intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM)
return SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this)) == return SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this)) ==
com.droiddeck.launcher.session.SessionDisplay.FOLLOW_SCREEN com.droiddeck.launcher.session.SessionDisplay.FOLLOW_SCREEN
} }
@@ -1654,8 +1525,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onConfigurationChanged(newConfig: android.content.res.Configuration) { override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
super.onConfigurationChanged(newConfig) super.onConfigurationChanged(newConfig)
if (started) SessionService.setActivityDisplay(this, shownOnDisplayId)
cancelTouchGestures()
applyFollowOrientation(newConfig) applyFollowOrientation(newConfig)
applyUnfoldedControls() applyUnfoldedControls()
} }
@@ -1664,21 +1533,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
// Hiding the phone surface after a handoff delivers a late destruction // Hiding the phone surface after a handoff delivers a late destruction
// callback. It must not reset the new output's size or attachment. // callback. It must not reset the new output's size or attachment.
if (holder !== outputHolder()) return if (holder !== outputHolder()) return
cancelTouchGestures()
surfaceW = 0 surfaceW = 0
surfaceH = 0 surfaceH = 0
glassesOutputActive = false glassesOutputActive = false
CompositorHost.detach(holder.surface) CompositorHost.detach(holder.surface)
} }
private fun cancelTouchGestures() {
if (::touchscreenGestures.isInitialized) touchscreenGestures.cancel()
if (::touchpad.isInitialized) touchpad.cancel()
if (::scrollTouch.isInitialized) scrollTouch.cancel()
scrollTouchGesture = false
gesturePointerReady = false
}
private fun panelBounds(): android.graphics.Rect = if (Build.VERSION.SDK_INT >= 30) { private fun panelBounds(): android.graphics.Rect = if (Build.VERSION.SDK_INT >= 30) {
windowManager.maximumWindowMetrics.bounds windowManager.maximumWindowMetrics.bounds
} else { } else {
@@ -1688,11 +1548,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
android.graphics.Rect(0, 0, metrics.widthPixels, metrics.heightPixels) android.graphics.Rect(0, 0, metrics.widthPixels, metrics.heightPixels)
} }
private fun displayMode(): String = SessionPrefs.displayMode(this,
intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM, intent.getStringExtra(SessionService.EXTRA_PROGRAM))
private fun outputSize(): Pair<Int, Int> { private fun outputSize(): Pair<Int, Int> {
val mode = displayMode() val mode = SessionPrefs.prefMode(intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM)
val panel = com.droiddeck.launcher.session.SessionDisplay.panelSize(this) val panel = com.droiddeck.launcher.session.SessionDisplay.panelSize(this)
val program = intent.getStringExtra(SessionService.EXTRA_PROGRAM) val program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
val choice = if (intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_RUN && val choice = if (intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_RUN &&
@@ -1706,9 +1563,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
glassesScreen?.hz?.takeIf { it > 1f }?.let { return it } glassesScreen?.hz?.takeIf { it > 1f }?.let { return it }
val display = if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay val display = if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay
val wanted = window.attributes.preferredDisplayModeId val wanted = window.attributes.preferredDisplayModeId
val requested = display?.supportedModes?.firstOrNull { wanted != 0 && it.modeId == wanted }?.refreshRate val hz = display?.supportedModes?.firstOrNull { wanted != 0 && it.modeId == wanted }?.refreshRate
val running = display?.refreshRate?.takeIf { it > 1f } ?: display?.refreshRate ?: 60f
val hz = listOfNotNull(requested, running).minOrNull() ?: 60f
val mirrorCap = mirrorRefreshLimit().takeIf { it > 0 }?.toFloat() ?: Float.POSITIVE_INFINITY val mirrorCap = mirrorRefreshLimit().takeIf { it > 0 }?.toFloat() ?: Float.POSITIVE_INFINITY
val capped = minOf(hz, PerfMode.peakRefreshCap(this), mirrorCap) val capped = minOf(hz, PerfMode.peakRefreshCap(this), mirrorCap)
return if (capped > 1f) capped else 60f return if (capped > 1f) capped else 60f
@@ -1789,7 +1645,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun onSessionEnded(status: Int) { private fun onSessionEnded(status: Int) {
ended = true ended = true
++steamVrRequestGeneration
if (isInPictureInPictureMode) { if (isInPictureInPictureMode) {
runOnUiThread { finish() } runOnUiThread { finish() }
return return
@@ -1812,7 +1667,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return return
} }
Thread({ Thread({
val hint = runtimeDamageHint() ?: sessionEndHint(SessionState.logFile) val hint = sessionEndHint(SessionState.logFile)
runOnUiThread { runOnUiThread {
if (isFinishing || isDestroyed) return@runOnUiThread if (isFinishing || isDestroyed) return@runOnUiThread
showEnded(status, hint) showEnded(status, hint)
@@ -1831,7 +1686,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionService.MODE_DESKTOP -> getString(R.string.session_ended_desktop) SessionService.MODE_DESKTOP -> getString(R.string.session_ended_desktop)
else -> getString(R.string.session_ended_named, "Steam") else -> getString(R.string.session_ended_named, "Steam")
} }
repairOffered = hint?.repair == true
loading.showEnded( loading.showEnded(
hint?.text ?: stopped, hint?.text ?: stopped,
getString(R.string.session_ended_detail, status, SessionState.logFile?.path ?: getString(R.string.session_ended_no_log)), getString(R.string.session_ended_detail, status, SessionState.logFile?.path ?: getString(R.string.session_ended_no_log)),
@@ -1850,13 +1704,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
uiHandler.post { sessionOverlay.requestFocus() } uiHandler.post { sessionOverlay.requestFocus() }
} }
private fun repairRuntime() {
val again = Intent(intent).putExtra(EXTRA_REPAIR_RUNTIME, true)
closeAtOnce = true
finish()
startActivity(again)
}
private fun retrySession() { private fun retrySession() {
val again = Intent(intent) val again = Intent(intent)
closeAtOnce = true closeAtOnce = true
@@ -1864,14 +1711,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
startActivity(again) startActivity(again)
} }
private class EndHint(val text: String, val evenOnSuccess: Boolean = false, val repair: Boolean = false) private class EndHint(val text: String, val evenOnSuccess: Boolean = false)
private fun runtimeDamageHint(): EndHint? {
val broken = runCatching { com.droiddeck.launcher.runtime.RuntimeHealth.brokenLibraryLinks(this) }.getOrDefault(emptyList())
if (broken.isEmpty()) return null
Log.w(TAG, "runtime has ${broken.size} broken library link(s): ${broken.take(8).joinToString()}")
return EndHint(resources.getQuantityString(R.plurals.session_end_runtime_damaged, broken.size, broken.size, broken.first()), repair = true)
}
private fun sessionEndHint(log: File?): EndHint? { private fun sessionEndHint(log: File?): EndHint? {
if (log == null || !log.isFile) return null if (log == null || !log.isFile) return null
@@ -1879,22 +1719,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
var enosys = 0 var enosys = 0
var fexMissing = false var fexMissing = false
val size = log.length() val size = log.length()
val text = java.io.RandomAccessFile(log, "r").use { f -> java.io.RandomAccessFile(log, "r").use { f ->
val start = maxOf(0L, size - 512L * 1024) val start = maxOf(0L, size - 512L * 1024)
f.seek(start) f.seek(start)
val bytes = ByteArray((size - start).toInt()) val bytes = ByteArray((size - start).toInt())
f.readFully(bytes) f.readFully(bytes)
String(bytes, Charsets.ISO_8859_1) String(bytes, Charsets.ISO_8859_1).lineSequence().forEach { line ->
if (line.contains("Function not implemented")) enosys++
if (line.contains(FEX_MISSING)) fexMissing = true
}
} }
text.lineSequence().forEach { line -> if (fexMissing) {
if (line.contains("Function not implemented")) enosys++
if (line.contains(FEX_MISSING)) fexMissing = true
}
val steamSetup = com.droiddeck.launcher.session.SteamClientSetupFailure.find(text.lineSequence())
if (steamSetup != null) {
val message = getString(if (steamSetup.download) R.string.session_end_steam_download else R.string.session_end_steam_setup)
EndHint(listOfNotNull(message, steamSetup.curlError).joinToString("\n"))
} else if (fexMissing) {
val what = com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_end_program) val what = com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_end_program)
EndHint(getString(R.string.session_end_fex_missing, what), evenOnSuccess = true) EndHint(getString(R.string.session_end_fex_missing, what), evenOnSuccess = true)
} else if (enosys >= 8) { } else if (enosys >= 8) {
@@ -2100,55 +1935,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
super.dispatchKeyEvent(event) super.dispatchKeyEvent(event)
} }
private fun refreshGestureConfig() {
gestureConfig = com.droiddeck.launcher.input.GesturePrefs.read(this, gestureGame)
if (::touchscreenGestures.isInitialized) touchscreenGestures.configure(gestureConfig)
gesturePointerReady = false
recognizedGesture = null
}
private val gestureOutput = object : TouchscreenGestures.Output {
override fun moveTo(x: Float, y: Float) {
val rect = drawnRect() ?: return
if (pointerLocked) {
if (gesturePointerReady) moveBy(x - gesturePointerX, y - gesturePointerY, true)
} else movePointer(x, y)
gesturePointerX = if (pointerLocked) x else x.coerceIn(rect.left, rect.right)
gesturePointerY = if (pointerLocked) y else y.coerceIn(rect.top, rect.bottom)
gesturePointerReady = true
cursorVisible = false
}
override fun moveBy(dx: Float, dy: Float, relative: Boolean) {
val rect = drawnRect() ?: return
if (relative || pointerLocked) {
val scale = SessionState.outputSize.first / rect.width()
WaylandCompositor.sendPointerDelta(dx * scale, dy * scale)
} else moveTo(gesturePointerX + dx, gesturePointerY + dy)
}
override fun button(code: Int, down: Boolean) {
WaylandCompositor.nativeSendSceneInput(3, code, if (down) 1 else 0)
}
override fun prepareRelativePan() {
if (pointerLocked) return
val rect = drawnRect() ?: return
// Gamescope retains the last absolute position while a game can warp
// its own cursor to the center. Its first unlocked motion must start
// from that same origin, before the game switches to pointer lock.
moveTo(rect.centerX(), rect.centerY())
}
override fun key(code: Int, down: Boolean) {
if (down) gestureKeysDown.add(code) else gestureKeysDown.remove(code)
if (code !in guestKeysDown) WaylandCompositor.nativeSendKey(code, if (down) 1 else 0)
}
override fun wheel(steps: Int) { WaylandCompositor.nativeSendSceneInput(4, steps, 0) }
override fun showKeyboard() { uiHandler.post { touchscreenGestures.cancel(); togglePcKeyboard() } }
override fun gesture(gesture: TouchscreenGestures.Gesture) {
recognizedGesture = gesture
uiHandler.removeCallbacks(clearRecognizedGesture)
uiHandler.postDelayed(clearRecognizedGesture, 1200)
}
}
private val pointerListener = object : PointerGestures.Listener { private val pointerListener = object : PointerGestures.Listener {
override fun onMove(x: Float, y: Float) { override fun onMove(x: Float, y: Float) {
if (pointerLocked) moveLockedPointer(x, y) else movePointer(x, y) if (pointerLocked) moveLockedPointer(x, y) else movePointer(x, y)
@@ -2283,13 +2069,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return true return true
} }
private val shownOnDisplayId: Int get() =
if (Build.VERSION.SDK_INT >= 30) display?.displayId ?: windowManager.defaultDisplay.displayId
else windowManager.defaultDisplay.displayId
private fun refreshSecondScreenDisplays() { private fun refreshSecondScreenDisplays() {
if (!::displayManager.isInitialized) return if (!::displayManager.isInitialized) return
val primaryId = shownOnDisplayId val primaryId = display?.displayId ?: windowManager.defaultDisplay.displayId
val candidates = SecondScreenDisplays.available(displayManager, primaryId) val candidates = SecondScreenDisplays.available(displayManager, primaryId)
.filter { glassesScreen == null || it.id != glasses.displayId } .filter { glassesScreen == null || it.id != glasses.displayId }
val oldIds = secondScreenDisplays.map { it.id }.toSet() val oldIds = secondScreenDisplays.map { it.id }.toSet()
@@ -2443,7 +2225,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (options == null || steamTouchControls?.visibility != View.VISIBLE) return SessionPrefs.touchMode(this) if (options == null || steamTouchControls?.visibility != View.VISIBLE) return SessionPrefs.touchMode(this)
return when { return when {
options.inputMode == com.droiddeck.launcher.input.SteamTouchConfig.INPUT_CONTROLLER -> SessionPrefs.TOUCH_OFF options.inputMode == com.droiddeck.launcher.input.SteamTouchConfig.INPUT_CONTROLLER -> SessionPrefs.TOUCH_OFF
SessionPrefs.touchMode(this) == SessionPrefs.TOUCH_GESTURES -> SessionPrefs.TOUCH_GESTURES
options.mouseMode == com.droiddeck.launcher.input.SteamTouchConfig.MOUSE_RELATIVE -> SessionPrefs.TOUCH_PAD options.mouseMode == com.droiddeck.launcher.input.SteamTouchConfig.MOUSE_RELATIVE -> SessionPrefs.TOUCH_PAD
else -> SessionPrefs.TOUCH_DIRECT else -> SessionPrefs.TOUCH_DIRECT
} }
@@ -2456,10 +2237,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
touchpad.sensitivity = 1.15f * speed touchpad.sensitivity = 1.15f * speed
} }
if (next == routedTouchMode) return if (next == routedTouchMode) return
if (::touchscreenGestures.isInitialized) touchscreenGestures.cancel()
gesturePointerReady = false
if (::touchpad.isInitialized) touchpad.cancel() if (::touchpad.isInitialized) touchpad.cancel()
if (::directTouchHold.isInitialized) directTouchHold.cancel()
if (::scrollTouch.isInitialized) scrollTouch.cancel() if (::scrollTouch.isInitialized) scrollTouch.cancel()
if (CompositorHost.isStarted) WaylandCompositor.nativeSendTouch(3, -1, 0, 0) if (CompositorHost.isStarted) WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
if (next == SessionPrefs.TOUCH_OFF) cursorVisible = false if (next == SessionPrefs.TOUCH_OFF) cursorVisible = false
@@ -2494,11 +2272,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onTouchEvent(event: MotionEvent): Boolean { override fun onTouchEvent(event: MotionEvent): Boolean {
if (event.isFromSource(android.view.InputDevice.SOURCE_MOUSE)) return onMouse(event) if (event.isFromSource(android.view.InputDevice.SOURCE_MOUSE)) return onMouse(event)
if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || pipUi || SessionState.suspended) return true
if (routedTouchMode == SessionPrefs.TOUCH_GESTURES) {
if (event.actionMasked == MotionEvent.ACTION_DOWN) gesturePointerReady = false
return touchscreenGestures.onTouch(event)
}
if (event.actionMasked == MotionEvent.ACTION_DOWN) { if (event.actionMasked == MotionEvent.ACTION_DOWN) {
scrollTouchGesture = scrollTouchMode() scrollTouchGesture = scrollTouchMode()
scrollRestX = 0f scrollRestX = 0f
@@ -2532,7 +2305,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL) ignoreGameTouch = false if (event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL) ignoreGameTouch = false
return true return true
} }
if (directTouchHold.onTouch(event)) return true
fun sendTouch(action: Int, index: Int) { fun sendTouch(action: Int, index: Int) {
val x = event.getX(index).coerceIn(rect.left, rect.right) val x = event.getX(index).coerceIn(rect.left, rect.right)
val y = event.getY(index).coerceIn(rect.top, rect.bottom) val y = event.getY(index).coerceIn(rect.top, rect.bottom)
@@ -2676,13 +2448,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
?.let { FileUtils.readString(it)?.trim()?.lowercase() } ?.let { FileUtils.readString(it)?.trim()?.lowercase() }
?: SessionPrefs.oscMode(this) ?: SessionPrefs.oscMode(this)
val controls = onScreenControls ?: return val controls = onScreenControls ?: return
if (pipUi || unfoldedPanel != null || pcKeyboardOpen) { if (pipUi || unfoldedPanel != null) {
onScreenButtonsVisible = false onScreenButtonsVisible = false
controls.releaseAll() controls.releaseAll()
controls.visibility = View.GONE controls.visibility = View.GONE
steamTouchControls?.let { it.releaseAll(); it.visibility = View.GONE } steamTouchControls?.let { it.releaseAll(); it.visibility = View.GONE }
com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = false com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = false
applyTouchRouting()
return return
} }
val buttonsOnly = forced == SessionPrefs.OSC_STEAM_QAM val buttonsOnly = forced == SessionPrefs.OSC_STEAM_QAM
@@ -2695,7 +2466,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (steam == null) { if (steam == null) {
steamTouchControls?.let { it.releaseAll(); it.visibility = View.GONE } steamTouchControls?.let { it.releaseAll(); it.visibility = View.GONE }
com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = false com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = false
applyTouchRouting()
} }
controls.setButtonsOnly(buttonsOnly) controls.setButtonsOnly(buttonsOnly)
val show = when (forced) { val show = when (forced) {
@@ -2708,33 +2478,29 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionState.mode != SessionService.MODE_DESKTOP SessionState.mode != SessionService.MODE_DESKTOP
} }
onScreenButtonsVisible = show onScreenButtonsVisible = show
val drawn = show && !keyboardCoversPad()
if (steam != null) { if (steam != null) {
if (controls.visibility == View.VISIBLE) { controls.releaseAll(); controls.visibility = View.GONE } if (controls.visibility == View.VISIBLE) { controls.releaseAll(); controls.visibility = View.GONE }
if (!drawn) steam.releaseAll() if (!show) steam.releaseAll()
steam.visibility = if (drawn) View.VISIBLE else View.GONE steam.visibility = if (show) View.VISIBLE else View.GONE
com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = show com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = show
applyTouchRouting() applyTouchRouting()
Log.i(TAG, "on-screen controls: Steam's touch controller " + if (drawn) "shown" else "hidden") Log.i(TAG, "on-screen controls: Steam's touch controller " + if (show) "shown" else "hidden")
return return
} }
if (drawn == (controls.visibility == View.VISIBLE)) return if (show == (controls.visibility == View.VISIBLE)) return
if (!drawn) controls.releaseAll() if (!show) controls.releaseAll()
controls.visibility = if (drawn) View.VISIBLE else View.GONE controls.visibility = if (show) View.VISIBLE else View.GONE
Log.i(TAG, "on-screen controls " + when { Log.i(TAG, "on-screen controls " + when {
!drawn -> "hidden" !show -> "hidden"
buttonsOnly -> "Steam + QAM" buttonsOnly -> "Steam + QAM"
else -> "full pad" else -> "full pad"
}) })
} }
private fun keyboardCoversPad() =
SessionState.mode == SessionService.MODE_STEAM && AgentGuest.steamKeyboard
private fun sendGuestKey(code: Int, down: Boolean) { private fun sendGuestKey(code: Int, down: Boolean) {
if (down && pipUi) return if (down && pipUi) return
if (down) guestKeysDown.add(code) else guestKeysDown.remove(code) if (down) guestKeysDown.add(code) else guestKeysDown.remove(code)
if (down || code !in gestureKeysDown) WaylandCompositor.nativeSendKey(code, if (down) 1 else 0) WaylandCompositor.nativeSendKey(code, if (down) 1 else 0)
} }
private fun pipBounds(): android.graphics.Rect { private fun pipBounds(): android.graphics.Rect {
@@ -2762,7 +2528,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
releasePads() releasePads()
touchpad.cancel() touchpad.cancel()
scrollTouch.cancel() scrollTouch.cancel()
directTouchHold.cancel()
guestKeysDown.toList().forEach { sendGuestKey(it, false) } guestKeysDown.toList().forEach { sendGuestKey(it, false) }
keyboard?.hide() keyboard?.hide()
sessionClipboard.stop() sessionClipboard.stop()
@@ -2816,7 +2581,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
refreshSecondScreenDisplays() refreshSecondScreenDisplays()
if (secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode) if (secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode)
startedScreens++ startedScreens++
SessionService.setActivityVisible(this, true, shownOnDisplayId) SessionService.setActivityVisible(this, true)
Glasses.rescan() Glasses.rescan()
updateGlassesScreen() updateGlassesScreen()
updateHandCamera() updateHandCamera()
@@ -2889,11 +2654,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onPause() { override fun onPause() {
if (runtimeRemovalBlocked) { super.onPause(); return } if (runtimeRemovalBlocked) { super.onPause(); return }
sessionClipboard.stop() sessionClipboard.stop()
if (::touchscreenGestures.isInitialized) touchscreenGestures.cancel()
if (::touchpad.isInitialized) touchpad.cancel()
if (::directTouchHold.isInitialized) directTouchHold.cancel()
uiHandler.removeCallbacks(clearRecognizedGesture)
gestureSettingsOpen = false
drawerOpen = false drawerOpen = false
pcKeyboardOpen = false pcKeyboardOpen = false
achievementsOpen = false achievementsOpen = false
@@ -2916,27 +2676,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
startActivity(android.content.Intent(this, QuestXrActivity::class.java)) startActivity(android.content.Intent(this, QuestXrActivity::class.java))
return return
} }
val request = ++steamVrRequestGeneration
val session = SessionState.sessionId
fun currentRequest() = request == steamVrRequestGeneration && session == SessionState.sessionId && !isDestroyed && !ended
if (action == "start") { if (action == "start") {
SessionState.steamVr = true SessionState.steamVr = true
steamVrAutoTried = true steamVrAutoTried = true
} }
if (action == "stop") { if (action == "stop") SessionState.steamVr = false
SessionState.steamVr = false
Glasses.cancelSteamVrStart()
}
if (glasses.present) { if (glasses.present) {
// Optional stereo starts only after RUNNING is observed. READY can // Optional stereo starts only after RUNNING is observed. READY can
// arrive repeatedly while the launch worker is still starting VR. // arrive repeatedly while the launch worker is still starting VR.
if (action == "install") steamVrStatus = SteamVr.Status.INSTALLING if (action == "install") steamVrStatus = SteamVr.Status.INSTALLING
runSteamVrAction(action, ::currentRequest) { steamVrWorker.execute {
val ok = SteamVr.run(this, action) val ok = SteamVr.run(this, action)
val now = SteamVr.status(this) val now = SteamVr.status(this)
uiHandler.post { uiHandler.post {
if (!currentRequest()) return@post
if (!ok && now != SteamVr.Status.RUNNING) Glasses.cancelSteamVrStart()
onSteamVrStatus(now) onSteamVrStatus(now)
if (!ok) Toast.makeText(this, getString(R.string.cardboard_steamvr_failed), Toast.LENGTH_LONG).show() if (!ok) Toast.makeText(this, getString(R.string.cardboard_steamvr_failed), Toast.LENGTH_LONG).show()
} }
@@ -2949,12 +2701,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
} }
if (action == "stop") restoreSteamVrPicture() if (action == "stop") restoreSteamVrPicture()
if (action == "install") steamVrStatus = SteamVr.Status.INSTALLING if (action == "install") steamVrStatus = SteamVr.Status.INSTALLING
runSteamVrAction(action, ::currentRequest) { steamVrWorker.execute {
val ok = SteamVr.run(this, action) val ok = SteamVr.run(this, action)
val now = SteamVr.status(this) val now = SteamVr.status(this)
uiHandler.post { uiHandler.post {
if (!currentRequest()) return@post
if (!ok && now != SteamVr.Status.RUNNING) Glasses.cancelSteamVrStart()
if (!ok && action == "start" && now != SteamVr.Status.RUNNING) restoreSteamVrPicture() if (!ok && action == "start" && now != SteamVr.Status.RUNNING) restoreSteamVrPicture()
onSteamVrStatus(now) onSteamVrStatus(now)
if (!ok) Toast.makeText(this, getString(R.string.cardboard_steamvr_failed), Toast.LENGTH_LONG).show() if (!ok) Toast.makeText(this, getString(R.string.cardboard_steamvr_failed), Toast.LENGTH_LONG).show()
@@ -2962,20 +2712,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
} }
} }
private fun runSteamVrAction(action: String, currentRequest: () -> Boolean, run: () -> Unit) {
if (action != "start") {
steamVrWorker.execute(run)
return
}
Glasses.prepareSteamVrStart {
uiHandler.post {
if (SessionState.steamVr && currentRequest()) steamVrWorker.execute {
if (SessionState.steamVr && currentRequest()) run()
}
}
}
}
private fun switchPictureForSteamVr() { private fun switchPictureForSteamVr() {
if (cardboard.source != Cardboard.SOURCE_SBS) { if (cardboard.source != Cardboard.SOURCE_SBS) {
SessionPrefs.setCardboardSourceBeforeSteamVr(this, cardboard.source) SessionPrefs.setCardboardSourceBeforeSteamVr(this, cardboard.source)
@@ -2986,21 +2722,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
steamVrSwitchedPicture = SessionPrefs.cardboardSourceBeforeSteamVr(this) >= 0 steamVrSwitchedPicture = SessionPrefs.cardboardSourceBeforeSteamVr(this) >= 0
} }
private fun usesSpatialControllers() =
GlassesRendering.usesGlasses(glasses, glassesScreen != null, steamVrStatus == SteamVr.Status.RUNNING) &&
glasses.usesSpatialControllers(glassesSettings)
private fun updateJoyConTracking() {
joyConVr?.setActive(steamVrStatus == SteamVr.Status.RUNNING &&
(ControllerPrefs.joyConVr(this) ||
(usesSpatialControllers() && glassesSettings.joyConTracking)))
}
private fun updateHandCamera() { private fun updateHandCamera() {
val joyCons = joyConVr?.holding == true val joyCons = joyConVr?.holding == true
val bare = !joyCons && !controllerConnected() val bare = !joyCons && !controllerConnected()
val want = started && steamVrStatus == SteamVr.Status.RUNNING && (joyCons || bare) && val want = started && steamVrStatus == SteamVr.Status.RUNNING && (joyCons || bare) &&
!usesSpatialControllers() &&
com.droiddeck.launcher.handtracking.HandTracking.wanted(this) com.droiddeck.launcher.handtracking.HandTracking.wanted(this)
handCamera?.bareHands = bare handCamera?.bareHands = bare
if (want == (handCamera != null)) return if (want == (handCamera != null)) return
@@ -3022,14 +2747,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
} }
private fun onSteamVrStatus(now: SteamVr.Status) { private fun onSteamVrStatus(now: SteamVr.Status) {
if (ended || isDestroyed) return
val was = steamVrStatus val was = steamVrStatus
steamVrStatus = now steamVrStatus = now
updateJoyConTracking() joyConVr?.setActive(now == SteamVr.Status.RUNNING && ControllerPrefs.joyConVr(this))
updateHandCamera() updateHandCamera()
autoStartSteamVr(now) autoStartSteamVr(now)
if ((was == SteamVr.Status.RUNNING) != (now == SteamVr.Status.RUNNING)) applyCardboard(cardboard) if ((was == SteamVr.Status.RUNNING) != (now == SteamVr.Status.RUNNING)) applyCardboard(cardboard)
if (now != SteamVr.Status.UNAVAILABLE) Glasses.setVrActive(now == SteamVr.Status.RUNNING)
if (glasses.present) onGlassesSteamVr(now) if (glasses.present) onGlassesSteamVr(now)
if (GlassesRendering.usesGlasses(glasses, glassesScreen != null, now == SteamVr.Status.RUNNING)) { if (GlassesRendering.usesGlasses(glasses, glassesScreen != null, now == SteamVr.Status.RUNNING)) {
return return
@@ -3085,17 +2808,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun updateHeadTracker() { private fun updateHeadTracker() {
val onGlasses = GlassesRendering.usesGlasses(glasses, glassesScreen != null, val onGlasses = GlassesRendering.usesGlasses(glasses, glassesScreen != null,
steamVrStatus == SteamVr.Status.RUNNING) steamVrStatus == SteamVr.Status.RUNNING)
SpatialTracking.setOutputUsesGlasses(onGlasses && !ended)
val c = activeCardboard val c = activeCardboard
val centerView = onGlasses && c.source == Cardboard.SOURCE_SCREEN
val want = !ended && (resumed || (glassesScreen != null && started)) && c.enabled && c.headTracking val want = !ended && (resumed || (glassesScreen != null && started)) && c.enabled && c.headTracking
val current = headTracker val current = headTracker
if (current != null && (!want || current.usesGlasses != onGlasses || current.centerView != centerView)) { if (current != null && (!want || current.usesGlasses != onGlasses)) {
current.stop() current.stop()
headTracker = null headTracker = null
} }
if (want) { if (want) {
val t = headTracker ?: HeadTracker(this, glasses = onGlasses, centerView = centerView) { val t = headTracker ?: HeadTracker(this, glasses = onGlasses) {
@Suppress("DEPRECATION") @Suppress("DEPRECATION")
(if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay)?.rotation ?: android.view.Surface.ROTATION_0 (if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay)?.rotation ?: android.view.Surface.ROTATION_0
}.also { headTracker = it } }.also { headTracker = it }
@@ -3104,18 +2825,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
headTracking = headTracker != null headTracking = headTracker != null
} }
private fun updateTrackingRecovery() {
val onGlasses = GlassesRendering.usesGlasses(glasses, glassesScreen != null,
steamVrStatus == SteamVr.Status.RUNNING)
val spatialView = onGlasses && SpatialTracking.selected && glassesSettings.positionalTracking &&
(SessionState.steamVr || steamVrStatus == SteamVr.Status.RUNNING ||
(glassesOutputActive && glassesSettings.headTracking && glassesSettings.picture3d == com.droiddeck.launcher.glasses.GlassesSettings.PICTURE_SCREEN))
val active = started && !ended && SessionState.running && !loading.visible && !pipUi && spatialView
if (active) SpatialTracking.refreshStatus()
trackingRecovery = TrackingRecovery.forSession(active, glasses.canControl, SpatialTracking.status.value)
glassesScreen?.trackingRecovery?.update(trackingRecovery, glasses.sbs)
}
private fun outputHolder(): SurfaceHolder = glassesScreen?.holder ?: surfaceView.holder private fun outputHolder(): SurfaceHolder = glassesScreen?.holder ?: surfaceView.holder
private fun onOutputAttached(holder: SurfaceHolder) { private fun onOutputAttached(holder: SurfaceHolder) {
@@ -3143,7 +2852,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun glassesOutputSize(): Pair<Int, Int>? { private fun glassesOutputSize(): Pair<Int, Int>? {
if (glassesScreen == null || glasses.width <= 0 || glasses.height <= 0) return null if (glassesScreen == null || glasses.width <= 0 || glasses.height <= 0) return null
val panel = (if (glasses.sbs) glasses.width / 2 else glasses.width) to glasses.height val panel = (if (glasses.sbs) glasses.width / 2 else glasses.width) to glasses.height
val mode = displayMode() val mode = SessionPrefs.prefMode(intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM)
val display = com.droiddeck.launcher.session.SessionDisplay val display = com.droiddeck.launcher.session.SessionDisplay
val choice = SessionPrefs.resolutionChoice(this, mode, panel) val choice = SessionPrefs.resolutionChoice(this, mode, panel)
val size = display.resolveChoice(panel, choice) val size = display.resolveChoice(panel, choice)
@@ -3154,7 +2863,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun onGlassesChanged() { private fun onGlassesChanged() {
val g = glasses val g = glasses
val s = glassesSettings val s = glassesSettings
val key = listOf(g.present, g.usable, g.displayId, g.sbs, g.sbs90, g.supports30Hz, g.switching3d, g.canControl, g.width, g.height, g.hz, g.resolutions, g.vrActive, s) val key = listOf(g.present, g.usable, g.displayId, g.sbs, g.sbs90, g.switching3d, g.canControl, g.width, g.height, g.hz, s)
if (key == glassesKey) return if (key == glassesKey) return
glassesKey = key glassesKey = key
updateGlassesScreen() updateGlassesScreen()
@@ -3188,7 +2897,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val target = if (want) Glasses.glassesDisplay()?.takeIf { it.isValid } else null val target = if (want) Glasses.glassesDisplay()?.takeIf { it.isValid } else null
val current = glassesScreen val current = glassesScreen
if (current != null && current.display.displayId == target?.displayId) { if (current != null && current.display.displayId == target?.displayId) {
current.prefer(Glasses.outputHz(), Glasses.outputResolution()) current.prefer(Glasses.outputHz())
applyOutputPacing() applyOutputPacing()
return return
} }
@@ -3197,7 +2906,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
runCatching { current.dismiss() } runCatching { current.dismiss() }
} }
if (target != null) { if (target != null) {
val screen = GlassesScreen(this, target, Glasses.outputHz(), this, Glasses.outputResolution()) val screen = GlassesScreen(this, target, Glasses.outputHz(), this)
// show() can create the surface synchronously. Select its holder // show() can create the surface synchronously. Select its holder
// first, otherwise surfaceCreated() rejects the glasses callback. // first, otherwise surfaceCreated() rejects the glasses callback.
glassesScreen = screen glassesScreen = screen
@@ -3269,10 +2978,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
super.onWindowFocusChanged(hasFocus) super.onWindowFocusChanged(hasFocus)
if (!hasFocus && ::padMouse.isInitialized) padMouse.reset() if (!hasFocus && ::padMouse.isInitialized) padMouse.reset()
if (runtimeRemovalBlocked) return if (runtimeRemovalBlocked) return
if (!hasFocus) {
if (::touchscreenGestures.isInitialized) touchscreenGestures.cancel()
if (::touchpad.isInitialized) touchpad.cancel()
}
if (hasFocus && !pipUi) { if (hasFocus && !pipUi) {
goFullscreen() goFullscreen()
refreshClipboard() refreshClipboard()
@@ -3383,7 +3088,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
companion object { companion object {
const val EXTRA_RETURN_HOME = "returnHome" const val EXTRA_RETURN_HOME = "returnHome"
const val EXTRA_STEAMVR = "steamVr" const val EXTRA_STEAMVR = "steamVr"
const val EXTRA_REPAIR_RUNTIME = "repairRuntime"
private const val LEAVE_TIMEOUT_MS = 1_500L private const val LEAVE_TIMEOUT_MS = 1_500L
private const val TAG = "SessionActivity" private const val TAG = "SessionActivity"
private var startedScreens = 0 private var startedScreens = 0
@@ -108,19 +108,15 @@ class AgentBridgeProvider : ContentProvider() {
val value = request.optString("value") val value = request.optString("value")
fun on() = value == "1" || value.equals("true", true) || value.equals("on", true) fun on() = value == "1" || value.equals("true", true) || value.equals("on", true)
val number = value.toIntOrNull() val number = value.toIntOrNull()
val numeric = setOf("refreshHz", "sbsHz", "brightness", "volume", "picture3d", "screenWidthDm", "screenDistanceDm", "vrFovDeg", "sbsSupport", "eyeHeightCm") val numeric = setOf("refreshHz", "sbsHz", "brightness", "volume", "picture3d", "screenWidthDm", "screenDistanceDm", "vrFovDeg", "sbsSupport")
if (key in numeric && number == null) return error("INVALID_VALUE", "'$key' takes a number") if (key in numeric && number == null) return error("INVALID_VALUE", "'$key' takes a number")
when (key) { when (key) {
"refreshHz" -> g.setRefreshHz(number!!) "refreshHz" -> g.setRefreshHz(number!!)
"sbsHz" -> g.setSbsHz(number!!) "sbsHz" -> g.setSbsHz(number!!)
"resolution2d" -> g.setResolution(com.droiddeck.launcher.glasses.GlassesDisplayProfile.TWO_D, value)
"resolution3d" -> g.setResolution(com.droiddeck.launcher.glasses.GlassesDisplayProfile.THREE_D, value)
"resolutionVr" -> g.setResolution(com.droiddeck.launcher.glasses.GlassesDisplayProfile.VR, value)
"brightness" -> g.setBrightness(number!!) "brightness" -> g.setBrightness(number!!)
"volume" -> g.setVolume(number!!) "volume" -> g.setVolume(number!!)
"sunblock" -> g.setSunblock(on()) "sunblock" -> g.setSunblock(on())
"3d" -> g.set3d(on()) "3d" -> g.set3d(on())
"3dof" -> g.set3dof(on())
"gameOnGlasses" -> g.setGameOnGlasses(on()) "gameOnGlasses" -> g.setGameOnGlasses(on())
"headTracking" -> g.setHeadTracking(on()) "headTracking" -> g.setHeadTracking(on())
"auto3d" -> g.setAuto3d(on()) "auto3d" -> g.setAuto3d(on())
@@ -129,10 +125,6 @@ class AgentBridgeProvider : ContentProvider() {
"screenDistanceDm" -> g.setScreenDistanceDm(number!!) "screenDistanceDm" -> g.setScreenDistanceDm(number!!)
"vrFovDeg" -> g.setVrFovDeg(number!!) "vrFovDeg" -> g.setVrFovDeg(number!!)
"sbsSupport" -> g.setSbsSupport(number!!) "sbsSupport" -> g.setSbsSupport(number!!)
"positionalTracking" -> g.setPositionalTracking(on())
"handControllers" -> g.setHandControllers(on())
"joyConTracking" -> g.setJoyConTracking(on())
"eyeHeightCm" -> g.setEyeHeight(number!!)
else -> return error("INVALID_KEY", "Unknown glasses setting '$key'") else -> return error("INVALID_KEY", "Unknown glasses setting '$key'")
} }
} }
@@ -144,34 +136,6 @@ class AgentBridgeProvider : ContentProvider() {
"calibrate" -> g.startCalibration() "calibrate" -> g.startCalibration()
"cancel-calibration" -> g.cancelCalibration() "cancel-calibration" -> g.cancelCalibration()
"reset-calibration" -> g.resetCalibration() "reset-calibration" -> g.resetCalibration()
"spatial-diagnostics" -> com.droiddeck.launcher.glasses.SpatialTracking.diagnostics(request.optBoolean("enabled",true))
"spatial-recenter" -> com.droiddeck.launcher.glasses.SpatialTracking.recenter(request.optBoolean("screen",false))
"spatial-floor" -> g.setSpatialFloor()
"spatial-restart" -> g.restartSpatialTracking()
"spatial-hand-options" -> {
AgentAccess.requireCommands(context)
if(request.has("lite")) com.droiddeck.launcher.glasses.SpatialTracking.setHandModel(request.getBoolean("lite"))
if(request.has("parallel")) com.droiddeck.launcher.glasses.SpatialTracking.setHandCpuParallel(request.getBoolean("parallel"))
if(request.has("halfRate")) com.droiddeck.launcher.glasses.SpatialTracking.setHandHalfRate(request.getBoolean("halfRate"))
if(request.has("adaptive")) com.droiddeck.launcher.glasses.SpatialTracking.setHandAdaptiveInput(request.getBoolean("adaptive"))
if(request.has("scheduled")) com.droiddeck.launcher.glasses.SpatialTracking.setHandScheduledTracking(request.getBoolean("scheduled"))
}
"spatial-hand-benchmark" -> {
AgentAccess.requireCommands(context)
com.droiddeck.launcher.glasses.SpatialTracking.benchmarkSavedCapture(request.getString("capture"))
}
"spatial-hand-capture" -> {
AgentAccess.requireCommands(context)
com.droiddeck.launcher.glasses.SpatialTracking.captureDiagnostic()
}
"spatial-rgb-capture", "spatial-rgb-status" -> {
AgentAccess.requireCommands(context)
return (if (request.getString("op") == "spatial-rgb-capture")
com.droiddeck.launcher.glasses.LumaRgbDiagnostic.capture(context!!,request.optString("transport","sdk"),
request.optInt("width",640),request.optInt("height",480),request.optInt("fps",30),
request.optInt("durationMs",5000))
else com.droiddeck.launcher.glasses.LumaRgbDiagnostic.status(context!!)).put("ok", true)
}
"query" -> { g.query(); Thread.sleep(600) } "query" -> { g.query(); Thread.sleep(600) }
"mode" -> { "mode" -> {
val mode = hex(request.optString("mode"), 0xFF) ?: return error("INVALID_VALUE", "mode must be one hex byte, e.g. 0x31") val mode = hex(request.optString("mode"), 0xFF) ?: return error("INVALID_VALUE", "mode must be one hex byte, e.g. 0x31")
@@ -5,7 +5,6 @@ import android.os.Handler
import android.os.Looper import android.os.Looper
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import android.os.FileObserver import android.os.FileObserver
import android.util.Log import android.util.Log
@@ -20,8 +19,6 @@ object AgentGuest {
private val main by lazy { Handler(Looper.getMainLooper()) } private val main by lazy { Handler(Looper.getMainLooper()) }
var focusRevision by mutableIntStateOf(0) var focusRevision by mutableIntStateOf(0)
private set private set
var steamKeyboard by mutableStateOf(false)
private set
private const val TAG = "AgentGuest" private const val TAG = "AgentGuest"
private const val POLL_MS = 50L private const val POLL_MS = 50L
private val lock = Any() private val lock = Any()
@@ -35,7 +32,6 @@ object AgentGuest {
observer?.stopWatching() observer?.stopWatching()
observer = null observer = null
lastFocusKey = null lastFocusKey = null
main.post { steamKeyboard = false }
val dir = dir(context) val dir = dir(context)
dir.deleteRecursively() dir.deleteRecursively()
dir.mkdirs() dir.mkdirs()
@@ -47,7 +43,6 @@ object AgentGuest {
SessionEvents.record("agent.ready", mapOf("pid" to it.optInt("pid"), "focus" to it.optBoolean("focus"))) SessionEvents.record("agent.ready", mapOf("pid" to it.optInt("pid"), "focus" to it.optBoolean("focus")))
} }
"focus.json" -> readJson(File(dir, path))?.let(::recordFocus) "focus.json" -> readJson(File(dir, path))?.let(::recordFocus)
"keyboard.json" -> readJson(File(dir, path))?.let { recordKeyboard(this, it) }
} }
} }
}.also { it.startWatching() } }.also { it.startWatching() }
@@ -58,19 +53,9 @@ object AgentGuest {
synchronized(lock) { synchronized(lock) {
observer?.stopWatching() observer?.stopWatching()
observer = null observer = null
main.post { steamKeyboard = false }
} }
} }
private fun recordKeyboard(source: FileObserver, snapshot: JSONObject) {
val showing = snapshot.optBoolean("steamKeyboard")
synchronized(lock) {
if (source !== observer) return
main.post { steamKeyboard = showing }
}
SessionEvents.record("keyboard.changed", mapOf("steamKeyboard" to showing, "seq" to snapshot.optInt("seq")))
}
private fun recordFocus(snapshot: JSONObject) { private fun recordFocus(snapshot: JSONObject) {
val fields = linkedMapOf<String, Any?>( val fields = linkedMapOf<String, Any?>(
"focusedApp" to snapshot.opt("focusedApp"), "focusedApp" to snapshot.opt("focusedApp"),
@@ -1,137 +0,0 @@
package com.droiddeck.launcher.core
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.BuildConfig
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileInputStream
/**
* A pack built by CI alongside this APK (tools/packs). Main and release builds publish it to
* DroidDeck-Components under a content-addressed tag; a PR test build attaches packs that are not there
* yet to its pr-N release on DroidDeck-CI. The APK pins the pack's SHA-256, so only the bytes this build
* was made with install, whichever host serves them.
*/
internal class AddonPack(val name: String, private val sha256: String, val size: Long, private val required: List<String>) {
sealed interface State {
data object Missing : State
data class Downloading(val progress: Float) : State
data object Failed : State
data object Ready : State
}
private val mutableState = MutableStateFlow<State>(State.Missing)
val state: StateFlow<State> = mutableState.asStateFlow()
private val lock = Any()
val available: Boolean get() = sha256.isNotEmpty()
private val tag get() = "pack-$name-${sha256.take(16)}"
private val urls get() = listOfNotNull(
"https://github.com/$REPO/releases/download/$tag/$name.tar.zst",
BuildConfig.PR_NUMBER.takeIf { it > 0 }?.let { "https://github.com/$PR_REPO/releases/download/pr-$it/$tag.tar.zst" },
)
private fun root(context: Context) = File(context.filesDir, "addons/$name")
/** App-private and written only after the archive matched the pinned digest. */
fun dir(context: Context) = File(root(context), sha256)
fun file(context: Context, relative: String) = File(dir(context), relative)
fun installed(context: Context): Boolean = available && File(dir(context), COMPLETE).isFile
fun refresh(context: Context): State {
val now = mutableState.value
if (now is State.Downloading) return now
return (if (installed(context)) State.Ready else if (now == State.Failed) State.Failed else State.Missing)
.also { mutableState.value = it }
}
/** Starts the download in the background unless the pack is already present or on its way. */
fun ensure(context: Context, onReady: (Context) -> Unit = {}) {
val app = context.applicationContext
synchronized(lock) {
if (installed(app)) { mutableState.value = State.Ready; return }
if (mutableState.value is State.Downloading) return
mutableState.value = State.Downloading(0f)
}
scope.launch {
val ok = runCatching { install(app) }.onFailure { Log.w(TAG, "$name: install failed", it) }.getOrDefault(false)
mutableState.value = if (ok) State.Ready else State.Failed
if (ok) onReady(app)
}
}
/** Blocks a worker thread until the pack is installed, starting the download if needed. */
@JvmOverloads
fun await(context: Context, running: () -> Boolean = { true }, onState: (State) -> Unit = {}): Boolean {
if (installed(context)) return true
ensure(context)
while (running()) {
val now = state.value
onState(now)
when (now) {
State.Ready -> return installed(context)
State.Failed -> return false
else -> try { Thread.sleep(250) } catch (e: InterruptedException) { return false }
}
}
return false
}
private fun install(context: Context): Boolean {
if (!available) {
Log.w(TAG, "$name: this build has no pack")
return false
}
val root = root(context).apply { mkdirs() }
val archive = File(root, "$sha256.tar.zst")
val downloaded = urls.any { url ->
Downloader.downloadFile(url, archive, true, sha256) { p -> mutableState.value = State.Downloading(p.coerceIn(0f, 1f)) }
.also { if (!it) archive.delete() }
}
if (!downloaded) return false
val staging = File(root, "$sha256.partial")
staging.deleteRecursively()
try {
if (!FileInputStream(archive).use { TarZst.extract(it, staging) }) return false
check(required.all { File(staging, it).isFile }) { "$name pack is incomplete" }
File(staging, COMPLETE).writeText(sha256)
val target = dir(context)
target.deleteRecursively()
check(staging.renameTo(target)) { "could not move the $name pack into place" }
} finally {
staging.deleteRecursively()
archive.delete()
}
root.listFiles().orEmpty().filter { it.name != sha256 }.forEach { it.deleteRecursively() }
return true
}
companion object {
private const val TAG = "AddonPack"
private const val REPO = "Droid-Deck/DroidDeck-Components"
private const val PR_REPO = "Droid-Deck/DroidDeck-CI"
const val COMPLETE = ".complete"
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
@JvmField
val PROOT = AddonPack("proot", BuildConfig.PACK_PROOT_SHA256, BuildConfig.PACK_PROOT_SIZE,
listOf("libproot.so", "libproot-loader.so"))
@JvmField
val DIRECTAUDIO = AddonPack("directaudio", BuildConfig.PACK_DIRECTAUDIO_SHA256, BuildConfig.PACK_DIRECTAUDIO_SIZE,
listOf("linux-wine11/version.txt", "linux-wine11-systhread/version.txt"))
val TRACKING = AddonPack("tracking", BuildConfig.PACK_TRACKING_SHA256, BuildConfig.PACK_TRACKING_SIZE, listOf(
"hand_landmarker.task", "hand_landmarker_lite.task", "pose_landmarker_lite.task",
"libopencv_java4.so", "libmediapipe_tasks_jni.so"))
val XBOX = AddonPack("xbox", BuildConfig.PACK_XBOX_SHA256, BuildConfig.PACK_XBOX_SIZE,
listOf("version", "xodus-cli", "xodus-service"))
val COMET = AddonPack("comet", BuildConfig.PACK_COMET_SHA256, BuildConfig.PACK_COMET_SIZE,
listOf("version", "comet"))
}
}
@@ -200,11 +200,9 @@ object DeviceReport {
h("Drivers") h("Drivers")
val gpu = com.droiddeck.launcher.gpu.GpuInfo.detect() val gpu = com.droiddeck.launcher.gpu.GpuInfo.detect()
k("GPU", "${gpu.name} · ${gpu.family.label} · ${gpu.supportText}" + if (gpu.oneUi8Gen2) " · One UI 8 Gen 2" else "") k("GPU", "${gpu.name} · ${gpu.family.label} · ${gpu.supportText}" + if (gpu.oneUi8Gen2) " · One UI 8 Gen 2" else "")
if (gpu.model == 740) k("TP UBWC hint", com.droiddeck.launcher.gpu.TpUbwcHint.forThisDevice() ?: "driver default")
k("Driver mode", SessionPrefs.gpuDriverMode(context) + k("Driver mode", SessionPrefs.gpuDriverMode(context) +
(com.droiddeck.launcher.gpu.DriverPairs.recommendedKey(gpu, com.droiddeck.launcher.gpu.DriverPairs.from( (com.droiddeck.launcher.gpu.DriverPairs.recommendedKey(gpu, com.droiddeck.launcher.gpu.DriverPairs.from(
com.droiddeck.launcher.gpu.TurnipReleases.cached(context)), com.droiddeck.launcher.gpu.TurnipReleases.autoPicks(context), com.droiddeck.launcher.gpu.TurnipReleases.cached(context)))?.let { " (recommended pair: $it)" } ?: ""))
com.droiddeck.launcher.gpu.AutoDriverTrial.bad(context))?.let { " (recommended pair: $it)" } ?: ""))
val turnip = TurnipDriver(context) val turnip = TurnipDriver(context)
val androidChoice = SessionPrefs.androidDriver(context) val androidChoice = SessionPrefs.androidDriver(context)
k("Display driver (chosen)", if (androidChoice.isEmpty()) "Auto -> ${turnip.autoId()}" else androidChoice) k("Display driver (chosen)", if (androidChoice.isEmpty()) "Auto -> ${turnip.autoId()}" else androidChoice)
@@ -225,9 +223,6 @@ object DeviceReport {
k("Installed version", LinuxRuntimeInstaller.installedVersion(context)) k("Installed version", LinuxRuntimeInstaller.installedVersion(context))
k("Runtime ready", LinuxRuntime.isInstalled(context)) k("Runtime ready", LinuxRuntime.isInstalled(context))
k("Desktop installed", DesktopCatalog.desktopInstalled(context)) k("Desktop installed", DesktopCatalog.desktopInstalled(context))
k("Interrupted installs", DesktopCatalog.interrupted(context).joinToString { "${it.id} ${it.version}" }.ifEmpty { "none" })
val broken = runCatching { com.droiddeck.launcher.runtime.RuntimeHealth.brokenLibraryLinks(context) }.getOrDefault(emptyList())
k("Broken library links", if (broken.isEmpty()) "none" else "${broken.size}: ${broken.take(8).joinToString()}")
k("Runtime root", LinuxRuntime.rootDir(context).path) k("Runtime root", LinuxRuntime.rootDir(context).path)
h("Settings in effect") h("Settings in effect")
@@ -38,7 +38,6 @@ object DownloadSource {
private val CATALOGS = listOf( private val CATALOGS = listOf(
"https://raw.githubusercontent.com/Droid-Deck/DroidDeck-CI/", "https://raw.githubusercontent.com/Droid-Deck/DroidDeck-CI/",
"https://raw.githubusercontent.com/Droid-Deck/DroidDeck-Components/", "https://raw.githubusercontent.com/Droid-Deck/DroidDeck-Components/",
"https://raw.githubusercontent.com/Droid-Deck/Drivers-CI/",
) )
data class Mirror(val host: String, val api: Boolean) data class Mirror(val host: String, val api: Boolean)
@@ -29,7 +29,6 @@ object GameEnvironment {
fun defaults(preset: String, forceSsbs: Boolean = false): Map<String, String?> = linkedMapOf<String, String?>( fun defaults(preset: String, forceSsbs: Boolean = false): Map<String, String?> = linkedMapOf<String, String?>(
"MESA_SHADER_CACHE_DISABLE" to "false", "MESA_SHADER_CACHE_DISABLE" to "false",
"DROIDDECK_ANTICHEAT_OFFLINE" to "1",
"VKD3D_FEATURE_LEVEL" to "12_2", "VKD3D_FEATURE_LEVEL" to "12_2",
"VKD3D_SHADER_MODEL" to "6_9", "VKD3D_SHADER_MODEL" to "6_9",
"DOTNET_GCRegionRange" to "800000000", "DOTNET_GCRegionRange" to "800000000",
@@ -51,29 +51,25 @@ object LogRedactor {
@Volatile @Volatile
private var accounts: List<Learned> = emptyList() private var accounts: List<Learned> = emptyList()
fun learnAccounts(vararg loginUsers: java.io.File) { fun learnAccounts(loginUsers: java.io.File) {
val names = LinkedHashSet<String>() val found = ArrayList<Learned>()
val kv = Regex("\"(AccountName|PersonaName)\"\\s+\"([^\"]*)\"") try {
var unread = false if (loginUsers.isFile) {
for (file in loginUsers) { val kv = Regex("\"(AccountName|PersonaName)\"\\s+\"([^\"]*)\"")
if (!file.isFile) continue kv.findAll(loginUsers.readText()).map { it.groupValues[2].trim() }.filter { it.length >= 3 }.distinct().forEach { name ->
val text = try { file.readText() } catch (e: Exception) { unread = true; continue } val needs = name.lowercase().takeIf { name.all { it.code < 0x80 } }
kv.findAll(text).map { it.groupValues[2].trim() }.filter { it.length >= 3 }.forEach { names += it } found += Learned(Regex("(?i)(?<![A-Za-z0-9_])" + Regex.escape(name) + "(?![A-Za-z0-9_])"), needs)
}
}
} catch (e: Exception) {
return
} }
val learned = names.map { name -> accounts = found
val needs = name.lowercase().takeIf { name.all { it.code < 0x80 } }
Learned(Regex("(?i)(?<![A-Za-z0-9_])" + Regex.escape(name) + "(?![A-Za-z0-9_])"), needs)
}
// A file that could not be read keeps the names learned from it before.
accounts = if (unread) (accounts + learned).distinctBy { it.regex.pattern } else learned
} }
fun learnFromRuntime(root: java.io.File) { fun learnFromRuntime(root: java.io.File) {
learnOwnAddresses(java.io.File(root, "etc/droiddeck-net")) learnOwnAddresses(java.io.File(root, "etc/droiddeck-net"))
learnAccounts( learnAccounts(java.io.File(root, "root/.local/share/Steam/config/loginusers.vdf"))
java.io.File(root, "root/.local/share/Steam/config/loginusers.vdf"),
java.io.File(root, "root/.droiddeck-x64/.local/share/Steam/config/loginusers.vdf"),
)
} }
@Volatile @Volatile
@@ -146,21 +142,16 @@ object LogRedactor {
return out return out
} }
/** The at-rest rewrite reads a file into memory twice; larger logs are only scrubbed on the way out. */ fun isText(file: java.io.File): Boolean = try {
const val IN_MEMORY_SCRUB_MAX = 64L * 1024 * 1024 file.isFile && file.length() < 64L * 1024 * 1024 && file.inputStream().use { input ->
fun isBinary(file: java.io.File): Boolean = try {
file.inputStream().use { input ->
val buf = ByteArray(4096) val buf = ByteArray(4096)
val n = input.read(buf) val n = input.read(buf)
n > 0 && (0 until n).any { buf[it].toInt() == 0 } n <= 0 || (0 until n).none { buf[it].toInt() == 0 }
} }
} catch (e: Exception) { } catch (e: Exception) {
true false
} }
fun isText(file: java.io.File): Boolean = file.isFile && file.length() < IN_MEMORY_SCRUB_MAX && !isBinary(file)
const val RULES_VERSION = 3 const val RULES_VERSION = 3
private val LAN_IPV4 = Regex( private val LAN_IPV4 = Regex(
@@ -181,62 +172,8 @@ object LogRedactor {
} }
} }
private const val SHARE_LINE_MAX = 64 * 1024
fun scrubForShare(src: java.io.File, out: java.io.Writer) { fun scrubForShare(src: java.io.File, out: java.io.Writer) {
src.inputStream().buffered().use { input -> src.forEachLine { line -> out.write(redactForShare(line)); out.write("\n") }
input.mark(2)
val first = input.read()
val second = input.read()
input.reset()
if ((first == 0xff && second == 0xfe) || (first == 0xfe && second == 0xff)) {
out.write("<unsupported encoding; file withheld>\n")
return
}
val decoder = Charsets.UTF_8.newDecoder()
.onMalformedInput(java.nio.charset.CodingErrorAction.REPORT)
.onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT)
java.io.InputStreamReader(input, decoder).use { reader ->
val buffer = CharArray(8192)
val line = StringBuilder()
var withheld = false
var afterCr = false
fun emit() {
out.write(if (withheld) "<unsupported or oversized line withheld>" else redactForShare(line.toString()))
out.write("\n")
line.setLength(0)
withheld = false
}
try {
while (true) {
val size = reader.read(buffer)
if (size < 0) break
for (i in 0 until size) {
val ch = buffer[i]
if (afterCr) {
afterCr = false
if (ch == '\n') continue
}
if (ch == '\r' || ch == '\n') {
emit()
afterCr = ch == '\r'
} else if (!withheld) {
// Splitting a line can separate a credential from its label.
if (ch == '\u0000' || line.length == SHARE_LINE_MAX) {
withheld = true
line.setLength(0)
} else {
line.append(ch)
}
}
}
}
if (withheld || line.isNotEmpty()) emit()
} catch (_: java.nio.charset.CharacterCodingException) {
out.write("<unsupported encoding; file withheld>\n")
}
}
}
} }
private fun quoted(value: String): String { private fun quoted(value: String): String {
@@ -85,7 +85,7 @@ class AppFilesProvider : DocumentsProvider() {
override fun deleteDocument(documentId: String) { override fun deleteDocument(documentId: String) {
val file = fileFor(documentId) val file = fileFor(documentId)
if (file.canonicalPath == baseCanonical) throw FileNotFoundException("the app folder itself is not deleted") if (file.absolutePath == base.absolutePath) throw FileNotFoundException("the app folder itself is not deleted")
try { try {
deleteTree(file.toPath()) deleteTree(file.toPath())
} catch (e: IOException) { } catch (e: IOException) {
@@ -154,7 +154,7 @@ class AppFilesProvider : DocumentsProvider() {
private fun fileFor(documentId: String): File { private fun fileFor(documentId: String): File {
val f = File(documentId) val f = File(documentId)
if (!f.isAbsolute || f.normalize().path != documentId || !inside(f)) throw FileNotFoundException("$documentId is outside the app's files") if (!f.isAbsolute || !inside(f)) throw FileNotFoundException("$documentId is outside the app's files")
if (!f.exists()) throw FileNotFoundException("$documentId not found") if (!f.exists()) throw FileNotFoundException("$documentId not found")
return f return f
} }
@@ -90,7 +90,6 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.session.SessionPrefs
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import java.io.File import java.io.File
@@ -152,11 +151,8 @@ fun FileManagerScreen(
var conflictChoice by remember { mutableStateOf<ConflictChoice?>(null) } var conflictChoice by remember { mutableStateOf<ConflictChoice?>(null) }
var conflictApplyToAll by remember { mutableStateOf(false) } var conflictApplyToAll by remember { mutableStateOf(false) }
var operationJob by remember { mutableStateOf<kotlinx.coroutines.Job?>(null) } var operationJob by remember { mutableStateOf<kotlinx.coroutines.Job?>(null) }
var cancelledJob by remember { mutableStateOf<kotlinx.coroutines.Job?>(null) }
var pendingBulkDelete by remember { mutableStateOf<List<File>>(emptyList()) } var pendingBulkDelete by remember { mutableStateOf<List<File>>(emptyList()) }
var searchQuery by remember { mutableStateOf("") } var searchQuery by remember { mutableStateOf("") }
val visibleEntries = if (searchQuery.isBlank()) entries
else entries.filter { it.name.contains(searchQuery, ignoreCase = true) }
var showSearch by remember { mutableStateOf(false) } var showSearch by remember { mutableStateOf(false) }
var sortBy by remember { mutableStateOf(browsePrefs.getString("fmSortBy", "name") ?: "name") } var sortBy by remember { mutableStateOf(browsePrefs.getString("fmSortBy", "name") ?: "name") }
var sortDesc by remember { mutableStateOf(browsePrefs.getBoolean("fmSortDesc", false)) } var sortDesc by remember { mutableStateOf(browsePrefs.getBoolean("fmSortDesc", false)) }
@@ -178,20 +174,16 @@ fun FileManagerScreen(
var showFavorites by remember { mutableStateOf(false) } var showFavorites by remember { mutableStateOf(false) }
var favTick by remember { mutableIntStateOf(0) } var favTick by remember { mutableIntStateOf(0) }
var listingJob by remember { mutableStateOf<kotlinx.coroutines.Job?>(null) }
fun loadDirectory(dir: File, resetScroll: Boolean = true) { fun loadDirectory(dir: File, resetScroll: Boolean = true) {
currentDir = dir currentDir = dir
if (pickMode) pickPrefs.edit().putString("lastFilePickerDir", dir.absolutePath).apply() if (pickMode) pickPrefs.edit().putString("lastFilePickerDir", dir.absolutePath).apply()
listingJob?.cancel() scope.launch {
listingJob = scope.launch {
val list = withContext(Dispatchers.IO) { val list = withContext(Dispatchers.IO) {
dir.listFiles()?.toList() dir.listFiles()?.toList()
?.filter { if (pickDirMode) it.isDirectory else !pickMode || it.isDirectory || matchesPickExt(it) } ?.filter { if (pickDirMode) it.isDirectory else !pickMode || it.isDirectory || matchesPickExt(it) }
?.filter { showHidden || !it.name.startsWith(".") } ?.filter { showHidden || !it.name.startsWith(".") }
?.sortedWith(comparatorFor(sortBy, sortDesc)) ?: emptyList() ?.sortedWith(comparatorFor(sortBy, sortDesc)) ?: emptyList()
} }
if (currentDir != dir) return@launch
entries = list entries = list
if (resetScroll) listState.scrollToItem(0) if (resetScroll) listState.scrollToItem(0)
} }
@@ -228,7 +220,7 @@ fun FileManagerScreen(
fun uniqueDestination(dir: File, name: String): File { fun uniqueDestination(dir: File, name: String): File {
var candidate = File(dir, name) var candidate = File(dir, name)
if (!java.nio.file.Files.exists(candidate.toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS)) return candidate if (!candidate.exists()) return candidate
val dot = name.lastIndexOf('.') val dot = name.lastIndexOf('.')
val base = if (dot > 0) name.substring(0, dot) else name val base = if (dot > 0) name.substring(0, dot) else name
val ext = if (dot > 0) name.substring(dot) else "" val ext = if (dot > 0) name.substring(dot) else ""
@@ -236,7 +228,7 @@ fun FileManagerScreen(
do { do {
candidate = File(dir, "$base ($i)$ext") candidate = File(dir, "$base ($i)$ext")
i++ i++
} while (java.nio.file.Files.exists(candidate.toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS)) } while (candidate.exists())
return candidate return candidate
} }
@@ -260,7 +252,7 @@ fun FileManagerScreen(
fun performPaste() { fun performPaste() {
val sources = clipboardFiles val sources = clipboardFiles
if (sources.isEmpty() || isOperationRunning || operationJob?.isActive == true || cancelledJob?.isCompleted == false) return if (sources.isEmpty()) return
val dstDir = currentDir val dstDir = currentDir
val cut = isCutOperation val cut = isCutOperation
@@ -269,7 +261,6 @@ fun FileManagerScreen(
operationDeterminate = true operationDeterminate = true
operationLabel = context.getString(if (cut) R.string.fm_op_moving else R.string.fm_op_copying) operationLabel = context.getString(if (cut) R.string.fm_op_moving else R.string.fm_op_copying)
isOperationRunning = true isOperationRunning = true
val job = coroutineContext[kotlinx.coroutines.Job]
var applyToAll: ConflictChoice? = null var applyToAll: ConflictChoice? = null
var failed = 0 var failed = 0
@@ -287,7 +278,7 @@ fun FileManagerScreen(
} }
var dst = File(dstDir, src.name) var dst = File(dstDir, src.name)
if (java.nio.file.Files.exists(dst.toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS)) { if (dst.exists()) {
val choice = applyToAll ?: askConflict(src)?.also { val choice = applyToAll ?: askConflict(src)?.also {
if (conflictApplyToAll) applyToAll = it if (conflictApplyToAll) applyToAll = it
} ?: run { skipped++; null } ?: continue } ?: run { skipped++; null } ?: continue
@@ -305,7 +296,6 @@ fun FileManagerScreen(
} }
var lastPct = -1 var lastPct = -1
val onProgress = FileOps.ProgressCallback { copied, total -> val onProgress = FileOps.ProgressCallback { copied, total ->
job?.ensureActive()
val pct = if (total > 0) ((copied * 100) / total).toInt() else 100 val pct = if (total > 0) ((copied * 100) / total).toInt() else 100
if (pct != lastPct) { if (pct != lastPct) {
lastPct = pct lastPct = pct
@@ -314,8 +304,8 @@ fun FileManagerScreen(
} }
val target = dst val target = dst
val ok = withContext(Dispatchers.IO) { val ok = withContext(Dispatchers.IO) {
if (cut) FileOps.moveWithProgress(src, target, onProgress) { job?.isActive == false } if (cut) FileOps.moveWithProgress(src, target, onProgress)
else FileOps.copyWithProgress(src, target, onProgress) { job?.isActive == false } else FileOps.copyWithProgress(src, target, onProgress)
} }
if (ok) done++ else failed++ if (ok) done++ else failed++
} }
@@ -801,21 +791,19 @@ fun FileManagerScreen(
fontSize = 13.sp, fontSize = 13.sp,
modifier = Modifier.weight(1f), modifier = Modifier.weight(1f),
) )
val allVisibleSelected = visibleEntries.isNotEmpty() && visibleEntries.all { it.absolutePath in selectedPaths }
val anyVisibleSelected = visibleEntries.any { it.absolutePath in selectedPaths }
val selBarPadding = PaddingValues(horizontal = 10.dp, vertical = 2.dp) val selBarPadding = PaddingValues(horizontal = 10.dp, vertical = 2.dp)
OutlinedButton( OutlinedButton(
onClick = { onClick = {
val shown = visibleEntries.map { it.absolutePath } selectedPaths = if (selectedPaths.size == entries.size) emptySet()
selectedPaths = if (allVisibleSelected) selectedPaths - shown.toSet() else selectedPaths + shown else entries.map { it.absolutePath }.toSet()
}, },
contentPadding = selBarPadding, contentPadding = selBarPadding,
) { Text(if (allVisibleSelected) stringResource(R.string.fm_select_none) else stringResource(R.string.fm_select_all), fontSize = 12.sp) } ) { Text(if (selectedPaths.size == entries.size) stringResource(R.string.fm_select_none) else stringResource(R.string.fm_select_all), fontSize = 12.sp) }
Spacer(Modifier.width(4.dp)) Spacer(Modifier.width(4.dp))
OutlinedButton( OutlinedButton(
enabled = anyVisibleSelected, enabled = selectedPaths.isNotEmpty(),
onClick = { onClick = {
clipboardFiles = visibleEntries.filter { it.absolutePath in selectedPaths } clipboardFiles = entries.filter { it.absolutePath in selectedPaths }
isCutOperation = false isCutOperation = false
selectionMode = false selectionMode = false
selectedPaths = emptySet() selectedPaths = emptySet()
@@ -824,9 +812,9 @@ fun FileManagerScreen(
) { Text(stringResource(R.string.fm_copy), fontSize = 12.sp) } ) { Text(stringResource(R.string.fm_copy), fontSize = 12.sp) }
Spacer(Modifier.width(4.dp)) Spacer(Modifier.width(4.dp))
OutlinedButton( OutlinedButton(
enabled = anyVisibleSelected, enabled = selectedPaths.isNotEmpty(),
onClick = { onClick = {
clipboardFiles = visibleEntries.filter { it.absolutePath in selectedPaths } clipboardFiles = entries.filter { it.absolutePath in selectedPaths }
isCutOperation = true isCutOperation = true
selectionMode = false selectionMode = false
selectedPaths = emptySet() selectedPaths = emptySet()
@@ -835,8 +823,8 @@ fun FileManagerScreen(
) { Text(stringResource(R.string.fm_cut), fontSize = 12.sp) } ) { Text(stringResource(R.string.fm_cut), fontSize = 12.sp) }
Spacer(Modifier.width(4.dp)) Spacer(Modifier.width(4.dp))
OutlinedButton( OutlinedButton(
enabled = anyVisibleSelected, enabled = selectedPaths.isNotEmpty(),
onClick = { pendingBulkDelete = visibleEntries.filter { it.absolutePath in selectedPaths } }, onClick = { pendingBulkDelete = entries.filter { it.absolutePath in selectedPaths } },
contentPadding = selBarPadding, contentPadding = selBarPadding,
border = BorderStroke(1.dp, MaterialTheme.colorScheme.error), border = BorderStroke(1.dp, MaterialTheme.colorScheme.error),
) { Text(stringResource(R.string.common_delete), color = MaterialTheme.colorScheme.error, fontSize = 12.sp) } ) { Text(stringResource(R.string.common_delete), color = MaterialTheme.colorScheme.error, fontSize = 12.sp) }
@@ -854,7 +842,7 @@ fun FileManagerScreen(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.background(MaterialTheme.colorScheme.outline.copy(alpha = 0.1f)) .background(MaterialTheme.colorScheme.outline.copy(alpha = 0.1f))
.clickable(enabled = !isOperationRunning) { performPaste() } .clickable { performPaste() }
.padding(horizontal = 16.dp, vertical = 8.dp), .padding(horizontal = 16.dp, vertical = 8.dp),
) { ) {
Icon(Icons.Filled.ContentPaste, stringResource(R.string.fm_paste), tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp)) Icon(Icons.Filled.ContentPaste, stringResource(R.string.fm_paste), tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp))
@@ -890,7 +878,6 @@ fun FileManagerScreen(
) )
if (operationJob != null) { if (operationJob != null) {
TextButton(onClick = { TextButton(onClick = {
cancelledJob = operationJob
operationJob?.cancel() operationJob?.cancel()
operationJob = null operationJob = null
isOperationRunning = false isOperationRunning = false
@@ -977,7 +964,8 @@ fun FileManagerScreen(
.fillMaxSize() .fillMaxSize()
.nestedScroll(pullState.nestedScrollConnection), .nestedScroll(pullState.nestedScrollConnection),
) { ) {
val shownEntries = visibleEntries val shownEntries = if (searchQuery.isBlank()) entries
else entries.filter { it.name.contains(searchQuery, ignoreCase = true) }
if (showGrid && entries.isNotEmpty()) { if (showGrid && entries.isNotEmpty()) {
LazyVerticalGrid( LazyVerticalGrid(
@@ -45,26 +45,23 @@ object FileOps {
return f.length() return f.length()
} }
fun moveWithProgress(src: File, dst: File, progress: ProgressCallback?, isCancelled: () -> Boolean = { false }): Boolean { fun moveWithProgress(src: File, dst: File, progress: ProgressCallback?): Boolean {
if (sameFile(src, dst)) return true if (sameFile(src, dst)) return true
if (isCancelled()) return false
if (!dst.exists() && src.renameTo(dst)) { if (!dst.exists() && src.renameTo(dst)) {
progress?.onProgress(1, 1) progress?.onProgress(1, 1)
return true return true
} }
if (!copyWithProgress(src, dst, progress, isCancelled)) return false if (!copyWithProgress(src, dst, progress)) return false
if (isCancelled()) return false
return delete(src) return delete(src)
} }
fun copyWithProgress(src: File, dst: File, progress: ProgressCallback?, isCancelled: () -> Boolean = { false }): Boolean { fun copyWithProgress(src: File, dst: File, progress: ProgressCallback?): Boolean {
val total = maxOf(totalSize(src), 1L) val total = maxOf(totalSize(src), 1L)
return copyWithProgress(src, dst, longArrayOf(0), total, progress, isCancelled) return copyWithProgress(src, dst, longArrayOf(0), total, progress)
} }
private fun copyWithProgress(src: File, dst: File, done: LongArray, total: Long, progress: ProgressCallback?, isCancelled: () -> Boolean): Boolean { private fun copyWithProgress(src: File, dst: File, done: LongArray, total: Long, progress: ProgressCallback?): Boolean {
if (isCancelled()) throw java.util.concurrent.CancellationException("Copy cancelled: $src") if (isSymlink(src)) return true
if (isSymlink(src)) return copyLink(src, dst)
if (sameFile(src, dst)) return true if (sameFile(src, dst)) return true
if (src.isDirectory && isWithin(dst, src)) { if (src.isDirectory && isWithin(dst, src)) {
Log.e(TAG, "Refusing to copy directory into itself: $src -> $dst") Log.e(TAG, "Refusing to copy directory into itself: $src -> $dst")
@@ -74,7 +71,7 @@ object FileOps {
if (!dst.exists() && !dst.mkdirs()) return false if (!dst.exists() && !dst.mkdirs()) return false
var allOk = true var allOk = true
src.list()?.forEach { name -> src.list()?.forEach { name ->
if (!copyWithProgress(File(src, name), File(dst, name), done, total, progress, isCancelled)) { if (!copyWithProgress(File(src, name), File(dst, name), done, total, progress)) {
Log.e(TAG, "Failed to copy: ${File(src, name)}") Log.e(TAG, "Failed to copy: ${File(src, name)}")
allOk = false allOk = false
} }
@@ -84,41 +81,13 @@ object FileOps {
val parent = dst.parentFile val parent = dst.parentFile
if (!src.exists() || (parent != null && !parent.exists() && !parent.mkdirs())) return false if (!src.exists() || (parent != null && !parent.exists() && !parent.mkdirs())) return false
val chunk = 4L * 1024 * 1024 val chunk = 4L * 1024 * 1024
var staging: File? = null
var created = false
var output: java.nio.channels.FileChannel? = null
try { try {
output = try {
java.nio.channels.FileChannel.open(dst.toPath(), java.nio.file.StandardOpenOption.WRITE, java.nio.file.StandardOpenOption.CREATE_NEW)
.also { created = true }
} catch (e: java.nio.file.FileAlreadyExistsException) {
null
}
val target = if (!created && isSymlink(dst)) dst.canonicalFile else dst
var permissions: Set<java.nio.file.attribute.PosixFilePermission>? = null
if (output == null) {
if (isSymlink(target) || target.parentFile?.isDirectory != true) {
throw IOException("Destination symlink target is not a writable directory entry: $dst")
}
if (target.isDirectory) throw IOException("Destination is a directory: $target")
permissions = try {
Files.getPosixFilePermissions(target.toPath())
} catch (e: java.nio.file.NoSuchFileException) {
null
} catch (e: UnsupportedOperationException) {
null
}
if (target.exists() && !target.canWrite()) throw IOException("Destination is not writable: $target")
val directory = Files.createTempDirectory(checkNotNull(target.absoluteFile.parentFile).toPath(), ".droiddeck-copy-")
staging = directory.toFile()
output = FileOutputStream(File(staging, "file")).channel
}
FileInputStream(src).channel.use { input -> FileInputStream(src).channel.use { input ->
checkNotNull(output).use { channel -> FileOutputStream(dst).channel.use { output ->
val size = input.size() val size = input.size()
var position = 0L var position = 0L
while (position < size) { while (position < size) {
val transferred = input.transferTo(position, minOf(chunk, size - position), channel) val transferred = input.transferTo(position, minOf(chunk, size - position), output)
if (transferred <= 0) break if (transferred <= 0) break
position += transferred position += transferred
done[0] += transferred done[0] += transferred
@@ -127,54 +96,11 @@ object FileOps {
if (position < size) throw IOException("Incomplete copy: $position/$size bytes") if (position < size) throw IOException("Incomplete copy: $position/$size bytes")
} }
} }
staging?.let { directory ->
val copied = File(directory, "file").toPath()
if (permissions != null && Files.getPosixFilePermissions(copied) != permissions) {
Files.setPosixFilePermissions(copied, permissions)
}
if (isCancelled()) throw java.util.concurrent.CancellationException("Copy cancelled: $src")
Files.move(copied, target.toPath(), java.nio.file.StandardCopyOption.ATOMIC_MOVE)
}
return true return true
} catch (e: java.util.concurrent.CancellationException) {
if (created) dst.delete()
throw e
} catch (e: IOException) { } catch (e: IOException) {
Log.e(TAG, "Failed to copy file: $src to $dst", e) Log.e(TAG, "Failed to copy file: $src to $dst", e)
if (created) dst.delete() dst.delete()
return false return false
} finally {
output?.close()
staging?.let { directory ->
File(directory, "file").delete()
directory.delete()
}
}
}
private fun copyLink(src: File, dst: File): Boolean {
if (src.absoluteFile == dst.absoluteFile) return true
return try {
val target = Files.readSymbolicLink(src.toPath())
val parent = dst.parentFile
if (parent != null && !parent.exists() && !parent.mkdirs()) return false
try {
Files.createSymbolicLink(dst.toPath(), target)
} catch (e: java.nio.file.FileAlreadyExistsException) {
val staging = Files.createTempDirectory(checkNotNull(dst.absoluteFile.parentFile).toPath(), ".droiddeck-link-")
val tmp = staging.resolve("link")
try {
Files.createSymbolicLink(tmp, target)
Files.move(tmp, dst.toPath(), java.nio.file.StandardCopyOption.ATOMIC_MOVE)
} finally {
Files.deleteIfExists(tmp)
Files.deleteIfExists(staging)
}
}
true
} catch (e: Exception) {
Log.e(TAG, "Failed to copy link: $src to $dst", e)
false
} }
} }
@@ -41,20 +41,10 @@ object AddedGames {
return SessionPrefs.gameFolderBinds(context).map { (host, guest) -> Root(File(host), guest) } return SessionPrefs.gameFolderBinds(context).map { (host, guest) -> Root(File(host), guest) }
} }
private val SKIP_PREFIX = Regex("(?i)^(unins|setup|vc_?redist|dxsetup|dxwebsetup|dotnet|directx|easyanticheat|battleye).*") private val SKIP = Regex(
private val SKIP_PART = Regex("(?i)redist|prereq|installer|uninstall|crashreport|crashhandler|crashpad|crashsender|launchhelper") "(?i)^(unins.*|setup.*|.*redist.*|vcredist.*|dxsetup.*|dxwebsetup.*|.*crash.*|.*report.*|dotnet.*|directx.*|.*prereq.*" +
private val SKIP_WORDS = setOf( "|.*installer.*|.*uninstall.*|.*updater?.*|.*config(ur.*)?|.*settings.*|.*editor.*|.*server.*|.*benchmark.*|.*helper.*|.*eac.*|.*easyanticheat.*|.*battleye.*)\\.exe$",
"eac", "report", "reporter", "editor", "server", "benchmark", "helper",
"update", "updater", "config", "configure", "configurator", "configuration", "settings",
) )
private val WORD = Regex("[A-Z]?[a-z]+|[A-Z]+(?![a-z])|[0-9]+")
internal fun skipExe(name: String): Boolean {
if (!name.endsWith(".exe", ignoreCase = true)) return false
val base = name.dropLast(4)
if (SKIP_PREFIX.matches(base) || SKIP_PART.containsMatchIn(base)) return true
return WORD.findAll(base).any { it.value.lowercase() in SKIP_WORDS }
}
const val GUEST_DIR = "/root/Games" const val GUEST_DIR = "/root/Games"
@@ -85,7 +75,7 @@ object AddedGames {
val key = "${folder.path}|${folder.lastModified()}" val key = "${folder.path}|${folder.lastModified()}"
val now = System.currentTimeMillis() val now = System.currentTimeMillis()
ranked[key]?.takeIf { now - it.first < RANK_FRESH_MS }?.let { return it.second } ranked[key]?.takeIf { now - it.first < RANK_FRESH_MS }?.let { return it.second }
val guessed = GameExePicker.rank(folder) { !skipExe(it.name) } val guessed = GameExePicker.rank(folder) { !SKIP.matches(it.name) }
val declared = declaredExes(folder) val declared = declaredExes(folder)
val preferred = declared.map { it.path }.toSet() val preferred = declared.map { it.path }.toSet()
val result = if (declared.isEmpty()) guessed else GameExePicker.Ranking( val result = if (declared.isEmpty()) guessed else GameExePicker.Ranking(
@@ -138,7 +128,7 @@ object AddedGames {
val root = runCatching { folder.canonicalPath + File.separator }.getOrNull() ?: return emptyList() val root = runCatching { folder.canonicalPath + File.separator }.getOrNull() ?: return emptyList()
return names.asSequence() return names.asSequence()
.map { File(folder, it.trim().replace('\\', '/').trimStart('/')) } .map { File(folder, it.trim().replace('\\', '/').trimStart('/')) }
.filter { it.name.endsWith(".exe", ignoreCase = true) && !skipExe(it.name) && it.isFile } .filter { it.name.endsWith(".exe", ignoreCase = true) && !SKIP.matches(it.name) && it.isFile }
.filter { runCatching { it.canonicalPath.startsWith(root) }.getOrDefault(false) } .filter { runCatching { it.canonicalPath.startsWith(root) }.getOrDefault(false) }
.distinctBy { it.path } .distinctBy { it.path }
.toList() .toList()
@@ -149,10 +139,6 @@ object AddedGames {
"appxmanifest.xml" to Regex("<Application\\b[^>]*?\\bExecutable\\s*=\\s*\"([^\"]+)\"", RegexOption.IGNORE_CASE), "appxmanifest.xml" to Regex("<Application\\b[^>]*?\\bExecutable\\s*=\\s*\"([^\"]+)\"", RegexOption.IGNORE_CASE),
) )
/** The card's Steam libraries: the arm64 client's steamapps and the x86-64 client's own folder beside it. */
internal fun isSteamLibraryFolder(name: String): Boolean =
name.equals("steamapps", ignoreCase = true) || name == com.droiddeck.launcher.session.GameStorage.X64_CARD_DIR
fun scan(context: Context): List<Game> { fun scan(context: Context): List<Game> {
val out = ArrayList<Game>() val out = ArrayList<Game>()
GamesFolderMigration.run(context) GamesFolderMigration.run(context)
@@ -165,7 +151,7 @@ object AddedGames {
if (!dir.isDirectory) { Log.w(TAG, "$dir is not a folder; skipped"); continue } if (!dir.isDirectory) { Log.w(TAG, "$dir is not a folder; skipped"); continue }
val steamInstalls = steamInstallDirs(dir) val steamInstalls = steamInstallDirs(dir)
for (folder in dir.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() } ?: emptyList()) { for (folder in dir.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() } ?: emptyList()) {
if (folder.name.lowercase() in steamInstalls || isSteamLibraryFolder(folder.name)) continue if (folder.name.lowercase() in steamInstalls || folder.name.equals("steamapps", ignoreCase = true)) continue
if (folder.path in removed) continue if (folder.path in removed) continue
if (folder.name == "Games" && StoreInstallRoot.roots(context).any { it.absolutePath == folder.absolutePath }) continue if (folder.name == "Games" && StoreInstallRoot.roots(context).any { it.absolutePath == folder.absolutePath }) continue
scanGame(context, folder, out) scanGame(context, folder, out)
@@ -214,10 +200,8 @@ object AddedGames {
GamesFolderMigration.run(context) GamesFolderMigration.run(context)
val path = canonical(exe) val path = canonical(exe)
fun holds(f: File) = inside(path, canonical(f)) fun holds(f: File) = inside(path, canonical(f))
val entries = AddedExes.list(context) AddedExes.list(context).map { File(it.folder) }.firstOrNull(::holds)?.let { return it }
fun owns(f: File) = holds(f) && sameGame(f, currentExe(context, entries, f), exe) SessionPrefs.removedAddedGames(context).map { File(it) }.firstOrNull(::holds)?.let { return it }
entries.map { File(it.folder) }.filter(::owns).maxByOrNull { canonical(it).length }?.let { return it }
SessionPrefs.removedAddedGames(context).map { File(it) }.filter(::owns).maxByOrNull { canonical(it).length }?.let { return it }
StoreInstallRoot.gameFolders(context).firstOrNull(::holds)?.let { return it } StoreInstallRoot.gameFolders(context).firstOrNull(::holds)?.let { return it }
val dirs = listOfNotNull( val dirs = listOfNotNull(
GameStorage.effective(context)?.let { File(it.path, "steamapps/common") }, GameStorage.effective(context)?.let { File(it.path, "steamapps/common") },
@@ -227,29 +211,11 @@ object AddedGames {
val base = canonical(dir) val base = canonical(dir)
if (!inside(path, base)) continue if (!inside(path, base)) continue
val first = path.removePrefix("$base/").substringBefore('/') val first = path.removePrefix("$base/").substringBefore('/')
File(dir, first).takeIf { it.isDirectory && !isSteamLibraryFolder(first) }?.let { return it } File(dir, first).takeIf { it.isDirectory && first != "steamapps" }?.let { return it }
} }
return null return null
} }
private fun currentExe(context: Context, entries: List<AddedExes.Entry>, folder: File): File? =
SessionPrefs.addedGameExe(context, folder.path).takeIf { it.isNotEmpty() }?.let(::File)
?: entries.firstOrNull { it.folder == folder.path }?.let { File(it.exe) }
?: rank(folder).exes.firstOrNull()
private fun sameGame(folder: File, current: File?, pick: File): Boolean {
val base = canonical(folder)
if (current == null || pick.parentFile?.let(::canonical) == base) return true
val known = canonical(current)
if (!inside(known, base) || known.substringBeforeLast('/') == base) return true
val picked = canonical(pick)
fun top(p: String) = p.removePrefix("$base/").substringBefore('/')
fun stem(p: String) = p.substringAfterLast('/').lowercase().removeSuffix(".exe").replace(EXE_BUILD, "").filter { it.isLetterOrDigit() }
return top(known) == top(picked) || stem(known).let { it.isNotEmpty() && it == stem(picked) }
}
private val EXE_BUILD = Regex("([-_. ](x64|x86|win64|win32|64|32|shipping))+$")
fun addExe(context: Context, exe: File): AddResult { fun addExe(context: Context, exe: File): AddResult {
val app = context.applicationContext val app = context.applicationContext
if (!exe.isFile) return AddResult.NotFound if (!exe.isFile) return AddResult.NotFound
@@ -258,10 +224,7 @@ object AddedGames {
if (owner != null && owner.path !in SessionPrefs.removedAddedGames(app)) { if (owner != null && owner.path !in SessionPrefs.removedAddedGames(app)) {
single(app, owner.path)?.takeIf { canonical(it.exe) == path }?.let { return AddResult.Existing(it) } single(app, owner.path)?.takeIf { canonical(it.exe) == path }?.let { return AddResult.Existing(it) }
} }
if (guestPath(app, exe) == null) { if (owner == null && guestPath(app, exe) == null) return AddResult.Unreachable
(owner ?: exe.parentFile)?.takeIf { guestPath(app, it) == null }?.let { bindFolder(app, it) }
if (guestPath(app, exe) == null) return AddResult.Unreachable
}
val folder = owner ?: exe.parentFile ?: return AddResult.NotFound val folder = owner ?: exe.parentFile ?: return AddResult.NotFound
SessionPrefs.setAddedGameRemoved(app, folder.path, false) SessionPrefs.setAddedGameRemoved(app, folder.path, false)
SessionPrefs.setAddedGameExe(app, folder.path, exe.path) SessionPrefs.setAddedGameExe(app, folder.path, exe.path)
@@ -276,8 +239,6 @@ object AddedGames {
fun addFolder(context: Context, dir: File, onGame: (Game) -> Unit = {}, onChecking: (String?) -> Unit = {}): FolderResult { fun addFolder(context: Context, dir: File, onGame: (Game) -> Unit = {}, onChecking: (String?) -> Unit = {}): FolderResult {
val app = context.applicationContext val app = context.applicationContext
// Binds are mounted at session start, so a new one reaches the session from the next start.
if (guestPath(app, dir) == null) bindFolder(app, dir)
val removed = SessionPrefs.removedAddedGames(app).toSet() val removed = SessionPrefs.removedAddedGames(app).toSet()
val listed = listedFolders(app, removed) val listed = listedFolders(app, removed)
var already = 0 var already = 0
@@ -301,20 +262,6 @@ object AddedGames {
return FolderResult(added, already) return FolderResult(added, already)
} }
@Synchronized
internal fun bindFolder(context: Context, dir: File) {
if (!dir.isDirectory || !dir.canRead()) return
val binds = SessionPrefs.gameFolderBinds(context)
if (binds.any { it.first == dir.path }) return
val taken = binds.map { it.second }.toSet()
val base = GamesFolderMigration.legacyRoots(binds.map { it.first } + dir.path).last().guest
var guest = base
var n = 2
while (guest in taken) guest = "$base-${n++}"
SessionPrefs.setGameFolderBinds(context, binds + (dir.path to guest))
Log.i(TAG, "games: bound $dir at $guest")
}
private fun listedFolders(context: Context, removed: Set<String>): List<String> { private fun listedFolders(context: Context, removed: Set<String>): List<String> {
val out = ArrayList<String>() val out = ArrayList<String>()
GamesFolderMigration.run(context) GamesFolderMigration.run(context)
@@ -324,7 +271,7 @@ object AddedGames {
) )
for (dir in dirs.distinctBy { it.absolutePath }) { for (dir in dirs.distinctBy { it.absolutePath }) {
for (folder in dir.listFiles { f -> f.isDirectory }.orEmpty()) { for (folder in dir.listFiles { f -> f.isDirectory }.orEmpty()) {
if (folder.path in removed || isSteamLibraryFolder(folder.name)) continue if (folder.path in removed || folder.name.equals("steamapps", ignoreCase = true)) continue
if (folder.name == "Games" && StoreInstallRoot.roots(context).any { it.absolutePath == folder.absolutePath }) continue if (folder.name == "Games" && StoreInstallRoot.roots(context).any { it.absolutePath == folder.absolutePath }) continue
out.add(canonical(folder)) out.add(canonical(folder))
} }
@@ -365,7 +312,7 @@ object AddedGames {
val autoName = sidecar?.title ?: identifiedName(folder, found) ?: folder.name val autoName = sidecar?.title ?: identifiedName(folder, found) ?: folder.name
val crc = CRC32().apply { update(("\"${foundGuest.replaceFirst(Regex("^$LIBRARY/"), "$LEGACY_LIBRARY/")}\"" + autoName).toByteArray()) }.value val crc = CRC32().apply { update(("\"${foundGuest.replaceFirst(Regex("^$LIBRARY/"), "$LEGACY_LIBRARY/")}\"" + autoName).toByteArray()) }.value
val appId = SessionPrefs.addedGameAppId(context, folder.path, crc or 0x80000000L) val appId = SessionPrefs.addedGameAppId(context, folder.path, crc or 0x80000000L)
val config = accountConfig(SessionPrefs.activeSteamRoot(context)) val config = accountConfig(File(LinuxRuntime.rootDir(context), "root/.local/share/Steam"))
val record = config?.let { shortcutRecord(it, appId) } val record = config?.let { shortcutRecord(it, appId) }
val rev = record?.optInt("rev", 0) ?: 0 val rev = record?.optInt("rev", 0) ?: 0
if (sidecar == null && record != null) adoptSteamEdits(context, folder, record) if (sidecar == null && record != null) adoptSteamEdits(context, folder, record)
@@ -401,7 +348,7 @@ object AddedGames {
}.getOrNull() }.getOrNull()
fun inSteam(context: Context, appId: Long): Boolean = fun inSteam(context: Context, appId: Long): Boolean =
accountConfig(SessionPrefs.activeSteamRoot(context))?.let { shortcutRecord(it, appId) } != null accountConfig(File(LinuxRuntime.rootDir(context), "root/.local/share/Steam"))?.let { shortcutRecord(it, appId) } != null
private fun shortcutRecord(config: File, appId: Long): JSONObject? = runCatching { private fun shortcutRecord(config: File, appId: Long): JSONObject? = runCatching {
JSONObject(File(config, ".droiddeck-shortcuts.json").readText()).optJSONObject("games")?.optJSONObject(appId.toString()) JSONObject(File(config, ".droiddeck-shortcuts.json").readText()).optJSONObject("games")?.optJSONObject(appId.toString())
@@ -26,7 +26,6 @@ object AddedGamesPublisher {
fun republish(context: Context) { fun republish(context: Context) {
val games = AddedGames.scan(context) val games = AddedGames.scan(context)
AddedGames.writeListing(context, games) AddedGames.writeListing(context, games)
val arch = com.droiddeck.launcher.session.SessionPrefs.activeSteamClientArch(context) LibraryCache.save(context, Library.launchableGames(context, added = games))
LibraryCache.save(context, Library.launchableGames(context, added = games, arch = arch), arch == "x86_64")
} }
} }
@@ -38,7 +38,7 @@ object GameFileSync {
@Synchronized private fun sync(context: Context, folder: File) { @Synchronized private fun sync(context: Context, folder: File) {
check(LinuxRuntime.isInstalled(context)) { context.getString(R.string.game_sync_err_runtime) } check(LinuxRuntime.isInstalled(context)) { context.getString(R.string.game_sync_err_runtime) }
check(File(SessionPrefs.activeSteamRoot(context), "steamapps").isDirectory) { context.getString(R.string.game_sync_err_steam_library) } check(File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps").isDirectory) { context.getString(R.string.game_sync_err_steam_library) }
val storage = GameStorage.effective(context) val storage = GameStorage.effective(context)
val storageSetting = SessionPrefs.gameStorage(context) val storageSetting = SessionPrefs.gameStorage(context)
val previousStorage = prefs(context).getString("storagePath", null) val previousStorage = prefs(context).getString("storagePath", null)
@@ -14,7 +14,6 @@ import java.io.InputStream
object GameFiles { object GameFiles {
const val EXTENSION = "steam" const val EXTENSION = "steam"
private const val MAX_BYTES = 128 private const val MAX_BYTES = 128
private const val MAX_NAME_BYTES = 200
private const val INVENTORY = ".droiddeck-sync.json" private const val INVENTORY = ".droiddeck-sync.json"
private const val FORMAT = "droiddeck-game-files-v1" private const val FORMAT = "droiddeck-game-files-v1"
@@ -51,15 +50,8 @@ object GameFiles {
fun filename(game: Library.SteamGame, disambiguate: Boolean = false): String { fun filename(game: Library.SteamGame, disambiguate: Boolean = false): String {
val sanitized = game.name.replace(Regex("[\\p{Cntrl}\\\\/:*?\"<>|]"), "_") val sanitized = game.name.replace(Regex("[\\p{Cntrl}\\\\/:*?\"<>|]"), "_")
.trim().trim('.').ifBlank { "Game" } .trim().trim('.').ifBlank { "Game" }
val points = sanitized.codePoints().toArray() val points = sanitized.codePoints().limit(40).toArray()
var end = 0 val title = String(points, 0, points.size)
var bytes = 0
while (end < points.size) {
bytes += String(points, end, 1).toByteArray().size
if (bytes > MAX_NAME_BYTES) break
end++
}
val title = String(points, 0, end).trimEnd { it.isWhitespace() || it == '.' }.ifBlank { "Game" }
val suffix = if (disambiguate) " (${game.gameIdString})" else "" val suffix = if (disambiguate) " (${game.gameIdString})" else ""
return "$title$suffix.$EXTENSION" return "$title$suffix.$EXTENSION"
} }
@@ -185,7 +185,7 @@ object GameIdentifier {
} }
private val JUNK_NAME_RE = Regex( private val JUNK_NAME_RE = Regex(
"""(?i)^(gse|steam|steam client|goldberg.*|launcher|game|play|start|setup|.* launcher.*|.*launcher redirector|.* redirector|rockstar games launcher.*|epic games launcher|smartsteamemu|coldclient.*|steamemu.*|bootstrappackagedgame)$""" """(?i)^(gse|steam|steam client|goldberg.*|launcher|game|play|start|setup|.* launcher.*|.*launcher redirector|.* redirector|rockstar games launcher.*|epic games launcher|smartsteamemu|coldclient.*|steamemu.*)$"""
) )
fun isJunkPeName(name: String): Boolean { fun isJunkPeName(name: String): Boolean {
@@ -1,52 +0,0 @@
package com.droiddeck.launcher.frontend
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstalls
import com.droiddeck.launcher.stores.StoresState
import java.io.File
object GameRemoval {
enum class Kind { STORE, SHORTCUT, LAUNCHER }
fun kind(game: Library.SteamGame): Kind = when {
game.library == Library.EPIC_LAUNCHER -> Kind.LAUNCHER
game.library == Library.ADDED && game.source == Library.ADDED -> Kind.SHORTCUT
else -> Kind.STORE
}
class SteamFiles(val dir: File, val manifest: File, val partial: File?)
fun steamFiles(game: Library.SteamGame): SteamFiles? {
val dir = game.gameFiles ?: return null
val common = dir.parentFile ?: return null
if (common.name != "common") return null
val steamapps = common.parentFile ?: return null
if (steamapps.name != "steamapps") return null
val manifest = File(steamapps, "appmanifest_${game.appId}.acf")
if (!manifest.isFile) return null
if (!declares(manifest, game.appId)) return null
return SteamFiles(dir, manifest, File(steamapps, "downloading/${game.appId}"))
}
fun delete(target: SteamFiles): Boolean {
StoreInstalls.deleteTree(target.dir)
if (target.dir.exists()) return false
target.partial?.let { StoreInstalls.deleteTree(it) }
target.manifest.delete()
return !target.manifest.exists()
}
fun storeGame(game: Library.SteamGame): InstalledStoreGame? {
val folder = game.gameFiles ?: return null
val store = Store.byId(game.source)
val id = game.storeId
if (store != null && id != null) StoresState.installedGame(store, id)?.let { return it }
val sidecar = StoreGameSidecar.read(folder)?.takeIf { it.isInstalled } ?: return null
return InstalledStoreGame(sidecar, folder)
}
private fun declares(manifest: File, appId: Int): Boolean =
runCatching { manifest.readText() }.getOrNull()?.let { Regex("\"appid\"\\s+\"$appId\"").containsMatchIn(it) } == true
}
@@ -10,7 +10,6 @@ import android.graphics.BitmapFactory
import android.graphics.drawable.Icon import android.graphics.drawable.Icon
import android.net.Uri import android.net.Uri
import android.widget.Toast import android.widget.Toast
import com.droiddeck.launcher.LauncherIcon
import com.droiddeck.launcher.MainActivity import com.droiddeck.launcher.MainActivity
import com.droiddeck.launcher.R import com.droiddeck.launcher.R
import java.io.File import java.io.File
@@ -24,7 +23,7 @@ object GameShortcuts {
val name = game.name.ifBlank { context.getString(R.string.app_name) } val name = game.name.ifBlank { context.getString(R.string.app_name) }
val icon = iconBitmap(game)?.let(Icon::createWithBitmap) ?: Icon.createWithResource(context, R.mipmap.ic_launcher) val icon = iconBitmap(game)?.let(Icon::createWithBitmap) ?: Icon.createWithResource(context, R.mipmap.ic_launcher)
return ShortcutInfo.Builder(context, "game:${game.gameIdString}") return ShortcutInfo.Builder(context, "game:${game.gameIdString}")
.setActivity(LauncherIcon.activity(context)) .setActivity(android.content.ComponentName(context, MainActivity::class.java))
.setShortLabel(name.take(40)).setLongLabel(name).setIcon(icon) .setShortLabel(name.take(40)).setLongLabel(name).setIcon(icon)
.setIntent(launchIntent(context, game.gameIdString)).build() .setIntent(launchIntent(context, game.gameIdString)).build()
} }
@@ -25,7 +25,7 @@ object GamesFolderMigration {
var n = 0 var n = 0
val steamInstalls = AddedGames.steamInstallDirs(root.host) val steamInstalls = AddedGames.steamInstallDirs(root.host)
for (folder in root.host.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() }.orEmpty()) { for (folder in root.host.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() }.orEmpty()) {
if (AddedGames.isSteamLibraryFolder(folder.name) || folder.name.lowercase() in steamInstalls) continue if (folder.name.equals("steamapps", ignoreCase = true) || folder.name.lowercase() in steamInstalls) continue
if (folder.absolutePath in storeRoots || StoreGameSidecar.read(folder) != null) continue if (folder.absolutePath in storeRoots || StoreGameSidecar.read(folder) != null) continue
if (folder.path in entries) continue if (folder.path in entries) continue
val picked = SessionPrefs.addedGameExe(context, folder.path).takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile } val picked = SessionPrefs.addedGameExe(context, folder.path).takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
@@ -72,17 +72,13 @@ object Library {
private val NAME = Regex("^\\s*\"name\"\\s*\"([^\"]*)\"", RegexOption.MULTILINE) private val NAME = Regex("^\\s*\"name\"\\s*\"([^\"]*)\"", RegexOption.MULTILINE)
private val STATE = Regex("^\\s*\"StateFlags\"\\s*\"(\\d+)\"", RegexOption.MULTILINE) private val STATE = Regex("^\\s*\"StateFlags\"\\s*\"(\\d+)\"", RegexOption.MULTILINE)
private val LAST_PLAYED = Regex("^\\s*\"LastPlayed\"\\s*\"(\\d+)\"", RegexOption.MULTILINE) private val LAST_PLAYED = Regex("^\\s*\"LastPlayed\"\\s*\"(\\d+)\"", RegexOption.MULTILINE)
private val PRIVATE_APPS = Regex("\"PrivateApps_\\d+\"\\s*\"\\[([^\\]]*)\\]\"")
private val INSTALL_DIR = Regex("^\\s*\"installdir\"\\s*\"([^\"]*)\"", RegexOption.MULTILINE) private val INSTALL_DIR = Regex("^\\s*\"installdir\"\\s*\"([^\"]*)\"", RegexOption.MULTILINE)
internal fun steamLibraries(context: Context, arch: String = SessionPrefs.activeSteamClientArch(context)): List<Pair<File, String>> { internal fun steamLibraries(context: Context): List<Pair<File, String>> {
val root = SessionPrefs.steamRoot(context, arch) val root = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
// The session gives the x86-64 client only its card folder; the games folders stay the arm64 client's.
val card = GameStorage.effective(context)
if (arch == "x86_64") return listOfNotNull(root to "internal", card?.let { File(it.path, GameStorage.X64_CARD_DIR) to it.label })
return listOfNotNull( return listOfNotNull(
root to "internal", root to "internal",
card?.let { File(it.path) to it.label }, GameStorage.effective(context)?.let { File(it.path) to it.label },
) + GameStorage.gamesFolderLibraries(context).map { it.host to it.label } ) + GameStorage.gamesFolderLibraries(context).map { it.host to it.label }
} }
@@ -102,10 +98,10 @@ object Library {
.firstOrNull { it.isDirectory } .firstOrNull { it.isDirectory }
} }
fun steamGames(context: Context, strictRead: Boolean = false, arch: String = SessionPrefs.activeSteamClientArch(context)): List<SteamGame> { fun steamGames(context: Context, strictRead: Boolean = false): List<SteamGame> {
val root = SessionPrefs.steamRoot(context, arch) val root = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
val cache = File(root, "appcache/librarycache") val cache = File(root, "appcache/librarycache")
val libraries = steamLibraries(context, arch) val libraries = steamLibraries(context)
val roots = libraries.map { it.first } val roots = libraries.map { it.first }
val out = LinkedHashMap<Int, SteamGame>() val out = LinkedHashMap<Int, SteamGame>()
for ((library, label) in libraries) { for ((library, label) in libraries) {
@@ -138,63 +134,22 @@ object Library {
} }
fun steamLibraryArt(context: Context): List<Pair<Int, File>> { fun steamLibraryArt(context: Context): List<Pair<Int, File>> {
val root = SessionPrefs.activeSteamRoot(context) val cache = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/appcache/librarycache")
val cache = File(root, "appcache/librarycache")
val concealed = concealedSteamApps(root)
return cache.listFiles().orEmpty().mapNotNull { dir -> return cache.listFiles().orEmpty().mapNotNull { dir ->
val appId = dir.name.toIntOrNull()?.takeIf { it !in NOT_GAMES && it.toLong() !in concealed } ?: return@mapNotNull null val appId = dir.name.toIntOrNull()?.takeIf { it !in NOT_GAMES } ?: return@mapNotNull null
steamCacheImage(cache, appId, STEAM_CAPSULES)?.let { appId to it } steamCacheImage(cache, appId, STEAM_CAPSULES)?.let { appId to it }
} }
} }
/** Apps the user hid (the "hidden" collection) or marked private in Steam. */ fun launchableGames(context: Context, strictRead: Boolean = false, added: List<AddedGames.Game>? = null): List<SteamGame> {
internal fun concealedSteamApps(root: File): Set<Long> { val roots = steamLibraries(context).map { it.first }
val config = AddedGames.accountConfig(root) ?: return emptySet()
val hidden = runCatching {
val entries = org.json.JSONArray(File(config, "cloudstorage/cloud-storage-namespace-1.json").readText())
val entry = (0 until entries.length()).map { entries.getJSONArray(it) }
.firstOrNull { it.optString(0) == "user-collections.hidden" }?.optJSONObject(1)
if (entry == null || entry.optBoolean("is_deleted")) emptySet() else {
val collection = org.json.JSONObject(entry.optString("value"))
fun ids(key: String) = collection.optJSONArray(key)?.let { a -> (0 until a.length()).map { a.optLong(it) } }.orEmpty()
ids("added").toSet() - ids("removed").toSet()
}
}.getOrDefault(emptySet())
val private = runCatching {
PRIVATE_APPS.find(File(config, "localconfig.vdf").readText())?.groupValues?.get(1)
?.split(',')?.mapNotNull { it.trim().toLongOrNull() }?.toSet()
}.getOrNull().orEmpty()
return hidden + private
}
fun fromSteamClient(g: SteamGame): Boolean = g.library != ADDED && g.source == SOURCE_STEAM
fun launchableGames(
context: Context, strictRead: Boolean = false, added: List<AddedGames.Game>? = null,
arch: String = SessionPrefs.activeSteamClientArch(context),
): List<SteamGame> {
val roots = steamLibraries(context, arch).map { it.first }
val list = added ?: AddedGames.scan(context) val list = added ?: AddedGames.scan(context)
var steam = steamGames(context, strictRead, arch) var steam = steamGames(context, strictRead)
val targets = steam.filter(::fromSteamClient).map { SteamGrid.target(it, context) } + list.map { SteamGrid.target(it, context) } val targets = steam.filter { it.library != ADDED && it.source == SOURCE_STEAM }.map { SteamGrid.target(it, context) } + list.map { SteamGrid.target(it, context) }
if (runCatching { SteamGrid.sync(context, targets) }.getOrDefault(false)) steam = steamGames(context, strictRead, arch) if (runCatching { SteamGrid.sync(context, targets) }.getOrDefault(false)) steam = steamGames(context, strictRead)
val claimed = claimedFolders(steam) return (steam + list.map { g -> addedGame(context, g, roots) }).distinctBy { it.gameId }
val own = list.filter { g ->
g.steamAppId != null || claimed.isEmpty() ||
(runCatching { g.folder.canonicalPath }.getOrDefault(g.folder.absolutePath) !in claimed &&
AddedGames.guestPath(context, g.folder).let { it == null || it !in claimed })
}
return (steam + own.map { g -> addedGame(context, g, roots) }).distinctBy { it.gameId }
} }
fun claimedFolders(steam: List<SteamGame>): Set<String> = steam.filter(::fromSteamClient).flatMap { g ->
val dir = g.gameFiles ?: return@flatMap emptyList()
listOfNotNull(
runCatching { dir.canonicalPath }.getOrNull(),
runCatching { java.nio.file.Files.readSymbolicLink(dir.toPath()).toString() }.getOrNull(),
)
}.toSet()
fun addedGame(context: Context, g: AddedGames.Game, roots: List<File> = steamLibraries(context).map { it.first }): SteamGame = fun addedGame(context: Context, g: AddedGames.Game, roots: List<File> = steamLibraries(context).map { it.first }): SteamGame =
AddedGameArt.resolve(context, g).let { art -> AddedGameArt.resolve(context, g).let { art ->
SteamGame( SteamGame(
@@ -10,14 +10,10 @@ object LibraryCache {
private const val TAG = "LibraryCache" private const val TAG = "LibraryCache"
private fun file(context: Context) = File(context.filesDir, "library-cache.json") private fun file(context: Context) = File(context.filesDir, "library-cache.json")
/** The cached games and whether they are the x86-64 client's; a cache written as a bare list is arm64's. */ fun load(context: Context): List<Library.SteamGame> = runCatching {
@Synchronized
fun snapshot(context: Context): Pair<List<Library.SteamGame>, Boolean> = runCatching {
val f = file(context) val f = file(context)
if (!f.isFile) return Pair(emptyList(), false) if (!f.isFile) return emptyList()
val text = f.readText().trim() val array = JSONArray(f.readText())
val (array, x64) = if (text.startsWith("{")) JSONObject(text).let { it.getJSONArray("games") to (it.optString("client") == "x86_64") }
else JSONArray(text) to false
List(array.length()) { i -> List(array.length()) { i ->
val o = array.getJSONObject(i) val o = array.getJSONObject(i)
Library.SteamGame( Library.SteamGame(
@@ -28,18 +24,11 @@ object LibraryCache {
source = o.optString("source").ifEmpty { if (o.getString("library") == Library.ADDED) Library.ADDED else Library.SOURCE_STEAM }, source = o.optString("source").ifEmpty { if (o.getString("library") == Library.ADDED) Library.ADDED else Library.SOURCE_STEAM },
storeId = o.optString("storeId").ifEmpty { null }, storeId = o.optString("storeId").ifEmpty { null },
) )
} to x64 }
}.getOrElse { e -> Log.w(TAG, "unreadable, ignored: ${e.message}"); Pair(emptyList(), false) } }.getOrElse { e -> Log.w(TAG, "unreadable, ignored: ${e.message}"); emptyList() }
fun load(context: Context): List<Library.SteamGame> = snapshot(context).first fun save(context: Context, games: List<Library.SteamGame>) {
fun listedX64(context: Context): Boolean = snapshot(context).second
/** Without [x64] the list keeps the client already recorded. */
@Synchronized
fun save(context: Context, games: List<Library.SteamGame>, x64: Boolean? = null) {
runCatching { runCatching {
val client = x64 ?: listedX64(context)
val array = JSONArray() val array = JSONArray()
for (g in games) array.put( for (g in games) array.put(
JSONObject().put("appId", g.appId).put("name", g.name).put("library", g.library).put("gameId", g.gameId) JSONObject().put("appId", g.appId).put("name", g.name).put("library", g.library).put("gameId", g.gameId)
@@ -49,12 +38,8 @@ object LibraryCache {
) )
val f = file(context) val f = file(context)
val tmp = File(f.path + ".tmp") val tmp = File(f.path + ".tmp")
tmp.writeText(JSONObject().put("client", if (client) "x86_64" else "arm64").put("games", array).toString()) tmp.writeText(array.toString())
if (!tmp.renameTo(f)) { tmp.renameTo(f)
tmp.delete()
f.delete()
Log.w(TAG, "not saved: rename failed; cache dropped so the next start scans")
}
}.onFailure { e -> Log.w(TAG, "not saved: ${e.message}") } }.onFailure { e -> Log.w(TAG, "not saved: ${e.message}") }
} }
@@ -25,16 +25,9 @@ object SessionInstalls {
STATE.find(text)?.groupValues?.get(1)?.toIntOrNull() == 4, file.parentFile!!) STATE.find(text)?.groupValues?.get(1)?.toIntOrNull() == 4, file.parentFile!!)
}.getOrNull() }.getOrNull()
internal fun steamappsDirs(context: Context): List<File> = ( internal fun steamappsDirs(context: Context): List<File> = listOfNotNull(
if (com.droiddeck.launcher.session.SessionPrefs.activeSteamClientArch(context) == "x86_64") File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps"),
listOfNotNull( GameStorage.effective(context)?.let { File(it.path, "steamapps") },
File(com.droiddeck.launcher.session.SessionPrefs.activeSteamRoot(context), "steamapps"),
GameStorage.x64CardLibrary(context)?.let { File(it, "steamapps") },
)
else listOfNotNull(
File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps"),
GameStorage.effective(context)?.let { File(it.path, "steamapps") },
)
).filter { it.isDirectory } ).filter { it.isDirectory }
internal class Watch(private val dirs: () -> List<File>) { internal class Watch(private val dirs: () -> List<File>) {
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.frontend
import android.content.Context import android.content.Context
import android.util.AtomicFile import android.util.AtomicFile
import android.util.Log import android.util.Log
import com.droiddeck.launcher.runtime.LinuxRuntime
import org.json.JSONArray import org.json.JSONArray
import org.json.JSONObject import org.json.JSONObject
import java.io.DataInputStream import java.io.DataInputStream
@@ -19,7 +20,7 @@ object SteamAppInfo {
class Info(val name: String, val sharedDepots: List<String>) class Info(val name: String, val sharedDepots: List<String>)
fun appinfoFile(context: Context) = File(com.droiddeck.launcher.session.SessionPrefs.activeSteamRoot(context), "appcache/appinfo.vdf") fun appinfoFile(context: Context) = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/appcache/appinfo.vdf")
@Synchronized @Synchronized
fun info(context: Context, appId: Int, appinfo: File = appinfoFile(context)): Info? { fun info(context: Context, appId: Int, appinfo: File = appinfoFile(context)): Info? {
@@ -153,7 +154,7 @@ object SteamAppInfo {
return String(bytes, Charsets.UTF_8) return String(bytes, Charsets.UTF_8)
} }
internal fun readMap(b: ByteBuffer, strings: List<String>?): Map<String, Any> { private fun readMap(b: ByteBuffer, strings: List<String>?): Map<String, Any> {
val out = LinkedHashMap<String, Any>() val out = LinkedHashMap<String, Any>()
while (b.hasRemaining()) { while (b.hasRemaining()) {
val type = b.get().toInt() and 0xFF val type = b.get().toInt() and 0xFF
@@ -1,8 +1,8 @@
package com.droiddeck.launcher.frontend package com.droiddeck.launcher.frontend
import android.content.Context import android.content.Context
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.stores.SteamLiveShortcuts import com.droiddeck.launcher.stores.SteamLiveShortcuts
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File import java.io.File
object SteamGameArt { object SteamGameArt {
@@ -35,7 +35,7 @@ object SteamGameArt {
} }
fun describe(context: Context, game: Library.SteamGame): List<AddedGameArt.SlotState> { fun describe(context: Context, game: Library.SteamGame): List<AddedGameArt.SlotState> {
val cache = File(SessionPrefs.activeSteamRoot(context), "appcache/librarycache") val cache = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/appcache/librarycache")
val own = withOverrides(context, game) val own = withOverrides(context, game)
return AddedGameArt.Slot.values().map { slot -> return AddedGameArt.Slot.values().map { slot ->
chosenFile(context, game.appId, slot)?.let { chosenFile(context, game.appId, slot)?.let {
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.frontend
import android.content.Context import android.content.Context
import android.util.Log import android.util.Log
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.session.SessionPrefs
import org.json.JSONObject import org.json.JSONObject
import java.io.File import java.io.File
@@ -27,7 +28,8 @@ object SteamGrid {
} }
internal fun dir(context: Context): File? { internal fun dir(context: Context): File? {
return AddedGames.accountConfig(SessionPrefs.activeSteamRoot(context))?.let { File(it, "grid") } val root = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
return AddedGames.accountConfig(root)?.let { File(it, "grid") }
} }
private fun files(grid: File, id: Long, slot: AddedGameArt.Slot): List<File> = private fun files(grid: File, id: Long, slot: AddedGameArt.Slot): List<File> =
@@ -35,18 +37,13 @@ object SteamGrid {
private fun signature(file: File?) = if (file == null) "" else "${file.length()}:${file.lastModified()}" private fun signature(file: File?) = if (file == null) "" else "${file.length()}:${file.lastModified()}"
/** Each Steam client has its own grid folder, so what was last seen there is kept per client. */ private fun sigFile(target: Target, slot: AddedGameArt.Slot) = File(target.artDir, "grid-${slot.key}")
private fun sigName(context: Context, key: String) =
if (SessionPrefs.activeSteamClientArch(context) == "x86_64") "grid-x86_64-$key" else "grid-$key"
private fun sigFile(context: Context, target: Target, slot: AddedGameArt.Slot) = File(target.artDir, sigName(context, slot.key)) private fun recorded(target: Target, slot: AddedGameArt.Slot): String? = sigFile(target, slot).takeIf { it.isFile }?.readText()
private fun recorded(context: Context, target: Target, slot: AddedGameArt.Slot): String? = private fun record(target: Target, slot: AddedGameArt.Slot, value: String) {
sigFile(context, target, slot).takeIf { it.isFile }?.readText()
private fun record(context: Context, target: Target, slot: AddedGameArt.Slot, value: String) {
target.artDir.mkdirs() target.artDir.mkdirs()
sigFile(context, target, slot).writeText(value) sigFile(target, slot).writeText(value)
} }
private fun writtenByDroidDeck(grid: File): Set<String> = runCatching { private fun writtenByDroidDeck(grid: File): Set<String> = runCatching {
@@ -62,7 +59,7 @@ object SteamGrid {
val grid = dir(context) ?: return true val grid = dir(context) ?: return true
if (file == null) { if (file == null) {
if (files(grid, target.id, slot).map { it.delete() }.any { !it }) return false if (files(grid, target.id, slot).map { it.delete() }.any { !it }) return false
record(context, target, slot, "") record(target, slot, "")
return true return true
} }
val ext = file.extension.lowercase().let { if (it == "jpeg") "jpg" else it } val ext = file.extension.lowercase().let { if (it == "jpeg") "jpg" else it }
@@ -76,12 +73,12 @@ object SteamGrid {
return false return false
} }
if (files(grid, target.id, slot).filter { it != dst }.map { it.delete() }.any { !it }) return false if (files(grid, target.id, slot).filter { it != dst }.map { it.delete() }.any { !it }) return false
record(context, target, slot, signature(placed)) record(target, slot, signature(placed))
return true return true
} }
private const val POSITION = "logo-position" private const val POSITION = "logo-position"
private const val POSITION_SIG = "json" private const val POSITION_SIG = "grid-json"
private fun positionFile(grid: File, id: Long) = File(grid, "$id.json") private fun positionFile(grid: File, id: Long) = File(grid, "$id.json")
@@ -90,12 +87,11 @@ object SteamGrid {
/** The logo position chosen here (or taken over from Steam) for a game; null when Steam's own default applies. */ /** The logo position chosen here (or taken over from Steam) for a game; null when Steam's own default applies. */
fun position(target: Target): LogoPosition.Value? = positionIn(File(target.artDir, POSITION)) fun position(target: Target): LogoPosition.Value? = positionIn(File(target.artDir, POSITION))
private fun positionRecorded(context: Context, target: Target): String? = private fun positionRecorded(target: Target): String? = File(target.artDir, POSITION_SIG).takeIf { it.isFile }?.readText()
File(target.artDir, sigName(context, POSITION_SIG)).takeIf { it.isFile }?.readText()
private fun recordPosition(context: Context, target: Target, value: String) { private fun recordPosition(target: Target, value: String) {
target.artDir.mkdirs() target.artDir.mkdirs()
File(target.artDir, sigName(context, POSITION_SIG)).writeText(value) File(target.artDir, POSITION_SIG).writeText(value)
} }
private fun storePosition(target: Target, value: LogoPosition.Value?): Boolean { private fun storePosition(target: Target, value: LogoPosition.Value?): Boolean {
@@ -119,7 +115,7 @@ object SteamGrid {
val next = if (value == null) existing?.let(LogoPosition::without) else LogoPosition.toJson(value, existing ?: JSONObject()) val next = if (value == null) existing?.let(LogoPosition::without) else LogoPosition.toJson(value, existing ?: JSONObject())
if (next == null) { if (next == null) {
if (file.isFile && !file.delete()) return false if (file.isFile && !file.delete()) return false
recordPosition(context, target, "") recordPosition(target, "")
return true return true
} }
grid.mkdirs() grid.mkdirs()
@@ -129,7 +125,7 @@ object SteamGrid {
tmp.delete() tmp.delete()
return false return false
} }
recordPosition(context, target, signature(file)) recordPosition(target, signature(file))
return true return true
} }
@@ -144,16 +140,16 @@ object SteamGrid {
if (hasUnknownPosition(file)) return if (hasUnknownPosition(file)) return
val theirs = positionIn(file) val theirs = positionIn(file)
val now = if (theirs != null) signature(file) else "" val now = if (theirs != null) signature(file) else ""
val before = positionRecorded(context, target) val before = positionRecorded(target)
val own = position(target) val own = position(target)
when { when {
before == null && own != null && theirs == null -> placePosition(context, target, own) before == null && own != null && theirs == null -> placePosition(context, target, own)
before == null || now != before -> { before == null || now != before -> {
// Recorded only once the local side agrees, so a failed take-over is tried again on the next scan. // Recorded only once the local side agrees, so a failed take-over is tried again on the next scan.
if (theirs != null) { if (theirs != null) {
if (own == theirs || storePosition(target, theirs)) recordPosition(context, target, now) if (own == theirs || storePosition(target, theirs)) recordPosition(target, now)
} else { } else {
if (own == null || storePosition(target, null)) recordPosition(context, target, "") if (own == null || storePosition(target, null)) recordPosition(target, "")
} }
} }
own != null && own != theirs -> placePosition(context, target, own) own != null && own != theirs -> placePosition(context, target, own)
@@ -173,20 +169,20 @@ object SteamGrid {
val present = files(grid, target.id, slot) val present = files(grid, target.id, slot)
val theirs = present.filter { it.name !in ours }.maxByOrNull { it.lastModified() } val theirs = present.filter { it.name !in ours }.maxByOrNull { it.lastModified() }
val now = signature(theirs) val now = signature(theirs)
val before = recorded(context, target, slot) val before = recorded(target, slot)
when { when {
before == null && own != null && theirs == null -> write(context, target, slot, own) before == null && own != null && theirs == null -> write(context, target, slot, own)
before == null || now != before -> { before == null || now != before -> {
if (theirs != null) { if (theirs != null) {
if (own != null && own.length() == theirs.length() && own.readBytes().contentEquals(theirs.readBytes())) record(context, target, slot, now) if (own != null && own.length() == theirs.length() && own.readBytes().contentEquals(theirs.readBytes())) record(target, slot, now)
else if (AddedGameArt.store(target.artDir, slot, AddedGameArt.Option(AddedGameArt.STEAM, theirs.path, theirs.path))) { else if (AddedGameArt.store(target.artDir, slot, AddedGameArt.Option(AddedGameArt.STEAM, theirs.path, theirs.path))) {
target.setSource(slot, AddedGameArt.STEAM + "|steam-client") target.setSource(slot, AddedGameArt.STEAM + "|steam-client")
record(context, target, slot, now) record(target, slot, now)
changed = true changed = true
} }
} else { } else {
if (own != null && present.isEmpty()) { own.delete(); target.setSource(slot, ""); changed = true } if (own != null && present.isEmpty()) { own.delete(); target.setSource(slot, ""); changed = true }
record(context, target, slot, "") record(target, slot, "")
} }
} }
own != null && theirs != null && now == before && own.length() != theirs.length() -> write(context, target, slot, own) own != null && theirs != null && now == before && own.length() != theirs.length() -> write(context, target, slot, own)
@@ -1,24 +0,0 @@
package com.droiddeck.launcher.glasses
import android.content.Context
import com.droiddeck.launcher.R
import kotlin.math.abs
internal data class CalibrationDistanceResult(val accepted: Boolean, val message: String)
internal object CalibrationDistanceCheck {
fun evaluate(context: Context, expected: Float, corners: Int, points: List<SpatialVector>?): CalibrationDistanceResult {
require(expected.isFinite() && expected in 0.15f..1.5f)
if (corners != 24) return CalibrationDistanceResult(false,
context.getString(R.string.spatial_distance_corners, corners))
if (points?.size != 24 || points.any { !it.finite() }) return CalibrationDistanceResult(false,
context.getString(R.string.spatial_distance_depth))
val measured=(points.reduce { a,b -> a+b }*(1f/points.size)).length()
if (!measured.isFinite()) return CalibrationDistanceResult(false,context.getString(R.string.spatial_distance_invalid))
val accepted=abs(measured-expected)<0.05f
return CalibrationDistanceResult(accepted,
context.getString(R.string.spatial_distance_result,
SpatialMeasurements.validation(measured), SpatialMeasurements.validation(expected),
context.getString(if (accepted) R.string.spatial_distance_passed else R.string.spatial_distance_retry)))
}
}
@@ -1,27 +0,0 @@
package com.droiddeck.launcher.glasses
import org.json.JSONObject
internal data class CalibrationObservationData(
val objects: List<DoubleArray>, val left: List<DoubleArray>, val right: List<DoubleArray>, val head: SpatialPose,
) {
companion object {
fun parse(view: JSONObject): CalibrationObservationData {
fun points(name: String, dimensions: Int): List<DoubleArray> {
val rows=view.getJSONArray(name)
require(rows.length() in 12..24) { "Invalid saved board corner count" }
return (0 until rows.length()).map { row ->
val values=rows.getJSONArray(row)
require(values.length()==dimensions)
DoubleArray(dimensions) { values.getDouble(it).also { value -> require(value.isFinite()) } }
}
}
val objects=points("objects",3); val left=points("left",2); val right=points("right",2)
require(objects.size==left.size && objects.size==right.size)
val pose=view.getJSONArray("head")
require(pose.length()==7)
val head=SpatialPose.fromSdk(FloatArray(7) { pose.getDouble(it).toFloat() }) ?: error("Invalid saved head pose")
return CalibrationObservationData(objects,left,right,head)
}
}
}
@@ -51,18 +51,10 @@ data class GlassesState(
val sbsSupport: Int = SBS_UNKNOWN, val sbsSupport: Int = SBS_UNKNOWN,
val sbs90: Boolean = false, val sbs90: Boolean = false,
val experimental: Boolean = false, val experimental: Boolean = false,
val supportsScreen3dof: Boolean = false,
val supports30Hz: Boolean = false,
val supportsSpatial: Boolean = false,
val resolutions: List<GlassesResolution> = emptyList(),
val vrActive: Boolean = false,
) { ) {
val hasDisplay: Boolean get() = displayId != Display.INVALID_DISPLAY val hasDisplay: Boolean get() = displayId != Display.INVALID_DISPLAY
val usable: Boolean get() = hasDisplay && !noSignal val usable: Boolean get() = hasDisplay && !noSignal
val canControl: Boolean get() = connected && controllable val canControl: Boolean get() = connected && controllable
val spatialConnected: Boolean get() = canControl && supportsSpatial
fun usesSpatialControllers(settings: GlassesSettings) = spatialConnected && settings.positionalTracking &&
(settings.handControllers || settings.joyConTracking)
val can3d: Boolean get() = canControl && !noSignal && sbsSupport != SBS_FAILS val can3d: Boolean get() = canControl && !noSignal && sbsSupport != SBS_FAILS
val verticalFovDeg: Float get() { val verticalFovDeg: Float get() {
val half = Math.toRadians(diagonalFovDeg / 2.0) val half = Math.toRadians(diagonalFovDeg / 2.0)
@@ -82,9 +74,6 @@ data class GlassesState(
data class GlassesSettings( data class GlassesSettings(
val refreshHz: Int = 120, val refreshHz: Int = 120,
val sbsHz: Int = 60, val sbsHz: Int = 60,
val resolution2d: String = "",
val resolution3d: String = "",
val resolutionVr: String = "",
val sunblock: Boolean? = null, val sunblock: Boolean? = null,
val gameOnGlasses: Boolean = true, val gameOnGlasses: Boolean = true,
val headTracking: Boolean = true, val headTracking: Boolean = true,
@@ -93,14 +82,7 @@ data class GlassesSettings(
val screenWidthDm: Int = 20, val screenWidthDm: Int = 20,
val screenDistanceDm: Int = 30, val screenDistanceDm: Int = 30,
val vrFovDeg: Int = VR_FOV_DEFAULT, val vrFovDeg: Int = VR_FOV_DEFAULT,
val positionalTracking: Boolean = false,
val handControllers: Boolean = false,
val joyConTracking: Boolean = false,
val steadyHandAim: Boolean = false,
val eyeHeightCm: Int = 160,
) { ) {
val screen3dof: Boolean get() = picture3d == PICTURE_SCREEN && headTracking
companion object { companion object {
const val VR_FOV_MIN = 24 const val VR_FOV_MIN = 24
const val VR_FOV_MAX = 90 const val VR_FOV_MAX = 90
@@ -147,13 +129,10 @@ object Glasses {
private var lastModeSentAt = 0L private var lastModeSentAt = 0L
private val modeState = GlassesModeState(SBS_CONFIRM_MS) private val modeState = GlassesModeState(SBS_CONFIRM_MS)
private val confirmMode = Runnable { refresh() } private val confirmMode = Runnable { refresh() }
private val steamVrSpatialGate = SteamVrSpatialGate()
private val resumeSteamVrSpatial = Runnable { updateSpatialMode() }
private var glassesMode = 0 private var glassesMode = 0
private var autoModeSent = false private var autoModeSent = false
@Volatile private var sink: PoseSink? = null @Volatile private var sink: PoseSink? = null
private val poseObservers = java.util.concurrent.CopyOnWriteArraySet<PoseSink>()
@Volatile private var probe: ((ByteArray?, FloatArray?) -> Unit)? = null @Volatile private var probe: ((ByteArray?, FloatArray?) -> Unit)? = null
@Volatile private var latest: FloatArray? = null @Volatile private var latest: FloatArray? = null
@Volatile private var imuPackets = 0L @Volatile private var imuPackets = 0L
@@ -163,7 +142,6 @@ object Glasses {
fun init(context: Context) { fun init(context: Context) {
if (::handler.isInitialized) return if (::handler.isInitialized) return
app = context.applicationContext app = context.applicationContext
SpatialTracking.initialize(app)
usb = app.getSystemService(Context.USB_SERVICE) as UsbManager usb = app.getSystemService(Context.USB_SERVICE) as UsbManager
displays = app.getSystemService(Context.DISPLAY_SERVICE) as DisplayManager displays = app.getSystemService(Context.DISPLAY_SERVICE) as DisplayManager
_settings.value = load() _settings.value = load()
@@ -222,84 +200,13 @@ object Glasses {
} }
fun setRefreshHz(hz: Int) = post { fun setRefreshHz(hz: Int) = post {
if (hz == 30 && (_state.value.sbs || !GlassesRendering.native30HzAvailable(_settings.value, _state.value))) return@post update { it.copy(refreshHz = hz.coerceIn(60, 120)) }
update { it.copy(refreshHz = if (hz == 30) 30 else hz.coerceIn(60, 120)) }
if (!_state.value.sbs) applyMode(force = true) if (!_state.value.sbs) applyMode(force = true)
} }
fun setSbsHz(hz: Int) = post { fun setSbsHz(hz: Int) = post {
if (hz == 30 && (!_state.value.sbs || !GlassesRendering.native30HzAvailable(_settings.value, _state.value))) return@post update { it.copy(sbsHz = if (hz >= 90) 90 else 60) }
update { it.copy(sbsHz = when { hz == 30 -> 30; hz >= 90 -> 90; else -> 60 }) } if (_state.value.sbs && _state.value.can3d) sendMode(true)
if (hz != 30 && _state.value.sbs && _state.value.can3d) sendMode(true)
}
fun setResolution(profile: GlassesDisplayProfile, value: String) = post {
val s = _state.value
val choice = if (value == "auto") "" else value
if (choice.isNotEmpty() && s.resolutions.none { it.key == choice }) return@post
if (GlassesDisplayModes.choice(_settings.value, profile) == choice) return@post
update { when (profile) {
GlassesDisplayProfile.TWO_D -> it.copy(resolution2d = choice)
GlassesDisplayProfile.THREE_D -> it.copy(resolution3d = choice)
GlassesDisplayProfile.VR -> it.copy(resolutionVr = choice)
} }
val active = GlassesDisplayModes.profile(s.sbs, s.vrActive)
val inheritedByVr = s.vrActive && _settings.value.resolutionVr.isEmpty() &&
profile == GlassesDisplayModes.profile(s.sbs, false)
if ((profile == active || inheritedByVr) && s.canControl && !s.switching3d &&
model?.resolutions?.isNotEmpty() == true) sendMode(s.sbs)
}
fun prepareSteamVrStart(onPrepared: () -> Unit = {}) {
if (!::handler.isInitialized) {
steamVrSpatialGate.prepare()
onPrepared()
return
}
post {
if (steamVrSpatialGate.prepare()) {
handler.removeCallbacks(resumeSteamVrSpatial)
updateSpatialMode()
}
onPrepared()
}
}
fun cancelSteamVrStart() {
if (!::handler.isInitialized) {
steamVrSpatialGate.cancel()
return
}
post {
steamVrSpatialGate.cancel()
handler.removeCallbacks(resumeSteamVrSpatial)
updateSpatialMode()
}
}
fun setVrActive(on: Boolean) = post {
val s = _state.value
val trackingChanged = steamVrSpatialGate.setRunning(on, SystemClock.uptimeMillis())
if (trackingChanged) {
handler.removeCallbacks(resumeSteamVrSpatial)
steamVrSpatialGate.deadline?.let {
Log.i(TAG, "SteamVR RUNNING; spatial resume scheduled at uptime ${it}ms")
handler.postAtTime(resumeSteamVrSpatial, it)
}
}
if (s.vrActive == on) {
if (trackingChanged) updateSpatialMode()
return@post
}
val previous = GlassesDisplayModes.selected(_settings.value, s)
publish { it.copy(vrActive = on) }
val restore2d = !on && modeState.stopVr()
val stereo = (s.sbs || modeState.pendingStereo) && !restore2d
val selected = GlassesDisplayModes.selected(_settings.value, _state.value, stereo)
if (s.canControl && s.usable && (restore2d ||
(previous != selected && model?.resolutions?.isNotEmpty() == true)) &&
!(on && _settings.value.auto3d && !s.sbs)) sendMode(stereo)
updateSpatialMode()
} }
fun set3d(on: Boolean) = post { fun set3d(on: Boolean) = post {
@@ -348,59 +255,7 @@ object Glasses {
markSbsFailed(linkDevice?.productId, s == GlassesState.SBS_FAILS) markSbsFailed(linkDevice?.productId, s == GlassesState.SBS_FAILS)
rememberSbs(s) rememberSbs(s)
} }
fun setGameOnGlasses(on: Boolean) = post { fun setGameOnGlasses(on: Boolean) = post { update { it.copy(gameOnGlasses = on) } }
val s = _state.value
if (!on && s.canControl && (s.sbs || modeState.pendingStereo)) {
modeState.manual()
sendMode(false)
}
update {
it.copy(
gameOnGlasses = on,
picture3d = if (!on && it.picture3d == GlassesSettings.PICTURE_SCREEN)
GlassesSettings.PICTURE_AUTO else it.picture3d,
)
}
}
fun set3dof(on: Boolean) = post {
if (!_state.value.supportsScreen3dof) return@post
update {
it.copy(
gameOnGlasses = on || it.gameOnGlasses,
headTracking = on || it.headTracking,
picture3d = if (on) GlassesSettings.PICTURE_SCREEN
else if (it.picture3d == GlassesSettings.PICTURE_SCREEN) GlassesSettings.PICTURE_AUTO else it.picture3d,
)
}
}
fun setPositionalTracking(on: Boolean) = post {
if (!_state.value.spatialConnected || _settings.value.positionalTracking == on) return@post
update { it.copy(positionalTracking = on, handControllers = it.handControllers && on,
joyConTracking = it.joyConTracking && on) }
if (!on) SpatialTracking.setControllers(false, false)
closeLink()
refresh()
}
fun setHandControllers(on: Boolean) = post {
val wanted = on && _settings.value.positionalTracking && _state.value.spatialConnected
update { it.copy(handControllers = wanted, joyConTracking = it.joyConTracking && !wanted) }
SpatialTracking.setControllers(wanted, _settings.value.joyConTracking)
}
fun setSteadyHandAim(on: Boolean) = post {
update { it.copy(steadyHandAim = on) }
SpatialTracking.setSteadyHandAim(on)
}
fun setJoyConTracking(on: Boolean) = post {
val wanted = on && _settings.value.positionalTracking && _state.value.spatialConnected
update { it.copy(joyConTracking = wanted, handControllers = it.handControllers && !wanted) }
SpatialTracking.setControllers(_settings.value.handControllers, wanted)
}
fun setEyeHeight(cm: Int) = post { update { it.copy(eyeHeightCm = cm.coerceIn(50, 250)) } }
fun setSpatialFloor() = SpatialTracking.setFloor(_settings.value.eyeHeightCm / 100f)
fun restartSpatialTracking() = post {
if (_state.value.spatialConnected && _settings.value.positionalTracking) { closeLink(); refresh() }
}
fun setHeadTracking(on: Boolean) = post { update { it.copy(headTracking = on) } } fun setHeadTracking(on: Boolean) = post { update { it.copy(headTracking = on) } }
fun setAuto3d(on: Boolean) = post { update { it.copy(auto3d = on) } } fun setAuto3d(on: Boolean) = post { update { it.copy(auto3d = on) } }
fun setPicture3d(picture: Int) = post { update { it.copy(picture3d = picture.coerceIn(0, 2)) } } fun setPicture3d(picture: Int) = post { update { it.copy(picture3d = picture.coerceIn(0, 2)) } }
@@ -409,7 +264,6 @@ object Glasses {
fun setVrFovDeg(deg: Int) = post { update { it.copy(vrFovDeg = deg.coerceIn(GlassesSettings.VR_FOV_MIN, GlassesSettings.VR_FOV_MAX)) } } fun setVrFovDeg(deg: Int) = post { update { it.copy(vrFovDeg = deg.coerceIn(GlassesSettings.VR_FOV_MIN, GlassesSettings.VR_FOV_MAX)) } }
fun outputHz(): Int = GlassesRendering.outputHz(_settings.value, _state.value) fun outputHz(): Int = GlassesRendering.outputHz(_settings.value, _state.value)
fun outputResolution(): GlassesResolution? = GlassesDisplayModes.selected(_settings.value, _state.value)
fun glassesDisplay(): Display? = _state.value.displayId.takeIf { it != Display.INVALID_DISPLAY }?.let { displays.getDisplay(it) } fun glassesDisplay(): Display? = _state.value.displayId.takeIf { it != Display.INVALID_DISPLAY }?.let { displays.getDisplay(it) }
@@ -423,16 +277,6 @@ object Glasses {
post { updateImu() } post { updateImu() }
} }
internal fun addPoseObserver(observer: PoseSink) {
poseObservers.add(observer)
post { updateImu() }
}
internal fun removePoseObserver(observer: PoseSink) {
poseObservers.remove(observer)
post { updateImu() }
}
fun simulate(seconds: Int, holdYaw: Double? = null, holdPitch: Double? = null): Boolean { fun simulate(seconds: Int, holdYaw: Double? = null, holdPitch: Double? = null): Boolean {
val hold = holdYaw != null || holdPitch != null val hold = holdYaw != null || holdPitch != null
val t = Thread({ val t = Thread({
@@ -468,15 +312,6 @@ object Glasses {
.put("permission", s.permission.name).put("connected", s.connected) .put("permission", s.permission.name).put("connected", s.connected)
.put("controlError", s.controlError ?: JSONObject.NULL) .put("controlError", s.controlError ?: JSONObject.NULL)
.put("experimental", s.experimental) .put("experimental", s.experimental)
.put("supportsScreen3dof", s.supportsScreen3dof)
.put("supportsSpatial", s.supportsSpatial)
.put("firmware", (link as? VitureSdkLink)?.firmware ?: JSONObject.NULL)
.put("spatialSdk", (link as? VitureSdkLink)?.spatialDiagnostics()?.let {
JSONObject().put("status",it[0]).put("callbackAgeMs",it[1]).put("cameraPoseDeltaMs",it[2])
} ?: JSONObject.NULL)
.put("spatial", SpatialTracking.diagnosticStatus())
.put("supports30Hz", s.supports30Hz).put("vrActive", s.vrActive)
.put("resolutions", JSONArray(s.resolutions.map { it.key }))
.put("display", if (s.hasDisplay) JSONObject().put("id", s.displayId).put("width", s.width).put("height", s.height).put("hz", s.hz.toDouble()) else JSONObject.NULL) .put("display", if (s.hasDisplay) JSONObject().put("id", s.displayId).put("width", s.width).put("height", s.height).put("hz", s.hz.toDouble()) else JSONObject.NULL)
.put("sbs", s.sbs).put("deviceMode", glassesMode).put("switching3d", s.switching3d) .put("sbs", s.sbs).put("deviceMode", glassesMode).put("switching3d", s.switching3d)
.put("brightness", s.brightness).put("volume", s.volume) .put("brightness", s.brightness).put("volume", s.volume)
@@ -490,11 +325,6 @@ object Glasses {
.put("fovDeg", s.diagonalFovDeg.toDouble()).put("noSignal", s.noSignal).put("sbsSupport", s.sbsSupport) .put("fovDeg", s.diagonalFovDeg.toDouble()).put("noSignal", s.noSignal).put("sbsSupport", s.sbsSupport)
.put("settings", JSONObject().put("refreshHz", g.refreshHz).put("sbsHz", g.sbsHz).put("sunblock", g.sunblock ?: JSONObject.NULL) .put("settings", JSONObject().put("refreshHz", g.refreshHz).put("sbsHz", g.sbsHz).put("sunblock", g.sunblock ?: JSONObject.NULL)
.put("gameOnGlasses", g.gameOnGlasses).put("headTracking", g.headTracking).put("auto3d", g.auto3d) .put("gameOnGlasses", g.gameOnGlasses).put("headTracking", g.headTracking).put("auto3d", g.auto3d)
.put("screen3dof", g.screen3dof)
.put("resolution2d", g.resolution2d).put("resolution3d", g.resolution3d).put("resolutionVr", g.resolutionVr)
.put("positionalTracking", g.positionalTracking).put("handControllers", g.handControllers)
.put("joyConTracking", g.joyConTracking).put("eyeHeightCm", g.eyeHeightCm)
.put("steadyHandAim", g.steadyHandAim)
.put("picture3d", g.picture3d).put("screenWidthDm", g.screenWidthDm).put("screenDistanceDm", g.screenDistanceDm) .put("picture3d", g.picture3d).put("screenWidthDm", g.screenWidthDm).put("screenDistanceDm", g.screenDistanceDm)
.put("vrFovDeg", g.vrFovDeg)) .put("vrFovDeg", g.vrFovDeg))
} }
@@ -620,14 +450,6 @@ object Glasses {
noSignal = noSignal, noSignal = noSignal,
sbs90 = m?.sbs90 == true, sbs90 = m?.sbs90 == true,
experimental = m === XrealModel, experimental = m === XrealModel,
supportsScreen3dof = link?.hasImu == true,
supports30Hz = display?.let(::supports30Hz) == true,
supportsSpatial = (link as? VitureSdkLink)?.isCarina == true,
resolutions = m?.resolutions?.takeIf { modes -> modes.isNotEmpty() }
?: display?.supportedModes.orEmpty().filter { mode ->
mode.physicalWidth >= 1280 && (mode.physicalWidth >= 3000) == sbsByDisplay
}.map { mode -> GlassesResolution(mode.physicalWidth / (if (sbsByDisplay) 2 else 1), mode.physicalHeight) }
.distinct().sortedWith(compareBy({ size -> size.height }, { size -> size.width })),
) )
} }
if (link != null) applyMode(force = false) if (link != null) applyMode(force = false)
@@ -636,14 +458,6 @@ object Glasses {
internal fun isGlassesVendor(vid: Int) = vid == VitureProtocol.VENDOR_ID || RayNeoModel.isVendor(vid) || vid == XrealModel.VENDOR_ID internal fun isGlassesVendor(vid: Int) = vid == VitureProtocol.VENDOR_ID || RayNeoModel.isVendor(vid) || vid == XrealModel.VENDOR_ID
internal fun supports30Hz(display: Display): Boolean {
val current = display.mode
return display.supportedModes.any {
it.physicalWidth == current.physicalWidth && it.physicalHeight == current.physicalHeight &&
abs(it.refreshRate - 30f) < 0.5f
}
}
private fun canOpenModel(m: GlassesModel): Boolean = m.controllable && private fun canOpenModel(m: GlassesModel): Boolean = m.controllable &&
(m !is VitureProtocol.Model || !m.needsSdk || VitureSdk.available) (m !is VitureProtocol.Model || !m.needsSdk || VitureSdk.available)
@@ -697,29 +511,14 @@ object Glasses {
runCatching { usb.requestPermission(device, pi) }.onFailure { Log.w(TAG, "requestPermission", it) } runCatching { usb.requestPermission(device, pi) }.onFailure { Log.w(TAG, "requestPermission", it) }
} }
private fun updateSpatialMode() {
val current = link as? VitureSdkLink ?: return
if (!current.ready || !current.isCarina || current.spatialEnabled ==
steamVrSpatialGate.spatialEnabled(_settings.value.positionalTracking, SystemClock.uptimeMillis())) return
val device = linkDevice
closeLink()
refresh()
val resumed = link as? VitureSdkLink
if (!current.spatialEnabled && resumed?.isCarina == true && resumed.spatialEnabled &&
device != null && linkDevice?.deviceName == device.deviceName) SpatialTracking.recenter(false)
}
private fun openLink(device: UsbDevice) { private fun openLink(device: UsbDevice) {
val generation = ++linkGeneration val generation = ++linkGeneration
val spatial = steamVrSpatialGate.spatialEnabled(_settings.value.positionalTracking, SystemClock.uptimeMillis())
calibrationKey = calibrationStore.key(device.vendorId, device.productId, calibrationKey = calibrationStore.key(device.vendorId, device.productId,
runCatching { device.serialNumber }.getOrNull(), model?.name.orEmpty()) runCatching { device.serialNumber }.getOrNull(), model?.name.orEmpty())
val l = if (device.vendorId == VitureProtocol.VENDOR_ID) { val l = if (device.vendorId == VitureProtocol.VENDOR_ID) {
if ((model as? VitureProtocol.Model)?.needsSdk == true) { if ((model as? VitureProtocol.Model)?.needsSdk == true) {
// Android can evict cacheDir while the SDK is running. VitureSdkLink.open(usb, device, File(app.cacheDir, "viture"), sdkListener(generation),
Log.i(TAG, "opening VITURE SDK pid=0x%04X spatial=%s".format(device.productId, spatial)) (model as? VitureProtocol.Model)?.family)
VitureSdkLink.open(usb, device, File(app.noBackupFilesDir, "viture"), sdkListener(generation),
(model as? VitureProtocol.Model)?.family, spatial)
} else VitureLink.open(usb, device, linkListener(generation)) } else VitureLink.open(usb, device, linkListener(generation))
} else if (model === XrealModel) { } else if (model === XrealModel) {
XrealLink.open(app, xrealListener(generation)) XrealLink.open(app, xrealListener(generation))
@@ -737,12 +536,6 @@ object Glasses {
return return
} }
link = opened link = opened
if (opened is VitureSdkLink && opened.isCarina) SpatialTracking.connect(opened.sdkToken, generation,
opened.spatialIdentity ?: runCatching { device.serialNumber }.getOrNull()?.takeIf { it.isNotBlank() }
?.let { "${device.vendorId}:${device.productId}:$it" },
spatial, _settings.value.eyeHeightCm / 100f, _settings.value.handControllers,
_settings.value.joyConTracking, _settings.value.steadyHandAim)
else SpatialTracking.useLegacyTracking()
_calibration.value = GlassesCalibrationState(supported = opened is RayNeoLink, _calibration.value = GlassesCalibrationState(supported = opened is RayNeoLink,
saved = opened is RayNeoLink && calibrationKey?.let(calibrationStore::load) != null) saved = opened is RayNeoLink && calibrationKey?.let(calibrationStore::load) != null)
linkDevice = device linkDevice = device
@@ -791,9 +584,6 @@ object Glasses {
} }
private fun sdkListener(generation: Long) = object : VitureSdkLink.Listener { private fun sdkListener(generation: Long) = object : VitureSdkLink.Listener {
override fun onSpatial(pose: FloatArray, timeNs: Long, valid: Boolean) {
if (generation == linkGeneration) SpatialTracking.accept(pose, timeNs, generation, valid)
}
override fun onValue(msgId: Int, value: Int) = post { override fun onValue(msgId: Int, value: Int) = post {
if (generation != linkGeneration) return@post if (generation != linkGeneration) return@post
when (msgId) { when (msgId) {
@@ -862,14 +652,13 @@ object Glasses {
private fun closeLink() { private fun closeLink() {
val l = link ?: return val l = link ?: return
linkGeneration++ linkGeneration++
SpatialTracking.disconnect()
link = null link = null
linkDevice = null linkDevice = null
calibrationKey = null calibrationKey = null
_calibration.value = GlassesCalibrationState(phase = if (_calibration.value.running) CalibrationPhase.FAILED else CalibrationPhase.IDLE) _calibration.value = GlassesCalibrationState(phase = if (_calibration.value.running) CalibrationPhase.FAILED else CalibrationPhase.IDLE)
glassesMode = 0 glassesMode = 0
l.close() l.close()
publish { it.copy(connected = false, tracking = false, supportsScreen3dof = false, supportsSpatial = false) } publish { it.copy(connected = false, tracking = false) }
Log.i(TAG, "link closed") Log.i(TAG, "link closed")
} }
@@ -899,14 +688,10 @@ object Glasses {
} }
if (!s.usable || s.sbs || modeState.pendingStereo) return if (!s.usable || s.sbs || modeState.pendingStereo) return
val hz = _settings.value.refreshHz val hz = _settings.value.refreshHz
// Native 30 Hz is selected by the Android presentation, without a vendor mode command. if (glassesMode == m.mode(hz, false)) return
if (hz == 30 && GlassesRendering.native30HzAvailable(_settings.value, s)) return
if (glassesMode == m.mode(hz, false, outputResolution())) return
if (!force) { if (!force) {
if (autoModeSent || SystemClock.uptimeMillis() - lastModeSentAt < 8_000) return if (autoModeSent || SystemClock.uptimeMillis() - lastModeSentAt < 8_000) return
val resolution = outputResolution() if (glassesMode == 0 && abs(s.hz - hz) < 1.5f) return
if (glassesMode == 0 && abs(s.hz - hz) < 1.5f &&
(resolution == null || (s.width == resolution.width && s.height == resolution.height))) return
autoModeSent = true autoModeSent = true
} }
sendMode(false) sendMode(false)
@@ -914,10 +699,8 @@ object Glasses {
private fun sendMode(sbs: Boolean): Boolean { private fun sendMode(sbs: Boolean): Boolean {
val m = model ?: return false val m = model ?: return false
if (sbs && !_settings.value.gameOnGlasses) update { it.copy(gameOnGlasses = true) }
val g = _settings.value val g = _settings.value
val resolution = GlassesDisplayModes.selected(g, _state.value, sbs) val mode = m.mode(if (sbs) g.sbsHz else g.refreshHz, sbs)
val mode = m.mode(if (sbs) g.sbsHz else g.refreshHz, sbs, resolution)
if (link?.send(VitureProtocol.MSG_DISPLAY, byteArrayOf(mode.toByte())) == true) { if (link?.send(VitureProtocol.MSG_DISPLAY, byteArrayOf(mode.toByte())) == true) {
if (link is RayNeoLink) glassesMode = mode if (link is RayNeoLink) glassesMode = mode
lastModeSentAt = SystemClock.uptimeMillis() lastModeSentAt = SystemClock.uptimeMillis()
@@ -945,7 +728,7 @@ object Glasses {
private fun updateImu() { private fun updateImu() {
val l = link ?: return val l = link ?: return
if (!l.ready) return if (!l.ready) return
val want = (sink != null || poseObservers.isNotEmpty() || probe != null || _calibration.value.running || SpatialTracking.enabled) && l.hasImu val want = (sink != null || probe != null || _calibration.value.running) && l.hasImu
if (want == _state.value.tracking) return if (want == _state.value.tracking) return
val accepted = l.send(VitureProtocol.MSG_IMU, byteArrayOf(if (want) 1 else 0)) val accepted = l.send(VitureProtocol.MSG_IMU, byteArrayOf(if (want) 1 else 0))
if (want && !accepted) return if (want && !accepted) return
@@ -986,7 +769,6 @@ object Glasses {
private fun deliver(q: FloatArray, timeNs: Long) { private fun deliver(q: FloatArray, timeNs: Long) {
latest = q latest = q
sink?.onPose(q[0], q[1], q[2], q[3], timeNs) sink?.onPose(q[0], q[1], q[2], q[3], timeNs)
poseObservers.forEach { it.onPose(q[0], q[1], q[2], q[3], timeNs) }
} }
private fun onReport(frame: VitureProtocol.Frame) { private fun onReport(frame: VitureProtocol.Frame) {
@@ -1050,16 +832,8 @@ object Glasses {
private fun load(): GlassesSettings { private fun load(): GlassesSettings {
val p = app.getSharedPreferences(PREFS, Context.MODE_PRIVATE) val p = app.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
return GlassesSettings( return GlassesSettings(
positionalTracking = p.getBoolean("positionalTracking", false),
handControllers = p.getBoolean("handControllers", false),
joyConTracking = p.getBoolean("joyConTracking", false),
steadyHandAim = p.getBoolean("steadyHandAim", false),
eyeHeightCm = p.getInt("eyeHeightCm", 160).coerceIn(50, 250),
refreshHz = p.getInt("refreshHz", 120), refreshHz = p.getInt("refreshHz", 120),
sbsHz = p.getInt("sbsHz", 60), sbsHz = p.getInt("sbsHz", 60),
resolution2d = p.getString("resolution2d", "").orEmpty(),
resolution3d = p.getString("resolution3d", "").orEmpty(),
resolutionVr = p.getString("resolutionVr", "").orEmpty(),
sunblock = if (p.contains("sunblock")) p.getBoolean("sunblock", false) else null, sunblock = if (p.contains("sunblock")) p.getBoolean("sunblock", false) else null,
gameOnGlasses = p.getBoolean("gameOnGlasses", true), gameOnGlasses = p.getBoolean("gameOnGlasses", true),
headTracking = p.getBoolean("headTracking", true), headTracking = p.getBoolean("headTracking", true),
@@ -1073,16 +847,8 @@ object Glasses {
private fun save(s: GlassesSettings) { private fun save(s: GlassesSettings) {
app.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().apply { app.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().apply {
putBoolean("positionalTracking", s.positionalTracking)
putBoolean("handControllers", s.handControllers)
putBoolean("joyConTracking", s.joyConTracking)
putBoolean("steadyHandAim", s.steadyHandAim)
putInt("eyeHeightCm", s.eyeHeightCm)
putInt("refreshHz", s.refreshHz) putInt("refreshHz", s.refreshHz)
putInt("sbsHz", s.sbsHz) putInt("sbsHz", s.sbsHz)
putString("resolution2d", s.resolution2d)
putString("resolution3d", s.resolution3d)
putString("resolutionVr", s.resolutionVr)
s.sunblock?.let { putBoolean("sunblock", it) } ?: remove("sunblock") s.sunblock?.let { putBoolean("sunblock", it) } ?: remove("sunblock")
putBoolean("gameOnGlasses", s.gameOnGlasses) putBoolean("gameOnGlasses", s.gameOnGlasses)
putBoolean("headTracking", s.headTracking) putBoolean("headTracking", s.headTracking)
@@ -1,29 +0,0 @@
package com.droiddeck.launcher.glasses
data class GlassesResolution(val width: Int, val height: Int) {
val key: String get() = "${width}x$height"
}
enum class GlassesDisplayProfile { TWO_D, THREE_D, VR }
internal object GlassesDisplayModes {
fun profile(stereo: Boolean, vr: Boolean): GlassesDisplayProfile = when {
vr -> GlassesDisplayProfile.VR
stereo -> GlassesDisplayProfile.THREE_D
else -> GlassesDisplayProfile.TWO_D
}
fun choice(settings: GlassesSettings, profile: GlassesDisplayProfile): String = when (profile) {
GlassesDisplayProfile.TWO_D -> settings.resolution2d
GlassesDisplayProfile.THREE_D -> settings.resolution3d
GlassesDisplayProfile.VR -> settings.resolutionVr
}
fun selected(settings: GlassesSettings, state: GlassesState,
stereo: Boolean = state.sbs, vr: Boolean = state.vrActive): GlassesResolution? {
val selected = choice(settings, profile(stereo, vr)).ifEmpty {
if (vr) choice(settings, profile(stereo, false)) else ""
}
return state.resolutions.firstOrNull { it.key == selected }
}
}
@@ -9,8 +9,6 @@ interface GlassesModel {
val diagonalFovDeg: Float val diagonalFovDeg: Float
val sbs90: Boolean val sbs90: Boolean
val hasSunblock: Boolean get() = true val hasSunblock: Boolean get() = true
val resolutions: List<GlassesResolution> get() = emptyList()
fun mode(hz: Int, sbs: Boolean, resolution: GlassesResolution?): Int = mode(hz, sbs)
fun mode(hz: Int, sbs: Boolean): Int fun mode(hz: Int, sbs: Boolean): Int
fun modeForStep(step: Int): Int? fun modeForStep(step: Int): Int?
} }
@@ -1,175 +0,0 @@
package com.droiddeck.launcher.glasses
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.graphics.Color
import android.graphics.PorterDuff
import android.graphics.SurfaceTexture
import android.os.Build
import android.os.Looper
import android.view.Choreographer
import android.view.Surface
import android.view.View
import android.view.WindowManager
import android.view.inspector.WindowInspector
import kotlin.math.min
import kotlin.math.roundToInt
class GlassesMenuCapture(private val activity: Activity, private val onSize: (Int, Int) -> Unit,
private val onFailure: (Throwable) -> Unit = {}) : Choreographer.FrameCallback {
private var texture: SurfaceTexture? = null
private var surface: Surface? = null
private var running = false
private var framePending = false
private var lastFrameNs = Long.MIN_VALUE
private var failures = 0
private var bufferWidth = 0
private var bufferHeight = 0
private val basePosition = IntArray(2)
private val windowPosition = IntArray(2)
fun attach(texture: SurfaceTexture, surface: Surface) {
checkMainThread()
this.texture = texture
this.surface = surface
bufferWidth = 0
bufferHeight = 0
failures = 0
lastFrameNs = Long.MIN_VALUE
}
fun start() {
checkMainThread()
if (running || activity.isDestroyed || activity.isFinishing) return
running = true
failures = 0
lastFrameNs = Long.MIN_VALUE
schedule()
}
fun stop() {
checkMainThread()
running = false
if (framePending) Choreographer.getInstance().removeFrameCallback(this)
framePending = false
}
override fun doFrame(frameTimeNanos: Long) {
framePending = false
if (!running) return
if (activity.isDestroyed || activity.isFinishing) {
stop()
return
}
if (lastFrameNs == Long.MIN_VALUE || frameTimeNanos - lastFrameNs >= FRAME_INTERVAL_NS) {
lastFrameNs = frameTimeNanos
try {
capture()
failures = 0
} catch (error: Exception) {
if (++failures >= MAX_FAILURES) {
stop()
onFailure(error)
}
}
}
if (running) schedule()
}
private fun schedule() {
if (framePending) return
framePending = true
Choreographer.getInstance().postFrameCallback(this)
}
private fun capture() {
val target = surface ?: return
val input = texture ?: return
val decor = activity.window.decorView
if (!decor.isAttachedToWindow || !decor.isShown) return
val size = captureSize(decor.width, decor.height) ?: return
check(target.isValid)
if (bufferWidth != size.first || bufferHeight != size.second) {
input.setDefaultBufferSize(size.first, size.second)
onSize(size.first, size.second)
bufferWidth = size.first
bufferHeight = size.second
}
val candidates = if (Build.VERSION.SDK_INT >= 29) WindowInspector.getGlobalWindowViews() else emptyList()
val roots = captureRoots(activity, candidates)
val canvas = target.lockHardwareCanvas()
val initialSave = canvas.save()
try {
canvas.drawColor(Color.BLACK, PorterDuff.Mode.SRC)
val scale = min(canvas.width.toFloat() / decor.width, canvas.height.toFloat() / decor.height)
canvas.translate((canvas.width - decor.width * scale) / 2f, (canvas.height - decor.height * scale) / 2f)
canvas.scale(scale, scale)
canvas.clipRect(0, 0, decor.width, decor.height)
decor.getLocationOnScreen(basePosition)
for (root in roots) {
val params = root.layoutParams as? WindowManager.LayoutParams
if (root !== decor && params != null && params.flags and WindowManager.LayoutParams.FLAG_DIM_BEHIND != 0) {
canvas.drawColor(Color.argb((params.dimAmount.coerceIn(0f, 1f) * 255).roundToInt(), 0, 0, 0))
}
root.getLocationOnScreen(windowPosition)
val saved = canvas.save()
try {
canvas.translate((windowPosition[0] - basePosition[0]).toFloat(), (windowPosition[1] - basePosition[1]).toFloat())
root.draw(canvas)
} finally {
canvas.restoreToCount(saved)
}
}
} finally {
try {
canvas.restoreToCount(initialSave)
} finally {
target.unlockCanvasAndPost(canvas)
}
}
}
private fun checkMainThread() {
check(Looper.myLooper() == Looper.getMainLooper())
}
internal companion object {
private const val FRAME_INTERVAL_NS = 33_333_334L
private const val MAX_FAILURES = 3
private const val MAX_EDGE = 1920
internal fun captureSize(width: Int, height: Int): Pair<Int, Int>? {
if (width <= 0 || height <= 0) return null
val scale = min(1.0, MAX_EDGE.toDouble() / maxOf(width, height))
return (width * scale).roundToInt().coerceAtLeast(1) to (height * scale).roundToInt().coerceAtLeast(1)
}
internal fun captureRoots(activity: Activity, candidates: List<View>): List<View> {
val decor = activity.window.decorView
if (activity.window.attributes.flags and WindowManager.LayoutParams.FLAG_SECURE != 0 ||
!decor.isAttachedToWindow || !decor.isShown) return emptyList()
if (Build.VERSION.SDK_INT < 29) return listOf(decor)
val display = decor.display?.displayId ?: return listOf(decor)
val token = decor.applicationWindowToken
return listOf(decor) + candidates.filter { root ->
if (root === decor || !root.isAttachedToWindow || !root.isShown || root.display?.displayId != display) return@filter false
val params = root.layoutParams as? WindowManager.LayoutParams ?: return@filter false
if (params.flags and WindowManager.LayoutParams.FLAG_SECURE != 0 ||
params.type !in WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW..WindowManager.LayoutParams.LAST_SUB_WINDOW) return@filter false
ownsContext(root.context, activity) || (token != null && root.applicationWindowToken == token)
}.distinct()
}
private fun ownsContext(context: Context, activity: Activity): Boolean {
var current = context
repeat(16) {
if (current === activity) return true
val next = (current as? ContextWrapper)?.baseContext ?: return false
if (next === current) return false
current = next
}
return false
}
}
}
@@ -1,219 +0,0 @@
package com.droiddeck.launcher.glasses
import android.app.Activity
import android.app.Application
import android.app.Presentation
import android.os.Bundle
import android.util.Log
import android.view.Display
import android.view.WindowManager
import com.droiddeck.launcher.SessionActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.launch
object GlassesMenuMirror {
private var controller: GlassesMenuController? = null
fun initialize(app: Application) {
if (controller != null) return
val pose = GlassesMenuPose()
val menus = GlassesMenuController(pose,
display = Glasses::glassesDisplay,
observe = { active -> if (active) Glasses.addPoseObserver(pose) else Glasses.removePoseObserver(pose) },
create = { activity, display, failure -> MenuPresentation(activity, display, pose, failure) })
controller = menus
app.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
override fun onActivityResumed(activity: Activity) = menus.resume(activity)
override fun onActivityPaused(activity: Activity) = menus.pause(activity)
override fun onActivityDestroyed(activity: Activity) = menus.pause(activity)
override fun onActivityCreated(activity: Activity, state: Bundle?) = Unit
override fun onActivityStarted(activity: Activity) = Unit
override fun onActivityStopped(activity: Activity) = Unit
override fun onActivitySaveInstanceState(activity: Activity, state: Bundle) = Unit
})
CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate).launch {
combine(Glasses.state, Glasses.settings) { state, settings -> state to settings }
.collect { (state, settings) -> menus.update(state, settings) }
}
}
fun setSessionMenuVisible(activity: Activity, visible: Boolean) {
controller?.setSessionMenuVisible(activity, visible)
}
fun recenter() { controller?.recenter() }
}
internal class GlassesMenuController(
private val pose: GlassesMenuPose,
private val display: () -> Display?,
private val observe: (Boolean) -> Unit,
private val create: (Activity, Display, (Throwable) -> Unit) -> Output,
private val schedule: (() -> Unit) -> Unit = { android.os.Handler(android.os.Looper.getMainLooper()).post(it) },
) {
interface Output {
fun configure(state: GlassesState, settings: GlassesSettings)
fun show()
fun close()
}
private var activity: Activity? = null
private val sessionMenus = java.util.WeakHashMap<Activity, Boolean>()
private var state = GlassesState()
private var settings = GlassesSettings()
private var output: Output? = null
private var outputDisplay = Display.INVALID_DISPLAY
private var failed = false
private var dismissalRetried = false
private var generation = 0
fun resume(owner: Activity) {
if (activity !== owner) close()
activity = owner
failed = false
dismissalRetried = false
reconcile()
}
fun pause(owner: Activity) {
if (activity !== owner) return
close()
activity = null
}
fun setSessionMenuVisible(owner: Activity, visible: Boolean) {
if (visible) sessionMenus[owner] = true else sessionMenus.remove(owner)
if (activity === owner) reconcile()
}
fun update(next: GlassesState, preferences: GlassesSettings) {
val deviceChanged = state.canControl != next.canControl || state.model != next.model
if (deviceChanged) pose.reset()
if (deviceChanged || state.displayId != next.displayId || state.width != next.width ||
state.height != next.height || state.sbs != next.sbs || settings != preferences) {
failed = false
dismissalRetried = false
}
state = next
settings = preferences
pose.configure(preferences)
reconcile()
}
fun recenter() = pose.recenter()
private fun reconcile() {
val owner = activity
val eligible = owner != null && !owner.isFinishing && !owner.isDestroyed && !owner.isInPictureInPictureMode &&
owner.window.attributes.flags and WindowManager.LayoutParams.FLAG_SECURE == 0 &&
owner !is com.droiddeck.launcher.QuestXrActivity &&
(owner !is SessionActivity || sessionMenus[owner] == true) &&
settings.gameOnGlasses && settings.screen3dof && state.usable && state.canControl && state.supportsScreen3dof
val target = if (eligible && !failed) display() else null
if (target == null || owner == null || owner.windowManager.defaultDisplay.displayId == target.displayId) {
close()
return
}
if (outputDisplay != target.displayId) close()
try {
output?.let { it.configure(state, settings); return }
val token = ++generation
val next = create(owner, target) { error ->
if (generation == token) {
close()
if (error is GlassesMenuDisplayStopped && !dismissalRetried) {
dismissalRetried = true
val retry = generation
schedule { if (generation == retry && activity === owner) reconcile() }
} else {
Log.w("GlassesMenu", "Tracked menus are unavailable for this display", error)
failed = true
}
}
}
if (generation != token) {
next.close()
return
}
output = next
outputDisplay = target.displayId
next.configure(state, settings)
if (generation != token) return
observe(true)
next.show()
} catch (error: RuntimeException) {
Log.w("GlassesMenu", "Could not show tracked menus", error)
failed = true
close()
}
}
private fun close() {
++generation
val previous = output
output = null
outputDisplay = Display.INVALID_DISPLAY
if (previous != null) {
observe(false)
try { previous.close() }
catch (error: RuntimeException) { Log.w("GlassesMenu", "Could not close tracked menus", error) }
}
}
}
internal class GlassesMenuDisplayStopped : IllegalStateException("The glasses menu display stopped")
private class MenuPresentation(
private val owner: Activity,
display: Display,
pose: GlassesMenuPose,
private val onFailure: (Throwable) -> Unit,
) : Presentation(owner, display), GlassesMenuController.Output {
private var closed = false
private val capture: GlassesMenuCapture = GlassesMenuCapture(owner,
onSize = { width, height -> surface.setSourceSize(width, height) }, onFailure = onFailure)
private val surface: GlassesMenuSurface = GlassesMenuSurface(context, pose, onFailure = onFailure) { texture, input ->
if (!closed) {
capture.attach(texture, input)
capture.start()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window?.addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
setContentView(surface)
}
override fun configure(state: GlassesState, settings: GlassesSettings) {
surface.configure(settings, state)
val mode = display.mode
val hz = if (state.sbs) settings.sbsHz else settings.refreshHz
val best = display.supportedModes.filter {
it.physicalWidth == mode.physicalWidth && it.physicalHeight == mode.physicalHeight
}.minByOrNull { kotlin.math.abs(it.refreshRate - hz) }
if (best != null) window?.let { it.attributes = it.attributes.apply { preferredDisplayModeId = best.modeId } }
}
override fun close() {
if (closed) return
closed = true
capture.stop()
surface.close()
dismiss()
}
override fun onStop() {
capture.stop()
surface.close()
super.onStop()
if (!closed) {
closed = true
onFailure(GlassesMenuDisplayStopped())
}
}
}
@@ -1,86 +0,0 @@
package com.droiddeck.launcher.glasses
import com.droiddeck.launcher.gpu.HeadPose
class GlassesMenuPose internal constructor(
private val spatialEnabled: () -> Boolean = { SpatialTracking.enabled },
private val spatialView: (Long) -> SpatialPose? = { now ->
synchronized(SpatialTracking.session) {
if (SpatialTracking.session.valid(now)) SpatialTracking.session.view(true) else null
}
},
private val recenterSpatial: () -> Unit = { SpatialTracking.recenter(true) },
) : Glasses.PoseSink {
data class Frame(
val rotation: FloatArray,
val position: FloatArray,
val valid: Boolean,
val spatial: Boolean,
)
private var tracking = true
private var positional = false
private var reference: HeadPose.Reference? = null
private var latest: FloatArray? = null
private var latestTime = 0L
private var safe = identity()
@Synchronized fun configure(settings: GlassesSettings) {
if (tracking != settings.headTracking) {
reference = null
safe = identity()
}
tracking = settings.headTracking
positional = settings.positionalTracking
}
@Synchronized override fun onPose(x: Float, y: Float, z: Float, w: Float, timeNs: Long) {
val norm = x*x + y*y + z*z + w*w
if (!norm.isFinite() || norm !in 0.25f..2.25f || timeNs <= latestTime) return
val matrix = HeadPose.fromGlasses(x, y, z, w)
if (matrix.any { !it.isFinite() }) return
latest = matrix
latestTime = timeNs
}
@Synchronized fun snapshot(now: Long = System.nanoTime()): Frame {
if (!tracking) return identity()
val spatial = positional && spatialEnabled()
if (spatial) {
val pose = spatialView(now)
val normalized = pose?.rotation?.normalized()
if (pose != null && pose.position.finite() && normalized != null) {
safe = Frame(normalized.matrix(), pose.position.array(), true, true)
return copy(safe)
}
} else {
val matrix = latest
if (matrix != null && latestTime > 0 && now-latestTime in 0..MAX_AGE_NS) {
val anchor = reference ?: HeadPose.recenter(matrix, centerView = true).also { reference = it }
safe = Frame(HeadPose.relative(anchor, matrix), FloatArray(3), true, false)
return copy(safe)
}
}
return copy(safe).copy(valid = false, spatial = spatial)
}
@Synchronized fun recenter() {
if (positional && spatialEnabled()) recenterSpatial()
else reference = null
}
@Synchronized fun reset() {
reference = null
latest = null
latestTime = 0L
safe = identity()
}
private fun copy(frame: Frame) = frame.copy(rotation = frame.rotation.copyOf(), position = frame.position.copyOf())
private fun identity() = Frame(HeadPose.IDENTITY.copyOf(), FloatArray(3), false, false)
companion object {
internal const val MAX_AGE_NS = 100_000_000L
}
}
@@ -1,291 +0,0 @@
package com.droiddeck.launcher.glasses
import android.content.Context
import android.graphics.SurfaceTexture
import android.opengl.GLES11Ext
import android.opengl.GLES20
import android.opengl.GLSurfaceView
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.Surface
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10
import kotlin.math.tan
class GlassesMenuSurface(
context: Context,
private val pose: GlassesMenuPose,
private val onFailure: (Throwable) -> Unit = {},
private val onInput: (SurfaceTexture, Surface) -> Unit,
) : GLSurfaceView(context) {
private data class Scene(val settings: GlassesSettings, val state: GlassesState)
private val main = Handler(Looper.getMainLooper())
private val closed = AtomicBoolean()
private val failed = AtomicBoolean()
private val generation = AtomicInteger()
private val pendingFrame = AtomicBoolean()
private val inputLock = Any()
private var inputTexture: SurfaceTexture? = null
private var inputSurface: Surface? = null
@Volatile private var scene = Scene(GlassesSettings(), GlassesState())
@Volatile private var sourceAspect = 16f / 9f
private val renderer = MenuRenderer()
init {
setEGLContextClientVersion(2)
setEGLConfigChooser(8, 8, 8, 8, 0, 0)
preserveEGLContextOnPause = true
setRenderer(renderer)
renderMode = RENDERMODE_CONTINUOUSLY
}
fun configure(settings: GlassesSettings, state: GlassesState) {
pose.configure(settings)
scene = Scene(settings, state)
}
fun setSourceSize(width: Int, height: Int) {
if (width > 0 && height > 0) sourceAspect = width.toFloat() / height
}
fun close() {
if (!closed.compareAndSet(false, true)) return
generation.incrementAndGet()
queueEvent { renderer.release() }
}
override fun onDetachedFromWindow() {
close()
super.onDetachedFromWindow()
// GLSurfaceView may exit its GL thread before queued cleanup is consumed.
releaseInput()
}
private fun releaseInput() = synchronized(inputLock) {
inputTexture?.setOnFrameAvailableListener(null)
inputSurface?.release()
inputTexture?.release()
inputSurface = null
inputTexture = null
pendingFrame.set(false)
}
private fun fail(error: Throwable) {
if (!failed.compareAndSet(false, true)) return
generation.incrementAndGet()
Log.e("GlassesMenu", "Menu rendering is unavailable", error)
main.post { if (!closed.get()) onFailure(error) }
}
private inner class MenuRenderer : Renderer {
private val vertices = ByteBuffer.allocateDirect(8 * 4).order(ByteOrder.nativeOrder()).asFloatBuffer().apply {
put(floatArrayOf(-1f, -1f, 1f, -1f, -1f, 1f, 1f, 1f)); position(0)
}
private val textureMatrix = FloatArray(16)
private var texture = 0
private var program = 0
private var width = 1
private var height = 1
private var hasFrame = false
private var positionLocation = 0
private var textureLocation = 0
private var transformLocation = 0
private var rotationLocation = IntArray(3)
private var headLocation = 0
private var screenLocation = 0
private var opticsLocation = 0
override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) {
releaseInput()
texture = 0
program = 0
hasFrame = false
if (closed.get() || failed.get()) return
val token = generation.incrementAndGet()
try {
program = linkProgram()
positionLocation = GLES20.glGetAttribLocation(program, "aPosition")
textureLocation = GLES20.glGetUniformLocation(program, "uTexture")
transformLocation = GLES20.glGetUniformLocation(program, "uTextureMatrix")
rotationLocation = IntArray(3) { GLES20.glGetUniformLocation(program, "uRotation$it") }
headLocation = GLES20.glGetUniformLocation(program, "uHead")
screenLocation = GLES20.glGetUniformLocation(program, "uScreen")
opticsLocation = GLES20.glGetUniformLocation(program, "uOptics")
val names = IntArray(1)
GLES20.glGenTextures(1, names, 0)
texture = names[0]
check(texture != 0) { "Could not allocate the menu texture" }
GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, texture)
GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR)
GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR)
GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE)
GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE)
checkGl("initialize menu texture")
val incoming = SurfaceTexture(texture)
val surface = synchronized(inputLock) {
inputTexture = incoming
Surface(incoming).also { inputSurface = it }
}
incoming.setOnFrameAvailableListener({
if (!closed.get() && generation.get() == token) pendingFrame.set(true)
}, main)
main.post {
if (!closed.get() && !failed.get() && generation.get() == token) onInput(incoming, surface)
}
} catch (e: RuntimeException) {
fail(e)
release()
}
}
override fun onSurfaceChanged(gl: GL10?, width: Int, height: Int) {
this.width = width.coerceAtLeast(1)
this.height = height.coerceAtLeast(1)
GLES20.glViewport(0, 0, this.width, this.height)
}
override fun onDrawFrame(gl: GL10?) {
if (closed.get() || failed.get()) return
GLES20.glClearColor(0.015f, 0.015f, 0.02f, 1f)
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT)
if (program == 0) return
if (pendingFrame.getAndSet(false)) synchronized(inputLock) {
inputTexture?.let {
try {
it.updateTexImage()
it.getTransformMatrix(textureMatrix)
checkGl("update menu texture")
hasFrame = true
} catch (e: RuntimeException) {
fail(e)
release()
return
}
}
}
if (!hasFrame) return
val current = scene
val frame = pose.snapshot()
val halfWidth = current.settings.screenWidthDm.coerceIn(5, 200) / 20f
val distance = current.settings.screenDistanceDm.coerceIn(5, 200) / 10f
val mono = !current.state.sbs
val fov = current.state.verticalFovDeg.takeIf { it.isFinite() }?.coerceIn(20f, 140f) ?: 23.3f
val tangent = tan(Math.toRadians(fov.toDouble()) / 2).toFloat()
GLES20.glUseProgram(program)
GLES20.glActiveTexture(GLES20.GL_TEXTURE0)
GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, texture)
GLES20.glUniform1i(textureLocation, 0)
GLES20.glUniformMatrix4fv(transformLocation, 1, false, textureMatrix, 0)
for (row in 0..2) GLES20.glUniform3fv(rotationLocation[row], 1, frame.rotation, row * 3)
GLES20.glUniform3fv(headLocation, 1, frame.position, 0)
GLES20.glUniform3f(screenLocation, halfWidth, distance, sourceAspect)
GLES20.glUniform4f(opticsLocation, tangent, width.toFloat() / height / (if (mono) 1f else 2f),
if (mono) 0f else IPD_METERS / 2f, if (mono) 1f else 0f)
vertices.position(0)
GLES20.glEnableVertexAttribArray(positionLocation)
GLES20.glVertexAttribPointer(positionLocation, 2, GLES20.GL_FLOAT, false, 0, vertices)
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4)
GLES20.glDisableVertexAttribArray(positionLocation)
}
fun release() {
releaseInput()
if (texture != 0) GLES20.glDeleteTextures(1, intArrayOf(texture), 0)
if (program != 0) GLES20.glDeleteProgram(program)
texture = 0
program = 0
hasFrame = false
}
private fun checkGl(operation: String) {
val error = GLES20.glGetError()
check(error == GLES20.GL_NO_ERROR) { "Could not $operation: GL error 0x${error.toString(16)}" }
}
private fun shader(type: Int, source: String): Int {
val shader = GLES20.glCreateShader(type)
GLES20.glShaderSource(shader, source)
GLES20.glCompileShader(shader)
val status = IntArray(1)
GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, status, 0)
if (status[0] == 0) {
val error = GLES20.glGetShaderInfoLog(shader)
GLES20.glDeleteShader(shader)
throw IllegalStateException(error)
}
return shader
}
private fun linkProgram(): Int {
val vertex = shader(GLES20.GL_VERTEX_SHADER, VERTEX)
var fragment = 0
var linked = 0
try {
fragment = shader(GLES20.GL_FRAGMENT_SHADER, FRAGMENT)
linked = GLES20.glCreateProgram()
GLES20.glAttachShader(linked, vertex)
GLES20.glAttachShader(linked, fragment)
GLES20.glLinkProgram(linked)
val status = IntArray(1)
GLES20.glGetProgramiv(linked, GLES20.GL_LINK_STATUS, status, 0)
check(status[0] != 0) { GLES20.glGetProgramInfoLog(linked) }
return linked
} catch (e: RuntimeException) {
if (linked != 0) GLES20.glDeleteProgram(linked)
throw e
} finally {
GLES20.glDeleteShader(vertex)
if (fragment != 0) GLES20.glDeleteShader(fragment)
}
}
}
companion object {
internal const val IPD_METERS = 0.064f
private const val VERTEX = """
attribute vec2 aPosition;
varying vec2 vUv;
void main() {
gl_Position = vec4(aPosition, 0.0, 1.0);
vUv = aPosition * 0.5 + 0.5;
}
"""
private const val FRAGMENT = """
#extension GL_OES_EGL_image_external : require
precision highp float;
uniform samplerExternalOES uTexture;
uniform mat4 uTextureMatrix;
uniform vec3 uRotation0, uRotation1, uRotation2, uHead, uScreen;
uniform vec4 uOptics;
varying vec2 vUv;
vec3 rotate(vec3 v) {
return vec3(dot(uRotation0, v), dot(uRotation1, v), dot(uRotation2, v));
}
void main() {
bool mono = uOptics.w > 0.5;
float eye = mono || vUv.x < 0.5 ? 0.0 : 1.0;
vec2 local = vec2(mono ? vUv.x : vUv.x * 2.0 - eye, 1.0 - vUv.y);
vec2 ray = (local - 0.5) * vec2(uOptics.y, 1.0) * (2.0 * uOptics.x);
vec3 direction = rotate(vec3(ray.x, -ray.y, -1.0));
vec3 origin = uHead + rotate(vec3((eye < 0.5 ? -1.0 : 1.0) * uOptics.z, 0.0, 0.0));
vec3 color = vec3(0.015, 0.015, 0.02);
if (direction.z < -0.0001) {
float distance = (-uScreen.y - origin.z) / direction.z;
vec3 hit = origin + direction * distance;
vec2 source = vec2(hit.x / uScreen.x, -hit.y * uScreen.z / uScreen.x) * 0.5 + 0.5;
if (distance > 0.0 && all(greaterThanEqual(source, vec2(0.0))) && all(lessThanEqual(source, vec2(1.0)))) {
vec2 uv = (uTextureMatrix * vec4(source.x, 1.0 - source.y, 0.0, 1.0)).xy;
color = texture2D(uTexture, uv).rgb;
}
}
gl_FragColor = vec4(color, 1.0);
}
"""
}
}
@@ -4,32 +4,13 @@ import com.droiddeck.launcher.gpu.Cardboard
/** Share the actual picture mode with settings so controls match the rendered view. */ /** Share the actual picture mode with settings so controls match the rendered view. */
internal object GlassesRendering { internal object GlassesRendering {
enum class Picture { FLAT, DUPLICATED, VIRTUAL_SCREEN, STEREO } enum class Picture { FLAT, VIRTUAL_SCREEN, STEREO }
fun native30HzAvailable(settings: GlassesSettings, state: GlassesState): Boolean = fun outputHz(settings: GlassesSettings, state: GlassesState): Int =
state.usable && state.supports30Hz && settings.gameOnGlasses if (state.sbs) if (state.sbs90) settings.sbsHz else 60 else settings.refreshHz
fun refreshRates(settings: GlassesSettings, state: GlassesState): List<Int> = buildList { fun mirrorRefreshLimit(settings: GlassesSettings, state: GlassesState, outputActive: Boolean): Int =
if (native30HzAvailable(settings, state)) add(30) if (state.usable && !outputActive) outputHz(settings, state) else 0
add(60)
if (!state.sbs || state.sbs90) add(90)
if (!state.sbs) add(120)
}
fun outputHz(settings: GlassesSettings, state: GlassesState): Int {
val requested = if (state.sbs) settings.sbsHz else settings.refreshHz
return when {
requested == 30 -> if (native30HzAvailable(settings, state)) 30 else 60
state.sbs && !state.sbs90 -> 60
else -> requested
}
}
fun mirrorRefreshLimit(settings: GlassesSettings, state: GlassesState, outputActive: Boolean): Int {
if (!state.usable || outputActive) return 0
val hz = outputHz(settings, state)
return if (hz == 30 && kotlin.math.abs(state.hz - 30f) >= 0.5f) 60 else hz
}
fun fpsLimit(requested: Int, mirrorRefreshLimit: Int): Int = when { fun fpsLimit(requested: Int, mirrorRefreshLimit: Int): Int = when {
mirrorRefreshLimit <= 0 -> requested mirrorRefreshLimit <= 0 -> requested
@@ -41,12 +22,14 @@ internal object GlassesRendering {
outputActive || (steamVrRunning && state.usable) outputActive || (steamVrRunning && state.usable)
fun picture(settings: GlassesSettings, stereoDisplay: Boolean, steamVrRunning: Boolean): Picture = fun picture(settings: GlassesSettings, stereoDisplay: Boolean, steamVrRunning: Boolean): Picture =
when { when (settings.picture3d) {
steamVrRunning -> Picture.STEREO GlassesSettings.PICTURE_SCREEN -> Picture.VIRTUAL_SCREEN
settings.picture3d == GlassesSettings.PICTURE_SCREEN -> Picture.VIRTUAL_SCREEN GlassesSettings.PICTURE_SBS -> Picture.STEREO
settings.picture3d == GlassesSettings.PICTURE_SBS -> Picture.STEREO else -> when {
stereoDisplay -> Picture.DUPLICATED steamVrRunning -> Picture.STEREO
else -> Picture.FLAT stereoDisplay -> Picture.VIRTUAL_SCREEN
else -> Picture.FLAT
}
} }
fun cardboard( fun cardboard(
@@ -72,17 +55,12 @@ internal object GlassesRendering {
if (picture == Picture.FLAT) return Cardboard.OFF if (picture == Picture.FLAT) return Cardboard.OFF
return Cardboard( return Cardboard(
enabled = true, enabled = true,
source = when (picture) { source = if (picture == Picture.STEREO) Cardboard.SOURCE_SBS else Cardboard.SOURCE_SCREEN,
Picture.STEREO -> Cardboard.SOURCE_SBS
Picture.DUPLICATED -> Cardboard.SOURCE_FLAT
else -> Cardboard.SOURCE_SCREEN
},
viewer = Cardboard.Viewer.VITURE.id, viewer = Cardboard.Viewer.VITURE.id,
ipdMm = base.ipdMm, ipdMm = base.ipdMm,
screenWidthDm = settings.screenWidthDm, screenWidthDm = settings.screenWidthDm,
screenDistanceDm = settings.screenDistanceDm, screenDistanceDm = settings.screenDistanceDm,
headTracking = settings.headTracking && state.canControl && headTracking = settings.headTracking && state.canControl,
(picture == Picture.VIRTUAL_SCREEN || steamVrRunning),
mono = !state.sbs, mono = !state.sbs,
) )
} }
@@ -13,12 +13,10 @@ import android.view.WindowManager
import android.widget.FrameLayout import android.widget.FrameLayout
import kotlin.math.abs import kotlin.math.abs
class GlassesScreen(context: Context, display: Display, refreshHz: Int, private val callback: SurfaceHolder.Callback, resolution: GlassesResolution? = null) : Presentation(context, display) { class GlassesScreen(context: Context, display: Display, refreshHz: Int, private val callback: SurfaceHolder.Callback) : Presentation(context, display) {
val surfaceView = SurfaceView(getContext()) val surfaceView = SurfaceView(getContext())
internal val trackingRecovery = com.droiddeck.launcher.ui.TrackingRecoveryView(getContext())
val holder: SurfaceHolder get() = surfaceView.holder val holder: SurfaceHolder get() = surfaceView.holder
private var wantHz = refreshHz private var wantHz = refreshHz
private var wantResolution = resolution
val hz: Float get() = display.mode.refreshRate val hz: Float get() = display.mode.refreshRate
@@ -26,16 +24,14 @@ class GlassesScreen(context: Context, display: Display, refreshHz: Int, private
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
val root = FrameLayout(context).apply { setBackgroundColor(Color.BLACK) } val root = FrameLayout(context).apply { setBackgroundColor(Color.BLACK) }
root.addView(surfaceView, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)) root.addView(surfaceView, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
root.addView(trackingRecovery, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
setContentView(root) setContentView(root)
window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
applyMode() applyMode()
surfaceView.holder.addCallback(callback) surfaceView.holder.addCallback(callback)
} }
fun prefer(hz: Int, resolution: GlassesResolution? = null) { fun prefer(hz: Int) {
wantHz = hz wantHz = hz
wantResolution = resolution
// A 2D/SBS transition can replace the active mode without changing Hz. // A 2D/SBS transition can replace the active mode without changing Hz.
applyMode() applyMode()
} }
@@ -43,14 +39,9 @@ class GlassesScreen(context: Context, display: Display, refreshHz: Int, private
private fun applyMode() { private fun applyMode() {
val w = window ?: return val w = window ?: return
val current = display.mode val current = display.mode
val target = wantResolution val best = display.supportedModes.filter {
val width = target?.width?.times(if (current.physicalWidth >= 3000) 2 else 1) ?: current.physicalWidth
val height = target?.height ?: current.physicalHeight
val requested = display.supportedModes.filter { it.physicalWidth == width && it.physicalHeight == height }
val candidates = requested.ifEmpty { display.supportedModes.filter {
it.physicalWidth == current.physicalWidth && it.physicalHeight == current.physicalHeight it.physicalWidth == current.physicalWidth && it.physicalHeight == current.physicalHeight
} } }.minByOrNull { abs(it.refreshRate - wantHz) } ?: return
val best = candidates.minByOrNull { abs(it.refreshRate - wantHz) } ?: return
if (w.attributes.preferredDisplayModeId != best.modeId) { if (w.attributes.preferredDisplayModeId != best.modeId) {
Log.i("GlassesScreen", "display ${display.displayId}: prefer mode ${best.modeId} " + Log.i("GlassesScreen", "display ${display.displayId}: prefer mode ${best.modeId} " +
"${best.physicalWidth}x${best.physicalHeight}@${best.refreshRate} (requested $wantHz Hz)") "${best.physicalWidth}x${best.physicalHeight}@${best.refreshRate} (requested $wantHz Hz)")
@@ -1,48 +0,0 @@
package com.droiddeck.launcher.glasses
import kotlin.math.*
internal class HandGestures(private val rightHand: Boolean) {
private var grip = false
private var last: SpatialHand? = null
var lastOutcome = HandObservationOutcome.LANDMARK_COUNT_INVALID; private set
fun reset() { grip = false; last = null }
fun resetAfterRejection(outcome: HandObservationOutcome) {
if (outcome != HandObservationOutcome.PALM_MOTION_REJECTED) reset()
}
private fun reject(outcome: HandObservationOutcome): SpatialHand? { lastOutcome = outcome; return null }
fun estimate(points: List<SpatialVector?>, worldFromCamera: SpatialPose, time: Long,
leftImage: List<SpatialVector>? = null, rightImage: List<SpatialVector>? = null): SpatialHand? {
if (points.size != 21) return reject(HandObservationOutcome.LANDMARK_COUNT_INVALID)
val p = points.map { it?.takeIf(SpatialVector::finite) }
val wrist = p[0] ?: return reject(HandObservationOutcome.PALM_LANDMARK_MISSING)
val index = p[5] ?: return reject(HandObservationOutcome.PALM_LANDMARK_MISSING)
val middle = p[9] ?: return reject(HandObservationOutcome.PALM_LANDMARK_MISSING)
val ring = p[13] ?: return reject(HandObservationOutcome.PALM_LANDMARK_MISSING)
val little = p[17] ?: return reject(HandObservationOutcome.PALM_LANDMARK_MISSING)
val width = (index-little).length()
if (width !in 0.035f..0.13f) return reject(HandObservationOutcome.PALM_WIDTH_INVALID)
val forward = (middle-wrist).normalized() ?: return reject(HandObservationOutcome.PALM_BASIS_INVALID)
val lateral = (if (rightHand) little-index else index-little).normalized() ?: return reject(HandObservationOutcome.PALM_BASIS_INVALID)
val up = lateral.cross(forward).normalized() ?: return reject(HandObservationOutcome.PALM_BASIS_INVALID)
val right = forward.cross(up).normalized() ?: return reject(HandObservationOutcome.PALM_BASIS_INVALID)
val palm = (wrist+index+middle+ring+little) * 0.2f
val pose = worldFromCamera * SpatialPose(palm,SpatialRotation.fromBasis(right,up,forward * -1f))
last?.let { old ->
val dt=(time-old.timeNs)/1e9f
if (dt>0 && dt<0.2f && (pose.position-old.pose.position).length()>0.08f+dt*3f)
return reject(HandObservationOutcome.PALM_MOTION_REJECTED)
}
val stereo = if (leftImage != null || rightImage != null)
StereoFingerGestures.estimate(leftImage,rightImage,grip) else null
val triggerValid = stereo?.triggerValid ?: (p[4] != null && p[8] != null)
val trigger = stereo?.trigger ?: if (triggerValid) ((0.55f-(p[4]!!-p[8]!!).length()/width)/0.35f).coerceIn(0f,1f) else 0f
val gripValid = stereo?.gripValid ?: listOf(12,16,20).all { p[it] != null }
val closed = if (stereo == null && gripValid) listOf(12 to 9,16 to 13,20 to 17).count { (tip,base) ->
(p[tip]!!-wrist).length() < (p[base]!!-wrist).length()*1.35f
} else 0
grip=stereo?.grip ?: (gripValid && if(grip) closed>=2 else closed==3)
lastOutcome = HandObservationOutcome.ACCEPTED
return SpatialHand(pose,time,true,trigger,grip,triggerValid,gripValid).also { last=it }
}
}
@@ -1,57 +0,0 @@
package com.droiddeck.launcher.glasses
import android.graphics.Bitmap
import com.google.mediapipe.framework.image.ByteBufferImageBuilder
import com.google.mediapipe.framework.image.MPImage
import java.nio.ByteBuffer
internal class HandImageBuffer {
companion object {
const val PREPROCESSING = "raw-grayscale-rgb"
}
private var pixels = ByteBuffer.allocateDirect(0)
private var source = IntArray(0)
private var rgb = ByteArray(0)
private fun allocateRgb(count: Int) {
if (rgb.size != count * 3) {
rgb = ByteArray(count * 3)
pixels = ByteBuffer.allocateDirect(rgb.size)
}
}
fun image(grayscale: ByteArray, width: Int, height: Int): MPImage {
require(width > 0 && height > 0 && width.toLong() * height == grayscale.size.toLong())
allocateRgb(grayscale.size)
var index = 0
for (value in grayscale) {
rgb[index++] = value
rgb[index++] = value
rgb[index++] = value
}
return image(width, height)
}
fun image(grayscale: Bitmap): MPImage {
val count = grayscale.width * grayscale.height
if (source.size != count) source = IntArray(count)
allocateRgb(count)
grayscale.getPixels(source, 0, grayscale.width, 0, 0, grayscale.width, grayscale.height)
var index = 0
for (pixel in source) {
val value = (pixel ushr 16).toByte()
rgb[index++] = value
rgb[index++] = value
rgb[index++] = value
}
return image(grayscale.width, grayscale.height)
}
private fun image(width: Int, height: Int): MPImage {
pixels.clear()
pixels.put(rgb)
pixels.rewind()
// MediaPipe applies the model metadata's float normalization to these RGB bytes.
return ByteBufferImageBuilder(pixels, width, height, MPImage.IMAGE_FORMAT_RGB).build()
}
}
@@ -1,72 +0,0 @@
package com.droiddeck.launcher.glasses
internal class HandInferenceSchedule(
private val stableFrames: Int = 3,
private val discoveryIntervalMs: Long = 240,
private val maximumGapMs: Long = 400
) {
init {
require(stableFrames > 0)
require(discoveryIntervalMs > 0 && maximumGapMs >= discoveryIntervalMs)
}
private var lastFrameMs = -1L
private var selectedAtMs = -1L
private var selectedMaximum = 2
private var lastSearchMs = -1L
private var candidateSide = -1
private var consistentFrames = 0
private var trackingSide = -1
fun select(timestampMs: Long): Int {
if (timestampMs < 0) {
reset()
return 2
}
if (selectedAtMs >= 0 || lastFrameMs >= 0 &&
(timestampMs <= lastFrameMs || timestampMs - lastFrameMs > maximumGapMs)) reset()
val maximum = if (trackingSide >= 0 && lastSearchMs >= 0 &&
timestampMs - lastSearchMs < discoveryIntervalMs) 1 else 2
lastFrameMs = timestampMs
selectedAtMs = timestampMs
selectedMaximum = maximum
if (maximum == 2) lastSearchMs = timestampMs
return maximum
}
fun observe(timestampMs: Long, leftSides: List<Int>, rightSides: List<Int>,
leftRawCount: Int = leftSides.size, rightRawCount: Int = rightSides.size) {
if (timestampMs < 0 || selectedAtMs != timestampMs) {
reset()
return
}
selectedAtMs = -1L
val side = leftSides.singleOrNull() ?: -1
val consistent = leftRawCount == 1 && rightRawCount == 1 && side in 0..1 &&
rightSides.singleOrNull() == side
if (!consistent || selectedMaximum == 1 && side != trackingSide) {
forgetHand()
return
}
if (candidateSide != side) {
candidateSide = side
consistentFrames = 0
}
consistentFrames = minOf(stableFrames, consistentFrames + 1)
if (consistentFrames >= stableFrames) trackingSide = side
}
fun reset() {
lastFrameMs = -1L
selectedAtMs = -1L
selectedMaximum = 2
lastSearchMs = -1L
forgetHand()
}
private fun forgetHand() {
candidateSide = -1
consistentFrames = 0
trackingSide = -1
}
}
@@ -1,12 +0,0 @@
package com.droiddeck.launcher.glasses
import com.droiddeck.launcher.handtracking.TrackingPack
internal enum class HandModel(val file: String, val sha256: String) {
FULL(TrackingPack.HAND, "fbc2a30080c3c557093b5ddfc334698132eb341044ccee322ccf8bcf3607cde1"),
LITE(TrackingPack.HAND_LITE, "173c0f47ecee7e935bd4a1e93aa580756b4180c1307c07d709313e82c28672c8");
companion object {
val DEFAULT = FULL
}
}
@@ -1,48 +0,0 @@
package com.droiddeck.launcher.glasses
internal class HandProcessingRate {
var permille = 500
private set
private var processingMs = Double.NaN
private var headroomSamples = 0
fun observe(processingNs: Long, observationAgeNs: Long, trackingHealthy: Boolean): Int {
if (!trackingHealthy || processingNs <= 0 || observationAgeNs < 0) return reset()
val measuredMs = processingNs / 1_000_000.0
val ageMs = observationAgeNs / 1_000_000.0
processingMs = if (processingMs.isNaN()) measuredMs else processingMs + 0.2 * (measuredMs - processingMs)
if (measuredMs >= 80 || ageMs >= 140) {
permille = 500
headroomSamples = 0
return permille
}
val reduced = when {
permille > 500 && processingMs > 1000.0 / 15 -> 500
permille == 800 && processingMs > 50 -> 600
else -> permille
}
if (reduced != permille) {
permille = reduced
headroomSamples = 0
return permille
}
val enoughHeadroom = when (permille) {
500 -> processingMs <= 55 && ageMs <= 110
600 -> processingMs <= 40 && ageMs <= 90
else -> false
}
headroomSamples = if (enoughHeadroom) headroomSamples + 1 else 0
if (headroomSamples >= 8) {
permille = if (permille == 500) 600 else 800
headroomSamples = 0
}
return permille
}
fun reset(): Int {
permille = 500
processingMs = Double.NaN
headroomSamples = 0
return permille
}
}
@@ -1,107 +0,0 @@
package com.droiddeck.launcher.glasses
internal enum class HandObservationOutcome {
ACCEPTED, DISABLED, CALIBRATION_REQUIRED, CLOCK_NOT_READY, HEAD_TRACKING_INVALID,
CAMERA_NOT_SYNCHRONIZED, STALE_OBSERVATION, INFERENCE_UNAVAILABLE,
NO_MATCHING_DETECTION, AMBIGUOUS_HANDEDNESS, ONE_CAMERA_ONLY, STEREO_REJECTED,
LANDMARK_COUNT_INVALID, PALM_LANDMARK_MISSING, PALM_WIDTH_INVALID, PALM_BASIS_INVALID,
PALM_MOTION_REJECTED, WRIST_LANDMARK_MISSING, WRIST_MOTION_REJECTED
}
internal data class HandObservationDiagnostic(
val outcome: HandObservationOutcome,
val reconstructedPalmLandmarks: List<Int> = emptyList(),
val triggerEstimate: Float = 0f,
val triggerGeometryValid: Boolean = false,
val gripEstimate: Boolean = false,
val gripGeometryValid: Boolean = false,
val positionSource: String = "none"
) {
val accepted get() = outcome == HandObservationOutcome.ACCEPTED
val triggerValid get() = accepted && triggerGeometryValid
val gripValid get() = accepted && gripGeometryValid
}
internal data class HandSideMetrics(
val observations: Long,
val accepted: Long,
val triggerValid: Long,
val gripValid: Long,
val triggerAboveClickThreshold: Long,
val triggerReleased: Long,
val gripPressed: Long,
val trackingLosses: Long,
val triggerLosses: Long,
val gripLosses: Long,
val maximumConsecutiveRejected: Long,
val outcomes: Map<HandObservationOutcome, Long>
)
internal data class HandTrackingMetricSnapshot(
val processedPairs: Long,
val inferencePairs: Long,
val left: HandSideMetrics,
val right: HandSideMetrics
)
internal class HandTrackingMetrics {
private class Side {
val outcomes = LongArray(HandObservationOutcome.entries.size)
var triggerValid = 0L
var gripValid = 0L
var triggerAboveClickThreshold = 0L
var triggerReleased = 0L
var gripPressed = 0L
var trackingLosses = 0L
var triggerLosses = 0L
var gripLosses = 0L
var consecutiveRejected = 0L
var maximumConsecutiveRejected = 0L
var wasAccepted = false
var wasTriggerValid = false
var wasGripValid = false
fun observe(sample: HandObservationDiagnostic) {
outcomes[sample.outcome.ordinal]++
if (sample.triggerValid) {
triggerValid++
if (sample.triggerEstimate > 0.65f) triggerAboveClickThreshold++
if (sample.triggerEstimate < 0.25f) triggerReleased++
}
if (sample.gripValid) {
gripValid++
if (sample.gripEstimate) gripPressed++
}
if (wasAccepted && !sample.accepted) trackingLosses++
if (wasTriggerValid && !sample.triggerValid) triggerLosses++
if (wasGripValid && !sample.gripValid) gripLosses++
consecutiveRejected = if (sample.accepted) 0 else consecutiveRejected + 1
maximumConsecutiveRejected = maxOf(maximumConsecutiveRejected, consecutiveRejected)
wasAccepted = sample.accepted
wasTriggerValid = sample.triggerValid
wasGripValid = sample.gripValid
}
fun snapshot() = HandSideMetrics(outcomes.sum(), outcomes[HandObservationOutcome.ACCEPTED.ordinal],
triggerValid, gripValid, triggerAboveClickThreshold, triggerReleased, gripPressed, trackingLosses, triggerLosses, gripLosses,
maximumConsecutiveRejected, HandObservationOutcome.entries.filter { outcomes[it.ordinal] > 0 }
.associateWith { outcomes[it.ordinal] })
}
private val sides = Array(2) { Side() }
private var lastSequence = 0L
private var processedPairs = 0L
private var inferencePairs = 0L
fun observe(sequence: Long, inferred: Boolean, left: HandObservationDiagnostic,
right: HandObservationDiagnostic) {
if (sequence <= lastSequence) return
lastSequence = sequence
processedPairs++
if (inferred) inferencePairs++
sides[0].observe(left)
sides[1].observe(right)
}
fun snapshot() = HandTrackingMetricSnapshot(processedPairs, inferencePairs, sides[0].snapshot(), sides[1].snapshot())
}
@@ -1,16 +0,0 @@
package com.droiddeck.launcher.glasses
import kotlin.math.hypot
internal object JoyConFlowGate {
const val MAX_SEED_AGE_NS = 750_000_000L
fun fresh(seed: Long, previous: Long, now: Long) = seed > 0 && previous > 0 &&
now > previous && now - previous <= 200_000_000L && now - seed in 0..MAX_SEED_AGE_NS
fun point(x: Double, y: Double, backX: Double, backY: Double, oldX: Double, oldY: Double,
error: Float, forward: Boolean, backward: Boolean, width: Int, height: Int): Boolean =
forward && backward && error.isFinite() && error in 0f..20f &&
x.isFinite() && y.isFinite() && backX.isFinite() && backY.isFinite() &&
x >= 3 && y >= 3 && x < width - 3 && y < height - 3 &&
hypot(backX - oldX, backY - oldY) <= 1.5 && hypot(x - oldX, y - oldY) <= 100
}
@@ -1,26 +0,0 @@
package com.droiddeck.launcher.glasses
internal class JoyConWristPosition {
private var last: SpatialHand? = null
var lastOutcome = HandObservationOutcome.WRIST_LANDMARK_MISSING; private set
fun reset() { last = null }
private fun reject(outcome: HandObservationOutcome): SpatialHand? {
lastOutcome = outcome
return null
}
fun estimate(points: List<SpatialVector?>, worldFromCamera: SpatialPose, time: Long): SpatialHand? {
val wrist = points.firstOrNull()?.takeIf(SpatialVector::finite)
?: return reject(HandObservationOutcome.WRIST_LANDMARK_MISSING)
val pose = worldFromCamera * SpatialPose(wrist)
last?.let { old ->
val dt = (time - old.timeNs) / 1e9f
if (dt <= 0 || (dt < .2f && (pose.position - old.pose.position).length() > .08f + dt * 3f))
return reject(HandObservationOutcome.WRIST_MOTION_REJECTED)
}
lastOutcome = HandObservationOutcome.ACCEPTED
return SpatialHand(pose, time, true, triggerValid = false, gripValid = false).also { last = it }
}
}
@@ -1,160 +0,0 @@
package com.droiddeck.launcher.glasses
import android.Manifest
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.hardware.usb.UsbManager
import android.os.IBinder
import android.util.AtomicFile
import org.json.JSONObject
import java.io.File
internal object LumaRgbDiagnostic {
private fun file(context: Context) = AtomicFile(File(context.filesDir, "spatial/rgb-diagnostic.json"))
private fun save(context: Context, value: JSONObject) {
val target = file(context)
target.baseFile.parentFile?.mkdirs()
val output = target.startWrite()
try {
output.write(value.toString().toByteArray(Charsets.UTF_8))
target.finishWrite(output)
} catch (e: Exception) { target.failWrite(output); throw e }
}
private fun expired(value: JSONObject, nowMs: Long) = nowMs-value.optLong("startedMs") !in
0..value.optLong("timeoutMs",15_000).coerceIn(15_000,45_000)
private fun workerAlive(context: Context, pid: Int): Boolean = pid > 0 && pid != android.os.Process.myPid() &&
runCatching {
File("/proc/$pid/cmdline").readText().substringBefore('\u0000') == "${context.packageName}:rgb_diagnostic"
}.getOrDefault(false)
internal fun resolveStatus(value: JSONObject, nowMs: Long, workerAlive: Boolean): JSONObject {
val pending = value.optString("state") == "capturing"
if (workerAlive && !expired(value,nowMs)) {
if (!pending) value.put("resultState",value.optString("state")).put("phase","finishing")
return value.put("state","capturing").put("busy",true)
}
if (pending && (expired(value,nowMs) || value.optInt("workerPid") > 0 && !workerAlive))
value.put("state","failed").put("message","RGB capture worker stopped or timed out")
return value.put("busy",workerAlive || value.optString("state") == "capturing")
}
fun status(context: Context): JSONObject = runCatching {
val value = JSONObject(file(context).readFully().toString(Charsets.UTF_8))
val now = android.os.SystemClock.elapsedRealtime()
val pid = value.optInt("workerPid")
if (expired(value,now) && workerAlive(context,pid)) android.os.Process.killProcess(pid)
resolveStatus(value,now,workerAlive(context,pid))
}.getOrElse { JSONObject().put("state", "idle") }
@Synchronized fun capture(context: Context, transport: String = "sdk", width: Int = 640, height: Int = 480,
fps: Int = 30, durationMs: Int = 5000): JSONObject {
require(transport in listOf("sdk","uvc") && width in 160..1920 && height in 120..1080 &&
fps in 5..30 && durationMs in 1000..30000) { "Invalid RGB capture options" }
val app = context.applicationContext
val old = status(app)
if (old.optBoolean("busy")) return old
val usb = app.getSystemService(Context.USB_SERVICE) as UsbManager
val device = usb.deviceList.values.singleOrNull { it.vendorId == 0x0c45 && it.productId == 0x636b }
fun state(value: String, message: String): JSONObject {
val result = JSONObject().put("state", value).put("message", message)
save(app, result)
return result
}
if (!Glasses.state.value.spatialConnected || device == null)
return state("unavailable", "Connect the Luma Ultra glasses and RGB camera")
if (app.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
return state("permission_required", "Grant Android camera permission to capture the RGB camera")
if (!usb.hasPermission(device)) {
val intent = Intent("${app.packageName}.RGB_DIAGNOSTIC_PERMISSION").setPackage(app.packageName)
val pending = PendingIntent.getBroadcast(app, 3, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
usb.requestPermission(device, pending)
return state("permission_required", "Approve the USB camera permission, then request the capture again")
}
val result = JSONObject().put("state", "capturing").put("startedMs", android.os.SystemClock.elapsedRealtime())
.put("timeoutMs",durationMs+15000).put("transport",transport)
save(app, result)
try { app.startService(Intent(app, LumaRgbCaptureService::class.java).putExtra("device", device.deviceName)
.putExtra("transport",transport).putExtra("width",width).putExtra("height",height)
.putExtra("fps",fps).putExtra("durationMs",durationMs)) }
catch (e: Exception) { return state("failed", e.message ?: e.toString()) }
return result
}
internal fun perform(context: Context, deviceName: String, transport: String, width: Int, height: Int,
fps: Int, durationMs: Int) {
val folder=File(context.filesDir,"spatial/rgb-captures/${System.nanoTime()}").apply { mkdirs() }
val startedMs=android.os.SystemClock.elapsedRealtime()
val workerPid=android.os.Process.myPid()
save(context,JSONObject().put("state","capturing").put("path",folder.path)
.put("startedMs",startedMs).put("timeoutMs",durationMs+15000)
.put("transport",transport).put("workerPid",workerPid))
val result = try {
val direct=transport=="uvc"
check(if(direct) UvcRgbDiagnostic.available else VitureSdk.available) { "Requested RGB transport is unavailable" }
val usb = context.getSystemService(Context.USB_SERVICE) as UsbManager
val device = checkNotNull(usb.deviceList[deviceName]) { "RGB camera disconnected" }
check(device.vendorId == 0x0c45 && device.productId == 0x636b && usb.hasPermission(device))
val connection = checkNotNull(usb.openDevice(device)) { "Could not open RGB camera" }
val metadata=LongArray(if(direct) 14 else 7)
val jpeg=try {
File(folder,"usb-descriptors.bin").writeBytes(connection.rawDescriptors)
android.os.ParcelFileDescriptor.open(File(folder,"usb.log"),
android.os.ParcelFileDescriptor.MODE_CREATE or android.os.ParcelFileDescriptor.MODE_TRUNCATE or
android.os.ParcelFileDescriptor.MODE_WRITE_ONLY).use { log ->
if(direct) UvcRgbDiagnostic.nativeSnapshot(connection.fileDescriptor,width,height,fps,durationMs,metadata,log.fd)
else VitureSdk.nativeRgbSnapshot(device.vendorId,device.productId,connection.fileDescriptor,metadata,log.fd)
}
} finally { connection.close() }
check(jpeg != null) { "RGB camera returned no frame ($transport status ${metadata[4]}, callbacks ${metadata[5]})" }
File(folder,"rgb.jpg").writeBytes(jpeg)
val info=JSONObject().put("state","completed").put("path",folder.path)
.put("width",metadata[0]).put("height",metadata[1]).put("timestampNs",metadata[2])
.put("sequence",metadata[3]).put("callbacks",metadata[5]).put("source","Luma Ultra UVC RGB")
.put("receiptNs",metadata[6]).put("timingBasis","Host callback receipt; not exposure time")
.put("snapshotAcquired",true)
if(direct) {
val health=UvcStreamHealth.assess(metadata,fps,durationMs)
info.put("firstReceiptNs",metadata[7]).put("maxFrameGapMs",health.maximumGapMs)
.put("completeFrames",metadata[9]).put("invalidFrames",metadata[10]).put("bytes",metadata[11])
.put("observationEndNs",metadata[12]).put("tailFrameAgeMs",metadata[13]/1e6)
.put("observationMs",health.observationMs).put("observedFps",health.observedFps)
.put("streamHealthy",health.healthy)
}
info
} catch (e: Exception) { JSONObject().put("state","failed").put("snapshotAcquired",false)
.put("message",e.message ?: e.toString()) }
result.put("path",folder.path).put("transport",transport).put("requestedWidth",width).put("requestedHeight",height)
.put("requestedFps",fps).put("durationMs",durationMs).put("workerPid",workerPid)
.put("startedMs",startedMs).put("timeoutMs",durationMs+15000)
if (transport == "uvc" && !result.has("streamHealthy")) result.put("streamHealthy",false)
File(folder,"frame.json").writeText(result.toString())
save(context,result)
}
}
class LumaRgbCaptureService : Service() {
private var running = false
override fun onBind(intent: Intent?): IBinder? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (!running) {
running = true
Thread({
try { LumaRgbDiagnostic.perform(this,intent?.getStringExtra("device") ?: "",
intent?.getStringExtra("transport") ?: "sdk",intent?.getIntExtra("width",640) ?: 640,
intent?.getIntExtra("height",480) ?: 480,intent?.getIntExtra("fps",30) ?: 30,
intent?.getIntExtra("durationMs",5000) ?: 5000) }
finally {
stopSelf()
// SDK 2.4.0 can crash while cancelling failed USB transfers; isolate each diagnostic.
android.os.Process.killProcess(android.os.Process.myPid())
}
}, "luma-rgb-diagnostic").start()
}
return START_NOT_STICKY
}
}
@@ -1,36 +0,0 @@
package com.droiddeck.launcher.glasses
import com.droiddeck.launcher.R
import java.util.Locale
import kotlin.math.roundToInt
internal object SpatialMeasurements {
fun height(centimeters: Int): String {
val tenths = (centimeters / 2.54 * 10).roundToInt()
return String.format(Locale.getDefault(), "%d cm (%d ft %.1f in)", centimeters, tenths / 120, tenths % 120 / 10.0)
}
fun distance(meters: Float): String = String.format(
Locale.getDefault(), "%.1f m (%.1f ft)", meters, meters / 0.3048f)
fun validation(meters: Float): String = String.format(
Locale.getDefault(), "%.1f cm (%.2f in)", meters * 100, meters / 0.0254f)
}
internal enum class CalibrationDistance(val meters: Float, val labelRes: Int) {
INCHES_12(0.3048f, R.string.spatial_distance_12in),
CENTIMETERS_30(0.3f, R.string.spatial_distance_30cm),
INCHES_20(0.508f, R.string.spatial_distance_20in),
CENTIMETERS_50(0.5f, R.string.spatial_distance_50cm),
}
internal data class SpatialCalibrationProgress(
val collecting: Boolean = false,
val views: Int = 0,
val fitted: Boolean = false,
val solving: Boolean = false,
val capturing: Boolean = false,
val captureMessage: String? = null,
val validating: Boolean = false,
val validationMessage: String? = null,
)
Loaded 100 of 649 files, more files were not shown because too many files have changed in this diff. Show more