Compare commits
319 Commits
camera-ite
...
0.44.1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
807928a8d3 | ||
|
|
f74c891907 | ||
|
|
2dc0fdadfd | ||
|
|
8e317a8e08 | ||
|
|
c41179a437 | ||
|
|
43910cce78 | ||
|
|
643986e03d | ||
|
|
a2b061ed43 | ||
|
|
c458624157 | ||
|
|
1d2b149395 | ||
|
|
c84848ea9c | ||
|
|
b34e5f7a19 | ||
|
|
af3d49c9ef | ||
|
|
d5d63b2f89 | ||
|
|
d4b7c3f61a | ||
|
|
36dacb3322 | ||
|
|
eec38dd60f | ||
|
|
1e0ea6ae92 | ||
|
|
31f45760f0 | ||
|
|
f76863a79b | ||
|
|
43b3499ed7 | ||
|
|
dfaaa2a3a9 | ||
|
|
b8d17ac7ca | ||
|
|
ed28914f86 | ||
|
|
f8fab6bf5a | ||
|
|
1b37d77304 | ||
|
|
6eb36516b0 | ||
|
|
f0200be990 | ||
|
|
cfd3d0016b | ||
|
|
fbf0f4f672 | ||
|
|
387fa96a60 | ||
|
|
d549018024 | ||
|
|
5cd92f2c03 | ||
|
|
2450411e21 | ||
|
|
b53bfde23b | ||
|
|
15eb73af41 | ||
|
|
3c82ae309c | ||
|
|
4adcfca2fe | ||
|
|
f893491bed | ||
|
|
9d1181aaca | ||
|
|
b0f9bf24cf | ||
|
|
3527ce2507 | ||
|
|
f045bfb93d | ||
|
|
3d4ab27a14 | ||
|
|
54ff87c146 | ||
|
|
2bc988fe3d | ||
|
|
051893858b | ||
|
|
1ac211c23f | ||
|
|
4874f010dd | ||
|
|
da894143f9 | ||
|
|
109affec81 | ||
|
|
665e6b034f | ||
|
|
fc45b4e400 | ||
|
|
af75d2a451 | ||
|
|
3136a8f2b7 | ||
|
|
e97368f3e2 | ||
|
|
4da7ed1ccf | ||
|
|
bf248e192f | ||
|
|
167c3d1cbf | ||
|
|
b39d8f37f4 | ||
|
|
1198797db8 | ||
|
|
823a71a286 | ||
|
|
f78da4b198 | ||
|
|
558fb1aa4e | ||
|
|
abe32a8dbd | ||
|
|
d9e040bf8b | ||
|
|
0b8da1d280 | ||
|
|
455f3a0e9c | ||
|
|
411b30294b | ||
|
|
1d54b75a53 | ||
|
|
4c56c31bfc | ||
|
|
b21e031668 | ||
|
|
7c6b2f5949 | ||
|
|
1f66d7dee4 | ||
|
|
53b035ef92 | ||
|
|
237b084a65 | ||
|
|
707e56cb6f | ||
|
|
6f4da69e36 | ||
|
|
5634729445 | ||
|
|
b9603dc0a1 | ||
|
|
0323fbfb86 | ||
|
|
433568da63 | ||
|
|
4e199dd43f | ||
|
|
a4430b9a95 | ||
|
|
136383326e | ||
|
|
5a86f11beb | ||
|
|
6ab2bb2d52 | ||
|
|
ce8877b67e | ||
|
|
74a2f7a249 | ||
|
|
11ecb0aebe | ||
|
|
281f5e91ff | ||
|
|
5dc7cfbe83 | ||
|
|
3432c63a6e | ||
|
|
02ac96b0dc | ||
|
|
0736f99631 | ||
|
|
4bbe3ad8d0 | ||
|
|
1cf9d0f8c5 | ||
|
|
51d0cab832 | ||
|
|
062c63af2b | ||
|
|
3ce3fadb8d | ||
|
|
f0e39195b7 | ||
|
|
0d639760e9 | ||
|
|
6109a6bde6 | ||
|
|
000b633767 | ||
|
|
e3b1276d77 | ||
|
|
1cb8e1b7a4 | ||
|
|
e879b724ec | ||
|
|
08010efa46 | ||
|
|
e682931e3e | ||
|
|
bf89b73e8f | ||
|
|
2e252279bb | ||
|
|
9cf43ec535 | ||
|
|
f15578f7df | ||
|
|
f63ca4a25b | ||
|
|
89741508e3 | ||
|
|
81be807749 | ||
|
|
fcdb8a7edf | ||
|
|
90ce185f29 | ||
|
|
d6353035ae | ||
|
|
ceb1b23264 | ||
|
|
199e6f70b3 | ||
|
|
641db4face | ||
|
|
80d292b511 | ||
|
|
7fbcc92d02 | ||
|
|
de46726d01 | ||
|
|
6efa3a909e | ||
|
|
ea0f174da7 | ||
|
|
444146fa21 | ||
|
|
a7930760e8 | ||
|
|
668c32f583 | ||
|
|
927e1c48e2 | ||
|
|
8cc20e054c | ||
|
|
b12b171b53 | ||
|
|
0e61d51072 | ||
|
|
e61c04960e | ||
|
|
5dc82be1a3 | ||
|
|
6861b92972 | ||
|
|
f68f350cd2 | ||
|
|
2820415373 | ||
|
|
f721a57604 | ||
|
|
fb4149eaa7 | ||
|
|
d3746ef787 | ||
|
|
9d4b4bee4d | ||
|
|
5390b0effb | ||
|
|
13da4c8d60 | ||
|
|
1740d55f9c | ||
|
|
52d5e97de6 | ||
|
|
633df045d4 | ||
|
|
415bf5bb04 | ||
|
|
4e2d4a15c9 | ||
|
|
ef0142183d | ||
|
|
e5dfd9d3df | ||
|
|
6773fe2cf3 | ||
|
|
5a6e7e02ca | ||
|
|
c5d8ec2ef1 | ||
|
|
a31781146e | ||
|
|
cb9368cb8e | ||
|
|
629c05e507 | ||
|
|
9123153bf3 | ||
|
|
f3dc632ffc | ||
|
|
c369100d8a | ||
|
|
e10d40ef5e | ||
|
|
d6ca367187 | ||
|
|
88ac8a8b86 | ||
|
|
70fef89e2d | ||
|
|
4d79a59b20 | ||
|
|
c776c1b712 | ||
|
|
d4de15e0b3 | ||
|
|
9d220ec235 | ||
|
|
09c6c010e2 | ||
|
|
c9e185e9f3 | ||
|
|
4737149c85 | ||
|
|
648451b47e | ||
|
|
a9ef2d6f4b | ||
|
|
d6ffcadd76 | ||
|
|
448b7489e8 | ||
|
|
622cf60a65 | ||
|
|
1ab11f1660 | ||
|
|
9654e6cc59 | ||
|
|
44d177858f | ||
|
|
be41f11b83 | ||
|
|
dd2bffc2b1 | ||
|
|
d2ef508607 | ||
|
|
0cc7c7bc24 | ||
|
|
8d65e304cb | ||
|
|
b0dbccbd18 | ||
|
|
a823fbfb57 | ||
|
|
4a864e6519 | ||
|
|
e23d847449 | ||
|
|
8ba199f053 | ||
|
|
23925b4475 | ||
|
|
7ea0220f33 | ||
|
|
969e4de882 | ||
|
|
e5acb3013f | ||
|
|
3d57bed1c0 | ||
|
|
45839ebf60 | ||
|
|
0bb5b53e02 | ||
|
|
4f966b6d71 | ||
|
|
2687a393b5 | ||
|
|
5c605932ef | ||
|
|
bccdc8221e | ||
|
|
bddf17bbef | ||
|
|
e8511e8759 | ||
|
|
85296f538b | ||
|
|
f8ff80b781 | ||
|
|
932fef87f5 | ||
|
|
742780e34e | ||
|
|
41ede661f7 | ||
|
|
8d85460803 | ||
|
|
ac71581db8 | ||
|
|
2f894c4058 | ||
|
|
2b97c98a6e | ||
|
|
98d9f491ba | ||
|
|
16d710e106 | ||
|
|
9ad202e778 | ||
|
|
b3747d623c | ||
|
|
d5ff9281e6 | ||
|
|
18ebd8c522 | ||
|
|
411f71c217 | ||
|
|
3027ae20a9 | ||
|
|
fbce321426 | ||
|
|
74bc3a306e | ||
|
|
a950ad59f1 | ||
|
|
cf840da444 | ||
|
|
173fba35fa | ||
|
|
97fbbec0fe | ||
|
|
400f3a23bf | ||
|
|
1ad3336b6f | ||
|
|
8e9956abe1 | ||
|
|
6ca93ea24c | ||
|
|
49810e8fd1 | ||
|
|
afd0946558 | ||
|
|
fd31d0cd99 | ||
|
|
2f380da62f | ||
|
|
1c6971cd11 | ||
|
|
da4cf084d2 | ||
|
|
ca95ed5461 | ||
|
|
1b06cb6952 | ||
|
|
df89c826bb | ||
|
|
21f7f66440 | ||
|
|
3f1bad18c8 | ||
|
|
0c190cc833 | ||
|
|
5f0df8e7c1 | ||
|
|
d715f2f9ed | ||
|
|
d7fa4e62b8 | ||
|
|
568ebb0060 | ||
|
|
42efc67625 | ||
|
|
dd4b0097a1 | ||
|
|
a483cdbc7d | ||
|
|
84a7546442 | ||
|
|
dd43f238ff | ||
|
|
4f057358c8 | ||
|
|
e20971aef7 | ||
|
|
eb0d3c5bcf | ||
|
|
a18222e3df | ||
|
|
93ca932da9 | ||
|
|
c512b2fef5 | ||
|
|
f53c684377 | ||
|
|
3552166207 | ||
|
|
0b6eb147c5 | ||
|
|
1833ed50f3 | ||
|
|
6cdbfb3bad | ||
|
|
a5e0cb19c9 | ||
|
|
519ab94312 | ||
|
|
f2a8c0ed13 | ||
|
|
b3998f315d | ||
|
|
40bcd61b98 | ||
|
|
7a4d557c61 | ||
|
|
303b3f3ca2 | ||
|
|
ac5e949614 | ||
|
|
60baabb850 | ||
|
|
248e48fd8e | ||
|
|
b9baee7e5f | ||
|
|
3598ffdbb1 | ||
|
|
c171d9e6db | ||
|
|
d7a607a663 | ||
|
|
03ccf9127d | ||
|
|
6a3024657f | ||
|
|
a0058fcc2e | ||
|
|
410cc13c4f | ||
|
|
bc259dbe01 | ||
|
|
3730e20248 | ||
|
|
1be413065d | ||
|
|
2721c20c8b | ||
|
|
80130f6ffd | ||
|
|
8da778eaba | ||
|
|
3c708d1aaf | ||
|
|
1ae1bef3c1 | ||
|
|
7fd0c1fddb | ||
|
|
fd9957b784 | ||
|
|
57da02dbad | ||
|
|
83a5b36ddc | ||
|
|
8c36d73775 | ||
|
|
8396b98f67 | ||
|
|
46d989ce7f | ||
|
|
75ac570486 | ||
|
|
242def9d06 | ||
|
|
959f32009b | ||
|
|
57796c217d | ||
|
|
cea3390e36 | ||
|
|
a756e80064 | ||
|
|
1f61d32877 | ||
|
|
da7e2c5e6e | ||
|
|
fd0940bfe9 | ||
|
|
2b4a495c07 | ||
|
|
cffb968d2e | ||
|
|
201ab3aee8 | ||
|
|
cfa3584dda | ||
|
|
f19ba93958 | ||
|
|
09a2572c3b | ||
|
|
c6316b4e8b | ||
|
|
9cd900b23f | ||
|
|
a6d30cb366 | ||
|
|
3e94a3f62a | ||
|
|
060f8264ff | ||
|
|
b7b3907647 | ||
|
|
1550555df1 | ||
|
|
c42a29a034 | ||
|
|
621bf6b82a |
2
.cargo/config.toml
Normal file
2
.cargo/config.toml
Normal file
@@ -0,0 +1,2 @@
|
||||
[build]
|
||||
rustflags = ["--cfg", "tokio_unstable"]
|
||||
13
.github/FUNDING.yml
vendored
Normal file
13
.github/FUNDING.yml
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: [technobaboo]
|
||||
patreon: # Replace with a single Patreon username
|
||||
open_collective: # Replace with a single Open Collective username
|
||||
ko_fi: # Replace with a single Ko-fi username
|
||||
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
|
||||
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||
liberapay: # Replace with a single Liberapay username
|
||||
issuehunt: # Replace with a single IssueHunt username
|
||||
otechie: # Replace with a single Otechie username
|
||||
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
|
||||
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||
46
.github/workflows/build.yml
vendored
Normal file
46
.github/workflows/build.yml
vendored
Normal file
@@ -0,0 +1,46 @@
|
||||
name: Build
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- '*'
|
||||
|
||||
jobs:
|
||||
build_and_package:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Install runtime dependencies
|
||||
run: sudo apt install -y --no-install-recommends libxkbcommon-dev libstdc++6 libopenxr-dev libx11-dev libxfixes-dev libgl1-mesa-dev libegl1-mesa-dev libgbm-dev libfontconfig-dev libjsoncpp-dev libxcb1-dev libglx-dev libxcb-glx0-dev libdrm-dev libwayland-dev libfreetype-dev libpng-dev
|
||||
|
||||
- name: Install build dependencies
|
||||
run: sudo apt install -y --no-install-recommends cmake ninja-build
|
||||
|
||||
- name: Set up Rust
|
||||
uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: stable
|
||||
|
||||
- name: Build server
|
||||
run: cargo build --release
|
||||
|
||||
|
||||
- name: Install appimagetool
|
||||
run: |
|
||||
wget https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-$(uname -m).AppImage -O /usr/local/bin/appimagetool; \
|
||||
chmod +x /usr/local/bin/appimagetool; \
|
||||
sed -i 's|AI\x02|\x00\x00\x00|' /usr/local/bin/appimagetool
|
||||
- name: Install cargo-appimage
|
||||
run: cargo install cargo-appimage
|
||||
|
||||
- name: Generate AppImage
|
||||
run: cargo appimage
|
||||
|
||||
- name: Upload AppImage
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: appimage
|
||||
path: '*.AppImage'
|
||||
11
.gitignore
vendored
11
.gitignore
vendored
@@ -2,11 +2,14 @@
|
||||
# will have compiled files and executables
|
||||
/target/
|
||||
|
||||
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
|
||||
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
|
||||
Cargo.lock
|
||||
|
||||
# These are backup files generated by rustfmt
|
||||
**/*.rs.bk
|
||||
|
||||
.vscode/
|
||||
|
||||
# Ignore build results from Nix
|
||||
*result*
|
||||
|
||||
/libs/
|
||||
*.AppImage
|
||||
*.blend1
|
||||
2867
Cargo.lock
generated
Normal file
2867
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
123
Cargo.toml
123
Cargo.toml
@@ -1,51 +1,114 @@
|
||||
[package]
|
||||
edition = "2018"
|
||||
edition = "2021"
|
||||
rust-version = "1.75"
|
||||
name = "stardust-xr-server"
|
||||
version = "0.10.1"
|
||||
version = "0.44.1"
|
||||
authors = ["Nova King <technobaboo@proton.me>"]
|
||||
description = "Stardust XR reference display server"
|
||||
license = "GPLv2"
|
||||
repository = "https://github.com/StardustXR/stardust-xr-server/"
|
||||
homepage = "https://stardustxr.org"
|
||||
|
||||
[workspace]
|
||||
members = ["codegen"]
|
||||
|
||||
[[bin]]
|
||||
name = "stardust-xr-server"
|
||||
path = "src/main.rs"
|
||||
|
||||
[features]
|
||||
default = ["wayland"]
|
||||
wayland = ["dep:smithay", "dep:xkbcommon"]
|
||||
xwayland_rootful = []
|
||||
xwayland_rootless = ["smithay/xwayland"]
|
||||
profile_tokio = ["dep:console-subscriber", "tokio/tracing"]
|
||||
profile_app = ["dep:tracing-tracy"]
|
||||
|
||||
[package.metadata.appimage]
|
||||
auto_link = true
|
||||
auto_link_exclude_list = [
|
||||
"libc*",
|
||||
"libdl*",
|
||||
"libpthread*",
|
||||
"ld-linux*",
|
||||
"libGL*",
|
||||
"libEGL*",
|
||||
]
|
||||
|
||||
[profile.dev.package."*"]
|
||||
opt-level = 3
|
||||
[profile.release]
|
||||
strip = true
|
||||
lto = true
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.57"
|
||||
clap = { version = "4.0.8", features = ["derive"] }
|
||||
ctrlc = "3.2.2"
|
||||
dashmap = "5.3.4"
|
||||
flatbuffers = "2.1.2"
|
||||
flexbuffers = "2.0.0"
|
||||
glam = {version = "0.21.3", features = ["mint"]}
|
||||
color-eyre = { version = "0.6.2", default-features = false }
|
||||
clap = { version = "4.2.4", features = ["derive"] }
|
||||
glam = { version = "0.23.0", features = ["mint"] }
|
||||
lazy_static = "1.4.0"
|
||||
mint = "0.5.9"
|
||||
nanoid = "0.4.0"
|
||||
once_cell = "1.12.0"
|
||||
once_cell = "1.17.1"
|
||||
parking_lot = "0.12.1"
|
||||
portable-atomic = {version = "0.3.0", features = ["float", "std"]}
|
||||
rccell = "0.1.3"
|
||||
portable-atomic = { version = "1.2.0", features = ["float", "std"] }
|
||||
rustc-hash = "1.1.0"
|
||||
slab = "0.4.6"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
thiserror = "1.0.31"
|
||||
tokio = { version = "1.27.0", features = ["rt-multi-thread", "signal", "time"] }
|
||||
send_wrapper = "0.6.0"
|
||||
prisma = "0.1.1"
|
||||
slog = "2.7.0"
|
||||
slog-stdlog = "4.1.1"
|
||||
xkbcommon = { version = "0.5.0", default-features = false }
|
||||
stardust-xr = "0.5.2"
|
||||
wayland-backend = "=0.1.0-beta.9"
|
||||
wayland-scanner = "=0.30.0-beta.9"
|
||||
directories = "4.0.1"
|
||||
serde = { version = "1.0.145", features = ["derive"] }
|
||||
directories = "5.0.0"
|
||||
serde = { version = "1.0.160", features = ["derive"] }
|
||||
serde_repr = "0.1.16"
|
||||
tracing = "0.1.37"
|
||||
tracing-subscriber = { version = "0.3.17", features = ["env-filter"] }
|
||||
global_counter = "0.2.2"
|
||||
rand = "0.8.5"
|
||||
atty = "0.2.14"
|
||||
xkbcommon = { version = "0.7.0", default-features = false, optional = true }
|
||||
ctrlc = "3.4.1"
|
||||
libc = "0.2.148"
|
||||
input-event-codes = "5.16.8"
|
||||
nix = "0.27.1"
|
||||
wayland-scanner = "0.31.1"
|
||||
wayland-backend = "0.3.3"
|
||||
cluFlock = "1.2.7"
|
||||
fxtypemap = "0.2.0"
|
||||
toml = "0.8.10"
|
||||
|
||||
[dependencies.smithay]
|
||||
# git = "https://github.com/technobaboo/smithay.git" # Until we get stereokit to understand OES samplers and external textures
|
||||
git = "https://github.com/smithay/smithay.git" # Until we get stereokit to understand OES samplers and external textures
|
||||
# path = "../smithay"
|
||||
default-features = false
|
||||
features = [
|
||||
"desktop",
|
||||
"backend_drm",
|
||||
"backend_egl",
|
||||
"renderer_gl",
|
||||
"wayland_frontend",
|
||||
]
|
||||
version = "*"
|
||||
optional = true
|
||||
|
||||
[dependencies.stereokit]
|
||||
default-features = false
|
||||
features = ["linux-egl"]
|
||||
version = "0.5.0"
|
||||
version = "0.16.9"
|
||||
|
||||
[dependencies.smithay]
|
||||
git = "https://github.com/technobaboo/smithay.git"
|
||||
branch = "feature/public_input"
|
||||
default-features = false
|
||||
features = ["desktop", "renderer_gl", "wayland_frontend"]
|
||||
version = "*"
|
||||
[dependencies.console-subscriber]
|
||||
version = "0.1.8"
|
||||
optional = true
|
||||
|
||||
[dependencies.tracing-tracy]
|
||||
version = "0.10.4"
|
||||
optional = true
|
||||
|
||||
[dependencies.stardust-xr]
|
||||
git = "https://github.com/StardustXR/core.git"
|
||||
|
||||
[dependencies.stardust-xr-server-codegen]
|
||||
path = "codegen"
|
||||
|
||||
# [patch.crates-io.stereokit]
|
||||
# path = "../stereokit-rs"
|
||||
# [patch.crates-io.stereokit-sys]
|
||||
# path = "../stereokit-sys"
|
||||
|
||||
71
README.md
71
README.md
@@ -15,8 +15,71 @@ This project is a usable Linux display server that reinvents human-computer inte
|
||||
```bash
|
||||
cargo build
|
||||
```
|
||||
The latest stable server is automatically built to an appimage at https://github.com/StardustXR/server/releases for easy testing.
|
||||
|
||||
## Install
|
||||
```bash
|
||||
cargo install
|
||||
```
|
||||
## Usage
|
||||
|
||||
First, try running `cargo run` in a terminal window. If a headset is plugged in and OpenXR is working no window will show up. However, the headset should show the same things as the window that opens:
|
||||
|
||||

|
||||
|
||||
Stardust won't do anything interesting without clients! Try some from https://github.com/StardustXR.
|
||||
|
||||
### Default Sky
|
||||
|
||||
You can set a default skytex/skylight by putting your favorite HDRI equirectangular sky in `~/.config/stardust/skytex.hdr`. Certain clients can override this.
|
||||
|
||||
Flatscreen mode when the default skybox is [Zhengyang Gate](https://polyhaven.com/a/zhengyang_gate):
|
||||

|
||||
|
||||
### Windowed Mode
|
||||
|
||||
If the stardust server can't connect to an OpenXR runtime or you force it into flatscreen mode with `-f`, the server will show in a window.
|
||||

|
||||
|
||||
You can navigate around by right click + dragging to look around, Shift+W/A/S/D/Q/E to move. If you have a virtual hand, left click pinches, right click points, both make a fist.
|
||||
|
||||
### Flags
|
||||
#### Flatscreen (-f)
|
||||
|
||||
The server will show up in windowed mode no matter what with your mouse pointer being turned into a 3D pointer. Keyboard input will be sent to whatever your mouse is hovering over like visionOS simulator.
|
||||
Flatscreen mode upon initial startup:
|
||||

|
||||
|
||||
#### Overlay (-o \<PRIORITY>)
|
||||
|
||||
The server will, if in XR mode, be overlaid using the OpenXR overlay extension with the given priority.
|
||||
|
||||
#### Disable controller (--disable-controller)
|
||||
|
||||
Some runtimes such as Monado may emulate a controller using a hand, and this messes with Stardust's input system. Set this flag to ignore the controllers that the OpenXR runtime provides.
|
||||
|
||||
#### Execute (-e </path/to/executable>)
|
||||
|
||||
When wayland and OpenXR and such are initialized, run the given executable (such as a bash script) with all the environment variables needed to connect all clients of any type to the server. If not set, the server will run the executable at `~/.config/stardust/startup` if it exists. This is how stardust desktop environments can be made.
|
||||
|
||||
#### Help (-h, --help)
|
||||
|
||||
help
|
||||
|
||||
## Test
|
||||
|
||||
##### Gnome Graphical Integration Test
|
||||
|
||||
- `nix build .#gnome-graphical-test`
|
||||
|
||||
This test uses Nix to reproducibly execute a QEMU virtual machine which
|
||||
spawns a full Gnome desktop. It runs `monado-service`, `stardust-xr-server`
|
||||
`flatland` underneath of Gnome and then attaches `weston-cliptest` to the
|
||||
`flatland` process running underneath of `stardust-xr-server`, the result is
|
||||
a screenshot in PNG format that should look like expected. If any process in
|
||||
this test produces an exit code above 0, the test will fail, graphical bugs
|
||||
should be visible in the screenshot. An example of the result is below.
|
||||
|
||||
###### Result
|
||||
|
||||

|
||||
|
||||
##### Everything
|
||||
|
||||
`nix flake check` will build every test underneath of the `checks` attribute in the `flake.nix`
|
||||
17
codegen/Cargo.toml
Normal file
17
codegen/Cargo.toml
Normal file
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
edition = "2021"
|
||||
name = "stardust-xr-server-codegen"
|
||||
version = "0.1.0"
|
||||
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
convert_case = "0.6.0"
|
||||
quote = "1.0.33"
|
||||
mint = "0.5.9"
|
||||
proc-macro2 = "1.0.71"
|
||||
split-iter = "0.1.0"
|
||||
|
||||
[dependencies.stardust-xr-schemas]
|
||||
git = "https://github.com/StardustXR/core.git"
|
||||
563
codegen/src/lib.rs
Normal file
563
codegen/src/lib.rs
Normal file
@@ -0,0 +1,563 @@
|
||||
use convert_case::{Case, Casing};
|
||||
use proc_macro2::{Ident, Span, TokenStream};
|
||||
use quote::{quote, ToTokens};
|
||||
use split_iter::Splittable;
|
||||
use stardust_xr_schemas::protocol::*;
|
||||
|
||||
fn fold_tokens(a: TokenStream, b: TokenStream) -> TokenStream {
|
||||
quote!(#a #b)
|
||||
}
|
||||
|
||||
// #[proc_macro]
|
||||
// pub fn codegen_root_protocol(_input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||
// codegen_protocol(ROOT_PROTOCOL)
|
||||
// }
|
||||
#[proc_macro]
|
||||
pub fn codegen_node_protocol(_input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||
codegen_protocol(NODE_PROTOCOL)
|
||||
}
|
||||
#[proc_macro]
|
||||
pub fn codegen_spatial_protocol(_input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||
codegen_protocol(SPATIAL_PROTOCOL)
|
||||
}
|
||||
#[proc_macro]
|
||||
pub fn codegen_field_protocol(_input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||
codegen_protocol(FIELD_PROTOCOL)
|
||||
}
|
||||
#[proc_macro]
|
||||
pub fn codegen_data_protocol(_input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||
codegen_protocol(DATA_PROTOCOL)
|
||||
}
|
||||
#[proc_macro]
|
||||
pub fn codegen_audio_protocol(_input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||
codegen_protocol(AUDIO_PROTOCOL)
|
||||
}
|
||||
#[proc_macro]
|
||||
pub fn codegen_drawable_protocol(_input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||
codegen_protocol(DRAWABLE_PROTOCOL)
|
||||
}
|
||||
// #[proc_macro]
|
||||
// pub fn codegen_input_protocol(_input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||
// codegen_protocol(INPUT_PROTOCOL)
|
||||
// }
|
||||
|
||||
fn codegen_protocol(protocol: &'static str) -> proc_macro::TokenStream {
|
||||
let protocol = Protocol::parse(protocol).unwrap();
|
||||
let interface = protocol
|
||||
.interface
|
||||
.map(|p| {
|
||||
let virtual_aspect_name = p.path[1..]
|
||||
.split('/')
|
||||
.map(ToString::to_string)
|
||||
.reduce(|a, b| format!("{a}_{b}"))
|
||||
.unwrap_or_default()
|
||||
+ "_interface";
|
||||
generate_aspect(&Aspect {
|
||||
name: virtual_aspect_name,
|
||||
description: protocol.description.clone(),
|
||||
members: p.members,
|
||||
})
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let custom_enums = protocol
|
||||
.custom_enums
|
||||
.iter()
|
||||
.map(generate_custom_enum)
|
||||
.reduce(fold_tokens)
|
||||
.unwrap_or_default();
|
||||
let custom_unions = protocol
|
||||
.custom_unions
|
||||
.iter()
|
||||
.map(generate_custom_union)
|
||||
.reduce(fold_tokens)
|
||||
.unwrap_or_default();
|
||||
let custom_structs = protocol
|
||||
.custom_structs
|
||||
.iter()
|
||||
.map(generate_custom_struct)
|
||||
.reduce(fold_tokens)
|
||||
.unwrap_or_default();
|
||||
let aspects = protocol
|
||||
.aspects
|
||||
.iter()
|
||||
.map(generate_aspect)
|
||||
.reduce(fold_tokens)
|
||||
.unwrap_or_default();
|
||||
// let nodes = protocol
|
||||
// .nodes
|
||||
// .iter()
|
||||
// .map(generate_node)
|
||||
// .reduce(fold_tokens)
|
||||
// .unwrap_or_default();
|
||||
quote!(#custom_enums #custom_unions #custom_structs #aspects #interface).into()
|
||||
}
|
||||
|
||||
fn generate_custom_enum(custom_enum: &CustomEnum) -> TokenStream {
|
||||
let name = Ident::new(&custom_enum.name.to_case(Case::Pascal), Span::call_site());
|
||||
let description = &custom_enum.description;
|
||||
|
||||
let argument_decls = custom_enum
|
||||
.variants
|
||||
.iter()
|
||||
.map(|a| Ident::new(&a.to_case(Case::Pascal), Span::call_site()).to_token_stream())
|
||||
.reduce(|a, b| quote!(#a, #b))
|
||||
.unwrap_or_default();
|
||||
|
||||
quote! {
|
||||
#[doc = #description]
|
||||
#[derive(Debug, Clone, Copy, serde_repr::Deserialize_repr, serde_repr::Serialize_repr)]
|
||||
#[repr(u32)]
|
||||
pub enum #name {#argument_decls}
|
||||
}
|
||||
}
|
||||
fn generate_custom_union(custom_union: &CustomUnion) -> TokenStream {
|
||||
let name = Ident::new(&custom_union.name.to_case(Case::Pascal), Span::call_site());
|
||||
let description = &custom_union.description;
|
||||
|
||||
let option_decls = custom_union
|
||||
.options
|
||||
.iter()
|
||||
.map(generate_union_option)
|
||||
.reduce(|a, b| quote!(#a, #b))
|
||||
.unwrap_or_default();
|
||||
|
||||
quote! {
|
||||
#[doc = #description]
|
||||
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum #name {#option_decls}
|
||||
}
|
||||
}
|
||||
fn generate_union_option(union_option: &UnionOption) -> TokenStream {
|
||||
let name = union_option
|
||||
.name
|
||||
.as_ref()
|
||||
.map(|n| n.to_case(Case::Pascal))
|
||||
.unwrap_or_else(|| argument_type_option_name(&union_option._type));
|
||||
let description = union_option
|
||||
.description
|
||||
.as_ref()
|
||||
.map(|d| quote!(#[doc = #d]))
|
||||
.unwrap_or_default();
|
||||
let identifier = Ident::new(&name, Span::call_site());
|
||||
let _type = generate_argument_type(&union_option._type, false, true);
|
||||
quote! (#description #identifier(#_type))
|
||||
}
|
||||
fn generate_custom_struct(custom_struct: &CustomStruct) -> TokenStream {
|
||||
let name = Ident::new(&custom_struct.name.to_case(Case::Pascal), Span::call_site());
|
||||
let description = &custom_struct.description;
|
||||
|
||||
let argument_decls = custom_struct
|
||||
.fields
|
||||
.iter()
|
||||
.map(|a| generate_argument_decl(a, true))
|
||||
.map(|d| quote!(pub #d))
|
||||
.reduce(|a, b| quote!(#a, #b))
|
||||
.unwrap_or_default();
|
||||
|
||||
quote! {
|
||||
#[doc = #description]
|
||||
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
|
||||
pub struct #name {#argument_decls}
|
||||
}
|
||||
}
|
||||
|
||||
// fn generate_node(node: &Node) -> TokenStream {
|
||||
// let node_name = Ident::new(&node.name, Span::call_site());
|
||||
// let description = &node.description;
|
||||
|
||||
// let aspects = node
|
||||
// .aspects
|
||||
// .iter()
|
||||
// .map(|a| {
|
||||
// let aspect_name = Ident::new(&format!("{a}Aspect"), Span::call_site());
|
||||
// quote!(impl #aspect_name for #node_name {})
|
||||
// })
|
||||
// .reduce(fold_tokens)
|
||||
// .unwrap_or_default();
|
||||
|
||||
// quote! {
|
||||
// #[doc = #description]
|
||||
// #[derive(Debug)]
|
||||
// pub struct #node_name (crate::node::Node);
|
||||
// impl crate::node::NodeType for #node_name {
|
||||
// fn node(&self) -> &crate::node::Node {
|
||||
// &self.0
|
||||
// }
|
||||
// fn alias(&self) -> Self {
|
||||
// #node_name(self.0.alias())
|
||||
// }
|
||||
// fn from_path(client: &std::sync::Arc<crate::client::Client>, path: String, destroyable: bool) -> Self {
|
||||
// #node_name(crate::node::Node::from_path(client, path, destroyable))
|
||||
// }
|
||||
// }
|
||||
// impl serde::Serialize for #node_name {
|
||||
// fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
// let node_path = self.0.get_path().map_err(|e| serde::ser::Error::custom(e))?;
|
||||
// serializer.serialize_str(&node_path)
|
||||
// }
|
||||
// }
|
||||
// #aspects
|
||||
// }
|
||||
// }
|
||||
|
||||
fn generate_aspect(aspect: &Aspect) -> TokenStream {
|
||||
let description = &aspect.description;
|
||||
let (client_members, server_members) = aspect.members.iter().split(|m| m.side == Side::Server);
|
||||
|
||||
let client_mod_name = Ident::new(
|
||||
&format!("{}_client", &aspect.name.to_case(Case::Snake)),
|
||||
Span::call_site(),
|
||||
);
|
||||
let client_side_members = client_members
|
||||
.map(generate_member)
|
||||
.reduce(fold_tokens)
|
||||
.map(|t| {
|
||||
quote! {
|
||||
pub mod #client_mod_name {
|
||||
#t
|
||||
}
|
||||
}
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
let aspect_trait_name = Ident::new(
|
||||
&format!("{}Aspect", &aspect.name.to_case(Case::Pascal)),
|
||||
Span::call_site(),
|
||||
);
|
||||
let server_side_members = server_members
|
||||
.map(generate_member)
|
||||
.reduce(fold_tokens)
|
||||
.unwrap_or_default();
|
||||
let add_node_members = aspect
|
||||
.members
|
||||
.iter()
|
||||
.filter(|m| m.side == Side::Server)
|
||||
.map(generate_handler)
|
||||
.reduce(fold_tokens)
|
||||
.map(|members| {
|
||||
quote! {
|
||||
fn add_node_members(node: &crate::nodes::Node) {
|
||||
#members
|
||||
}
|
||||
}
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let server_side_members = quote! {
|
||||
#[doc = #description]
|
||||
pub trait #aspect_trait_name {
|
||||
#add_node_members
|
||||
#server_side_members
|
||||
}
|
||||
};
|
||||
quote!(#client_side_members #server_side_members)
|
||||
}
|
||||
|
||||
fn generate_member(member: &Member) -> TokenStream {
|
||||
let name_str = &member.name;
|
||||
let name = Ident::new(&member.name.to_case(Case::Snake), Span::call_site());
|
||||
let description = &member.description;
|
||||
|
||||
let side = member.side;
|
||||
let _type = member._type;
|
||||
|
||||
let first_args = match member.side {
|
||||
Side::Server => {
|
||||
quote!(_node: std::sync::Arc<crate::nodes::Node>, _calling_client: std::sync::Arc<crate::core::client::Client>)
|
||||
}
|
||||
Side::Client => quote!(_node: &crate::nodes::Node),
|
||||
};
|
||||
let argument_decls = member
|
||||
.arguments
|
||||
.iter()
|
||||
.map(|a| generate_argument_decl(a, member.side == Side::Server))
|
||||
.fold(first_args, |a, b| quote!(#a, #b));
|
||||
|
||||
let argument_uses = member
|
||||
.arguments
|
||||
.iter()
|
||||
.map(|a| generate_argument_serialize(&a.name, &a._type, a.optional))
|
||||
.reduce(|a, b| quote!(#a, #b))
|
||||
.unwrap_or_default();
|
||||
let return_type = member
|
||||
.return_type
|
||||
.as_ref()
|
||||
.map(|r| generate_argument_type(&r, false, true))
|
||||
.unwrap_or_else(|| quote!(()));
|
||||
|
||||
match (side, _type) {
|
||||
(Side::Client, MemberType::Method) => {
|
||||
quote! {
|
||||
#[doc = #description]
|
||||
pub async fn #name(#argument_decls) -> color_eyre::eyre::Result<#return_type> {
|
||||
_node.execute_remote_method(#name_str, &(#argument_uses)).await
|
||||
}
|
||||
}
|
||||
}
|
||||
(Side::Client, MemberType::Signal) => {
|
||||
quote! {
|
||||
#[doc = #description]
|
||||
pub fn #name(#argument_decls) -> color_eyre::eyre::Result<()> {
|
||||
let serialized = stardust_xr::schemas::flex::serialize((#argument_uses))?;
|
||||
_node.send_remote_signal(#name_str, serialized)
|
||||
}
|
||||
}
|
||||
}
|
||||
(Side::Server, MemberType::Method) => {
|
||||
quote! {
|
||||
#[doc = #description]
|
||||
fn #name(#argument_decls) -> impl std::future::Future<Output = color_eyre::eyre::Result<#return_type>> + Send + 'static;
|
||||
}
|
||||
}
|
||||
(Side::Server, MemberType::Signal) => {
|
||||
let prefix =
|
||||
if let Some(ArgumentType::Node { _type, return_info }) = &member.return_type {
|
||||
if let Some(return_info) = return_info {
|
||||
let parent_name = Ident::new(
|
||||
&(name_str.to_case(Case::ScreamingSnake) + "_PARENT_PATH"),
|
||||
Span::call_site(),
|
||||
);
|
||||
let parent_path = &return_info.parent;
|
||||
quote!(const #parent_name: &'static str = #parent_path;)
|
||||
} else {
|
||||
TokenStream::default()
|
||||
}
|
||||
} else {
|
||||
TokenStream::default()
|
||||
};
|
||||
quote! {
|
||||
#prefix
|
||||
#[doc = #description]
|
||||
fn #name(#argument_decls) -> color_eyre::eyre::Result<()>;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn generate_handler(member: &Member) -> TokenStream {
|
||||
let member_name = &member.name;
|
||||
let member_name_ident = Ident::new(&member_name, Span::call_site());
|
||||
|
||||
let argument_names = member
|
||||
.arguments
|
||||
.iter()
|
||||
.map(generate_argument_name)
|
||||
.reduce(|a, b| quote!(#a, #b));
|
||||
let argument_types = member
|
||||
.arguments
|
||||
.iter()
|
||||
.map(|a| {
|
||||
let _type = convert_deserializeable_argument_type(&a._type);
|
||||
generate_argument_type(&_type, a.optional, true)
|
||||
})
|
||||
.reduce(|a, b| quote!(#a, #b));
|
||||
// dbg!(&argument_types);
|
||||
let deserialize = argument_names
|
||||
.clone()
|
||||
.zip(argument_types)
|
||||
.map(|(argument_names, argument_types)| {
|
||||
quote!(let (#argument_names): (#argument_types) = stardust_xr::schemas::flex::deserialize(_message.as_ref())?;)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let argument_uses = member
|
||||
.arguments
|
||||
.iter()
|
||||
.map(|a| generate_argument_deserialize(&a.name, &a._type, a.optional))
|
||||
.reduce(|a, b| quote!(#a, #b))
|
||||
.unwrap_or_default();
|
||||
match member._type {
|
||||
MemberType::Signal => quote! {
|
||||
node.add_local_signal(#member_name, |_node, _calling_client, _message| {
|
||||
#deserialize
|
||||
Self::#member_name_ident(_node, _calling_client.clone(), #argument_uses)
|
||||
});
|
||||
},
|
||||
MemberType::Method => quote! {
|
||||
node.add_local_method(#member_name, |_node, _calling_client, _message, _method_response| {
|
||||
_method_response.wrap_async(async move {
|
||||
#deserialize
|
||||
Ok((Self::#member_name_ident(_node, _calling_client.clone(), #argument_uses).await?, Vec::new()))
|
||||
});
|
||||
});
|
||||
},
|
||||
}
|
||||
}
|
||||
fn generate_argument_name(argument: &Argument) -> TokenStream {
|
||||
Ident::new(&argument.name.to_case(Case::Snake), Span::call_site()).to_token_stream()
|
||||
}
|
||||
|
||||
fn convert_deserializeable_argument_type(argument_type: &ArgumentType) -> ArgumentType {
|
||||
match argument_type {
|
||||
ArgumentType::Node { .. } => ArgumentType::String,
|
||||
f => f.clone(),
|
||||
}
|
||||
}
|
||||
fn generate_argument_deserialize(
|
||||
argument_name: &str,
|
||||
argument_type: &ArgumentType,
|
||||
optional: bool,
|
||||
) -> TokenStream {
|
||||
let name = Ident::new(&argument_name.to_case(Case::Snake), Span::call_site());
|
||||
|
||||
match argument_type {
|
||||
ArgumentType::Node { .. } => match optional {
|
||||
true => quote!(#name.map(|n| _calling_client.get_node(#argument_name, &n)?)),
|
||||
false => quote!(_calling_client.get_node(#argument_name, &#name)?),
|
||||
},
|
||||
ArgumentType::Color => quote!(color::rgba_linear!(#name[0], #name[1], #name[2], #name[3])),
|
||||
ArgumentType::Vec(v) => {
|
||||
let mapping = generate_argument_deserialize("a", v, false);
|
||||
quote!(#name.into_iter().map(|a| Ok(#mapping)).collect::<color_eyre::eyre::Result<Vec<_>>>()?)
|
||||
}
|
||||
ArgumentType::Map(v) => {
|
||||
let mapping = generate_argument_deserialize("a", v, false);
|
||||
quote!(#name.into_iter().map(|(k, a)| Ok((k, #mapping))).collect::<color_eyre::eyre::Result<rustc_hash::FxHashMap<String, _>>>()?)
|
||||
}
|
||||
_ => quote!(#name),
|
||||
}
|
||||
}
|
||||
fn generate_argument_serialize(
|
||||
argument_name: &str,
|
||||
argument_type: &ArgumentType,
|
||||
optional: bool,
|
||||
) -> TokenStream {
|
||||
let name = Ident::new(&argument_name.to_case(Case::Snake), Span::call_site());
|
||||
match argument_type {
|
||||
ArgumentType::Node {
|
||||
_type,
|
||||
return_info: _,
|
||||
} => match optional {
|
||||
true => quote!(#name.map(|n| n.get_path())),
|
||||
false => quote!(#name.get_path()),
|
||||
},
|
||||
ArgumentType::Color => quote!([#name.c.r, #name.c.g, #name.c.b, #name.a]),
|
||||
ArgumentType::Vec(v) => {
|
||||
let mapping = generate_argument_serialize("a", v, false);
|
||||
quote!(#name.into_iter().map(|a| Ok(#mapping)).collect::<color_eyre::eyre::Result<Vec<_>>>()?)
|
||||
}
|
||||
ArgumentType::Map(v) => {
|
||||
let mapping = generate_argument_serialize("a", v, false);
|
||||
quote!(#name.into_iter().map(|(k, a)| Ok((k, #mapping))).collect::<color_eyre::eyre::Result<rustc_hash::FxHashMap<String, _>>>()?)
|
||||
}
|
||||
_ => quote!(#name),
|
||||
}
|
||||
}
|
||||
fn generate_argument_decl(argument: &Argument, owned_values: bool) -> TokenStream {
|
||||
let name = Ident::new(&argument.name.to_case(Case::Snake), Span::call_site());
|
||||
let mut _type = generate_argument_type(&argument._type, argument.optional, owned_values);
|
||||
quote!(#name: #_type)
|
||||
}
|
||||
fn argument_type_option_name(argument_type: &ArgumentType) -> String {
|
||||
match argument_type {
|
||||
ArgumentType::Bool => "Bool".to_string(),
|
||||
ArgumentType::Int => "Int".to_string(),
|
||||
ArgumentType::UInt => "UInt".to_string(),
|
||||
ArgumentType::Float => "Float".to_string(),
|
||||
ArgumentType::Vec2 => "Vec2".to_string(),
|
||||
ArgumentType::Vec3 => "Vec3".to_string(),
|
||||
ArgumentType::Quat => "Quat".to_string(),
|
||||
ArgumentType::Color => "Color".to_string(),
|
||||
ArgumentType::String => "String".to_string(),
|
||||
ArgumentType::Bytes => "Bytes".to_string(),
|
||||
ArgumentType::Vec(v) => format!("{}Vector", argument_type_option_name(&v)),
|
||||
ArgumentType::Map(m) => format!("{}Map", argument_type_option_name(&m)),
|
||||
ArgumentType::Datamap => "Datamap".to_string(),
|
||||
ArgumentType::ResourceID => "ResourceID".to_string(),
|
||||
ArgumentType::Enum(e) => e.clone(),
|
||||
ArgumentType::Union(u) => u.clone(),
|
||||
ArgumentType::Struct(s) => s.clone(),
|
||||
ArgumentType::Node { _type, .. } => _type.clone(),
|
||||
}
|
||||
}
|
||||
fn generate_argument_type(
|
||||
argument_type: &ArgumentType,
|
||||
optional: bool,
|
||||
owned: bool,
|
||||
) -> TokenStream {
|
||||
let _type = match argument_type {
|
||||
ArgumentType::Bool => quote!(bool),
|
||||
ArgumentType::Int => quote!(i32),
|
||||
ArgumentType::UInt => quote!(u32),
|
||||
ArgumentType::Float => quote!(f32),
|
||||
ArgumentType::Vec2 => quote!(mint::Vector2<f32>),
|
||||
ArgumentType::Vec3 => quote!(mint::Vector3<f32>),
|
||||
ArgumentType::Quat => quote!(mint::Quaternion<f32>),
|
||||
ArgumentType::Color => quote!(stardust_xr::values::Color),
|
||||
ArgumentType::Bytes => {
|
||||
if !owned {
|
||||
quote!(&[u8])
|
||||
} else {
|
||||
quote!(Vec<u8>)
|
||||
}
|
||||
}
|
||||
ArgumentType::String => {
|
||||
if !owned {
|
||||
quote!(&str)
|
||||
} else {
|
||||
quote!(String)
|
||||
}
|
||||
}
|
||||
ArgumentType::Vec(t) => {
|
||||
let t = generate_argument_type(&t, false, true);
|
||||
if !owned {
|
||||
quote!(&[#t])
|
||||
} else {
|
||||
quote!(Vec<#t>)
|
||||
}
|
||||
}
|
||||
ArgumentType::Map(t) => {
|
||||
let t = generate_argument_type(&t, false, true);
|
||||
|
||||
if !owned {
|
||||
quote!(&rustc_hash::FxHashMap<String, #t>)
|
||||
} else {
|
||||
quote!(rustc_hash::FxHashMap<String, #t>)
|
||||
}
|
||||
}
|
||||
ArgumentType::Datamap => {
|
||||
if !owned {
|
||||
quote!(&stardust_xr::values::Datamap)
|
||||
} else {
|
||||
quote!(stardust_xr::values::Datamap)
|
||||
}
|
||||
}
|
||||
ArgumentType::ResourceID => {
|
||||
if !owned {
|
||||
quote!(&stardust_xr::values::ResourceID)
|
||||
} else {
|
||||
quote!(stardust_xr::values::ResourceID)
|
||||
}
|
||||
}
|
||||
ArgumentType::Enum(e) => {
|
||||
let enum_name = Ident::new(&e.to_case(Case::Pascal), Span::call_site());
|
||||
quote!(#enum_name)
|
||||
}
|
||||
ArgumentType::Union(u) => {
|
||||
let union_name = Ident::new(&u.to_case(Case::Pascal), Span::call_site());
|
||||
quote!(#union_name)
|
||||
}
|
||||
ArgumentType::Struct(s) => {
|
||||
let struct_name = Ident::new(&s.to_case(Case::Pascal), Span::call_site());
|
||||
if !owned {
|
||||
quote!(&#struct_name)
|
||||
} else {
|
||||
quote!(#struct_name)
|
||||
}
|
||||
}
|
||||
ArgumentType::Node {
|
||||
_type,
|
||||
return_info: _,
|
||||
} => {
|
||||
if !owned {
|
||||
quote!(&std::sync::Arc<crate::nodes::Node>)
|
||||
} else {
|
||||
quote!(std::sync::Arc<crate::nodes::Node>)
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if optional {
|
||||
quote!(Option<#_type>)
|
||||
} else {
|
||||
_type
|
||||
}
|
||||
}
|
||||
195
flake.lock
generated
Normal file
195
flake.lock
generated
Normal file
@@ -0,0 +1,195 @@
|
||||
{
|
||||
"nodes": {
|
||||
"fenix": {
|
||||
"inputs": {
|
||||
"nixpkgs": [
|
||||
"flatland",
|
||||
"nixpkgs"
|
||||
],
|
||||
"rust-analyzer-src": "rust-analyzer-src"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1700115779,
|
||||
"narHash": "sha256-oajhxEBg+16/KH74CaygAQ6b5KUHS7DwBoL9ecD9qeI=",
|
||||
"owner": "nix-community",
|
||||
"repo": "fenix",
|
||||
"rev": "4378e7e5f5bdef438eee5ce967f37593b9b5cd16",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "nix-community",
|
||||
"repo": "fenix",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"flake-parts": {
|
||||
"inputs": {
|
||||
"nixpkgs-lib": "nixpkgs-lib"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1709336216,
|
||||
"narHash": "sha256-Dt/wOWeW6Sqm11Yh+2+t0dfEWxoMxGBvv3JpIocFl9E=",
|
||||
"owner": "hercules-ci",
|
||||
"repo": "flake-parts",
|
||||
"rev": "f7b3c975cf067e56e7cda6cb098ebe3fb4d74ca2",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "hercules-ci",
|
||||
"repo": "flake-parts",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"flake-parts_2": {
|
||||
"inputs": {
|
||||
"nixpkgs-lib": [
|
||||
"hercules-ci-effects",
|
||||
"nixpkgs"
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1701473968,
|
||||
"narHash": "sha256-YcVE5emp1qQ8ieHUnxt1wCZCC3ZfAS+SRRWZ2TMda7E=",
|
||||
"owner": "hercules-ci",
|
||||
"repo": "flake-parts",
|
||||
"rev": "34fed993f1674c8d06d58b37ce1e0fe5eebcb9f5",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"id": "flake-parts",
|
||||
"type": "indirect"
|
||||
}
|
||||
},
|
||||
"flatland": {
|
||||
"inputs": {
|
||||
"fenix": "fenix",
|
||||
"nixpkgs": "nixpkgs"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1709774755,
|
||||
"narHash": "sha256-6tSG4G+SB+l71101XNyEHN/J8pSuJvbNPhKgzqP5sVU=",
|
||||
"owner": "StardustXR",
|
||||
"repo": "flatland",
|
||||
"rev": "fef8c317928a1d1798d8cee9af94d219a7c09e8c",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "StardustXR",
|
||||
"repo": "flatland",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"hercules-ci-effects": {
|
||||
"inputs": {
|
||||
"flake-parts": "flake-parts_2",
|
||||
"nixpkgs": "nixpkgs_2"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1708547820,
|
||||
"narHash": "sha256-xU/KC1PWqq5zL9dQ9wYhcdgxAwdeF/dJCLPH3PNZEBg=",
|
||||
"owner": "hercules-ci",
|
||||
"repo": "hercules-ci-effects",
|
||||
"rev": "0ca27bd58e4d5be3135a4bef66b582e57abe8f4a",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "hercules-ci",
|
||||
"repo": "hercules-ci-effects",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1699781429,
|
||||
"narHash": "sha256-UYefjidASiLORAjIvVsUHG6WBtRhM67kTjEY4XfZOFs=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "e44462d6021bfe23dfb24b775cc7c390844f773d",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "NixOS",
|
||||
"ref": "nixos-unstable",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nixpkgs-lib": {
|
||||
"locked": {
|
||||
"dir": "lib",
|
||||
"lastModified": 1709237383,
|
||||
"narHash": "sha256-cy6ArO4k5qTx+l5o+0mL9f5fa86tYUX3ozE1S+Txlds=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "1536926ef5621b09bba54035ae2bb6d806d72ac8",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"dir": "lib",
|
||||
"owner": "NixOS",
|
||||
"ref": "nixos-unstable",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nixpkgs_2": {
|
||||
"locked": {
|
||||
"lastModified": 1703637592,
|
||||
"narHash": "sha256-8MXjxU0RfFfzl57Zy3OfXCITS0qWDNLzlBAdwxGZwfY=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "cfc3698c31b1fb9cdcf10f36c9643460264d0ca8",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "NixOS",
|
||||
"ref": "nixos-unstable",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nixpkgs_3": {
|
||||
"locked": {
|
||||
"lastModified": 1709479366,
|
||||
"narHash": "sha256-n6F0n8UV6lnTZbYPl1A9q1BS0p4hduAv1mGAP17CVd0=",
|
||||
"owner": "nixos",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "b8697e57f10292a6165a20f03d2f42920dfaf973",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "nixos",
|
||||
"ref": "nixos-unstable",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"inputs": {
|
||||
"flake-parts": "flake-parts",
|
||||
"flatland": "flatland",
|
||||
"hercules-ci-effects": "hercules-ci-effects",
|
||||
"nixpkgs": "nixpkgs_3"
|
||||
}
|
||||
},
|
||||
"rust-analyzer-src": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1700077026,
|
||||
"narHash": "sha256-Vf7ykubXsriSjBbeYAm8bzBIvSOYVUmRiCQ3iLL/E+U=",
|
||||
"owner": "rust-lang",
|
||||
"repo": "rust-analyzer",
|
||||
"rev": "58de0b130a763f3a2d373f508ac0c18a8e7d0acd",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "rust-lang",
|
||||
"ref": "nightly",
|
||||
"repo": "rust-analyzer",
|
||||
"type": "github"
|
||||
}
|
||||
}
|
||||
},
|
||||
"root": "root",
|
||||
"version": 7
|
||||
}
|
||||
80
flake.nix
Normal file
80
flake.nix
Normal file
@@ -0,0 +1,80 @@
|
||||
{
|
||||
nixConfig = {
|
||||
extra-substituters = [ "https://stardustxr.cachix.org" ];
|
||||
extra-trusted-public-keys = [ "stardustxr.cachix.org-1:mWSn8Ap2RLsIWT/8gsj+VfbJB6xoOkPaZpbjO+r9HBo=" ];
|
||||
};
|
||||
inputs = {
|
||||
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
|
||||
flake-parts.url = "github:hercules-ci/flake-parts";
|
||||
hercules-ci-effects.url = "github:hercules-ci/hercules-ci-effects";
|
||||
|
||||
# Since we do not have a monorepo, we have to fetch Flatland in order to use
|
||||
# it to create VM Tests
|
||||
flatland.url = "github:StardustXR/flatland";
|
||||
};
|
||||
outputs = inputs@{ self, flake-parts, nixpkgs, hercules-ci-effects, flatland, ... }:
|
||||
let
|
||||
name = (builtins.fromTOML (builtins.readFile ./Cargo.toml)).package.name;
|
||||
src = builtins.path {
|
||||
name = "${name}-source";
|
||||
path = toString ./.;
|
||||
filter = path: type:
|
||||
nixpkgs.lib.all
|
||||
(n: builtins.baseNameOf path != n)
|
||||
[
|
||||
"flake.nix"
|
||||
"flake.lock"
|
||||
"nix"
|
||||
"README.md"
|
||||
];
|
||||
};
|
||||
in
|
||||
flake-parts.lib.mkFlake { inherit inputs; } {
|
||||
imports = [
|
||||
flake-parts.flakeModules.easyOverlay
|
||||
];
|
||||
systems = [ "aarch64-linux" "x86_64-linux" "riscv64-linux" ];
|
||||
perSystem = { config, self', inputs', pkgs, system, ... }: {
|
||||
_module.args.pkgs = import inputs.nixpkgs { inherit system; overlays = [ inputs.self.overlays.default ]; };
|
||||
overlayAttrs = config.packages;
|
||||
packages = {
|
||||
default = self'.packages.${name};
|
||||
gnome-graphical-test = self'.checks.gnome-graphical-test;
|
||||
"${name}" = pkgs.callPackage ./nix/stardust-xr-server.nix { inherit name src; };
|
||||
};
|
||||
checks.gnome-graphical-test = pkgs.nixosTest (import ./nix/gnome-graphical-test.nix { inherit pkgs self; });
|
||||
devShells.default = pkgs.mkShell {
|
||||
inputsFrom = [ self'.packages.default ];
|
||||
LIBCLANG_PATH = "${pkgs.libclang.lib}/lib";
|
||||
};
|
||||
};
|
||||
flake = {
|
||||
herculesCI.ciSystems = [ "x86_64-linux" ];
|
||||
effects = let
|
||||
pkgs = nixpkgs.legacyPackages.x86_64-linux;
|
||||
hci-effects = hercules-ci-effects.lib.withPkgs pkgs;
|
||||
in { ref, rev, ... }: {
|
||||
gnome-graphical-test = hci-effects.mkEffect {
|
||||
secretsMap."stardustxrDiscord" = "stardustxrDiscord";
|
||||
secretsMap."stardustxrIpfs" = "stardustxrIpfs";
|
||||
effectScript = ''
|
||||
readSecretString stardustxrDiscord .webhook > .webhook
|
||||
readSecretString stardustxrIpfs .basicauth > .basicauth
|
||||
set -x
|
||||
export RESPONSE=$(curl -H @.basicauth -F file=@${self.packages."x86_64-linux".gnome-graphical-test}/screen.png https://ipfs-api.stardustxr.org/api/v0/add)
|
||||
export CID=$(echo "$RESPONSE" | ${pkgs.jq}/bin/jq -r .Hash)
|
||||
set +x
|
||||
export ADDRESS="https://ipfs.stardustxr.org/ipfs/$CID"
|
||||
${pkgs.discord-sh}/bin/discord.sh \
|
||||
--description "\`stardustxr/server\` has been modified, here's how it renders \`weston-cliptest\` on \`flatland\` via \`monado-service\` inside of the \`gnome-graphical-test\`" \
|
||||
--field "Ref;${ref}" \
|
||||
--field "Commit ID;${rev}" \
|
||||
--field "Flatland Revision;${flatland.rev}" \
|
||||
--field "Reproducer;\`nix build github:stardustxr/server/${rev}#gnome-graphical-test\`" \
|
||||
--image "$ADDRESS"
|
||||
'';
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
BIN
img/flatscreen_1.png
Normal file
BIN
img/flatscreen_1.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 9.6 KiB |
BIN
img/flatscreen_2.png
Normal file
BIN
img/flatscreen_2.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
BIN
img/flatscreen_3.png
Normal file
BIN
img/flatscreen_3.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 789 KiB |
BIN
img/xr_mode_windowed_blank.png
Normal file
BIN
img/xr_mode_windowed_blank.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
155
nix/gnome-graphical-test.nix
Normal file
155
nix/gnome-graphical-test.nix
Normal file
@@ -0,0 +1,155 @@
|
||||
{ pkgs, lib ? pkgs.lib, self, ... }:
|
||||
# Some code is copy-pasted from https://github.com/NixOS/nixpkgs/blob/master/nixos/tests/gnome.nix
|
||||
# TODO: make this less boiler-platey and make a function like mkGnomeTest that does all this and upstream it to nixpkgs
|
||||
{
|
||||
name = "stardust-xr-server-gnome-vmtest";
|
||||
meta = with lib; {
|
||||
maintainers = [ maintainers.matthewcroughan ];
|
||||
};
|
||||
nodes.machine = { ... }: {
|
||||
imports = [ "${pkgs.path}/nixos/tests/common/user-account.nix" ];
|
||||
virtualisation.qemu.options = [
|
||||
"-device virtio-gpu-pci"
|
||||
];
|
||||
environment.systemPackages = [ pkgs.monado ];
|
||||
services.xserver = {
|
||||
enable = true;
|
||||
desktopManager.gnome = {
|
||||
enable = true;
|
||||
debug = true;
|
||||
# Set a nice desktop background that is pleasing to the eyes :3
|
||||
extraGSettingsOverrides = ''
|
||||
[org.gnome.desktop.background]
|
||||
picture-uri='file://${pkgs.gnome.gnome-backgrounds}/share/backgrounds/gnome/blobs-l.svg'
|
||||
picture-uri-dark='file://${pkgs.gnome.gnome-backgrounds}/share/backgrounds/gnome/blobs-l.svg'
|
||||
'';
|
||||
};
|
||||
displayManager = {
|
||||
gdm = {
|
||||
enable = true;
|
||||
debug = true;
|
||||
};
|
||||
autoLogin = {
|
||||
enable = true;
|
||||
user = "alice";
|
||||
};
|
||||
};
|
||||
};
|
||||
systemd.user.services = {
|
||||
"monado" = {
|
||||
after = [ "graphical-session.target" "default.target" "org.gnome.Shell@wayland.service" ];
|
||||
environment = {
|
||||
XRT_COMPOSITOR_FORCE_WAYLAND = "1";
|
||||
WAYLAND_DISPLAY = "wayland-0";
|
||||
};
|
||||
serviceConfig = {
|
||||
ExecStartPre = [
|
||||
"${pkgs.writeShellScript "sleep" ''
|
||||
sleep 3
|
||||
''}"
|
||||
];
|
||||
ExecStart = let
|
||||
# stdin disappears in NixOS test driver ( machine.succeed() ), requiring us to specify < /dev/ttyS0 to fake stdin
|
||||
exec-monado-service = pkgs.writeShellScript "exec-monado-service" "${pkgs.monado}/bin/monado-service < /dev/ttyS0";
|
||||
in [
|
||||
"${exec-monado-service}"
|
||||
];
|
||||
};
|
||||
};
|
||||
"stardust-xr-server" = {
|
||||
after = [ "monado.service" ];
|
||||
serviceConfig = {
|
||||
Type = "notify";
|
||||
NotifyAccess = "all";
|
||||
ExecStartPre = [
|
||||
"${pkgs.writeShellScript "sleep" ''
|
||||
sleep 3
|
||||
''}"
|
||||
];
|
||||
ExecStart = let
|
||||
notifyReady = pkgs.writeShellScript "notifyReady" "systemd-notify --ready";
|
||||
exec-stardust-xr-server = pkgs.writeShellScript "exec-stardust-xr-server" "${self.packages.${pkgs.hostPlatform.system}.default}/bin/stardust-xr-server -e ${notifyReady}";
|
||||
in [
|
||||
"${exec-stardust-xr-server}"
|
||||
];
|
||||
};
|
||||
};
|
||||
"weston-cliptest" = {
|
||||
after = [ "flatland.service" ];
|
||||
environment.WAYLAND_DISPLAY = "wayland-1";
|
||||
serviceConfig = {
|
||||
ExecStart = [
|
||||
"${pkgs.weston}/bin/weston-cliptest"
|
||||
];
|
||||
};
|
||||
};
|
||||
"flatland" = {
|
||||
after = [ "stardust-xr-server.service" ];
|
||||
serviceConfig = {
|
||||
ExecStart = [
|
||||
"${self.inputs.flatland.packages.${pkgs.hostPlatform.system}.default}/bin/flatland"
|
||||
];
|
||||
};
|
||||
};
|
||||
"org.gnome.Shell@wayland" = {
|
||||
wants = [ "monado.service" "stardust-xr-server.service" "flatland.service" "weston-cliptest.service" ];
|
||||
serviceConfig = {
|
||||
ExecStart = [
|
||||
# Clear the list before overriding it.
|
||||
""
|
||||
# Eval API is now internal so Shell needs to run in unsafe mode.
|
||||
# TODO: improve test driver so that it supports openqa-like manipulation
|
||||
# that would allow us to drop this mess.
|
||||
"${pkgs.gnome.gnome-shell}/bin/gnome-shell --unsafe-mode"
|
||||
];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
testScript = { nodes, ... }: let
|
||||
# Keep line widths somewhat managable
|
||||
user = nodes.machine.config.users.users.alice;
|
||||
uid = toString user.uid;
|
||||
bus = "DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/${uid}/bus";
|
||||
gdbus = "${bus} gdbus";
|
||||
su = command: "su ${user.name} -c '${command}'";
|
||||
|
||||
# Call javascript in gnome shell, returns a tuple (success, output), where
|
||||
# `success` is true if the dbus call was successful and output is what the
|
||||
# javascript evaluates to.
|
||||
eval = "call --session -d org.gnome.Shell -o /org/gnome/Shell -m org.gnome.Shell.Eval";
|
||||
|
||||
# False when startup is done
|
||||
startingUp = su "${gdbus} ${eval} Main.layoutManager._startingUp";
|
||||
in ''
|
||||
with subtest("Login to GNOME with GDM"):
|
||||
# wait for gdm to start
|
||||
machine.wait_for_unit("display-manager.service")
|
||||
# wait for the wayland server
|
||||
machine.wait_for_file("/run/user/${uid}/wayland-0")
|
||||
# wait for alice to be logged in
|
||||
machine.wait_for_unit("default.target", "${user.name}")
|
||||
# check that logging in has given the user ownership of devices
|
||||
assert "alice" in machine.succeed("getfacl -p /dev/snd/timer")
|
||||
|
||||
with subtest("Wait for GNOME Shell"):
|
||||
# correct output should be (true, 'false')
|
||||
machine.wait_until_succeeds(
|
||||
"${startingUp} | grep -q 'true,..false'"
|
||||
)
|
||||
|
||||
# To allow monado-service to use < /dev/ttyS0
|
||||
machine.succeed("chown alice /dev/ttyS0")
|
||||
|
||||
with subtest("Open Monado and StardustXR"):
|
||||
# Close the Activities view so that Shell can correctly track the focused window.
|
||||
machine.send_key("esc")
|
||||
machine.wait_for_unit("monado.service", "${user.name}")
|
||||
machine.wait_for_unit("stardust-xr-server.service", "${user.name}")
|
||||
machine.wait_for_unit("flatland.service", "${user.name}")
|
||||
machine.wait_for_unit("weston-cliptest.service", "${user.name}")
|
||||
machine.sleep(3)
|
||||
machine.screenshot("screen")
|
||||
'';
|
||||
}
|
||||
40
nix/stardust-xr-server.nix
Normal file
40
nix/stardust-xr-server.nix
Normal file
@@ -0,0 +1,40 @@
|
||||
{ rustPlatform
|
||||
, src
|
||||
, name
|
||||
, openxr-loader
|
||||
, libGL
|
||||
, mesa
|
||||
, xorg
|
||||
, fontconfig
|
||||
, libxkbcommon
|
||||
, libclang
|
||||
, cmake
|
||||
, cpm-cmake
|
||||
, pkg-config
|
||||
, llvmPackages
|
||||
}:
|
||||
|
||||
rustPlatform.buildRustPackage rec {
|
||||
inherit src name;
|
||||
cargoLock = {
|
||||
lockFile = (src + "/Cargo.lock");
|
||||
allowBuiltinFetchGit = true;
|
||||
};
|
||||
CPM_SOURCE_CACHE = "./build";
|
||||
postPatch = ''
|
||||
sk=$(echo $cargoDepsCopy/stereokit-sys-*/StereoKit)
|
||||
mkdir -p $sk/build/cpm
|
||||
|
||||
# This is not ideal, the original approach was to fetch the exact cmake
|
||||
# file version that was wanted from GitHub directly, but at least this way it comes from Nixpkgs.. so meh
|
||||
cp ${cpm-cmake}/share/cpm/CPM.cmake $sk/build/cpm/CPM_0.32.2.cmake
|
||||
'';
|
||||
nativeBuildInputs = [
|
||||
cmake pkg-config llvmPackages.libcxxClang
|
||||
];
|
||||
buildInputs = [
|
||||
openxr-loader libGL mesa xorg.libX11 fontconfig libxkbcommon
|
||||
];
|
||||
LIBCLANG_PATH = "${libclang.lib}/lib";
|
||||
}
|
||||
|
||||
@@ -1,136 +1,247 @@
|
||||
use super::{eventloop::EventLoop, scenegraph::Scenegraph};
|
||||
use crate::{
|
||||
core::registry::Registry,
|
||||
nodes::{data, drawable, fields, hmd, input, items, root::Root, spatial, startup, Node},
|
||||
use super::{
|
||||
client_state::{ClientState, CLIENT_STATES},
|
||||
destroy_queue,
|
||||
scenegraph::Scenegraph,
|
||||
};
|
||||
use anyhow::{anyhow, Result};
|
||||
use crate::{
|
||||
core::{registry::OwnedRegistry, task},
|
||||
nodes::{audio, data, drawable, fields, hmd, input, items, root::Root, spatial, Node},
|
||||
};
|
||||
use color_eyre::eyre::{eyre, Result};
|
||||
use lazy_static::lazy_static;
|
||||
use once_cell::sync::OnceCell;
|
||||
use parking_lot::Mutex;
|
||||
use stardust_xr::messenger::Messenger;
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
sync::{Arc, Weak},
|
||||
use rustc_hash::FxHashMap;
|
||||
use stardust_xr::{
|
||||
messenger::{self, MessageSenderHandle},
|
||||
schemas::flex::serialize,
|
||||
};
|
||||
use tokio::{net::UnixStream, sync::Notify, task::JoinHandle};
|
||||
use std::{fmt::Debug, fs, iter::FromIterator, path::PathBuf, sync::Arc};
|
||||
use tokio::{net::UnixStream, task::JoinHandle};
|
||||
use tracing::info;
|
||||
|
||||
lazy_static! {
|
||||
pub static ref CLIENTS: Registry<Client> = Registry::new();
|
||||
pub static ref CLIENTS: OwnedRegistry<Client> = OwnedRegistry::new();
|
||||
pub static ref INTERNAL_CLIENT: Arc<Client> = CLIENTS.add(Client {
|
||||
event_loop: Weak::new(),
|
||||
index: 0,
|
||||
pid: None,
|
||||
// env: None,
|
||||
exe: None,
|
||||
|
||||
stop_notifier: Default::default(),
|
||||
join_handle: OnceCell::new(),
|
||||
dispatch_join_handle: OnceCell::new(),
|
||||
flush_join_handle: OnceCell::new(),
|
||||
disconnect_status: OnceCell::new(),
|
||||
|
||||
messenger: None,
|
||||
message_sender_handle: None,
|
||||
scenegraph: Default::default(),
|
||||
root: OnceCell::new(),
|
||||
base_resource_prefixes: Default::default(),
|
||||
state: Arc::new(ClientState::default()),
|
||||
});
|
||||
}
|
||||
|
||||
pub struct Client {
|
||||
event_loop: Weak<EventLoop>,
|
||||
index: usize,
|
||||
stop_notifier: Arc<Notify>,
|
||||
join_handle: OnceCell<JoinHandle<Result<()>>>,
|
||||
pub fn get_env(pid: i32) -> Result<FxHashMap<String, String>, std::io::Error> {
|
||||
let env = fs::read_to_string(format!("/proc/{pid}/environ"))?;
|
||||
Ok(FxHashMap::from_iter(
|
||||
env.split('\0')
|
||||
.filter_map(|var| var.split_once('='))
|
||||
.map(|(k, v)| (k.to_string(), v.to_string())),
|
||||
))
|
||||
}
|
||||
pub fn state(env: &FxHashMap<String, String>) -> Option<Arc<ClientState>> {
|
||||
let token = env.get("STARDUST_STARTUP_TOKEN")?;
|
||||
CLIENT_STATES.lock().get(token).cloned()
|
||||
}
|
||||
|
||||
pub messenger: Option<Messenger>,
|
||||
pub scenegraph: Scenegraph,
|
||||
pub struct Client {
|
||||
pub pid: Option<i32>,
|
||||
// env: Option<FxHashMap<String, String>>,
|
||||
exe: Option<PathBuf>,
|
||||
dispatch_join_handle: OnceCell<JoinHandle<Result<()>>>,
|
||||
flush_join_handle: OnceCell<JoinHandle<Result<()>>>,
|
||||
disconnect_status: OnceCell<Result<()>>,
|
||||
|
||||
pub message_sender_handle: Option<MessageSenderHandle>,
|
||||
pub scenegraph: Arc<Scenegraph>,
|
||||
pub root: OnceCell<Arc<Root>>,
|
||||
pub base_resource_prefixes: Mutex<Vec<PathBuf>>,
|
||||
pub state: Arc<ClientState>,
|
||||
}
|
||||
impl Client {
|
||||
pub fn from_connection(
|
||||
index: usize,
|
||||
event_loop: &Arc<EventLoop>,
|
||||
connection: UnixStream,
|
||||
) -> Arc<Self> {
|
||||
println!("New client connected");
|
||||
let client = CLIENTS.add(Client {
|
||||
event_loop: Arc::downgrade(event_loop),
|
||||
index,
|
||||
stop_notifier: Default::default(),
|
||||
join_handle: OnceCell::new(),
|
||||
pub fn from_connection(connection: UnixStream) -> Result<Arc<Self>> {
|
||||
let pid = connection.peer_cred().ok().and_then(|c| c.pid());
|
||||
let env = pid.and_then(|pid| get_env(pid).ok());
|
||||
let exe = pid.and_then(|pid| fs::read_link(format!("/proc/{}/exe", pid)).ok());
|
||||
info!(
|
||||
pid,
|
||||
exe = exe
|
||||
.as_ref()
|
||||
.and_then(|exe| exe.to_str().map(|s| s.to_string())),
|
||||
"New client connected"
|
||||
);
|
||||
|
||||
messenger: Some(Messenger::new(
|
||||
tokio::runtime::Handle::current(),
|
||||
connection,
|
||||
)),
|
||||
scenegraph: Default::default(),
|
||||
let (mut messenger_tx, mut messenger_rx) = messenger::create(connection);
|
||||
let scenegraph = Arc::new(Scenegraph::default());
|
||||
let state = env
|
||||
.as_ref()
|
||||
.and_then(state)
|
||||
.unwrap_or_else(|| Arc::new(ClientState::default()));
|
||||
|
||||
let client = CLIENTS.add(Client {
|
||||
pid,
|
||||
// env,
|
||||
exe: exe.clone(),
|
||||
|
||||
dispatch_join_handle: OnceCell::new(),
|
||||
flush_join_handle: OnceCell::new(),
|
||||
disconnect_status: OnceCell::new(),
|
||||
|
||||
message_sender_handle: Some(messenger_tx.handle()),
|
||||
scenegraph: scenegraph.clone(),
|
||||
root: OnceCell::new(),
|
||||
base_resource_prefixes: Default::default(),
|
||||
state,
|
||||
});
|
||||
let _ = client.scenegraph.client.set(Arc::downgrade(&client));
|
||||
let _ = client.root.set(Root::create(&client));
|
||||
hmd::make_alias(&client);
|
||||
spatial::create_interface(&client);
|
||||
fields::create_interface(&client);
|
||||
drawable::create_interface(&client);
|
||||
data::create_interface(&client);
|
||||
items::create_interface(&client);
|
||||
input::create_interface(&client);
|
||||
startup::create_interface(&client);
|
||||
let _ = client.root.set(Root::create(&client)?);
|
||||
hmd::make_alias(&client)?;
|
||||
spatial::create_interface(&client)?;
|
||||
fields::create_interface(&client)?;
|
||||
drawable::create_interface(&client)?;
|
||||
audio::create_interface(&client)?;
|
||||
data::create_interface(&client)?;
|
||||
items::create_interface(&client)?;
|
||||
input::create_interface(&client)?;
|
||||
|
||||
let _ = client.join_handle.set(tokio::spawn({
|
||||
let client = client.clone();
|
||||
async move {
|
||||
let dispatch_loop = async {
|
||||
loop {
|
||||
client.dispatch().await?
|
||||
}
|
||||
};
|
||||
let flush_loop = async {
|
||||
loop {
|
||||
client.flush().await?
|
||||
}
|
||||
};
|
||||
|
||||
let result = tokio::select! {
|
||||
_ = client.stop_notifier.notified() => Ok(()),
|
||||
e = dispatch_loop => e,
|
||||
e = flush_loop => e,
|
||||
};
|
||||
client.disconnect().await;
|
||||
result
|
||||
}
|
||||
}));
|
||||
client
|
||||
.root
|
||||
.get()
|
||||
.unwrap()
|
||||
.node
|
||||
.send_remote_signal("restore_state", serialize(client.state.apply_to(&client))?)?;
|
||||
|
||||
let pid_printable = pid
|
||||
.map(|pid| pid.to_string())
|
||||
.unwrap_or_else(|| "??".to_string());
|
||||
let exe_printable = exe
|
||||
.and_then(|exe| {
|
||||
exe.file_name()
|
||||
.and_then(|exe| exe.to_str())
|
||||
.map(|exe| exe.to_string())
|
||||
})
|
||||
.unwrap_or_else(|| "??".to_string());
|
||||
let _ = client.dispatch_join_handle.get_or_try_init(|| {
|
||||
task::new(
|
||||
|| {
|
||||
format!(
|
||||
"client dispatch pid={} exe={}",
|
||||
&pid_printable, &exe_printable,
|
||||
)
|
||||
},
|
||||
{
|
||||
let client = client.clone();
|
||||
async move {
|
||||
loop {
|
||||
match messenger_rx.dispatch(&*scenegraph).await {
|
||||
Err(e) => {
|
||||
client.disconnect(Err(e.into()));
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
});
|
||||
let _ = client.flush_join_handle.get_or_try_init(|| {
|
||||
task::new(
|
||||
|| format!("client flush pid={} exe={}", &pid_printable, &exe_printable,),
|
||||
{
|
||||
let client = client.clone();
|
||||
async move {
|
||||
loop {
|
||||
match messenger_tx.flush().await {
|
||||
Err(e) => {
|
||||
client.disconnect(Err(e.into()));
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
});
|
||||
|
||||
Ok(client)
|
||||
}
|
||||
|
||||
pub fn get_cmdline(&self) -> Option<Vec<String>> {
|
||||
let pid = self.pid?;
|
||||
let exe_proc_path = format!("/proc/{pid}/exe");
|
||||
let cmdline_proc_path = format!("/proc/{pid}/cmdline");
|
||||
let exe = std::fs::read_link(exe_proc_path).ok()?;
|
||||
let cmdline = std::fs::read_to_string(cmdline_proc_path).ok()?;
|
||||
let mut cmdline_split: Vec<_> = cmdline.split('\0').map(ToString::to_string).collect();
|
||||
cmdline_split.pop();
|
||||
*cmdline_split.get_mut(0).unwrap() = exe.to_str()?.to_string();
|
||||
Some(cmdline_split)
|
||||
}
|
||||
pub fn get_cwd(&self) -> Option<PathBuf> {
|
||||
let pid = self.pid?;
|
||||
let cwd_proc_path = format!("/proc/{pid}/cwd");
|
||||
std::fs::read_link(cwd_proc_path).ok()
|
||||
}
|
||||
pub async fn save_state(&self) -> Option<ClientState> {
|
||||
let internal = self.root.get()?.save_state().await.ok()?;
|
||||
Some(ClientState::from_deserialized(self, internal))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get_node(&self, name: &'static str, path: &str) -> Result<Arc<Node>> {
|
||||
self.scenegraph
|
||||
.get_node(path)
|
||||
.ok_or_else(|| anyhow!("{} not found", name))
|
||||
.ok_or_else(|| eyre!("{} not found", name))
|
||||
}
|
||||
|
||||
pub async fn dispatch(&self) -> Result<(), std::io::Error> {
|
||||
match &self.messenger {
|
||||
Some(messenger) => messenger.dispatch(&self.scenegraph).await,
|
||||
None => Err(std::io::Error::from(std::io::ErrorKind::Unsupported)),
|
||||
pub fn disconnect(&self, reason: Result<()>) {
|
||||
let _ = self.disconnect_status.set(reason);
|
||||
if let Some(dispatch_join_handle) = self.dispatch_join_handle.get() {
|
||||
dispatch_join_handle.abort();
|
||||
}
|
||||
if let Some(flush_join_handle) = self.flush_join_handle.get() {
|
||||
flush_join_handle.abort();
|
||||
}
|
||||
if let Some(client) = CLIENTS.remove(self) {
|
||||
destroy_queue::add(client);
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn flush(&self) -> Result<(), std::io::Error> {
|
||||
match &self.messenger {
|
||||
Some(messenger) => messenger.flush().await,
|
||||
None => Err(std::io::Error::from(std::io::ErrorKind::Unsupported)),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn disconnect(&self) {
|
||||
self.stop_notifier.notify_one();
|
||||
if let Some(event_loop) = self.event_loop.upgrade() {
|
||||
event_loop.clients.lock().await.remove(self.index);
|
||||
}
|
||||
}
|
||||
impl Debug for Client {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Client")
|
||||
.field("pid", &self.pid)
|
||||
.field("exe", &self.exe)
|
||||
.field("dispatch_join_handle", &self.dispatch_join_handle)
|
||||
.field("flush_join_handle", &self.flush_join_handle)
|
||||
.field("disconnect_status", &self.disconnect_status)
|
||||
.field("base_resource_prefixes", &self.base_resource_prefixes)
|
||||
.field("state", &self.state)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
impl Drop for Client {
|
||||
fn drop(&mut self) {
|
||||
self.stop_notifier.notify_one();
|
||||
CLIENTS.remove(self);
|
||||
println!("Client disconnected");
|
||||
info!(
|
||||
pid = self.pid,
|
||||
exe = self
|
||||
.exe
|
||||
.as_ref()
|
||||
.and_then(|exe| exe.to_str().map(|s| s.to_string())),
|
||||
disconnect_status = match self.disconnect_status.take() {
|
||||
Some(Ok(_)) => "Graceful disconnect".to_string(),
|
||||
Some(Err(e)) => format!("Error: {}", e.root_cause()),
|
||||
None => "Unknown".to_string(),
|
||||
},
|
||||
"Client disconnected"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
131
src/core/client_state.rs
Normal file
131
src/core/client_state.rs
Normal file
@@ -0,0 +1,131 @@
|
||||
use super::client::{get_env, Client};
|
||||
use crate::nodes::{spatial::Spatial, Node};
|
||||
use glam::Mat4;
|
||||
use parking_lot::Mutex;
|
||||
use rustc_hash::FxHashMap;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
pub static ref CLIENT_STATES: Mutex<FxHashMap<String, Arc<ClientState>>> = Default::default();
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct LaunchInfo {
|
||||
pub cmdline: Vec<String>,
|
||||
pub cwd: PathBuf,
|
||||
pub env: FxHashMap<String, String>,
|
||||
}
|
||||
impl LaunchInfo {
|
||||
fn from_client(client: &Client) -> Option<Self> {
|
||||
Some(LaunchInfo {
|
||||
cmdline: client.get_cmdline()?,
|
||||
cwd: client.get_cwd()?,
|
||||
env: get_env(client.pid?).ok()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct ClientState {
|
||||
pub launch_info: Option<LaunchInfo>,
|
||||
pub data: Vec<u8>,
|
||||
pub root: Mat4,
|
||||
pub spatial_anchors: FxHashMap<String, Mat4>,
|
||||
}
|
||||
impl ClientState {
|
||||
pub fn from_deserialized(client: &Client, state: ClientStateInternal) -> Self {
|
||||
ClientState {
|
||||
launch_info: LaunchInfo::from_client(client),
|
||||
data: state.data.unwrap_or_default(),
|
||||
root: Self::spatial_transform(client, &state.root.unwrap_or_default())
|
||||
.unwrap_or_default(),
|
||||
spatial_anchors: state
|
||||
.spatial_anchors
|
||||
.into_iter()
|
||||
.filter_map(|(k, v)| Some((k, Self::spatial_transform(client, &v)?)))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
fn spatial_transform(client: &Client, path: &str) -> Option<Mat4> {
|
||||
let node = client.scenegraph.get_node(path)?;
|
||||
let spatial = node.get_aspect::<Spatial>().ok()?;
|
||||
Some(spatial.global_transform())
|
||||
}
|
||||
|
||||
pub fn token(self) -> String {
|
||||
let token = nanoid::nanoid!();
|
||||
CLIENT_STATES.lock().insert(token.clone(), Arc::new(self));
|
||||
token
|
||||
}
|
||||
pub fn from_file(file: &Path) -> Option<Self> {
|
||||
let file_string = std::fs::read_to_string(file).ok()?;
|
||||
toml::from_str(&file_string).ok()
|
||||
}
|
||||
pub fn to_file(self, directory: &Path) {
|
||||
let app_name = self
|
||||
.launch_info
|
||||
.as_ref()
|
||||
.map(|l| l.cmdline.get(0).unwrap().split('/').last().unwrap())
|
||||
.unwrap_or("unknown");
|
||||
let state_file_path = directory
|
||||
.join(format!("{app_name}-{}", nanoid::nanoid!()))
|
||||
.with_extension("toml");
|
||||
|
||||
std::fs::write(state_file_path, toml::to_string(&self).unwrap()).unwrap();
|
||||
}
|
||||
|
||||
pub fn apply_to(&self, client: &Arc<Client>) -> ClientStateInternal {
|
||||
if let Some(root) = client.root.get() {
|
||||
root.set_transform(self.root)
|
||||
}
|
||||
ClientStateInternal {
|
||||
data: Some(self.data.clone()),
|
||||
root: Some("/".to_string()),
|
||||
spatial_anchors: self
|
||||
.spatial_anchors
|
||||
.iter()
|
||||
.map(|(k, v)| {
|
||||
(k.clone(), {
|
||||
let node = Node::create_parent_name(client, "/spatial/anchor", k, true)
|
||||
.add_to_scenegraph()
|
||||
.unwrap();
|
||||
Spatial::add_to(&node, None, *v, false);
|
||||
k.clone()
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
pub fn launch_command(self) -> Option<Command> {
|
||||
let launch_info = self.launch_info.as_ref()?;
|
||||
let mut cmdline = launch_info.cmdline.iter();
|
||||
let mut command = Command::new(cmdline.next()?);
|
||||
command.args(cmdline);
|
||||
command.current_dir(&launch_info.cwd);
|
||||
command.envs(launch_info.env.iter());
|
||||
command.env("STARDUST_STARTUP_TOKEN", self.token());
|
||||
Some(command)
|
||||
}
|
||||
}
|
||||
impl Default for ClientState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
launch_info: None,
|
||||
data: Default::default(),
|
||||
root: Mat4::IDENTITY,
|
||||
spatial_anchors: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Serialize, Deserialize)]
|
||||
pub struct ClientStateInternal {
|
||||
data: Option<Vec<u8>>,
|
||||
root: Option<String>,
|
||||
spatial_anchors: FxHashMap<String, String>,
|
||||
}
|
||||
47
src/core/delta.rs
Normal file
47
src/core/delta.rs
Normal file
@@ -0,0 +1,47 @@
|
||||
use std::ops::{Deref, DerefMut};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Delta<T> {
|
||||
value: T,
|
||||
changed: bool,
|
||||
}
|
||||
#[allow(dead_code)]
|
||||
impl<T> Delta<T> {
|
||||
pub const fn new(value: T) -> Self {
|
||||
Delta {
|
||||
value,
|
||||
changed: false,
|
||||
}
|
||||
}
|
||||
pub fn peek_delta(&self) -> Option<&T> {
|
||||
self.changed.then_some(&self.value)
|
||||
}
|
||||
pub fn delta(&mut self) -> Option<&mut T> {
|
||||
let delta = self.changed.then_some(&mut self.value);
|
||||
self.changed = false;
|
||||
delta
|
||||
}
|
||||
pub fn mark_changed(&mut self) {
|
||||
self.changed = true;
|
||||
}
|
||||
pub const fn value(&self) -> &T {
|
||||
&self.value
|
||||
}
|
||||
pub fn value_mut(&mut self) -> &mut T {
|
||||
self.mark_changed();
|
||||
&mut self.value
|
||||
}
|
||||
}
|
||||
impl<T> Deref for Delta<T> {
|
||||
type Target = T;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.value
|
||||
}
|
||||
}
|
||||
impl<T> DerefMut for Delta<T> {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
self.mark_changed();
|
||||
&mut self.value
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,22 @@
|
||||
use once_cell::sync::Lazy;
|
||||
use parking_lot::Mutex;
|
||||
use std::any::Any;
|
||||
use tokio::sync::mpsc::{self, unbounded_channel};
|
||||
|
||||
static MAIN_DESTROY_QUEUE: Mutex<Vec<Box<dyn Any + Send + Sync>>> = Mutex::new(Vec::new());
|
||||
static MAIN_DESTROY_QUEUE: Lazy<(
|
||||
mpsc::UnboundedSender<Box<dyn Any + Send + Sync>>,
|
||||
Mutex<mpsc::UnboundedReceiver<Box<dyn Any + Send + Sync>>>,
|
||||
)> = Lazy::new(|| {
|
||||
let (tx, rx) = unbounded_channel();
|
||||
(tx, Mutex::new(rx))
|
||||
});
|
||||
|
||||
pub fn add<T: Any + Sync + Send>(thing: T) {
|
||||
MAIN_DESTROY_QUEUE.lock().push(Box::new(thing));
|
||||
MAIN_DESTROY_QUEUE.0.send(Box::new(thing)).unwrap();
|
||||
}
|
||||
|
||||
pub fn clear() {
|
||||
MAIN_DESTROY_QUEUE.lock().clear();
|
||||
while let Ok(thing) = MAIN_DESTROY_QUEUE.1.lock().try_recv() {
|
||||
drop(thing)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,61 +1,36 @@
|
||||
use super::client::Client;
|
||||
use anyhow::Result;
|
||||
use slab::Slab;
|
||||
use stardust_xr::server;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use super::task;
|
||||
use color_eyre::eyre::Result;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use tokio::net::UnixListener;
|
||||
use tokio::sync::{Mutex, Notify};
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
pub static FRAME: AtomicU64 = AtomicU64::new(0);
|
||||
use tracing::error;
|
||||
|
||||
pub struct EventLoop {
|
||||
pub socket_path: String,
|
||||
stop_notifier: Arc<Notify>,
|
||||
pub clients: Mutex<Slab<Arc<Client>>>,
|
||||
join_handle: JoinHandle<()>,
|
||||
}
|
||||
|
||||
impl EventLoop {
|
||||
pub fn new() -> Result<(Arc<Self>, JoinHandle<Result<()>>)> {
|
||||
let socket_path = server::get_free_socket_path()
|
||||
.ok_or_else(|| std::io::Error::from(std::io::ErrorKind::Other))?;
|
||||
let socket = UnixListener::bind(socket_path.clone())?;
|
||||
pub fn new(socket_path: PathBuf) -> Result<Arc<Self>> {
|
||||
let socket = UnixListener::bind(socket_path)?;
|
||||
|
||||
let event_loop = Arc::new(EventLoop {
|
||||
socket_path,
|
||||
stop_notifier: Default::default(),
|
||||
clients: Mutex::new(Slab::new()),
|
||||
});
|
||||
|
||||
let event_loop_join_handle = tokio::spawn({
|
||||
let event_loop = event_loop.clone();
|
||||
async move { EventLoop::event_loop(socket, event_loop).await }
|
||||
});
|
||||
|
||||
Ok((event_loop, event_loop_join_handle))
|
||||
}
|
||||
|
||||
async fn event_loop(socket: UnixListener, event_loop: Arc<EventLoop>) -> Result<()> {
|
||||
let event_loop_async = async {
|
||||
let join_handle = task::new(|| "event loop", async move {
|
||||
loop {
|
||||
let (socket, _) = socket.accept().await?;
|
||||
let mut clients = event_loop.clients.lock().await;
|
||||
let vacant_client = clients.vacant_entry();
|
||||
let idx = vacant_client.key();
|
||||
vacant_client.insert(Client::from_connection(idx, &event_loop, socket));
|
||||
let Ok((socket, _)) = socket.accept().await else { continue };
|
||||
if let Err(e) = Client::from_connection(socket) {
|
||||
error!(?e, "Unable to create client from connection");
|
||||
}
|
||||
}
|
||||
};
|
||||
})?;
|
||||
let event_loop = Arc::new(EventLoop { join_handle });
|
||||
|
||||
tokio::select! {
|
||||
_ = event_loop.stop_notifier.notified() => Ok(()),
|
||||
e = event_loop_async => e,
|
||||
}
|
||||
Ok(event_loop)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for EventLoop {
|
||||
fn drop(&mut self) {
|
||||
self.stop_notifier.notify_one();
|
||||
self.join_handle.abort();
|
||||
}
|
||||
}
|
||||
|
||||
11
src/core/idl_utils.rs
Normal file
11
src/core/idl_utils.rs
Normal file
@@ -0,0 +1,11 @@
|
||||
#[macro_export]
|
||||
macro_rules! create_interface {
|
||||
($iface:ident, $aspect:ident, $path:expr) => {
|
||||
pub fn create_interface(client: &Arc<Client>) -> Result<()> {
|
||||
let node = Node::create_path(client, $path, false);
|
||||
<$iface as $aspect>::add_node_members(&node);
|
||||
node.add_to_scenegraph()?;
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,7 +1,11 @@
|
||||
pub mod client;
|
||||
pub mod client_state;
|
||||
pub mod delta;
|
||||
pub mod destroy_queue;
|
||||
pub mod eventloop;
|
||||
pub mod nodelist;
|
||||
pub mod idl_utils;
|
||||
pub mod node_collections;
|
||||
pub mod registry;
|
||||
pub mod resource;
|
||||
pub mod scenegraph;
|
||||
pub mod task;
|
||||
|
||||
83
src/core/node_collections.rs
Normal file
83
src/core/node_collections.rs
Normal file
@@ -0,0 +1,83 @@
|
||||
use crate::nodes::Node;
|
||||
use parking_lot::Mutex;
|
||||
use rustc_hash::FxHashMap;
|
||||
use std::{
|
||||
borrow::Borrow,
|
||||
hash::Hash,
|
||||
sync::{Arc, Weak},
|
||||
};
|
||||
|
||||
// #[derive(Default)]
|
||||
// pub struct LifeLinkedNodeList {
|
||||
// nodes: Mutex<Vec<Weak<Node>>>,
|
||||
// }
|
||||
// impl LifeLinkedNodeList {
|
||||
// pub fn add(&self, node: Weak<Node>) {
|
||||
// self.nodes.lock().push(node);
|
||||
// }
|
||||
// pub fn clear(&self) {
|
||||
// self.nodes
|
||||
// .lock()
|
||||
// .iter()
|
||||
// .filter_map(|node| node.upgrade())
|
||||
// .for_each(|node| {
|
||||
// node.destroy();
|
||||
// });
|
||||
// self.nodes.lock().clear();
|
||||
// }
|
||||
// }
|
||||
// impl Drop for LifeLinkedNodeList {
|
||||
// fn drop(&mut self) {
|
||||
// self.clear();
|
||||
// }
|
||||
// }
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
pub struct LifeLinkedNodeMap<K: Hash + Eq> {
|
||||
nodes: Mutex<FxHashMap<K, Weak<Node>>>,
|
||||
}
|
||||
#[allow(dead_code)]
|
||||
impl<K: Hash + Eq> LifeLinkedNodeMap<K> {
|
||||
pub fn add(&self, key: K, node: &Arc<Node>) {
|
||||
self.nodes.lock().insert(key, Arc::downgrade(node));
|
||||
}
|
||||
pub fn get<Q>(&self, key: &Q) -> Option<Arc<Node>>
|
||||
where
|
||||
Q: ?Sized,
|
||||
K: Borrow<Q>,
|
||||
Q: Hash + Eq,
|
||||
{
|
||||
self.nodes.lock().get(key).and_then(|n| n.upgrade())
|
||||
}
|
||||
pub fn nodes(&self) -> Vec<Arc<Node>> {
|
||||
self.nodes
|
||||
.lock()
|
||||
.values()
|
||||
.filter_map(|v| v.upgrade())
|
||||
.collect()
|
||||
}
|
||||
pub fn remove<Q>(&self, key: &Q) -> Option<Arc<Node>>
|
||||
where
|
||||
Q: ?Sized,
|
||||
K: Borrow<Q>,
|
||||
Q: Hash + Eq,
|
||||
{
|
||||
self.nodes.lock().remove(key).and_then(|n| n.upgrade())
|
||||
}
|
||||
|
||||
pub fn clear(&self) {
|
||||
let mut nodes = self.nodes.lock();
|
||||
nodes
|
||||
.values()
|
||||
.filter_map(|node| node.upgrade())
|
||||
.for_each(|node| {
|
||||
node.destroy();
|
||||
});
|
||||
nodes.clear();
|
||||
}
|
||||
}
|
||||
impl<K: Hash + Eq> Drop for LifeLinkedNodeMap<K> {
|
||||
fn drop(&mut self) {
|
||||
self.clear();
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
use crate::nodes::Node;
|
||||
use parking_lot::Mutex;
|
||||
use std::sync::Weak;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct LifeLinkedNodeList {
|
||||
nodes: Mutex<Vec<Weak<Node>>>,
|
||||
}
|
||||
impl LifeLinkedNodeList {
|
||||
pub fn add(&self, node: Weak<Node>) {
|
||||
self.nodes.lock().push(node);
|
||||
}
|
||||
|
||||
pub fn clear(&self) {
|
||||
self.nodes
|
||||
.lock()
|
||||
.iter()
|
||||
.filter_map(|node| node.upgrade())
|
||||
.for_each(|node| {
|
||||
node.destroy();
|
||||
});
|
||||
self.nodes.lock().clear();
|
||||
}
|
||||
}
|
||||
impl Drop for LifeLinkedNodeList {
|
||||
fn drop(&mut self) {
|
||||
self.clear();
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,21 @@
|
||||
#![allow(dead_code)]
|
||||
|
||||
use parking_lot::{const_mutex, MappedMutexGuard, Mutex, MutexGuard};
|
||||
use rustc_hash::FxHashMap;
|
||||
use std::ptr;
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use once_cell::sync::Lazy;
|
||||
use parking_lot::Mutex;
|
||||
use rustc_hash::FxHashMap;
|
||||
|
||||
pub struct Registry<T: Send + Sync + ?Sized>(Lazy<Mutex<FxHashMap<usize, Weak<T>>>>);
|
||||
#[derive(Debug)]
|
||||
pub struct Registry<T: Send + Sync + ?Sized>(Mutex<Option<FxHashMap<usize, Weak<T>>>>);
|
||||
|
||||
impl<T: Send + Sync + ?Sized> Registry<T> {
|
||||
pub const fn new() -> Self {
|
||||
Registry(Lazy::new(|| Mutex::new(FxHashMap::default())))
|
||||
Registry(const_mutex(None))
|
||||
}
|
||||
fn lock(&self) -> MappedMutexGuard<FxHashMap<usize, Weak<T>>> {
|
||||
MutexGuard::map(self.0.lock(), |r| {
|
||||
r.get_or_insert_with(|| FxHashMap::default())
|
||||
})
|
||||
}
|
||||
pub fn add(&self, t: T) -> Arc<T>
|
||||
where
|
||||
@@ -22,23 +26,99 @@ impl<T: Send + Sync + ?Sized> Registry<T> {
|
||||
t_arc
|
||||
}
|
||||
pub fn add_raw(&self, t: &Arc<T>) {
|
||||
self.0
|
||||
.lock()
|
||||
self.lock()
|
||||
.insert(Arc::as_ptr(t) as *const () as usize, Arc::downgrade(t));
|
||||
}
|
||||
pub fn contains(&self, t: &T) -> bool {
|
||||
self.lock()
|
||||
.contains_key(&(ptr::addr_of!(*t) as *const () as usize))
|
||||
}
|
||||
pub fn get_valid_contents(&self) -> Vec<Arc<T>> {
|
||||
self.0
|
||||
.lock()
|
||||
self.lock()
|
||||
.iter()
|
||||
.filter_map(|pair| pair.1.upgrade())
|
||||
.collect()
|
||||
}
|
||||
pub fn remove(&self, t: &T) {
|
||||
pub fn take_valid_contents(&self) -> Vec<Arc<T>> {
|
||||
self.0
|
||||
.lock()
|
||||
.take()
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter_map(|pair| pair.1.upgrade())
|
||||
.collect()
|
||||
}
|
||||
pub fn remove(&self, t: &T) {
|
||||
self.lock()
|
||||
.remove(&(ptr::addr_of!(*t) as *const () as usize));
|
||||
}
|
||||
pub fn clear(&self) {
|
||||
self.0.lock().clear();
|
||||
self.lock().clear();
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
let registry = self.0.lock();
|
||||
let Some(registry) = &*registry else {
|
||||
return true;
|
||||
};
|
||||
if registry.is_empty() {
|
||||
return true;
|
||||
}
|
||||
registry.values().all(|v| v.strong_count() == 0)
|
||||
}
|
||||
}
|
||||
impl<T: Send + Sync + ?Sized> Clone for Registry<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self(Mutex::new(self.0.lock().clone()))
|
||||
}
|
||||
}
|
||||
impl<T: Send + Sync + ?Sized> Default for Registry<T> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct OwnedRegistry<T: Send + Sync + ?Sized>(Mutex<Option<FxHashMap<usize, Arc<T>>>>);
|
||||
|
||||
impl<T: Send + Sync + ?Sized> OwnedRegistry<T> {
|
||||
pub const fn new() -> Self {
|
||||
OwnedRegistry(const_mutex(None))
|
||||
}
|
||||
fn lock(&self) -> MappedMutexGuard<FxHashMap<usize, Arc<T>>> {
|
||||
MutexGuard::map(self.0.lock(), |r| {
|
||||
r.get_or_insert_with(|| FxHashMap::default())
|
||||
})
|
||||
}
|
||||
pub fn add(&self, t: T) -> Arc<T>
|
||||
where
|
||||
T: Sized,
|
||||
{
|
||||
let t_arc = Arc::new(t);
|
||||
self.add_raw(t_arc.clone());
|
||||
t_arc
|
||||
}
|
||||
pub fn add_raw(&self, t: Arc<T>) {
|
||||
self.lock().insert(Arc::as_ptr(&t) as *const () as usize, t);
|
||||
}
|
||||
pub fn get_vec(&self) -> Vec<Arc<T>> {
|
||||
self.lock().values().cloned().collect::<Vec<_>>()
|
||||
}
|
||||
pub fn contains(&self, t: &T) -> bool {
|
||||
self.lock()
|
||||
.contains_key(&(ptr::addr_of!(*t) as *const () as usize))
|
||||
}
|
||||
pub fn remove(&self, t: &T) -> Option<Arc<T>>
|
||||
where
|
||||
T: Sized,
|
||||
{
|
||||
self.lock()
|
||||
.remove(&(ptr::addr_of!(*t) as *const () as usize))
|
||||
}
|
||||
pub fn clear(&self) {
|
||||
self.lock().clear();
|
||||
}
|
||||
}
|
||||
impl<T: Send + Sync + ?Sized> Clone for OwnedRegistry<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self(Mutex::new(self.0.lock().clone()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,71 +1,46 @@
|
||||
use anyhow::anyhow;
|
||||
use serde::{de::Visitor, Deserialize};
|
||||
use std::path::PathBuf;
|
||||
use stardust_xr::values::ResourceID;
|
||||
use std::{ffi::OsStr, path::PathBuf};
|
||||
|
||||
pub enum ResourceID {
|
||||
File(PathBuf),
|
||||
Namespaced { namespace: String, path: PathBuf },
|
||||
use super::client::Client;
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
static ref THEMES: Vec<PathBuf> = std::env::var("STARDUST_THEMES").map(|s| s.split(":").map(PathBuf::from).collect()).unwrap_or_default();
|
||||
}
|
||||
impl ResourceID {
|
||||
pub fn get_file(&self, prefixes: &[PathBuf]) -> Option<PathBuf> {
|
||||
match self {
|
||||
ResourceID::File(file) => (file.is_absolute() && file.exists()).then_some(file.clone()),
|
||||
ResourceID::Namespaced { namespace, path } => {
|
||||
for prefix in prefixes {
|
||||
let mut test_path = prefix.clone();
|
||||
test_path.push(namespace.clone());
|
||||
test_path.push(path.clone());
|
||||
|
||||
if test_path.as_path().exists() {
|
||||
return Some(test_path);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
fn has_extension(path: &PathBuf, extensions: &[&OsStr]) -> bool {
|
||||
if let Some(path_extension) = path.extension() {
|
||||
extensions.contains(&path_extension)
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_resource_file(
|
||||
resource: &ResourceID,
|
||||
client: &Client,
|
||||
extensions: &[&OsStr],
|
||||
) -> Option<PathBuf> {
|
||||
match resource {
|
||||
ResourceID::Direct(file) => {
|
||||
(file.is_absolute() && file.exists() && has_extension(file, extensions))
|
||||
.then_some(file.clone())
|
||||
}
|
||||
ResourceID::Namespaced { namespace, path } => {
|
||||
let file_name = path.file_name()?;
|
||||
let base_prefixes = client.base_resource_prefixes.lock().clone();
|
||||
THEMES
|
||||
.iter()
|
||||
.chain(base_prefixes.iter())
|
||||
.filter_map(|prefix| {
|
||||
let prefixed_path = prefix.clone().join(namespace).join(path);
|
||||
let parent = prefixed_path.parent()?;
|
||||
std::fs::read_dir(parent).ok()
|
||||
})
|
||||
.flatten()
|
||||
.filter_map(|item| item.ok())
|
||||
.map(|dir_entry| dir_entry.path())
|
||||
.filter(|path| path.file_stem() == Some(file_name))
|
||||
.find(|path| has_extension(path, extensions))
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<'de> Deserialize<'de> for ResourceID {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
deserializer.deserialize_any(ResourceVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
struct ResourceVisitor;
|
||||
impl<'de> Visitor<'de> for ResourceVisitor {
|
||||
type Value = ResourceID;
|
||||
|
||||
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
formatter.write_str("A string containing an absolute path to file or \"[namespace]:[path]\" for a namespaced resource")
|
||||
}
|
||||
|
||||
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
|
||||
where
|
||||
E: serde::de::Error,
|
||||
{
|
||||
Ok(if v.starts_with('/') {
|
||||
let path = PathBuf::from(v);
|
||||
path.metadata().map_err(serde::de::Error::custom)?;
|
||||
ResourceID::File(path)
|
||||
} else if let Some((namespace, path)) = v.split_once(':') {
|
||||
ResourceID::Namespaced {
|
||||
namespace: namespace.to_string(),
|
||||
path: PathBuf::from(path),
|
||||
}
|
||||
} else {
|
||||
return Err(serde::de::Error::custom(anyhow!(
|
||||
"Invalid format for string"
|
||||
)));
|
||||
})
|
||||
}
|
||||
|
||||
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
|
||||
where
|
||||
E: serde::de::Error,
|
||||
{
|
||||
self.visit_str(&v)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,24 +1,30 @@
|
||||
use crate::core::client::Client;
|
||||
use crate::nodes::alias::Alias;
|
||||
use crate::nodes::Node;
|
||||
use anyhow::Result;
|
||||
use crate::{core::client::Client, nodes::Message};
|
||||
use color_eyre::eyre::Result;
|
||||
use once_cell::sync::OnceCell;
|
||||
use parking_lot::Mutex;
|
||||
use portable_atomic::Ordering;
|
||||
use rustc_hash::FxHashMap;
|
||||
use serde::Serialize;
|
||||
use stardust_xr::scenegraph;
|
||||
use stardust_xr::scenegraph::ScenegraphError;
|
||||
use stardust_xr::schemas::flex::serialize;
|
||||
use std::future::Future;
|
||||
use std::os::fd::OwnedFd;
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use core::hash::BuildHasherDefault;
|
||||
use dashmap::DashMap;
|
||||
use rustc_hash::FxHasher;
|
||||
use tokio::sync::oneshot;
|
||||
use tracing::{debug, debug_span};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Scenegraph {
|
||||
pub(super) client: OnceCell<Weak<Client>>,
|
||||
nodes: DashMap<String, Arc<Node>, BuildHasherDefault<FxHasher>>,
|
||||
nodes: Mutex<FxHashMap<String, Arc<Node>>>,
|
||||
}
|
||||
|
||||
impl Scenegraph {
|
||||
pub fn get_client(&self) -> Arc<Client> {
|
||||
self.client.get().unwrap().upgrade().unwrap()
|
||||
pub fn get_client(&self) -> Option<Arc<Client>> {
|
||||
self.client.get()?.upgrade()
|
||||
}
|
||||
|
||||
pub fn add_node(&self, node: Node) -> Arc<Node> {
|
||||
@@ -27,38 +33,113 @@ impl Scenegraph {
|
||||
node_arc
|
||||
}
|
||||
pub fn add_node_raw(&self, node: Arc<Node>) {
|
||||
debug!(node = ?&*node, "Add node");
|
||||
let path = node.get_path().to_string();
|
||||
self.nodes.insert(path, node);
|
||||
self.nodes.lock().insert(path, node);
|
||||
}
|
||||
|
||||
pub fn get_node(&self, path: &str) -> Option<Arc<Node>> {
|
||||
let mut node = self.nodes.get(path)?.clone();
|
||||
if let Some(alias) = node.alias.get() {
|
||||
node = alias.original.upgrade()?;
|
||||
let mut node = self.nodes.lock().get(path)?.clone();
|
||||
while let Ok(alias) = node.get_aspect::<Alias>() {
|
||||
if alias.enabled.load(Ordering::Acquire) {
|
||||
node = alias.original.upgrade()?;
|
||||
} else {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(node)
|
||||
}
|
||||
|
||||
pub fn remove_node(&self, path: &str) -> Option<Arc<Node>> {
|
||||
let (_, node) = self.nodes.remove(path)?;
|
||||
Some(node)
|
||||
debug!(path, "Remove node");
|
||||
self.nodes.lock().remove(path)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MethodResponseSender(oneshot::Sender<Result<(Vec<u8>, Vec<OwnedFd>), ScenegraphError>>);
|
||||
impl MethodResponseSender {
|
||||
pub fn send(self, t: Result<Message, ScenegraphError>) {
|
||||
let _ = self.0.send(t.map(|m| (m.data, m.fds)));
|
||||
}
|
||||
// pub fn send_method_return<T: Serialize>(
|
||||
// self,
|
||||
// result: color_eyre::eyre::Result<(T, Vec<OwnedFd>)>,
|
||||
// ) {
|
||||
// let _ = self.0.send(map_method_return(result));
|
||||
// }
|
||||
pub fn wrap_sync<F: FnOnce() -> color_eyre::eyre::Result<Message>>(self, f: F) {
|
||||
self.send(f().map_err(|e| ScenegraphError::MethodError {
|
||||
error: e.to_string(),
|
||||
}))
|
||||
}
|
||||
pub fn wrap_async<T: Serialize>(
|
||||
self,
|
||||
f: impl Future<Output = color_eyre::eyre::Result<(T, Vec<OwnedFd>)>> + Send + 'static,
|
||||
) {
|
||||
tokio::task::spawn(async move { self.0.send(map_method_return(f.await)) });
|
||||
}
|
||||
}
|
||||
fn map_method_return<T: Serialize>(
|
||||
result: color_eyre::eyre::Result<(T, Vec<OwnedFd>)>,
|
||||
) -> Result<(Vec<u8>, Vec<OwnedFd>), ScenegraphError> {
|
||||
let (value, fds) = result.map_err(|e| ScenegraphError::MethodError {
|
||||
error: e.to_string(),
|
||||
})?;
|
||||
|
||||
let serialized_value = serialize(value).map_err(|e| ScenegraphError::MethodError {
|
||||
error: format!("Internal: Serialization failed: {e}"),
|
||||
})?;
|
||||
Ok((serialized_value, fds))
|
||||
}
|
||||
impl scenegraph::Scenegraph for Scenegraph {
|
||||
fn send_signal(&self, path: &str, method: &str, data: &[u8]) -> Result<(), ScenegraphError> {
|
||||
self.get_node(path)
|
||||
.ok_or(ScenegraphError::NodeNotFound)?
|
||||
.send_local_signal(self.get_client(), method, data)
|
||||
fn send_signal(
|
||||
&self,
|
||||
path: &str,
|
||||
method: &str,
|
||||
data: &[u8],
|
||||
fds: Vec<OwnedFd>,
|
||||
) -> Result<(), ScenegraphError> {
|
||||
let Some(client) = self.get_client() else {
|
||||
return Err(ScenegraphError::SignalNotFound);
|
||||
};
|
||||
debug_span!("Handle signal", path, method).in_scope(|| {
|
||||
self.get_node(path)
|
||||
.ok_or(ScenegraphError::NodeNotFound)?
|
||||
.send_local_signal(
|
||||
client,
|
||||
method,
|
||||
Message {
|
||||
data: data.to_vec(),
|
||||
fds,
|
||||
},
|
||||
)
|
||||
})
|
||||
}
|
||||
fn execute_method(
|
||||
&self,
|
||||
path: &str,
|
||||
method: &str,
|
||||
data: &[u8],
|
||||
) -> Result<Vec<u8>, ScenegraphError> {
|
||||
self.get_node(path)
|
||||
.ok_or(ScenegraphError::NodeNotFound)?
|
||||
.execute_local_method(self.get_client(), method, data)
|
||||
fds: Vec<OwnedFd>,
|
||||
response: oneshot::Sender<Result<(Vec<u8>, Vec<OwnedFd>), ScenegraphError>>,
|
||||
) {
|
||||
let Some(client) = self.get_client() else {
|
||||
let _ = response.send(Err(ScenegraphError::MethodNotFound));
|
||||
return;
|
||||
};
|
||||
debug!(path, method, "Handle method");
|
||||
let Some(node) = self.get_node(path) else {
|
||||
let _ = response.send(Err(ScenegraphError::NodeNotFound));
|
||||
return;
|
||||
};
|
||||
node.execute_local_method(
|
||||
client,
|
||||
method,
|
||||
Message {
|
||||
data: data.to_vec(),
|
||||
fds,
|
||||
},
|
||||
MethodResponseSender(response),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
22
src/core/task.rs
Normal file
22
src/core/task.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
use color_eyre::eyre::Result;
|
||||
use std::future::Future;
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
#[allow(unused_variables)]
|
||||
pub fn new<
|
||||
F: FnOnce() -> S,
|
||||
S: AsRef<str>,
|
||||
A: Future<Output = O> + Send + 'static,
|
||||
O: Send + 'static,
|
||||
>(
|
||||
name_fn: F,
|
||||
async_future: A,
|
||||
) -> Result<JoinHandle<O>> {
|
||||
#[cfg(not(feature = "profile_tokio"))]
|
||||
let result = Ok(tokio::task::spawn(async_future));
|
||||
#[cfg(feature = "profile_tokio")]
|
||||
let result = tokio::task::Builder::new()
|
||||
.name(name_fn().as_ref())
|
||||
.spawn(async_future);
|
||||
result
|
||||
}
|
||||
510
src/main.rs
510
src/main.rs
@@ -1,27 +1,42 @@
|
||||
mod core;
|
||||
mod nodes;
|
||||
mod objects;
|
||||
#[cfg(feature = "wayland")]
|
||||
mod wayland;
|
||||
|
||||
use crate::core::client::CLIENTS;
|
||||
use crate::core::destroy_queue;
|
||||
use crate::nodes::{drawable, hmd, input};
|
||||
use crate::nodes::items::camera;
|
||||
use crate::nodes::{audio, drawable, hmd, input};
|
||||
use crate::objects::input::eye_pointer::EyePointer;
|
||||
use crate::objects::input::mouse_pointer::MousePointer;
|
||||
use crate::objects::input::sk_controller::SkController;
|
||||
use crate::objects::input::sk_hand::SkHand;
|
||||
use crate::wayland::Wayland;
|
||||
use crate::objects::play_space::PlaySpace;
|
||||
use crate::wayland::X_DISPLAY;
|
||||
|
||||
use self::core::eventloop::EventLoop;
|
||||
use anyhow::Result;
|
||||
use clap::Parser;
|
||||
use core::client_state::ClientState;
|
||||
use directories::ProjectDirs;
|
||||
use slog::Drain;
|
||||
use once_cell::sync::OnceCell;
|
||||
use stardust_xr::server;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::Arc;
|
||||
use stereokit::input::Handed;
|
||||
use stereokit::lifecycle::DepthMode;
|
||||
use stereokit::render::SphericalHarmonics;
|
||||
use stereokit::texture::Texture;
|
||||
use stereokit::{lifecycle::DisplayMode, Settings};
|
||||
use std::time::Duration;
|
||||
use stereokit::{
|
||||
named_colors::BLACK, DepthMode, DisplayMode, Handed, LogLevel, StereoKitMultiThread,
|
||||
TextureFormat, TextureType,
|
||||
};
|
||||
use stereokit::{DisplayBlend, Sk};
|
||||
use tokio::sync::Notify;
|
||||
use tokio::task::LocalSet;
|
||||
use tokio::{runtime::Handle, sync::oneshot};
|
||||
use tracing::metadata::LevelFilter;
|
||||
use tracing::{debug_span, error, info};
|
||||
use tracing_subscriber::{fmt, prelude::*, EnvFilter};
|
||||
|
||||
#[derive(Parser)]
|
||||
#[clap(author, version, about, long_about = None)]
|
||||
@@ -33,140 +48,425 @@ struct CliArgs {
|
||||
/// Run Stardust XR as an overlay with given priority
|
||||
#[clap(id = "PRIORITY", short = 'o', long = "overlay", action)]
|
||||
overlay_priority: Option<u32>,
|
||||
|
||||
/// Don't create a tip input for controller because SOME RUNTIMES will lie
|
||||
#[clap(long, action)]
|
||||
disable_controller: bool,
|
||||
|
||||
/// Run a script when ready for clients to connect. If this is not set the script at $HOME/.config/stardust/startup will be ran if it exists.
|
||||
#[clap(id = "PATH", short = 'e', long = "execute-startup-script", action)]
|
||||
startup_script: Option<PathBuf>,
|
||||
|
||||
/// Restore the session with the given ID (or `latest`), ignoring the startup script. Sessions are stored in directories at `~/.local/state/stardust/`.
|
||||
#[clap(id = "SESSION_ID", long = "restore", action)]
|
||||
restore: Option<String>,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let project_dirs = ProjectDirs::from("", "", "stardust").unwrap();
|
||||
let cli_args = Arc::new(CliArgs::parse());
|
||||
let log = ::slog::Logger::root(::slog_stdlog::StdLog.fuse(), slog::o!());
|
||||
slog_stdlog::init()?;
|
||||
static STARDUST_INSTANCE: OnceCell<String> = OnceCell::new();
|
||||
static SK_MULTITHREAD: OnceCell<Sk> = OnceCell::new();
|
||||
static STOP_NOTIFIER: Notify = Notify::const_new();
|
||||
|
||||
let mut stereokit = Settings::default()
|
||||
.app_name("Stardust XR")
|
||||
.overlay_app(cli_args.overlay_priority.is_some())
|
||||
.overlay_priority(cli_args.overlay_priority.unwrap_or(u32::MAX))
|
||||
.disable_desktop_input_window(true)
|
||||
.display_preference(if cli_args.flatscreen {
|
||||
struct EventLoopInfo {
|
||||
tokio_handle: Handle,
|
||||
socket_path: PathBuf,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
ctrlc::set_handler(|| {
|
||||
if atty::isnt(atty::Stream::Stdout) {
|
||||
STOP_NOTIFIER.notify_waiters()
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let registry = tracing_subscriber::registry();
|
||||
|
||||
#[cfg(feature = "profile_app")]
|
||||
let registry = registry.with(tracing_tracy::TracyLayer::new().with_filter(LevelFilter::DEBUG));
|
||||
|
||||
#[cfg(feature = "profile_tokio")]
|
||||
let (console_layer, _) = console_subscriber::ConsoleLayer::builder().build();
|
||||
#[cfg(feature = "profile_tokio")]
|
||||
let registry = registry.with(console_layer);
|
||||
|
||||
let log_layer = fmt::Layer::new()
|
||||
.with_thread_names(true)
|
||||
.with_ansi(true)
|
||||
.with_line_number(true)
|
||||
.with_filter(EnvFilter::from_default_env());
|
||||
registry.with(log_layer).init();
|
||||
|
||||
let project_dirs = ProjectDirs::from("", "", "stardust");
|
||||
if project_dirs.is_none() {
|
||||
error!("Unable to get Stardust project directories, default skybox and startup script will not work.");
|
||||
}
|
||||
let cli_args = Arc::new(CliArgs::parse());
|
||||
|
||||
let sk = stereokit::Settings {
|
||||
app_name: "Stardust XR".to_string(),
|
||||
display_preference: if cli_args.flatscreen {
|
||||
DisplayMode::Flatscreen
|
||||
} else {
|
||||
DisplayMode::MixedReality
|
||||
})
|
||||
.depth_mode(DepthMode::D32)
|
||||
.init()
|
||||
.expect("StereoKit failed to initialize");
|
||||
println!("Init StereoKit");
|
||||
},
|
||||
blend_preference: DisplayBlend::AnyTransparent,
|
||||
depth_mode: DepthMode::D32,
|
||||
log_filter: match EnvFilter::from_default_env().max_level_hint() {
|
||||
Some(LevelFilter::ERROR) => LogLevel::Error,
|
||||
Some(LevelFilter::WARN) => LogLevel::Warning,
|
||||
Some(LevelFilter::INFO) => LogLevel::Inform,
|
||||
Some(LevelFilter::DEBUG) => LogLevel::Diagnostic,
|
||||
Some(LevelFilter::TRACE) => LogLevel::Diagnostic,
|
||||
Some(LevelFilter::OFF) => LogLevel::None,
|
||||
None => LogLevel::Warning,
|
||||
},
|
||||
overlay_app: cli_args.overlay_priority.is_some(),
|
||||
overlay_priority: cli_args.overlay_priority.unwrap_or(u32::MAX),
|
||||
disable_desktop_input_window: true,
|
||||
render_scaling: 2.0,
|
||||
..Default::default()
|
||||
}
|
||||
.init()
|
||||
.expect("StereoKit failed to initialize");
|
||||
let _ = SK_MULTITHREAD.set(sk.multithreaded());
|
||||
info!("Init StereoKit");
|
||||
|
||||
sk.render_set_multisample(0);
|
||||
|
||||
sk.material_set_shader(
|
||||
sk.material_find("default/material_pbr").unwrap(),
|
||||
sk.shader_find("default/shader_pbr_clip").unwrap(),
|
||||
);
|
||||
|
||||
// Skytex/light stuff
|
||||
{
|
||||
let skytex_path = project_dirs.config_dir().join("skytex.hdr");
|
||||
if let Some((tex, light)) = skytex_path
|
||||
.exists()
|
||||
.then(|| Texture::from_cubemap_equirectangular(&stereokit, &skytex_path, true, 100))
|
||||
if let Some((light, tex)) = project_dirs
|
||||
.as_ref()
|
||||
.and_then(|dirs| {
|
||||
let skytex_path = dirs.config_dir().join("skytex.hdr");
|
||||
skytex_path
|
||||
.exists()
|
||||
.then(|| sk.tex_create_cubemap_file(&skytex_path, true, 100).ok())
|
||||
})
|
||||
.flatten()
|
||||
{
|
||||
stereokit.set_skytex(&tex);
|
||||
stereokit.set_skylight(&light);
|
||||
} else if let Some(tex) = Texture::cubemap_from_spherical_harmonics(
|
||||
&stereokit,
|
||||
&SphericalHarmonics::default(),
|
||||
16,
|
||||
0.0,
|
||||
0.0,
|
||||
) {
|
||||
stereokit.set_skytex(&tex);
|
||||
sk.render_set_skytex(&tex);
|
||||
sk.render_set_skylight(light);
|
||||
} else {
|
||||
sk.render_set_skytex(sk.tex_gen_color(
|
||||
BLACK,
|
||||
1,
|
||||
1,
|
||||
TextureType::CUBEMAP,
|
||||
TextureFormat::RGBA32,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let mouse_pointer = cli_args.flatscreen.then(MousePointer::new);
|
||||
let mut hands =
|
||||
(!cli_args.flatscreen).then(|| [SkHand::new(Handed::Left), SkHand::new(Handed::Right)]);
|
||||
let mut controllers = (!cli_args.flatscreen).then(|| {
|
||||
[
|
||||
SkController::new(Handed::Left),
|
||||
SkController::new(Handed::Right),
|
||||
]
|
||||
});
|
||||
let mut mouse_pointer = cli_args
|
||||
.flatscreen
|
||||
.then(MousePointer::new)
|
||||
.transpose()
|
||||
.unwrap();
|
||||
let mut hands = (!cli_args.flatscreen)
|
||||
.then(|| {
|
||||
let left = SkHand::new(Handed::Left).ok();
|
||||
let right = SkHand::new(Handed::Right).ok();
|
||||
left.zip(right)
|
||||
})
|
||||
.flatten();
|
||||
let mut controllers = (!cli_args.flatscreen && !cli_args.disable_controller)
|
||||
.then(|| {
|
||||
let left = SkController::new(&sk, Handed::Left).ok();
|
||||
let right = SkController::new(&sk, Handed::Right).ok();
|
||||
left.zip(right)
|
||||
})
|
||||
.flatten();
|
||||
let eye_pointer = (sk.active_display_mode() == DisplayMode::MixedReality
|
||||
&& sk.device_has_eye_gaze())
|
||||
.then(EyePointer::new)
|
||||
.transpose()
|
||||
.unwrap();
|
||||
|
||||
if hands.is_none() {
|
||||
unsafe {
|
||||
stereokit::sys::input_hand_visible(stereokit::sys::handed__handed_left, false as i32);
|
||||
stereokit::sys::input_hand_visible(stereokit::sys::handed__handed_right, false as i32);
|
||||
}
|
||||
sk.input_hand_visible(Handed::Left, false);
|
||||
sk.input_hand_visible(Handed::Right, false);
|
||||
}
|
||||
|
||||
let (event_stop_tx, event_stop_rx) = oneshot::channel::<()>();
|
||||
let (handle_sender, handle_receiver) = oneshot::channel::<Handle>();
|
||||
let play_space = sk
|
||||
.world_has_bounds()
|
||||
.then(|| PlaySpace::new().ok())
|
||||
.flatten();
|
||||
|
||||
let (info_sender, info_receiver) = oneshot::channel::<EventLoopInfo>();
|
||||
let event_thread = std::thread::Builder::new()
|
||||
.name("event_loop".to_owned())
|
||||
.spawn(move || event_loop(handle_sender, event_stop_rx))?;
|
||||
let _tokio_handle = handle_receiver.blocking_recv()?.enter();
|
||||
.spawn({
|
||||
let project_dirs = project_dirs.clone();
|
||||
move || event_loop(info_sender, project_dirs.clone())
|
||||
})
|
||||
.unwrap();
|
||||
let event_loop_info = info_receiver.blocking_recv().unwrap();
|
||||
let _tokio_handle = event_loop_info.tokio_handle.enter();
|
||||
|
||||
let mut wayland = Wayland::new(log)?;
|
||||
println!("Stardust ready!");
|
||||
stereokit.run(
|
||||
|sk, draw_ctx| {
|
||||
hmd::frame(sk);
|
||||
wayland.frame(sk);
|
||||
destroy_queue::clear();
|
||||
#[cfg(feature = "wayland")]
|
||||
let mut wayland = wayland::Wayland::new().expect("Could not initialize wayland");
|
||||
info!("Stardust ready!");
|
||||
|
||||
if let Some(mouse_pointer) = &mouse_pointer {
|
||||
mouse_pointer.update(sk);
|
||||
}
|
||||
if let Some(hands) = &mut hands {
|
||||
hands[0].update(sk);
|
||||
hands[1].update(sk);
|
||||
}
|
||||
if let Some(controllers) = &mut controllers {
|
||||
controllers[0].update(sk);
|
||||
controllers[1].update(sk);
|
||||
}
|
||||
input::process_input();
|
||||
nodes::root::Root::logic_step(sk.time_elapsed());
|
||||
drawable::draw(sk, draw_ctx);
|
||||
let mut startup_children = project_dirs
|
||||
.as_ref()
|
||||
.map(|project_dirs| {
|
||||
launch_start(
|
||||
&cli_args,
|
||||
project_dirs,
|
||||
&event_loop_info,
|
||||
#[cfg(feature = "wayland")]
|
||||
&wayland,
|
||||
)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
wayland.make_context_current();
|
||||
},
|
||||
|_| {
|
||||
println!("Cleanly shut down StereoKit");
|
||||
},
|
||||
);
|
||||
let mut last_frame_delta = Duration::ZERO;
|
||||
let mut sleep_duration = Duration::ZERO;
|
||||
debug_span!("StereoKit").in_scope(|| {
|
||||
sk.run(
|
||||
|sk| {
|
||||
let _span = debug_span!("StereoKit step");
|
||||
let _span = _span.enter();
|
||||
|
||||
hmd::frame(sk);
|
||||
camera::update(sk);
|
||||
#[cfg(feature = "wayland")]
|
||||
wayland.frame_event(sk);
|
||||
destroy_queue::clear();
|
||||
|
||||
if let Some(mouse_pointer) = &mut mouse_pointer {
|
||||
mouse_pointer.update(sk);
|
||||
}
|
||||
if let Some((left_hand, right_hand)) = &mut hands {
|
||||
left_hand.update(!cli_args.disable_controller, sk);
|
||||
right_hand.update(!cli_args.disable_controller, sk);
|
||||
}
|
||||
if let Some((left_controller, right_controller)) = &mut controllers {
|
||||
left_controller.update(sk);
|
||||
right_controller.update(sk);
|
||||
}
|
||||
if let Some(eye_pointer) = &eye_pointer {
|
||||
eye_pointer.update(sk);
|
||||
}
|
||||
if let Some(play_space) = &play_space {
|
||||
play_space.update(sk);
|
||||
}
|
||||
input::process_input();
|
||||
nodes::root::Root::send_frame_events(sk.time_elapsed_unscaled());
|
||||
adaptive_sleep(
|
||||
sk,
|
||||
&mut last_frame_delta,
|
||||
&mut sleep_duration,
|
||||
Duration::from_micros(250),
|
||||
);
|
||||
|
||||
#[cfg(feature = "wayland")]
|
||||
wayland.update(sk);
|
||||
drawable::draw(sk);
|
||||
audio::update(sk);
|
||||
#[cfg(feature = "wayland")]
|
||||
wayland.make_context_current();
|
||||
},
|
||||
|_sk| {
|
||||
info!("Cleanly shut down StereoKit");
|
||||
},
|
||||
)
|
||||
});
|
||||
|
||||
#[cfg(feature = "wayland")]
|
||||
drop(wayland);
|
||||
|
||||
let _ = event_stop_tx.send(());
|
||||
STOP_NOTIFIER.notify_waiters();
|
||||
event_thread
|
||||
.join()
|
||||
.expect("Failed to cleanly shut down event loop")?;
|
||||
println!("Cleanly shut down Stardust");
|
||||
Ok(())
|
||||
.expect("Failed to cleanly shut down event loop")
|
||||
.unwrap();
|
||||
for mut startup_child in startup_children.drain(..) {
|
||||
let _ = startup_child.kill();
|
||||
}
|
||||
|
||||
info!("Cleanly shut down Stardust");
|
||||
}
|
||||
|
||||
fn adaptive_sleep(
|
||||
sk: &impl StereoKitMultiThread,
|
||||
last_frame_delta: &mut Duration,
|
||||
sleep_duration: &mut Duration,
|
||||
sleep_duration_increase: Duration,
|
||||
) {
|
||||
let frame_delta = Duration::from_secs_f64(sk.time_elapsed_unscaled());
|
||||
if *last_frame_delta < frame_delta {
|
||||
if let Some(frame_delta_delta) = frame_delta.checked_sub(*last_frame_delta) {
|
||||
if let Some(new_sleep_duration) = sleep_duration.checked_sub(frame_delta_delta) {
|
||||
*sleep_duration = new_sleep_duration;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
*sleep_duration += sleep_duration_increase;
|
||||
}
|
||||
|
||||
debug_span!("Sleep", ?sleep_duration, ?frame_delta, ?last_frame_delta).in_scope(|| {
|
||||
*last_frame_delta = frame_delta;
|
||||
std::thread::sleep(*sleep_duration); // to give clients a chance to even update anything before drawing
|
||||
});
|
||||
}
|
||||
|
||||
// #[tokio::main]
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn event_loop(
|
||||
handle_sender: oneshot::Sender<Handle>,
|
||||
stop_rx: oneshot::Receiver<()>,
|
||||
) -> anyhow::Result<()> {
|
||||
let _ = handle_sender.send(Handle::current());
|
||||
// console_subscriber::init();
|
||||
info_sender: oneshot::Sender<EventLoopInfo>,
|
||||
project_dirs: Option<ProjectDirs>,
|
||||
) -> color_eyre::eyre::Result<()> {
|
||||
let socket_path =
|
||||
server::get_free_socket_path().expect("Unable to find a free stardust socket path");
|
||||
STARDUST_INSTANCE.set(socket_path.file_name().unwrap().to_string_lossy().into_owned()).expect("Someone hasn't done their job, yell at Nova because how is this set multiple times what the hell");
|
||||
let _event_loop = EventLoop::new(socket_path.clone()).expect("Couldn't create server socket");
|
||||
info!("Init event loop");
|
||||
info!(
|
||||
socket_path = ?socket_path.display(),
|
||||
"Stardust socket created"
|
||||
);
|
||||
let _ = info_sender.send(EventLoopInfo {
|
||||
tokio_handle: Handle::current(),
|
||||
socket_path,
|
||||
});
|
||||
|
||||
let (event_loop, event_loop_join_handle) =
|
||||
EventLoop::new().expect("Couldn't create server socket");
|
||||
println!("Init event loop");
|
||||
println!("Stardust socket created at {}", event_loop.socket_path);
|
||||
STOP_NOTIFIER.notified().await;
|
||||
println!("Stopping...");
|
||||
if let Some(project_dirs) = project_dirs {
|
||||
save_session(&project_dirs).await;
|
||||
}
|
||||
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
_ = tokio::signal::ctrl_c() => Ok(()),
|
||||
_ = stop_rx => Ok(()),
|
||||
e = event_loop_join_handle => e?,
|
||||
};
|
||||
|
||||
println!("Cleanly shut down event loop");
|
||||
info!("Cleanly shut down event loop");
|
||||
|
||||
unsafe {
|
||||
stereokit::sys::sk_quit();
|
||||
}
|
||||
|
||||
result
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn launch_start(
|
||||
cli_args: &CliArgs,
|
||||
project_dirs: &ProjectDirs,
|
||||
event_loop_info: &EventLoopInfo,
|
||||
#[cfg(feature = "wayland")] wayland: &wayland::Wayland,
|
||||
) -> Vec<Child> {
|
||||
if let Some(session_id) = &cli_args.restore {
|
||||
let session_dir = project_dirs.state_dir().unwrap().join(session_id);
|
||||
return restore_session(&session_dir, event_loop_info, wayland);
|
||||
}
|
||||
let startup_script_path = cli_args
|
||||
.startup_script
|
||||
.clone()
|
||||
.and_then(|p| p.canonicalize().ok())
|
||||
.unwrap_or_else(|| project_dirs.config_dir().join("startup"));
|
||||
run_script(&startup_script_path, event_loop_info, wayland)
|
||||
}
|
||||
|
||||
fn restore_session(
|
||||
session_dir: &Path,
|
||||
event_loop_info: &EventLoopInfo,
|
||||
#[cfg(feature = "wayland")] wayland: &wayland::Wayland,
|
||||
) -> Vec<Child> {
|
||||
let Ok(clients) = session_dir.read_dir() else {
|
||||
return Vec::new();
|
||||
};
|
||||
clients
|
||||
.filter_map(Result::ok)
|
||||
.filter_map(|c| ClientState::from_file(&c.path()))
|
||||
.filter_map(ClientState::launch_command)
|
||||
.filter_map(|startup_command| {
|
||||
run_client(
|
||||
startup_command,
|
||||
event_loop_info,
|
||||
#[cfg(feature = "wayland")]
|
||||
wayland,
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn run_script(
|
||||
script_path: &Path,
|
||||
event_loop_info: &EventLoopInfo,
|
||||
#[cfg(feature = "wayland")] wayland: &wayland::Wayland,
|
||||
) -> Vec<Child> {
|
||||
let _ = std::fs::set_permissions(script_path, std::fs::Permissions::from_mode(0o755));
|
||||
let startup_command = Command::new(script_path);
|
||||
run_client(
|
||||
startup_command,
|
||||
event_loop_info,
|
||||
#[cfg(feature = "wayland")]
|
||||
wayland,
|
||||
)
|
||||
.map(|c| vec![c])
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn run_client(
|
||||
mut command: Command,
|
||||
event_loop_info: &EventLoopInfo,
|
||||
#[cfg(feature = "wayland")] wayland: &wayland::Wayland,
|
||||
) -> Option<Child> {
|
||||
command.stdin(Stdio::null());
|
||||
command.stdout(Stdio::null());
|
||||
command.stderr(Stdio::null());
|
||||
command.env(
|
||||
"FLAT_WAYLAND_DISPLAY",
|
||||
std::env::var_os("WAYLAND_DISPLAY").unwrap_or_default(),
|
||||
);
|
||||
command.env(
|
||||
"STARDUST_INSTANCE",
|
||||
event_loop_info
|
||||
.socket_path
|
||||
.file_name()
|
||||
.expect("Stardust socket path not found"),
|
||||
);
|
||||
#[cfg(feature = "wayland")]
|
||||
{
|
||||
if let Some(wayland_socket) = wayland.socket_name.as_ref() {
|
||||
command.env("WAYLAND_DISPLAY", &wayland_socket);
|
||||
}
|
||||
command.env(
|
||||
"DISPLAY",
|
||||
format!(":{}", X_DISPLAY.get().cloned().unwrap_or_default()),
|
||||
);
|
||||
command.env("GDK_BACKEND", "wayland");
|
||||
command.env("QT_QPA_PLATFORM", "wayland");
|
||||
command.env("MOZ_ENABLE_WAYLAND", "1");
|
||||
command.env("CLUTTER_BACKEND", "wayland");
|
||||
command.env("SDL_VIDEODRIVER", "wayland");
|
||||
}
|
||||
let child = command.spawn().ok()?;
|
||||
Some(child)
|
||||
}
|
||||
|
||||
async fn save_session(project_dirs: &ProjectDirs) {
|
||||
let session_id = nanoid::nanoid!();
|
||||
let state_dir = project_dirs.state_dir().unwrap();
|
||||
let session_dir = state_dir.join(&session_id);
|
||||
std::fs::create_dir_all(&session_dir).unwrap();
|
||||
let _ = std::fs::remove_dir_all(state_dir.join("latest"));
|
||||
std::os::unix::fs::symlink(&session_dir, state_dir.join("latest")).unwrap();
|
||||
|
||||
let local_set = LocalSet::new();
|
||||
for client in CLIENTS.get_vec() {
|
||||
let session_dir = session_dir.clone();
|
||||
local_set.spawn_local(async move {
|
||||
tokio::select! {
|
||||
biased;
|
||||
s = client.save_state() => {s.map(|s| s.to_file(&session_dir));},
|
||||
_ = tokio::time::sleep(Duration::from_millis(100)) => (),
|
||||
}
|
||||
});
|
||||
}
|
||||
local_set.await;
|
||||
println!("Session ID for restore is {session_id}");
|
||||
}
|
||||
|
||||
@@ -1,38 +1,52 @@
|
||||
use super::{Aspect, Node};
|
||||
use crate::core::client::Client;
|
||||
|
||||
use super::Node;
|
||||
use color_eyre::eyre::{ensure, Result};
|
||||
use portable_atomic::AtomicBool;
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct AliasInfo {
|
||||
pub(super) local_signals: Vec<&'static str>,
|
||||
pub(super) local_methods: Vec<&'static str>,
|
||||
pub(super) remote_signals: Vec<&'static str>,
|
||||
pub(super) server_signals: Vec<&'static str>,
|
||||
pub(super) server_methods: Vec<&'static str>,
|
||||
pub(super) client_signals: Vec<&'static str>,
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub struct Alias {
|
||||
pub enabled: Arc<AtomicBool>,
|
||||
pub(super) node: Weak<Node>,
|
||||
pub original: Weak<Node>,
|
||||
|
||||
pub info: AliasInfo,
|
||||
}
|
||||
impl Alias {
|
||||
pub fn new(
|
||||
pub fn create(
|
||||
client: &Arc<Client>,
|
||||
parent: &str,
|
||||
name: &str,
|
||||
original: &Arc<Node>,
|
||||
info: AliasInfo,
|
||||
) -> Arc<Node> {
|
||||
let node = Node::create(client, parent, name, true).add_to_scenegraph();
|
||||
) -> Result<Arc<Node>> {
|
||||
ensure!(
|
||||
client
|
||||
.scenegraph
|
||||
.get_node(&(parent.to_string() + "/" + name))
|
||||
.is_none(),
|
||||
"Node already exists"
|
||||
);
|
||||
|
||||
let node = Node::create_parent_name(client, parent, name, true).add_to_scenegraph()?;
|
||||
let alias = Alias {
|
||||
enabled: Arc::new(AtomicBool::new(true)),
|
||||
node: Arc::downgrade(&node),
|
||||
original: Arc::downgrade(original),
|
||||
info,
|
||||
};
|
||||
let alias = original.aliases.add(alias);
|
||||
let _ = node.alias.set(alias);
|
||||
node
|
||||
node.add_aspect_raw(alias);
|
||||
Ok(node)
|
||||
}
|
||||
}
|
||||
impl Aspect for Alias {
|
||||
const NAME: &'static str = "Alias";
|
||||
}
|
||||
|
||||
128
src/nodes/audio.rs
Normal file
128
src/nodes/audio.rs
Normal file
@@ -0,0 +1,128 @@
|
||||
use super::{Aspect, Node};
|
||||
use crate::core::client::Client;
|
||||
use crate::core::destroy_queue;
|
||||
use crate::core::registry::Registry;
|
||||
use crate::core::resource::get_resource_file;
|
||||
use crate::create_interface;
|
||||
use crate::nodes::spatial::{Spatial, Transform};
|
||||
use color_eyre::eyre::{eyre, Result};
|
||||
use glam::{vec3, Vec4Swizzles};
|
||||
use once_cell::sync::OnceCell;
|
||||
use parking_lot::Mutex;
|
||||
use send_wrapper::SendWrapper;
|
||||
use stardust_xr::values::ResourceID;
|
||||
|
||||
use std::ops::DerefMut;
|
||||
use std::sync::Arc;
|
||||
use std::{ffi::OsStr, path::PathBuf};
|
||||
use stereokit::{Sound as SkSound, SoundInstance, StereoKitDraw};
|
||||
|
||||
static SOUND_REGISTRY: Registry<Sound> = Registry::new();
|
||||
|
||||
stardust_xr_server_codegen::codegen_audio_protocol!();
|
||||
pub struct Sound {
|
||||
space: Arc<Spatial>,
|
||||
|
||||
volume: f32,
|
||||
pending_audio_path: PathBuf,
|
||||
sk_sound: OnceCell<SendWrapper<SkSound>>,
|
||||
instance: Mutex<Option<SoundInstance>>,
|
||||
stop: Mutex<Option<()>>,
|
||||
play: Mutex<Option<()>>,
|
||||
}
|
||||
impl Sound {
|
||||
pub fn add_to(node: &Arc<Node>, resource_id: ResourceID) -> Result<Arc<Sound>> {
|
||||
let pending_audio_path = get_resource_file(
|
||||
&resource_id,
|
||||
&*node.get_client().ok_or_else(|| eyre!("Client not found"))?,
|
||||
&[OsStr::new("wav"), OsStr::new("mp3")],
|
||||
)
|
||||
.ok_or_else(|| eyre!("Resource not found"))?;
|
||||
let sound = Sound {
|
||||
space: node.get_aspect::<Spatial>().unwrap().clone(),
|
||||
volume: 1.0,
|
||||
pending_audio_path,
|
||||
sk_sound: OnceCell::new(),
|
||||
instance: Mutex::new(None),
|
||||
stop: Mutex::new(None),
|
||||
play: Mutex::new(None),
|
||||
};
|
||||
let sound_arc = SOUND_REGISTRY.add(sound);
|
||||
node.add_aspect_raw(sound_arc.clone());
|
||||
<Sound as SoundAspect>::add_node_members(node);
|
||||
Ok(sound_arc)
|
||||
}
|
||||
|
||||
fn update(&self, sk: &impl StereoKitDraw) {
|
||||
let sound = self.sk_sound.get_or_init(|| {
|
||||
SendWrapper::new(sk.sound_create(self.pending_audio_path.clone()).unwrap())
|
||||
});
|
||||
if self.stop.lock().take().is_some() {
|
||||
if let Some(instance) = self.instance.lock().take() {
|
||||
sk.sound_inst_stop(instance);
|
||||
}
|
||||
}
|
||||
if self.instance.lock().is_none() && self.play.lock().take().is_some() {
|
||||
self.instance.lock().replace(sk.sound_play(
|
||||
sound.as_ref(),
|
||||
vec3(0.0, 0.0, 0.0),
|
||||
self.volume,
|
||||
));
|
||||
}
|
||||
if let Some(instance) = self.instance.lock().deref_mut() {
|
||||
sk.sound_inst_set_pos(*instance, self.space.global_transform().w_axis.xyz());
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Aspect for Sound {
|
||||
const NAME: &'static str = "Sound";
|
||||
}
|
||||
impl SoundAspect for Sound {
|
||||
fn play(node: Arc<Node>, _calling_client: Arc<Client>) -> Result<()> {
|
||||
let sound = node.get_aspect::<Sound>().unwrap();
|
||||
sound.play.lock().replace(());
|
||||
Ok(())
|
||||
}
|
||||
fn stop(node: Arc<Node>, _calling_client: Arc<Client>) -> Result<()> {
|
||||
let sound = node.get_aspect::<Sound>().unwrap();
|
||||
sound.stop.lock().replace(());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Drop for Sound {
|
||||
fn drop(&mut self) {
|
||||
if let Some(sk_sound) = self.sk_sound.take() {
|
||||
destroy_queue::add(sk_sound);
|
||||
}
|
||||
SOUND_REGISTRY.remove(self);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update(sk: &impl StereoKitDraw) {
|
||||
for sound in SOUND_REGISTRY.get_valid_contents() {
|
||||
sound.update(sk)
|
||||
}
|
||||
}
|
||||
|
||||
create_interface!(AudioInterface, AudioInterfaceAspect, "/audio");
|
||||
struct AudioInterface;
|
||||
impl AudioInterfaceAspect for AudioInterface {
|
||||
#[doc = "Create a sound node. WAV and MP3 are supported."]
|
||||
fn create_sound(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
name: String,
|
||||
parent: Arc<Node>,
|
||||
transform: Transform,
|
||||
resource: ResourceID,
|
||||
) -> Result<()> {
|
||||
let node =
|
||||
Node::create_parent_name(&calling_client, Self::CREATE_SOUND_PARENT_PATH, &name, true);
|
||||
let parent = parent.get_aspect::<Spatial>()?;
|
||||
let transform = transform.to_mat4(true, true, true);
|
||||
let node = node.add_to_scenegraph()?;
|
||||
Spatial::add_to(&node, Some(parent.clone()), transform, false);
|
||||
Sound::add_to(&node, resource)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,29 +1,50 @@
|
||||
use super::alias::AliasInfo;
|
||||
use super::fields::Field;
|
||||
use super::spatial::{parse_transform, Spatial};
|
||||
use super::{Alias, Node};
|
||||
use super::{Alias, Aspect, Node};
|
||||
use crate::core::client::Client;
|
||||
use crate::core::nodelist::LifeLinkedNodeList;
|
||||
use crate::core::node_collections::LifeLinkedNodeMap;
|
||||
use crate::core::registry::Registry;
|
||||
use crate::nodes::fields::find_field;
|
||||
use crate::nodes::spatial::find_spatial_parent;
|
||||
use anyhow::{anyhow, ensure, Result};
|
||||
use glam::vec3a;
|
||||
use crate::create_interface;
|
||||
use crate::nodes::fields::FIELD_ALIAS_INFO;
|
||||
use crate::nodes::spatial::Transform;
|
||||
use color_eyre::eyre::{bail, ensure, eyre, Result};
|
||||
use lazy_static::lazy_static;
|
||||
use nanoid::nanoid;
|
||||
use parking_lot::Mutex;
|
||||
use serde::Deserialize;
|
||||
use stardust_xr::schemas::flex::{deserialize, serialize};
|
||||
use stardust_xr::values::Transform;
|
||||
use rustc_hash::FxHashMap;
|
||||
use stardust_xr::schemas::flex::flexbuffers;
|
||||
use stardust_xr::values::Datamap;
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
static PULSE_SENDER_REGISTRY: Registry<PulseSender> = Registry::new();
|
||||
static PULSE_RECEIVER_REGISTRY: Registry<PulseReceiver> = Registry::new();
|
||||
lazy_static! {
|
||||
pub static ref KEYMAPS: Mutex<FxHashMap<String, String>> = Mutex::new(FxHashMap::default());
|
||||
}
|
||||
|
||||
fn mask_matches(mask_map_lesser: &Mask, mask_map_greater: &Mask) -> bool {
|
||||
static PULSE_SENDER_REGISTRY: Registry<PulseSender> = Registry::new();
|
||||
pub static PULSE_RECEIVER_REGISTRY: Registry<PulseReceiver> = Registry::new();
|
||||
|
||||
pub fn get_mask(datamap: &Datamap) -> Result<flexbuffers::MapReader<&[u8]>> {
|
||||
flexbuffers::Reader::get_root(datamap.raw().as_slice())
|
||||
.map_err(|_| eyre!("Mask is not a valid flexbuffer"))?
|
||||
.get_map()
|
||||
.map_err(|_| eyre!("Mask is not a valid map"))
|
||||
}
|
||||
pub fn mask_matches(mask_map_lesser: &Datamap, mask_map_greater: &Datamap) -> bool {
|
||||
(|| -> Result<_> {
|
||||
for key in mask_map_lesser.get_mask()?.iter_keys() {
|
||||
let lesser_key_type = mask_map_lesser.get_mask()?.index(key)?.flexbuffer_type();
|
||||
let greater_key_type = mask_map_greater.get_mask()?.index(key)?.flexbuffer_type();
|
||||
if lesser_key_type != greater_key_type {
|
||||
for key in get_mask(mask_map_lesser)?.iter_keys() {
|
||||
let lesser_key = get_mask(mask_map_lesser)?.index(key)?;
|
||||
let greater_key = get_mask(mask_map_greater)?.index(key)?;
|
||||
// otherwise zero-length vectors don't count the same as a single type vector
|
||||
if lesser_key.flexbuffer_type().is_heterogenous_vector()
|
||||
&& lesser_key.as_vector().len() == 0
|
||||
&& greater_key.flexbuffer_type().is_vector()
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if !lesser_key.flexbuffer_type().is_null()
|
||||
&& lesser_key.flexbuffer_type() != greater_key.flexbuffer_type()
|
||||
{
|
||||
return Err(flexbuffers::ReaderError::InvalidPackedType {}.into());
|
||||
}
|
||||
}
|
||||
@@ -32,122 +53,88 @@ fn mask_matches(mask_map_lesser: &Mask, mask_map_greater: &Mask) -> bool {
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
type MaskMapGetFn = fn(&[u8]) -> Result<flexbuffers::MapReader<&[u8]>>;
|
||||
pub struct Mask {
|
||||
binary: Vec<u8>,
|
||||
get_fn: MaskMapGetFn,
|
||||
}
|
||||
impl Mask {
|
||||
pub fn get_mask(&self) -> Result<flexbuffers::MapReader<&[u8]>> {
|
||||
(self.get_fn)(self.binary.as_slice())
|
||||
}
|
||||
pub fn set_mask(&mut self, binary: Vec<u8>, get_fn: MaskMapGetFn) {
|
||||
self.binary = binary;
|
||||
self.get_fn = get_fn;
|
||||
}
|
||||
}
|
||||
impl Default for Mask {
|
||||
fn default() -> Self {
|
||||
Mask {
|
||||
binary: Default::default(),
|
||||
get_fn: mask_get_err,
|
||||
}
|
||||
}
|
||||
}
|
||||
fn mask_get_err(_binary: &[u8]) -> Result<flexbuffers::MapReader<&[u8]>> {
|
||||
Err(anyhow!("You need to call setMask to set the mask!"))
|
||||
}
|
||||
fn mask_get_map_at_root(binary: &[u8]) -> Result<flexbuffers::MapReader<&[u8]>> {
|
||||
flexbuffers::Reader::get_root(binary)
|
||||
.map_err(|_| anyhow!("Mask is not a valid flexbuffer"))?
|
||||
.get_map()
|
||||
.map_err(|_| anyhow!("Mask is not a valid map"))
|
||||
}
|
||||
stardust_xr_server_codegen::codegen_data_protocol!();
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct PulseSender {
|
||||
mask: Mutex<Mask>,
|
||||
aliases: LifeLinkedNodeList,
|
||||
node: Weak<Node>,
|
||||
pub mask: Datamap,
|
||||
aliases: LifeLinkedNodeMap<String>,
|
||||
}
|
||||
impl PulseSender {
|
||||
pub fn add_to(node: &Arc<Node>) -> Result<()> {
|
||||
ensure!(
|
||||
node.spatial.get().is_some(),
|
||||
"Internal: Node does not have a spatial attached!"
|
||||
);
|
||||
pub fn add_to(node: &Arc<Node>, mask: Datamap) -> Result<Arc<PulseSender>> {
|
||||
let sender = PulseSender {
|
||||
node: Arc::downgrade(node),
|
||||
mask,
|
||||
aliases: LifeLinkedNodeMap::default(),
|
||||
};
|
||||
|
||||
let sender = Default::default();
|
||||
// <PulseSender as PulseSenderAspect>::add_node_members(node);
|
||||
let sender = PULSE_SENDER_REGISTRY.add(sender);
|
||||
let _ = node.pulse_sender.set(sender);
|
||||
node.add_local_signal("setMask", PulseSender::set_mask_flex);
|
||||
node.add_local_method("getReceivers", PulseSender::get_receivers_flex);
|
||||
Ok(())
|
||||
node.add_aspect_raw(sender.clone());
|
||||
for receiver in PULSE_RECEIVER_REGISTRY.get_valid_contents() {
|
||||
sender.handle_new_receiver(&receiver);
|
||||
}
|
||||
Ok(sender.clone())
|
||||
}
|
||||
pub fn set_mask_flex(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
ensure!(
|
||||
node.pulse_sender.get().is_some(),
|
||||
"Internal: Node does not have a pulse sender aspect"
|
||||
);
|
||||
node.pulse_sender
|
||||
.get()
|
||||
.unwrap()
|
||||
.mask
|
||||
.lock()
|
||||
.set_mask(data.to_vec(), mask_get_map_at_root);
|
||||
Ok(())
|
||||
fn handle_new_receiver(&self, receiver: &PulseReceiver) {
|
||||
if !mask_matches(&self.mask, &receiver.mask) {
|
||||
return;
|
||||
}
|
||||
let Some(tx_node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let Some(tx_client) = tx_node.get_client() else {
|
||||
return;
|
||||
};
|
||||
let Some(rx_node) = receiver.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
// Receiver itself
|
||||
let Ok(rx_alias) = Alias::create(
|
||||
&tx_client,
|
||||
tx_node.get_path(),
|
||||
receiver.uid.as_str(),
|
||||
&rx_node,
|
||||
AliasInfo {
|
||||
server_methods: vec!["send_data"],
|
||||
..Default::default()
|
||||
},
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
self.aliases.add(receiver.uid.clone(), &rx_alias);
|
||||
|
||||
// Receiver's field
|
||||
let Ok(rx_field_alias) = Alias::create(
|
||||
&tx_client,
|
||||
rx_alias.get_path(),
|
||||
"field",
|
||||
&rx_node.get_aspect::<PulseReceiver>().unwrap().field_node,
|
||||
FIELD_ALIAS_INFO.clone(),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
self.aliases
|
||||
.add(receiver.uid.clone() + "-field", &rx_field_alias);
|
||||
|
||||
let _ =
|
||||
pulse_sender_client::new_receiver(&tx_node, &receiver.uid, &rx_alias, &rx_field_alias);
|
||||
}
|
||||
fn get_receivers_flex(
|
||||
node: &Node,
|
||||
calling_client: Arc<Client>,
|
||||
_data: &[u8],
|
||||
) -> Result<Vec<u8>> {
|
||||
let sender_spatial = node
|
||||
.spatial
|
||||
.get()
|
||||
.ok_or_else(|| anyhow!("Node does not have a spatial aspect!"))?;
|
||||
let sender = node
|
||||
.pulse_sender
|
||||
.get()
|
||||
.ok_or_else(|| anyhow!("Node does not have a sender aspect!"))?;
|
||||
let valid_receivers = PULSE_RECEIVER_REGISTRY.get_valid_contents();
|
||||
let mut distance_sorted_receivers: Vec<(f32, &PulseReceiver)> = valid_receivers
|
||||
.iter()
|
||||
.filter(|receiver| receiver.get_field().is_some())
|
||||
.filter(|receiver| mask_matches(&*sender.mask.lock(), &*receiver.mask.lock()))
|
||||
.map(|receiver| {
|
||||
(
|
||||
receiver
|
||||
.get_field()
|
||||
.unwrap()
|
||||
.distance(sender_spatial, vec3a(0_f32, 0_f32, 0_f32)),
|
||||
receiver.as_ref(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
distance_sorted_receivers.sort_by(|(d1, _), (d2, _)| d1.partial_cmp(d2).unwrap());
|
||||
sender.aliases.clear();
|
||||
let uids: Vec<String> = distance_sorted_receivers
|
||||
.into_iter()
|
||||
.map(|(_, receiver)| {
|
||||
let receiver_alias = Alias::new(
|
||||
&calling_client,
|
||||
node.get_path(),
|
||||
receiver.uid.as_str(),
|
||||
receiver.node.upgrade().as_ref().unwrap(),
|
||||
AliasInfo {
|
||||
local_methods: vec!["sendData"],
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
sender.aliases.add(Arc::downgrade(&receiver_alias));
|
||||
|
||||
receiver.uid.clone()
|
||||
})
|
||||
.collect();
|
||||
|
||||
serialize(uids).map_err(|e| e.into())
|
||||
fn handle_drop_receiver(&self, receiver: &PulseReceiver) {
|
||||
let uid = receiver.uid.as_str();
|
||||
self.aliases.remove(uid);
|
||||
self.aliases.remove(&(uid.to_string() + "-field"));
|
||||
let Some(tx_node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let _ = pulse_sender_client::drop_receiver(&tx_node, uid);
|
||||
}
|
||||
}
|
||||
impl Aspect for PulseSender {
|
||||
const NAME: &'static str = "PulseSender";
|
||||
}
|
||||
impl PulseSenderAspect for PulseSender {}
|
||||
impl Drop for PulseSender {
|
||||
fn drop(&mut self) {
|
||||
PULSE_SENDER_REGISTRY.remove(self);
|
||||
@@ -156,138 +143,146 @@ impl Drop for PulseSender {
|
||||
|
||||
pub struct PulseReceiver {
|
||||
uid: String,
|
||||
node: Weak<Node>,
|
||||
pub mask: Mutex<Mask>,
|
||||
field: Weak<Field>,
|
||||
pub node: Weak<Node>,
|
||||
pub field_node: Arc<Node>,
|
||||
pub mask: Datamap,
|
||||
}
|
||||
impl PulseReceiver {
|
||||
pub fn add_to(node: &Arc<Node>, field: Arc<Field>) -> Result<()> {
|
||||
ensure!(
|
||||
node.spatial.get().is_some(),
|
||||
"Internal: Node does not have a spatial attached!"
|
||||
);
|
||||
|
||||
pub fn add_to(
|
||||
node: &Arc<Node>,
|
||||
field_node: Arc<Node>,
|
||||
mask: Datamap,
|
||||
) -> Result<Arc<PulseReceiver>> {
|
||||
let receiver = PulseReceiver {
|
||||
uid: node.uid.clone(),
|
||||
uid: nanoid!(),
|
||||
node: Arc::downgrade(node),
|
||||
field: Arc::downgrade(&field),
|
||||
mask: Default::default(),
|
||||
field_node,
|
||||
mask,
|
||||
};
|
||||
let receiver = PULSE_RECEIVER_REGISTRY.add(receiver);
|
||||
let _ = node.pulse_receiver.set(receiver);
|
||||
node.add_local_signal("setMask", PulseReceiver::set_mask_flex);
|
||||
node.add_local_signal("sendData", PulseReceiver::send_data_flex);
|
||||
Ok(())
|
||||
}
|
||||
fn get_field(&self) -> Option<Arc<Field>> {
|
||||
self.field.upgrade()
|
||||
}
|
||||
fn send_data_flex(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
ensure!(
|
||||
node.pulse_receiver.get().is_some(),
|
||||
"Internal: Node does not have a pulse receiver aspect"
|
||||
);
|
||||
let receiver_mask = node.pulse_receiver.get().unwrap().mask.lock();
|
||||
let data_mask = Mask {
|
||||
binary: data.to_vec(),
|
||||
get_fn: mask_get_map_at_root,
|
||||
};
|
||||
if !mask_matches(&receiver_mask, &data_mask) {
|
||||
return Err(anyhow!(
|
||||
"Message does not contain the same keys as the receiver mask"
|
||||
));
|
||||
|
||||
<PulseReceiver as PulseReceiverAspect>::add_node_members(node);
|
||||
node.add_aspect_raw(receiver.clone());
|
||||
for sender in PULSE_SENDER_REGISTRY.get_valid_contents() {
|
||||
sender.handle_new_receiver(&receiver);
|
||||
}
|
||||
drop(receiver_mask);
|
||||
node.send_remote_signal("pulse", data)?;
|
||||
Ok(())
|
||||
Ok(receiver)
|
||||
}
|
||||
fn set_mask_flex(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
}
|
||||
impl Aspect for PulseReceiver {
|
||||
const NAME: &'static str = "PulseReceiver";
|
||||
}
|
||||
impl PulseReceiverAspect for PulseReceiver {
|
||||
fn send_data(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
sender: Arc<Node>,
|
||||
data: Datamap,
|
||||
) -> Result<()> {
|
||||
let this_receiver = node.get_aspect::<PulseReceiver>().unwrap();
|
||||
|
||||
ensure!(
|
||||
node.pulse_receiver.get().is_some(),
|
||||
"Internal: Node does not have a pulse receiver aspect"
|
||||
mask_matches(&this_receiver.mask, &data),
|
||||
"Message ({data:?}) does not contain the same keys as the receiver's mask ({:?})",
|
||||
this_receiver.mask
|
||||
);
|
||||
node.pulse_receiver
|
||||
.get()
|
||||
.unwrap()
|
||||
.mask
|
||||
.lock()
|
||||
.set_mask(data.to_vec(), mask_get_map_at_root);
|
||||
pulse_receiver_client::data(&node, &sender.uid, &data)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PulseReceiver {
|
||||
fn drop(&mut self) {
|
||||
PULSE_RECEIVER_REGISTRY.remove(self);
|
||||
for sender in PULSE_SENDER_REGISTRY.get_valid_contents() {
|
||||
sender.handle_drop_receiver(self);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_interface(client: &Arc<Client>) {
|
||||
let node = Node::create(client, "", "data", false);
|
||||
node.add_local_signal("createPulseSender", create_pulse_sender_flex);
|
||||
node.add_local_signal("createPulseReceiver", create_pulse_receiver_flex);
|
||||
node.add_to_scenegraph();
|
||||
}
|
||||
|
||||
// pub fn mask_get_map_pulse_sender_create_args(mask: &Mask) -> Result<flexbuffers::MapReader<&[u8]>> {
|
||||
// flexbuffers::Reader::get_root(mask.binary.as_slice())
|
||||
// .map_err(|_| anyhow!("Mask is not a valid flexbuffer"))?
|
||||
// .get_vector()?
|
||||
// .index(4)?
|
||||
// .get_map()
|
||||
// .map_err(|_| anyhow!("Mask is not a valid map"))
|
||||
// }
|
||||
pub fn create_pulse_sender_flex(
|
||||
_node: &Node,
|
||||
calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct CreatePulseSenderInfo<'a> {
|
||||
name: &'a str,
|
||||
parent_path: &'a str,
|
||||
create_interface!(DataInterface, DataInterfaceAspect, "/data");
|
||||
struct DataInterface;
|
||||
impl DataInterfaceAspect for DataInterface {
|
||||
fn create_pulse_sender(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
name: String,
|
||||
parent: Arc<Node>,
|
||||
transform: Transform,
|
||||
}
|
||||
let info: CreatePulseSenderInfo = deserialize(data)?;
|
||||
let node = Node::create(&calling_client, "/data/sender", info.name, true);
|
||||
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||
let transform = parse_transform(info.transform, true, true, false)?;
|
||||
let node = node.add_to_scenegraph();
|
||||
Spatial::add_to(&node, Some(parent), transform)?;
|
||||
PulseSender::add_to(&node)?;
|
||||
Ok(())
|
||||
}
|
||||
mask: Datamap,
|
||||
) -> Result<()> {
|
||||
get_mask(&mask)?;
|
||||
let node = Node::create_parent_name(
|
||||
&calling_client,
|
||||
Self::CREATE_PULSE_SENDER_PARENT_PATH,
|
||||
&name,
|
||||
true,
|
||||
);
|
||||
let parent = parent.get_aspect::<Spatial>()?;
|
||||
let transform = transform.to_mat4(true, true, false);
|
||||
|
||||
// pub fn mask_get_map_pulse_receiver_create_args(
|
||||
// mask: &Mask,
|
||||
// ) -> Result<flexbuffers::MapReader<&[u8]>> {
|
||||
// flexbuffers::Reader::get_root(mask.binary.as_slice())
|
||||
// .map_err(|_| anyhow!("Mask is not a valid flexbuffer"))?
|
||||
// .get_vector()?
|
||||
// .index(5)?
|
||||
// .get_map()
|
||||
// .map_err(|_| anyhow!("Mask is not a valid map"))
|
||||
// }
|
||||
pub fn create_pulse_receiver_flex(
|
||||
_node: &Node,
|
||||
calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct CreatePulseReceiverInfo<'a> {
|
||||
name: &'a str,
|
||||
parent_path: &'a str,
|
||||
let node = node.add_to_scenegraph()?;
|
||||
Spatial::add_to(&node, Some(parent.clone()), transform, false);
|
||||
PulseSender::add_to(&node, mask)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn create_pulse_receiver(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
name: String,
|
||||
parent: Arc<Node>,
|
||||
transform: Transform,
|
||||
field_path: &'a str,
|
||||
}
|
||||
let info: CreatePulseReceiverInfo = deserialize(data)?;
|
||||
let node = Node::create(&calling_client, "/data/sender", info.name, true);
|
||||
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||
let transform = parse_transform(info.transform, true, true, false)?;
|
||||
let field = find_field(&calling_client, info.field_path)?;
|
||||
field: Arc<Node>,
|
||||
mask: Datamap,
|
||||
) -> Result<()> {
|
||||
get_mask(&mask)?;
|
||||
let node = Node::create_parent_name(
|
||||
&calling_client,
|
||||
Self::CREATE_PULSE_RECEIVER_PARENT_PATH,
|
||||
&name,
|
||||
true,
|
||||
);
|
||||
let parent = parent.get_aspect::<Spatial>()?;
|
||||
let transform = parse_transform(transform, true, true, false);
|
||||
let _ = field.get_aspect::<Field>()?;
|
||||
|
||||
let node = node.add_to_scenegraph();
|
||||
Spatial::add_to(&node, Some(parent), transform)?;
|
||||
PulseReceiver::add_to(&node, field)?;
|
||||
Ok(())
|
||||
let node = node.add_to_scenegraph()?;
|
||||
Spatial::add_to(&node, Some(parent.clone()), transform, false);
|
||||
PulseReceiver::add_to(&node, field, mask)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn register_keymap(
|
||||
_node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
keymap: String,
|
||||
) -> Result<String> {
|
||||
let mut keymaps = KEYMAPS.lock();
|
||||
if let Some(found_keymap_id) = keymaps
|
||||
.iter()
|
||||
.filter(|(_k, v)| *v == &keymap)
|
||||
.map(|(k, _v)| k)
|
||||
.last()
|
||||
{
|
||||
return Ok(found_keymap_id.clone());
|
||||
}
|
||||
|
||||
let generated_id = nanoid!();
|
||||
keymaps.insert(generated_id.clone(), keymap);
|
||||
|
||||
Ok(generated_id)
|
||||
}
|
||||
|
||||
async fn get_keymap(
|
||||
_node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
keymap_id: String,
|
||||
) -> Result<String> {
|
||||
let keymaps = KEYMAPS.lock();
|
||||
let Some(keymap) = keymaps.get(&keymap_id) else {
|
||||
bail!("Could not find keymap. Try registering it")
|
||||
};
|
||||
|
||||
Ok(keymap.clone())
|
||||
}
|
||||
}
|
||||
|
||||
117
src/nodes/drawable/lines.rs
Normal file
117
src/nodes/drawable/lines.rs
Normal file
@@ -0,0 +1,117 @@
|
||||
use super::{Line, LinesAspect};
|
||||
use crate::{
|
||||
core::{client::Client, registry::Registry},
|
||||
nodes::{spatial::Spatial, Aspect, Node},
|
||||
};
|
||||
use color_eyre::eyre::Result;
|
||||
use glam::Vec3A;
|
||||
use parking_lot::Mutex;
|
||||
use portable_atomic::{AtomicBool, Ordering};
|
||||
use prisma::Lerp;
|
||||
use std::{collections::VecDeque, sync::Arc};
|
||||
use stereokit::{bounds_grow_to_fit_pt, Bounds, Color128, LinePoint as SkLinePoint, StereoKitDraw};
|
||||
|
||||
static LINES_REGISTRY: Registry<Lines> = Registry::new();
|
||||
|
||||
pub struct Lines {
|
||||
enabled: Arc<AtomicBool>,
|
||||
space: Arc<Spatial>,
|
||||
data: Mutex<Vec<Line>>,
|
||||
}
|
||||
impl Lines {
|
||||
pub fn add_to(node: &Arc<Node>, lines: Vec<Line>) -> Result<Arc<Lines>> {
|
||||
let _ = node
|
||||
.get_aspect::<Spatial>()
|
||||
.unwrap()
|
||||
.bounding_box_calc
|
||||
.set(|node| {
|
||||
let mut bounds = Bounds::default();
|
||||
if let Ok(lines) = node.get_aspect::<Lines>() {
|
||||
for line in &*lines.data.lock() {
|
||||
for point in &line.points {
|
||||
bounds = bounds_grow_to_fit_pt(bounds, point.point);
|
||||
}
|
||||
}
|
||||
}
|
||||
bounds
|
||||
});
|
||||
|
||||
let lines = LINES_REGISTRY.add(Lines {
|
||||
enabled: node.enabled.clone(),
|
||||
space: node.get_aspect::<Spatial>()?.clone(),
|
||||
data: Mutex::new(lines),
|
||||
});
|
||||
<Lines as LinesAspect>::add_node_members(node);
|
||||
node.add_aspect_raw(lines.clone());
|
||||
|
||||
Ok(lines)
|
||||
}
|
||||
|
||||
fn draw(&self, draw_ctx: &impl StereoKitDraw) {
|
||||
let transform_mat = self.space.global_transform();
|
||||
let data = self.data.lock().clone();
|
||||
for line in &data {
|
||||
let mut points: VecDeque<SkLinePoint> = line
|
||||
.points
|
||||
.iter()
|
||||
.map(|p| SkLinePoint {
|
||||
pt: transform_mat.transform_point3a(Vec3A::from(p.point)).into(),
|
||||
thickness: p.thickness,
|
||||
color: stereokit::sys::color128::from([
|
||||
p.color.c.r,
|
||||
p.color.c.g,
|
||||
p.color.c.b,
|
||||
p.color.a,
|
||||
])
|
||||
.into(),
|
||||
})
|
||||
.collect();
|
||||
if line.cyclic && !points.is_empty() {
|
||||
let first = line.points.first().unwrap();
|
||||
let last = line.points.last().unwrap();
|
||||
|
||||
let color = Color128 {
|
||||
r: first.color.c.r.lerp(&last.color.c.r, 0.5),
|
||||
g: first.color.c.g.lerp(&last.color.c.g, 0.5),
|
||||
b: first.color.c.b.lerp(&last.color.c.b, 0.5),
|
||||
a: first.color.a.lerp(&last.color.a, 0.5),
|
||||
};
|
||||
let connect_point = SkLinePoint {
|
||||
pt: transform_mat
|
||||
.transform_point3a(
|
||||
Vec3A::from(first.point).lerp(Vec3A::from(last.point), 0.5),
|
||||
)
|
||||
.into(),
|
||||
thickness: (first.thickness + last.thickness) * 0.5,
|
||||
color: color.into(),
|
||||
};
|
||||
points.push_front(connect_point.clone());
|
||||
points.push_back(connect_point);
|
||||
}
|
||||
draw_ctx.line_add_listv(points.make_contiguous());
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Aspect for Lines {
|
||||
const NAME: &'static str = "Lines";
|
||||
}
|
||||
impl LinesAspect for Lines {
|
||||
fn set_lines(node: Arc<Node>, _calling_client: Arc<Client>, lines: Vec<Line>) -> Result<()> {
|
||||
let lines_aspect = node.get_aspect::<Lines>()?;
|
||||
*lines_aspect.data.lock() = lines;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Drop for Lines {
|
||||
fn drop(&mut self) {
|
||||
LINES_REGISTRY.remove(self);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn draw_all(draw_ctx: &impl StereoKitDraw) {
|
||||
for lines in LINES_REGISTRY.get_valid_contents() {
|
||||
if lines.enabled.load(Ordering::Relaxed) {
|
||||
lines.draw(draw_ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,47 +1,37 @@
|
||||
pub mod lines;
|
||||
pub mod model;
|
||||
pub mod shaders;
|
||||
pub mod text;
|
||||
|
||||
use super::Node;
|
||||
use crate::core::client::Client;
|
||||
use anyhow::Result;
|
||||
use self::{lines::Lines, model::Model, text::Text};
|
||||
use super::{
|
||||
spatial::{Spatial, Transform},
|
||||
Node,
|
||||
};
|
||||
use crate::{
|
||||
core::{client::Client, resource::get_resource_file},
|
||||
create_interface,
|
||||
};
|
||||
use color_eyre::eyre::{self, Result};
|
||||
use parking_lot::Mutex;
|
||||
use serde::Deserialize;
|
||||
use stardust_xr::schemas::flex::deserialize;
|
||||
use std::{path::PathBuf, sync::Arc};
|
||||
use stereokit::{lifecycle::DrawContext, texture::Texture, StereoKit};
|
||||
use stardust_xr::values::ResourceID;
|
||||
use std::{ffi::OsStr, path::PathBuf, sync::Arc};
|
||||
use stereokit::StereoKitDraw;
|
||||
|
||||
pub fn create_interface(client: &Arc<Client>) {
|
||||
let node = Node::create(client, "", "drawable", false);
|
||||
node.add_local_signal("createModel", model::create_flex);
|
||||
node.add_local_signal("createText", text::create_flex);
|
||||
node.add_local_signal("setSkyFile", set_sky_file_flex);
|
||||
node.add_to_scenegraph();
|
||||
}
|
||||
// #[instrument(level = "debug", skip(sk))]
|
||||
pub fn draw(sk: &impl StereoKitDraw) {
|
||||
lines::draw_all(sk);
|
||||
model::draw_all(sk);
|
||||
text::draw_all(sk);
|
||||
|
||||
pub fn draw(sk: &mut StereoKit, draw_ctx: &DrawContext) {
|
||||
model::draw_all(sk, draw_ctx);
|
||||
text::draw_all(sk, draw_ctx);
|
||||
|
||||
let new_skytex = QUEUED_SKYTEX.lock().take();
|
||||
let mut new_skylight = QUEUED_SKYLIGHT.lock().take();
|
||||
let same_file = new_skytex == new_skylight;
|
||||
|
||||
if let Some(skytex) = new_skytex {
|
||||
if let Some((skytex, skylight)) =
|
||||
Texture::from_cubemap_equirectangular(sk, &skytex, true, i32::MAX)
|
||||
{
|
||||
sk.set_skytex(&skytex);
|
||||
if same_file {
|
||||
sk.set_skylight(&skylight);
|
||||
new_skylight = None;
|
||||
}
|
||||
if let Some(skytex) = QUEUED_SKYTEX.lock().take() {
|
||||
if let Ok((_skylight, skytex)) = sk.tex_create_cubemap_file(&skytex, true, i32::MAX) {
|
||||
sk.render_set_skytex(&skytex);
|
||||
}
|
||||
}
|
||||
if let Some(skylight) = new_skylight {
|
||||
if let Some((_, skylight)) =
|
||||
Texture::from_cubemap_equirectangular(sk, &skylight, true, i32::MAX)
|
||||
{
|
||||
sk.set_skylight(&skylight);
|
||||
if let Some(skylight) = QUEUED_SKYLIGHT.lock().take() {
|
||||
if let Ok((skylight, _)) = sk.tex_create_cubemap_file(&skylight, true, i32::MAX) {
|
||||
sk.render_set_skylight(skylight);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -49,21 +39,83 @@ pub fn draw(sk: &mut StereoKit, draw_ctx: &DrawContext) {
|
||||
static QUEUED_SKYLIGHT: Mutex<Option<PathBuf>> = Mutex::new(None);
|
||||
static QUEUED_SKYTEX: Mutex<Option<PathBuf>> = Mutex::new(None);
|
||||
|
||||
fn set_sky_file_flex(_node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct SkyFileInfo {
|
||||
path: PathBuf,
|
||||
skytex: Option<bool>,
|
||||
skylight: Option<bool>,
|
||||
}
|
||||
let info: SkyFileInfo = deserialize(data)?;
|
||||
info.path.metadata()?;
|
||||
if info.skytex.unwrap_or_default() {
|
||||
QUEUED_SKYTEX.lock().replace(info.path.clone());
|
||||
}
|
||||
if info.skylight.unwrap_or_default() {
|
||||
QUEUED_SKYLIGHT.lock().replace(info.path);
|
||||
stardust_xr_server_codegen::codegen_drawable_protocol!();
|
||||
create_interface!(DrawableInterface, DrawableInterfaceAspect, "/drawable");
|
||||
|
||||
pub struct DrawableInterface;
|
||||
impl DrawableInterfaceAspect for DrawableInterface {
|
||||
fn set_sky_tex(_node: Arc<Node>, calling_client: Arc<Client>, tex: ResourceID) -> Result<()> {
|
||||
let resource_path = get_resource_file(&tex, &calling_client, &[OsStr::new("hdr")])
|
||||
.ok_or(eyre::eyre!("Could not find resource"))?;
|
||||
QUEUED_SKYTEX.lock().replace(resource_path);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Ok(())
|
||||
fn set_sky_light(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
light: ResourceID,
|
||||
) -> Result<()> {
|
||||
let resource_path = get_resource_file(&light, &calling_client, &[OsStr::new("hdr")])
|
||||
.ok_or(eyre::eyre!("Could not find resource"))?;
|
||||
QUEUED_SKYLIGHT.lock().replace(resource_path);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn create_lines(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
name: String,
|
||||
parent: Arc<Node>,
|
||||
transform: Transform,
|
||||
lines: Vec<Line>,
|
||||
) -> Result<()> {
|
||||
let node =
|
||||
Node::create_parent_name(&calling_client, Self::CREATE_LINES_PARENT_PATH, &name, true);
|
||||
let parent = parent.get_aspect::<Spatial>()?;
|
||||
let transform = transform.to_mat4(true, true, true);
|
||||
|
||||
let node = node.add_to_scenegraph()?;
|
||||
Spatial::add_to(&node, Some(parent.clone()), transform, false);
|
||||
Lines::add_to(&node, lines)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_model(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
name: String,
|
||||
parent: Arc<Node>,
|
||||
transform: Transform,
|
||||
model: ResourceID,
|
||||
) -> Result<()> {
|
||||
let node =
|
||||
Node::create_parent_name(&calling_client, Self::LOAD_MODEL_PARENT_PATH, &name, true);
|
||||
let parent = parent.get_aspect::<Spatial>()?;
|
||||
let transform = transform.to_mat4(true, true, true);
|
||||
let node = node.add_to_scenegraph()?;
|
||||
Spatial::add_to(&node, Some(parent.clone()), transform, false);
|
||||
Model::add_to(&node, model)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn create_text(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
name: String,
|
||||
parent: Arc<Node>,
|
||||
transform: Transform,
|
||||
text: String,
|
||||
style: TextStyle,
|
||||
) -> Result<()> {
|
||||
let node =
|
||||
Node::create_parent_name(&calling_client, Self::CREATE_TEXT_PARENT_PATH, &name, true);
|
||||
let parent = parent.get_aspect::<Spatial>()?;
|
||||
let transform = transform.to_mat4(true, true, true);
|
||||
|
||||
let node = node.add_to_scenegraph()?;
|
||||
Spatial::add_to(&node, Some(parent.clone()), transform, false);
|
||||
Text::add_to(&node, text, style)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,184 +1,340 @@
|
||||
use super::Node;
|
||||
use super::{MaterialParameter, ModelAspect, ModelPartAspect, Node};
|
||||
use crate::core::client::Client;
|
||||
use crate::core::destroy_queue;
|
||||
use crate::core::node_collections::LifeLinkedNodeMap;
|
||||
use crate::core::registry::Registry;
|
||||
use crate::core::resource::ResourceID;
|
||||
use crate::nodes::spatial::{find_spatial_parent, parse_transform, Spatial};
|
||||
use anyhow::{anyhow, ensure, Result};
|
||||
use crate::core::resource::get_resource_file;
|
||||
use crate::nodes::spatial::Spatial;
|
||||
use crate::nodes::Aspect;
|
||||
use crate::SK_MULTITHREAD;
|
||||
use color_eyre::eyre::{eyre, Result};
|
||||
use once_cell::sync::OnceCell;
|
||||
use parking_lot::Mutex;
|
||||
use prisma::{Rgb, Rgba};
|
||||
use portable_atomic::{AtomicBool, Ordering};
|
||||
use rustc_hash::FxHashMap;
|
||||
use send_wrapper::SendWrapper;
|
||||
use serde::Deserialize;
|
||||
use stardust_xr::schemas::flex::deserialize;
|
||||
use stardust_xr::values::Transform;
|
||||
use std::fmt::Error;
|
||||
use stardust_xr::values::ResourceID;
|
||||
|
||||
use std::ffi::OsStr;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use stereokit::lifecycle::DrawContext;
|
||||
use stereokit::material::Material;
|
||||
use stereokit::model::Model as SKModel;
|
||||
use stereokit::render::RenderLayer;
|
||||
use stereokit::texture::Texture;
|
||||
use stereokit::StereoKit;
|
||||
use std::sync::{Arc, Weak};
|
||||
use stereokit::named_colors::WHITE;
|
||||
use stereokit::{
|
||||
Bounds, Color128, Material, Model as SKModel, RenderLayer, Shader, StereoKitDraw,
|
||||
StereoKitMultiThread, Transparency,
|
||||
};
|
||||
|
||||
static MODEL_REGISTRY: Registry<Model> = Registry::new();
|
||||
static HOLDOUT_MATERIAL: OnceCell<Arc<Material>> = OnceCell::new();
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
#[serde(untagged)]
|
||||
pub enum MaterialParameter {
|
||||
Texture(PathBuf),
|
||||
impl MaterialParameter {
|
||||
fn apply_to_material(
|
||||
&self,
|
||||
client: &Client,
|
||||
sk: &impl StereoKitMultiThread,
|
||||
material: &Material,
|
||||
parameter_name: &str,
|
||||
) {
|
||||
match self {
|
||||
MaterialParameter::Bool(val) => {
|
||||
sk.material_set_bool(material, parameter_name, *val);
|
||||
}
|
||||
MaterialParameter::Int(val) => {
|
||||
sk.material_set_int(material, parameter_name, *val);
|
||||
}
|
||||
MaterialParameter::UInt(val) => {
|
||||
sk.material_set_uint(material, parameter_name, *val);
|
||||
}
|
||||
MaterialParameter::Float(val) => {
|
||||
sk.material_set_float(material, parameter_name, *val);
|
||||
}
|
||||
MaterialParameter::Vec2(val) => {
|
||||
sk.material_set_vector2(material, parameter_name, *val);
|
||||
}
|
||||
MaterialParameter::Vec3(val) => {
|
||||
sk.material_set_vector3(material, parameter_name, *val);
|
||||
}
|
||||
MaterialParameter::Color(val) => {
|
||||
sk.material_set_color(
|
||||
material,
|
||||
parameter_name,
|
||||
Color128::new(val.c.r, val.c.g, val.c.b, val.a),
|
||||
);
|
||||
}
|
||||
MaterialParameter::Texture(resource) => {
|
||||
let Some(texture_path) =
|
||||
get_resource_file(&resource, &client, &[OsStr::new("png"), OsStr::new("jpg")])
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if let Ok(tex) = sk.tex_create_file(texture_path, true, 0) {
|
||||
sk.material_set_texture(material, parameter_name, &tex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Model {
|
||||
pub struct ModelPart {
|
||||
id: i32,
|
||||
path: PathBuf,
|
||||
space: Arc<Spatial>,
|
||||
resource_id: ResourceID,
|
||||
pending_model_path: OnceCell<PathBuf>,
|
||||
pending_material_parameters: Mutex<FxHashMap<(u32, String), MaterialParameter>>,
|
||||
pub pending_material_replacements: Mutex<FxHashMap<u32, Arc<SendWrapper<Material>>>>,
|
||||
sk_model: OnceCell<SendWrapper<SKModel>>,
|
||||
model: Weak<Model>,
|
||||
pending_material_parameters: Mutex<FxHashMap<String, MaterialParameter>>,
|
||||
pending_material_replacement: Mutex<Option<Arc<Material>>>,
|
||||
}
|
||||
impl ModelPart {
|
||||
fn create_for_model(sk: &impl StereoKitMultiThread, model: &Arc<Model>, sk_model: &SKModel) {
|
||||
HOLDOUT_MATERIAL.get_or_init(|| {
|
||||
let mat = sk.material_copy(Material::UNLIT);
|
||||
sk.material_set_transparency(&mat, Transparency::None);
|
||||
sk.material_set_color(
|
||||
&mat,
|
||||
"color",
|
||||
stereokit::sys::color128 {
|
||||
r: 0.0,
|
||||
g: 0.0,
|
||||
b: 0.0,
|
||||
a: 0.0,
|
||||
},
|
||||
);
|
||||
Arc::new(mat)
|
||||
});
|
||||
|
||||
impl Model {
|
||||
pub fn add_to(node: &Arc<Node>, resource_id: ResourceID) -> Result<Arc<Model>> {
|
||||
ensure!(
|
||||
node.spatial.get().is_some(),
|
||||
"Internal: Node does not have a spatial attached!"
|
||||
);
|
||||
ensure!(
|
||||
node.model.get().is_none(),
|
||||
"Internal: Node already has a model attached!"
|
||||
);
|
||||
let model = Model {
|
||||
space: node.spatial.get().unwrap().clone(),
|
||||
resource_id,
|
||||
pending_model_path: OnceCell::new(),
|
||||
pending_material_parameters: Mutex::new(FxHashMap::default()),
|
||||
pending_material_replacements: Mutex::new(FxHashMap::default()),
|
||||
sk_model: OnceCell::new(),
|
||||
};
|
||||
node.add_local_signal("setMaterialParameter", Model::set_material_parameter);
|
||||
let model_arc = MODEL_REGISTRY.add(model);
|
||||
let _ = model_arc.pending_model_path.set(
|
||||
model_arc
|
||||
.resource_id
|
||||
.get_file(
|
||||
&node
|
||||
.get_client()
|
||||
.ok_or_else(|| anyhow!("Client not found"))?
|
||||
.base_resource_prefixes
|
||||
.lock()
|
||||
.clone(),
|
||||
)
|
||||
.ok_or_else(|| anyhow!("Resource not found"))?,
|
||||
);
|
||||
let _ = node.model.set(model_arc.clone());
|
||||
Ok(model_arc)
|
||||
let first_root_part = sk.model_node_get_root(sk_model);
|
||||
let mut current_option_part = Some(first_root_part);
|
||||
|
||||
while let Some(current_part) = &mut current_option_part {
|
||||
ModelPart::create(sk, model, sk_model, *current_part);
|
||||
|
||||
if let Some(child) = sk.model_node_child(sk_model, *current_part) {
|
||||
*current_part = child;
|
||||
} else if let Some(sibling) = sk.model_node_sibling(sk_model, *current_part) {
|
||||
*current_part = sibling;
|
||||
} else {
|
||||
while let Some(current_part) = &mut current_option_part {
|
||||
if let Some(sibling) = sk.model_node_sibling(sk_model, *current_part) {
|
||||
*current_part = sibling;
|
||||
break;
|
||||
}
|
||||
current_option_part = sk.model_node_parent(sk_model, *current_part);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn set_material_parameter(
|
||||
node: &Node,
|
||||
_calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct MaterialParameterInfo {
|
||||
idx: u32,
|
||||
name: String,
|
||||
value: MaterialParameter,
|
||||
}
|
||||
let info: MaterialParameterInfo = deserialize(data)?;
|
||||
fn create(
|
||||
sk: &impl StereoKitMultiThread,
|
||||
model: &Arc<Model>,
|
||||
sk_model: &SKModel,
|
||||
id: i32,
|
||||
) -> Option<Arc<Self>> {
|
||||
let parent_node = sk
|
||||
.model_node_parent(sk_model, id)
|
||||
.and_then(|id| model.parts.get(&id));
|
||||
let parent_part = parent_node
|
||||
.as_ref()
|
||||
.and_then(|node| node.get_aspect::<ModelPart>().ok());
|
||||
|
||||
node.model
|
||||
.get()
|
||||
let stardust_model_part = model.space.node()?;
|
||||
let client = stardust_model_part.get_client()?;
|
||||
let mut part_path = parent_part.map(|n| n.path.clone()).unwrap_or_default();
|
||||
part_path.push(sk.model_node_get_name(sk_model, id)?);
|
||||
let node = client.scenegraph.add_node(Node::create_parent_name(
|
||||
&client,
|
||||
stardust_model_part.get_path(),
|
||||
part_path.to_str()?,
|
||||
false,
|
||||
));
|
||||
let spatial_parent = parent_node
|
||||
.and_then(|n| n.get_aspect::<Spatial>().ok())
|
||||
.unwrap_or_else(|| model.space.clone());
|
||||
let space = Spatial::add_to(
|
||||
&node,
|
||||
Some(spatial_parent),
|
||||
sk.model_node_get_transform_local(sk_model, id),
|
||||
false,
|
||||
);
|
||||
|
||||
let _ = node
|
||||
.get_aspect::<Spatial>()
|
||||
.unwrap()
|
||||
.pending_material_parameters
|
||||
.lock()
|
||||
.insert((info.idx, info.name), info.value);
|
||||
.bounding_box_calc
|
||||
.set(|node| {
|
||||
let Ok(model_part) = node.get_aspect::<ModelPart>() else {
|
||||
return Bounds::default();
|
||||
};
|
||||
let Some(sk) = SK_MULTITHREAD.get() else {
|
||||
return Bounds::default();
|
||||
};
|
||||
let Some(model) = model_part.model.upgrade() else {
|
||||
return Bounds::default();
|
||||
};
|
||||
let Some(sk_model) = model.sk_model.get() else {
|
||||
return Bounds::default();
|
||||
};
|
||||
let Some(sk_mesh) = sk.model_node_get_mesh(sk_model, model_part.id) else {
|
||||
return Bounds::default();
|
||||
};
|
||||
sk.mesh_get_bounds(sk_mesh)
|
||||
});
|
||||
|
||||
let model_part = Arc::new(ModelPart {
|
||||
id,
|
||||
path: part_path,
|
||||
space,
|
||||
model: Arc::downgrade(model),
|
||||
pending_material_parameters: Mutex::new(FxHashMap::default()),
|
||||
pending_material_replacement: Mutex::new(None),
|
||||
});
|
||||
<ModelPart as ModelPartAspect>::add_node_members(&node);
|
||||
node.add_aspect_raw(model_part.clone());
|
||||
model.parts.add(id, &node);
|
||||
Some(model_part)
|
||||
}
|
||||
|
||||
pub fn replace_material(&self, replacement: Arc<Material>) {
|
||||
self.pending_material_replacement
|
||||
.lock()
|
||||
.replace(replacement);
|
||||
}
|
||||
|
||||
fn update(&self, sk: &impl StereoKitDraw) {
|
||||
let Some(model) = self.model.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let Some(sk_model) = model.sk_model.get() else {
|
||||
return;
|
||||
};
|
||||
let Some(node) = model.space.node() else {
|
||||
return;
|
||||
};
|
||||
let Some(client) = node.get_client() else {
|
||||
return;
|
||||
};
|
||||
if let Some(material_replacement) = self.pending_material_replacement.lock().take() {
|
||||
sk.model_node_set_material(sk_model, self.id, material_replacement.as_ref().as_ref());
|
||||
}
|
||||
|
||||
let mut material_parameters = self.pending_material_parameters.lock();
|
||||
for (parameter_name, parameter_value) in material_parameters.drain() {
|
||||
let Some(material) = sk.model_node_get_material(sk_model, self.id) else {
|
||||
continue;
|
||||
};
|
||||
let new_material = sk.material_copy(material);
|
||||
parameter_value.apply_to_material(&client, sk, &new_material, parameter_name.as_str());
|
||||
sk.model_node_set_material(sk_model, self.id, &new_material);
|
||||
}
|
||||
|
||||
sk.model_node_set_transform_model(
|
||||
sk_model,
|
||||
self.id,
|
||||
Spatial::space_to_space_matrix(Some(&self.space), Some(&model.space)),
|
||||
);
|
||||
}
|
||||
}
|
||||
impl Aspect for ModelPart {
|
||||
const NAME: &'static str = "ModelPart";
|
||||
}
|
||||
impl ModelPartAspect for ModelPart {
|
||||
#[doc = "Set this model part's material to one that cuts a hole in the world. Often used for overlays/passthrough where you want to show the background through an object."]
|
||||
fn apply_holdout_material(node: Arc<Node>, _calling_client: Arc<Client>) -> Result<()> {
|
||||
let model_part = node.get_aspect::<ModelPart>()?;
|
||||
model_part.replace_material(HOLDOUT_MATERIAL.get().unwrap().clone());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn draw(&self, sk: &StereoKit, draw_ctx: &DrawContext) {
|
||||
let sk_model = self
|
||||
.sk_model
|
||||
.get_or_try_init(|| {
|
||||
self.pending_model_path
|
||||
.get()
|
||||
.and_then(|path| SKModel::from_file(sk, path.as_path(), None))
|
||||
.as_ref()
|
||||
.cloned()
|
||||
.map(SendWrapper::new)
|
||||
.ok_or(Error)
|
||||
})
|
||||
.ok();
|
||||
#[doc = "Set the material parameter with `parameter_name` to `value`"]
|
||||
fn set_material_parameter(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
parameter_name: String,
|
||||
value: MaterialParameter,
|
||||
) -> Result<()> {
|
||||
let model_part = node.get_aspect::<ModelPart>()?;
|
||||
model_part
|
||||
.pending_material_parameters
|
||||
.lock()
|
||||
.insert(parameter_name, value);
|
||||
|
||||
if let Some(sk_model) = sk_model {
|
||||
{
|
||||
let mut material_replacements = self.pending_material_replacements.lock();
|
||||
for (material_idx, replacement_material) in material_replacements.iter() {
|
||||
sk_model.set_material(*material_idx as i32, replacement_material);
|
||||
}
|
||||
material_replacements.clear();
|
||||
}
|
||||
|
||||
{
|
||||
let mut material_parameters = self.pending_material_parameters.lock();
|
||||
for ((material_idx, parameter_name), parameter_value) in material_parameters.iter()
|
||||
{
|
||||
if let Some(material) = sk_model.get_material(sk, *material_idx as i32) {
|
||||
match parameter_value {
|
||||
MaterialParameter::Texture(path) => {
|
||||
if let Some(tex) = Texture::from_file(sk, path.as_path(), true, 0) {
|
||||
material.set_parameter(parameter_name.as_str(), &tex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
material_parameters.clear();
|
||||
}
|
||||
|
||||
let global_transform = self.space.global_transform().into();
|
||||
sk_model.draw(
|
||||
draw_ctx,
|
||||
global_transform,
|
||||
Rgba::new(Rgb::new(1_f32, 1_f32, 1_f32), 1_f32),
|
||||
RenderLayer::Layer0,
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Model {
|
||||
self_ref: Weak<Model>,
|
||||
enabled: Arc<AtomicBool>,
|
||||
space: Arc<Spatial>,
|
||||
_resource_id: ResourceID,
|
||||
sk_model: OnceCell<SKModel>,
|
||||
parts: LifeLinkedNodeMap<i32>,
|
||||
}
|
||||
unsafe impl Send for Model {}
|
||||
unsafe impl Sync for Model {}
|
||||
|
||||
impl Model {
|
||||
pub fn add_to(node: &Arc<Node>, resource_id: ResourceID) -> Result<Arc<Model>> {
|
||||
let pending_model_path = get_resource_file(
|
||||
&resource_id,
|
||||
&*node.get_client().ok_or_else(|| eyre!("Client not found"))?,
|
||||
&[OsStr::new("glb"), OsStr::new("gltf")],
|
||||
)
|
||||
.ok_or_else(|| eyre!("Resource not found"))?;
|
||||
|
||||
let model = Arc::new_cyclic(|self_ref| Model {
|
||||
self_ref: self_ref.clone(),
|
||||
enabled: node.enabled.clone(),
|
||||
space: node.get_aspect::<Spatial>().unwrap().clone(),
|
||||
_resource_id: resource_id,
|
||||
sk_model: OnceCell::new(),
|
||||
parts: LifeLinkedNodeMap::default(),
|
||||
});
|
||||
MODEL_REGISTRY.add_raw(&model);
|
||||
|
||||
let sk = SK_MULTITHREAD.get().unwrap();
|
||||
let sk_model = sk.model_copy(
|
||||
sk.model_create_file(pending_model_path.to_str().unwrap(), None::<Shader>)?,
|
||||
);
|
||||
ModelPart::create_for_model(sk, &model.self_ref.upgrade().unwrap(), &sk_model);
|
||||
let _ = model.sk_model.set(sk_model);
|
||||
node.add_aspect_raw(model.clone());
|
||||
Ok(model)
|
||||
}
|
||||
|
||||
fn draw(&self, sk: &impl StereoKitDraw) {
|
||||
let Some(sk_model) = self.sk_model.get() else {
|
||||
return;
|
||||
};
|
||||
for model_node_node in self.parts.nodes() {
|
||||
if let Ok(model_node) = model_node_node.get_aspect::<ModelPart>() {
|
||||
model_node.update(sk);
|
||||
};
|
||||
}
|
||||
|
||||
sk.model_draw(
|
||||
sk_model,
|
||||
self.space.global_transform(),
|
||||
WHITE,
|
||||
RenderLayer::LAYER0,
|
||||
);
|
||||
}
|
||||
}
|
||||
impl Aspect for Model {
|
||||
const NAME: &'static str = "Model";
|
||||
}
|
||||
impl ModelAspect for Model {}
|
||||
impl Drop for Model {
|
||||
fn drop(&mut self) {
|
||||
if let Some(model) = self.sk_model.take() {
|
||||
destroy_queue::add(model);
|
||||
if let Some(sk_model) = self.sk_model.take() {
|
||||
destroy_queue::add(sk_model);
|
||||
}
|
||||
MODEL_REGISTRY.remove(self);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn draw_all(sk: &StereoKit, draw_ctx: &DrawContext) {
|
||||
pub fn draw_all(sk: &impl StereoKitDraw) {
|
||||
for model in MODEL_REGISTRY.get_valid_contents() {
|
||||
model.draw(sk, draw_ctx);
|
||||
if model.enabled.load(Ordering::Relaxed) {
|
||||
model.draw(sk);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_flex(_node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct CreateModelInfo<'a> {
|
||||
name: &'a str,
|
||||
parent_path: &'a str,
|
||||
transform: Transform,
|
||||
resource: ResourceID,
|
||||
}
|
||||
let info: CreateModelInfo = deserialize(data)?;
|
||||
let node = Node::create(&calling_client, "/drawable/model", info.name, true);
|
||||
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||
let transform = parse_transform(info.transform, true, true, true)?;
|
||||
let node = node.add_to_scenegraph();
|
||||
Spatial::add_to(&node, Some(parent), transform)?;
|
||||
Model::add_to(&node, info.resource)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
144
src/nodes/drawable/shaders/mod.rs
Normal file
144
src/nodes/drawable/shaders/mod.rs
Normal file
@@ -0,0 +1,144 @@
|
||||
#![allow(dead_code)]
|
||||
use smithay::backend::renderer::gles::{
|
||||
ffi::{self, Gles2, FRAGMENT_SHADER, VERTEX_SHADER},
|
||||
GlesError,
|
||||
};
|
||||
use std::mem::transmute;
|
||||
use stereokit::Shader;
|
||||
use tracing::error;
|
||||
|
||||
// Simula shader with fancy lanzcos sampling
|
||||
pub const UNLIT_SHADER_BYTES: &[u8] = include_bytes!("shader_unlit_gamma.sks");
|
||||
|
||||
// Simula shader with fancy lanzcos sampling
|
||||
pub const PANEL_SHADER_BYTES: &[u8] = include_bytes!("shader_unlit_simula.sks");
|
||||
|
||||
struct FfiAssetHeader {
|
||||
asset_type: i32,
|
||||
asset_state: i32,
|
||||
id: u64,
|
||||
index: u64,
|
||||
refs: i32,
|
||||
debug: *mut u8,
|
||||
}
|
||||
|
||||
struct FfiSkgShader {
|
||||
meta: *mut u8,
|
||||
vertex: u32,
|
||||
pixel: u32,
|
||||
program: u32,
|
||||
compute: u32,
|
||||
}
|
||||
|
||||
struct FfiShader {
|
||||
header: FfiAssetHeader,
|
||||
shader: FfiSkgShader,
|
||||
}
|
||||
|
||||
unsafe fn compile_shader(
|
||||
gl: &ffi::Gles2,
|
||||
variant: ffi::types::GLuint,
|
||||
src: &str,
|
||||
) -> Result<ffi::types::GLuint, GlesError> {
|
||||
let shader = gl.CreateShader(variant);
|
||||
if shader == 0 {
|
||||
return Err(GlesError::CreateShaderObject);
|
||||
}
|
||||
|
||||
gl.ShaderSource(
|
||||
shader,
|
||||
1,
|
||||
&src.as_ptr() as *const *const u8 as *const *const ffi::types::GLchar,
|
||||
&(src.len() as i32) as *const _,
|
||||
);
|
||||
gl.CompileShader(shader);
|
||||
|
||||
let mut status = ffi::FALSE as i32;
|
||||
gl.GetShaderiv(shader, ffi::COMPILE_STATUS, &mut status as *mut _);
|
||||
if status == ffi::FALSE as i32 {
|
||||
let mut max_len = 0;
|
||||
gl.GetShaderiv(shader, ffi::INFO_LOG_LENGTH, &mut max_len as *mut _);
|
||||
|
||||
let mut error = Vec::with_capacity(max_len as usize);
|
||||
let mut len = 0;
|
||||
gl.GetShaderInfoLog(
|
||||
shader,
|
||||
max_len as _,
|
||||
&mut len as *mut _,
|
||||
error.as_mut_ptr() as *mut _,
|
||||
);
|
||||
error.set_len(len as usize);
|
||||
|
||||
error!(
|
||||
"[GL] {}",
|
||||
std::str::from_utf8(&error).unwrap_or("<Error Message no utf8>")
|
||||
);
|
||||
|
||||
gl.DeleteShader(shader);
|
||||
return Err(GlesError::ShaderCompileError);
|
||||
}
|
||||
|
||||
Ok(shader)
|
||||
}
|
||||
|
||||
unsafe fn link_program(
|
||||
gl: &ffi::Gles2,
|
||||
vert: ffi::types::GLuint,
|
||||
frag: ffi::types::GLuint,
|
||||
) -> Result<ffi::types::GLuint, GlesError> {
|
||||
let program = gl.CreateProgram();
|
||||
gl.AttachShader(program, vert);
|
||||
gl.AttachShader(program, frag);
|
||||
gl.LinkProgram(program);
|
||||
// gl.DetachShader(program, vert);
|
||||
// gl.DetachShader(program, frag);
|
||||
// gl.DeleteShader(vert);
|
||||
// gl.DeleteShader(frag);
|
||||
|
||||
let mut status = ffi::FALSE as i32;
|
||||
gl.GetProgramiv(program, ffi::LINK_STATUS, &mut status as *mut _);
|
||||
if status == ffi::FALSE as i32 {
|
||||
let mut max_len = 0;
|
||||
gl.GetProgramiv(program, ffi::INFO_LOG_LENGTH, &mut max_len as *mut _);
|
||||
|
||||
let mut error = Vec::with_capacity(max_len as usize);
|
||||
let mut len = 0;
|
||||
gl.GetProgramInfoLog(
|
||||
program,
|
||||
max_len as _,
|
||||
&mut len as *mut _,
|
||||
error.as_mut_ptr() as *mut _,
|
||||
);
|
||||
error.set_len(len as usize);
|
||||
|
||||
error!(
|
||||
"[GL] {}",
|
||||
std::str::from_utf8(&error).unwrap_or("<Error Message no utf8>")
|
||||
);
|
||||
|
||||
gl.DeleteProgram(program);
|
||||
return Err(GlesError::ProgramLinkError);
|
||||
}
|
||||
|
||||
Ok(program)
|
||||
}
|
||||
|
||||
pub unsafe fn shader_inject(
|
||||
c: &Gles2,
|
||||
sk_shader: &mut Shader,
|
||||
vert_str: &str,
|
||||
frag_str: &str,
|
||||
) -> Result<(), GlesError> {
|
||||
let gl_vert = compile_shader(c, VERTEX_SHADER, vert_str)?;
|
||||
let gl_frag = compile_shader(c, FRAGMENT_SHADER, frag_str)?;
|
||||
let gl_prog = link_program(c, gl_vert, gl_frag)?;
|
||||
|
||||
let shader: *mut FfiShader = transmute(sk_shader.0.as_mut());
|
||||
if let Some(shader) = shader.as_mut() {
|
||||
shader.shader.vertex = gl_vert;
|
||||
shader.shader.pixel = gl_frag;
|
||||
shader.shader.program = gl_prog;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -28,7 +28,7 @@ psIn vs(vsIn input, uint id : SV_InstanceID) {
|
||||
float3 world = mul(float4(input.pos.xyz, 1), sk_inst[id].world).xyz;
|
||||
o.pos = mul(float4(world, 1), sk_viewproj[o.view_id]);
|
||||
|
||||
o.uv = (input.uv) + uv_offset * uv_scale;
|
||||
o.uv = (input.uv + uv_offset) * uv_scale;
|
||||
return o;
|
||||
}
|
||||
float4 ps(psIn input) : SV_TARGET {
|
||||
Binary file not shown.
@@ -4,19 +4,19 @@
|
||||
|
||||
//--name = stardust/text_shader
|
||||
//--diffuse = white
|
||||
//--fcFactor = 1.0
|
||||
//--ripple = 4.0
|
||||
//--uv_offset = 0.0, 0.0
|
||||
//--uv_scale = 1.0, 1.0
|
||||
//--fcFactor = 1.0
|
||||
//--ripple = 4.0
|
||||
//--alpha_min = 0.0
|
||||
//--alpha_max = 1.0
|
||||
Texture2D diffuse : register(t0);
|
||||
SamplerState diffuse_s : register(s0);
|
||||
float4 diffuse_i;
|
||||
float fcFactor;
|
||||
float ripple;
|
||||
float2 uv_scale;
|
||||
float2 uv_offset;
|
||||
float fcFactor;
|
||||
float ripple;
|
||||
float alpha_min;
|
||||
float alpha_max;
|
||||
|
||||
@@ -39,7 +39,7 @@ psIn vs(vsIn input, uint id : SV_InstanceID) {
|
||||
float3 world = mul(float4(input.pos.xyz, 1), sk_inst[id].world).xyz;
|
||||
o.pos = mul(float4(world, 1), sk_viewproj[o.view_id]);
|
||||
|
||||
o.uv = (input.uv) + uv_offset * uv_scale;
|
||||
o.uv = (input.uv + uv_offset) * uv_scale;
|
||||
return o;
|
||||
}
|
||||
|
||||
Binary file not shown.
@@ -1,112 +1,79 @@
|
||||
use crate::{
|
||||
core::{client::Client, destroy_queue, registry::Registry, resource::ResourceID},
|
||||
nodes::{
|
||||
spatial::{find_spatial_parent, parse_transform, Spatial},
|
||||
Node,
|
||||
},
|
||||
core::{client::Client, destroy_queue, registry::Registry, resource::get_resource_file},
|
||||
nodes::{spatial::Spatial, Aspect, Node},
|
||||
};
|
||||
use anyhow::{anyhow, ensure, Result};
|
||||
use color_eyre::eyre::{eyre, Result};
|
||||
use glam::{vec3, Mat4, Vec2};
|
||||
use mint::Vector2;
|
||||
use once_cell::sync::OnceCell;
|
||||
use parking_lot::Mutex;
|
||||
use prisma::{Flatten, Rgb, Rgba};
|
||||
use send_wrapper::SendWrapper;
|
||||
use serde::Deserialize;
|
||||
use stardust_xr::{schemas::flex::deserialize, values::Transform};
|
||||
use std::{path::PathBuf, sync::Arc};
|
||||
use portable_atomic::{AtomicBool, Ordering};
|
||||
use std::{ffi::OsStr, path::PathBuf, sync::Arc};
|
||||
use stereokit::{
|
||||
font::Font,
|
||||
lifecycle::DrawContext,
|
||||
text::{self, TextAlign, TextFit, TextStyle},
|
||||
StereoKit,
|
||||
named_colors::WHITE, Color128, StereoKitDraw, TextAlign, TextFit, TextStyle as SkTextStyle,
|
||||
};
|
||||
|
||||
use super::{TextAspect, TextStyle};
|
||||
|
||||
static TEXT_REGISTRY: Registry<Text> = Registry::new();
|
||||
|
||||
struct TextData {
|
||||
text: String,
|
||||
character_height: f32,
|
||||
text_align: TextAlign,
|
||||
bounds: Option<Vec2>,
|
||||
fit: TextFit,
|
||||
bounds_align: TextAlign,
|
||||
color: Rgba<f32>,
|
||||
fn convert_align(x_align: super::XAlign, y_align: super::YAlign) -> TextAlign {
|
||||
let x_align = match x_align {
|
||||
super::XAlign::Left => TextAlign::XLeft,
|
||||
super::XAlign::Center => TextAlign::XCenter,
|
||||
super::XAlign::Right => TextAlign::XRight,
|
||||
} as u32;
|
||||
let y_align = match y_align {
|
||||
super::YAlign::Top => TextAlign::YTop,
|
||||
super::YAlign::Center => TextAlign::YCenter,
|
||||
super::YAlign::Bottom => TextAlign::YBottom,
|
||||
} as u32;
|
||||
|
||||
unsafe { std::mem::transmute(x_align | y_align) }
|
||||
}
|
||||
|
||||
pub struct Text {
|
||||
enabled: Arc<AtomicBool>,
|
||||
space: Arc<Spatial>,
|
||||
font_path: Option<PathBuf>,
|
||||
style: OnceCell<SendWrapper<TextStyle>>,
|
||||
style: OnceCell<SkTextStyle>,
|
||||
|
||||
data: Mutex<TextData>,
|
||||
text: Mutex<String>,
|
||||
data: Mutex<TextStyle>,
|
||||
}
|
||||
impl Text {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn add_to(
|
||||
node: &Arc<Node>,
|
||||
font_resource_id: Option<ResourceID>,
|
||||
text: String,
|
||||
character_height: f32,
|
||||
text_align: TextAlign,
|
||||
bounds: Option<Vector2<f32>>,
|
||||
fit: TextFit,
|
||||
bounds_align: TextAlign,
|
||||
color: Rgba<f32>,
|
||||
) -> Result<Arc<Text>> {
|
||||
ensure!(
|
||||
node.spatial.get().is_some(),
|
||||
"Internal: Node does not have a spatial attached!"
|
||||
);
|
||||
ensure!(
|
||||
node.model.get().is_none(),
|
||||
"Internal: Node already has text attached!"
|
||||
);
|
||||
|
||||
let client = node
|
||||
.get_client()
|
||||
.ok_or_else(|| anyhow!("Client not found"))?;
|
||||
pub fn add_to(node: &Arc<Node>, text: String, style: TextStyle) -> Result<Arc<Text>> {
|
||||
let client = node.get_client().ok_or_else(|| eyre!("Client not found"))?;
|
||||
let text = TEXT_REGISTRY.add(Text {
|
||||
space: node.spatial.get().unwrap().clone(),
|
||||
font_path: font_resource_id
|
||||
.and_then(|res| res.get_file(&client.base_resource_prefixes.lock().clone())),
|
||||
enabled: node.enabled.clone(),
|
||||
space: node.get_aspect::<Spatial>().unwrap().clone(),
|
||||
font_path: style.font.as_ref().and_then(|res| {
|
||||
get_resource_file(&res, &client, &[OsStr::new("ttf"), OsStr::new("otf")])
|
||||
}),
|
||||
style: OnceCell::new(),
|
||||
|
||||
data: Mutex::new(TextData {
|
||||
text,
|
||||
character_height,
|
||||
text_align,
|
||||
bounds: bounds.map(|b| b.into()),
|
||||
fit,
|
||||
bounds_align,
|
||||
color,
|
||||
}),
|
||||
text: Mutex::new(text),
|
||||
data: Mutex::new(style),
|
||||
});
|
||||
node.add_local_signal("setCharacterHeight", Text::set_character_height_flex);
|
||||
node.add_local_signal("setText", Text::set_text_flex);
|
||||
let _ = node.text.set(text.clone());
|
||||
<Text as TextAspect>::add_node_members(node);
|
||||
node.add_aspect_raw(text.clone());
|
||||
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
fn draw(&self, sk: &StereoKit, draw_ctx: &DrawContext) {
|
||||
fn draw(&self, sk: &impl StereoKitDraw) {
|
||||
let style =
|
||||
self.style
|
||||
.get_or_try_init(|| -> Result<SendWrapper<TextStyle>, anyhow::Error> {
|
||||
let font = if let Some(path) = self.font_path.as_deref() {
|
||||
Font::from_file(sk, path)
|
||||
} else {
|
||||
Some(Font::default(sk))
|
||||
};
|
||||
Ok(SendWrapper::new(TextStyle::new(
|
||||
sk,
|
||||
font.ok_or(std::fmt::Error)?,
|
||||
1.0,
|
||||
Rgba::new(Rgb::new(1.0, 1.0, 1.0), 1.0),
|
||||
)))
|
||||
.get_or_try_init(|| -> Result<SkTextStyle, color_eyre::eyre::Error> {
|
||||
let font = self
|
||||
.font_path
|
||||
.as_deref()
|
||||
.and_then(|path| sk.font_create(path).ok())
|
||||
.unwrap_or_else(|| sk.font_find("default/font").unwrap());
|
||||
Ok(unsafe { sk.text_make_style(font, 1.0, WHITE) })
|
||||
});
|
||||
|
||||
if let Ok(style) = style {
|
||||
let text = self.text.lock();
|
||||
let data = self.data.lock();
|
||||
let transform = self.space.global_transform()
|
||||
* Mat4::from_scale(vec3(
|
||||
@@ -114,47 +81,55 @@ impl Text {
|
||||
data.character_height,
|
||||
data.character_height,
|
||||
));
|
||||
if let Some(bounds) = data.bounds {
|
||||
text::draw_in(
|
||||
draw_ctx,
|
||||
&data.text,
|
||||
if let Some(bounds) = &data.bounds {
|
||||
sk.text_add_in(
|
||||
&*text,
|
||||
transform,
|
||||
bounds / data.character_height,
|
||||
data.fit,
|
||||
style,
|
||||
data.bounds_align,
|
||||
data.text_align,
|
||||
Vec2::from(bounds.bounds) / data.character_height,
|
||||
match bounds.fit {
|
||||
super::TextFit::Wrap => TextFit::Wrap,
|
||||
super::TextFit::Clip => TextFit::Clip,
|
||||
super::TextFit::Squeeze => TextFit::Squeeze,
|
||||
super::TextFit::Exact => TextFit::Exact,
|
||||
super::TextFit::Overflow => TextFit::Overflow,
|
||||
},
|
||||
*style,
|
||||
convert_align(bounds.anchor_align_x.clone(), bounds.anchor_align_y.clone()),
|
||||
convert_align(data.text_align_x.clone(), data.text_align_y.clone()),
|
||||
vec3(0.0, 0.0, 0.0),
|
||||
data.color,
|
||||
Color128::from([data.color.c.r, data.color.c.g, data.color.c.b, data.color.a]),
|
||||
);
|
||||
} else {
|
||||
text::draw_at(
|
||||
draw_ctx,
|
||||
&data.text,
|
||||
sk.text_add_at(
|
||||
&*text,
|
||||
transform,
|
||||
style,
|
||||
data.bounds_align,
|
||||
data.text_align,
|
||||
*style,
|
||||
TextAlign::Center,
|
||||
convert_align(data.text_align_x.clone(), data.text_align_y.clone()),
|
||||
vec3(0.0, 0.0, 0.0),
|
||||
data.color,
|
||||
Color128::from([data.color.c.r, data.color.c.g, data.color.c.b, data.color.a]),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_character_height_flex(
|
||||
node: &Node,
|
||||
}
|
||||
impl Aspect for Text {
|
||||
const NAME: &'static str = "Text";
|
||||
}
|
||||
impl TextAspect for Text {
|
||||
fn set_character_height(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
height: f32,
|
||||
) -> Result<()> {
|
||||
let height = flexbuffers::Reader::get_root(data)?.get_f64()? as f32;
|
||||
node.text.get().unwrap().data.lock().character_height = height;
|
||||
let this_text = node.get_aspect::<Text>()?;
|
||||
this_text.data.lock().character_height = height;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_text_flex(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
let text = flexbuffers::Reader::get_root(data)?.get_str()?.to_string();
|
||||
node.text.get().unwrap().data.lock().text = text;
|
||||
fn set_text(node: Arc<Node>, _calling_client: Arc<Client>, text: String) -> Result<()> {
|
||||
let this_text = node.get_aspect::<Text>()?;
|
||||
*this_text.text.lock() = text;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -167,45 +142,10 @@ impl Drop for Text {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn draw_all(sk: &StereoKit, draw_ctx: &DrawContext) {
|
||||
pub fn draw_all(sk: &impl StereoKitDraw) {
|
||||
for text in TEXT_REGISTRY.get_valid_contents() {
|
||||
text.draw(sk, draw_ctx);
|
||||
if text.enabled.load(Ordering::Relaxed) {
|
||||
text.draw(sk);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_flex(_node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct CreateTextInfo<'a> {
|
||||
name: &'a str,
|
||||
parent_path: &'a str,
|
||||
transform: Transform,
|
||||
text: String,
|
||||
font_resource: Option<ResourceID>,
|
||||
character_height: f32,
|
||||
text_align: TextAlign,
|
||||
bounds: Option<Vector2<f32>>,
|
||||
fit: TextFit,
|
||||
bounds_align: TextAlign,
|
||||
color: [f32; 4],
|
||||
}
|
||||
let info: CreateTextInfo = deserialize(data)?;
|
||||
let node = Node::create(&calling_client, "/drawable/text", info.name, true);
|
||||
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||
let transform = parse_transform(info.transform, true, true, true)?;
|
||||
let color = Rgba::from_slice(&info.color);
|
||||
|
||||
let node = node.add_to_scenegraph();
|
||||
Spatial::add_to(&node, Some(parent), transform)?;
|
||||
Text::add_to(
|
||||
&node,
|
||||
info.font_resource,
|
||||
info.text,
|
||||
info.character_height,
|
||||
info.text_align,
|
||||
info.bounds,
|
||||
info.fit,
|
||||
info.bounds_align,
|
||||
color,
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
use super::{Field, FieldTrait, Node};
|
||||
use crate::core::client::Client;
|
||||
use crate::nodes::spatial::{find_spatial_parent, parse_transform, Spatial};
|
||||
use anyhow::{ensure, Result};
|
||||
use super::{BoxFieldAspect, FieldTrait, Node};
|
||||
use crate::nodes::fields::FieldAspect;
|
||||
use crate::nodes::spatial::Spatial;
|
||||
use crate::{core::client::Client, nodes::fields::Field};
|
||||
use color_eyre::eyre::Result;
|
||||
use glam::{vec3, vec3a, Vec3, Vec3A};
|
||||
use mint::Vector3;
|
||||
use parking_lot::Mutex;
|
||||
use serde::Deserialize;
|
||||
use stardust_xr::schemas::flex::deserialize;
|
||||
use stardust_xr::values::Transform;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct BoxField {
|
||||
@@ -16,35 +14,19 @@ pub struct BoxField {
|
||||
}
|
||||
|
||||
impl BoxField {
|
||||
pub fn add_to(node: &Arc<Node>, size: Vector3<f32>) -> Result<()> {
|
||||
ensure!(
|
||||
node.spatial.get().is_some(),
|
||||
"Internal: Node does not have a spatial attached!"
|
||||
);
|
||||
ensure!(
|
||||
node.field.get().is_none(),
|
||||
"Internal: Node already has a field attached!"
|
||||
);
|
||||
pub fn add_to(node: &Arc<Node>, size: Vector3<f32>) {
|
||||
let box_field = BoxField {
|
||||
space: node.spatial.get().unwrap().clone(),
|
||||
space: node.get_aspect::<Spatial>().unwrap().clone(),
|
||||
size: Mutex::new(size.into()),
|
||||
};
|
||||
box_field.add_field_methods(node);
|
||||
node.add_local_signal("setSize", BoxField::set_size_flex);
|
||||
let _ = node.field.set(Arc::new(Field::Box(box_field)));
|
||||
Ok(())
|
||||
<BoxField as FieldAspect>::add_node_members(node);
|
||||
<BoxField as BoxFieldAspect>::add_node_members(node);
|
||||
node.add_aspect(Field::Box(box_field));
|
||||
}
|
||||
|
||||
pub fn set_size(&self, size: Vector3<f32>) {
|
||||
*self.size.lock() = size.into();
|
||||
}
|
||||
|
||||
pub fn set_size_flex(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
if let Field::Box(box_field) = node.field.get().unwrap().as_ref() {
|
||||
box_field.set_size(deserialize(data)?);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl FieldTrait for BoxField {
|
||||
@@ -62,21 +44,17 @@ impl FieldTrait for BoxField {
|
||||
self.space.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_box_field_flex(_node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct CreateFieldInfo<'a> {
|
||||
name: &'a str,
|
||||
parent_path: &'a str,
|
||||
transform: Transform,
|
||||
size: Vector3<f32>,
|
||||
impl BoxFieldAspect for BoxField {
|
||||
fn set_size(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
size: mint::Vector3<f32>,
|
||||
) -> Result<()> {
|
||||
let this_field = node.get_aspect::<Field>()?;
|
||||
let Field::Box(this_field) = &*this_field else {
|
||||
return Ok(());
|
||||
};
|
||||
this_field.set_size(size.into());
|
||||
Ok(())
|
||||
}
|
||||
let info: CreateFieldInfo = deserialize(data)?;
|
||||
let node = Node::create(&calling_client, "/field", info.name, true);
|
||||
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||
let transform = parse_transform(info.transform, true, true, false)?;
|
||||
let node = node.add_to_scenegraph();
|
||||
Spatial::add_to(&node, Some(parent), transform)?;
|
||||
BoxField::add_to(&node, info.size)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
use super::{Field, FieldTrait, Node};
|
||||
use super::{CylinderFieldAspect, Field, FieldTrait, Node};
|
||||
use crate::core::client::Client;
|
||||
use crate::nodes::spatial::{find_spatial_parent, parse_transform, Spatial};
|
||||
use anyhow::{ensure, Result};
|
||||
use crate::nodes::fields::FieldAspect;
|
||||
use crate::nodes::spatial::Spatial;
|
||||
use color_eyre::eyre::Result;
|
||||
use glam::{swizzles::*, vec2, Vec3A};
|
||||
use portable_atomic::AtomicF32;
|
||||
use serde::Deserialize;
|
||||
use stardust_xr::schemas::flex::deserialize;
|
||||
use stardust_xr::values::Transform;
|
||||
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::Arc;
|
||||
@@ -18,40 +16,22 @@ pub struct CylinderField {
|
||||
}
|
||||
|
||||
impl CylinderField {
|
||||
pub fn add_to(node: &Arc<Node>, length: f32, radius: f32) -> Result<()> {
|
||||
ensure!(
|
||||
node.spatial.get().is_some(),
|
||||
"Internal: Node does not have a spatial attached!"
|
||||
);
|
||||
ensure!(
|
||||
node.field.get().is_none(),
|
||||
"Internal: Node already has a field attached!"
|
||||
);
|
||||
pub fn add_to(node: &Arc<Node>, length: f32, radius: f32) {
|
||||
let cylinder_field = CylinderField {
|
||||
space: node.spatial.get().unwrap().clone(),
|
||||
space: node.get_aspect::<Spatial>().unwrap().clone(),
|
||||
length: AtomicF32::new(length.abs()),
|
||||
radius: AtomicF32::new(radius.abs()),
|
||||
};
|
||||
cylinder_field.add_field_methods(node);
|
||||
node.add_local_signal("setSize", CylinderField::set_size_flex);
|
||||
let _ = node.field.set(Arc::new(Field::Cylinder(cylinder_field)));
|
||||
Ok(())
|
||||
<CylinderField as FieldAspect>::add_node_members(node);
|
||||
<CylinderField as CylinderFieldAspect>::add_node_members(node);
|
||||
node.add_aspect(Field::Cylinder(cylinder_field));
|
||||
}
|
||||
|
||||
pub fn set_size(&self, length: f32, radius: f32) {
|
||||
self.length.store(length.abs(), Ordering::Relaxed);
|
||||
self.radius.store(radius.abs(), Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn set_size_flex(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
if let Field::Cylinder(cylinder_field) = node.field.get().unwrap().as_ref() {
|
||||
let (length, radius) = deserialize(data)?;
|
||||
cylinder_field.set_size(length, radius);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl FieldTrait for CylinderField {
|
||||
fn local_distance(&self, p: Vec3A) -> f32 {
|
||||
let radius = self.radius.load(Ordering::Relaxed);
|
||||
@@ -64,26 +44,18 @@ impl FieldTrait for CylinderField {
|
||||
self.space.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_cylinder_field_flex(
|
||||
_node: &Node,
|
||||
calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct CreateFieldInfo<'a> {
|
||||
name: &'a str,
|
||||
parent_path: &'a str,
|
||||
transform: Transform,
|
||||
impl CylinderFieldAspect for CylinderField {
|
||||
fn set_size(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
length: f32,
|
||||
radius: f32,
|
||||
) -> Result<()> {
|
||||
let this_field = node.get_aspect::<Field>()?;
|
||||
let Field::Cylinder(this_field) = &*this_field else {
|
||||
return Ok(());
|
||||
};
|
||||
this_field.set_size(length, radius);
|
||||
Ok(())
|
||||
}
|
||||
let info: CreateFieldInfo = deserialize(data)?;
|
||||
let node = Node::create(&calling_client, "/field", info.name, true);
|
||||
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||
let transform = parse_transform(info.transform, true, true, false)?;
|
||||
let node = node.add_to_scenegraph();
|
||||
Spatial::add_to(&node, Some(parent), transform)?;
|
||||
CylinderField::add_to(&node, dbg!(info.length), dbg!(info.radius))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,25 +1,38 @@
|
||||
mod r#box;
|
||||
pub mod r#box;
|
||||
mod cylinder;
|
||||
mod sphere;
|
||||
mod torus;
|
||||
|
||||
use self::cylinder::{create_cylinder_field_flex, CylinderField};
|
||||
use self::r#box::{create_box_field_flex, BoxField};
|
||||
use self::sphere::{create_sphere_field_flex, SphereField};
|
||||
use self::cylinder::CylinderField;
|
||||
use self::r#box::BoxField;
|
||||
use self::sphere::SphereField;
|
||||
use self::torus::TorusField;
|
||||
|
||||
use super::alias::AliasInfo;
|
||||
use super::spatial::Spatial;
|
||||
use super::Node;
|
||||
use super::{Aspect, Node};
|
||||
use crate::core::client::Client;
|
||||
use crate::nodes::spatial::find_reference_space;
|
||||
use anyhow::Result;
|
||||
use glam::{vec2, vec3a, Vec3, Vec3A};
|
||||
use crate::create_interface;
|
||||
use crate::nodes::spatial::Transform;
|
||||
use color_eyre::eyre::Result;
|
||||
use glam::{vec2, vec3a, Mat4, Vec3, Vec3A};
|
||||
use mint::Vector3;
|
||||
use serde::Deserialize;
|
||||
use stardust_xr::schemas::flex::{deserialize, serialize};
|
||||
|
||||
use once_cell::sync::Lazy;
|
||||
use std::ops::Deref;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub trait FieldTrait {
|
||||
// TODO: get SDFs working properly with non-uniform scale and so on, output distance relative to the spatial it's compared against
|
||||
|
||||
pub static FIELD_ALIAS_INFO: Lazy<AliasInfo> = Lazy::new(|| AliasInfo {
|
||||
server_methods: vec!["distance", "normal", "closest_point", "ray_march"],
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
stardust_xr_server_codegen::codegen_field_protocol!();
|
||||
|
||||
pub trait FieldTrait: Send + Sync + 'static {
|
||||
fn spatial_ref(&self) -> &Spatial;
|
||||
|
||||
fn local_distance(&self, p: Vec3A) -> f32;
|
||||
fn local_normal(&self, p: Vec3A, r: f32) -> Vec3A {
|
||||
let d = self.local_distance(p);
|
||||
@@ -61,93 +74,94 @@ pub trait FieldTrait {
|
||||
.transform_point3a(self.local_closest_point(local_p, r))
|
||||
}
|
||||
|
||||
fn add_field_methods(&self, node: &Arc<Node>) {
|
||||
node.add_local_method("distance", field_distance_flex);
|
||||
node.add_local_method("normal", field_normal_flex);
|
||||
node.add_local_method("closest_point", field_closest_point_flex);
|
||||
}
|
||||
fn ray_march(&self, ray: Ray) -> RayMarchResult {
|
||||
let mut result = RayMarchResult {
|
||||
ray_origin: ray.origin.into(),
|
||||
ray_direction: ray.direction.into(),
|
||||
min_distance: f32::MAX,
|
||||
deepest_point_distance: 0_f32,
|
||||
ray_length: 0_f32,
|
||||
ray_steps: 0,
|
||||
};
|
||||
|
||||
fn spatial_ref(&self) -> &Spatial;
|
||||
}
|
||||
let ray_to_field_matrix =
|
||||
Spatial::space_to_space_matrix(Some(&ray.space), Some(self.spatial_ref()));
|
||||
let mut ray_point = ray_to_field_matrix.transform_point3a(ray.origin.into());
|
||||
let ray_direction = ray_to_field_matrix
|
||||
.transform_vector3a(ray.direction.into())
|
||||
.normalize();
|
||||
|
||||
fn field_distance_flex(node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Result<Vec<u8>> {
|
||||
#[derive(Deserialize)]
|
||||
struct FieldInfoArgs<'a> {
|
||||
reference_space_path: &'a str,
|
||||
point: Vector3<f32>,
|
||||
}
|
||||
let args: FieldInfoArgs = deserialize(data)?;
|
||||
let reference_space = find_reference_space(&calling_client, args.reference_space_path)?;
|
||||
while result.ray_steps < MAX_RAY_STEPS && result.ray_length < MAX_RAY_LENGTH {
|
||||
let distance = self.local_distance(ray_point);
|
||||
let march_distance = distance.clamp(MIN_RAY_MARCH, MAX_RAY_MARCH);
|
||||
|
||||
let distance = node
|
||||
.field
|
||||
.get()
|
||||
.unwrap()
|
||||
.distance(reference_space.as_ref(), args.point.into());
|
||||
Ok(serialize(distance)?)
|
||||
}
|
||||
fn field_normal_flex(node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Result<Vec<u8>> {
|
||||
#[derive(Deserialize)]
|
||||
struct FieldInfoArgs<'a> {
|
||||
reference_space_path: &'a str,
|
||||
point: Vector3<f32>,
|
||||
radius: Option<f32>,
|
||||
}
|
||||
let args: FieldInfoArgs = deserialize(data)?;
|
||||
let reference_space = find_reference_space(&calling_client, args.reference_space_path)?;
|
||||
result.ray_length += march_distance;
|
||||
ray_point += ray_direction * march_distance;
|
||||
|
||||
let normal = node.field.get().as_ref().unwrap().normal(
|
||||
reference_space.as_ref(),
|
||||
args.point.into(),
|
||||
args.radius.unwrap_or(0.001),
|
||||
);
|
||||
Ok(serialize(mint::Vector3::from(normal))?)
|
||||
}
|
||||
fn field_closest_point_flex(
|
||||
node: &Node,
|
||||
calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
) -> Result<Vec<u8>> {
|
||||
#[derive(Deserialize)]
|
||||
struct FieldInfoArgs<'a> {
|
||||
reference_space_path: &'a str,
|
||||
point: Vector3<f32>,
|
||||
radius: Option<f32>,
|
||||
}
|
||||
let args: FieldInfoArgs = deserialize(data)?;
|
||||
let reference_space = find_reference_space(&calling_client, args.reference_space_path)?;
|
||||
if result.min_distance > distance {
|
||||
result.deepest_point_distance = result.ray_length;
|
||||
result.min_distance = distance;
|
||||
}
|
||||
|
||||
let closest_point = node.field.get().as_ref().unwrap().closest_point(
|
||||
reference_space.as_ref(),
|
||||
args.point.into(),
|
||||
args.radius.unwrap_or(0.001),
|
||||
);
|
||||
Ok(serialize(mint::Vector3::from(closest_point))?)
|
||||
}
|
||||
|
||||
pub enum Field {
|
||||
Box(BoxField),
|
||||
Cylinder(CylinderField),
|
||||
Sphere(SphereField),
|
||||
}
|
||||
|
||||
impl Deref for Field {
|
||||
type Target = dyn FieldTrait;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
match self {
|
||||
Field::Box(field) => field,
|
||||
Field::Cylinder(field) => field,
|
||||
Field::Sphere(field) => field,
|
||||
result.ray_steps += 1;
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
}
|
||||
impl<Fi: FieldTrait + 'static> FieldAspect for Fi {
|
||||
async fn distance(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
space: Arc<Node>,
|
||||
point: mint::Vector3<f32>,
|
||||
) -> Result<f32> {
|
||||
let reference_space = space.get_aspect::<Spatial>()?;
|
||||
let this_field = node.get_aspect::<Field>()?;
|
||||
Ok((*this_field).distance(reference_space.as_ref(), point.into()))
|
||||
}
|
||||
|
||||
pub fn create_interface(client: &Arc<Client>) {
|
||||
let node = Node::create(client, "", "field", false);
|
||||
node.add_local_signal("createBoxField", create_box_field_flex);
|
||||
node.add_local_signal("createCylinderField", create_cylinder_field_flex);
|
||||
node.add_local_signal("createSphereField", create_sphere_field_flex);
|
||||
node.add_to_scenegraph();
|
||||
async fn normal(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
space: Arc<Node>,
|
||||
point: mint::Vector3<f32>,
|
||||
) -> Result<Vector3<f32>> {
|
||||
let reference_space = space.get_aspect::<Spatial>()?;
|
||||
let this_field = node.get_aspect::<Field>()?;
|
||||
Ok(this_field
|
||||
.normal(reference_space.as_ref(), point.into(), 0.001)
|
||||
.into())
|
||||
}
|
||||
|
||||
async fn closest_point(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
space: Arc<Node>,
|
||||
point: mint::Vector3<f32>,
|
||||
) -> Result<Vector3<f32>> {
|
||||
let reference_space = space.get_aspect::<Spatial>()?;
|
||||
let this_field = node.get_aspect::<Field>()?;
|
||||
Ok(this_field
|
||||
.closest_point(reference_space.as_ref(), point.into(), 0.001)
|
||||
.into())
|
||||
}
|
||||
|
||||
async fn ray_march(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
space: Arc<Node>,
|
||||
ray_origin: mint::Vector3<f32>,
|
||||
ray_direction: mint::Vector3<f32>,
|
||||
) -> Result<RayMarchResult> {
|
||||
let reference_space = space.get_aspect::<Spatial>()?;
|
||||
let this_field = node.get_aspect::<Field>()?;
|
||||
Ok(this_field.ray_march(Ray {
|
||||
origin: ray_origin.into(),
|
||||
direction: ray_direction.into(),
|
||||
space: reference_space.clone(),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Ray {
|
||||
@@ -156,14 +170,6 @@ pub struct Ray {
|
||||
pub space: Arc<Spatial>,
|
||||
}
|
||||
|
||||
pub struct RayMarchResult {
|
||||
pub ray: Ray,
|
||||
pub distance: f32,
|
||||
pub deepest_point_distance: f32,
|
||||
pub ray_length: f32,
|
||||
pub ray_steps: u32,
|
||||
}
|
||||
|
||||
// const MIN_RAY_STEPS: u32 = 0;
|
||||
const MAX_RAY_STEPS: u32 = 1000;
|
||||
|
||||
@@ -173,40 +179,191 @@ const MAX_RAY_MARCH: f32 = f32::MAX;
|
||||
// const MIN_RAY_LENGTH: f32 = 0_f32;
|
||||
const MAX_RAY_LENGTH: f32 = 1000_f32;
|
||||
|
||||
pub fn ray_march(ray: Ray, field: &Field) -> RayMarchResult {
|
||||
let mut result = RayMarchResult {
|
||||
ray,
|
||||
distance: f32::MAX,
|
||||
deepest_point_distance: 0_f32,
|
||||
ray_length: 0_f32,
|
||||
ray_steps: 0,
|
||||
};
|
||||
|
||||
let ray_to_field_matrix =
|
||||
Spatial::space_to_space_matrix(Some(&result.ray.space), Some(field.spatial_ref()));
|
||||
let mut ray_point = ray_to_field_matrix.transform_point3a(result.ray.origin.into());
|
||||
let ray_direction = ray_to_field_matrix.transform_vector3a(result.ray.direction.into());
|
||||
|
||||
while result.ray_steps < MAX_RAY_STEPS && result.ray_length < MAX_RAY_LENGTH {
|
||||
let distance = field.local_distance(ray_point);
|
||||
let march_distance = distance.clamp(MIN_RAY_MARCH, MAX_RAY_MARCH);
|
||||
|
||||
result.ray_length += march_distance;
|
||||
ray_point += ray_direction * march_distance;
|
||||
|
||||
if result.distance > distance {
|
||||
result.deepest_point_distance = result.ray_length;
|
||||
pub enum Field {
|
||||
Box(BoxField),
|
||||
Cylinder(CylinderField),
|
||||
Sphere(SphereField),
|
||||
Torus(TorusField),
|
||||
}
|
||||
impl Aspect for Field {
|
||||
const NAME: &'static str = "Field";
|
||||
}
|
||||
impl Deref for Field {
|
||||
type Target = dyn FieldTrait;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
match self {
|
||||
Field::Box(field) => field,
|
||||
Field::Cylinder(field) => field,
|
||||
Field::Sphere(field) => field,
|
||||
Field::Torus(field) => field,
|
||||
}
|
||||
result.distance = distance.min(result.distance);
|
||||
}
|
||||
}
|
||||
// impl FieldTrait for Field {
|
||||
// fn spatial_ref(&self) -> &Spatial {
|
||||
// match self {
|
||||
// Field::Box(field) => field.spatial_ref(),
|
||||
// Field::Cylinder(field) => field.spatial_ref(),
|
||||
// Field::Sphere(field) => field.spatial_ref(),
|
||||
// Field::Torus(field) => field.spatial_ref(),
|
||||
// }
|
||||
// }
|
||||
// fn local_distance(&self, p: Vec3A) -> f32 {
|
||||
// match self {
|
||||
// Field::Box(field) => field.local_distance(p),
|
||||
// Field::Cylinder(field) => field.local_distance(p),
|
||||
// Field::Sphere(field) => field.local_distance(p),
|
||||
// Field::Torus(field) => field.local_distance(p),
|
||||
// }
|
||||
// }
|
||||
// fn local_normal(&self, p: Vec3A, r: f32) -> Vec3A {
|
||||
// match self {
|
||||
// Field::Box(field) => field.local_normal(p, r),
|
||||
// Field::Cylinder(field) => field.local_normal(p, r),
|
||||
// Field::Sphere(field) => field.local_normal(p, r),
|
||||
// Field::Torus(field) => field.local_normal(p, r),
|
||||
// }
|
||||
// }
|
||||
// fn local_closest_point(&self, p: Vec3A, r: f32) -> Vec3A {
|
||||
// match self {
|
||||
// Field::Box(field) => field.local_closest_point(p, r),
|
||||
// Field::Cylinder(field) => field.local_closest_point(p, r),
|
||||
// Field::Sphere(field) => field.local_closest_point(p, r),
|
||||
// Field::Torus(field) => field.local_closest_point(p, r),
|
||||
// }
|
||||
// }
|
||||
// fn distance(&self, reference_space: &Spatial, p: Vec3A) -> f32 {
|
||||
// match self {
|
||||
// Field::Box(field) => field.distance(reference_space, p),
|
||||
// Field::Cylinder(field) => field.distance(reference_space, p),
|
||||
// Field::Sphere(field) => field.distance(reference_space, p),
|
||||
// Field::Torus(field) => field.distance(reference_space, p),
|
||||
// }
|
||||
// }
|
||||
// fn normal(&self, reference_space: &Spatial, p: Vec3A, r: f32) -> Vec3A {
|
||||
// match self {
|
||||
// Field::Box(field) => field.normal(reference_space, p, r),
|
||||
// Field::Cylinder(field) => field.normal(reference_space, p, r),
|
||||
// Field::Sphere(field) => field.normal(reference_space, p, r),
|
||||
// Field::Torus(field) => field.normal(reference_space, p, r),
|
||||
// }
|
||||
// }
|
||||
// fn closest_point(&self, reference_space: &Spatial, p: Vec3A, r: f32) -> Vec3A {
|
||||
// match self {
|
||||
// Field::Box(field) => field.closest_point(reference_space, p, r),
|
||||
// Field::Cylinder(field) => field.closest_point(reference_space, p, r),
|
||||
// Field::Sphere(field) => field.closest_point(reference_space, p, r),
|
||||
// Field::Torus(field) => field.closest_point(reference_space, p, r),
|
||||
// }
|
||||
// }
|
||||
// fn ray_march(&self, ray: Ray) -> RayMarchResult {
|
||||
// match self {
|
||||
// Field::Box(field) => field.ray_march(ray),
|
||||
// Field::Cylinder(field) => field.ray_march(ray),
|
||||
// Field::Sphere(field) => field.ray_march(ray),
|
||||
// Field::Torus(field) => field.ray_march(ray),
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
result.ray_steps += 1;
|
||||
create_interface!(FieldInterface, FieldInterfaceAspect, "/field");
|
||||
pub struct FieldInterface;
|
||||
impl FieldInterfaceAspect for FieldInterface {
|
||||
fn create_box_field(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
name: String,
|
||||
parent: Arc<Node>,
|
||||
transform: Transform,
|
||||
size: mint::Vector3<f32>,
|
||||
) -> Result<()> {
|
||||
let transform = transform.to_mat4(true, true, false);
|
||||
let parent = parent.get_aspect::<Spatial>()?;
|
||||
let node = Node::create_parent_name(
|
||||
&calling_client,
|
||||
Self::CREATE_BOX_FIELD_PARENT_PATH,
|
||||
&name,
|
||||
true,
|
||||
)
|
||||
.add_to_scenegraph()?;
|
||||
Spatial::add_to(&node, Some(parent.clone()), transform, false);
|
||||
BoxField::add_to(&node, size);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
result
|
||||
fn create_cylinder_field(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
name: String,
|
||||
parent: Arc<Node>,
|
||||
transform: Transform,
|
||||
length: f32,
|
||||
radius: f32,
|
||||
) -> Result<()> {
|
||||
let transform = transform.to_mat4(true, true, false);
|
||||
let parent = parent.get_aspect::<Spatial>()?;
|
||||
let node = Node::create_parent_name(
|
||||
&calling_client,
|
||||
Self::CREATE_CYLINDER_FIELD_PARENT_PATH,
|
||||
&name,
|
||||
true,
|
||||
)
|
||||
.add_to_scenegraph()?;
|
||||
Spatial::add_to(&node, Some(parent.clone()), transform, false);
|
||||
CylinderField::add_to(&node, length, radius);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn create_sphere_field(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
name: String,
|
||||
parent: Arc<Node>,
|
||||
position: mint::Vector3<f32>,
|
||||
radius: f32,
|
||||
) -> Result<()> {
|
||||
let parent = parent.get_aspect::<Spatial>()?;
|
||||
let node = Node::create_parent_name(
|
||||
&calling_client,
|
||||
Self::CREATE_SPHERE_FIELD_PARENT_PATH,
|
||||
&name,
|
||||
true,
|
||||
)
|
||||
.add_to_scenegraph()?;
|
||||
Spatial::add_to(
|
||||
&node,
|
||||
Some(parent.clone()),
|
||||
Mat4::from_translation(position.into()),
|
||||
false,
|
||||
);
|
||||
SphereField::add_to(&node, radius);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn create_torus_field(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
name: String,
|
||||
parent: Arc<Node>,
|
||||
transform: Transform,
|
||||
radius_a: f32,
|
||||
radius_b: f32,
|
||||
) -> Result<()> {
|
||||
let transform = transform.to_mat4(true, true, false);
|
||||
let parent = parent.get_aspect::<Spatial>()?;
|
||||
let node = Node::create_parent_name(
|
||||
&calling_client,
|
||||
Self::CREATE_TORUS_FIELD_PARENT_PATH,
|
||||
&name,
|
||||
true,
|
||||
)
|
||||
.add_to_scenegraph()?;
|
||||
Spatial::add_to(&node, Some(parent.clone()), transform, false);
|
||||
TorusField::add_to(&node, radius_a, radius_b);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn find_field(client: &Client, path: &str) -> Result<Arc<Field>> {
|
||||
Ok(client
|
||||
.get_node("Field", path)?
|
||||
.get_aspect("Field", "info", |n| &n.field)?)
|
||||
client.get_node("Field", path)?.get_aspect::<Field>()
|
||||
}
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
use super::{Field, FieldTrait, Node};
|
||||
use super::{Field, FieldTrait, Node, SphereFieldAspect};
|
||||
use crate::core::client::Client;
|
||||
use crate::nodes::spatial::{find_spatial_parent, Spatial};
|
||||
use anyhow::{ensure, Result};
|
||||
use glam::{Mat4, Vec3A};
|
||||
use mint::Vector3;
|
||||
use crate::nodes::fields::FieldAspect;
|
||||
use crate::nodes::spatial::Spatial;
|
||||
use color_eyre::eyre::Result;
|
||||
use glam::Vec3A;
|
||||
use portable_atomic::AtomicF32;
|
||||
use serde::Deserialize;
|
||||
use stardust_xr::schemas::flex::deserialize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -16,36 +14,19 @@ pub struct SphereField {
|
||||
}
|
||||
|
||||
impl SphereField {
|
||||
pub fn add_to(node: &Arc<Node>, radius: f32) -> Result<()> {
|
||||
ensure!(
|
||||
node.spatial.get().is_some(),
|
||||
"Internal: Node does not have a spatial attached!"
|
||||
);
|
||||
ensure!(
|
||||
node.field.get().is_none(),
|
||||
"Internal: Node already has a field attached!"
|
||||
);
|
||||
pub fn add_to(node: &Arc<Node>, radius: f32) {
|
||||
let sphere_field = SphereField {
|
||||
space: node.spatial.get().unwrap().clone(),
|
||||
space: node.get_aspect::<Spatial>().unwrap().clone(),
|
||||
radius: AtomicF32::new(radius),
|
||||
};
|
||||
sphere_field.add_field_methods(node);
|
||||
node.add_local_signal("setRadius", SphereField::set_radius_flex);
|
||||
let _ = node.field.set(Arc::new(Field::Sphere(sphere_field)));
|
||||
Ok(())
|
||||
<SphereField as FieldAspect>::add_node_members(node);
|
||||
<SphereField as SphereFieldAspect>::add_node_members(node);
|
||||
node.add_aspect(Field::Sphere(sphere_field));
|
||||
}
|
||||
|
||||
pub fn set_radius(&self, radius: f32) {
|
||||
self.radius.store(radius, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn set_radius_flex(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
let radius = flexbuffers::Reader::get_root(data)?.get_f64()? as f32;
|
||||
if let Field::Sphere(sphere_field) = node.field.get().unwrap().as_ref() {
|
||||
sphere_field.set_radius(radius);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl FieldTrait for SphereField {
|
||||
@@ -62,29 +43,13 @@ impl FieldTrait for SphereField {
|
||||
self.space.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_sphere_field_flex(
|
||||
_node: &Node,
|
||||
calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct CreateFieldInfo<'a> {
|
||||
name: &'a str,
|
||||
parent_path: &'a str,
|
||||
origin: Option<Vector3<f32>>,
|
||||
radius: f32,
|
||||
impl SphereFieldAspect for SphereField {
|
||||
fn set_radius(node: Arc<Node>, _calling_client: Arc<Client>, radius: f32) -> Result<()> {
|
||||
let this_field = node.get_aspect::<Field>()?;
|
||||
let Field::Sphere(this_field) = &*this_field else {
|
||||
return Ok(());
|
||||
};
|
||||
this_field.set_radius(radius);
|
||||
Ok(())
|
||||
}
|
||||
let info: CreateFieldInfo = deserialize(data)?;
|
||||
let node = Node::create(&calling_client, "/field", info.name, true);
|
||||
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||
let transform = Mat4::from_translation(
|
||||
info.origin
|
||||
.unwrap_or_else(|| Vector3::from([0.0; 3]))
|
||||
.into(),
|
||||
);
|
||||
let node = node.add_to_scenegraph();
|
||||
Spatial::add_to(&node, Some(parent), transform)?;
|
||||
SphereField::add_to(&node, info.radius)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
60
src/nodes/fields/torus.rs
Normal file
60
src/nodes/fields/torus.rs
Normal file
@@ -0,0 +1,60 @@
|
||||
use super::{Field, FieldTrait, Node, TorusFieldAspect};
|
||||
use crate::core::client::Client;
|
||||
use crate::nodes::fields::FieldAspect;
|
||||
use crate::nodes::spatial::Spatial;
|
||||
use color_eyre::eyre::Result;
|
||||
use glam::{swizzles::*, vec2, Vec3A};
|
||||
use portable_atomic::AtomicF32;
|
||||
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct TorusField {
|
||||
space: Arc<Spatial>,
|
||||
radius_a: AtomicF32,
|
||||
radius_b: AtomicF32,
|
||||
}
|
||||
|
||||
impl TorusField {
|
||||
pub fn add_to(node: &Arc<Node>, radius_a: f32, radius_b: f32) {
|
||||
let torus_field = TorusField {
|
||||
space: node.get_aspect::<Spatial>().unwrap().clone(),
|
||||
radius_a: AtomicF32::new(radius_a.abs()),
|
||||
radius_b: AtomicF32::new(radius_b.abs()),
|
||||
};
|
||||
<TorusField as FieldAspect>::add_node_members(node);
|
||||
<TorusField as TorusFieldAspect>::add_node_members(node);
|
||||
node.add_aspect(Field::Torus(torus_field));
|
||||
}
|
||||
|
||||
pub fn set_size(&self, radius_a: f32, radius_b: f32) {
|
||||
self.radius_a.store(radius_a.abs(), Ordering::Relaxed);
|
||||
self.radius_b.store(radius_b.abs(), Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
impl FieldTrait for TorusField {
|
||||
fn local_distance(&self, p: Vec3A) -> f32 {
|
||||
let radius_a = self.radius_a.load(Ordering::Relaxed);
|
||||
let radius_b = self.radius_b.load(Ordering::Relaxed);
|
||||
let q = vec2(p.xz().length() - radius_a, p.y);
|
||||
q.length() - radius_b
|
||||
}
|
||||
fn spatial_ref(&self) -> &Spatial {
|
||||
self.space.as_ref()
|
||||
}
|
||||
}
|
||||
impl TorusFieldAspect for TorusField {
|
||||
fn set_size(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
radius_a: f32,
|
||||
radius_b: f32,
|
||||
) -> Result<()> {
|
||||
let this_field = node.get_aspect::<Field>()?;
|
||||
let Field::Torus(this_field) = &*this_field else {
|
||||
return Ok(());
|
||||
};
|
||||
this_field.set_size(radius_a, radius_b);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -3,23 +3,24 @@ use crate::{
|
||||
core::client::{Client, INTERNAL_CLIENT},
|
||||
nodes::alias::AliasInfo,
|
||||
};
|
||||
use color_eyre::eyre::Result;
|
||||
use glam::{vec3, Mat4};
|
||||
use std::sync::Arc;
|
||||
use stereokit::StereoKit;
|
||||
use stereokit::StereoKitMultiThread;
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
static ref HMD: Arc<Node> = create();
|
||||
}
|
||||
|
||||
fn create() -> Arc<Node> {
|
||||
let node = Arc::new(Node::create(&INTERNAL_CLIENT, "", "hmd", false));
|
||||
Spatial::add_to(&node, None, Mat4::IDENTITY).unwrap();
|
||||
let node = Arc::new(Node::create_parent_name(&INTERNAL_CLIENT, "", "hmd", false));
|
||||
Spatial::add_to(&node, None, Mat4::IDENTITY, false);
|
||||
|
||||
node
|
||||
}
|
||||
|
||||
pub fn frame(sk: &StereoKit) {
|
||||
let spatial = HMD.spatial.get().unwrap();
|
||||
pub fn frame(sk: &impl StereoKitMultiThread) {
|
||||
let spatial = HMD.get_aspect::<Spatial>().unwrap();
|
||||
let hmd_pose = sk.input_head();
|
||||
*spatial.transform.lock() = Mat4::from_scale_rotation_translation(
|
||||
vec3(1.0, 1.0, 1.0),
|
||||
@@ -28,14 +29,14 @@ pub fn frame(sk: &StereoKit) {
|
||||
);
|
||||
}
|
||||
|
||||
pub fn make_alias(client: &Arc<Client>) -> Arc<Node> {
|
||||
Alias::new(
|
||||
pub fn make_alias(client: &Arc<Client>) -> Result<Arc<Node>> {
|
||||
Alias::create(
|
||||
client,
|
||||
"",
|
||||
"hmd",
|
||||
&HMD,
|
||||
AliasInfo {
|
||||
local_signals: vec!["getTransform"],
|
||||
server_signals: vec!["get_bounds", "get_transform"],
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
|
||||
@@ -11,7 +11,10 @@ pub struct Hand {
|
||||
pub base: FlatHand,
|
||||
}
|
||||
impl InputSpecialization for Hand {
|
||||
fn distance(&self, space: &Arc<Spatial>, field: &Field) -> f32 {
|
||||
fn compare_distance(&self, space: &Arc<Spatial>, field: &Field) -> f32 {
|
||||
self.true_distance(space, field).abs()
|
||||
}
|
||||
fn true_distance(&self, space: &Arc<Spatial>, field: &Field) -> f32 {
|
||||
let mut min_distance = f32::MAX;
|
||||
|
||||
for tip in [
|
||||
@@ -28,7 +31,7 @@ impl InputSpecialization for Hand {
|
||||
}
|
||||
fn serialize(
|
||||
&self,
|
||||
_distance_link: &DistanceLink,
|
||||
distance_link: &DistanceLink,
|
||||
local_to_handler_matrix: Mat4,
|
||||
) -> InputDataType {
|
||||
let mut hand = self.base;
|
||||
@@ -60,12 +63,15 @@ impl InputSpecialization for Hand {
|
||||
]);
|
||||
|
||||
for joint in joints {
|
||||
let joint_matrix =
|
||||
Mat4::from_rotation_translation(joint.rotation.into(), joint.position.into())
|
||||
* local_to_handler_matrix;
|
||||
let joint_matrix = local_to_handler_matrix
|
||||
* Mat4::from_rotation_translation(joint.rotation.into(), joint.position.into());
|
||||
let (_, rotation, position) = joint_matrix.to_scale_rotation_translation();
|
||||
joint.position = position.into();
|
||||
joint.rotation = rotation.into();
|
||||
joint.distance = distance_link
|
||||
.handler
|
||||
.field
|
||||
.distance(&distance_link.handler.spatial, position.into());
|
||||
}
|
||||
|
||||
InputDataType::Hand(Box::new(hand))
|
||||
|
||||
@@ -6,30 +6,36 @@ use self::hand::Hand;
|
||||
use self::pointer::Pointer;
|
||||
use self::tip::Tip;
|
||||
|
||||
use super::fields::Field;
|
||||
use super::spatial::{find_spatial_parent, parse_transform, Spatial};
|
||||
use super::Node;
|
||||
use crate::core::client::Client;
|
||||
use crate::core::eventloop::FRAME;
|
||||
use crate::core::registry::Registry;
|
||||
use crate::nodes::fields::find_field;
|
||||
use anyhow::{ensure, Result};
|
||||
use super::{
|
||||
alias::{Alias, AliasInfo},
|
||||
fields::{find_field, Field, FIELD_ALIAS_INFO},
|
||||
spatial::{parse_transform, Spatial},
|
||||
Aspect, Message, Node,
|
||||
};
|
||||
use crate::core::{client::Client, node_collections::LifeLinkedNodeMap};
|
||||
use crate::{core::registry::Registry, nodes::spatial::Transform};
|
||||
use color_eyre::eyre::Result;
|
||||
use glam::Mat4;
|
||||
use nanoid::nanoid;
|
||||
use once_cell::sync::OnceCell;
|
||||
use parking_lot::Mutex;
|
||||
use portable_atomic::AtomicBool;
|
||||
use serde::Deserialize;
|
||||
use stardust_xr::schemas::flat::{Datamap, InputDataType};
|
||||
use stardust_xr::schemas::{flat::InputData, flex::deserialize};
|
||||
use stardust_xr::values::Transform;
|
||||
use stardust_xr::schemas::{flat::InputDataType, flex::serialize};
|
||||
use stardust_xr::{
|
||||
schemas::{flat::InputData, flex::deserialize},
|
||||
values::Datamap,
|
||||
};
|
||||
use std::ops::Deref;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::{Arc, Weak};
|
||||
use tracing::{debug_span, instrument};
|
||||
|
||||
static INPUT_METHOD_REGISTRY: Registry<InputMethod> = Registry::new();
|
||||
static INPUT_HANDLER_REGISTRY: Registry<InputHandler> = Registry::new();
|
||||
|
||||
pub trait InputSpecialization: Send + Sync {
|
||||
fn distance(&self, space: &Arc<Spatial>, field: &Field) -> f32;
|
||||
fn compare_distance(&self, space: &Arc<Spatial>, field: &Field) -> f32;
|
||||
fn true_distance(&self, space: &Arc<Spatial>, field: &Field) -> f32;
|
||||
fn serialize(
|
||||
&self,
|
||||
distance_link: &DistanceLink,
|
||||
@@ -53,64 +59,191 @@ impl Deref for InputType {
|
||||
}
|
||||
|
||||
pub struct InputMethod {
|
||||
pub uid: String,
|
||||
node: Weak<Node>,
|
||||
uid: String,
|
||||
pub enabled: Mutex<bool>,
|
||||
pub spatial: Arc<Spatial>,
|
||||
pub specialization: Mutex<InputType>,
|
||||
pub captures: Registry<InputHandler>,
|
||||
captures: Registry<InputHandler>,
|
||||
pub datamap: Mutex<Option<Datamap>>,
|
||||
handler_aliases: LifeLinkedNodeMap<String>,
|
||||
handler_order: OnceCell<Mutex<Vec<Weak<InputHandler>>>>,
|
||||
}
|
||||
impl InputMethod {
|
||||
pub fn new(spatial: Arc<Spatial>, specialization: InputType) -> Arc<InputMethod> {
|
||||
let method = InputMethod {
|
||||
uid: nanoid!(),
|
||||
enabled: Mutex::new(true),
|
||||
spatial,
|
||||
specialization: Mutex::new(specialization),
|
||||
captures: Registry::new(),
|
||||
datamap: Mutex::new(None),
|
||||
};
|
||||
INPUT_METHOD_REGISTRY.add(method)
|
||||
}
|
||||
#[allow(dead_code)]
|
||||
pub fn add_to(
|
||||
node: &Arc<Node>,
|
||||
specialization: InputType,
|
||||
datamap: Option<Datamap>,
|
||||
) -> Result<()> {
|
||||
ensure!(
|
||||
node.spatial.get().is_some(),
|
||||
"Internal: Node does not have a spatial attached!"
|
||||
);
|
||||
|
||||
node.add_local_signal("setDatamap", InputMethod::set_datamap);
|
||||
) -> Result<Arc<InputMethod>> {
|
||||
node.add_local_signal("capture", InputMethod::capture_flex);
|
||||
node.add_local_signal("set_datamap", InputMethod::set_datamap_flex);
|
||||
node.add_local_signal("set_handlers", InputMethod::set_handlers_flex);
|
||||
|
||||
let method = InputMethod {
|
||||
node: Arc::downgrade(node),
|
||||
uid: node.uid.clone(),
|
||||
enabled: Mutex::new(true),
|
||||
spatial: node.spatial.get().unwrap().clone(),
|
||||
spatial: node.get_aspect::<Spatial>().unwrap().clone(),
|
||||
specialization: Mutex::new(specialization),
|
||||
captures: Registry::new(),
|
||||
datamap: Mutex::new(datamap),
|
||||
handler_aliases: LifeLinkedNodeMap::default(),
|
||||
handler_order: OnceCell::new(),
|
||||
};
|
||||
for handler in INPUT_HANDLER_REGISTRY.get_valid_contents() {
|
||||
method.handle_new_handler(&handler);
|
||||
method.make_alias(&handler);
|
||||
}
|
||||
let method = INPUT_METHOD_REGISTRY.add(method);
|
||||
let _ = node.input_method.set(method);
|
||||
Ok(())
|
||||
node.add_aspect_raw(method.clone());
|
||||
Ok(method)
|
||||
}
|
||||
fn get(node: &Node) -> Result<Arc<Self>> {
|
||||
node.get_aspect::<Self>()
|
||||
}
|
||||
|
||||
fn set_datamap(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
node.input_method
|
||||
.get()
|
||||
.unwrap()
|
||||
fn capture_flex(node: Arc<Node>, calling_client: Arc<Client>, message: Message) -> Result<()> {
|
||||
let method = InputMethod::get(&node)?;
|
||||
let handler = InputHandler::find(&calling_client, deserialize(message.as_ref())?)?;
|
||||
|
||||
method.captures.add_raw(&handler);
|
||||
node.send_remote_signal("capture", message)
|
||||
}
|
||||
fn set_datamap_flex(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
message: Message,
|
||||
) -> Result<()> {
|
||||
let method = InputMethod::get(&node)?;
|
||||
method
|
||||
.datamap
|
||||
.lock()
|
||||
.replace(Datamap::new(data.to_vec())?);
|
||||
.replace(Datamap::from_raw(message.data)?);
|
||||
Ok(())
|
||||
}
|
||||
fn set_handlers_flex(
|
||||
node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
message: Message,
|
||||
) -> Result<()> {
|
||||
let method = InputMethod::get(&node)?;
|
||||
let handler_paths: Vec<&str> = deserialize(message.as_ref())?;
|
||||
let handlers: Vec<Weak<InputHandler>> = handler_paths
|
||||
.into_iter()
|
||||
.filter_map(|p| InputHandler::find(&calling_client, p).ok())
|
||||
.map(|h| Arc::downgrade(&h))
|
||||
.collect();
|
||||
|
||||
*method
|
||||
.handler_order
|
||||
.get_or_init(|| Mutex::new(Vec::new()))
|
||||
.lock() = handlers;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn distance(&self, to: &Field) -> f32 {
|
||||
self.specialization.lock().distance(&self.spatial, to)
|
||||
fn make_alias(&self, handler: &InputHandler) {
|
||||
let Some(method_node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let Some(handler_node) = handler.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let Some(client) = handler_node.get_client() else {
|
||||
return;
|
||||
};
|
||||
let Ok(method_alias) = Alias::create(
|
||||
&client,
|
||||
handler_node.get_path(),
|
||||
&self.uid,
|
||||
&method_node,
|
||||
AliasInfo {
|
||||
server_signals: vec!["capture"],
|
||||
..Default::default()
|
||||
},
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
method_alias.enabled.store(false, Ordering::Relaxed);
|
||||
handler
|
||||
.method_aliases
|
||||
.add(self as *const InputMethod as usize, &method_alias);
|
||||
}
|
||||
|
||||
fn compare_distance(&self, to: &InputHandler) -> f32 {
|
||||
let distance = self
|
||||
.specialization
|
||||
.lock()
|
||||
.compare_distance(&self.spatial, &to.field);
|
||||
if self.captures.contains(to) {
|
||||
distance * 0.5
|
||||
} else {
|
||||
distance
|
||||
}
|
||||
}
|
||||
fn true_distance(&self, to: &Field) -> f32 {
|
||||
self.specialization.lock().true_distance(&self.spatial, to)
|
||||
}
|
||||
|
||||
fn handle_new_handler(&self, handler: &InputHandler) {
|
||||
let Some(method_node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let Some(method_client) = method_node.get_client() else {
|
||||
return;
|
||||
};
|
||||
let Some(handler_node) = handler.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
// Receiver itself
|
||||
let Ok(handler_alias) = Alias::create(
|
||||
&method_client,
|
||||
method_node.get_path(),
|
||||
handler.uid.as_str(),
|
||||
&handler_node,
|
||||
AliasInfo {
|
||||
server_methods: vec!["get_transform"],
|
||||
..Default::default()
|
||||
},
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
self.handler_aliases
|
||||
.add(handler.uid.clone(), &handler_alias);
|
||||
|
||||
if let Some(handler_field_node) = handler.field.spatial_ref().node.upgrade() {
|
||||
// Handler's field
|
||||
let Ok(rx_field_alias) = Alias::create(
|
||||
&method_client,
|
||||
handler_alias.get_path(),
|
||||
"field",
|
||||
&handler_field_node,
|
||||
FIELD_ALIAS_INFO.clone(),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
self.handler_aliases
|
||||
.add(handler.uid.clone() + "-field", &rx_field_alias);
|
||||
}
|
||||
|
||||
let Ok(data) = serialize(&handler.uid) else {
|
||||
return;
|
||||
};
|
||||
let _ = method_node.send_remote_signal("handler_created", data);
|
||||
}
|
||||
fn handle_drop_handler(&self, handler: &InputHandler) {
|
||||
let uid = handler.uid.as_str();
|
||||
self.handler_aliases.remove(uid);
|
||||
self.handler_aliases.remove(&(uid.to_string() + "-field"));
|
||||
let Some(tx_node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let Ok(data) = serialize(&uid) else { return };
|
||||
let _ = tx_node.send_remote_signal("handler_destroyed", data);
|
||||
}
|
||||
}
|
||||
impl Aspect for InputMethod {
|
||||
const NAME: &'static str = "InputMethod";
|
||||
}
|
||||
impl Drop for InputMethod {
|
||||
fn drop(&mut self) {
|
||||
@@ -119,26 +252,24 @@ impl Drop for InputMethod {
|
||||
}
|
||||
|
||||
pub struct DistanceLink {
|
||||
pub distance: f32,
|
||||
pub method: Arc<InputMethod>,
|
||||
pub handler: Arc<InputHandler>,
|
||||
pub handler_field: Arc<Field>,
|
||||
distance: f32,
|
||||
method: Arc<InputMethod>,
|
||||
handler: Arc<InputHandler>,
|
||||
}
|
||||
impl DistanceLink {
|
||||
fn from(method: Arc<InputMethod>, handler: Arc<InputHandler>) -> Option<Self> {
|
||||
let handler_field = handler.field.upgrade()?;
|
||||
Some(DistanceLink {
|
||||
distance: method.distance(&handler_field),
|
||||
fn from(method: Arc<InputMethod>, handler: Arc<InputHandler>) -> Self {
|
||||
DistanceLink {
|
||||
distance: method.compare_distance(&handler),
|
||||
method,
|
||||
handler,
|
||||
handler_field,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn send_input(&self, frame: u64, datamap: Datamap) {
|
||||
self.handler.send_input(frame, self, datamap);
|
||||
fn send_input(&self, order: u32, captured: bool, datamap: Datamap) {
|
||||
self.handler.send_input(order, captured, self, datamap);
|
||||
}
|
||||
fn serialize(&self, datamap: Datamap) -> Vec<u8> {
|
||||
#[instrument(level = "debug", skip(self))]
|
||||
fn serialize(&self, order: u32, captured: bool, datamap: Datamap) -> Vec<u8> {
|
||||
let input = self.method.specialization.lock().serialize(
|
||||
self,
|
||||
Spatial::space_to_space_matrix(Some(&self.method.spatial), Some(&self.handler.spatial)),
|
||||
@@ -147,78 +278,88 @@ impl DistanceLink {
|
||||
let root = InputData {
|
||||
uid: self.method.uid.clone(),
|
||||
input,
|
||||
distance: self.distance,
|
||||
distance: self.method.true_distance(&self.handler.field),
|
||||
datamap,
|
||||
order,
|
||||
captured,
|
||||
};
|
||||
root.serialize()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct InputHandler {
|
||||
enabled: Arc<AtomicBool>,
|
||||
uid: String,
|
||||
node: Weak<Node>,
|
||||
spatial: Arc<Spatial>,
|
||||
pub field: Weak<Field>,
|
||||
field: Arc<Field>,
|
||||
method_aliases: LifeLinkedNodeMap<usize>,
|
||||
}
|
||||
impl InputHandler {
|
||||
pub fn add_to(node: &Arc<Node>, field: &Arc<Field>) -> Result<()> {
|
||||
ensure!(
|
||||
node.spatial.get().is_some(),
|
||||
"Internal: Node does not have a spatial attached!"
|
||||
);
|
||||
|
||||
let handler = InputHandler {
|
||||
enabled: node.enabled.clone(),
|
||||
uid: node.uid.clone(),
|
||||
node: Arc::downgrade(node),
|
||||
spatial: node.spatial.get().unwrap().clone(),
|
||||
field: Arc::downgrade(field),
|
||||
spatial: node.get_aspect::<Spatial>().unwrap().clone(),
|
||||
field: field.clone(),
|
||||
method_aliases: LifeLinkedNodeMap::default(),
|
||||
};
|
||||
for method in INPUT_METHOD_REGISTRY.get_valid_contents() {
|
||||
method.make_alias(&handler);
|
||||
method.handle_new_handler(&handler);
|
||||
}
|
||||
let handler = INPUT_HANDLER_REGISTRY.add(handler);
|
||||
let _ = node.input_handler.set(handler);
|
||||
node.add_aspect_raw(handler);
|
||||
Ok(())
|
||||
}
|
||||
fn find(client: &Client, path: &str) -> Result<Arc<Self>> {
|
||||
client.get_node("Input Handler", path)?.get_aspect::<Self>()
|
||||
}
|
||||
|
||||
fn send_input(&self, frame: u64, distance_link: &DistanceLink, datamap: Datamap) {
|
||||
let data = distance_link.serialize(datamap);
|
||||
let node = self.node.upgrade().unwrap();
|
||||
let method = Arc::downgrade(&distance_link.method);
|
||||
let handler = Arc::downgrade(&distance_link.handler);
|
||||
|
||||
tokio::spawn(async move {
|
||||
let data = node.execute_remote_method("input", data).await;
|
||||
if frame == FRAME.load(Ordering::Relaxed) {
|
||||
if let Ok(data) = data {
|
||||
let capture = flexbuffers::Reader::get_root(data.as_slice())
|
||||
.and_then(|data| data.get_bool())
|
||||
.unwrap_or(false);
|
||||
|
||||
if let Some(method) = method.upgrade() {
|
||||
if let Some(handler) = handler.upgrade() {
|
||||
if capture {
|
||||
method.captures.add_raw(&handler);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
#[instrument(level = "debug", skip(self, distance_link))]
|
||||
fn send_input(
|
||||
&self,
|
||||
order: u32,
|
||||
captured: bool,
|
||||
distance_link: &DistanceLink,
|
||||
datamap: Datamap,
|
||||
) {
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let _ = node.send_remote_signal("input", distance_link.serialize(order, captured, datamap));
|
||||
}
|
||||
}
|
||||
impl Aspect for InputHandler {
|
||||
const NAME: &'static str = "InputHandler";
|
||||
}
|
||||
impl PartialEq for InputHandler {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.spatial == other.spatial
|
||||
}
|
||||
}
|
||||
impl Drop for InputHandler {
|
||||
fn drop(&mut self) {
|
||||
INPUT_HANDLER_REGISTRY.remove(self);
|
||||
for method in INPUT_METHOD_REGISTRY.get_valid_contents() {
|
||||
method.handle_drop_handler(self);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_interface(client: &Arc<Client>) {
|
||||
let node = Node::create(client, "", "input", false);
|
||||
node.add_local_signal("createInputHandler", create_input_handler_flex);
|
||||
node.add_local_signal("createInputMethodTip", tip::create_tip_flex);
|
||||
node.add_to_scenegraph();
|
||||
pub fn create_interface(client: &Arc<Client>) -> Result<()> {
|
||||
let node = Node::create_path(client, "/input", false);
|
||||
node.add_local_signal("create_input_handler", create_input_handler_flex);
|
||||
node.add_local_signal("create_input_method_pointer", pointer::create_pointer_flex);
|
||||
node.add_local_signal("create_input_method_tip", tip::create_tip_flex);
|
||||
node.add_to_scenegraph().map(|_| ())
|
||||
}
|
||||
|
||||
pub fn create_input_handler_flex(
|
||||
_node: &Node,
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
message: Message,
|
||||
) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct CreateInputHandlerInfo<'a> {
|
||||
@@ -227,52 +368,95 @@ pub fn create_input_handler_flex(
|
||||
transform: Transform,
|
||||
field_path: &'a str,
|
||||
}
|
||||
let info: CreateInputHandlerInfo = deserialize(data)?;
|
||||
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||
let transform = parse_transform(info.transform, true, true, false)?;
|
||||
let info: CreateInputHandlerInfo = deserialize(message.as_ref())?;
|
||||
let parent = calling_client
|
||||
.get_node("Spatial parent", info.parent_path)?
|
||||
.get_aspect::<Spatial>()?;
|
||||
let transform = parse_transform(info.transform, true, true, true);
|
||||
let field = find_field(&calling_client, info.field_path)?;
|
||||
|
||||
let node = Node::create(&calling_client, "/input/handler", info.name, true).add_to_scenegraph();
|
||||
Spatial::add_to(&node, Some(parent), transform)?;
|
||||
let node = Node::create_parent_name(&calling_client, "/input/handler", info.name, true)
|
||||
.add_to_scenegraph()?;
|
||||
Spatial::add_to(&node, Some(parent.clone()), transform, false);
|
||||
InputHandler::add_to(&node, &field)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "debug")]
|
||||
pub fn process_input() {
|
||||
for method in INPUT_METHOD_REGISTRY
|
||||
.get_valid_contents()
|
||||
.into_iter()
|
||||
.filter(|method| *method.enabled.lock())
|
||||
.filter(|method| method.datamap.lock().is_some())
|
||||
{
|
||||
let mut distance_links: Vec<DistanceLink> = INPUT_HANDLER_REGISTRY
|
||||
// Iterate over all valid input methods
|
||||
let methods = debug_span!("Get valid methods").in_scope(|| {
|
||||
INPUT_METHOD_REGISTRY
|
||||
.get_valid_contents()
|
||||
.into_iter()
|
||||
.filter(|handler| handler.field.upgrade().is_some())
|
||||
.filter_map(|handler| DistanceLink::from(method.clone(), handler))
|
||||
.collect();
|
||||
distance_links.sort_unstable_by(|a, b| {
|
||||
a.distance
|
||||
.abs()
|
||||
.partial_cmp(&b.distance.abs())
|
||||
.unwrap()
|
||||
.reverse()
|
||||
});
|
||||
|
||||
let mut last_distance = 0.0;
|
||||
let frame = FRAME.load(Ordering::Relaxed);
|
||||
let captures = method.captures.get_valid_contents();
|
||||
for distance_link in distance_links {
|
||||
distance_link.send_input(frame, method.datamap.lock().clone().unwrap());
|
||||
if last_distance != distance_link.distance
|
||||
&& captures
|
||||
.iter()
|
||||
.any(|c| Arc::ptr_eq(c, &distance_link.handler))
|
||||
{
|
||||
break;
|
||||
}
|
||||
last_distance = distance_link.distance;
|
||||
.filter(|method| *method.enabled.lock())
|
||||
.filter(|method| method.datamap.lock().is_some())
|
||||
});
|
||||
let handlers = INPUT_HANDLER_REGISTRY.get_valid_contents();
|
||||
const LIMIT: usize = 50;
|
||||
for method in methods {
|
||||
for alias in method.node.upgrade().unwrap().aliases.get_valid_contents() {
|
||||
alias.enabled.store(false, Ordering::Release);
|
||||
}
|
||||
method.captures.clear();
|
||||
|
||||
debug_span!("Process input method").in_scope(|| {
|
||||
// Get all valid input handlers and convert them to DistanceLink objects
|
||||
let distance_links: Vec<DistanceLink> = debug_span!("Generate distance links")
|
||||
.in_scope(|| {
|
||||
if let Some(handler_order) = method.handler_order.get() {
|
||||
let handler_order = handler_order.lock();
|
||||
handler_order
|
||||
.iter()
|
||||
.filter_map(|h| h.upgrade())
|
||||
.filter(|handler| handler.enabled.load(Ordering::Relaxed))
|
||||
.map(|handler| DistanceLink::from(method.clone(), handler))
|
||||
.collect()
|
||||
} else {
|
||||
let mut distance_links: Vec<_> = handlers
|
||||
.iter()
|
||||
.filter(|handler| handler.enabled.load(Ordering::Relaxed))
|
||||
.map(|handler| {
|
||||
debug_span!("Create distance link").in_scope(|| {
|
||||
DistanceLink::from(method.clone(), handler.clone())
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Sort the distance links by their distance in ascending order
|
||||
debug_span!("Sort distance links").in_scope(|| {
|
||||
distance_links.sort_unstable_by(|a, b| {
|
||||
a.distance.abs().partial_cmp(&b.distance.abs()).unwrap()
|
||||
});
|
||||
});
|
||||
|
||||
distance_links.truncate(LIMIT);
|
||||
distance_links
|
||||
}
|
||||
});
|
||||
|
||||
let captures = method.captures.take_valid_contents();
|
||||
// Iterate over the distance links and send input to them
|
||||
for (i, distance_link) in distance_links.into_iter().enumerate() {
|
||||
if let Some(method_alias) = distance_link
|
||||
.handler
|
||||
.method_aliases
|
||||
.get(&(Arc::as_ptr(&distance_link.method) as usize))
|
||||
.and_then(|a| a.get_aspect::<Alias>().ok())
|
||||
{
|
||||
method_alias.enabled.store(true, Ordering::Release);
|
||||
}
|
||||
let captured = captures.contains(&distance_link.handler);
|
||||
distance_link.send_input(
|
||||
i as u32,
|
||||
captured,
|
||||
method.datamap.lock().clone().unwrap(),
|
||||
);
|
||||
|
||||
// If the current distance link is in the list of captured input handlers,
|
||||
// break out of the loop to avoid sending input to the remaining distance links
|
||||
if captured {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,19 @@
|
||||
use super::{DistanceLink, InputSpecialization};
|
||||
use crate::nodes::fields::{ray_march, Field, Ray, RayMarchResult};
|
||||
use crate::nodes::spatial::Spatial;
|
||||
use crate::core::client::Client;
|
||||
use crate::nodes::fields::{Field, Ray, RayMarchResult};
|
||||
use crate::nodes::input::{InputMethod, InputType};
|
||||
use crate::nodes::spatial::{parse_transform, Spatial, Transform};
|
||||
use crate::nodes::{Message, Node};
|
||||
use glam::{vec3, Mat4};
|
||||
use serde::Deserialize;
|
||||
use stardust_xr::schemas::flat::{InputDataType, Pointer as FlatPointer};
|
||||
use stardust_xr::schemas::flex::deserialize;
|
||||
use stardust_xr::values::Datamap;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Pointer {}
|
||||
pub struct Pointer;
|
||||
// impl Default for Pointer {
|
||||
// fn default() -> Self {
|
||||
// Pointer {
|
||||
@@ -17,20 +24,28 @@ pub struct Pointer {}
|
||||
// }
|
||||
impl Pointer {
|
||||
fn ray_march(&self, space: &Arc<Spatial>, field: &Field) -> RayMarchResult {
|
||||
ray_march(
|
||||
Ray {
|
||||
origin: vec3(0_f32, 0_f32, 0_f32),
|
||||
direction: vec3(0_f32, 0_f32, 1_f32),
|
||||
space: space.clone(),
|
||||
},
|
||||
field,
|
||||
)
|
||||
field.ray_march(Ray {
|
||||
origin: vec3(0.0, 0.0, 0.0),
|
||||
direction: vec3(0.0, 0.0, -1.0),
|
||||
space: space.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl InputSpecialization for Pointer {
|
||||
fn distance(&self, space: &Arc<Spatial>, field: &Field) -> f32 {
|
||||
self.ray_march(space, field).distance
|
||||
fn compare_distance(&self, space: &Arc<Spatial>, field: &Field) -> f32 {
|
||||
let ray_info = self.ray_march(space, field);
|
||||
if ray_info.min_distance > 0.0 {
|
||||
ray_info.deepest_point_distance + 1000.0
|
||||
} else {
|
||||
ray_info
|
||||
.deepest_point_distance
|
||||
.hypot(0.001 / ray_info.min_distance)
|
||||
}
|
||||
}
|
||||
fn true_distance(&self, space: &Arc<Spatial>, field: &Field) -> f32 {
|
||||
let ray_info = self.ray_march(space, field);
|
||||
ray_info.min_distance
|
||||
}
|
||||
fn serialize(
|
||||
&self,
|
||||
@@ -38,11 +53,8 @@ impl InputSpecialization for Pointer {
|
||||
local_to_handler_matrix: Mat4,
|
||||
) -> InputDataType {
|
||||
let (_, orientation, origin) = local_to_handler_matrix.to_scale_rotation_translation();
|
||||
let direction = local_to_handler_matrix.transform_vector3(vec3(0_f32, 0_f32, 1_f32));
|
||||
let ray_march = self.ray_march(
|
||||
&distance_link.method.spatial,
|
||||
&distance_link.handler.field.upgrade().unwrap(),
|
||||
);
|
||||
let direction = local_to_handler_matrix.transform_vector3(vec3(0.0, 0.0, -1.0));
|
||||
let ray_march = self.ray_march(&distance_link.method.spatial, &distance_link.handler.field);
|
||||
let deepest_point = (direction * ray_march.deepest_point_distance) + origin;
|
||||
|
||||
InputDataType::Pointer(FlatPointer {
|
||||
@@ -52,3 +64,33 @@ impl InputSpecialization for Pointer {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_pointer_flex(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
message: Message,
|
||||
) -> color_eyre::eyre::Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct CreatePointerInfo<'a> {
|
||||
name: &'a str,
|
||||
parent_path: &'a str,
|
||||
transform: Transform,
|
||||
datamap: Option<Vec<u8>>,
|
||||
}
|
||||
let info: CreatePointerInfo = deserialize(message.as_ref())?;
|
||||
let node = Node::create_parent_name(&calling_client, "/input/method/pointer", info.name, true);
|
||||
let parent = calling_client
|
||||
.get_node("Spatial parent", info.parent_path)?
|
||||
.get_aspect::<Spatial>()?;
|
||||
let transform = parse_transform(info.transform, true, true, false);
|
||||
|
||||
let node = node.add_to_scenegraph()?;
|
||||
Spatial::add_to(&node, Some(parent.clone()), transform, false);
|
||||
InputMethod::add_to(
|
||||
&node,
|
||||
InputType::Pointer(Pointer),
|
||||
info.datamap
|
||||
.and_then(|datamap| Datamap::from_raw(datamap).ok()),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -2,14 +2,15 @@ use super::{DistanceLink, InputSpecialization};
|
||||
use crate::core::client::Client;
|
||||
use crate::nodes::fields::Field;
|
||||
use crate::nodes::input::{InputMethod, InputType};
|
||||
use crate::nodes::spatial::{find_spatial_parent, parse_transform, Spatial};
|
||||
use crate::nodes::Node;
|
||||
use anyhow::Result;
|
||||
use crate::nodes::spatial::{parse_transform, Spatial, Transform};
|
||||
use crate::nodes::{Message, Node};
|
||||
use color_eyre::eyre::Result;
|
||||
use glam::{vec3a, Mat4};
|
||||
use serde::Deserialize;
|
||||
use stardust_xr::schemas::flat::{Datamap, InputDataType, Tip as FlatTip};
|
||||
use stardust_xr::schemas::flat::{InputDataType, Tip as FlatTip};
|
||||
use stardust_xr::schemas::flex::deserialize;
|
||||
use stardust_xr::values::Transform;
|
||||
use stardust_xr::values::Datamap;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -17,15 +18,19 @@ pub struct Tip {
|
||||
pub radius: f32,
|
||||
}
|
||||
impl Tip {
|
||||
fn set_radius(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
if let InputType::Tip(tip) = &mut *node.input_method.get().unwrap().specialization.lock() {
|
||||
tip.radius = deserialize(data)?;
|
||||
fn set_radius(node: Arc<Node>, _calling_client: Arc<Client>, message: Message) -> Result<()> {
|
||||
let input_method = node.get_aspect::<InputMethod>()?;
|
||||
if let InputType::Tip(tip) = &mut *input_method.specialization.lock() {
|
||||
tip.radius = deserialize(message.as_ref())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl InputSpecialization for Tip {
|
||||
fn distance(&self, space: &Arc<Spatial>, field: &Field) -> f32 {
|
||||
fn compare_distance(&self, space: &Arc<Spatial>, field: &Field) -> f32 {
|
||||
field.distance(space, vec3a(0.0, 0.0, 0.0)).abs()
|
||||
}
|
||||
fn true_distance(&self, space: &Arc<Spatial>, field: &Field) -> f32 {
|
||||
field.distance(space, vec3a(0.0, 0.0, 0.0))
|
||||
}
|
||||
fn serialize(
|
||||
@@ -42,7 +47,11 @@ impl InputSpecialization for Tip {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_tip_flex(_node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
pub fn create_tip_flex(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
message: Message,
|
||||
) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct CreateTipInfo<'a> {
|
||||
name: &'a str,
|
||||
@@ -51,20 +60,23 @@ pub fn create_tip_flex(_node: &Node, calling_client: Arc<Client>, data: &[u8]) -
|
||||
radius: f32,
|
||||
datamap: Option<Vec<u8>>,
|
||||
}
|
||||
let info: CreateTipInfo = deserialize(data)?;
|
||||
let node = Node::create(&calling_client, "/input/method/tip", info.name, true);
|
||||
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||
let transform = parse_transform(info.transform, true, true, false)?;
|
||||
let info: CreateTipInfo = deserialize(message.as_ref())?;
|
||||
let node = Node::create_parent_name(&calling_client, "/input/method/tip", info.name, true);
|
||||
let parent = calling_client
|
||||
.get_node("Spatial parent", info.parent_path)?
|
||||
.get_aspect::<Spatial>()?;
|
||||
let transform = parse_transform(info.transform, true, true, false);
|
||||
|
||||
let node = node.add_to_scenegraph();
|
||||
Spatial::add_to(&node, Some(parent), transform)?;
|
||||
let node = node.add_to_scenegraph()?;
|
||||
Spatial::add_to(&node, Some(parent.clone()), transform, false);
|
||||
InputMethod::add_to(
|
||||
&node,
|
||||
InputType::Tip(Tip {
|
||||
radius: info.radius,
|
||||
}),
|
||||
info.datamap.and_then(|datamap| Datamap::new(datamap).ok()),
|
||||
info.datamap
|
||||
.and_then(|datamap| Datamap::from_raw(datamap).ok()),
|
||||
)?;
|
||||
node.add_local_signal("setRadius", Tip::set_radius);
|
||||
node.add_local_signal("set_radius", Tip::set_radius);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
193
src/nodes/items/camera.rs
Normal file
193
src/nodes/items/camera.rs
Normal file
@@ -0,0 +1,193 @@
|
||||
use super::{Item, ItemType};
|
||||
use crate::{
|
||||
core::{
|
||||
client::{Client, INTERNAL_CLIENT},
|
||||
registry::Registry,
|
||||
scenegraph::MethodResponseSender,
|
||||
},
|
||||
nodes::{
|
||||
drawable::{model::ModelPart, shaders::UNLIT_SHADER_BYTES},
|
||||
items::TypeInfo,
|
||||
spatial::{parse_transform, Spatial, Transform},
|
||||
Message, Node,
|
||||
},
|
||||
};
|
||||
use color_eyre::eyre::{bail, eyre, Result};
|
||||
use glam::Mat4;
|
||||
use lazy_static::lazy_static;
|
||||
use mint::{RowMatrix4, Vector2};
|
||||
use nanoid::nanoid;
|
||||
use once_cell::sync::OnceCell;
|
||||
use parking_lot::Mutex;
|
||||
use serde::Deserialize;
|
||||
use stardust_xr::schemas::flex::{deserialize, serialize};
|
||||
use std::sync::Arc;
|
||||
use stereokit::{
|
||||
Color128, Material, Rect, RenderLayer, StereoKitDraw, Tex, TextureType, Transparency,
|
||||
};
|
||||
|
||||
lazy_static! {
|
||||
pub(super) static ref ITEM_TYPE_INFO_CAMERA: TypeInfo = TypeInfo {
|
||||
type_name: "camera",
|
||||
aliased_local_signals: vec!["apply_preview_material", "frame"],
|
||||
aliased_local_methods: vec![],
|
||||
aliased_remote_signals: vec![],
|
||||
ui: Default::default(),
|
||||
items: Registry::new(),
|
||||
acceptors: Registry::new(),
|
||||
};
|
||||
}
|
||||
|
||||
struct FrameInfo {
|
||||
proj_matrix: Mat4,
|
||||
px_size: Vector2<u32>,
|
||||
}
|
||||
|
||||
pub struct CameraItem {
|
||||
space: Arc<Spatial>,
|
||||
frame_info: Mutex<FrameInfo>,
|
||||
sk_tex: OnceCell<Tex>,
|
||||
sk_mat: OnceCell<Arc<Material>>,
|
||||
applied_to: Registry<ModelPart>,
|
||||
apply_to: Registry<ModelPart>,
|
||||
}
|
||||
impl CameraItem {
|
||||
pub fn add_to(node: &Arc<Node>, proj_matrix: Mat4, px_size: Vector2<u32>) {
|
||||
Item::add_to(
|
||||
node,
|
||||
nanoid!(),
|
||||
&ITEM_TYPE_INFO_CAMERA,
|
||||
ItemType::Camera(CameraItem {
|
||||
space: node.get_aspect::<Spatial>().unwrap().clone(),
|
||||
frame_info: Mutex::new(FrameInfo {
|
||||
proj_matrix,
|
||||
px_size,
|
||||
}),
|
||||
sk_tex: OnceCell::new(),
|
||||
sk_mat: OnceCell::new(),
|
||||
applied_to: Registry::new(),
|
||||
apply_to: Registry::new(),
|
||||
}),
|
||||
);
|
||||
node.add_local_method("frame", CameraItem::frame_flex);
|
||||
node.add_local_signal(
|
||||
"apply_preview_material",
|
||||
CameraItem::apply_preview_material_flex,
|
||||
);
|
||||
}
|
||||
|
||||
fn frame_flex(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
_message: Message,
|
||||
response: MethodResponseSender,
|
||||
) {
|
||||
response.wrap_sync(move || {
|
||||
let ItemType::Camera(_camera) = &node.get_aspect::<Item>().unwrap().specialization
|
||||
else {
|
||||
return Err(eyre!("Wrong item type?"));
|
||||
};
|
||||
Ok(serialize(())?.into())
|
||||
});
|
||||
}
|
||||
|
||||
fn apply_preview_material_flex(
|
||||
node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
message: Message,
|
||||
) -> Result<()> {
|
||||
let ItemType::Camera(camera) = &node.get_aspect::<Item>().unwrap().specialization else {
|
||||
bail!("Wrong item type?")
|
||||
};
|
||||
let model_part_node =
|
||||
calling_client.get_node("Model part", deserialize(&message.data).unwrap())?;
|
||||
let model_part = model_part_node.get_aspect::<ModelPart>()?;
|
||||
camera.applied_to.add_raw(&model_part);
|
||||
camera.apply_to.add_raw(&model_part);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn serialize_start_data(&self, id: &str) -> Result<Message> {
|
||||
Ok(serialize(id)?.into())
|
||||
}
|
||||
|
||||
pub fn update(&self, sk: &impl StereoKitDraw) {
|
||||
let frame_info = self.frame_info.lock();
|
||||
let sk_tex = self.sk_tex.get_or_init(|| {
|
||||
sk.tex_gen_color(
|
||||
Color128::default(),
|
||||
frame_info.px_size.x as i32,
|
||||
frame_info.px_size.y as i32,
|
||||
TextureType::RENDER_TARGET,
|
||||
stereokit::TextureFormat::RGBA32Linear,
|
||||
)
|
||||
});
|
||||
let sk_mat = self.sk_mat.get_or_init(|| {
|
||||
let shader = sk.shader_create_mem(&UNLIT_SHADER_BYTES).unwrap();
|
||||
let mat = sk.material_create(&shader);
|
||||
sk.material_set_texture(&mat, "diffuse", sk_tex.as_ref());
|
||||
sk.material_set_transparency(&mat, Transparency::Blend);
|
||||
Arc::new(mat)
|
||||
});
|
||||
for model_part in self.apply_to.take_valid_contents() {
|
||||
model_part.replace_material(sk_mat.clone())
|
||||
}
|
||||
|
||||
if !self.applied_to.is_empty() {
|
||||
sk.render_to(
|
||||
sk_tex,
|
||||
frame_info.proj_matrix,
|
||||
self.space.global_transform(),
|
||||
RenderLayer::all(),
|
||||
stereokit::RenderClear::All,
|
||||
Rect {
|
||||
x: 0.0,
|
||||
y: 0.0,
|
||||
w: 0.0,
|
||||
h: 0.0,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update(sk: &impl StereoKitDraw) {
|
||||
for camera in ITEM_TYPE_INFO_CAMERA.items.get_valid_contents() {
|
||||
let ItemType::Camera(camera) = &camera.specialization else {
|
||||
continue;
|
||||
};
|
||||
camera.update(sk);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn create_camera_item_flex(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
message: Message,
|
||||
) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct CreateCameraItemInfo<'a> {
|
||||
name: &'a str,
|
||||
parent_path: &'a str,
|
||||
transform: Transform,
|
||||
proj_matrix: RowMatrix4<f32>,
|
||||
px_size: Vector2<u32>,
|
||||
}
|
||||
let info: CreateCameraItemInfo = deserialize(message.as_ref())?;
|
||||
let parent_name = format!("/item/{}/item", ITEM_TYPE_INFO_CAMERA.type_name);
|
||||
let space = calling_client
|
||||
.get_node("Spatial parent", info.parent_path)?
|
||||
.get_aspect::<Spatial>()?;
|
||||
let transform = parse_transform(info.transform, true, true, false);
|
||||
|
||||
let node = Node::create_parent_name(&INTERNAL_CLIENT, &parent_name, info.name, false)
|
||||
.add_to_scenegraph()?;
|
||||
Spatial::add_to(&node, None, transform * space.global_transform(), false);
|
||||
CameraItem::add_to(&node, info.proj_matrix.into(), info.px_size);
|
||||
node.get_aspect::<Item>().unwrap().make_alias_named(
|
||||
&calling_client,
|
||||
&parent_name,
|
||||
info.name,
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,19 +1,35 @@
|
||||
use super::{Item, ItemSpecialization, ItemType, ITEM_TYPE_INFO_ENVIRONMENT};
|
||||
use super::{Item, ItemType};
|
||||
use crate::{
|
||||
core::client::{Client, INTERNAL_CLIENT},
|
||||
core::{
|
||||
client::{Client, INTERNAL_CLIENT},
|
||||
registry::Registry,
|
||||
scenegraph::MethodResponseSender,
|
||||
},
|
||||
nodes::{
|
||||
spatial::{find_spatial_parent, parse_transform, Spatial},
|
||||
Node,
|
||||
items::TypeInfo,
|
||||
spatial::{parse_transform, Spatial, Transform},
|
||||
Message, Node,
|
||||
},
|
||||
};
|
||||
use anyhow::{anyhow, Result};
|
||||
use color_eyre::eyre::{eyre, Result};
|
||||
use lazy_static::lazy_static;
|
||||
use nanoid::nanoid;
|
||||
use serde::Deserialize;
|
||||
use stardust_xr::{
|
||||
schemas::flex::{deserialize, serialize},
|
||||
values::Transform,
|
||||
};
|
||||
use stardust_xr::schemas::flex::{deserialize, serialize};
|
||||
use std::sync::Arc;
|
||||
|
||||
lazy_static! {
|
||||
pub(super) static ref ITEM_TYPE_INFO_ENVIRONMENT: TypeInfo = TypeInfo {
|
||||
type_name: "environment",
|
||||
aliased_local_signals: vec!["apply_sky_tex", "apply_sky_light"],
|
||||
aliased_local_methods: vec![],
|
||||
aliased_remote_signals: vec![],
|
||||
ui: Default::default(),
|
||||
items: Registry::new(),
|
||||
acceptors: Registry::new(),
|
||||
};
|
||||
}
|
||||
|
||||
pub struct EnvironmentItem {
|
||||
path: String,
|
||||
}
|
||||
@@ -21,30 +37,38 @@ impl EnvironmentItem {
|
||||
pub fn add_to(node: &Arc<Node>, path: String) {
|
||||
Item::add_to(
|
||||
node,
|
||||
nanoid!(),
|
||||
&ITEM_TYPE_INFO_ENVIRONMENT,
|
||||
ItemType::Environment(EnvironmentItem { path }),
|
||||
);
|
||||
node.add_local_method("getPath", EnvironmentItem::get_path_flex);
|
||||
node.add_local_method("get_path", EnvironmentItem::get_path_flex);
|
||||
}
|
||||
|
||||
fn get_path_flex(node: &Node, _calling_client: Arc<Client>, _data: &[u8]) -> Result<Vec<u8>> {
|
||||
let path: Result<String> = match &node.item.get().unwrap().specialization {
|
||||
ItemType::Environment(env) => Ok(env.path.clone()),
|
||||
_ => Err(anyhow!("")),
|
||||
};
|
||||
Ok(flexbuffers::singleton(path?.as_str()))
|
||||
fn get_path_flex(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
_message: Message,
|
||||
response: MethodResponseSender,
|
||||
) {
|
||||
response.wrap_sync(move || {
|
||||
let ItemType::Environment(environment_item) =
|
||||
&node.get_aspect::<Item>().unwrap().specialization
|
||||
else {
|
||||
return Err(eyre!("Wrong item type?"));
|
||||
};
|
||||
Ok(serialize(environment_item.path.as_str())?.into())
|
||||
});
|
||||
}
|
||||
}
|
||||
impl ItemSpecialization for EnvironmentItem {
|
||||
fn serialize_start_data(&self, id: &str) -> Vec<u8> {
|
||||
serialize((id, self.path.as_str())).unwrap()
|
||||
|
||||
pub fn serialize_start_data(&self, id: &str) -> Result<Message> {
|
||||
Ok(serialize((id, self.path.as_str()))?.into())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn create_environment_item_flex(
|
||||
_node: &Node,
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
message: Message,
|
||||
) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct CreateEnvironmentItemInfo<'a> {
|
||||
@@ -53,33 +77,21 @@ pub(super) fn create_environment_item_flex(
|
||||
transform: Transform,
|
||||
item_data: String,
|
||||
}
|
||||
let info: CreateEnvironmentItemInfo = deserialize(data)?;
|
||||
let parent_name = format!("/item/{}/item/", ITEM_TYPE_INFO_ENVIRONMENT.type_name);
|
||||
let node = Node::create(&INTERNAL_CLIENT, &parent_name, info.name, true);
|
||||
let space = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||
let transform = parse_transform(info.transform, true, true, false)?;
|
||||
let node = node.add_to_scenegraph();
|
||||
Spatial::add_to(&node, None, transform * space.global_transform())?;
|
||||
let info: CreateEnvironmentItemInfo = deserialize(message.as_ref())?;
|
||||
let parent_name = format!("/item/{}/item", ITEM_TYPE_INFO_ENVIRONMENT.type_name);
|
||||
let space = calling_client
|
||||
.get_node("Spatial parent", info.parent_path)?
|
||||
.get_aspect::<Spatial>()?;
|
||||
let transform = parse_transform(info.transform, true, true, false);
|
||||
|
||||
let node = Node::create_parent_name(&INTERNAL_CLIENT, &parent_name, info.name, false)
|
||||
.add_to_scenegraph()?;
|
||||
Spatial::add_to(&node, None, transform * space.global_transform(), false);
|
||||
EnvironmentItem::add_to(&node, info.item_data);
|
||||
node.item
|
||||
.get()
|
||||
.unwrap()
|
||||
.make_alias(&calling_client, &parent_name);
|
||||
node.get_aspect::<Item>().unwrap().make_alias_named(
|
||||
&calling_client,
|
||||
&parent_name,
|
||||
info.name,
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn create_environment_item_acceptor_flex(
|
||||
_node: &Node,
|
||||
calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
) -> Result<()> {
|
||||
super::create_item_acceptor_flex(calling_client, data, &ITEM_TYPE_INFO_ENVIRONMENT)
|
||||
}
|
||||
|
||||
pub(super) fn register_environment_item_ui_flex(
|
||||
_node: &Node,
|
||||
calling_client: Arc<Client>,
|
||||
_data: &[u8],
|
||||
) -> Result<()> {
|
||||
super::register_item_ui_flex(calling_client, &ITEM_TYPE_INFO_ENVIRONMENT)
|
||||
}
|
||||
|
||||
@@ -1,66 +1,61 @@
|
||||
pub mod camera;
|
||||
mod environment;
|
||||
pub mod panel;
|
||||
|
||||
use self::environment::EnvironmentItem;
|
||||
use self::camera::CameraItem;
|
||||
use self::environment::{EnvironmentItem, ITEM_TYPE_INFO_ENVIRONMENT};
|
||||
use self::panel::{PanelItemTrait, ITEM_TYPE_INFO_PANEL};
|
||||
use super::fields::Field;
|
||||
use super::spatial::{find_spatial_parent, parse_transform, Spatial};
|
||||
use super::{Alias, Node};
|
||||
use crate::core::client::{Client, INTERNAL_CLIENT};
|
||||
use crate::core::nodelist::LifeLinkedNodeList;
|
||||
use super::spatial::{parse_transform, Spatial};
|
||||
use super::{Alias, Aspect, Message, Node};
|
||||
use crate::core::client::Client;
|
||||
use crate::core::node_collections::LifeLinkedNodeMap;
|
||||
use crate::core::registry::Registry;
|
||||
use crate::nodes::alias::AliasInfo;
|
||||
use crate::nodes::fields::find_field;
|
||||
use crate::wayland::panel_item::{register_panel_item_ui_flex, PanelItem};
|
||||
use anyhow::{anyhow, ensure, Result};
|
||||
use crate::nodes::spatial::Transform;
|
||||
use color_eyre::eyre::{ensure, eyre, Result};
|
||||
use lazy_static::lazy_static;
|
||||
use nanoid::nanoid;
|
||||
use parking_lot::Mutex;
|
||||
use portable_atomic::Ordering;
|
||||
use serde::Deserialize;
|
||||
use stardust_xr::schemas::flex::deserialize;
|
||||
use stardust_xr::values::Transform;
|
||||
use stardust_xr::schemas::flex::{deserialize, serialize};
|
||||
|
||||
use std::ops::Deref;
|
||||
use std::hash::Hash;
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
lazy_static! {
|
||||
static ref ITEM_ALIAS_LOCAL_SIGNALS: Vec<&'static str> = vec![
|
||||
"getTransform",
|
||||
"setTransform",
|
||||
"setSpatialParent",
|
||||
"setSpatialParentInPlace",
|
||||
"setZoneable",
|
||||
"get_bounds",
|
||||
"get_transform",
|
||||
"set_transform",
|
||||
"set_spatial_parent",
|
||||
"set_spatial_parent_in_place",
|
||||
"set_zoneable",
|
||||
"release",
|
||||
];
|
||||
static ref ITEM_ALIAS_LOCAL_METHODS: Vec<&'static str> = vec!["captureInto"];
|
||||
static ref ITEM_ALIAS_LOCAL_METHODS: Vec<&'static str> = vec![];
|
||||
static ref ITEM_ALIAS_REMOTE_SIGNALS: Vec<&'static str> = vec![];
|
||||
static ref ITEM_ALIAS_REMOTE_METHODS: Vec<&'static str> = vec![];
|
||||
static ref ITEM_TYPE_INFO_ENVIRONMENT: TypeInfo = TypeInfo {
|
||||
type_name: "environment",
|
||||
aliased_local_signals: vec!["applySkyTex", "applySkyLight"],
|
||||
aliased_local_methods: vec![],
|
||||
aliased_remote_signals: vec![],
|
||||
aliased_remote_methods: vec![],
|
||||
ui: Default::default(),
|
||||
items: Registry::new(),
|
||||
acceptors: Registry::new(),
|
||||
};
|
||||
}
|
||||
|
||||
fn capture(item: &Arc<Item>, acceptor: &Arc<ItemAcceptor>) {
|
||||
if item.captured_acceptor.lock().upgrade().is_some() {
|
||||
pub fn capture(item: &Arc<Item>, acceptor: &Arc<ItemAcceptor>) {
|
||||
if item.captured_acceptor.lock().strong_count() > 0 {
|
||||
release(item);
|
||||
}
|
||||
*item.captured_acceptor.lock() = Arc::downgrade(acceptor);
|
||||
acceptor.handle_capture(item);
|
||||
if let Some(ui) = item.type_info.ui.lock().upgrade() {
|
||||
ui.handle_capture(item);
|
||||
ui.handle_capture_item(item, acceptor);
|
||||
}
|
||||
}
|
||||
fn release(item: &Arc<Item>) {
|
||||
if let Some(acceptor) = item.captured_acceptor.lock().upgrade() {
|
||||
*item.captured_acceptor.lock() = Weak::default();
|
||||
fn release(item: &Item) {
|
||||
let mut captured_acceptor = item.captured_acceptor.lock();
|
||||
if let Some(acceptor) = captured_acceptor.upgrade().as_ref() {
|
||||
*captured_acceptor = Weak::default();
|
||||
acceptor.handle_release(item);
|
||||
if let Some(ui) = item.type_info.ui.lock().upgrade() {
|
||||
ui.handle_release(item);
|
||||
ui.handle_release_item(item, &acceptor);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -70,27 +65,21 @@ pub struct TypeInfo {
|
||||
pub aliased_local_signals: Vec<&'static str>,
|
||||
pub aliased_local_methods: Vec<&'static str>,
|
||||
pub aliased_remote_signals: Vec<&'static str>,
|
||||
pub aliased_remote_methods: Vec<&'static str>,
|
||||
pub ui: Mutex<Weak<ItemUI>>,
|
||||
pub items: Registry<Item>,
|
||||
pub acceptors: Registry<ItemAcceptor>,
|
||||
}
|
||||
|
||||
fn capture_into_flex(node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
let acceptor_path = flexbuffers::Reader::get_root(data)?
|
||||
.get_str()
|
||||
.map_err(|_| anyhow!("Acceptor path is not a string"))?;
|
||||
let acceptor = calling_client
|
||||
.scenegraph
|
||||
.get_node(acceptor_path)
|
||||
.ok_or_else(|| anyhow!("Acceptor node not found"))?;
|
||||
let acceptor = acceptor
|
||||
.item_acceptor
|
||||
.get()
|
||||
.ok_or_else(|| anyhow!("Acceptor node is not an acceptor!"))?;
|
||||
capture(node.item.get().unwrap(), acceptor);
|
||||
Ok(())
|
||||
impl Hash for TypeInfo {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.type_name.hash(state);
|
||||
}
|
||||
}
|
||||
impl PartialEq for TypeInfo {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.type_name == other.type_name
|
||||
}
|
||||
}
|
||||
impl Eq for TypeInfo {}
|
||||
|
||||
pub struct Item {
|
||||
node: Weak<Node>,
|
||||
@@ -102,84 +91,126 @@ pub struct Item {
|
||||
impl Item {
|
||||
pub fn add_to(
|
||||
node: &Arc<Node>,
|
||||
uid: String,
|
||||
type_info: &'static TypeInfo,
|
||||
specialization: ItemType,
|
||||
) -> Arc<Self> {
|
||||
node.add_local_signal("captureInto", capture_into_flex);
|
||||
let item = Item {
|
||||
node: Arc::downgrade(node),
|
||||
uid: nanoid!(),
|
||||
uid,
|
||||
type_info,
|
||||
captured_acceptor: Default::default(),
|
||||
specialization,
|
||||
};
|
||||
let item = type_info.items.add(item);
|
||||
|
||||
node.add_local_signal("release", Item::release_flex);
|
||||
if let Some(ui) = type_info.ui.lock().upgrade() {
|
||||
ui.handle_create_item(&item);
|
||||
}
|
||||
let _ = node.item.set(item.clone());
|
||||
node.add_aspect_raw(item.clone());
|
||||
|
||||
// if let Some(auto_acceptor) = node.get_client().and_then(|client| {
|
||||
// client
|
||||
// .state
|
||||
// .as_ref()
|
||||
// .and_then(|settings| settings.acceptors.get(type_info))
|
||||
// .and_then(|acceptor| acceptor.upgrade())
|
||||
// }) {
|
||||
// capture(&item, &auto_acceptor);
|
||||
// }
|
||||
|
||||
item
|
||||
}
|
||||
fn make_alias(&self, client: &Arc<Client>, parent: &str) -> (Arc<Node>, Arc<Alias>) {
|
||||
let node = Alias::new(
|
||||
fn make_alias_named(
|
||||
&self,
|
||||
client: &Arc<Client>,
|
||||
parent: &str,
|
||||
name: &str,
|
||||
) -> Result<Arc<Node>> {
|
||||
Alias::create(
|
||||
client,
|
||||
parent,
|
||||
&self.uid,
|
||||
name,
|
||||
&self.node.upgrade().unwrap(),
|
||||
AliasInfo {
|
||||
local_signals: [
|
||||
server_signals: [
|
||||
&self.type_info.aliased_local_signals,
|
||||
ITEM_ALIAS_LOCAL_SIGNALS.as_slice(),
|
||||
]
|
||||
.concat(),
|
||||
local_methods: [
|
||||
server_methods: [
|
||||
&self.type_info.aliased_local_methods,
|
||||
ITEM_ALIAS_LOCAL_METHODS.as_slice(),
|
||||
]
|
||||
.concat(),
|
||||
remote_signals: [
|
||||
client_signals: [
|
||||
&self.type_info.aliased_remote_signals,
|
||||
ITEM_ALIAS_REMOTE_SIGNALS.as_slice(),
|
||||
]
|
||||
.concat(),
|
||||
},
|
||||
);
|
||||
let alias = node.alias.get().unwrap().clone();
|
||||
(node, alias)
|
||||
)
|
||||
}
|
||||
fn make_alias(&self, client: &Arc<Client>, parent: &str) -> Result<Arc<Node>> {
|
||||
self.make_alias_named(client, parent, &self.uid)
|
||||
}
|
||||
|
||||
fn release_flex(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
_message: Message,
|
||||
) -> Result<()> {
|
||||
let item = node.get_aspect::<Item>()?;
|
||||
release(&item);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Aspect for Item {
|
||||
const NAME: &'static str = "Item";
|
||||
}
|
||||
impl Drop for Item {
|
||||
fn drop(&mut self) {
|
||||
self.type_info.items.remove(self);
|
||||
release(self);
|
||||
if let Some(ui) = self.type_info.ui.lock().upgrade() {
|
||||
ui.handle_destroy_item(self);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub trait ItemSpecialization {
|
||||
fn serialize_start_data(&self, id: &str) -> Vec<u8>;
|
||||
}
|
||||
|
||||
pub enum ItemType {
|
||||
Camera(CameraItem),
|
||||
Environment(EnvironmentItem),
|
||||
Panel(PanelItem),
|
||||
Panel(Arc<dyn PanelItemTrait>),
|
||||
}
|
||||
impl Deref for ItemType {
|
||||
type Target = dyn ItemSpecialization;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
impl ItemType {
|
||||
fn serialize_start_data(&self, id: &str) -> Result<Message> {
|
||||
match self {
|
||||
ItemType::Environment(item) => item,
|
||||
ItemType::Panel(item) => item,
|
||||
ItemType::Camera(c) => c.serialize_start_data(id),
|
||||
ItemType::Environment(e) => e.serialize_start_data(id),
|
||||
ItemType::Panel(p) => p.serialize_start_data(id),
|
||||
}
|
||||
}
|
||||
}
|
||||
// impl Deref for ItemType {
|
||||
// type Target = dyn ItemSpecialization;
|
||||
|
||||
// fn deref(&self) -> &Self::Target {
|
||||
// match self {
|
||||
// ItemType::Environment(item) => item,
|
||||
// ItemType::Panel(item) => item.as_ref(),
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
pub struct ItemUI {
|
||||
node: Weak<Node>,
|
||||
type_info: &'static TypeInfo,
|
||||
aliases: LifeLinkedNodeList,
|
||||
item_aliases: LifeLinkedNodeMap<String>,
|
||||
acceptor_aliases: LifeLinkedNodeMap<String>,
|
||||
acceptor_field_aliases: LifeLinkedNodeMap<String>,
|
||||
}
|
||||
impl ItemUI {
|
||||
fn add_to(node: &Arc<Node>, type_info: &'static TypeInfo) -> Result<()> {
|
||||
@@ -191,59 +222,103 @@ impl ItemUI {
|
||||
let ui = Arc::new(ItemUI {
|
||||
node: Arc::downgrade(node),
|
||||
type_info,
|
||||
aliases: Default::default(),
|
||||
item_aliases: Default::default(),
|
||||
acceptor_aliases: Default::default(),
|
||||
acceptor_field_aliases: Default::default(),
|
||||
});
|
||||
*type_info.ui.lock() = Arc::downgrade(&ui);
|
||||
let _ = node.item_ui.set(ui.clone());
|
||||
node.add_aspect_raw(ui.clone());
|
||||
|
||||
for item in type_info.items.get_valid_contents() {
|
||||
ui.handle_create_item(&item);
|
||||
}
|
||||
for acceptor in type_info.acceptors.get_valid_contents() {
|
||||
ui.handle_create_acceptor(&acceptor);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn send_state(&self, state: &str, name: &str) {
|
||||
let Ok(serialized_data) = serialize(name) else {
|
||||
return;
|
||||
};
|
||||
let _ = self
|
||||
.node
|
||||
.upgrade()
|
||||
.unwrap()
|
||||
.send_remote_signal(state, flexbuffers::singleton(name).as_slice());
|
||||
.send_remote_signal(state, serialized_data);
|
||||
}
|
||||
|
||||
fn handle_create_item(&self, item: &Item) {
|
||||
let node = self.node.upgrade().unwrap();
|
||||
if let Some(client) = node.get_client() {
|
||||
let (alias_node, _) =
|
||||
item.make_alias(&client, &(node.get_path().to_string() + "/item"));
|
||||
self.aliases.add(Arc::downgrade(&alias_node));
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let Some(client) = node.get_client() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let _ = node.send_remote_signal(
|
||||
"create",
|
||||
&item.specialization.serialize_start_data(&item.uid),
|
||||
);
|
||||
if let Ok(alias_node) = item.make_alias(&client, &(node.get_path().to_string() + "/item")) {
|
||||
self.item_aliases.add(item.uid.clone(), &alias_node);
|
||||
}
|
||||
|
||||
let Ok(serialized_data) = item.specialization.serialize_start_data(&item.uid) else {
|
||||
return;
|
||||
};
|
||||
let _ = node.send_remote_signal("create_item", serialized_data);
|
||||
}
|
||||
fn handle_destroy_item(&self, item: &Item) {
|
||||
self.send_state("destroy", item.uid.as_str());
|
||||
self.item_aliases.remove(&item.uid);
|
||||
self.send_state("destroy_item", item.uid.as_str());
|
||||
}
|
||||
fn handle_capture(&self, item: &Item) {
|
||||
self.send_state("capture", item.uid.as_str());
|
||||
fn handle_capture_item(&self, item: &Item, acceptor: &ItemAcceptor) {
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let Ok(message) = serialize((item.uid.as_str(), acceptor.uid.as_str())) else {
|
||||
return;
|
||||
};
|
||||
let _ = node.send_remote_signal("capture_item", message);
|
||||
}
|
||||
fn handle_release(&self, item: &Item) {
|
||||
self.send_state("release", item.uid.as_str());
|
||||
fn handle_release_item(&self, item: &Item, acceptor: &ItemAcceptor) {
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let Ok(message) = serialize((item.uid.as_str(), acceptor.uid.as_str())) else {
|
||||
return;
|
||||
};
|
||||
let _ = node.send_remote_signal("release_item", message);
|
||||
}
|
||||
fn handle_create_acceptor(&self, acceptor: &ItemAcceptor) {
|
||||
let node = self.node.upgrade().unwrap();
|
||||
if let Some(client) = node.get_client() {
|
||||
let aliases = acceptor.make_aliases(
|
||||
&client,
|
||||
&format!("/item/{}/acceptor", self.type_info.type_name),
|
||||
);
|
||||
aliases
|
||||
.iter()
|
||||
.for_each(|alias| self.aliases.add(Arc::downgrade(alias)));
|
||||
}
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let Some(client) = node.get_client() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let Ok((alias, field_alias)) = acceptor.make_aliases(
|
||||
&client,
|
||||
&format!("/item/{}/acceptor", self.type_info.type_name),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
self.acceptor_aliases.add(acceptor.uid.clone(), &alias);
|
||||
self.acceptor_field_aliases
|
||||
.add(acceptor.uid.clone(), &field_alias);
|
||||
let Ok(message) = serialize(&acceptor.uid) else {
|
||||
return;
|
||||
};
|
||||
let _ = node.send_remote_signal("create_acceptor", message);
|
||||
}
|
||||
fn handle_destroy_acceptor(&self, _acceptor: &ItemAcceptor) {}
|
||||
fn handle_destroy_acceptor(&self, acceptor: &ItemAcceptor) {
|
||||
self.send_state("destroy_acceptor", acceptor.uid.as_str());
|
||||
self.acceptor_aliases.remove(&acceptor.uid);
|
||||
self.acceptor_field_aliases.remove(&acceptor.uid);
|
||||
}
|
||||
}
|
||||
impl Aspect for ItemUI {
|
||||
const NAME: &'static str = "Item";
|
||||
}
|
||||
impl Drop for ItemUI {
|
||||
fn drop(&mut self) {
|
||||
@@ -252,98 +327,155 @@ impl Drop for ItemUI {
|
||||
}
|
||||
|
||||
pub struct ItemAcceptor {
|
||||
uid: String,
|
||||
node: Weak<Node>,
|
||||
type_info: &'static TypeInfo,
|
||||
field: Mutex<Weak<Field>>,
|
||||
accepted: Registry<Item>,
|
||||
pub type_info: &'static TypeInfo,
|
||||
field: Arc<Field>,
|
||||
accepted_aliases: LifeLinkedNodeMap<String>,
|
||||
accepted_registry: Registry<Item>,
|
||||
}
|
||||
impl ItemAcceptor {
|
||||
fn add_to(node: &Arc<Node>, type_info: &'static TypeInfo, field: Weak<Field>) {
|
||||
fn add_to(node: &Arc<Node>, type_info: &'static TypeInfo, field: Arc<Field>) {
|
||||
let acceptor = type_info.acceptors.add(ItemAcceptor {
|
||||
uid: nanoid!(),
|
||||
node: Arc::downgrade(node),
|
||||
type_info,
|
||||
field: Mutex::new(field),
|
||||
accepted: Registry::new(),
|
||||
field,
|
||||
accepted_aliases: Default::default(),
|
||||
accepted_registry: Registry::new(),
|
||||
});
|
||||
node.add_local_signal("capture", ItemAcceptor::capture_flex);
|
||||
if let Some(ui) = type_info.ui.lock().upgrade() {
|
||||
ui.handle_create_acceptor(&acceptor);
|
||||
}
|
||||
let _ = node.item_acceptor.set(acceptor);
|
||||
node.add_aspect_raw(acceptor);
|
||||
}
|
||||
fn make_aliases(&self, client: &Arc<Client>, parent: &str) -> Vec<Arc<Node>> {
|
||||
let mut aliases = Vec::new();
|
||||
|
||||
fn capture_flex(node: Arc<Node>, calling_client: Arc<Client>, message: Message) -> Result<()> {
|
||||
if !node.enabled.load(Ordering::Relaxed) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let acceptor = node.get_aspect::<ItemAcceptor>().unwrap();
|
||||
let item_path: &str = deserialize(message.as_ref())?;
|
||||
let item_node = calling_client.get_node("Item", item_path)?;
|
||||
let item = item_node.get_aspect::<Item>()?;
|
||||
capture(&item, &acceptor);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn make_aliases(&self, client: &Arc<Client>, parent: &str) -> Result<(Arc<Node>, Arc<Node>)> {
|
||||
let acceptor_node = &self.node.upgrade().unwrap();
|
||||
let acceptor_alias = Alias::new(
|
||||
let acceptor_alias = Alias::create(
|
||||
client,
|
||||
parent,
|
||||
acceptor_node.uid.as_str(),
|
||||
&self.uid,
|
||||
acceptor_node,
|
||||
AliasInfo {
|
||||
local_signals: vec!["release"],
|
||||
server_signals: vec!["capture"],
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
if let Some(field) = self.field.lock().upgrade() {
|
||||
let acceptor_field_alias = Alias::new(
|
||||
client,
|
||||
acceptor_alias.get_path(),
|
||||
"field",
|
||||
&field.spatial_ref().node.upgrade().unwrap(),
|
||||
AliasInfo::default(),
|
||||
);
|
||||
)?;
|
||||
|
||||
aliases.push(acceptor_field_alias);
|
||||
}
|
||||
aliases.push(acceptor_alias);
|
||||
aliases
|
||||
}
|
||||
fn send_event(&self, state: &str, name: &str) {
|
||||
let _ = self
|
||||
.node
|
||||
.upgrade()
|
||||
.unwrap()
|
||||
.send_remote_signal(state, flexbuffers::singleton(name).as_slice());
|
||||
let acceptor_field_alias = Alias::create(
|
||||
client,
|
||||
acceptor_alias.get_path(),
|
||||
"field",
|
||||
&self.field.spatial_ref().node.upgrade().unwrap(),
|
||||
AliasInfo::default(),
|
||||
)?;
|
||||
|
||||
Ok((acceptor_alias, acceptor_field_alias))
|
||||
}
|
||||
fn handle_capture(&self, item: &Arc<Item>) {
|
||||
self.accepted.add_raw(item);
|
||||
self.send_event("capture", item.uid.as_str());
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let Some(client) = node.get_client() else {
|
||||
return;
|
||||
};
|
||||
|
||||
self.accepted_registry.add_raw(item);
|
||||
if let Ok(alias_node) = item.make_alias(&client, &node.path) {
|
||||
self.accepted_aliases.add(item.uid.clone(), &alias_node);
|
||||
}
|
||||
|
||||
let Ok(serialized_data) = item.specialization.serialize_start_data(&item.uid) else {
|
||||
return;
|
||||
};
|
||||
let _ = node.send_remote_signal("capture", serialized_data);
|
||||
}
|
||||
fn handle_release(&self, item: &Item) {
|
||||
self.accepted.remove(item);
|
||||
self.send_event("release", item.uid.as_str());
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
|
||||
self.accepted_registry.remove(item);
|
||||
self.accepted_aliases.remove(&item.uid);
|
||||
let Ok(message) = serialize(&item.uid) else {
|
||||
return;
|
||||
};
|
||||
let _ = node.send_remote_signal("release", message);
|
||||
}
|
||||
}
|
||||
impl Aspect for ItemAcceptor {
|
||||
const NAME: &'static str = "ItemAcceptor";
|
||||
}
|
||||
impl Drop for ItemAcceptor {
|
||||
fn drop(&mut self) {
|
||||
self.type_info.acceptors.remove(self);
|
||||
for item in self.accepted_registry.get_valid_contents() {
|
||||
release(&item);
|
||||
}
|
||||
if let Some(ui) = self.type_info.ui.lock().upgrade() {
|
||||
ui.handle_destroy_acceptor(self);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_interface(client: &Arc<Client>) {
|
||||
let node = Node::create(client, "", "item", false);
|
||||
pub fn create_interface(client: &Arc<Client>) -> Result<()> {
|
||||
let node = Node::create_parent_name(client, "", "item", false);
|
||||
node.add_local_signal("create_camera_item", camera::create_camera_item_flex);
|
||||
node.add_local_signal(
|
||||
"createEnvironmentItem",
|
||||
"create_environment_item",
|
||||
environment::create_environment_item_flex,
|
||||
);
|
||||
node.add_local_signal(
|
||||
"registerEnvironmentItemUI",
|
||||
environment::register_environment_item_ui_flex,
|
||||
);
|
||||
node.add_local_signal("registerPanelItemUI", register_panel_item_ui_flex);
|
||||
node.add_local_signal(
|
||||
"createEnvironmentItemAcceptor",
|
||||
environment::create_environment_item_acceptor_flex,
|
||||
);
|
||||
node.add_to_scenegraph();
|
||||
node.add_local_signal("register_item_ui", register_item_ui_flex);
|
||||
node.add_local_signal("create_item_acceptor", create_item_acceptor_flex);
|
||||
node.add_to_scenegraph().map(|_| ())
|
||||
}
|
||||
|
||||
pub(self) fn create_item_acceptor_flex(
|
||||
fn type_info(name: &str) -> Result<&'static TypeInfo> {
|
||||
match name {
|
||||
"environment" => Ok(&ITEM_TYPE_INFO_ENVIRONMENT),
|
||||
#[cfg(feature = "wayland")]
|
||||
"panel" => Ok(&ITEM_TYPE_INFO_PANEL),
|
||||
_ => Err(eyre!("Invalid item type")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register_item_ui_flex(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
type_info: &'static TypeInfo,
|
||||
message: Message,
|
||||
) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct RegisterItemUIInfo<'a> {
|
||||
item_type: &'a str,
|
||||
}
|
||||
let info: RegisterItemUIInfo = deserialize(message.as_ref())?;
|
||||
let type_info = type_info(info.item_type)?;
|
||||
let ui = Node::create_parent_name(&calling_client, "/item", type_info.type_name, true)
|
||||
.add_to_scenegraph()?;
|
||||
ItemUI::add_to(&ui, type_info)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn create_item_acceptor_flex(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
message: Message,
|
||||
) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct CreateItemAcceptorInfo<'a> {
|
||||
@@ -351,28 +483,24 @@ pub(self) fn create_item_acceptor_flex(
|
||||
parent_path: &'a str,
|
||||
transform: Transform,
|
||||
field_path: &'a str,
|
||||
item_type: &'a str,
|
||||
}
|
||||
let info: CreateItemAcceptorInfo = deserialize(data)?;
|
||||
let parent_name = format!("/item/{}/acceptor/", ITEM_TYPE_INFO_ENVIRONMENT.type_name);
|
||||
let space = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||
let transform = parse_transform(info.transform, true, true, false)?;
|
||||
let info: CreateItemAcceptorInfo = deserialize(message.as_ref())?;
|
||||
let space = calling_client
|
||||
.get_node("Reference space", info.parent_path)?
|
||||
.get_aspect::<Spatial>()?;
|
||||
let transform = parse_transform(info.transform, true, true, false);
|
||||
let field = find_field(&calling_client, info.field_path)?;
|
||||
let type_info = type_info(info.item_type)?;
|
||||
|
||||
let node = Node::create(&INTERNAL_CLIENT, &parent_name, info.name, true).add_to_scenegraph();
|
||||
Spatial::add_to(&node, Some(space), transform)?;
|
||||
ItemAcceptor::add_to(&node, type_info, Arc::downgrade(&field));
|
||||
node.item
|
||||
.get()
|
||||
.unwrap()
|
||||
.make_alias(&calling_client, &parent_name);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn register_item_ui_flex(
|
||||
calling_client: Arc<Client>,
|
||||
type_info: &'static TypeInfo,
|
||||
) -> Result<()> {
|
||||
let ui = Node::create(&calling_client, "/item", type_info.type_name, true).add_to_scenegraph();
|
||||
ItemUI::add_to(&ui, type_info)?;
|
||||
let node = Node::create_parent_name(
|
||||
&calling_client,
|
||||
&format!("/item/{}/acceptor", type_info.type_name),
|
||||
info.name,
|
||||
true,
|
||||
)
|
||||
.add_to_scenegraph()?;
|
||||
Spatial::add_to(&node, Some(space.clone()), transform, false);
|
||||
ItemAcceptor::add_to(&node, type_info, field);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
601
src/nodes/items/panel.rs
Normal file
601
src/nodes/items/panel.rs
Normal file
@@ -0,0 +1,601 @@
|
||||
use crate::{
|
||||
core::{
|
||||
client::{get_env, state, Client, INTERNAL_CLIENT},
|
||||
registry::Registry,
|
||||
},
|
||||
nodes::{
|
||||
drawable::model::ModelPart,
|
||||
items::{Item, ItemType, TypeInfo},
|
||||
spatial::Spatial,
|
||||
Message, Node,
|
||||
},
|
||||
};
|
||||
use color_eyre::eyre::{eyre, Result};
|
||||
use glam::Mat4;
|
||||
use lazy_static::lazy_static;
|
||||
use mint::Vector2;
|
||||
use nanoid::nanoid;
|
||||
use rustc_hash::FxHashMap;
|
||||
use serde::{
|
||||
de::{Deserializer, Error, SeqAccess, Visitor},
|
||||
ser::Serializer,
|
||||
Deserialize, Serialize,
|
||||
};
|
||||
use stardust_xr::schemas::flex::{deserialize, serialize};
|
||||
use std::sync::{Arc, Weak};
|
||||
use tracing::{debug, info};
|
||||
|
||||
lazy_static! {
|
||||
pub static ref ITEM_TYPE_INFO_PANEL: TypeInfo = TypeInfo {
|
||||
type_name: "panel",
|
||||
aliased_local_signals: vec![
|
||||
"apply_surface_material",
|
||||
"close_toplevel",
|
||||
"auto_size_toplevel",
|
||||
"set_toplevel_size",
|
||||
"set_toplevel_focused_visuals",
|
||||
"pointer_motion",
|
||||
"pointer_button",
|
||||
"pointer_scroll",
|
||||
"keyboard_keymap",
|
||||
"keyboard_key",
|
||||
"touch_down",
|
||||
"touch_move",
|
||||
"touch_up",
|
||||
"reset_touches",
|
||||
],
|
||||
aliased_local_methods: vec![],
|
||||
aliased_remote_signals: vec![
|
||||
"toplevel_parent_changed",
|
||||
"toplevel_title_changed",
|
||||
"toplevel_app_id_changed",
|
||||
"toplevel_fullscreen_active",
|
||||
"toplevel_move_request",
|
||||
"toplevel_resize_request",
|
||||
"toplevel_size_changed",
|
||||
"set_cursor",
|
||||
"new_child",
|
||||
"reposition_child",
|
||||
"drop_child",
|
||||
],
|
||||
ui: Default::default(),
|
||||
items: Registry::new(),
|
||||
acceptors: Registry::new(),
|
||||
};
|
||||
}
|
||||
|
||||
/// An ID for a surface inside this panel item
|
||||
#[derive(Debug, Clone)]
|
||||
#[allow(dead_code)]
|
||||
pub enum SurfaceID {
|
||||
Cursor,
|
||||
Toplevel,
|
||||
Child(String),
|
||||
}
|
||||
impl Default for SurfaceID {
|
||||
fn default() -> Self {
|
||||
Self::Toplevel
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> serde::Deserialize<'de> for SurfaceID {
|
||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
deserializer.deserialize_seq(SurfaceIDVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
struct SurfaceIDVisitor;
|
||||
|
||||
impl<'de> Visitor<'de> for SurfaceIDVisitor {
|
||||
type Value = SurfaceID;
|
||||
|
||||
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
f.write_str("idk")
|
||||
}
|
||||
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
|
||||
let Some(discrim) = seq.next_element()? else {
|
||||
return Err(A::Error::missing_field("discrim"));
|
||||
};
|
||||
|
||||
// idk if you wanna check for extraneous elements
|
||||
// I didn't bother
|
||||
|
||||
match discrim {
|
||||
"Cursor" => Ok(SurfaceID::Cursor),
|
||||
"Toplevel" => Ok(SurfaceID::Toplevel),
|
||||
"Child" => {
|
||||
let Some(text) = seq.next_element()? else {
|
||||
return Err(A::Error::missing_field("child_text"));
|
||||
};
|
||||
Ok(SurfaceID::Child(text))
|
||||
}
|
||||
_ => Err(A::Error::unknown_variant(
|
||||
discrim,
|
||||
&["Cursor", "Toplevel", "Child"],
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl serde::Serialize for SurfaceID {
|
||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
match self {
|
||||
Self::Cursor => ["Cursor"].serialize(serializer),
|
||||
Self::Toplevel => ["Toplevel"].serialize(serializer),
|
||||
Self::Child(text) => ["Child", text].serialize(serializer),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The origin and size of the surface's "solid" part.
|
||||
#[derive(Debug, Serialize, Clone, Copy)]
|
||||
pub struct Geometry {
|
||||
pub origin: Vector2<i32>,
|
||||
pub size: Vector2<u32>,
|
||||
}
|
||||
/// The state of the panel item's toplevel.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct ToplevelInfo {
|
||||
/// The UID of the panel item of the parent of this toplevel, if it exists
|
||||
pub parent: Option<String>,
|
||||
/// Equivalent to the window title
|
||||
pub title: Option<String>,
|
||||
/// Application identifier, see <https://standards.freedesktop.org/desktop-entry-spec/>
|
||||
pub app_id: Option<String>,
|
||||
/// Current size in pixels
|
||||
pub size: Vector2<u32>,
|
||||
/// Recommended minimum size in pixels
|
||||
pub min_size: Option<Vector2<u32>>,
|
||||
/// Recommended maximum size in pixels
|
||||
pub max_size: Option<Vector2<u32>>,
|
||||
/// Surface geometry
|
||||
pub logical_rectangle: Geometry,
|
||||
}
|
||||
|
||||
/// Data on positioning a child
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct ChildInfo {
|
||||
pub parent: SurfaceID,
|
||||
pub geometry: Geometry,
|
||||
}
|
||||
|
||||
/// The init data for the panel item.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct PanelItemInitData {
|
||||
/// The cursor, if applicable.
|
||||
pub cursor: Option<Geometry>,
|
||||
/// Size of the toplevel surface in pixels.
|
||||
pub toplevel: ToplevelInfo,
|
||||
/// Vector of childs that already exist
|
||||
pub children: FxHashMap<String, ChildInfo>,
|
||||
/// The surface, if any, that has exclusive input to the pointer.
|
||||
pub pointer_grab: Option<SurfaceID>,
|
||||
/// The surface, if any, that has exclusive input to the keyboard.
|
||||
pub keyboard_grab: Option<SurfaceID>,
|
||||
}
|
||||
|
||||
pub trait Backend: Send + Sync + 'static {
|
||||
fn start_data(&self) -> Result<PanelItemInitData>;
|
||||
|
||||
fn apply_surface_material(&self, surface: SurfaceID, model_part: &Arc<ModelPart>);
|
||||
|
||||
fn close_toplevel(&self);
|
||||
fn auto_size_toplevel(&self);
|
||||
fn set_toplevel_size(&self, size: Vector2<u32>);
|
||||
fn set_toplevel_focused_visuals(&self, focused: bool);
|
||||
|
||||
fn pointer_motion(&self, surface: &SurfaceID, position: Vector2<f32>);
|
||||
fn pointer_button(&self, surface: &SurfaceID, button: u32, pressed: bool);
|
||||
fn pointer_scroll(
|
||||
&self,
|
||||
surface: &SurfaceID,
|
||||
scroll_distance: Option<Vector2<f32>>,
|
||||
scroll_steps: Option<Vector2<f32>>,
|
||||
);
|
||||
|
||||
fn keyboard_keys(&self, surface: &SurfaceID, keymap_id: &str, keys: Vec<i32>);
|
||||
|
||||
fn touch_down(&self, surface: &SurfaceID, id: u32, position: Vector2<f32>);
|
||||
fn touch_move(&self, id: u32, position: Vector2<f32>);
|
||||
fn touch_up(&self, id: u32);
|
||||
fn reset_touches(&self);
|
||||
}
|
||||
|
||||
pub fn panel_item_from_node(node: &Node) -> Option<Arc<dyn PanelItemTrait>> {
|
||||
let ItemType::Panel(panel_item) = &node.get_aspect::<Item>().ok()?.specialization else {
|
||||
return None;
|
||||
};
|
||||
Some(panel_item.clone())
|
||||
}
|
||||
|
||||
pub trait PanelItemTrait: Backend + Send + Sync + 'static {
|
||||
fn uid(&self) -> &str;
|
||||
fn serialize_start_data(&self, id: &str) -> Result<Message>;
|
||||
}
|
||||
|
||||
pub struct PanelItem<B: Backend + ?Sized> {
|
||||
pub uid: String,
|
||||
node: Weak<Node>,
|
||||
pub backend: Box<B>,
|
||||
}
|
||||
impl<B: Backend + ?Sized> PanelItem<B> {
|
||||
pub fn create(backend: Box<B>, pid: Option<i32>) -> (Arc<Node>, Arc<PanelItem<B>>) {
|
||||
debug!(?pid, "Create panel item");
|
||||
|
||||
let startup_settings = pid
|
||||
.and_then(|pid| get_env(pid).ok())
|
||||
.and_then(|env| state(&env));
|
||||
|
||||
let uid = nanoid!();
|
||||
let node = Arc::new(Node::create_parent_name(
|
||||
&INTERNAL_CLIENT,
|
||||
"/item/panel/item",
|
||||
&uid,
|
||||
true,
|
||||
));
|
||||
let spatial = Spatial::add_to(&node, None, Mat4::IDENTITY, false);
|
||||
if let Some(startup_settings) = &startup_settings {
|
||||
spatial.set_local_transform(startup_settings.root);
|
||||
}
|
||||
|
||||
let panel_item = Arc::new(PanelItem {
|
||||
uid: uid.clone(),
|
||||
node: Arc::downgrade(&node),
|
||||
backend,
|
||||
});
|
||||
|
||||
let generic_panel_item: Arc<dyn PanelItemTrait> = panel_item.clone();
|
||||
Item::add_to(
|
||||
&node,
|
||||
uid,
|
||||
&ITEM_TYPE_INFO_PANEL,
|
||||
ItemType::Panel(generic_panel_item),
|
||||
);
|
||||
|
||||
node.add_local_signal("apply_surface_material", Self::apply_surface_material_flex);
|
||||
node.add_local_signal("close_toplevel", Self::close_toplevel_flex);
|
||||
node.add_local_signal("auto_size_toplevel", Self::auto_size_toplevel_flex);
|
||||
node.add_local_signal("set_toplevel_size", Self::set_toplevel_size_flex);
|
||||
|
||||
node.add_local_signal("pointer_motion", Self::pointer_motion_flex);
|
||||
node.add_local_signal("pointer_button", Self::pointer_button_flex);
|
||||
node.add_local_signal("pointer_scroll", Self::pointer_scroll_flex);
|
||||
|
||||
node.add_local_signal("keyboard_key", Self::keyboard_keys_flex);
|
||||
|
||||
node.add_local_signal("touch_down", Self::touch_down_flex);
|
||||
node.add_local_signal("touch_move", Self::touch_move_flex);
|
||||
node.add_local_signal("touch_up", Self::touch_up_flex);
|
||||
node.add_local_signal("reset_touches", Self::reset_touches_flex);
|
||||
|
||||
(node, panel_item)
|
||||
}
|
||||
pub fn drop_toplevel(&self) {
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
node.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
// Remote signals
|
||||
impl<B: Backend + ?Sized> PanelItem<B> {
|
||||
pub fn toplevel_parent_changed(&self, parent: &str) {
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let _ = node.send_remote_signal("toplevel_parent_changed", serialize(parent).unwrap());
|
||||
}
|
||||
pub fn toplevel_title_changed(&self, title: &str) {
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let _ = node.send_remote_signal("toplevel_title_changed", serialize(title).unwrap());
|
||||
}
|
||||
pub fn toplevel_app_id_changed(&self, app_id: &str) {
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let _ = node.send_remote_signal("toplevel_app_id_changed", serialize(app_id).unwrap());
|
||||
}
|
||||
pub fn toplevel_fullscreen_active(&self, active: bool) {
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let _ = node.send_remote_signal("toplevel_fullscreen_active", serialize(active).unwrap());
|
||||
}
|
||||
pub fn toplevel_move_request(&self) {
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let _ = node.send_remote_signal("toplevel_move_request", Vec::<u8>::new());
|
||||
}
|
||||
pub fn toplevel_resize_request(&self, up: bool, down: bool, left: bool, right: bool) {
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let _ = node.send_remote_signal(
|
||||
"toplevel_resize_request",
|
||||
serialize((up, down, left, right)).unwrap(),
|
||||
);
|
||||
}
|
||||
pub fn toplevel_size_changed(&self, size: Vector2<u32>) {
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let _ = node.send_remote_signal("toplevel_size_changed", serialize(size).unwrap());
|
||||
}
|
||||
|
||||
pub fn set_cursor(&self, geometry: Option<Geometry>) {
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let _ = node.send_remote_signal("set_cursor", serialize(geometry).unwrap());
|
||||
}
|
||||
|
||||
pub fn new_child(&self, uid: &str, info: ChildInfo) {
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let _ = node.send_remote_signal("new_child", serialize((uid, info)).unwrap());
|
||||
}
|
||||
pub fn reposition_child(&self, uid: &str, geometry: Geometry) {
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let _ = node.send_remote_signal("reposition_child", serialize((uid, geometry)).unwrap());
|
||||
}
|
||||
pub fn drop_child(&self, uid: &str) {
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let _ = node.send_remote_signal("drop_child", serialize(uid).unwrap());
|
||||
}
|
||||
}
|
||||
// Local signals
|
||||
macro_rules! flex_no_args {
|
||||
($fn_name: ident, $trait_fn: ident) => {
|
||||
fn $fn_name(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
_message: Message,
|
||||
) -> Result<()> {
|
||||
let Some(panel_item) = panel_item_from_node(&node) else {
|
||||
return Ok(());
|
||||
};
|
||||
panel_item.$trait_fn();
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
}
|
||||
macro_rules! flex_deserialize {
|
||||
($fn_name: ident, $trait_fn: ident) => {
|
||||
fn $fn_name(node: Arc<Node>, _calling_client: Arc<Client>, message: Message) -> Result<()> {
|
||||
let Some(panel_item) = panel_item_from_node(&node) else {
|
||||
return Ok(());
|
||||
};
|
||||
panel_item.$trait_fn(deserialize(message.as_ref())?);
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
}
|
||||
impl<B: Backend + ?Sized> PanelItem<B> {
|
||||
fn apply_surface_material_flex(
|
||||
node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
message: Message,
|
||||
) -> Result<()> {
|
||||
let Some(panel_item) = panel_item_from_node(&node) else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SurfaceMaterialInfo<'a> {
|
||||
surface: SurfaceID,
|
||||
model_node_path: &'a str,
|
||||
}
|
||||
|
||||
let info: SurfaceMaterialInfo = deserialize(message.as_ref())?;
|
||||
|
||||
let model_node = calling_client
|
||||
.scenegraph
|
||||
.get_node(info.model_node_path)
|
||||
.ok_or_else(|| eyre!("Model node not found"))?;
|
||||
let model_part = model_node.get_aspect::<ModelPart>()?;
|
||||
debug!(?info, "Apply surface material");
|
||||
|
||||
panel_item.apply_surface_material(info.surface, &model_part);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
flex_no_args!(close_toplevel_flex, close_toplevel);
|
||||
flex_no_args!(auto_size_toplevel_flex, auto_size_toplevel);
|
||||
flex_deserialize!(set_toplevel_size_flex, set_toplevel_size);
|
||||
|
||||
fn pointer_motion_flex(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
message: Message,
|
||||
) -> Result<()> {
|
||||
let Some(panel_item) = panel_item_from_node(&node) else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let (surface_id, position): (SurfaceID, Vector2<f32>) = deserialize(message.as_ref())?;
|
||||
debug!(?surface_id, ?position, "Pointer deactivate");
|
||||
|
||||
panel_item.pointer_motion(&surface_id, position);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
fn pointer_button_flex(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
message: Message,
|
||||
) -> Result<()> {
|
||||
let Some(panel_item) = panel_item_from_node(&node) else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let (surface_id, button, state): (SurfaceID, u32, u32) = deserialize(message.as_ref())?;
|
||||
debug!(?surface_id, button, state, "Pointer button");
|
||||
|
||||
panel_item.pointer_button(&surface_id, button, state != 0);
|
||||
Ok(())
|
||||
}
|
||||
fn pointer_scroll_flex(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
message: Message,
|
||||
) -> Result<()> {
|
||||
let Some(panel_item) = panel_item_from_node(&node) else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct PointerScrollInfo {
|
||||
surface_id: SurfaceID,
|
||||
axis_continuous: Option<Vector2<f32>>,
|
||||
axis_discrete: Option<Vector2<f32>>,
|
||||
}
|
||||
let info: PointerScrollInfo = deserialize(message.as_ref())?;
|
||||
debug!(?info, "Pointer scroll");
|
||||
|
||||
panel_item.pointer_scroll(&info.surface_id, info.axis_continuous, info.axis_discrete);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn keyboard_keys_flex(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
message: Message,
|
||||
) -> Result<()> {
|
||||
let Some(panel_item) = panel_item_from_node(&node) else {
|
||||
return Ok(());
|
||||
};
|
||||
let (surface_id, keymap_id, keys): (SurfaceID, &str, Vec<i32>) =
|
||||
deserialize(message.as_ref())?;
|
||||
debug!(?keys, "Set keyboard key state");
|
||||
|
||||
panel_item.keyboard_keys(&surface_id, keymap_id, keys);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
pub fn grab_keyboard(&self, sid: Option<SurfaceID>) {
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let Ok(message) = serialize(sid) else { return };
|
||||
let _ = node.send_remote_signal("grab_keyboard", message);
|
||||
}
|
||||
|
||||
fn touch_down_flex(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
message: Message,
|
||||
) -> Result<()> {
|
||||
let Some(panel_item) = panel_item_from_node(&node) else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let (surface_id, id, position): (SurfaceID, u32, Vector2<f32>) =
|
||||
deserialize(message.as_ref())?;
|
||||
debug!(?surface_id, id, ?position, "Touch down");
|
||||
|
||||
panel_item.touch_down(&surface_id, id, position);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
fn touch_move_flex(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
message: Message,
|
||||
) -> Result<()> {
|
||||
let Some(panel_item) = panel_item_from_node(&node) else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let (id, position): (u32, Vector2<f32>) = deserialize(message.as_ref())?;
|
||||
debug!(?position, "Touch move");
|
||||
|
||||
panel_item.touch_move(id, position);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
flex_deserialize!(touch_up_flex, touch_up);
|
||||
flex_no_args!(reset_touches_flex, reset_touches);
|
||||
}
|
||||
impl<B: Backend + ?Sized> PanelItemTrait for PanelItem<B> {
|
||||
fn uid(&self) -> &str {
|
||||
&self.uid
|
||||
}
|
||||
|
||||
fn serialize_start_data(&self, id: &str) -> Result<Message> {
|
||||
Ok(serialize((id, self.start_data()?))?.into())
|
||||
}
|
||||
}
|
||||
impl<B: Backend + ?Sized> Backend for PanelItem<B> {
|
||||
fn start_data(&self) -> Result<PanelItemInitData> {
|
||||
self.backend.start_data()
|
||||
}
|
||||
|
||||
fn apply_surface_material(&self, surface: SurfaceID, model_part: &Arc<ModelPart>) {
|
||||
self.backend.apply_surface_material(surface, model_part)
|
||||
}
|
||||
|
||||
fn close_toplevel(&self) {
|
||||
self.backend.close_toplevel()
|
||||
}
|
||||
fn auto_size_toplevel(&self) {
|
||||
self.backend.auto_size_toplevel()
|
||||
}
|
||||
fn set_toplevel_size(&self, size: Vector2<u32>) {
|
||||
self.backend.set_toplevel_size(size)
|
||||
}
|
||||
fn set_toplevel_focused_visuals(&self, focused: bool) {
|
||||
self.backend.set_toplevel_focused_visuals(focused)
|
||||
}
|
||||
|
||||
fn pointer_motion(&self, surface: &SurfaceID, position: Vector2<f32>) {
|
||||
self.backend.pointer_motion(surface, position)
|
||||
}
|
||||
fn pointer_button(&self, surface: &SurfaceID, button: u32, pressed: bool) {
|
||||
self.backend.pointer_button(surface, button, pressed)
|
||||
}
|
||||
fn pointer_scroll(
|
||||
&self,
|
||||
surface: &SurfaceID,
|
||||
scroll_distance: Option<Vector2<f32>>,
|
||||
scroll_steps: Option<Vector2<f32>>,
|
||||
) {
|
||||
self.backend
|
||||
.pointer_scroll(surface, scroll_distance, scroll_steps)
|
||||
}
|
||||
|
||||
fn keyboard_keys(&self, surface: &SurfaceID, keymap_id: &str, keys: Vec<i32>) {
|
||||
self.backend.keyboard_keys(surface, keymap_id, keys)
|
||||
}
|
||||
|
||||
fn touch_down(&self, surface: &SurfaceID, id: u32, position: Vector2<f32>) {
|
||||
self.backend.touch_down(surface, id, position)
|
||||
}
|
||||
fn touch_move(&self, id: u32, position: Vector2<f32>) {
|
||||
self.backend.touch_move(id, position)
|
||||
}
|
||||
fn touch_up(&self, id: u32) {
|
||||
self.backend.touch_up(id)
|
||||
}
|
||||
fn reset_touches(&self) {
|
||||
self.backend.reset_touches()
|
||||
}
|
||||
}
|
||||
impl<B: Backend + ?Sized> Drop for PanelItem<B> {
|
||||
fn drop(&mut self) {
|
||||
// Dropped panel item, basically just a debug breakpoint place
|
||||
info!("Dropped panel item {}", self.uid);
|
||||
}
|
||||
}
|
||||
378
src/nodes/mod.rs
378
src/nodes/mod.rs
@@ -1,4 +1,5 @@
|
||||
pub mod alias;
|
||||
pub mod audio;
|
||||
pub mod data;
|
||||
pub mod drawable;
|
||||
pub mod fields;
|
||||
@@ -7,75 +8,65 @@ pub mod input;
|
||||
pub mod items;
|
||||
pub mod root;
|
||||
pub mod spatial;
|
||||
pub mod startup;
|
||||
|
||||
use anyhow::{anyhow, Result};
|
||||
use color_eyre::eyre::{eyre, Result};
|
||||
use nanoid::nanoid;
|
||||
use once_cell::sync::OnceCell;
|
||||
use parking_lot::Mutex;
|
||||
use portable_atomic::{AtomicBool, Ordering};
|
||||
use rustc_hash::FxHashMap;
|
||||
use serde::{de::DeserializeOwned, Serialize};
|
||||
use stardust_xr::messenger::MessageSenderHandle;
|
||||
use stardust_xr::scenegraph::ScenegraphError;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use stardust_xr::schemas::flex::{deserialize, serialize};
|
||||
use std::any::{Any, TypeId};
|
||||
use std::fmt::Debug;
|
||||
use std::os::fd::OwnedFd;
|
||||
use std::sync::{Arc, Weak};
|
||||
use std::vec::Vec;
|
||||
|
||||
use core::hash::BuildHasherDefault;
|
||||
use dashmap::DashMap;
|
||||
use rustc_hash::FxHasher;
|
||||
|
||||
use crate::core::client::Client;
|
||||
use crate::core::registry::Registry;
|
||||
use crate::core::scenegraph::MethodResponseSender;
|
||||
|
||||
use self::alias::Alias;
|
||||
use self::data::{PulseReceiver, PulseSender};
|
||||
|
||||
use self::drawable::model::Model;
|
||||
use self::drawable::text::Text;
|
||||
use self::fields::Field;
|
||||
use self::input::{InputHandler, InputMethod};
|
||||
use self::items::{Item, ItemAcceptor, ItemUI};
|
||||
use self::spatial::Spatial;
|
||||
use self::startup::StartupSettings;
|
||||
|
||||
pub type Signal = fn(&Node, Arc<Client>, &[u8]) -> Result<()>;
|
||||
pub type Method = fn(&Node, Arc<Client>, &[u8]) -> Result<Vec<u8>>;
|
||||
|
||||
pub struct Node {
|
||||
pub(super) uid: String,
|
||||
path: String,
|
||||
// trailing_slash_pos: usize,
|
||||
local_signals: DashMap<String, Signal, BuildHasherDefault<FxHasher>>,
|
||||
local_methods: DashMap<String, Method, BuildHasherDefault<FxHasher>>,
|
||||
destroyable: AtomicBool,
|
||||
|
||||
pub alias: OnceCell<Arc<Alias>>,
|
||||
aliases: Registry<Alias>,
|
||||
|
||||
pub spatial: OnceCell<Arc<Spatial>>,
|
||||
pub field: OnceCell<Arc<Field>>,
|
||||
|
||||
// Data
|
||||
pub pulse_sender: OnceCell<Arc<PulseSender>>,
|
||||
pub pulse_receiver: OnceCell<Arc<PulseReceiver>>,
|
||||
|
||||
// Drawable
|
||||
pub model: OnceCell<Arc<Model>>,
|
||||
pub text: OnceCell<Arc<Text>>,
|
||||
|
||||
// Input
|
||||
pub input_method: OnceCell<Arc<InputMethod>>,
|
||||
pub input_handler: OnceCell<Arc<InputHandler>>,
|
||||
|
||||
// Item
|
||||
pub item: OnceCell<Arc<Item>>,
|
||||
pub item_acceptor: OnceCell<Arc<ItemAcceptor>>,
|
||||
pub item_ui: OnceCell<Arc<ItemUI>>,
|
||||
|
||||
// Startup
|
||||
pub startup_settings: OnceCell<Mutex<StartupSettings>>,
|
||||
|
||||
pub(crate) client: Weak<Client>,
|
||||
#[derive(Default)]
|
||||
pub struct Message {
|
||||
pub data: Vec<u8>,
|
||||
pub fds: Vec<OwnedFd>,
|
||||
}
|
||||
impl From<Vec<u8>> for Message {
|
||||
fn from(data: Vec<u8>) -> Self {
|
||||
Message {
|
||||
data,
|
||||
fds: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl AsRef<[u8]> for Message {
|
||||
fn as_ref(&self) -> &[u8] {
|
||||
&self.data
|
||||
}
|
||||
}
|
||||
|
||||
pub type Signal = fn(Arc<Node>, Arc<Client>, Message) -> Result<()>;
|
||||
pub type Method = fn(Arc<Node>, Arc<Client>, Message, MethodResponseSender);
|
||||
|
||||
stardust_xr_server_codegen::codegen_node_protocol!();
|
||||
|
||||
pub struct Node {
|
||||
pub enabled: Arc<AtomicBool>,
|
||||
pub(super) uid: String,
|
||||
path: String,
|
||||
client: Weak<Client>,
|
||||
message_sender_handle: Option<MessageSenderHandle>,
|
||||
// trailing_slash_pos: usize,
|
||||
local_signals: Mutex<FxHashMap<String, Signal>>,
|
||||
local_methods: Mutex<FxHashMap<String, Method>>,
|
||||
aliases: Registry<Alias>,
|
||||
aspects: Aspects,
|
||||
destroyable: bool,
|
||||
}
|
||||
impl Node {
|
||||
pub fn get_client(&self) -> Option<Arc<Client>> {
|
||||
self.client.upgrade()
|
||||
@@ -86,162 +77,241 @@ impl Node {
|
||||
pub fn get_path(&self) -> &str {
|
||||
self.path.as_str()
|
||||
}
|
||||
pub fn is_destroyable(&self) -> bool {
|
||||
self.destroyable.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub fn create(client: &Arc<Client>, parent: &str, name: &str, destroyable: bool) -> Self {
|
||||
pub fn create_parent_name(
|
||||
client: &Arc<Client>,
|
||||
parent: &str,
|
||||
name: &str,
|
||||
destroyable: bool,
|
||||
) -> Self {
|
||||
let mut path = parent.to_string();
|
||||
path.push('/');
|
||||
path.push_str(name);
|
||||
Self::create_path(client, path, destroyable)
|
||||
}
|
||||
pub fn create_path(client: &Arc<Client>, path: impl ToString, destroyable: bool) -> Self {
|
||||
let node = Node {
|
||||
enabled: Arc::new(AtomicBool::new(true)),
|
||||
uid: nanoid!(),
|
||||
client: Arc::downgrade(client),
|
||||
path,
|
||||
message_sender_handle: client.message_sender_handle.clone(),
|
||||
path: path.to_string(),
|
||||
// trailing_slash_pos: parent.len(),
|
||||
local_signals: Default::default(),
|
||||
local_methods: Default::default(),
|
||||
destroyable: AtomicBool::from(destroyable),
|
||||
|
||||
alias: OnceCell::new(),
|
||||
aliases: Registry::new(),
|
||||
|
||||
spatial: OnceCell::new(),
|
||||
field: OnceCell::new(),
|
||||
pulse_sender: OnceCell::new(),
|
||||
pulse_receiver: OnceCell::new(),
|
||||
model: OnceCell::new(),
|
||||
text: OnceCell::new(),
|
||||
input_method: OnceCell::new(),
|
||||
input_handler: OnceCell::new(),
|
||||
item: OnceCell::new(),
|
||||
item_acceptor: OnceCell::new(),
|
||||
item_ui: OnceCell::new(),
|
||||
startup_settings: OnceCell::new(),
|
||||
aliases: Default::default(),
|
||||
aspects: Default::default(),
|
||||
destroyable,
|
||||
};
|
||||
node.add_local_signal("destroy", Node::destroy_flex);
|
||||
<Node as NodeAspect>::add_node_members(&node);
|
||||
node
|
||||
}
|
||||
pub fn add_to_scenegraph(self) -> Arc<Node> {
|
||||
self.get_client().unwrap().scenegraph.add_node(self)
|
||||
pub fn add_to_scenegraph(self) -> Result<Arc<Node>> {
|
||||
Ok(self
|
||||
.get_client()
|
||||
.ok_or_else(|| eyre!("Internal: Unable to get client"))?
|
||||
.scenegraph
|
||||
.add_node(self))
|
||||
}
|
||||
pub fn destroy(&self) {
|
||||
let _ = self
|
||||
.get_client()
|
||||
.map(|c| c.scenegraph.remove_node(self.get_path()));
|
||||
if let Some(client) = self.get_client() {
|
||||
client.scenegraph.remove_node(self.get_path());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn destroy_flex(node: &Node, _calling_client: Arc<Client>, _data: &[u8]) -> Result<()> {
|
||||
if node.is_destroyable() {
|
||||
node.destroy();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
// very much up for debate if we should allow this, as you can match objects using this
|
||||
// pub fn get_client_pid_flex(
|
||||
// node: Arc<Node>,
|
||||
// _calling_client: Arc<Client>,
|
||||
// _message: Message,
|
||||
// ) -> Result<Message> {
|
||||
// let client = node
|
||||
// .client
|
||||
// .upgrade()
|
||||
// .ok_or_else(|| eyre!("Could not get client for node?"))?;
|
||||
// let pid = client.pid.ok_or_else(|| eyre!("Client PID is unknown"))?;
|
||||
// Ok(serialize(pid)?.into())
|
||||
// }
|
||||
|
||||
pub fn add_local_signal(&self, name: &str, signal: Signal) {
|
||||
self.local_signals.insert(name.to_string(), signal);
|
||||
self.local_signals.lock().insert(name.to_string(), signal);
|
||||
}
|
||||
pub fn add_local_method(&self, name: &str, method: Method) {
|
||||
self.local_methods.insert(name.to_string(), method);
|
||||
self.local_methods.lock().insert(name.to_string(), method);
|
||||
}
|
||||
|
||||
pub fn get_aspect<F, T>(
|
||||
&self,
|
||||
node_name: &'static str,
|
||||
aspect_type: &'static str,
|
||||
aspect_fn: F,
|
||||
) -> Result<Arc<T>>
|
||||
where
|
||||
F: FnOnce(&Node) -> &OnceCell<Arc<T>>,
|
||||
{
|
||||
aspect_fn(self)
|
||||
.get()
|
||||
.ok_or_else(|| anyhow!("{} is not a {} node", node_name, aspect_type))
|
||||
.cloned()
|
||||
pub fn add_aspect<A: Aspect>(&self, aspect: A) -> Arc<A> {
|
||||
self.aspects.add(aspect)
|
||||
}
|
||||
pub fn add_aspect_raw<A: Aspect>(&self, aspect: Arc<A>) {
|
||||
self.aspects.add_raw(aspect)
|
||||
}
|
||||
pub fn get_aspect<A: Aspect>(&self) -> Result<Arc<A>> {
|
||||
self.aspects.get()
|
||||
}
|
||||
|
||||
pub fn send_local_signal(
|
||||
&self,
|
||||
self: Arc<Self>,
|
||||
calling_client: Arc<Client>,
|
||||
method: &str,
|
||||
data: &[u8],
|
||||
message: Message,
|
||||
) -> Result<(), ScenegraphError> {
|
||||
if let Some(alias) = self.alias.get() {
|
||||
if !alias.info.local_signals.iter().any(|e| e == &method) {
|
||||
if let Ok(alias) = self.get_aspect::<Alias>() {
|
||||
if !alias.info.server_signals.iter().any(|e| e == &method) {
|
||||
return Err(ScenegraphError::SignalNotFound);
|
||||
}
|
||||
alias
|
||||
.original
|
||||
.upgrade()
|
||||
.ok_or(ScenegraphError::BrokenAlias)?
|
||||
.send_local_signal(calling_client, method, data)
|
||||
.send_local_signal(calling_client, method, message)
|
||||
} else {
|
||||
let signal = self
|
||||
.local_signals
|
||||
.lock()
|
||||
.get(method)
|
||||
.cloned()
|
||||
.ok_or(ScenegraphError::SignalNotFound)?;
|
||||
signal(self, calling_client, data)
|
||||
.map_err(|error| ScenegraphError::SignalError { error })
|
||||
signal(self, calling_client, message).map_err(|error| ScenegraphError::SignalError {
|
||||
error: error.to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
pub fn execute_local_method(
|
||||
&self,
|
||||
self: Arc<Self>,
|
||||
calling_client: Arc<Client>,
|
||||
method: &str,
|
||||
data: &[u8],
|
||||
) -> Result<Vec<u8>, ScenegraphError> {
|
||||
if let Some(alias) = self.alias.get() {
|
||||
if !alias.info.local_methods.iter().any(|e| e == &method) {
|
||||
return Err(ScenegraphError::MethodNotFound);
|
||||
message: Message,
|
||||
response: MethodResponseSender,
|
||||
) {
|
||||
if let Ok(alias) = self.get_aspect::<Alias>() {
|
||||
if !alias.info.server_methods.iter().any(|e| e == &method) {
|
||||
response.send(Err(ScenegraphError::MethodNotFound));
|
||||
return;
|
||||
}
|
||||
alias
|
||||
.original
|
||||
.upgrade()
|
||||
.ok_or(ScenegraphError::BrokenAlias)?
|
||||
.execute_local_method(calling_client, method, data)
|
||||
let Some(alias) = alias.original.upgrade() else {
|
||||
response.send(Err(ScenegraphError::BrokenAlias));
|
||||
return;
|
||||
};
|
||||
alias.execute_local_method(
|
||||
calling_client,
|
||||
method,
|
||||
Message {
|
||||
data: message.data.clone(),
|
||||
fds: Vec::new(),
|
||||
},
|
||||
response,
|
||||
)
|
||||
} else {
|
||||
let method = self
|
||||
.local_methods
|
||||
.get(method)
|
||||
.ok_or(ScenegraphError::MethodNotFound)?;
|
||||
method(self, calling_client, data)
|
||||
.map_err(|error| ScenegraphError::MethodError { error })
|
||||
let Some(method) = self.local_methods.lock().get(method).cloned() else {
|
||||
response.send(Err(ScenegraphError::MethodNotFound));
|
||||
return;
|
||||
};
|
||||
method(self, calling_client, message, response);
|
||||
}
|
||||
}
|
||||
pub fn send_remote_signal(&self, method: &str, data: &[u8]) -> Result<()> {
|
||||
pub fn send_remote_signal(&self, method: &str, message: impl Into<Message>) -> Result<()> {
|
||||
let message = message.into();
|
||||
self.aliases
|
||||
.get_valid_contents()
|
||||
.iter()
|
||||
.filter(|alias| alias.info.remote_signals.iter().any(|e| e == &method))
|
||||
.for_each(|alias| {
|
||||
let _ = alias
|
||||
.node
|
||||
.upgrade()
|
||||
.unwrap()
|
||||
.send_remote_signal(method, data);
|
||||
.filter(|alias| alias.info.client_signals.iter().any(|e| e == &method))
|
||||
.filter_map(|alias| alias.node.upgrade())
|
||||
.for_each(|node| {
|
||||
// Beware! file descriptors will not be sent to aliases!!!
|
||||
let _ = node.send_remote_signal(
|
||||
method,
|
||||
Message {
|
||||
data: message.data.clone(),
|
||||
fds: Vec::new(),
|
||||
},
|
||||
);
|
||||
});
|
||||
let path = self.path.clone();
|
||||
let method = method.to_string();
|
||||
let data = data.to_vec();
|
||||
if let Some(client) = self.get_client() {
|
||||
if let Some(messenger) = client.messenger.as_ref() {
|
||||
messenger.send_remote_signal(path.as_str(), method.as_str(), data.as_slice());
|
||||
}
|
||||
if let Some(handle) = self.message_sender_handle.as_ref() {
|
||||
handle.signal(path.as_str(), method.as_str(), &message.data, message.fds)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub async fn execute_remote_method(&self, method: &str, data: Vec<u8>) -> Result<Vec<u8>> {
|
||||
if let Some(client) = self.get_client() {
|
||||
match client.messenger.as_ref() {
|
||||
None => Err(anyhow!("Messenger does not exist for this node's client")),
|
||||
Some(messenger) => {
|
||||
messenger
|
||||
.execute_remote_method(self.path.as_str(), method, &data)
|
||||
.await
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Err(anyhow!("Client does not exist somehow?"))
|
||||
}
|
||||
pub async fn execute_remote_method_typed<S: Serialize, D: DeserializeOwned>(
|
||||
&self,
|
||||
method: &str,
|
||||
input: S,
|
||||
fds: Vec<OwnedFd>,
|
||||
) -> Result<(D, Vec<OwnedFd>)> {
|
||||
let message_sender_handle = self
|
||||
.message_sender_handle
|
||||
.as_ref()
|
||||
.ok_or(eyre!("Messenger does not exist for this node"))?;
|
||||
|
||||
let serialized = serialize(input)?;
|
||||
let result = message_sender_handle
|
||||
.method(self.path.as_str(), method, &serialized, fds)?
|
||||
.await
|
||||
.map_err(|e| eyre!(e))?;
|
||||
|
||||
let (message, fds) = result.into_components();
|
||||
let deserialized: D = deserialize(&message)?;
|
||||
Ok((deserialized, fds))
|
||||
}
|
||||
}
|
||||
impl Debug for Node {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Node")
|
||||
.field("uid", &self.uid)
|
||||
.field("path", &self.path)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
impl NodeAspect for Node {
|
||||
fn set_enabled(node: Arc<Node>, _calling_client: Arc<Client>, enabled: bool) -> Result<()> {
|
||||
node.enabled.store(enabled, Ordering::Relaxed);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn destroy(node: Arc<Node>, _calling_client: Arc<Client>) -> Result<()> {
|
||||
if node.destroyable {
|
||||
node.destroy();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Drop for Node {
|
||||
fn drop(&mut self) {
|
||||
// Debug breakpoint
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Aspect: Any + Send + Sync + 'static {
|
||||
const NAME: &'static str;
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Aspects(Mutex<FxHashMap<TypeId, Arc<dyn Any + Send + Sync + 'static>>>);
|
||||
impl Aspects {
|
||||
fn add<A: Aspect>(&self, t: A) -> Arc<A> {
|
||||
let aspect = Arc::new(t);
|
||||
self.add_raw(aspect.clone());
|
||||
aspect
|
||||
}
|
||||
fn add_raw<A: Aspect>(&self, aspect: Arc<A>) {
|
||||
self.0.lock().insert(Self::type_key::<A>(), aspect);
|
||||
}
|
||||
fn get<A: Aspect + Any + Send + Sync + 'static>(&self) -> Result<Arc<A>> {
|
||||
self.0
|
||||
.lock()
|
||||
.get(&Self::type_key::<A>())
|
||||
.and_then(|a| Arc::downcast(a.clone()).ok())
|
||||
.ok_or(eyre!("Couldn't get aspect {}", A::NAME.to_lowercase()))
|
||||
}
|
||||
|
||||
fn type_key<A: 'static>() -> TypeId {
|
||||
TypeId::of::<A>()
|
||||
}
|
||||
}
|
||||
impl Drop for Aspects {
|
||||
fn drop(&mut self) {
|
||||
self.0.lock().clear()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,77 +1,105 @@
|
||||
use super::spatial::Spatial;
|
||||
use super::startup::DESKTOP_STARTUP_IDS;
|
||||
use super::Node;
|
||||
use super::{Message, Node};
|
||||
use crate::core::client::Client;
|
||||
use crate::core::client_state::{ClientState, ClientStateInternal};
|
||||
use crate::core::registry::Registry;
|
||||
use anyhow::{anyhow, Result};
|
||||
use crate::core::scenegraph::MethodResponseSender;
|
||||
#[cfg(feature = "wayland")]
|
||||
use crate::wayland::WAYLAND_DISPLAY;
|
||||
#[cfg(feature = "xwayland")]
|
||||
use crate::wayland::X_DISPLAY;
|
||||
use crate::STARDUST_INSTANCE;
|
||||
use color_eyre::eyre::Result;
|
||||
use glam::Mat4;
|
||||
use rustc_hash::FxHashMap;
|
||||
use stardust_xr::schemas::flex::{deserialize, serialize};
|
||||
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Arc;
|
||||
use tracing::instrument;
|
||||
|
||||
static ROOT_REGISTRY: Registry<Root> = Registry::new();
|
||||
|
||||
pub struct Root {
|
||||
node: Arc<Node>,
|
||||
logic_step: AtomicBool,
|
||||
pub node: Arc<Node>,
|
||||
send_frame_event: AtomicBool,
|
||||
}
|
||||
impl Root {
|
||||
pub fn create(client: &Arc<Client>) -> Arc<Self> {
|
||||
let node = Node::create(client, "", "", false);
|
||||
node.add_local_signal("applyDesktopStartupID", Root::apply_desktop_startup_id);
|
||||
node.add_local_signal("subscribeLogicStep", Root::subscribe_logic_step);
|
||||
node.add_local_signal("setBasePrefixes", Root::set_base_prefixes);
|
||||
let node = node.add_to_scenegraph();
|
||||
let _ = Spatial::add_to(&node, None, Mat4::IDENTITY);
|
||||
pub fn create(client: &Arc<Client>) -> Result<Arc<Self>> {
|
||||
let node = Node::create_parent_name(client, "", "", false);
|
||||
node.add_local_signal("subscribe_frame", Root::subscribe_frame_flex);
|
||||
node.add_local_signal("set_base_prefixes", Root::set_base_prefixes_flex);
|
||||
node.add_local_method("state_token", Root::state_token_flex);
|
||||
node.add_local_method(
|
||||
"get_connection_environment",
|
||||
get_connection_environment_flex,
|
||||
);
|
||||
let node = node.add_to_scenegraph()?;
|
||||
let _ = Spatial::add_to(&node, None, client.state.root, false);
|
||||
|
||||
ROOT_REGISTRY.add(Root {
|
||||
Ok(ROOT_REGISTRY.add(Root {
|
||||
node,
|
||||
logic_step: AtomicBool::from(false),
|
||||
})
|
||||
send_frame_event: AtomicBool::from(false),
|
||||
}))
|
||||
}
|
||||
|
||||
fn apply_desktop_startup_id(
|
||||
node: &Node,
|
||||
_calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
fn subscribe_frame_flex(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
_message: Message,
|
||||
) -> Result<()> {
|
||||
let startup_settings = DESKTOP_STARTUP_IDS
|
||||
.lock()
|
||||
.remove(flexbuffers::Reader::get_root(data)?.get_str()?)
|
||||
.ok_or_else(|| anyhow!("Desktop startup ID not found in the list!"))?;
|
||||
node.spatial
|
||||
.get()
|
||||
.unwrap()
|
||||
.set_local_transform(startup_settings.transform);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn subscribe_logic_step(_node: &Node, calling_client: Arc<Client>, _data: &[u8]) -> Result<()> {
|
||||
calling_client
|
||||
.root
|
||||
.get()
|
||||
.unwrap()
|
||||
.logic_step
|
||||
.send_frame_event
|
||||
.store(true, Ordering::Relaxed);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn logic_step(delta: f64) {
|
||||
#[instrument(level = "debug")]
|
||||
pub fn send_frame_events(delta: f64) {
|
||||
if let Ok(data) = serialize((delta, 0.0)) {
|
||||
for root in ROOT_REGISTRY.get_valid_contents() {
|
||||
if root.logic_step.load(Ordering::Relaxed) {
|
||||
let _ = root.node.send_remote_signal("logicStep", &data);
|
||||
if root.send_frame_event.load(Ordering::Relaxed) {
|
||||
let _ = root.node.send_remote_signal("frame", data.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn set_base_prefixes(_node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
*calling_client.base_resource_prefixes.lock() = deserialize(data)?;
|
||||
fn set_base_prefixes_flex(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
message: Message,
|
||||
) -> Result<()> {
|
||||
*calling_client.base_resource_prefixes.lock() = deserialize(message.as_ref())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn state_token_flex(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
message: Message,
|
||||
response: MethodResponseSender,
|
||||
) {
|
||||
response.wrap_sync(|| {
|
||||
let state: ClientStateInternal = deserialize(message.as_ref())?;
|
||||
let token = ClientState::from_deserialized(&calling_client, state).token();
|
||||
Ok(serialize(token)?.into())
|
||||
})
|
||||
}
|
||||
|
||||
pub fn set_transform(&self, transform: Mat4) {
|
||||
let spatial = self.node.get_aspect::<Spatial>().unwrap();
|
||||
spatial.set_spatial_parent(None).unwrap();
|
||||
spatial.set_local_transform(transform);
|
||||
}
|
||||
pub async fn save_state(&self) -> Result<ClientStateInternal> {
|
||||
self.node
|
||||
.execute_remote_method_typed("save_state", (), Vec::new())
|
||||
.await
|
||||
.map(|(m, _)| m)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Root {
|
||||
@@ -79,3 +107,36 @@ impl Drop for Root {
|
||||
ROOT_REGISTRY.remove(self);
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! var_env_insert {
|
||||
($env:ident, $name:ident) => {
|
||||
$env.insert(stringify!($name).to_string(), $name.get().unwrap().clone());
|
||||
};
|
||||
}
|
||||
pub fn get_connection_environment_flex(
|
||||
_node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
_message: Message,
|
||||
response: MethodResponseSender,
|
||||
) {
|
||||
response.wrap_sync(move || {
|
||||
let mut env: FxHashMap<String, String> = FxHashMap::default();
|
||||
var_env_insert!(env, STARDUST_INSTANCE);
|
||||
#[cfg(feature = "wayland")]
|
||||
{
|
||||
var_env_insert!(env, WAYLAND_DISPLAY);
|
||||
#[cfg(feature = "xwayland")]
|
||||
env.insert(
|
||||
"DISPLAY".to_string(),
|
||||
format!(":{}", X_DISPLAY.get().unwrap()),
|
||||
);
|
||||
env.insert("GDK_BACKEND".to_string(), "wayland".to_string());
|
||||
env.insert("QT_QPA_PLATFORM".to_string(), "wayland".to_string());
|
||||
env.insert("MOZ_ENABLE_WAYLAND".to_string(), "1".to_string());
|
||||
env.insert("CLUTTER_BACKEND".to_string(), "wayland".to_string());
|
||||
env.insert("SDL_VIDEODRIVER".to_string(), "wayland".to_string());
|
||||
}
|
||||
|
||||
Ok(serialize(env)?.into())
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,291 +0,0 @@
|
||||
use super::Node;
|
||||
use crate::core::client::Client;
|
||||
use anyhow::{anyhow, ensure, Result};
|
||||
use glam::{Mat4, Quat};
|
||||
use mint::Vector3;
|
||||
use parking_lot::Mutex;
|
||||
|
||||
use serde::Deserialize;
|
||||
use stardust_xr::schemas::flex::{deserialize, serialize};
|
||||
use stardust_xr::values::Transform;
|
||||
use std::ptr;
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
pub struct Spatial {
|
||||
pub(super) node: Weak<Node>,
|
||||
parent: Mutex<Option<Arc<Spatial>>>,
|
||||
pub(super) transform: Mutex<Mat4>,
|
||||
}
|
||||
|
||||
impl Spatial {
|
||||
pub fn new(node: Weak<Node>, parent: Option<Arc<Spatial>>, transform: Mat4) -> Arc<Self> {
|
||||
Arc::new(Spatial {
|
||||
node,
|
||||
parent: Mutex::new(parent),
|
||||
transform: Mutex::new(transform),
|
||||
})
|
||||
}
|
||||
pub fn add_to(
|
||||
node: &Arc<Node>,
|
||||
parent: Option<Arc<Spatial>>,
|
||||
transform: Mat4,
|
||||
) -> Result<Arc<Spatial>> {
|
||||
ensure!(
|
||||
node.spatial.get().is_none(),
|
||||
"Internal: Node already has a Spatial aspect!"
|
||||
);
|
||||
let spatial = Spatial {
|
||||
node: Arc::downgrade(node),
|
||||
parent: Mutex::new(parent),
|
||||
transform: Mutex::new(transform),
|
||||
};
|
||||
node.add_local_method("getTransform", Spatial::get_transform_flex);
|
||||
node.add_local_signal("setTransform", Spatial::set_transform_flex);
|
||||
node.add_local_signal("setSpatialParent", Spatial::set_spatial_parent_flex);
|
||||
node.add_local_signal(
|
||||
"setSpatialParentInPlace",
|
||||
Spatial::set_spatial_parent_in_place_flex,
|
||||
);
|
||||
let spatial_arc = Arc::new(spatial);
|
||||
let _ = node.spatial.set(spatial_arc.clone());
|
||||
Ok(spatial_arc)
|
||||
}
|
||||
|
||||
pub fn space_to_space_matrix(from: Option<&Spatial>, to: Option<&Spatial>) -> Mat4 {
|
||||
let space_to_world_matrix = from.map_or(Mat4::IDENTITY, |from| from.global_transform());
|
||||
let world_to_space_matrix = to.map_or(Mat4::IDENTITY, |to| to.global_transform().inverse());
|
||||
world_to_space_matrix * space_to_world_matrix
|
||||
}
|
||||
|
||||
pub fn local_transform(&self) -> Mat4 {
|
||||
*self.transform.lock()
|
||||
}
|
||||
pub fn global_transform(&self) -> Mat4 {
|
||||
match self.parent.lock().clone() {
|
||||
Some(value) => value.global_transform() * *self.transform.lock(),
|
||||
None => *self.transform.lock(),
|
||||
}
|
||||
}
|
||||
pub fn set_local_transform(&self, transform: Mat4) {
|
||||
*self.transform.lock() = transform;
|
||||
}
|
||||
pub fn set_local_transform_components(
|
||||
&self,
|
||||
reference_space: Option<&Spatial>,
|
||||
transform: Transform,
|
||||
) {
|
||||
let reference_to_parent_transform = reference_space
|
||||
.map(|reference_space| {
|
||||
Spatial::space_to_space_matrix(Some(reference_space), self.parent.lock().as_deref())
|
||||
})
|
||||
.unwrap_or(Mat4::IDENTITY);
|
||||
let mut local_transform_in_reference_space =
|
||||
reference_to_parent_transform.inverse() * self.local_transform();
|
||||
let (mut reference_space_scl, mut reference_space_rot, mut reference_space_pos) =
|
||||
local_transform_in_reference_space.to_scale_rotation_translation();
|
||||
|
||||
if let Some(pos) = transform.position {
|
||||
reference_space_pos = pos.into()
|
||||
}
|
||||
if let Some(rot) = transform.rotation {
|
||||
reference_space_rot = rot.into()
|
||||
} else if reference_space_rot.is_nan() {
|
||||
reference_space_rot = Quat::IDENTITY;
|
||||
}
|
||||
if let Some(scl) = transform.scale {
|
||||
reference_space_scl = scl.into()
|
||||
}
|
||||
|
||||
local_transform_in_reference_space = Mat4::from_scale_rotation_translation(
|
||||
reference_space_scl,
|
||||
reference_space_rot,
|
||||
reference_space_pos,
|
||||
);
|
||||
self.set_local_transform(
|
||||
reference_to_parent_transform * local_transform_in_reference_space,
|
||||
);
|
||||
}
|
||||
|
||||
pub fn is_ancestor_of(&self, spatial: Arc<Spatial>) -> bool {
|
||||
let mut current_ancestor = spatial;
|
||||
loop {
|
||||
if Arc::as_ptr(¤t_ancestor) == ptr::addr_of!(*self) {
|
||||
return true;
|
||||
}
|
||||
|
||||
let current_ancestor_parent = current_ancestor.parent.lock().clone();
|
||||
if let Some(parent) = current_ancestor_parent {
|
||||
current_ancestor = parent;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_spatial_parent(&self, parent: Option<&Arc<Spatial>>) -> Result<()> {
|
||||
let is_ancestor = parent
|
||||
.map(|parent| self.is_ancestor_of(parent.clone()))
|
||||
.unwrap_or(false);
|
||||
if is_ancestor {
|
||||
return Err(anyhow!("Setting spatial parent would cause a loop"));
|
||||
}
|
||||
|
||||
*self.parent.lock() = parent.cloned();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_spatial_parent_in_place(&self, parent: Option<&Arc<Spatial>>) -> Result<()> {
|
||||
let is_ancestor = parent
|
||||
.map(|parent| self.is_ancestor_of(parent.clone()))
|
||||
.unwrap_or(false);
|
||||
if is_ancestor {
|
||||
return Err(anyhow!("Setting spatial parent would cause a loop"));
|
||||
}
|
||||
|
||||
self.set_local_transform(Spatial::space_to_space_matrix(
|
||||
Some(self),
|
||||
parent.cloned().as_deref(),
|
||||
));
|
||||
*self.parent.lock() = parent.cloned();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get_transform_flex(
|
||||
node: &Node,
|
||||
calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
) -> Result<Vec<u8>> {
|
||||
let this_spatial = node
|
||||
.spatial
|
||||
.get()
|
||||
.ok_or_else(|| anyhow!("Node doesn't have a spatial?"))?;
|
||||
let relative_spatial = find_reference_space(&calling_client, deserialize(data)?)?;
|
||||
|
||||
let (scale, rotation, position) = Spatial::space_to_space_matrix(
|
||||
Some(this_spatial.as_ref()),
|
||||
Some(relative_spatial.as_ref()),
|
||||
)
|
||||
.to_scale_rotation_translation();
|
||||
|
||||
serialize((
|
||||
mint::Vector3::from(position),
|
||||
mint::Quaternion::from(rotation),
|
||||
mint::Vector3::from(scale),
|
||||
))
|
||||
.map_err(|e| e.into())
|
||||
}
|
||||
pub fn set_transform_flex(node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct TransformArgs<'a> {
|
||||
reference_space_path: Option<&'a str>,
|
||||
transform: Transform,
|
||||
}
|
||||
let transform_args: TransformArgs = deserialize(data)?;
|
||||
let reference_space_transform = transform_args
|
||||
.reference_space_path
|
||||
.map(|path| find_reference_space(&calling_client, path))
|
||||
.transpose()?;
|
||||
|
||||
node.spatial.get().unwrap().set_local_transform_components(
|
||||
reference_space_transform.as_deref(),
|
||||
transform_args.transform,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
pub fn set_spatial_parent_flex(
|
||||
node: &Node,
|
||||
calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
) -> Result<()> {
|
||||
let parent = find_spatial_parent(&calling_client, deserialize(data)?)?;
|
||||
node.spatial
|
||||
.get()
|
||||
.unwrap()
|
||||
.set_spatial_parent(Some(&parent))
|
||||
}
|
||||
pub fn set_spatial_parent_in_place_flex(
|
||||
node: &Node,
|
||||
calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
) -> Result<()> {
|
||||
let parent = find_spatial_parent(&calling_client, deserialize(data)?)?;
|
||||
node.spatial
|
||||
.get()
|
||||
.unwrap()
|
||||
.set_spatial_parent_in_place(Some(&parent))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_transform(
|
||||
transform: Transform,
|
||||
translation: bool,
|
||||
rotation: bool,
|
||||
scale: bool,
|
||||
) -> Result<Mat4> {
|
||||
let translation = translation
|
||||
.then_some(transform.position)
|
||||
.flatten()
|
||||
.unwrap_or_else(|| Vector3::from([0.0; 3]));
|
||||
let rotation = rotation
|
||||
.then_some(transform.rotation)
|
||||
.flatten()
|
||||
.unwrap_or_else(|| Quat::IDENTITY.into());
|
||||
let scale = scale
|
||||
.then_some(transform.scale)
|
||||
.flatten()
|
||||
.unwrap_or_else(|| Vector3::from([1.0; 3]));
|
||||
|
||||
Ok(Mat4::from_scale_rotation_translation(
|
||||
scale.into(),
|
||||
rotation.into(),
|
||||
translation.into(),
|
||||
))
|
||||
}
|
||||
|
||||
pub fn find_spatial(
|
||||
calling_client: &Arc<Client>,
|
||||
node_name: &'static str,
|
||||
node_path: &str,
|
||||
) -> anyhow::Result<Arc<Spatial>> {
|
||||
Ok(calling_client
|
||||
.get_node(node_name, node_path)?
|
||||
.get_aspect(node_name, "spatial", |n| &n.spatial)?
|
||||
.clone())
|
||||
}
|
||||
pub fn find_spatial_parent(
|
||||
calling_client: &Arc<Client>,
|
||||
node_path: &str,
|
||||
) -> anyhow::Result<Arc<Spatial>> {
|
||||
find_spatial(calling_client, "Spatial parent", node_path)
|
||||
}
|
||||
pub fn find_reference_space(
|
||||
calling_client: &Arc<Client>,
|
||||
node_path: &str,
|
||||
) -> anyhow::Result<Arc<Spatial>> {
|
||||
find_spatial(calling_client, "Reference space", node_path)
|
||||
}
|
||||
|
||||
pub fn create_interface(client: &Arc<Client>) {
|
||||
let node = Node::create(client, "", "spatial", false);
|
||||
node.add_local_signal("createSpatial", create_spatial_flex);
|
||||
node.add_to_scenegraph();
|
||||
}
|
||||
|
||||
pub fn create_spatial_flex(_node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct CreateSpatialInfo<'a> {
|
||||
name: &'a str,
|
||||
parent_path: &'a str,
|
||||
transform: Transform,
|
||||
}
|
||||
let info: CreateSpatialInfo = deserialize(data)?;
|
||||
let node = Node::create(&calling_client, "/spatial/spatial", info.name, true);
|
||||
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||
let transform = parse_transform(info.transform, true, true, true)?;
|
||||
let node = node.add_to_scenegraph();
|
||||
Spatial::add_to(&node, Some(parent), transform)?;
|
||||
Ok(())
|
||||
}
|
||||
441
src/nodes/spatial/mod.rs
Normal file
441
src/nodes/spatial/mod.rs
Normal file
@@ -0,0 +1,441 @@
|
||||
pub mod zone;
|
||||
|
||||
use self::zone::Zone;
|
||||
use super::fields::Field;
|
||||
use super::{Aspect, Node};
|
||||
use crate::core::client::Client;
|
||||
use crate::core::registry::Registry;
|
||||
use crate::create_interface;
|
||||
use color_eyre::eyre::{eyre, Result};
|
||||
use glam::{vec3a, Mat4, Quat};
|
||||
use mint::Vector3;
|
||||
use nanoid::nanoid;
|
||||
use once_cell::sync::OnceCell;
|
||||
use parking_lot::Mutex;
|
||||
use std::fmt::Debug;
|
||||
use std::ptr;
|
||||
use std::sync::{Arc, Weak};
|
||||
use stereokit::{bounds_grow_to_fit_box, Bounds};
|
||||
|
||||
stardust_xr_server_codegen::codegen_spatial_protocol!();
|
||||
impl Transform {
|
||||
pub fn to_mat4(self, position: bool, rotation: bool, scale: bool) -> Mat4 {
|
||||
let position = position
|
||||
.then_some(self.translation)
|
||||
.flatten()
|
||||
.unwrap_or_else(|| Vector3::from([0.0; 3]));
|
||||
let rotation = rotation
|
||||
.then_some(self.rotation)
|
||||
.flatten()
|
||||
.unwrap_or_else(|| Quat::IDENTITY.into());
|
||||
let scale = scale
|
||||
.then_some(self.scale)
|
||||
.flatten()
|
||||
.unwrap_or_else(|| Vector3::from([1.0; 3]));
|
||||
|
||||
Mat4::from_scale_rotation_translation(scale.into(), rotation.into(), position.into())
|
||||
}
|
||||
}
|
||||
|
||||
static ZONEABLE_REGISTRY: Registry<Spatial> = Registry::new();
|
||||
|
||||
pub struct Spatial {
|
||||
uid: String,
|
||||
pub(super) node: Weak<Node>,
|
||||
parent: Mutex<Option<Arc<Spatial>>>,
|
||||
old_parent: Mutex<Option<Arc<Spatial>>>,
|
||||
pub(super) transform: Mutex<Mat4>,
|
||||
zone: Mutex<Weak<Zone>>,
|
||||
children: Registry<Spatial>,
|
||||
pub(super) bounding_box_calc: OnceCell<fn(&Node) -> Bounds>,
|
||||
}
|
||||
|
||||
impl Spatial {
|
||||
pub fn new(node: Weak<Node>, parent: Option<Arc<Spatial>>, transform: Mat4) -> Arc<Self> {
|
||||
Arc::new(Spatial {
|
||||
uid: nanoid!(),
|
||||
node,
|
||||
parent: Mutex::new(parent),
|
||||
old_parent: Mutex::new(None),
|
||||
transform: Mutex::new(transform),
|
||||
zone: Mutex::new(Weak::new()),
|
||||
children: Registry::new(),
|
||||
bounding_box_calc: OnceCell::default(),
|
||||
})
|
||||
}
|
||||
pub fn add_to(
|
||||
node: &Arc<Node>,
|
||||
parent: Option<Arc<Spatial>>,
|
||||
transform: Mat4,
|
||||
zoneable: bool,
|
||||
) -> Arc<Spatial> {
|
||||
let spatial = Spatial::new(Arc::downgrade(node), parent.clone(), transform);
|
||||
<Spatial as SpatialAspect>::add_node_members(node);
|
||||
if zoneable {
|
||||
ZONEABLE_REGISTRY.add_raw(&spatial);
|
||||
}
|
||||
if let Some(parent) = parent {
|
||||
parent.children.add_raw(&spatial);
|
||||
}
|
||||
<Spatial as SpatialAspect>::add_node_members(node);
|
||||
node.add_aspect_raw(spatial.clone());
|
||||
spatial
|
||||
}
|
||||
|
||||
pub fn node(&self) -> Option<Arc<Node>> {
|
||||
self.node.upgrade()
|
||||
}
|
||||
|
||||
pub fn space_to_space_matrix(from: Option<&Spatial>, to: Option<&Spatial>) -> Mat4 {
|
||||
let space_to_world_matrix = from.map_or(Mat4::IDENTITY, |from| from.global_transform());
|
||||
let world_to_space_matrix = to.map_or(Mat4::IDENTITY, |to| to.global_transform().inverse());
|
||||
world_to_space_matrix * space_to_world_matrix
|
||||
}
|
||||
|
||||
// the output bounds are probably way bigger than they need to be
|
||||
pub fn get_bounding_box(&self) -> Bounds {
|
||||
let Some(node) = self.node() else {
|
||||
return Bounds::default();
|
||||
};
|
||||
let mut bounds = self
|
||||
.bounding_box_calc
|
||||
.get()
|
||||
.map(|b| (b)(&node))
|
||||
.unwrap_or_default();
|
||||
for child in self.children.get_valid_contents() {
|
||||
bounds = bounds_grow_to_fit_box(
|
||||
bounds,
|
||||
child.get_bounding_box(),
|
||||
Some(child.local_transform()),
|
||||
);
|
||||
}
|
||||
bounds
|
||||
}
|
||||
|
||||
pub fn local_transform(&self) -> Mat4 {
|
||||
*self.transform.lock()
|
||||
}
|
||||
pub fn global_transform(&self) -> Mat4 {
|
||||
let parent_transform = self
|
||||
.get_parent()
|
||||
.as_deref()
|
||||
.map(Self::global_transform)
|
||||
.unwrap_or_default();
|
||||
parent_transform * self.local_transform()
|
||||
}
|
||||
pub fn set_local_transform(&self, transform: Mat4) {
|
||||
*self.transform.lock() = transform;
|
||||
}
|
||||
pub fn set_local_transform_components(
|
||||
&self,
|
||||
reference_space: Option<&Spatial>,
|
||||
transform: Transform,
|
||||
) {
|
||||
if reference_space == Some(self) {
|
||||
self.set_local_transform(
|
||||
parse_transform(transform, true, true, true) * self.local_transform(),
|
||||
);
|
||||
return;
|
||||
}
|
||||
let reference_to_parent_transform = reference_space
|
||||
.map(|reference_space| {
|
||||
Spatial::space_to_space_matrix(Some(reference_space), self.get_parent().as_deref())
|
||||
})
|
||||
.unwrap_or(Mat4::IDENTITY);
|
||||
let mut local_transform_in_reference_space =
|
||||
reference_to_parent_transform.inverse() * self.local_transform();
|
||||
let (mut reference_space_scl, mut reference_space_rot, mut reference_space_pos) =
|
||||
local_transform_in_reference_space.to_scale_rotation_translation();
|
||||
|
||||
if let Some(pos) = transform.translation {
|
||||
reference_space_pos = pos.into()
|
||||
}
|
||||
if let Some(rot) = transform.rotation {
|
||||
reference_space_rot = rot.into()
|
||||
} else if reference_space_rot.is_nan() {
|
||||
reference_space_rot = Quat::IDENTITY;
|
||||
}
|
||||
if let Some(scl) = transform.scale {
|
||||
reference_space_scl = scl.into()
|
||||
}
|
||||
|
||||
local_transform_in_reference_space = Mat4::from_scale_rotation_translation(
|
||||
reference_space_scl,
|
||||
reference_space_rot,
|
||||
reference_space_pos,
|
||||
);
|
||||
self.set_local_transform(
|
||||
reference_to_parent_transform * local_transform_in_reference_space,
|
||||
);
|
||||
}
|
||||
|
||||
pub fn is_ancestor_of(&self, spatial: Arc<Spatial>) -> bool {
|
||||
let mut current_ancestor = spatial;
|
||||
loop {
|
||||
if Arc::as_ptr(¤t_ancestor) == ptr::addr_of!(*self) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if let Some(parent) = current_ancestor.get_parent() {
|
||||
current_ancestor = parent;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn get_parent(&self) -> Option<Arc<Spatial>> {
|
||||
self.parent.lock().clone()
|
||||
}
|
||||
fn set_parent(self: &Arc<Self>, new_parent: Option<&Arc<Spatial>>) {
|
||||
if let Some(parent) = self.get_parent() {
|
||||
parent.children.remove(&self);
|
||||
}
|
||||
if let Some(new_parent) = &new_parent {
|
||||
new_parent.children.add_raw(self);
|
||||
}
|
||||
|
||||
*self.parent.lock() = new_parent.cloned();
|
||||
}
|
||||
|
||||
pub fn set_spatial_parent(self: &Arc<Self>, parent: Option<&Arc<Spatial>>) -> Result<()> {
|
||||
let is_ancestor = parent
|
||||
.as_ref()
|
||||
.map(|parent| self.is_ancestor_of((*parent).clone()))
|
||||
.unwrap_or(false);
|
||||
if is_ancestor {
|
||||
return Err(eyre!("Setting spatial parent would cause a loop"));
|
||||
}
|
||||
self.set_parent(parent);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
pub fn set_spatial_parent_in_place(
|
||||
self: &Arc<Self>,
|
||||
parent: Option<&Arc<Spatial>>,
|
||||
) -> Result<()> {
|
||||
let is_ancestor = parent
|
||||
.as_ref()
|
||||
.map(|parent| self.is_ancestor_of((*parent).clone()))
|
||||
.unwrap_or(false);
|
||||
if is_ancestor {
|
||||
return Err(eyre!("Setting spatial parent would cause a loop"));
|
||||
}
|
||||
|
||||
self.set_local_transform(Spatial::space_to_space_matrix(
|
||||
Some(&self),
|
||||
parent.map(AsRef::as_ref),
|
||||
));
|
||||
self.set_parent(parent);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(self) fn zone_distance(&self) -> f32 {
|
||||
self.zone
|
||||
.lock()
|
||||
.upgrade()
|
||||
.and_then(|zone| zone.field.upgrade())
|
||||
.map(|field| field.distance(self, vec3a(0.0, 0.0, 0.0)))
|
||||
.unwrap_or(f32::MAX)
|
||||
}
|
||||
}
|
||||
impl Aspect for Spatial {
|
||||
const NAME: &'static str = "Spatial";
|
||||
}
|
||||
impl SpatialAspect for Spatial {
|
||||
async fn get_local_bounding_box(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
) -> Result<BoundingBox> {
|
||||
let this_spatial = node.get_aspect::<Spatial>()?;
|
||||
let bounds = this_spatial.get_bounding_box();
|
||||
|
||||
Ok(BoundingBox {
|
||||
center: mint::Vector3::from(bounds.center),
|
||||
size: mint::Vector3::from(bounds.dimensions),
|
||||
})
|
||||
}
|
||||
|
||||
async fn get_relative_bounding_box(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
relative_to: Arc<Node>,
|
||||
) -> Result<BoundingBox> {
|
||||
let this_spatial = node.get_aspect::<Spatial>()?;
|
||||
let relative_spatial = relative_to.get_aspect::<Spatial>()?;
|
||||
let center = Spatial::space_to_space_matrix(Some(&this_spatial), Some(&relative_spatial))
|
||||
.transform_point3([0.0; 3].into());
|
||||
let bounds = bounds_grow_to_fit_box(
|
||||
Bounds {
|
||||
center,
|
||||
dimensions: [0.0; 3].into(),
|
||||
},
|
||||
this_spatial.get_bounding_box(),
|
||||
Some(Spatial::space_to_space_matrix(
|
||||
Some(&this_spatial),
|
||||
Some(&relative_spatial),
|
||||
)),
|
||||
);
|
||||
|
||||
Ok(BoundingBox {
|
||||
center: mint::Vector3::from(bounds.center),
|
||||
size: mint::Vector3::from(bounds.dimensions),
|
||||
})
|
||||
}
|
||||
|
||||
async fn get_transform(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
relative_to: Arc<Node>,
|
||||
) -> Result<Transform> {
|
||||
let this_spatial = node.get_aspect::<Spatial>()?;
|
||||
let relative_spatial = relative_to.get_aspect::<Spatial>()?;
|
||||
|
||||
let (scale, rotation, position) = Spatial::space_to_space_matrix(
|
||||
Some(this_spatial.as_ref()),
|
||||
Some(relative_spatial.as_ref()),
|
||||
)
|
||||
.to_scale_rotation_translation();
|
||||
|
||||
Ok(Transform {
|
||||
translation: Some(position.into()),
|
||||
rotation: Some(rotation.into()),
|
||||
scale: Some(scale.into()),
|
||||
})
|
||||
}
|
||||
|
||||
fn set_local_transform(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
transform: Transform,
|
||||
) -> Result<()> {
|
||||
let this_spatial = node.get_aspect::<Spatial>()?;
|
||||
this_spatial.set_local_transform_components(None, transform);
|
||||
Ok(())
|
||||
}
|
||||
fn set_relative_transform(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
relative_to: Arc<Node>,
|
||||
transform: Transform,
|
||||
) -> Result<()> {
|
||||
let this_spatial = node.get_aspect::<Spatial>()?;
|
||||
let relative_spatial = relative_to.get_aspect::<Spatial>()?;
|
||||
|
||||
this_spatial.set_local_transform_components(Some(&relative_spatial), transform);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_spatial_parent(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
parent: Arc<Node>,
|
||||
) -> Result<()> {
|
||||
let this_spatial = node.get_aspect::<Spatial>()?;
|
||||
let parent = parent.get_aspect::<Spatial>()?;
|
||||
|
||||
this_spatial.set_spatial_parent(Some(&parent))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_spatial_parent_in_place(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
parent: Arc<Node>,
|
||||
) -> Result<()> {
|
||||
let this_spatial = node.get_aspect::<Spatial>()?;
|
||||
let parent = parent.get_aspect::<Spatial>()?;
|
||||
|
||||
this_spatial.set_spatial_parent_in_place(Some(&parent))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_zoneable(node: Arc<Node>, _calling_client: Arc<Client>, zoneable: bool) -> Result<()> {
|
||||
let spatial = node.get_aspect::<Spatial>()?;
|
||||
if zoneable {
|
||||
ZONEABLE_REGISTRY.add_raw(&spatial);
|
||||
} else {
|
||||
ZONEABLE_REGISTRY.remove(&spatial);
|
||||
zone::release(&spatial);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl PartialEq for Spatial {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.uid == other.uid
|
||||
}
|
||||
}
|
||||
impl Debug for Spatial {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Spatial")
|
||||
.field("uid", &self.uid)
|
||||
.field("parent", &self.parent)
|
||||
.field("old_parent", &self.old_parent)
|
||||
.field("transform", &self.transform)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
impl Drop for Spatial {
|
||||
fn drop(&mut self) {
|
||||
zone::release_drop(self);
|
||||
ZONEABLE_REGISTRY.remove(self);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_transform(transform: Transform, position: bool, rotation: bool, scale: bool) -> Mat4 {
|
||||
let position = position
|
||||
.then_some(transform.translation)
|
||||
.flatten()
|
||||
.unwrap_or_else(|| Vector3::from([0.0; 3]));
|
||||
let rotation = rotation
|
||||
.then_some(transform.rotation)
|
||||
.flatten()
|
||||
.unwrap_or_else(|| Quat::IDENTITY.into());
|
||||
let scale = scale
|
||||
.then_some(transform.scale)
|
||||
.flatten()
|
||||
.unwrap_or_else(|| Vector3::from([1.0; 3]));
|
||||
|
||||
Mat4::from_scale_rotation_translation(scale.into(), rotation.into(), position.into())
|
||||
}
|
||||
|
||||
pub struct SpatialInterface;
|
||||
impl SpatialInterfaceAspect for SpatialInterface {
|
||||
fn create_spatial(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
name: String,
|
||||
parent: Arc<Node>,
|
||||
transform: Transform,
|
||||
zoneable: bool,
|
||||
) -> Result<()> {
|
||||
let parent = parent.get_aspect::<Spatial>()?;
|
||||
let transform = parse_transform(transform, true, true, true);
|
||||
let node = Node::create_parent_name(&calling_client, "/spatial/spatial", &name, true)
|
||||
.add_to_scenegraph()?;
|
||||
Spatial::add_to(&node, Some(parent.clone()), transform, zoneable);
|
||||
Ok(())
|
||||
}
|
||||
fn create_zone(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
name: String,
|
||||
parent: Arc<Node>,
|
||||
transform: Transform,
|
||||
field: Arc<Node>,
|
||||
) -> Result<()> {
|
||||
let parent = parent.get_aspect::<Spatial>()?;
|
||||
let transform = parse_transform(transform, true, true, false);
|
||||
let field = field.get_aspect::<Field>()?;
|
||||
|
||||
let node = Node::create_parent_name(&calling_client, "/spatial/zone", &name, true)
|
||||
.add_to_scenegraph()?;
|
||||
let space = Spatial::add_to(&node, Some(parent.clone()), transform, false);
|
||||
Zone::add_to(&node, space, &field);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
create_interface!(SpatialInterface, SpatialInterfaceAspect, "/spatial");
|
||||
175
src/nodes/spatial/zone.rs
Normal file
175
src/nodes/spatial/zone.rs
Normal file
@@ -0,0 +1,175 @@
|
||||
use super::{Spatial, ZoneAspect, ZONEABLE_REGISTRY};
|
||||
use crate::{
|
||||
core::{client::Client, registry::Registry},
|
||||
nodes::{
|
||||
alias::{Alias, AliasInfo},
|
||||
fields::Field,
|
||||
Aspect, Node,
|
||||
},
|
||||
};
|
||||
use glam::vec3a;
|
||||
use parking_lot::Mutex;
|
||||
use rustc_hash::FxHashMap;
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
pub fn capture(spatial: &Arc<Spatial>, zone: &Arc<Zone>) {
|
||||
let old_distance = spatial.zone_distance();
|
||||
let new_distance = zone
|
||||
.field
|
||||
.upgrade()
|
||||
.map(|field| field.distance(spatial, vec3a(0.0, 0.0, 0.0)))
|
||||
.unwrap_or(f32::MAX);
|
||||
if new_distance.abs() < old_distance.abs() {
|
||||
release(spatial);
|
||||
*spatial.old_parent.lock() = spatial.get_parent();
|
||||
*spatial.zone.lock() = Arc::downgrade(zone);
|
||||
zone.captured.add_raw(spatial);
|
||||
let Some(node) = zone.spatial.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let _ = super::zone_client::capture(&node, &spatial.uid);
|
||||
}
|
||||
}
|
||||
pub fn release(spatial: &Arc<Spatial>) {
|
||||
let _ = spatial.set_spatial_parent_in_place(spatial.old_parent.lock().take().as_ref());
|
||||
let mut spatial_zone = spatial.zone.lock();
|
||||
if let Some(spatial_zone) = spatial_zone.upgrade() {
|
||||
let Some(node) = spatial_zone.spatial.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
spatial_zone.captured.remove(spatial);
|
||||
let _ = super::zone_client::release(&node, &spatial.uid);
|
||||
}
|
||||
*spatial_zone = Weak::new();
|
||||
}
|
||||
pub(super) fn release_drop(spatial: &Spatial) {
|
||||
let spatial_zone = spatial.zone.lock();
|
||||
if let Some(spatial_zone) = spatial_zone.upgrade() {
|
||||
let Some(node) = spatial_zone.spatial.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
spatial_zone.captured.remove(spatial);
|
||||
let _ = super::zone_client::release(&node, &spatial.uid);
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Zone {
|
||||
spatial: Arc<Spatial>,
|
||||
pub field: Weak<Field>,
|
||||
zoneables: Mutex<FxHashMap<String, Arc<Node>>>,
|
||||
captured: Registry<Spatial>,
|
||||
}
|
||||
impl Zone {
|
||||
pub fn add_to(node: &Arc<Node>, spatial: Arc<Spatial>, field: &Arc<Field>) -> Arc<Zone> {
|
||||
let zone = Arc::new(Zone {
|
||||
spatial,
|
||||
field: Arc::downgrade(field),
|
||||
zoneables: Mutex::new(FxHashMap::default()),
|
||||
captured: Registry::new(),
|
||||
});
|
||||
<Zone as ZoneAspect>::add_node_members(node);
|
||||
node.add_aspect_raw(zone.clone());
|
||||
zone
|
||||
}
|
||||
}
|
||||
impl Aspect for Zone {
|
||||
const NAME: &'static str = "Zone";
|
||||
}
|
||||
impl ZoneAspect for Zone {
|
||||
fn update(node: Arc<Node>, _calling_client: Arc<Client>) -> color_eyre::eyre::Result<()> {
|
||||
let zone = node.get_aspect::<Zone>()?;
|
||||
let Some(field) = zone.field.upgrade() else {
|
||||
return Err(color_eyre::eyre::eyre!("Zone's field has been destroyed"));
|
||||
};
|
||||
let Some((zone_client, zone_node)) = zone
|
||||
.spatial
|
||||
.node
|
||||
.upgrade()
|
||||
.and_then(|n| n.get_client().zip(Some(n)))
|
||||
else {
|
||||
return Err(color_eyre::eyre::eyre!("No client on node?"));
|
||||
};
|
||||
let mut old_zoneables = zone.zoneables.lock();
|
||||
for (_uid, zoneable) in old_zoneables.iter() {
|
||||
zoneable.destroy();
|
||||
}
|
||||
let captured = zone.captured.get_valid_contents();
|
||||
let zoneables = ZONEABLE_REGISTRY
|
||||
.get_valid_contents()
|
||||
.into_iter()
|
||||
.filter(|zoneable| zoneable.node.upgrade().is_some())
|
||||
.filter(|zoneable| {
|
||||
if captured
|
||||
.iter()
|
||||
.any(|captured| Arc::ptr_eq(captured, zoneable))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
let spatial_zone_distance = zoneable.zone_distance();
|
||||
let self_zone_distance = field.distance(zoneable, vec3a(0.0, 0.0, 0.0));
|
||||
self_zone_distance < 0.0 && spatial_zone_distance > self_zone_distance
|
||||
})
|
||||
.filter_map(|zoneable| {
|
||||
let alias = Alias::create(
|
||||
&zone_client,
|
||||
zone_node.get_path(),
|
||||
&zoneable.uid,
|
||||
&zoneable.node.upgrade().unwrap(),
|
||||
AliasInfo {
|
||||
server_signals: vec![
|
||||
"set_transform",
|
||||
"set_spatial_parent",
|
||||
"set_spatial_parent_in_place",
|
||||
],
|
||||
server_methods: vec!["get_bounds", "get_transform"],
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.ok()?;
|
||||
Some((zoneable.uid.clone(), alias))
|
||||
})
|
||||
.collect::<FxHashMap<String, Arc<Node>>>();
|
||||
|
||||
for (uid, zoneable) in zoneables
|
||||
.iter()
|
||||
.filter(|(k, _)| !old_zoneables.contains_key(*k))
|
||||
{
|
||||
super::zone_client::enter(&node, uid, zoneable)?;
|
||||
}
|
||||
for left_uid in old_zoneables.keys().filter(|k| !zoneables.contains_key(*k)) {
|
||||
super::zone_client::leave(&node, &left_uid)?;
|
||||
}
|
||||
|
||||
*old_zoneables = zoneables;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn capture(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
spatial: Arc<Node>,
|
||||
) -> color_eyre::eyre::Result<()> {
|
||||
let zone = node.get_aspect::<Zone>()?;
|
||||
let spatial = spatial.get_aspect()?;
|
||||
capture(&spatial, &zone);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn release(
|
||||
_node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
spatial: Arc<Node>,
|
||||
) -> color_eyre::eyre::Result<()> {
|
||||
let spatial = spatial.get_aspect()?;
|
||||
release(&spatial);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Drop for Zone {
|
||||
fn drop(&mut self) {
|
||||
for captured in self.captured.get_valid_contents() {
|
||||
release(&captured);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
use crate::core::client::Client;
|
||||
|
||||
use super::Node;
|
||||
use anyhow::{anyhow, Result};
|
||||
use glam::Mat4;
|
||||
use parking_lot::Mutex;
|
||||
use rustc_hash::FxHashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
pub static ref DESKTOP_STARTUP_IDS: Mutex<FxHashMap<String, StartupSettings>> = Default::default();
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct StartupSettings {
|
||||
pub transform: Mat4,
|
||||
}
|
||||
impl StartupSettings {
|
||||
pub fn add_to(node: &Arc<Node>) {
|
||||
node.startup_settings
|
||||
.set(Mutex::new(StartupSettings::default()))
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn set_root_flex(node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
let startup_id = flexbuffers::Reader::get_root(data)?.get_str()?;
|
||||
let spatial_node = calling_client
|
||||
.scenegraph
|
||||
.get_node(startup_id)
|
||||
.ok_or_else(|| anyhow!("Root spatial node does not exist"))?;
|
||||
let spatial = spatial_node
|
||||
.spatial
|
||||
.get()
|
||||
.ok_or_else(|| anyhow!("Root spatial node is not a spatial"))?;
|
||||
node.startup_settings.get().unwrap().lock().transform = spatial.global_transform();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn generate_desktop_startup_id_flex(
|
||||
node: &Node,
|
||||
_calling_client: Arc<Client>,
|
||||
_data: &[u8],
|
||||
) -> Result<Vec<u8>> {
|
||||
let id = nanoid::nanoid!();
|
||||
let data = flexbuffers::singleton(id.as_str());
|
||||
DESKTOP_STARTUP_IDS
|
||||
.lock()
|
||||
.insert(id, node.startup_settings.get().unwrap().lock().clone());
|
||||
Ok(data)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_interface(client: &Arc<Client>) {
|
||||
let node = Node::create(client, "", "startup", false);
|
||||
node.add_local_signal("createStartupSettings", create_startup_settings_flex);
|
||||
node.add_to_scenegraph();
|
||||
}
|
||||
|
||||
pub fn create_startup_settings_flex(
|
||||
_node: &Node,
|
||||
calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
) -> Result<()> {
|
||||
let name = flexbuffers::Reader::get_root(data)?.get_str()?;
|
||||
let node = Node::create(&calling_client, "/startup/settings", name, true).add_to_scenegraph();
|
||||
StartupSettings::add_to(&node);
|
||||
|
||||
node.add_local_signal("setRoot", StartupSettings::set_root_flex);
|
||||
node.add_local_method(
|
||||
"generateDesktopStartupID",
|
||||
StartupSettings::generate_desktop_startup_id_flex,
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
BIN
src/objects/input/cursor.blend
Normal file
BIN
src/objects/input/cursor.blend
Normal file
Binary file not shown.
BIN
src/objects/input/cursor.glb
Normal file
BIN
src/objects/input/cursor.glb
Normal file
Binary file not shown.
55
src/objects/input/eye_pointer.rs
Normal file
55
src/objects/input/eye_pointer.rs
Normal file
@@ -0,0 +1,55 @@
|
||||
use crate::{
|
||||
core::client::INTERNAL_CLIENT,
|
||||
nodes::{
|
||||
input::{pointer::Pointer, InputMethod, InputType},
|
||||
spatial::Spatial,
|
||||
Node,
|
||||
},
|
||||
};
|
||||
use color_eyre::eyre::Result;
|
||||
use glam::Mat4;
|
||||
use nanoid::nanoid;
|
||||
use serde::Serialize;
|
||||
use stardust_xr::{schemas::flex::flexbuffers, values::Datamap};
|
||||
use std::sync::Arc;
|
||||
use stereokit::StereoKitMultiThread;
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct KeyboardEvent {
|
||||
pub keyboard: String,
|
||||
pub keymap: Option<String>,
|
||||
pub keys_up: Option<Vec<u32>>,
|
||||
pub keys_down: Option<Vec<u32>>,
|
||||
}
|
||||
|
||||
pub struct EyePointer {
|
||||
spatial: Arc<Spatial>,
|
||||
pointer: Arc<InputMethod>,
|
||||
}
|
||||
impl EyePointer {
|
||||
pub fn new() -> Result<Self> {
|
||||
let node = Node::create_parent_name(&INTERNAL_CLIENT, "", &nanoid!(), false)
|
||||
.add_to_scenegraph()?;
|
||||
let spatial = Spatial::add_to(&node, None, Mat4::IDENTITY, false);
|
||||
let pointer =
|
||||
InputMethod::add_to(&node, InputType::Pointer(Pointer::default()), None).unwrap();
|
||||
|
||||
Ok(EyePointer { spatial, pointer })
|
||||
}
|
||||
pub fn update(&self, sk: &impl StereoKitMultiThread) {
|
||||
let ray = sk.input_eyes();
|
||||
self.spatial
|
||||
.set_local_transform(Mat4::from_rotation_translation(
|
||||
ray.orientation,
|
||||
ray.position,
|
||||
));
|
||||
{
|
||||
// Set pointer input datamap
|
||||
let mut fbb = flexbuffers::Builder::default();
|
||||
let mut map = fbb.start_map();
|
||||
map.push("eye", 2);
|
||||
map.end_map();
|
||||
*self.pointer.datamap.lock() = Datamap::from_raw(fbb.take_buffer()).ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
pub mod eye_pointer;
|
||||
pub mod mouse_pointer;
|
||||
pub mod sk_controller;
|
||||
pub mod sk_hand;
|
||||
|
||||
@@ -1,59 +1,290 @@
|
||||
use crate::nodes::{
|
||||
input::{pointer::Pointer, InputMethod, InputType},
|
||||
spatial::Spatial,
|
||||
};
|
||||
use glam::{vec3, Mat4};
|
||||
use stardust_xr::{schemas::flat::Datamap, values::Transform};
|
||||
use std::sync::{Arc, Weak};
|
||||
use stereokit::{
|
||||
input::{ButtonState, Key, Ray},
|
||||
StereoKit,
|
||||
use crate::{
|
||||
core::client::INTERNAL_CLIENT,
|
||||
nodes::{
|
||||
data::{
|
||||
mask_matches, pulse_receiver_client, PulseSender, KEYMAPS, PULSE_RECEIVER_REGISTRY,
|
||||
},
|
||||
fields::{Field, Ray},
|
||||
input::{pointer::Pointer, InputMethod, InputType},
|
||||
spatial::Spatial,
|
||||
Node,
|
||||
},
|
||||
};
|
||||
use color_eyre::eyre::Result;
|
||||
use glam::{vec2, vec3, Mat4, Vec2, Vec3};
|
||||
use nanoid::nanoid;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use stardust_xr::values::Datamap;
|
||||
use std::{convert::TryFrom, sync::Arc};
|
||||
use stereokit::{ray_from_mouse, ButtonState, Key, StereoKitMultiThread};
|
||||
use xkbcommon::xkb::{Context, Keymap, FORMAT_TEXT_V1};
|
||||
|
||||
#[derive(Default, Deserialize, Serialize)]
|
||||
struct MouseEvent {
|
||||
select: f32,
|
||||
middle: f32,
|
||||
context: f32,
|
||||
grab: f32,
|
||||
scroll_continuous: Vec2,
|
||||
scroll_discrete: Vec2,
|
||||
raw_input_events: Vec<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct KeyboardEvent {
|
||||
pub keyboard: (),
|
||||
pub xkbv1: (),
|
||||
pub keymap_id: String,
|
||||
pub keys: Vec<i32>,
|
||||
}
|
||||
impl Default for KeyboardEvent {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
keyboard: (),
|
||||
xkbv1: (),
|
||||
keymap_id: "flatscreen".to_string(),
|
||||
keys: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MousePointer {
|
||||
node: Arc<Node>,
|
||||
spatial: Arc<Spatial>,
|
||||
pointer: Arc<InputMethod>,
|
||||
mouse_datamap: MouseEvent,
|
||||
keyboard_datamap: KeyboardEvent,
|
||||
keyboard_sender: Arc<PulseSender>,
|
||||
}
|
||||
impl MousePointer {
|
||||
pub fn new() -> Self {
|
||||
MousePointer {
|
||||
pointer: InputMethod::new(
|
||||
Spatial::new(Weak::new(), None, Mat4::IDENTITY),
|
||||
InputType::Pointer(Pointer::default()),
|
||||
),
|
||||
}
|
||||
pub fn new() -> Result<Self> {
|
||||
let node = Node::create_parent_name(&INTERNAL_CLIENT, "", &nanoid!(), false)
|
||||
.add_to_scenegraph()?;
|
||||
let spatial = Spatial::add_to(&node, None, Mat4::IDENTITY, false);
|
||||
let pointer =
|
||||
InputMethod::add_to(&node, InputType::Pointer(Pointer::default()), None).unwrap();
|
||||
|
||||
KEYMAPS.lock().insert(
|
||||
"flatscreen".to_string(),
|
||||
Keymap::new_from_names(&Context::new(0), "evdev", "", "", "", None, 0)
|
||||
.unwrap()
|
||||
.get_as_string(FORMAT_TEXT_V1),
|
||||
);
|
||||
|
||||
let keyboard_sender = PulseSender::add_to(
|
||||
&node,
|
||||
Datamap::from_typed(KeyboardEvent::default()).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
Ok(MousePointer {
|
||||
node,
|
||||
spatial,
|
||||
pointer,
|
||||
mouse_datamap: Default::default(),
|
||||
keyboard_datamap: Default::default(),
|
||||
keyboard_sender,
|
||||
})
|
||||
}
|
||||
pub fn update(&self, sk: &StereoKit) {
|
||||
if let Some(ray) = Ray::from_mouse(sk.input_mouse()) {
|
||||
self.pointer.spatial.set_local_transform_components(
|
||||
None,
|
||||
Transform {
|
||||
position: Some(ray.pos),
|
||||
rotation: Some(
|
||||
glam::Quat::from_rotation_arc(vec3(0.0, 0.0, 1.0), ray.dir.into()).into(),
|
||||
),
|
||||
scale: None,
|
||||
},
|
||||
);
|
||||
pub fn update(&mut self, sk: &impl StereoKitMultiThread) {
|
||||
let mouse = sk.input_mouse();
|
||||
|
||||
let ray = ray_from_mouse(mouse.pos).unwrap();
|
||||
self.spatial.set_local_transform(
|
||||
Mat4::look_to_rh(
|
||||
Vec3::from(ray.pos),
|
||||
Vec3::from(ray.dir),
|
||||
vec3(0.0, 1.0, 0.0),
|
||||
)
|
||||
.inverse(),
|
||||
);
|
||||
{
|
||||
// Set pointer input datamap
|
||||
self.mouse_datamap.select =
|
||||
if sk.input_key(Key::MouseLeft).contains(ButtonState::ACTIVE) {
|
||||
1.0f32
|
||||
} else {
|
||||
0.0f32
|
||||
};
|
||||
self.mouse_datamap.middle =
|
||||
if sk.input_key(Key::MouseCenter).contains(ButtonState::ACTIVE) {
|
||||
1.0f32
|
||||
} else {
|
||||
0.0f32
|
||||
};
|
||||
self.mouse_datamap.context =
|
||||
if sk.input_key(Key::MouseRight).contains(ButtonState::ACTIVE) {
|
||||
1.0f32
|
||||
} else {
|
||||
0.0f32
|
||||
};
|
||||
self.mouse_datamap.grab = if sk.input_key(Key::MouseBack).contains(ButtonState::ACTIVE)
|
||||
|| sk
|
||||
.input_key(Key::MouseForward)
|
||||
.contains(ButtonState::ACTIVE)
|
||||
{
|
||||
1.0f32
|
||||
} else {
|
||||
0.0f32
|
||||
};
|
||||
self.mouse_datamap.scroll_continuous = vec2(0.0, mouse.scroll_change / 120.0);
|
||||
self.mouse_datamap.scroll_discrete = vec2(0.0, mouse.scroll_change / 120.0);
|
||||
*self.pointer.datamap.lock() = Datamap::from_typed(&self.mouse_datamap).ok();
|
||||
}
|
||||
self.send_keyboard_input(sk);
|
||||
}
|
||||
|
||||
fn send_keyboard_input(&mut self, sk: &impl StereoKitMultiThread) {
|
||||
let rx = PULSE_RECEIVER_REGISTRY
|
||||
.get_valid_contents()
|
||||
.into_iter()
|
||||
.filter(|rx| mask_matches(&rx.mask, &self.keyboard_sender.mask))
|
||||
.map(|rx| {
|
||||
let result = rx.field_node.get_aspect::<Field>().unwrap().ray_march(Ray {
|
||||
origin: vec3(0.0, 0.0, 0.0),
|
||||
direction: vec3(0.0, 0.0, -1.0),
|
||||
space: self.spatial.clone(),
|
||||
});
|
||||
(rx, result)
|
||||
})
|
||||
.filter(|(_rx, result)| {
|
||||
result.deepest_point_distance > 0.0 && result.min_distance < 0.05
|
||||
})
|
||||
.reduce(|(rx_a, result_a), (rx_b, result_b)| {
|
||||
if result_a.deepest_point_distance < result_b.deepest_point_distance {
|
||||
(rx_a, result_a)
|
||||
} else {
|
||||
(rx_b, result_b)
|
||||
}
|
||||
})
|
||||
.map(|(rx, _)| rx);
|
||||
|
||||
if let Some(rx) = rx {
|
||||
let keys = (8_u32..254)
|
||||
.filter_map(|i| Key::try_from(i).ok())
|
||||
.filter_map(|k| Some((map_key(k)?, sk.input_key(k))))
|
||||
.filter_map(|(i, k)| {
|
||||
if k.contains(ButtonState::JUST_ACTIVE) {
|
||||
Some(i as i32)
|
||||
} else if k.contains(ButtonState::JUST_INACTIVE) {
|
||||
Some(-(i as i32))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
self.keyboard_datamap.keys = keys;
|
||||
if !self.keyboard_datamap.keys.is_empty() {
|
||||
pulse_receiver_client::data(
|
||||
&rx.node.upgrade().unwrap(),
|
||||
&self.node.uid,
|
||||
&Datamap::from_typed(&self.keyboard_datamap).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
let mut fbb = flexbuffers::Builder::default();
|
||||
let mut map = fbb.start_map();
|
||||
map.push(
|
||||
"select",
|
||||
if sk.input_key(Key::MouseLeft).contains(ButtonState::Active) {
|
||||
1.0f32
|
||||
} else {
|
||||
0.0f32
|
||||
},
|
||||
);
|
||||
map.push(
|
||||
"grab",
|
||||
if sk.input_key(Key::MouseRight).contains(ButtonState::Active) {
|
||||
1.0f32
|
||||
} else {
|
||||
0.0f32
|
||||
},
|
||||
);
|
||||
map.end_map();
|
||||
*self.pointer.datamap.lock() = Datamap::new(fbb.take_buffer()).ok();
|
||||
}
|
||||
}
|
||||
|
||||
fn map_key(key: Key) -> Option<u32> {
|
||||
match key {
|
||||
Key::Backspace => Some(input_event_codes::KEY_BACKSPACE!()),
|
||||
Key::Tab => Some(input_event_codes::KEY_TAB!()),
|
||||
Key::Return => Some(input_event_codes::KEY_ENTER!()),
|
||||
Key::Shift => Some(input_event_codes::KEY_LEFTSHIFT!()),
|
||||
Key::Ctrl => Some(input_event_codes::KEY_LEFTCTRL!()),
|
||||
Key::Alt => Some(input_event_codes::KEY_LEFTALT!()),
|
||||
Key::CapsLock => Some(input_event_codes::KEY_CAPSLOCK!()),
|
||||
Key::Esc => Some(input_event_codes::KEY_ESC!()),
|
||||
Key::Space => Some(input_event_codes::KEY_SPACE!()),
|
||||
Key::End => Some(input_event_codes::KEY_END!()),
|
||||
Key::Home => Some(input_event_codes::KEY_HOME!()),
|
||||
Key::Left => Some(input_event_codes::KEY_LEFT!()),
|
||||
Key::Right => Some(input_event_codes::KEY_RIGHT!()),
|
||||
Key::Up => Some(input_event_codes::KEY_UP!()),
|
||||
Key::Down => Some(input_event_codes::KEY_DOWN!()),
|
||||
Key::PageUp => Some(input_event_codes::KEY_PAGEUP!()),
|
||||
Key::PageDown => Some(input_event_codes::KEY_PAGEDOWN!()),
|
||||
Key::PrintScreen => Some(input_event_codes::KEY_PRINT!()),
|
||||
Key::KeyInsert => Some(input_event_codes::KEY_INSERT!()),
|
||||
Key::Del => Some(input_event_codes::KEY_DELETE!()),
|
||||
Key::Key0 => Some(input_event_codes::KEY_0!()),
|
||||
Key::Key1 => Some(input_event_codes::KEY_1!()),
|
||||
Key::Key2 => Some(input_event_codes::KEY_2!()),
|
||||
Key::Key3 => Some(input_event_codes::KEY_3!()),
|
||||
Key::Key4 => Some(input_event_codes::KEY_4!()),
|
||||
Key::Key5 => Some(input_event_codes::KEY_5!()),
|
||||
Key::Key6 => Some(input_event_codes::KEY_6!()),
|
||||
Key::Key7 => Some(input_event_codes::KEY_7!()),
|
||||
Key::Key8 => Some(input_event_codes::KEY_8!()),
|
||||
Key::Key9 => Some(input_event_codes::KEY_9!()),
|
||||
Key::A => Some(input_event_codes::KEY_A!()),
|
||||
Key::B => Some(input_event_codes::KEY_B!()),
|
||||
Key::C => Some(input_event_codes::KEY_C!()),
|
||||
Key::D => Some(input_event_codes::KEY_D!()),
|
||||
Key::E => Some(input_event_codes::KEY_E!()),
|
||||
Key::F => Some(input_event_codes::KEY_F!()),
|
||||
Key::G => Some(input_event_codes::KEY_G!()),
|
||||
Key::H => Some(input_event_codes::KEY_H!()),
|
||||
Key::I => Some(input_event_codes::KEY_I!()),
|
||||
Key::J => Some(input_event_codes::KEY_J!()),
|
||||
Key::K => Some(input_event_codes::KEY_K!()),
|
||||
Key::L => Some(input_event_codes::KEY_L!()),
|
||||
Key::M => Some(input_event_codes::KEY_M!()),
|
||||
Key::N => Some(input_event_codes::KEY_N!()),
|
||||
Key::O => Some(input_event_codes::KEY_O!()),
|
||||
Key::P => Some(input_event_codes::KEY_P!()),
|
||||
Key::Q => Some(input_event_codes::KEY_Q!()),
|
||||
Key::R => Some(input_event_codes::KEY_R!()),
|
||||
Key::S => Some(input_event_codes::KEY_S!()),
|
||||
Key::T => Some(input_event_codes::KEY_T!()),
|
||||
Key::U => Some(input_event_codes::KEY_U!()),
|
||||
Key::V => Some(input_event_codes::KEY_V!()),
|
||||
Key::W => Some(input_event_codes::KEY_W!()),
|
||||
Key::X => Some(input_event_codes::KEY_X!()),
|
||||
Key::Y => Some(input_event_codes::KEY_Y!()),
|
||||
Key::Z => Some(input_event_codes::KEY_Z!()),
|
||||
Key::Numpad0 => Some(input_event_codes::KEY_NUMERIC_0!()),
|
||||
Key::Numpad1 => Some(input_event_codes::KEY_NUMERIC_1!()),
|
||||
Key::Numpad2 => Some(input_event_codes::KEY_NUMERIC_2!()),
|
||||
Key::Numpad3 => Some(input_event_codes::KEY_NUMERIC_3!()),
|
||||
Key::Numpad4 => Some(input_event_codes::KEY_NUMERIC_4!()),
|
||||
Key::Numpad5 => Some(input_event_codes::KEY_NUMERIC_5!()),
|
||||
Key::Numpad6 => Some(input_event_codes::KEY_NUMERIC_6!()),
|
||||
Key::Numpad7 => Some(input_event_codes::KEY_NUMERIC_7!()),
|
||||
Key::Numpad8 => Some(input_event_codes::KEY_NUMERIC_8!()),
|
||||
Key::Numpad9 => Some(input_event_codes::KEY_NUMERIC_9!()),
|
||||
Key::F1 => Some(input_event_codes::KEY_F1!()),
|
||||
Key::F2 => Some(input_event_codes::KEY_F2!()),
|
||||
Key::F3 => Some(input_event_codes::KEY_F3!()),
|
||||
Key::F4 => Some(input_event_codes::KEY_F4!()),
|
||||
Key::F5 => Some(input_event_codes::KEY_F5!()),
|
||||
Key::F6 => Some(input_event_codes::KEY_F6!()),
|
||||
Key::F7 => Some(input_event_codes::KEY_F7!()),
|
||||
Key::F8 => Some(input_event_codes::KEY_F8!()),
|
||||
Key::F9 => Some(input_event_codes::KEY_F9!()),
|
||||
Key::F10 => Some(input_event_codes::KEY_F10!()),
|
||||
Key::F11 => Some(input_event_codes::KEY_F11!()),
|
||||
Key::F12 => Some(input_event_codes::KEY_F12!()),
|
||||
Key::Comma => Some(input_event_codes::KEY_COMMA!()),
|
||||
Key::Period => Some(input_event_codes::KEY_DOT!()),
|
||||
Key::SlashFwd => Some(input_event_codes::KEY_SLASH!()),
|
||||
Key::SlashBack => Some(input_event_codes::KEY_BACKSLASH!()),
|
||||
Key::Semicolon => Some(input_event_codes::KEY_SEMICOLON!()),
|
||||
Key::Apostrophe => Some(input_event_codes::KEY_APOSTROPHE!()),
|
||||
Key::BracketOpen => Some(input_event_codes::KEY_LEFTBRACE!()),
|
||||
Key::BracketClose => Some(input_event_codes::KEY_RIGHTBRACE!()),
|
||||
Key::Minus => Some(input_event_codes::KEY_MINUS!()),
|
||||
Key::Equals => Some(input_event_codes::KEY_EQUAL!()),
|
||||
Key::Backtick => None,
|
||||
Key::LCmd => Some(input_event_codes::KEY_LEFTMETA!()),
|
||||
Key::RCmd => Some(input_event_codes::KEY_RIGHTMETA!()),
|
||||
Key::Multiply => Some(input_event_codes::KEY_NUMERIC_STAR!()),
|
||||
Key::Add => Some(input_event_codes::KEY_KPPLUS!()),
|
||||
Key::Subtract => Some(input_event_codes::KEY_MINUS!()),
|
||||
Key::Decimal => Some(input_event_codes::KEY_DOT!()),
|
||||
Key::Divide => Some(input_event_codes::KEY_SLASH!()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,47 +1,79 @@
|
||||
use crate::nodes::{
|
||||
input::{tip::Tip, InputMethod, InputType},
|
||||
spatial::Spatial,
|
||||
use crate::{
|
||||
core::client::INTERNAL_CLIENT,
|
||||
nodes::{
|
||||
input::{tip::Tip, InputMethod, InputType},
|
||||
spatial::Spatial,
|
||||
Node,
|
||||
},
|
||||
};
|
||||
use glam::Mat4;
|
||||
use stardust_xr::{schemas::flat::Datamap, values::Transform};
|
||||
use std::sync::{Arc, Weak};
|
||||
use color_eyre::eyre::Result;
|
||||
use glam::{Mat4, Vec2, Vec3};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use stardust_xr::values::Datamap;
|
||||
use std::sync::Arc;
|
||||
use stereokit::{
|
||||
input::{ButtonState, Handed},
|
||||
StereoKit,
|
||||
named_colors::WHITE, ButtonState, Handed, Model, RenderLayer, StereoKitDraw,
|
||||
StereoKitMultiThread,
|
||||
};
|
||||
|
||||
#[derive(Default, Deserialize, Serialize)]
|
||||
struct ControllerDatamap {
|
||||
select: f32,
|
||||
grab: f32,
|
||||
scroll: Vec2,
|
||||
}
|
||||
|
||||
pub struct SkController {
|
||||
tip: Arc<InputMethod>,
|
||||
_node: Arc<Node>,
|
||||
input: Arc<InputMethod>,
|
||||
model: Model,
|
||||
handed: Handed,
|
||||
datamap: ControllerDatamap,
|
||||
}
|
||||
impl SkController {
|
||||
pub fn new(handed: Handed) -> Self {
|
||||
SkController {
|
||||
tip: InputMethod::new(
|
||||
Spatial::new(Weak::new(), None, Mat4::IDENTITY),
|
||||
InputType::Tip(Tip::default()),
|
||||
),
|
||||
pub fn new(sk: &impl StereoKitMultiThread, handed: Handed) -> Result<Self> {
|
||||
let _node = Node::create_parent_name(
|
||||
&INTERNAL_CLIENT,
|
||||
"",
|
||||
if handed == Handed::Left {
|
||||
"controller_left"
|
||||
} else {
|
||||
"controller_right"
|
||||
},
|
||||
false,
|
||||
)
|
||||
.add_to_scenegraph()?;
|
||||
Spatial::add_to(&_node, None, Mat4::IDENTITY, false);
|
||||
let model = sk.model_create_mem("cursor.glb", include_bytes!("cursor.glb"), None)?;
|
||||
let tip = InputType::Tip(Tip::default());
|
||||
let input = InputMethod::add_to(&_node, tip, None)?;
|
||||
Ok(SkController {
|
||||
_node,
|
||||
input,
|
||||
handed,
|
||||
}
|
||||
model,
|
||||
datamap: Default::default(),
|
||||
})
|
||||
}
|
||||
pub fn update(&mut self, sk: &StereoKit) {
|
||||
pub fn update(&mut self, sk: &impl StereoKitDraw) {
|
||||
let controller = sk.input_controller(self.handed);
|
||||
*self.tip.enabled.lock() = controller.tracked.contains(ButtonState::Active);
|
||||
if *self.tip.enabled.lock() {
|
||||
self.tip.spatial.set_local_transform_components(
|
||||
None,
|
||||
Transform {
|
||||
position: Some(controller.pose.position),
|
||||
rotation: Some(controller.pose.orientation),
|
||||
scale: None,
|
||||
},
|
||||
*self.input.enabled.lock() = controller.tracked.contains(ButtonState::ACTIVE);
|
||||
if *self.input.enabled.lock() {
|
||||
let world_transform = Mat4::from_rotation_translation(
|
||||
controller.aim.orientation,
|
||||
controller.aim.position,
|
||||
);
|
||||
sk.model_draw(
|
||||
&self.model,
|
||||
world_transform * Mat4::from_scale(Vec3::ONE * 0.02),
|
||||
WHITE,
|
||||
RenderLayer::LAYER0,
|
||||
);
|
||||
self.input.spatial.set_local_transform(world_transform);
|
||||
}
|
||||
let mut fbb = flexbuffers::Builder::default();
|
||||
let mut map = fbb.start_map();
|
||||
map.push("select", controller.trigger);
|
||||
map.push("grab", controller.grip);
|
||||
map.end_map();
|
||||
*self.tip.datamap.lock() = Datamap::new(fbb.take_buffer()).ok();
|
||||
self.datamap.select = controller.trigger;
|
||||
self.datamap.grab = controller.grip;
|
||||
self.datamap.scroll = controller.stick;
|
||||
*self.input.datamap.lock() = Datamap::from_typed(&self.datamap).ok();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,49 +1,74 @@
|
||||
use crate::nodes::{
|
||||
input::{hand::Hand, InputMethod, InputType},
|
||||
spatial::Spatial,
|
||||
use crate::{
|
||||
core::client::INTERNAL_CLIENT,
|
||||
nodes::{
|
||||
input::{hand::Hand, InputMethod, InputType},
|
||||
spatial::Spatial,
|
||||
Node,
|
||||
},
|
||||
};
|
||||
use color_eyre::eyre::Result;
|
||||
use glam::Mat4;
|
||||
use stardust_xr::schemas::flat::{Datamap, Hand as FlatHand, Joint};
|
||||
use std::sync::{Arc, Weak};
|
||||
use stereokit::{
|
||||
input::{ButtonState, Handed, Joint as SkJoint},
|
||||
StereoKit,
|
||||
use nanoid::nanoid;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use stardust_xr::{
|
||||
schemas::flat::{Hand as FlatHand, Joint},
|
||||
values::Datamap,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
use stereokit::{ButtonState, HandJoint, Handed, StereoKitMultiThread};
|
||||
|
||||
fn convert_joint(joint: SkJoint) -> Joint {
|
||||
fn convert_joint(joint: HandJoint) -> Joint {
|
||||
Joint {
|
||||
position: joint.position,
|
||||
rotation: joint.orientation,
|
||||
position: joint.position.into(),
|
||||
rotation: joint.orientation.into(),
|
||||
radius: joint.radius,
|
||||
distance: 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize, Serialize)]
|
||||
struct HandDatamap {
|
||||
pinch_strength: f32,
|
||||
grab_strength: f32,
|
||||
}
|
||||
|
||||
pub struct SkHand {
|
||||
hand: Arc<InputMethod>,
|
||||
_node: Arc<Node>,
|
||||
input: Arc<InputMethod>,
|
||||
handed: Handed,
|
||||
datamap: HandDatamap,
|
||||
}
|
||||
impl SkHand {
|
||||
pub fn new(handed: Handed) -> Self {
|
||||
SkHand {
|
||||
hand: InputMethod::new(
|
||||
Spatial::new(Weak::new(), None, Mat4::IDENTITY),
|
||||
InputType::Hand(Box::new(Hand {
|
||||
base: FlatHand {
|
||||
right: handed == Handed::Right,
|
||||
..Default::default()
|
||||
},
|
||||
})),
|
||||
),
|
||||
pub fn new(handed: Handed) -> Result<Self> {
|
||||
let _node = Node::create_parent_name(&INTERNAL_CLIENT, "", &nanoid!(), false)
|
||||
.add_to_scenegraph()?;
|
||||
Spatial::add_to(&_node, None, Mat4::IDENTITY, false);
|
||||
let hand = InputType::Hand(Box::new(Hand {
|
||||
base: FlatHand {
|
||||
right: handed == Handed::Right,
|
||||
..Default::default()
|
||||
},
|
||||
}));
|
||||
let input = InputMethod::add_to(&_node, hand, None)?;
|
||||
Ok(SkHand {
|
||||
_node,
|
||||
input,
|
||||
handed,
|
||||
}
|
||||
datamap: Default::default(),
|
||||
})
|
||||
}
|
||||
pub fn update(&mut self, sk: &StereoKit) {
|
||||
pub fn update(&mut self, controller_enabled: bool, sk: &impl StereoKitMultiThread) {
|
||||
let sk_hand = sk.input_hand(self.handed);
|
||||
if let InputType::Hand(hand) = &mut *self.hand.specialization.lock() {
|
||||
let controller = sk.input_controller(self.handed);
|
||||
*self.hand.enabled.lock() = controller.tracked.contains(ButtonState::Inactive)
|
||||
&& sk_hand.tracked_state.contains(ButtonState::Active);
|
||||
if *self.hand.enabled.lock() {
|
||||
if let InputType::Hand(hand) = &mut *self.input.specialization.lock() {
|
||||
let controller_active = controller_enabled
|
||||
&& sk
|
||||
.input_controller(self.handed)
|
||||
.tracked
|
||||
.contains(ButtonState::ACTIVE);
|
||||
*self.input.enabled.lock() =
|
||||
!controller_active && sk_hand.tracked_state.contains(ButtonState::ACTIVE);
|
||||
sk.input_hand_visible(self.handed, *self.input.enabled.lock());
|
||||
if *self.input.enabled.lock() {
|
||||
hand.base.thumb.tip = convert_joint(sk_hand.fingers[0][4]);
|
||||
hand.base.thumb.distal = convert_joint(sk_hand.fingers[0][3]);
|
||||
hand.base.thumb.proximal = convert_joint(sk_hand.fingers[0][2]);
|
||||
@@ -62,24 +87,21 @@ impl SkHand {
|
||||
finger.metacarpal = convert_joint(sk_finger[0]);
|
||||
}
|
||||
|
||||
hand.base.palm.position = sk_hand.palm.position;
|
||||
hand.base.palm.rotation = sk_hand.palm.orientation;
|
||||
hand.base.palm.position = sk_hand.palm.position.into();
|
||||
hand.base.palm.rotation = sk_hand.palm.orientation.into();
|
||||
hand.base.palm.radius =
|
||||
(sk_hand.fingers[2][0].radius + sk_hand.fingers[2][1].radius) * 0.5;
|
||||
|
||||
hand.base.wrist.position = sk_hand.wrist.position;
|
||||
hand.base.wrist.rotation = sk_hand.wrist.orientation;
|
||||
hand.base.wrist.position = sk_hand.wrist.position.into();
|
||||
hand.base.wrist.rotation = sk_hand.wrist.orientation.into();
|
||||
hand.base.wrist.radius =
|
||||
(sk_hand.fingers[0][0].radius + sk_hand.fingers[4][0].radius) * 0.5;
|
||||
|
||||
hand.base.elbow = None;
|
||||
}
|
||||
}
|
||||
let mut fbb = flexbuffers::Builder::default();
|
||||
let mut map = fbb.start_map();
|
||||
map.push("grabStrength", sk_hand.grip_activation);
|
||||
map.push("pinchStrength", sk_hand.pinch_activation);
|
||||
map.end_map();
|
||||
*self.hand.datamap.lock() = Datamap::new(fbb.take_buffer()).ok();
|
||||
self.datamap.pinch_strength = sk_hand.pinch_activation;
|
||||
self.datamap.grab_strength = sk_hand.grip_activation;
|
||||
*self.input.datamap.lock() = Datamap::from_typed(&self.datamap).ok();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
pub mod input;
|
||||
pub mod play_space;
|
||||
|
||||
81
src/objects/play_space.rs
Normal file
81
src/objects/play_space.rs
Normal file
@@ -0,0 +1,81 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use color_eyre::eyre::Result;
|
||||
use glam::Mat4;
|
||||
use mint::Vector2;
|
||||
use nanoid::nanoid;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use stardust_xr::values::Datamap;
|
||||
use stereokit::StereoKitMultiThread;
|
||||
|
||||
use crate::{
|
||||
core::client::INTERNAL_CLIENT,
|
||||
nodes::{
|
||||
data::PulseReceiver,
|
||||
fields::{r#box::BoxField, Field},
|
||||
spatial::Spatial,
|
||||
Node,
|
||||
},
|
||||
};
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
struct PlaySpaceMap {
|
||||
play_space: (),
|
||||
size: Vector2<f32>,
|
||||
}
|
||||
impl Default for PlaySpaceMap {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
play_space: (),
|
||||
size: [0.0; 2].into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PlaySpace {
|
||||
_node: Arc<Node>,
|
||||
spatial: Arc<Spatial>,
|
||||
field: Arc<Field>,
|
||||
_pulse_rx: Arc<PulseReceiver>,
|
||||
}
|
||||
impl PlaySpace {
|
||||
pub fn new() -> Result<Self> {
|
||||
let node = Node::create_parent_name(&INTERNAL_CLIENT, "", &nanoid!(), false)
|
||||
.add_to_scenegraph()?;
|
||||
let spatial = Spatial::add_to(&node, None, Mat4::IDENTITY, false);
|
||||
BoxField::add_to(&node, [0.0; 3].into());
|
||||
let field = node.get_aspect::<Field>()?.clone();
|
||||
|
||||
let pulse_rx = PulseReceiver::add_to(
|
||||
&node,
|
||||
node.clone(),
|
||||
Datamap::from_typed(PlaySpaceMap::default())?,
|
||||
)?;
|
||||
|
||||
Ok(PlaySpace {
|
||||
_node: node,
|
||||
spatial,
|
||||
field,
|
||||
_pulse_rx: pulse_rx,
|
||||
})
|
||||
}
|
||||
pub fn update(&self, sk: &impl StereoKitMultiThread) {
|
||||
let pose = sk.world_get_bounds_pose();
|
||||
self.spatial
|
||||
.set_local_transform(Mat4::from_rotation_translation(
|
||||
pose.orientation,
|
||||
pose.position,
|
||||
));
|
||||
let Field::Box(box_field) = self.field.as_ref() else {
|
||||
return;
|
||||
};
|
||||
box_field.set_size(
|
||||
[
|
||||
sk.world_get_bounds_size().x,
|
||||
0.0,
|
||||
sk.world_get_bounds_size().y,
|
||||
]
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,16 @@
|
||||
use super::{state::WaylandState, surface::CoreSurface};
|
||||
use crate::wayland::surface::CoreSurface;
|
||||
|
||||
use super::state::{ClientState, WaylandState};
|
||||
use portable_atomic::{AtomicU32, Ordering};
|
||||
#[cfg(feature = "xwayland")]
|
||||
use smithay::xwayland::XWaylandClientData;
|
||||
use smithay::{
|
||||
delegate_compositor,
|
||||
reexports::wayland_server::protocol::wl_surface::WlSurface,
|
||||
wayland::compositor::{self, CompositorHandler, CompositorState},
|
||||
reexports::wayland_server::{protocol::wl_surface::WlSurface, Client},
|
||||
wayland::compositor::{self, CompositorClientState, CompositorHandler, CompositorState},
|
||||
};
|
||||
use std::sync::Arc;
|
||||
use tracing::debug;
|
||||
|
||||
impl CompositorHandler for WaylandState {
|
||||
fn compositor_state(&mut self) -> &mut CompositorState {
|
||||
@@ -11,16 +18,35 @@ impl CompositorHandler for WaylandState {
|
||||
}
|
||||
|
||||
fn commit(&mut self, surface: &WlSurface) {
|
||||
compositor::with_states(surface, |data| {
|
||||
data.data_map.insert_if_missing_threadsafe(|| {
|
||||
CoreSurface::new(
|
||||
&self.weak_ref.upgrade().unwrap(),
|
||||
&self.display,
|
||||
self.display_handle.clone(),
|
||||
surface,
|
||||
)
|
||||
})
|
||||
debug!(?surface, "Surface commit");
|
||||
let mut count = 0;
|
||||
let core_surface = compositor::with_states(surface, |data| {
|
||||
let count_new = data
|
||||
.data_map
|
||||
.insert_if_missing_threadsafe(|| AtomicU32::new(0));
|
||||
if !count_new {
|
||||
if let Some(stored_count) = data.data_map.get::<AtomicU32>() {
|
||||
count = stored_count.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
data.data_map.get::<Arc<CoreSurface>>().cloned()
|
||||
});
|
||||
if let Some(core_surface) = core_surface {
|
||||
core_surface.commit(count);
|
||||
}
|
||||
}
|
||||
|
||||
fn client_compositor_state<'a>(&self, client: &'a Client) -> &'a CompositorClientState {
|
||||
if let Some(client_state) = client.get_data::<ClientState>() {
|
||||
&client_state.compositor_state
|
||||
} else {
|
||||
#[cfg(feature = "xwayland")]
|
||||
if let Some(xwayland_client_data) = client.get_data::<XWaylandClientData>() {
|
||||
return &xwayland_client_data.compositor_state;
|
||||
}
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,34 +1,97 @@
|
||||
use super::state::WaylandState;
|
||||
use smithay::{
|
||||
delegate_kde_decoration, delegate_xdg_decoration,
|
||||
reexports::wayland_protocols::xdg::decoration::zv1::server::zxdg_toplevel_decoration_v1::Mode,
|
||||
wayland::shell::{
|
||||
self, kde::decoration::KdeDecorationHandler, xdg::decoration::XdgDecorationHandler,
|
||||
delegate_kde_decoration,
|
||||
reexports::{
|
||||
wayland_protocols::xdg::{
|
||||
decoration::zv1::server::{
|
||||
zxdg_decoration_manager_v1::{self, ZxdgDecorationManagerV1},
|
||||
zxdg_toplevel_decoration_v1::{self, Mode, ZxdgToplevelDecorationV1},
|
||||
},
|
||||
shell::server::xdg_toplevel::XdgToplevel,
|
||||
},
|
||||
wayland_protocols_misc::server_decoration::server::org_kde_kwin_server_decoration::{
|
||||
Mode as KdeMode, OrgKdeKwinServerDecoration,
|
||||
},
|
||||
wayland_server::{
|
||||
protocol::wl_surface::WlSurface, Client, DataInit, Dispatch, DisplayHandle,
|
||||
GlobalDispatch, New, Resource, WEnum, Weak,
|
||||
},
|
||||
},
|
||||
wayland::shell::{self, kde::decoration::KdeDecorationHandler},
|
||||
};
|
||||
|
||||
impl XdgDecorationHandler for WaylandState {
|
||||
fn new_decoration(&mut self, toplevel: smithay::wayland::shell::xdg::ToplevelSurface) {
|
||||
toplevel.with_pending_state(|state| {
|
||||
state.decoration_mode = Some(Mode::ServerSide);
|
||||
});
|
||||
toplevel.send_configure();
|
||||
}
|
||||
|
||||
fn request_mode(
|
||||
&mut self,
|
||||
_toplevel: smithay::wayland::shell::xdg::ToplevelSurface,
|
||||
_mode: smithay::reexports::wayland_protocols::xdg::decoration::zv1::server::zxdg_toplevel_decoration_v1::Mode,
|
||||
impl GlobalDispatch<ZxdgDecorationManagerV1, (), WaylandState> for WaylandState {
|
||||
fn bind(
|
||||
_state: &mut WaylandState,
|
||||
_handle: &DisplayHandle,
|
||||
_client: &Client,
|
||||
resource: New<ZxdgDecorationManagerV1>,
|
||||
_global_data: &(),
|
||||
data_init: &mut DataInit<'_, WaylandState>,
|
||||
) {
|
||||
data_init.init(resource, ());
|
||||
}
|
||||
}
|
||||
|
||||
impl Dispatch<ZxdgDecorationManagerV1, (), WaylandState> for WaylandState {
|
||||
fn request(
|
||||
_state: &mut WaylandState,
|
||||
_client: &Client,
|
||||
_resource: &ZxdgDecorationManagerV1,
|
||||
request: zxdg_decoration_manager_v1::Request,
|
||||
_data: &(),
|
||||
_dhandle: &DisplayHandle,
|
||||
data_init: &mut DataInit<'_, WaylandState>,
|
||||
) {
|
||||
match request {
|
||||
zxdg_decoration_manager_v1::Request::Destroy => (),
|
||||
zxdg_decoration_manager_v1::Request::GetToplevelDecoration { id, toplevel } => {
|
||||
data_init.init(id, toplevel.downgrade());
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Dispatch<ZxdgToplevelDecorationV1, Weak<XdgToplevel>, WaylandState> for WaylandState {
|
||||
fn request(
|
||||
_state: &mut WaylandState,
|
||||
_client: &Client,
|
||||
resource: &ZxdgToplevelDecorationV1,
|
||||
request: zxdg_toplevel_decoration_v1::Request,
|
||||
_data: &Weak<XdgToplevel>,
|
||||
_dhandle: &DisplayHandle,
|
||||
_data_init: &mut DataInit<'_, WaylandState>,
|
||||
) {
|
||||
match request {
|
||||
zxdg_toplevel_decoration_v1::Request::SetMode { mode: _ } => {
|
||||
resource.configure(Mode::ServerSide);
|
||||
}
|
||||
zxdg_toplevel_decoration_v1::Request::UnsetMode => {
|
||||
resource.configure(Mode::ServerSide);
|
||||
}
|
||||
zxdg_toplevel_decoration_v1::Request::Destroy => (),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
fn unset_mode(&mut self, _toplevel: smithay::wayland::shell::xdg::ToplevelSurface) {}
|
||||
}
|
||||
delegate_xdg_decoration!(WaylandState);
|
||||
|
||||
impl KdeDecorationHandler for WaylandState {
|
||||
fn kde_decoration_state(&self) -> &shell::kde::decoration::KdeDecorationState {
|
||||
&self.kde_decoration_state
|
||||
}
|
||||
|
||||
fn new_decoration(&mut self, _surface: &WlSurface, decoration: &OrgKdeKwinServerDecoration) {
|
||||
decoration.mode(KdeMode::Server);
|
||||
}
|
||||
|
||||
fn request_mode(
|
||||
&mut self,
|
||||
_surface: &WlSurface,
|
||||
decoration: &OrgKdeKwinServerDecoration,
|
||||
mode: WEnum<KdeMode>,
|
||||
) {
|
||||
let Ok(mode) = mode.into_result() else {return};
|
||||
decoration.mode(mode);
|
||||
}
|
||||
}
|
||||
delegate_kde_decoration!(WaylandState);
|
||||
|
||||
144
src/wayland/drm.rs
Normal file
144
src/wayland/drm.rs
Normal file
@@ -0,0 +1,144 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// Re-export only the actual code, and then only use this re-export
|
||||
// The `generated` module below is just some boilerplate to properly isolate stuff
|
||||
// and avoid exposing internal details.
|
||||
//
|
||||
// You can use all the types from my_protocol as if they went from `wayland_client::protocol`.
|
||||
pub use generated::wl_drm;
|
||||
|
||||
#[allow(non_upper_case_globals, non_camel_case_types)]
|
||||
mod generated {
|
||||
use smithay::reexports::wayland_server::{self, protocol::*};
|
||||
|
||||
pub mod __interfaces {
|
||||
use smithay::reexports::wayland_server::protocol::__interfaces::*;
|
||||
wayland_scanner::generate_interfaces!("src/wayland/wayland-drm.xml");
|
||||
}
|
||||
use self::__interfaces::*;
|
||||
|
||||
wayland_scanner::generate_server_code!("src/wayland/wayland-drm.xml");
|
||||
}
|
||||
|
||||
use super::state::WaylandState;
|
||||
use smithay::{
|
||||
backend::allocator::{
|
||||
dmabuf::{Dmabuf, DmabufFlags},
|
||||
Fourcc, Modifier,
|
||||
},
|
||||
reexports::wayland_server::{
|
||||
Client, DataInit, Dispatch, DisplayHandle, GlobalDispatch, New, Resource,
|
||||
},
|
||||
};
|
||||
use std::convert::TryFrom;
|
||||
|
||||
impl GlobalDispatch<wl_drm::WlDrm, (), WaylandState> for WaylandState {
|
||||
fn bind(
|
||||
state: &mut WaylandState,
|
||||
_dh: &DisplayHandle,
|
||||
_client: &Client,
|
||||
resource: New<wl_drm::WlDrm>,
|
||||
_global_data: &(),
|
||||
data_init: &mut DataInit<'_, WaylandState>,
|
||||
) {
|
||||
let drm_instance = data_init.init(resource, ());
|
||||
|
||||
drm_instance.device("/dev/dri/renderD128".to_string());
|
||||
if drm_instance.version() >= 2 {
|
||||
drm_instance.capabilities(wl_drm::Capability::Prime as u32);
|
||||
}
|
||||
for format in state.drm_formats.iter() {
|
||||
if let Ok(converted) = wl_drm::Format::try_from(*format as u32) {
|
||||
drm_instance.format(converted as u32);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn can_view(_client: Client, _global_dataa: &()) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl Dispatch<wl_drm::WlDrm, (), WaylandState> for WaylandState {
|
||||
fn request(
|
||||
state: &mut WaylandState,
|
||||
_client: &Client,
|
||||
drm: &wl_drm::WlDrm,
|
||||
request: wl_drm::Request,
|
||||
_data: &(),
|
||||
_dh: &DisplayHandle,
|
||||
data_init: &mut DataInit<'_, WaylandState>,
|
||||
) {
|
||||
match request {
|
||||
wl_drm::Request::Authenticate { .. } => drm.authenticated(),
|
||||
wl_drm::Request::CreateBuffer { .. } => drm.post_error(
|
||||
wl_drm::Error::InvalidName,
|
||||
String::from("Flink handles are unsupported, use PRIME"),
|
||||
),
|
||||
wl_drm::Request::CreatePlanarBuffer { .. } => drm.post_error(
|
||||
wl_drm::Error::InvalidName,
|
||||
String::from("Flink handles are unsupported, use PRIME"),
|
||||
),
|
||||
wl_drm::Request::CreatePrimeBuffer {
|
||||
id,
|
||||
name,
|
||||
width,
|
||||
height,
|
||||
format,
|
||||
offset0,
|
||||
stride0,
|
||||
..
|
||||
} => {
|
||||
let format = match Fourcc::try_from(format) {
|
||||
Ok(format) => {
|
||||
if !state.drm_formats.contains(&format) {
|
||||
drm.post_error(
|
||||
wl_drm::Error::InvalidFormat,
|
||||
String::from("Format not advertised by wl_drm"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
format
|
||||
}
|
||||
Err(_) => {
|
||||
drm.post_error(
|
||||
wl_drm::Error::InvalidFormat,
|
||||
String::from("Format unknown / not advertised by wl_drm"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
if width < 1 || height < 1 {
|
||||
drm.post_error(
|
||||
wl_drm::Error::InvalidFormat,
|
||||
String::from("width or height not positive"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let mut dma = Dmabuf::builder(
|
||||
(width, height),
|
||||
format,
|
||||
Modifier::Invalid,
|
||||
DmabufFlags::empty(),
|
||||
);
|
||||
dma.add_plane(name, 0, offset0 as u32, stride0 as u32);
|
||||
match dma.build() {
|
||||
Some(dmabuf) => {
|
||||
state.dmabuf_tx.send((dmabuf.clone(), None)).unwrap();
|
||||
data_init.init(id, dmabuf);
|
||||
}
|
||||
None => {
|
||||
// Buffer import failed. The protocol documentation heavily implies killing the
|
||||
// client is the right thing to do here.
|
||||
drm.post_error(
|
||||
wl_drm::Error::InvalidName,
|
||||
"dmabuf global was destroyed on server",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,38 +1,59 @@
|
||||
pub mod compositor;
|
||||
mod compositor;
|
||||
mod data_device;
|
||||
pub mod decoration;
|
||||
pub mod panel_item;
|
||||
pub mod seat;
|
||||
pub mod shaders;
|
||||
pub mod state;
|
||||
pub mod surface;
|
||||
pub mod xdg_activation;
|
||||
pub mod xdg_shell;
|
||||
mod decoration;
|
||||
mod seat;
|
||||
mod state;
|
||||
mod surface;
|
||||
// mod xdg_activation;
|
||||
mod drm;
|
||||
mod utils;
|
||||
mod xdg_shell;
|
||||
#[cfg(feature = "xwayland_rootful")]
|
||||
pub mod xwayland_rootful;
|
||||
#[cfg(feature = "xwayland_rootful")]
|
||||
use self::xwayland_rootful::X11Lock;
|
||||
#[cfg(feature = "xwayland_rootful")]
|
||||
use crate::wayland::xwayland_rootful::start_xwayland;
|
||||
#[cfg(feature = "xwayland_rootless")]
|
||||
pub mod xwayland_rootless;
|
||||
#[cfg(feature = "xwayland_rootless")]
|
||||
use self::xwayland_rootless::XWaylandState;
|
||||
|
||||
use self::{panel_item::PanelItem, state::WaylandState, surface::CORE_SURFACES};
|
||||
use crate::wayland::state::ClientState;
|
||||
use anyhow::{ensure, Result};
|
||||
use self::{state::WaylandState, surface::CORE_SURFACES};
|
||||
use crate::wayland::seat::SeatData;
|
||||
use crate::{core::task, wayland::state::ClientState};
|
||||
use color_eyre::eyre::{ensure, Result};
|
||||
use global_counter::primitive::exact::CounterU32;
|
||||
use once_cell::sync::OnceCell;
|
||||
use parking_lot::Mutex;
|
||||
use slog::Logger;
|
||||
use smithay::{
|
||||
backend::{egl::EGLContext, renderer::gles2::Gles2Renderer},
|
||||
reexports::wayland_server::{backend::GlobalId, Display, ListeningSocket, Resource},
|
||||
};
|
||||
use sk::StereoKitDraw;
|
||||
use smithay::backend::allocator::dmabuf::Dmabuf;
|
||||
use smithay::backend::egl::EGLContext;
|
||||
use smithay::backend::renderer::gles::GlesRenderer;
|
||||
use smithay::backend::renderer::ImportDma;
|
||||
use smithay::output::Output;
|
||||
use smithay::reexports::wayland_server::backend::ClientId;
|
||||
use smithay::reexports::wayland_server::DisplayHandle;
|
||||
use smithay::reexports::wayland_server::{Display, ListeningSocket};
|
||||
use smithay::wayland::dmabuf;
|
||||
use std::ffi::OsStr;
|
||||
use std::os::fd::OwnedFd;
|
||||
use std::os::unix::prelude::AsRawFd;
|
||||
use std::{
|
||||
ffi::c_void,
|
||||
os::unix::{
|
||||
net::UnixListener,
|
||||
prelude::{FromRawFd, RawFd},
|
||||
},
|
||||
os::unix::{net::UnixListener, prelude::FromRawFd},
|
||||
sync::Arc,
|
||||
};
|
||||
use stereokit as sk;
|
||||
use stereokit::StereoKit;
|
||||
use tokio::sync::mpsc::UnboundedReceiver;
|
||||
use tokio::{
|
||||
io::unix::AsyncFd, net::UnixListener as AsyncUnixListener, sync::mpsc, task::JoinHandle,
|
||||
};
|
||||
use tracing::{debug_span, info, instrument};
|
||||
|
||||
pub static X_DISPLAY: OnceCell<u32> = OnceCell::new();
|
||||
pub static WAYLAND_DISPLAY: OnceCell<String> = OnceCell::new();
|
||||
pub static SERIAL_COUNTER: CounterU32 = CounterU32::new(0);
|
||||
|
||||
struct EGLRawHandles {
|
||||
display: *const c_void,
|
||||
@@ -55,122 +76,153 @@ fn get_sk_egl() -> Result<EGLRawHandles> {
|
||||
})
|
||||
}
|
||||
|
||||
static GLOBAL_DESTROY_QUEUE: OnceCell<mpsc::Sender<GlobalId>> = OnceCell::new();
|
||||
pub struct DisplayWrapper(Mutex<Display<WaylandState>>, DisplayHandle);
|
||||
impl DisplayWrapper {
|
||||
pub fn handle(&self) -> DisplayHandle {
|
||||
self.1.clone()
|
||||
}
|
||||
pub fn dispatch_clients(&self, state: &mut WaylandState) -> Result<usize, std::io::Error> {
|
||||
self.0.lock().dispatch_clients(state)
|
||||
}
|
||||
pub fn flush_clients(&self, client: Option<ClientId>) {
|
||||
if let Some(mut lock) = self.0.try_lock() {
|
||||
let _ = lock.backend().flush(client);
|
||||
}
|
||||
}
|
||||
pub fn poll_fd(&self) -> Result<OwnedFd, std::io::Error> {
|
||||
self.0.lock().backend().poll_fd().try_clone_to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Wayland {
|
||||
log: slog::Logger,
|
||||
|
||||
display: Arc<Mutex<Display<WaylandState>>>,
|
||||
display: Arc<DisplayWrapper>,
|
||||
pub socket_name: Option<String>,
|
||||
join_handle: JoinHandle<Result<()>>,
|
||||
renderer: Gles2Renderer,
|
||||
state: Arc<Mutex<WaylandState>>,
|
||||
renderer: GlesRenderer,
|
||||
output: Output,
|
||||
dmabuf_rx: UnboundedReceiver<(Dmabuf, Option<dmabuf::ImportNotifier>)>,
|
||||
#[cfg(feature = "xwayland_rootful")]
|
||||
pub x_lock: X11Lock,
|
||||
#[cfg(feature = "xwayland_rootless")]
|
||||
pub xwayland_state: XWaylandState,
|
||||
}
|
||||
impl Wayland {
|
||||
pub fn new(log: Logger) -> Result<Self> {
|
||||
pub fn new() -> Result<Self> {
|
||||
let egl_raw_handles = get_sk_egl()?;
|
||||
let renderer = unsafe {
|
||||
Gles2Renderer::new(
|
||||
EGLContext::from_raw(
|
||||
egl_raw_handles.display,
|
||||
egl_raw_handles.config,
|
||||
egl_raw_handles.context,
|
||||
log.clone(),
|
||||
)?,
|
||||
log.clone(),
|
||||
)?
|
||||
GlesRenderer::new(EGLContext::from_raw(
|
||||
egl_raw_handles.display,
|
||||
egl_raw_handles.config,
|
||||
egl_raw_handles.context,
|
||||
)?)?
|
||||
};
|
||||
|
||||
let display: Display<WaylandState> = Display::new()?;
|
||||
let display_handle = display.handle();
|
||||
|
||||
let display = Arc::new(Mutex::new(display));
|
||||
let state = WaylandState::new(log.clone(), display.clone(), display_handle);
|
||||
let (dmabuf_tx, dmabuf_rx) = mpsc::unbounded_channel();
|
||||
let display = Arc::new(DisplayWrapper(Mutex::new(display), display_handle.clone()));
|
||||
|
||||
let (global_destroy_queue_in, global_destroy_queue) = mpsc::channel(8);
|
||||
GLOBAL_DESTROY_QUEUE.set(global_destroy_queue_in).unwrap();
|
||||
#[cfg(feature = "xwayland_rootless")]
|
||||
let xwayland_state = XWaylandState::create(&display_handle)?;
|
||||
let wayland_state = WaylandState::new(display_handle, &renderer, dmabuf_tx);
|
||||
let output = wayland_state.lock().output.clone();
|
||||
|
||||
let join_handle =
|
||||
Wayland::start_loop(display.clone(), state.clone(), global_destroy_queue)?;
|
||||
let socket = ListeningSocket::bind_auto("wayland", 0..33)?;
|
||||
let socket_name = socket
|
||||
.socket_name()
|
||||
.and_then(OsStr::to_str)
|
||||
.map(ToString::to_string);
|
||||
if let Some(socket_name) = &socket_name {
|
||||
let _ = WAYLAND_DISPLAY.set(socket_name.clone());
|
||||
}
|
||||
#[cfg(feature = "xwayland_rootful")]
|
||||
let x_display = start_xwayland(socket.as_raw_fd())?;
|
||||
info!(socket_name, "Wayland active");
|
||||
|
||||
let join_handle = Wayland::start_loop(display.clone(), socket, wayland_state)?;
|
||||
Ok(Wayland {
|
||||
log,
|
||||
display,
|
||||
socket_name,
|
||||
join_handle,
|
||||
renderer,
|
||||
state,
|
||||
output,
|
||||
dmabuf_rx,
|
||||
#[cfg(feature = "xwayland_rootful")]
|
||||
x_lock: x_display,
|
||||
#[cfg(feature = "xwayland_rootless")]
|
||||
xwayland_state,
|
||||
})
|
||||
}
|
||||
|
||||
fn start_loop(
|
||||
display: Arc<Mutex<Display<WaylandState>>>,
|
||||
display: Arc<DisplayWrapper>,
|
||||
socket: ListeningSocket,
|
||||
state: Arc<Mutex<WaylandState>>,
|
||||
mut global_destroy_queue: mpsc::Receiver<GlobalId>,
|
||||
) -> Result<JoinHandle<Result<()>>> {
|
||||
let socket = ListeningSocket::bind_auto("wayland", 0..33)?;
|
||||
if let Some(socket_name) = socket.socket_name() {
|
||||
println!("Wayland compositor {:?} active", socket_name);
|
||||
}
|
||||
|
||||
let listen_async =
|
||||
AsyncUnixListener::from_std(unsafe { UnixListener::from_raw_fd(socket.as_raw_fd()) })?;
|
||||
|
||||
let dispatch_poll_fd: RawFd = display.lock().backend().poll_fd();
|
||||
let dispatch_poll_fd = display.poll_fd()?;
|
||||
let dispatch_poll_listener = AsyncFd::new(dispatch_poll_fd)?;
|
||||
|
||||
let dh1 = display.lock().handle();
|
||||
let dh1 = display.handle();
|
||||
let mut dh2 = dh1.clone();
|
||||
|
||||
Ok(tokio::task::spawn(async move {
|
||||
Ok(task::new(|| "wayland loop", async move {
|
||||
let _socket = socket; // Keep the socket alive
|
||||
loop {
|
||||
tokio::select! {
|
||||
e = global_destroy_queue.recv() => { // New global to destroy
|
||||
dh1.remove_global::<WaylandState>(e.unwrap());
|
||||
}
|
||||
acc = listen_async.accept() => { // New client connected
|
||||
let (stream, _) = acc?;
|
||||
let client = dh2.insert_client(stream.into_std()?, Arc::new(ClientState))?;
|
||||
|
||||
state.lock().new_client(client.id(), &dh2);
|
||||
let client_state = Arc::new(ClientState {
|
||||
id: OnceCell::new(),
|
||||
compositor_state: Default::default(),
|
||||
display: Arc::downgrade(&display),
|
||||
seat: SeatData::new(&dh1)
|
||||
});
|
||||
let client = dh2.insert_client(stream.into_std()?, client_state.clone())?;
|
||||
let _ = client_state.seat.client.set(client.id());
|
||||
}
|
||||
e = dispatch_poll_listener.readable() => { // Dispatch
|
||||
let mut guard = e?;
|
||||
let mut display = display.lock();
|
||||
display.dispatch_clients(&mut *state.lock())?;
|
||||
display.flush_clients()?;
|
||||
debug_span!("Dispatch wayland event").in_scope(|| -> Result<(), color_eyre::Report> {
|
||||
display.dispatch_clients(&mut state.lock())?;
|
||||
display.flush_clients(None);
|
||||
Ok(())
|
||||
})?;
|
||||
guard.clear_ready();
|
||||
}
|
||||
}
|
||||
}
|
||||
}))
|
||||
})?)
|
||||
}
|
||||
|
||||
pub fn frame(&mut self, sk: &StereoKit) {
|
||||
let time_ms = (sk.time_getf() * 1000.) as u32;
|
||||
|
||||
#[instrument(level = "debug", name = "Wayland frame", skip(self, sk))]
|
||||
pub fn update(&mut self, sk: &impl StereoKitDraw) {
|
||||
while let Ok((dmabuf, notifier)) = self.dmabuf_rx.try_recv() {
|
||||
if self.renderer.import_dmabuf(&dmabuf, None).is_err() {
|
||||
if let Some(notifier) = notifier {
|
||||
notifier.failed();
|
||||
}
|
||||
}
|
||||
}
|
||||
for core_surface in CORE_SURFACES.get_valid_contents() {
|
||||
let client_id = core_surface.wl_surface().client_id().unwrap();
|
||||
let seat_data = self.state.lock().seats.get(&client_id).unwrap().clone();
|
||||
core_surface.process(
|
||||
sk,
|
||||
&mut self.renderer,
|
||||
time_ms,
|
||||
&self.log,
|
||||
|data| {
|
||||
PanelItem::on_mapped(&core_surface, data, seat_data);
|
||||
},
|
||||
|data| {
|
||||
PanelItem::if_mapped(&core_surface, data);
|
||||
},
|
||||
);
|
||||
core_surface.process(sk, &mut self.renderer);
|
||||
}
|
||||
|
||||
self.display.lock().flush_clients().unwrap();
|
||||
self.display.flush_clients(None);
|
||||
}
|
||||
|
||||
pub fn frame_event(&self, sk: &impl StereoKitDraw) {
|
||||
for core_surface in CORE_SURFACES.get_valid_contents() {
|
||||
core_surface.frame(sk, self.output.clone());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn make_context_current(&self) {
|
||||
unsafe {
|
||||
self.renderer.egl_context().make_current().unwrap();
|
||||
let _ = self.renderer.egl_context().make_current();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,506 +0,0 @@
|
||||
use super::{
|
||||
seat::{KeyboardInfo, SeatData},
|
||||
surface::CoreSurface,
|
||||
};
|
||||
use crate::{
|
||||
core::{
|
||||
client::{Client, INTERNAL_CLIENT},
|
||||
registry::Registry,
|
||||
},
|
||||
nodes::{
|
||||
items::{register_item_ui_flex, Item, ItemSpecialization, ItemType, TypeInfo},
|
||||
spatial::Spatial,
|
||||
Node,
|
||||
},
|
||||
};
|
||||
use anyhow::{anyhow, bail, Result};
|
||||
use glam::Mat4;
|
||||
use lazy_static::lazy_static;
|
||||
use mint::Vector2;
|
||||
use nanoid::nanoid;
|
||||
use serde::Deserialize;
|
||||
use smithay::{
|
||||
reexports::wayland_server::protocol::wl_pointer::{Axis, ButtonState},
|
||||
utils::Size,
|
||||
wayland::{compositor::SurfaceData, shell::xdg::XdgToplevelSurfaceData},
|
||||
};
|
||||
use stardust_xr::schemas::flex::{deserialize, serialize};
|
||||
use std::sync::{Arc, Weak};
|
||||
use xkbcommon::xkb::{self, ffi::XKB_KEYMAP_FORMAT_TEXT_V1, Keymap};
|
||||
|
||||
lazy_static! {
|
||||
static ref ITEM_TYPE_INFO_PANEL: TypeInfo = TypeInfo {
|
||||
type_name: "panel",
|
||||
aliased_local_signals: vec![
|
||||
"applySurfaceMaterial",
|
||||
"applyCursorMaterial",
|
||||
"pointerDeactivate",
|
||||
"pointerScroll",
|
||||
"pointerButton",
|
||||
"pointerMotion",
|
||||
"keyboardSetActive",
|
||||
"keyboardSetKeyState",
|
||||
"keyboardSetModifiers",
|
||||
"resize",
|
||||
"close",
|
||||
],
|
||||
aliased_local_methods: vec![],
|
||||
aliased_remote_signals: vec!["resize", "setCursor",],
|
||||
aliased_remote_methods: vec![],
|
||||
ui: Default::default(),
|
||||
items: Registry::new(),
|
||||
acceptors: Registry::new(),
|
||||
};
|
||||
}
|
||||
|
||||
pub struct PanelItem {
|
||||
node: Weak<Node>,
|
||||
core_surface: Weak<CoreSurface>,
|
||||
seat_data: SeatData,
|
||||
}
|
||||
impl PanelItem {
|
||||
pub fn create(core_surface: &Arc<CoreSurface>, seat_data: SeatData) -> Arc<Node> {
|
||||
let node = Arc::new(Node::create(
|
||||
&INTERNAL_CLIENT,
|
||||
"/item/panel/item",
|
||||
&nanoid!(),
|
||||
true,
|
||||
));
|
||||
Spatial::add_to(&node, None, Mat4::IDENTITY).unwrap();
|
||||
|
||||
let specialization = ItemType::Panel(PanelItem {
|
||||
node: Arc::downgrade(&node),
|
||||
core_surface: Arc::downgrade(core_surface),
|
||||
seat_data,
|
||||
});
|
||||
let item = Item::add_to(&node, &ITEM_TYPE_INFO_PANEL, specialization);
|
||||
if let ItemType::Panel(panel) = &item.specialization {
|
||||
let _ = panel.seat_data.panel_item.set(Arc::downgrade(&item));
|
||||
}
|
||||
|
||||
node.add_local_signal(
|
||||
"applySurfaceMaterial",
|
||||
PanelItem::apply_surface_material_flex,
|
||||
);
|
||||
node.add_local_signal("applyCursorMaterial", PanelItem::apply_cursor_material_flex);
|
||||
node.add_local_signal("pointerDeactivate", PanelItem::pointer_deactivate_flex);
|
||||
node.add_local_signal("pointerScroll", PanelItem::pointer_scroll_flex);
|
||||
node.add_local_signal("pointerButton", PanelItem::pointer_button_flex);
|
||||
node.add_local_signal("pointerMotion", PanelItem::pointer_motion_flex);
|
||||
node.add_local_signal(
|
||||
"keyboardActivateString",
|
||||
PanelItem::keyboard_activate_string_flex,
|
||||
);
|
||||
node.add_local_signal(
|
||||
"keyboardActivateNames",
|
||||
PanelItem::keyboard_activate_names_flex,
|
||||
);
|
||||
node.add_local_signal("keyboardDeactivate", PanelItem::keyboard_deactivate_flex);
|
||||
node.add_local_signal("keyboardKeyState", PanelItem::keyboard_key_state_flex);
|
||||
node.add_local_signal("resize", PanelItem::resize_flex);
|
||||
node
|
||||
}
|
||||
|
||||
pub fn from_node(node: &Node) -> &PanelItem {
|
||||
match &node.item.get().unwrap().specialization {
|
||||
ItemType::Panel(panel_item) => panel_item,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_surface_material_flex(
|
||||
node: &Node,
|
||||
calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct SurfaceMaterialInfo<'a> {
|
||||
model_path: &'a str,
|
||||
idx: u32,
|
||||
}
|
||||
let info: SurfaceMaterialInfo = deserialize(data)?;
|
||||
let model_node = calling_client
|
||||
.scenegraph
|
||||
.get_node(info.model_path)
|
||||
.ok_or_else(|| anyhow!("Model node not found"))?;
|
||||
let model = model_node
|
||||
.model
|
||||
.get()
|
||||
.ok_or_else(|| anyhow!("Node is not a model"))?;
|
||||
|
||||
if let ItemType::Panel(panel_item) = &node.item.get().unwrap().specialization {
|
||||
if let Some(core_surface) = panel_item.core_surface.upgrade() {
|
||||
core_surface.apply_material(model.clone(), info.idx);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn apply_cursor_material_flex(
|
||||
node: &Node,
|
||||
calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct SurfaceMaterialInfo<'a> {
|
||||
model_path: &'a str,
|
||||
idx: u32,
|
||||
}
|
||||
let info: SurfaceMaterialInfo = deserialize(data)?;
|
||||
let model_node = calling_client
|
||||
.scenegraph
|
||||
.get_node(info.model_path)
|
||||
.ok_or_else(|| anyhow!("Model node not found"))?;
|
||||
let model = model_node
|
||||
.model
|
||||
.get()
|
||||
.ok_or_else(|| anyhow!("Node is not a model"))?;
|
||||
|
||||
if let ItemType::Panel(panel_item) = &node.item.get().unwrap().specialization {
|
||||
if let Some(cursor) = &*panel_item.seat_data.cursor.lock() {
|
||||
if let Some(core_surface) = cursor.lock().core_surface.upgrade() {
|
||||
core_surface.apply_material(model.clone(), info.idx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn on_mapped(
|
||||
core_surface: &Arc<CoreSurface>,
|
||||
surface_data: &SurfaceData,
|
||||
seat_data: SeatData,
|
||||
) {
|
||||
if surface_data
|
||||
.data_map
|
||||
.get::<XdgToplevelSurfaceData>()
|
||||
.is_some()
|
||||
{
|
||||
surface_data
|
||||
.data_map
|
||||
.insert_if_missing_threadsafe(|| PanelItem::create(core_surface, seat_data));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn if_mapped(_core_surface: &Arc<CoreSurface>, surface_data: &SurfaceData) {
|
||||
if let Some(panel_node) = surface_data.data_map.get::<Arc<Node>>() {
|
||||
let panel_item = PanelItem::from_node(panel_node);
|
||||
|
||||
// core_surface.with_data(|core_surface_data| {
|
||||
// panel_item.resize();
|
||||
// });
|
||||
|
||||
panel_item.set_cursor();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resize(&self) {
|
||||
self.core_surface.upgrade().unwrap().with_data(|data| {
|
||||
let _ = self
|
||||
.node
|
||||
.upgrade()
|
||||
.unwrap()
|
||||
.send_remote_signal("resize", &serialize(data.size).unwrap());
|
||||
});
|
||||
}
|
||||
|
||||
pub fn set_cursor(&self) {
|
||||
let mut cursor_changed = self.seat_data.cursor_changed.lock();
|
||||
if !*cursor_changed {
|
||||
return;
|
||||
}
|
||||
let mut data = serialize(()).unwrap();
|
||||
|
||||
if let Some(cursor) = &*self.seat_data.cursor.lock() {
|
||||
let cursor = cursor.lock();
|
||||
if let Some(core_surface) = cursor.core_surface.upgrade() {
|
||||
if let Some(mapped_data) = &*core_surface.mapped_data.lock() {
|
||||
data = serialize((mapped_data.size, cursor.hotspot)).unwrap();
|
||||
} else {
|
||||
return;
|
||||
};
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let _ = self
|
||||
.node
|
||||
.upgrade()
|
||||
.unwrap()
|
||||
.send_remote_signal("setCursor", &data);
|
||||
*cursor_changed = false;
|
||||
}
|
||||
|
||||
fn pointer_deactivate_flex(
|
||||
node: &Node,
|
||||
_calling_client: Arc<Client>,
|
||||
_data: &[u8],
|
||||
) -> Result<()> {
|
||||
let panel_item = PanelItem::from_node(node);
|
||||
if *panel_item.seat_data.pointer_active.lock() {
|
||||
if let Some(core_surface) = panel_item.core_surface.upgrade() {
|
||||
if let Some(pointer) = panel_item.seat_data.pointer() {
|
||||
pointer.leave(0, &core_surface.wl_surface());
|
||||
*panel_item.seat_data.pointer_active.lock() = false;
|
||||
pointer.frame();
|
||||
core_surface.flush_clients();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn pointer_motion_flex(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
if let ItemType::Panel(panel_item) = &node.item.get().unwrap().specialization {
|
||||
if let Some(pointer) = panel_item.seat_data.pointer() {
|
||||
if let Some(core_surface) = panel_item.core_surface.upgrade() {
|
||||
if let Some(size) = core_surface.with_data(|data| data.size) {
|
||||
let mut position: Vector2<f64> = deserialize(data)?;
|
||||
position.x = position.x.clamp(0.0, size.x as f64);
|
||||
position.y = position.y.clamp(0.0, size.y as f64);
|
||||
let mut pointer_active = panel_item.seat_data.pointer_active.lock();
|
||||
if *pointer_active {
|
||||
pointer.motion(0, position.x, position.y);
|
||||
} else {
|
||||
pointer.enter(0, &core_surface.wl_surface(), position.x, position.y);
|
||||
*pointer_active = true;
|
||||
}
|
||||
pointer.frame();
|
||||
core_surface.flush_clients();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn pointer_button_flex(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
if let ItemType::Panel(panel_item) = &node.item.get().unwrap().specialization {
|
||||
if let Some(pointer) = panel_item.seat_data.pointer() {
|
||||
if *panel_item.seat_data.pointer_active.lock() {
|
||||
if let Some(core_surface) = panel_item.core_surface.upgrade() {
|
||||
let (button, state): (u32, u32) = deserialize(data)?;
|
||||
pointer.button(
|
||||
0,
|
||||
0,
|
||||
button,
|
||||
match state {
|
||||
0 => ButtonState::Released,
|
||||
1 => ButtonState::Pressed,
|
||||
_ => {
|
||||
bail!("Button state is out of bounds")
|
||||
}
|
||||
},
|
||||
);
|
||||
pointer.frame();
|
||||
core_surface.flush_clients();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn pointer_scroll_flex(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct PointerScrollArgs {
|
||||
axis_continuous: Vector2<f32>,
|
||||
axis_discrete: Option<Vector2<f32>>,
|
||||
}
|
||||
let args: PointerScrollArgs = deserialize(data)?;
|
||||
if let ItemType::Panel(panel_item) = &node.item.get().unwrap().specialization {
|
||||
if let Some(pointer) = panel_item.seat_data.pointer() {
|
||||
if *panel_item.seat_data.pointer_active.lock() {
|
||||
if let Some(core_surface) = panel_item.core_surface.upgrade() {
|
||||
let flex = flexbuffers::Reader::get_root(data)?;
|
||||
if flex.flexbuffer_type().is_null() {
|
||||
pointer.axis_stop(0, Axis::HorizontalScroll);
|
||||
pointer.axis_stop(0, Axis::VerticalScroll);
|
||||
} else {
|
||||
pointer.axis(0, Axis::HorizontalScroll, args.axis_continuous.x as f64);
|
||||
pointer.axis(0, Axis::VerticalScroll, args.axis_continuous.y as f64);
|
||||
if let Some(axis_discrete_vec) = args.axis_discrete {
|
||||
pointer.axis_discrete(
|
||||
Axis::HorizontalScroll,
|
||||
axis_discrete_vec.x as i32,
|
||||
);
|
||||
pointer.axis_discrete(
|
||||
Axis::VerticalScroll,
|
||||
axis_discrete_vec.y as i32,
|
||||
);
|
||||
}
|
||||
}
|
||||
pointer.frame();
|
||||
core_surface.flush_clients();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn keyboard_activate_string_flex(
|
||||
node: &Node,
|
||||
_calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
) -> Result<()> {
|
||||
let context = xkb::Context::new(0);
|
||||
let keymap =
|
||||
Keymap::new_from_string(&context, deserialize(data)?, XKB_KEYMAP_FORMAT_TEXT_V1, 0)
|
||||
.ok_or_else(|| anyhow!("Keymap is not valid"))?;
|
||||
|
||||
PanelItem::keyboard_activate_flex(node, &keymap)
|
||||
}
|
||||
|
||||
fn keyboard_activate_names_flex(
|
||||
node: &Node,
|
||||
_calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct Names<'a> {
|
||||
rules: &'a str,
|
||||
model: &'a str,
|
||||
layout: &'a str,
|
||||
variant: &'a str,
|
||||
options: Option<String>,
|
||||
}
|
||||
let names: Names = deserialize(data)?;
|
||||
let context = xkb::Context::new(0);
|
||||
let keymap = Keymap::new_from_names(
|
||||
&context,
|
||||
names.rules,
|
||||
names.model,
|
||||
names.layout,
|
||||
names.variant,
|
||||
names.options,
|
||||
XKB_KEYMAP_FORMAT_TEXT_V1,
|
||||
)
|
||||
.ok_or_else(|| anyhow!("Keymap is not valid"))?;
|
||||
|
||||
PanelItem::keyboard_activate_flex(node, &keymap)
|
||||
}
|
||||
|
||||
fn keyboard_activate_flex(node: &Node, keymap: &Keymap) -> Result<()> {
|
||||
if let ItemType::Panel(panel_item) = &node.item.get().unwrap().specialization {
|
||||
if let Some(keyboard) = panel_item.seat_data.keyboard() {
|
||||
if let Some(core_surface) = panel_item.core_surface.upgrade() {
|
||||
let mut keyboard_info = panel_item.seat_data.keyboard_info.lock();
|
||||
if keyboard_info.is_none() {
|
||||
keyboard.enter(0, &core_surface.wl_surface(), vec![]);
|
||||
keyboard.repeat_info(0, 0);
|
||||
}
|
||||
keyboard_info.replace(KeyboardInfo::new(keymap));
|
||||
keyboard_info.as_ref().unwrap().keymap.send(keyboard)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn keyboard_deactivate_flex(
|
||||
node: &Node,
|
||||
_calling_client: Arc<Client>,
|
||||
_data: &[u8],
|
||||
) -> Result<()> {
|
||||
if let ItemType::Panel(panel_item) = &node.item.get().unwrap().specialization {
|
||||
if let Some(keyboard) = panel_item.seat_data.keyboard() {
|
||||
if let Some(core_surface) = panel_item.core_surface.upgrade() {
|
||||
let mut keyboard_info = panel_item.seat_data.keyboard_info.lock();
|
||||
if keyboard_info.is_some() {
|
||||
keyboard.leave(0, &core_surface.wl_surface());
|
||||
*keyboard_info = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn keyboard_key_state_flex(
|
||||
node: &Node,
|
||||
_calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
) -> Result<()> {
|
||||
if let ItemType::Panel(panel_item) = &node.item.get().unwrap().specialization {
|
||||
if let Some(keyboard) = panel_item.seat_data.keyboard() {
|
||||
let mut keyboard_info = panel_item.seat_data.keyboard_info.lock();
|
||||
if let Some(keyboard_info) = &mut *keyboard_info {
|
||||
let (key, state): (u32, u32) = deserialize(data)?;
|
||||
keyboard_info.process(key, state, keyboard)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn resize_flex(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
if let ItemType::Panel(panel_item) = &node.item.get().unwrap().specialization {
|
||||
if let Some(core_surface) = panel_item.core_surface.upgrade() {
|
||||
let size: Vector2<u32> = deserialize(data)?;
|
||||
|
||||
let toplevel_surface = core_surface
|
||||
.wayland_state()
|
||||
.lock()
|
||||
.xdg_shell_state
|
||||
.toplevel_surfaces(|surfaces| {
|
||||
surfaces
|
||||
.iter()
|
||||
.find(|surf| surf.wl_surface().clone() == core_surface.wl_surface())
|
||||
.cloned()
|
||||
});
|
||||
|
||||
if let Some(toplevel_surface) = toplevel_surface {
|
||||
let mut size_set = false;
|
||||
toplevel_surface.with_pending_state(|state| {
|
||||
state.size = Some(Size::default());
|
||||
state.size.as_mut().unwrap().w = size.x as i32;
|
||||
state.size.as_mut().unwrap().h = size.y as i32;
|
||||
size_set = true;
|
||||
});
|
||||
if size_set {
|
||||
toplevel_surface.send_configure();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl ItemSpecialization for PanelItem {
|
||||
fn serialize_start_data(&self, id: &str) -> Vec<u8> {
|
||||
// Panel size
|
||||
let panel_size = self
|
||||
.core_surface
|
||||
.upgrade()
|
||||
.unwrap()
|
||||
.with_data(|data| data.size);
|
||||
|
||||
let cursor_lock = (*self.seat_data.cursor.lock()).clone();
|
||||
let cursor_size = cursor_lock
|
||||
.clone()
|
||||
.and_then(|cursor| cursor.lock().core_surface.upgrade())
|
||||
.and_then(|surf| surf.with_data(|data| data.size));
|
||||
let cursor_hotspot = cursor_lock.map(|cursor| cursor.lock().hotspot);
|
||||
|
||||
serialize((id, (panel_size, cursor_size.zip(cursor_hotspot)))).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register_panel_item_ui_flex(
|
||||
_node: &Node,
|
||||
calling_client: Arc<Client>,
|
||||
_data: &[u8],
|
||||
) -> Result<()> {
|
||||
register_item_ui_flex(calling_client, &ITEM_TYPE_INFO_PANEL)
|
||||
}
|
||||
@@ -1,59 +1,81 @@
|
||||
use super::{state::WaylandState, surface::CoreSurface, GLOBAL_DESTROY_QUEUE};
|
||||
use crate::nodes::items::Item;
|
||||
use anyhow::Result;
|
||||
use super::{
|
||||
state::{ClientState, WaylandState},
|
||||
surface::CoreSurface,
|
||||
SERIAL_COUNTER,
|
||||
};
|
||||
use crate::{
|
||||
core::task,
|
||||
nodes::items::panel::{Backend, Geometry, PanelItem},
|
||||
};
|
||||
use color_eyre::eyre::{bail, eyre, Result};
|
||||
use mint::Vector2;
|
||||
use nanoid::nanoid;
|
||||
use once_cell::sync::OnceCell;
|
||||
use parking_lot::Mutex;
|
||||
use rand::{seq::IteratorRandom, thread_rng};
|
||||
use rustc_hash::{FxHashMap, FxHashSet};
|
||||
use smithay::{
|
||||
input::keyboard::{KeymapFile, ModifiersState},
|
||||
reexports::wayland_server::{
|
||||
backend::{ClientId, GlobalId},
|
||||
delegate_dispatch, delegate_global_dispatch,
|
||||
backend::{ClientId, GlobalId, ObjectId},
|
||||
protocol::{
|
||||
wl_keyboard::{self, KeyState, WlKeyboard},
|
||||
wl_pointer::{self, WlPointer},
|
||||
wl_pointer::{self, Axis, ButtonState, WlPointer},
|
||||
wl_seat::{self, Capability, WlSeat, EVT_NAME_SINCE},
|
||||
wl_surface::WlSurface,
|
||||
wl_touch::{self, WlTouch},
|
||||
},
|
||||
Client, DataInit, Dispatch, DisplayHandle, GlobalDispatch, New, Resource,
|
||||
Client, DataInit, Dispatch, DisplayHandle, GlobalDispatch, New, Resource, Weak as WlWeak,
|
||||
},
|
||||
wayland::compositor,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
use std::{ops::Deref, sync::Weak};
|
||||
use xkbcommon::xkb::{self, Keymap};
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tokio::sync::watch;
|
||||
use tracing::{debug, warn};
|
||||
use xkbcommon::xkb::{self, ffi::XKB_KEYMAP_FORMAT_TEXT_V1, Keycode, Keymap};
|
||||
|
||||
pub struct Cursor {
|
||||
pub core_surface: Weak<CoreSurface>,
|
||||
pub hotspot: Vector2<i32>,
|
||||
pub fn handle_cursor<B: Backend>(
|
||||
panel_item: &Arc<PanelItem<B>>,
|
||||
mut cursor: watch::Receiver<Option<CursorInfo>>,
|
||||
) {
|
||||
let panel_item_weak = Arc::downgrade(panel_item);
|
||||
let _ = task::new(|| "cursor handler", async move {
|
||||
while cursor.changed().await.is_ok() {
|
||||
let Some(panel_item) = panel_item_weak.upgrade() else {continue};
|
||||
let cursor_info = cursor.borrow();
|
||||
panel_item.set_cursor(cursor_info.as_ref().and_then(CursorInfo::cursor_data));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub struct KeyboardInfo {
|
||||
pub keymap: KeymapFile,
|
||||
pub state: xkb::State,
|
||||
pub mods: ModifiersState,
|
||||
keymap_string: String,
|
||||
keymap: KeymapFile,
|
||||
state: xkb::State,
|
||||
mods: ModifiersState,
|
||||
keys: FxHashSet<u32>,
|
||||
}
|
||||
impl KeyboardInfo {
|
||||
pub fn new(keymap: &Keymap) -> Self {
|
||||
pub fn new(keymap_string: String, keymap: &Keymap) -> Self {
|
||||
KeyboardInfo {
|
||||
keymap_string,
|
||||
state: xkb::State::new(keymap),
|
||||
keymap: KeymapFile::new(keymap, None),
|
||||
keymap: KeymapFile::new(keymap),
|
||||
mods: ModifiersState::default(),
|
||||
keys: FxHashSet::default(),
|
||||
}
|
||||
}
|
||||
pub fn process(&mut self, key: u32, state: u32, keyboard: &WlKeyboard) -> Result<()> {
|
||||
let wl_key_state = match state {
|
||||
0 => KeyState::Released,
|
||||
1 => KeyState::Pressed,
|
||||
_ => anyhow::bail!("Invalid key state!"),
|
||||
pub fn process(&mut self, key: u32, pressed: bool, keyboard: &WlKeyboard) -> Result<usize> {
|
||||
let xkb_key_state = if pressed {
|
||||
xkb::KeyDirection::Down
|
||||
} else {
|
||||
xkb::KeyDirection::Up
|
||||
};
|
||||
let xkb_key_state = match state {
|
||||
0 => xkb::KeyDirection::Up,
|
||||
1 => xkb::KeyDirection::Down,
|
||||
_ => anyhow::bail!("Invalid key state!"),
|
||||
};
|
||||
let state_components = self.state.update_key(key + 8, xkb_key_state);
|
||||
let state_components = self.state.update_key(Keycode::new(key + 8), xkb_key_state);
|
||||
if state_components != 0 {
|
||||
self.mods.update_with(&self.state);
|
||||
keyboard.modifiers(
|
||||
@@ -64,85 +86,400 @@ impl KeyboardInfo {
|
||||
0,
|
||||
);
|
||||
}
|
||||
keyboard.key(0, 0, key, wl_key_state);
|
||||
Ok(())
|
||||
// if pressed {
|
||||
// println!("Key {key} is being pressed with {state_components} modifiers");
|
||||
// } else {
|
||||
// println!("Key {key} is being released with {state_components} modifiers");
|
||||
// }
|
||||
|
||||
let wl_key_state = if pressed {
|
||||
KeyState::Pressed
|
||||
} else {
|
||||
KeyState::Released
|
||||
};
|
||||
keyboard.key(SERIAL_COUNTER.inc(), 0, key, wl_key_state);
|
||||
match wl_key_state {
|
||||
KeyState::Pressed => {
|
||||
self.keys.insert(key);
|
||||
}
|
||||
KeyState::Released => {
|
||||
self.keys.remove(&key);
|
||||
}
|
||||
_ => unimplemented!(),
|
||||
}
|
||||
Ok(self.keys.len())
|
||||
}
|
||||
}
|
||||
unsafe impl Send for KeyboardInfo {}
|
||||
|
||||
pub struct SeatDelegate;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct SeatData(Arc<SeatDataInner>);
|
||||
impl SeatData {
|
||||
pub fn new(dh: &DisplayHandle, client: ClientId) -> Self {
|
||||
let seat_data = SeatData(Arc::new(SeatDataInner {
|
||||
client,
|
||||
global_id: OnceCell::new(),
|
||||
panel_item: OnceCell::new(),
|
||||
cursor: Mutex::new(None),
|
||||
cursor_changed: Mutex::new(false),
|
||||
pointer: OnceCell::new(),
|
||||
pointer_active: Mutex::new(false),
|
||||
keyboard: OnceCell::new(),
|
||||
keyboard_info: Mutex::new(None),
|
||||
touch: OnceCell::new(),
|
||||
}));
|
||||
|
||||
seat_data
|
||||
.global_id
|
||||
.set(dh.create_global::<WaylandState, _, _>(7, seat_data.clone()))
|
||||
.unwrap();
|
||||
|
||||
seat_data
|
||||
}
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum PointerEvent {
|
||||
Motion(Vector2<f32>),
|
||||
Button {
|
||||
button: u32,
|
||||
state: u32,
|
||||
},
|
||||
Scroll {
|
||||
axis_continuous: Option<Vector2<f32>>,
|
||||
axis_discrete: Option<Vector2<f32>>,
|
||||
},
|
||||
}
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum KeyboardEvent {
|
||||
Keymap,
|
||||
Key { key: u32, state: bool },
|
||||
}
|
||||
impl Deref for SeatData {
|
||||
type Target = SeatDataInner;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
const POINTER_EVENT_TIMEOUT: Duration = Duration::from_millis(50);
|
||||
struct SurfaceInfo {
|
||||
wl_surface: WlWeak<WlSurface>,
|
||||
cursor_sender: watch::Sender<Option<CursorInfo>>,
|
||||
pointer_queue: VecDeque<PointerEvent>,
|
||||
pointer_latest_event: Instant,
|
||||
keyboard_queue: VecDeque<KeyboardEvent>,
|
||||
keyboard_info: Option<KeyboardInfo>,
|
||||
}
|
||||
impl SurfaceInfo {
|
||||
fn new(wl_surface: &WlSurface, cursor_sender: watch::Sender<Option<CursorInfo>>) -> Self {
|
||||
SurfaceInfo {
|
||||
wl_surface: wl_surface.downgrade(),
|
||||
cursor_sender,
|
||||
pointer_queue: VecDeque::new(),
|
||||
pointer_latest_event: Instant::now(),
|
||||
keyboard_queue: VecDeque::new(),
|
||||
keyboard_info: None,
|
||||
}
|
||||
}
|
||||
fn flush(&self) {
|
||||
if let Some(client) = self.wl_surface.upgrade().ok().and_then(|s| s.client()) {
|
||||
if let Some(client_data) = client.get_data::<ClientState>() {
|
||||
client_data.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
fn handle_pointer_events(&mut self, pointer: &WlPointer, mut locked: bool) -> bool {
|
||||
let Ok(focus) = self.wl_surface.upgrade() else { return false; };
|
||||
let Some(core_surface) = CoreSurface::from_wl_surface(&focus) else { return false; };
|
||||
let Some(focus_size) = core_surface.size() else { return false; };
|
||||
|
||||
if !self.pointer_queue.is_empty() {
|
||||
self.pointer_latest_event = Instant::now();
|
||||
}
|
||||
while let Some(event) = self.pointer_queue.pop_front() {
|
||||
match (locked, event) {
|
||||
(false, PointerEvent::Motion(pos)) => {
|
||||
pointer.enter(
|
||||
SERIAL_COUNTER.inc(),
|
||||
&focus,
|
||||
(pos.x as f64).clamp(0.0, focus_size.x as f64),
|
||||
(pos.y as f64).clamp(0.0, focus_size.y as f64),
|
||||
);
|
||||
locked = true;
|
||||
}
|
||||
(true, PointerEvent::Motion(pos)) => {
|
||||
pointer.motion(
|
||||
0,
|
||||
(pos.x as f64).clamp(0.0, focus_size.x as f64),
|
||||
(pos.y as f64).clamp(0.0, focus_size.y as f64),
|
||||
);
|
||||
if pointer.version() >= wl_pointer::EVT_FRAME_SINCE {
|
||||
pointer.frame();
|
||||
}
|
||||
}
|
||||
(true, PointerEvent::Button { button, state }) => {
|
||||
pointer.button(
|
||||
0,
|
||||
0,
|
||||
button,
|
||||
match state {
|
||||
0 => ButtonState::Released,
|
||||
1 => ButtonState::Pressed,
|
||||
_ => continue,
|
||||
},
|
||||
);
|
||||
if pointer.version() >= wl_pointer::EVT_FRAME_SINCE {
|
||||
pointer.frame();
|
||||
}
|
||||
}
|
||||
(
|
||||
true,
|
||||
PointerEvent::Scroll {
|
||||
axis_continuous,
|
||||
axis_discrete,
|
||||
},
|
||||
) => {
|
||||
if let Some(axis_continuous) = axis_continuous {
|
||||
pointer.axis(0, Axis::HorizontalScroll, axis_continuous.x as f64);
|
||||
pointer.axis(0, Axis::VerticalScroll, -axis_continuous.y as f64);
|
||||
}
|
||||
if pointer.version() >= wl_pointer::EVT_AXIS_DISCRETE_SINCE {
|
||||
if let Some(axis_discrete) = axis_discrete {
|
||||
pointer.axis_discrete(Axis::HorizontalScroll, axis_discrete.x as i32);
|
||||
pointer.axis_discrete(Axis::VerticalScroll, -axis_discrete.y as i32);
|
||||
}
|
||||
}
|
||||
if pointer.version() >= wl_pointer::EVT_AXIS_STOP_SINCE
|
||||
&& axis_discrete.is_none()
|
||||
&& axis_continuous.is_none()
|
||||
{
|
||||
pointer.axis_stop(0, Axis::HorizontalScroll);
|
||||
pointer.axis_stop(0, Axis::VerticalScroll);
|
||||
}
|
||||
if pointer.version() >= wl_pointer::EVT_FRAME_SINCE {
|
||||
pointer.frame();
|
||||
}
|
||||
}
|
||||
(locked, event) => {
|
||||
warn!(locked, ?event, "Invalid pointer event!");
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.pointer_latest_event.elapsed() > POINTER_EVENT_TIMEOUT {
|
||||
pointer.leave(SERIAL_COUNTER.inc(), &focus);
|
||||
locked = false;
|
||||
}
|
||||
self.flush();
|
||||
|
||||
locked
|
||||
}
|
||||
fn handle_keyboard_events(&mut self, keyboard: &WlKeyboard, mut locked: bool) -> bool {
|
||||
let Ok(focus) = self.wl_surface.upgrade() else { return false; };
|
||||
let Some(info) = self.keyboard_info.as_mut() else { return true; };
|
||||
|
||||
if !locked {
|
||||
keyboard.enter(0, &focus, vec![]);
|
||||
if keyboard.version() >= wl_keyboard::EVT_REPEAT_INFO_SINCE {
|
||||
keyboard.repeat_info(0, 0);
|
||||
}
|
||||
locked = info.keymap.send(keyboard).is_ok();
|
||||
}
|
||||
while let Some(event) = self.keyboard_queue.pop_front() {
|
||||
debug!(locked, ?event, "Process keyboard event");
|
||||
match (locked, event) {
|
||||
(true, KeyboardEvent::Keymap) => {
|
||||
let _ = info.keymap.send(keyboard);
|
||||
}
|
||||
(true, KeyboardEvent::Key { key, state }) => {
|
||||
if let Ok(key_count) = info.process(key, state, keyboard) {
|
||||
if key_count == 0 {
|
||||
keyboard.leave(SERIAL_COUNTER.inc(), &focus);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
(locked, event) => {
|
||||
warn!(locked, ?event, "Invalid keyboard event!");
|
||||
}
|
||||
}
|
||||
}
|
||||
self.flush();
|
||||
locked
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SeatDataInner {
|
||||
client: ClientId,
|
||||
pub global_id: OnceCell<GlobalId>,
|
||||
pub panel_item: OnceCell<Weak<Item>>,
|
||||
pub cursor: Mutex<Option<Arc<Mutex<Cursor>>>>,
|
||||
pub cursor_changed: Mutex<bool>,
|
||||
pointer: OnceCell<WlPointer>,
|
||||
pub pointer_active: Mutex<bool>,
|
||||
keyboard: OnceCell<WlKeyboard>,
|
||||
pub keyboard_info: Mutex<Option<KeyboardInfo>>,
|
||||
pub struct SeatData {
|
||||
pub client: OnceCell<ClientId>,
|
||||
global_id: OnceCell<GlobalId>,
|
||||
surfaces: Mutex<FxHashMap<ObjectId, SurfaceInfo>>,
|
||||
pointer: OnceCell<(WlPointer, Mutex<ObjectId>)>,
|
||||
keyboard: OnceCell<(WlKeyboard, Mutex<ObjectId>)>,
|
||||
touch: OnceCell<WlTouch>,
|
||||
touches: Mutex<FxHashMap<ObjectId, u32>>,
|
||||
}
|
||||
impl SeatDataInner {
|
||||
pub fn pointer(&self) -> Option<&WlPointer> {
|
||||
self.pointer.get()
|
||||
impl SeatData {
|
||||
pub fn new(dh: &DisplayHandle) -> Arc<Self> {
|
||||
let seat_data = Arc::new(SeatData {
|
||||
client: OnceCell::new(),
|
||||
global_id: OnceCell::new(),
|
||||
surfaces: Mutex::new(FxHashMap::default()),
|
||||
pointer: OnceCell::new(),
|
||||
keyboard: OnceCell::new(),
|
||||
touch: OnceCell::new(),
|
||||
touches: Mutex::new(FxHashMap::default()),
|
||||
});
|
||||
|
||||
let _ = seat_data
|
||||
.global_id
|
||||
.set(dh.create_global::<WaylandState, _, _>(7, seat_data.clone()));
|
||||
|
||||
seat_data
|
||||
}
|
||||
pub fn keyboard(&self) -> Option<&WlKeyboard> {
|
||||
self.keyboard.get()
|
||||
|
||||
pub fn set_keymap(&self, keymap_str: String, surfaces: Vec<WlSurface>) -> Result<()> {
|
||||
let context = xkb::Context::new(0);
|
||||
let keymap =
|
||||
Keymap::new_from_string(&context, keymap_str.clone(), XKB_KEYMAP_FORMAT_TEXT_V1, 0)
|
||||
.ok_or_else(|| eyre!("Keymap is not valid"))?;
|
||||
let mut panels = self.surfaces.lock();
|
||||
let Some((_, focus)) = self.keyboard.get() else {bail!("Could not get keyboard")};
|
||||
for surface in surfaces {
|
||||
let Some(surface_info) = panels.get_mut(&surface.id()) else {continue};
|
||||
if let Some(keyboard_info) = &mut surface_info.keyboard_info {
|
||||
if &keyboard_info.keymap_string == &keymap_str {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
surface_info
|
||||
.keyboard_info
|
||||
.replace(KeyboardInfo::new(keymap_str.clone(), &keymap));
|
||||
|
||||
if *focus.lock() == surface.id() {
|
||||
surface_info.keyboard_queue.push_back(KeyboardEvent::Keymap);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
#[allow(dead_code)]
|
||||
pub fn touch(&self) -> Option<&WlTouch> {
|
||||
self.touch.get()
|
||||
|
||||
pub fn pointer_event(&self, surface: &WlSurface, event: PointerEvent) {
|
||||
let mut surfaces = self.surfaces.lock();
|
||||
let Some(surface_info) = surfaces.get_mut(&surface.id()) else {return};
|
||||
surface_info.pointer_queue.push_back(event);
|
||||
drop(surfaces);
|
||||
self.handle_pointer_events();
|
||||
}
|
||||
}
|
||||
impl Drop for SeatDataInner {
|
||||
fn drop(&mut self) {
|
||||
let id = self.global_id.take().unwrap();
|
||||
tokio::spawn(async move { GLOBAL_DESTROY_QUEUE.get().unwrap().send(id).await });
|
||||
pub fn keyboard_event(&self, surface: &WlSurface, event: KeyboardEvent) {
|
||||
let mut surfaces = self.surfaces.lock();
|
||||
let Some(surface_info) = surfaces.get_mut(&surface.id()) else {return};
|
||||
surface_info.keyboard_queue.push_back(event);
|
||||
drop(surfaces);
|
||||
self.handle_keyboard_events();
|
||||
}
|
||||
|
||||
fn handle_pointer_events(&self) {
|
||||
let mut surfaces = self.surfaces.lock();
|
||||
let Some((pointer, pointer_focus)) = self.pointer.get() else {return};
|
||||
let mut pointer_focus = pointer_focus.lock();
|
||||
|
||||
loop {
|
||||
let locked = !pointer_focus.is_null();
|
||||
// Pick a pointer to focus on if there is none
|
||||
if pointer_focus.is_null() {
|
||||
*pointer_focus = surfaces
|
||||
.iter()
|
||||
.filter(|(_k, v)| !v.pointer_queue.is_empty())
|
||||
.map(|(k, _v)| k)
|
||||
.choose(&mut thread_rng())
|
||||
.cloned()
|
||||
.unwrap_or(ObjectId::null());
|
||||
}
|
||||
if pointer_focus.is_null() {
|
||||
// If there's still none, guess we're done with pointer events for the time being
|
||||
break;
|
||||
}
|
||||
let Some(surface_info) = surfaces.get_mut(&pointer_focus) else {break};
|
||||
if surface_info.handle_pointer_events(pointer, locked) {
|
||||
// We haven't gotten to a point where we can switch the focus
|
||||
break;
|
||||
} else {
|
||||
*pointer_focus = ObjectId::null();
|
||||
}
|
||||
}
|
||||
}
|
||||
fn handle_keyboard_events(&self) {
|
||||
let mut surfaces = self.surfaces.lock();
|
||||
let Some((keyboard, keyboard_focus)) = self.keyboard.get() else {return};
|
||||
let mut keyboard_focus = keyboard_focus.lock();
|
||||
loop {
|
||||
let locked = !keyboard_focus.is_null();
|
||||
// Pick a keyboard to focus on if there is none
|
||||
if keyboard_focus.is_null() {
|
||||
*keyboard_focus = surfaces
|
||||
.iter()
|
||||
.filter(|(_k, v)| v.keyboard_info.is_some())
|
||||
.filter(|(_k, v)| !v.keyboard_queue.is_empty())
|
||||
.map(|(k, _v)| k)
|
||||
.choose(&mut thread_rng())
|
||||
.cloned()
|
||||
.unwrap_or(ObjectId::null());
|
||||
}
|
||||
// If there's still none, guess we're done with keyboard events for the time being
|
||||
let Some(surface_info) = surfaces.get_mut(&keyboard_focus) else {break};
|
||||
if surface_info.handle_keyboard_events(keyboard, locked) {
|
||||
// We haven't gotten to a point where we can switch the focus
|
||||
break;
|
||||
} else {
|
||||
*keyboard_focus = ObjectId::null();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new_surface(&self, surface: &WlSurface) -> watch::Receiver<Option<CursorInfo>> {
|
||||
let (tx, rx) = watch::channel(None);
|
||||
self.surfaces
|
||||
.lock()
|
||||
.insert(surface.id(), SurfaceInfo::new(surface, tx));
|
||||
|
||||
rx
|
||||
}
|
||||
pub fn drop_surface(&self, surface: &WlSurface) {
|
||||
self.surfaces.lock().remove(&surface.id());
|
||||
if let Some((_, pointer_focus)) = self.pointer.get() {
|
||||
let mut pointer_focus = pointer_focus.lock();
|
||||
if *pointer_focus == surface.id() {
|
||||
*pointer_focus = ObjectId::null();
|
||||
}
|
||||
}
|
||||
if let Some((_, keyboard_focus)) = self.keyboard.get() {
|
||||
let mut keyboard_focus = keyboard_focus.lock();
|
||||
if *keyboard_focus == surface.id() {
|
||||
*keyboard_focus = ObjectId::null();
|
||||
}
|
||||
}
|
||||
self.touches.lock().remove(&surface.id());
|
||||
}
|
||||
|
||||
pub fn touch_down(&self, surface: &WlSurface, id: u32, position: Vector2<f32>) {
|
||||
let Some(touch) = self.touch.get() else {return};
|
||||
touch.down(
|
||||
SERIAL_COUNTER.inc(),
|
||||
0,
|
||||
surface,
|
||||
id as i32,
|
||||
position.x as f64,
|
||||
position.y as f64,
|
||||
);
|
||||
self.touches.lock().insert(surface.id(), id);
|
||||
}
|
||||
pub fn touch_move(&self, id: u32, position: Vector2<f32>) {
|
||||
let Some(touch) = self.touch.get() else {return};
|
||||
touch.motion(0, id as i32, position.x as f64, position.y as f64);
|
||||
}
|
||||
pub fn touch_up(&self, id: u32) {
|
||||
let Some(touch) = self.touch.get() else {return};
|
||||
touch.up(SERIAL_COUNTER.inc(), 0, id as i32);
|
||||
let mut touches = self.touches.lock();
|
||||
touches.retain(|_, tid| *tid != id);
|
||||
}
|
||||
pub fn reset_touches(&self) {
|
||||
let Some(touch) = self.touch.get() else {return};
|
||||
for (_, touch_id) in self.touches.lock().drain() {
|
||||
touch.up(SERIAL_COUNTER.inc(), 0, touch_id as i32);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl GlobalDispatch<WlSeat, SeatData, WaylandState> for SeatDelegate {
|
||||
pub struct CursorInfo {
|
||||
pub surface: WlWeak<WlSurface>,
|
||||
pub hotspot_x: i32,
|
||||
pub hotspot_y: i32,
|
||||
}
|
||||
impl CursorInfo {
|
||||
pub fn cursor_data(&self) -> Option<Geometry> {
|
||||
let cursor_size = CoreSurface::from_wl_surface(&self.surface.upgrade().ok()?)?.size()?;
|
||||
Some(Geometry {
|
||||
origin: [self.hotspot_x, self.hotspot_y].into(),
|
||||
size: cursor_size,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl GlobalDispatch<WlSeat, Arc<SeatData>, WaylandState> for WaylandState {
|
||||
fn bind(
|
||||
_state: &mut WaylandState,
|
||||
_handle: &DisplayHandle,
|
||||
_client: &Client,
|
||||
resource: New<WlSeat>,
|
||||
data: &SeatData,
|
||||
data: &Arc<SeatData>,
|
||||
data_init: &mut DataInit<'_, WaylandState>,
|
||||
) {
|
||||
let resource = data_init.init(resource, data.clone());
|
||||
@@ -151,51 +488,53 @@ impl GlobalDispatch<WlSeat, SeatData, WaylandState> for SeatDelegate {
|
||||
resource.name(nanoid!());
|
||||
}
|
||||
|
||||
resource.capabilities(Capability::Pointer | Capability::Keyboard);
|
||||
resource.capabilities(Capability::Pointer | Capability::Keyboard | Capability::Touch);
|
||||
}
|
||||
|
||||
fn can_view(client: Client, data: &SeatData) -> bool {
|
||||
client.id() == data.0.client
|
||||
fn can_view(client: Client, data: &Arc<SeatData>) -> bool {
|
||||
let Some(seat_client) = data.client.get().cloned() else {return false};
|
||||
client.id() == seat_client
|
||||
}
|
||||
}
|
||||
delegate_global_dispatch!(WaylandState: [WlSeat: SeatData] => SeatDelegate);
|
||||
|
||||
impl Dispatch<WlSeat, SeatData, WaylandState> for SeatDelegate {
|
||||
impl Dispatch<WlSeat, Arc<SeatData>, WaylandState> for WaylandState {
|
||||
fn request(
|
||||
_state: &mut WaylandState,
|
||||
_client: &Client,
|
||||
_resource: &WlSeat,
|
||||
request: <WlSeat as Resource>::Request,
|
||||
data: &SeatData,
|
||||
request: wl_seat::Request,
|
||||
data: &Arc<SeatData>,
|
||||
_dh: &DisplayHandle,
|
||||
data_init: &mut DataInit<'_, WaylandState>,
|
||||
) {
|
||||
match request {
|
||||
wl_seat::Request::GetPointer { id } => {
|
||||
let _ = data.0.pointer.set(data_init.init(id, data.clone()));
|
||||
let pointer = data_init.init(id, data.clone());
|
||||
let _ = data.pointer.set((pointer, Mutex::new(ObjectId::null())));
|
||||
}
|
||||
wl_seat::Request::GetKeyboard { id } => {
|
||||
let keyboard = data_init.init(id, data.clone());
|
||||
keyboard.repeat_info(0, 0);
|
||||
let _ = data.0.keyboard.set(keyboard);
|
||||
if keyboard.version() >= wl_keyboard::EVT_REPEAT_INFO_SINCE {
|
||||
keyboard.repeat_info(0, 0);
|
||||
}
|
||||
let _ = data.keyboard.set((keyboard, Mutex::new(ObjectId::null())));
|
||||
}
|
||||
wl_seat::Request::GetTouch { id } => {
|
||||
let _ = data.0.touch.set(data_init.init(id, data.clone()));
|
||||
let _ = data.touch.set(data_init.init(id, data.clone()));
|
||||
}
|
||||
wl_seat::Request::Release => (),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
delegate_dispatch!(WaylandState: [WlSeat: SeatData] => SeatDelegate);
|
||||
|
||||
impl Dispatch<WlPointer, SeatData, WaylandState> for SeatDelegate {
|
||||
impl Dispatch<WlPointer, Arc<SeatData>, WaylandState> for WaylandState {
|
||||
fn request(
|
||||
state: &mut WaylandState,
|
||||
_state: &mut WaylandState,
|
||||
_client: &Client,
|
||||
_resource: &WlPointer,
|
||||
request: <WlPointer as Resource>::Request,
|
||||
seat_data: &SeatData,
|
||||
request: wl_pointer::Request,
|
||||
seat_data: &Arc<SeatData>,
|
||||
dh: &DisplayHandle,
|
||||
_data_init: &mut DataInit<'_, WaylandState>,
|
||||
) {
|
||||
@@ -206,54 +545,39 @@ impl Dispatch<WlPointer, SeatData, WaylandState> for SeatDelegate {
|
||||
hotspot_x,
|
||||
hotspot_y,
|
||||
} => {
|
||||
if !*seat_data.pointer_active.lock() {
|
||||
return;
|
||||
}
|
||||
*seat_data.0.cursor_changed.lock() = true;
|
||||
if let Some(surface) = surface.as_ref() {
|
||||
CoreSurface::add_to(dh.clone(), surface, || (), |_| ());
|
||||
compositor::with_states(surface, |data| {
|
||||
data.data_map.insert_if_missing_threadsafe(|| {
|
||||
CoreSurface::new(
|
||||
&state.weak_ref.upgrade().unwrap(),
|
||||
&state.display,
|
||||
dh.clone(),
|
||||
surface,
|
||||
)
|
||||
});
|
||||
if !data.data_map.insert_if_missing_threadsafe(|| {
|
||||
Arc::new(Mutex::new(Cursor {
|
||||
core_surface: Arc::downgrade(
|
||||
data.data_map.get::<Arc<CoreSurface>>().unwrap(),
|
||||
),
|
||||
hotspot: Vector2::from([hotspot_x, hotspot_y]),
|
||||
}))
|
||||
}) {
|
||||
let mut cursor =
|
||||
data.data_map.get::<Arc<Mutex<Cursor>>>().unwrap().lock();
|
||||
cursor.hotspot = Vector2::from([hotspot_x, hotspot_y]);
|
||||
if let Some(core_surface) = data.data_map.get::<Arc<CoreSurface>>() {
|
||||
core_surface.set_material_offset(1);
|
||||
}
|
||||
})
|
||||
}
|
||||
*seat_data.cursor.lock() = surface.and_then(|surf| {
|
||||
compositor::with_states(&surf, |data| {
|
||||
data.data_map.get::<Arc<Mutex<Cursor>>>().cloned()
|
||||
})
|
||||
|
||||
let Some((_, focus)) = seat_data.pointer.get() else {return};
|
||||
let focus = focus.lock();
|
||||
let surfaces = seat_data.surfaces.lock();
|
||||
let Some(surface_info) = surfaces.get(&focus) else {return};
|
||||
let cursor_info = surface.map(|surface| CursorInfo {
|
||||
surface: surface.downgrade(),
|
||||
hotspot_x,
|
||||
hotspot_y,
|
||||
});
|
||||
let _ = surface_info.cursor_sender.send_replace(cursor_info);
|
||||
}
|
||||
wl_pointer::Request::Release => (),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
delegate_dispatch!(WaylandState: [WlPointer: SeatData] => SeatDelegate);
|
||||
|
||||
impl Dispatch<WlKeyboard, SeatData, WaylandState> for SeatDelegate {
|
||||
impl Dispatch<WlKeyboard, Arc<SeatData>, WaylandState> for WaylandState {
|
||||
fn request(
|
||||
_state: &mut WaylandState,
|
||||
_client: &Client,
|
||||
_resource: &WlKeyboard,
|
||||
request: <WlKeyboard as Resource>::Request,
|
||||
_data: &SeatData,
|
||||
_data: &Arc<SeatData>,
|
||||
_dh: &DisplayHandle,
|
||||
_data_init: &mut DataInit<'_, WaylandState>,
|
||||
) {
|
||||
@@ -263,15 +587,14 @@ impl Dispatch<WlKeyboard, SeatData, WaylandState> for SeatDelegate {
|
||||
}
|
||||
}
|
||||
}
|
||||
delegate_dispatch!(WaylandState: [WlKeyboard: SeatData] => SeatDelegate);
|
||||
|
||||
impl Dispatch<WlTouch, SeatData, WaylandState> for SeatDelegate {
|
||||
impl Dispatch<WlTouch, Arc<SeatData>, WaylandState> for WaylandState {
|
||||
fn request(
|
||||
_state: &mut WaylandState,
|
||||
_client: &Client,
|
||||
_resource: &WlTouch,
|
||||
request: <WlTouch as Resource>::Request,
|
||||
_data: &SeatData,
|
||||
_data: &Arc<SeatData>,
|
||||
_dh: &DisplayHandle,
|
||||
_data_init: &mut DataInit<'_, WaylandState>,
|
||||
) {
|
||||
@@ -281,4 +604,3 @@ impl Dispatch<WlTouch, SeatData, WaylandState> for SeatDelegate {
|
||||
}
|
||||
}
|
||||
}
|
||||
delegate_dispatch!(WaylandState: [WlTouch: SeatData] => SeatDelegate);
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
#![allow(dead_code)]
|
||||
|
||||
// Basic gamma correction shader
|
||||
// pub const PANEL_SHADER_BYTES: &[u8] = include_bytes!("shader_unlit_gamma.sks");
|
||||
|
||||
// Simula shader with fancy lanzcos sampling
|
||||
pub const PANEL_SHADER_BYTES: &[u8] = include_bytes!("shader_unlit_simula.sks");
|
||||
@@ -1,41 +1,68 @@
|
||||
use crate::wayland::seat::SeatData;
|
||||
use super::DisplayWrapper;
|
||||
use crate::wayland::{drm::wl_drm::WlDrm, seat::SeatData};
|
||||
use once_cell::sync::OnceCell;
|
||||
use parking_lot::Mutex;
|
||||
use rustc_hash::FxHashMap;
|
||||
use slog::Logger;
|
||||
use smithay::{
|
||||
delegate_output, delegate_shm,
|
||||
output::{Output, Scale, Subpixel},
|
||||
backend::{
|
||||
allocator::{dmabuf::Dmabuf, Fourcc},
|
||||
egl::EGLDevice,
|
||||
renderer::gles::GlesRenderer,
|
||||
},
|
||||
delegate_dmabuf, delegate_output, delegate_shm,
|
||||
output::{Mode, Output, Scale, Subpixel},
|
||||
reexports::{
|
||||
wayland_protocols_misc::server_decoration::server::org_kde_kwin_server_decoration_manager::Mode,
|
||||
wayland_protocols::xdg::{
|
||||
decoration::zv1::server::zxdg_decoration_manager_v1::ZxdgDecorationManagerV1,
|
||||
shell::server::xdg_wm_base::XdgWmBase,
|
||||
},
|
||||
wayland_protocols_misc::server_decoration::server::org_kde_kwin_server_decoration_manager::Mode as DecorationMode,
|
||||
wayland_server::{
|
||||
backend::{ClientData, ClientId, DisconnectReason},
|
||||
protocol::wl_data_device_manager::WlDataDeviceManager,
|
||||
Display, DisplayHandle,
|
||||
protocol::{
|
||||
wl_buffer::WlBuffer, wl_data_device_manager::WlDataDeviceManager,
|
||||
wl_output::WlOutput,
|
||||
},
|
||||
DisplayHandle,
|
||||
},
|
||||
},
|
||||
utils::Size,
|
||||
utils::{Size, Transform},
|
||||
wayland::{
|
||||
buffer::BufferHandler,
|
||||
compositor::CompositorState,
|
||||
output::OutputManagerState,
|
||||
shell::{
|
||||
kde::decoration::KdeDecorationState,
|
||||
xdg::{decoration::XdgDecorationState, XdgShellState},
|
||||
compositor::{CompositorClientState, CompositorState},
|
||||
dmabuf::{
|
||||
self, DmabufFeedback, DmabufFeedbackBuilder, DmabufGlobal, DmabufHandler, DmabufState,
|
||||
},
|
||||
output::OutputHandler,
|
||||
shell::kde::decoration::KdeDecorationState,
|
||||
shm::{ShmHandler, ShmState},
|
||||
xdg_activation::XdgActivationState,
|
||||
},
|
||||
};
|
||||
use std::sync::{Arc, Weak};
|
||||
use tokio::sync::mpsc::UnboundedSender;
|
||||
use tracing::{info, warn};
|
||||
|
||||
pub struct ClientState;
|
||||
pub struct ClientState {
|
||||
pub id: OnceCell<ClientId>,
|
||||
pub compositor_state: CompositorClientState,
|
||||
pub display: Weak<DisplayWrapper>,
|
||||
pub seat: Arc<SeatData>,
|
||||
}
|
||||
impl ClientState {
|
||||
pub fn flush(&self) {
|
||||
let Some(display) = self.display.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let _ = display.flush_clients(self.id.get().cloned());
|
||||
}
|
||||
}
|
||||
impl ClientData for ClientState {
|
||||
fn initialized(&self, client_id: ClientId) {
|
||||
println!("Wayland client {:?} connected", client_id);
|
||||
info!("Wayland client {:?} connected", client_id);
|
||||
let _ = self.id.set(client_id);
|
||||
}
|
||||
|
||||
fn disconnected(&self, client_id: ClientId, reason: DisconnectReason) {
|
||||
println!(
|
||||
info!(
|
||||
"Wayland client {:?} disconnected because {:#?}",
|
||||
client_id, reason
|
||||
);
|
||||
@@ -44,34 +71,68 @@ impl ClientData for ClientState {
|
||||
|
||||
pub struct WaylandState {
|
||||
pub weak_ref: Weak<Mutex<WaylandState>>,
|
||||
pub display: Arc<Mutex<Display<WaylandState>>>,
|
||||
pub display_handle: DisplayHandle,
|
||||
|
||||
pub compositor_state: CompositorState,
|
||||
pub xdg_activation_state: XdgActivationState,
|
||||
pub xdg_decoration_state: XdgDecorationState,
|
||||
// pub xdg_activation_state: XdgActivationState,
|
||||
pub kde_decoration_state: KdeDecorationState,
|
||||
pub xdg_shell_state: XdgShellState,
|
||||
pub shm_state: ShmState,
|
||||
pub output_manager_state: OutputManagerState,
|
||||
dmabuf_state: (DmabufState, DmabufGlobal, Option<DmabufFeedback>),
|
||||
pub drm_formats: Vec<Fourcc>,
|
||||
pub dmabuf_tx: UnboundedSender<(Dmabuf, Option<dmabuf::ImportNotifier>)>,
|
||||
pub output: Output,
|
||||
pub seats: FxHashMap<ClientId, SeatData>,
|
||||
}
|
||||
|
||||
impl WaylandState {
|
||||
pub fn new(
|
||||
log: Logger,
|
||||
display: Arc<Mutex<Display<WaylandState>>>,
|
||||
display_handle: DisplayHandle,
|
||||
renderer: &GlesRenderer,
|
||||
dmabuf_tx: UnboundedSender<(Dmabuf, Option<dmabuf::ImportNotifier>)>,
|
||||
) -> Arc<Mutex<Self>> {
|
||||
let compositor_state = CompositorState::new::<Self, _>(&display_handle, log.clone());
|
||||
let xdg_activation_state = XdgActivationState::new::<Self, _>(&display_handle, log.clone());
|
||||
let xdg_shell_state = XdgShellState::new::<Self, _>(&display_handle, log.clone());
|
||||
let xdg_decoration_state = XdgDecorationState::new::<Self, _>(&display_handle, log.clone());
|
||||
let compositor_state = CompositorState::new::<Self>(&display_handle);
|
||||
// let xdg_activation_state = XdgActivationState::new::<Self, _>(&display_handle);
|
||||
let kde_decoration_state =
|
||||
KdeDecorationState::new::<Self, _>(&display_handle, Mode::Server, log.clone());
|
||||
let shm_state = ShmState::new::<Self, _>(&display_handle, vec![], log.clone());
|
||||
let output_manager_state = OutputManagerState::new_with_xdg_output::<Self>(&display_handle);
|
||||
KdeDecorationState::new::<Self>(&display_handle, DecorationMode::Server);
|
||||
let shm_state = ShmState::new::<Self>(&display_handle, vec![]);
|
||||
let render_node = EGLDevice::device_for_display(renderer.egl_context().display())
|
||||
.and_then(|device| device.try_get_render_node());
|
||||
let dmabuf_formats = renderer
|
||||
.egl_context()
|
||||
.dmabuf_render_formats()
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
let drm_formats = dmabuf_formats.iter().map(|f| f.code).collect();
|
||||
|
||||
let dmabuf_default_feedback = match render_node {
|
||||
Ok(Some(node)) => DmabufFeedbackBuilder::new(node.dev_id(), dmabuf_formats.clone())
|
||||
.build()
|
||||
.ok(),
|
||||
Ok(None) => {
|
||||
warn!("failed to query render node, dmabuf will use v3");
|
||||
None
|
||||
}
|
||||
Err(err) => {
|
||||
warn!(?err, "failed to egl device for display, dmabuf will use v3");
|
||||
None
|
||||
}
|
||||
};
|
||||
// if we failed to build dmabuf feedback we fall back to dmabuf v3
|
||||
// Note: egl on Mesa requires either v4 or wl_drm (initialized with bind_wl_display)
|
||||
let dmabuf_state = if let Some(default_feedback) = dmabuf_default_feedback {
|
||||
let mut dmabuf_state = DmabufState::new();
|
||||
let dmabuf_global = dmabuf_state.create_global_with_default_feedback::<WaylandState>(
|
||||
&display_handle,
|
||||
&default_feedback,
|
||||
);
|
||||
(dmabuf_state, dmabuf_global, Some(default_feedback))
|
||||
} else {
|
||||
let mut dmabuf_state = DmabufState::new();
|
||||
let dmabuf_global =
|
||||
dmabuf_state.create_global::<WaylandState>(&display_handle, dmabuf_formats.clone());
|
||||
(dmabuf_state, dmabuf_global, None)
|
||||
};
|
||||
|
||||
let output = Output::new(
|
||||
"1x".to_owned(),
|
||||
smithay::output::PhysicalProperties {
|
||||
@@ -80,54 +141,73 @@ impl WaylandState {
|
||||
make: "Virtual XR Display".to_owned(),
|
||||
model: "Your Headset Name Here".to_owned(),
|
||||
},
|
||||
log.clone(),
|
||||
);
|
||||
let _global = output.create_global::<Self>(&display_handle);
|
||||
output.change_current_state(None, None, Some(Scale::Integer(2)), None);
|
||||
let _output_global = output.create_global::<Self>(&display_handle);
|
||||
let mode = Mode {
|
||||
size: (2048, 2048).into(),
|
||||
refresh: 60000,
|
||||
};
|
||||
output.change_current_state(
|
||||
Some(mode),
|
||||
Some(Transform::Normal),
|
||||
Some(Scale::Integer(2)),
|
||||
None,
|
||||
);
|
||||
output.set_preferred(mode);
|
||||
display_handle.create_global::<Self, WlDataDeviceManager, _>(3, ());
|
||||
display_handle.create_global::<Self, XdgWmBase, _>(5, ());
|
||||
display_handle.create_global::<Self, ZxdgDecorationManagerV1, _>(1, ());
|
||||
display_handle.create_global::<Self, WlDrm, _>(2, ());
|
||||
|
||||
println!("Init Wayland compositor");
|
||||
info!("Init Wayland compositor");
|
||||
|
||||
Arc::new_cyclic(|weak| {
|
||||
Mutex::new(WaylandState {
|
||||
weak_ref: weak.clone(),
|
||||
display,
|
||||
display_handle,
|
||||
|
||||
compositor_state,
|
||||
xdg_activation_state,
|
||||
xdg_decoration_state,
|
||||
// xdg_activation_state,
|
||||
kde_decoration_state,
|
||||
xdg_shell_state,
|
||||
shm_state,
|
||||
output_manager_state,
|
||||
drm_formats,
|
||||
dmabuf_state,
|
||||
dmabuf_tx,
|
||||
output,
|
||||
seats: FxHashMap::default(),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub fn new_client(&mut self, client: ClientId, dh: &DisplayHandle) {
|
||||
let seat_data = SeatData::new(dh, client.clone());
|
||||
self.seats.insert(client, seat_data);
|
||||
}
|
||||
}
|
||||
impl Drop for WaylandState {
|
||||
fn drop(&mut self) {
|
||||
println!("Cleanly shut down the Wayland compositor");
|
||||
info!("Cleanly shut down the Wayland compositor");
|
||||
}
|
||||
}
|
||||
impl BufferHandler for WaylandState {
|
||||
fn buffer_destroyed(
|
||||
&mut self,
|
||||
_buffer: &smithay::reexports::wayland_server::protocol::wl_buffer::WlBuffer,
|
||||
) {
|
||||
}
|
||||
fn buffer_destroyed(&mut self, _buffer: &WlBuffer) {}
|
||||
}
|
||||
impl ShmHandler for WaylandState {
|
||||
fn shm_state(&self) -> &smithay::wayland::shm::ShmState {
|
||||
fn shm_state(&self) -> &ShmState {
|
||||
&self.shm_state
|
||||
}
|
||||
}
|
||||
impl DmabufHandler for WaylandState {
|
||||
fn dmabuf_state(&mut self) -> &mut DmabufState {
|
||||
&mut self.dmabuf_state.0
|
||||
}
|
||||
|
||||
fn dmabuf_imported(
|
||||
&mut self,
|
||||
_global: &DmabufGlobal,
|
||||
dmabuf: Dmabuf,
|
||||
notifier: dmabuf::ImportNotifier,
|
||||
) {
|
||||
self.dmabuf_tx.send((dmabuf, Some(notifier))).unwrap();
|
||||
}
|
||||
}
|
||||
impl OutputHandler for WaylandState {
|
||||
fn output_bound(&mut self, _output: Output, _wl_output: WlOutput) {}
|
||||
}
|
||||
delegate_dmabuf!(WaylandState);
|
||||
delegate_shm!(WaylandState);
|
||||
delegate_output!(WaylandState);
|
||||
|
||||
@@ -1,137 +1,116 @@
|
||||
use super::{shaders::PANEL_SHADER_BYTES, state::WaylandState};
|
||||
use super::{state::WaylandState, utils::get_data};
|
||||
use crate::{
|
||||
core::{destroy_queue, registry::Registry},
|
||||
nodes::drawable::model::Model,
|
||||
core::{delta::Delta, destroy_queue, registry::Registry},
|
||||
nodes::drawable::{model::ModelPart, shaders::PANEL_SHADER_BYTES},
|
||||
};
|
||||
use mint::Vector2;
|
||||
use once_cell::sync::OnceCell;
|
||||
use parking_lot::Mutex;
|
||||
use send_wrapper::SendWrapper;
|
||||
use slog::Logger;
|
||||
use smithay::{
|
||||
backend::renderer::{
|
||||
gles2::{Gles2Renderer, Gles2Texture},
|
||||
gles::{GlesRenderer, GlesTexture},
|
||||
utils::{import_surface_tree, on_commit_buffer_handler, RendererSurfaceStateUserData},
|
||||
Texture,
|
||||
Renderer, Texture,
|
||||
},
|
||||
desktop::utils::send_frames_surface_tree,
|
||||
reexports::wayland_server::{
|
||||
backend::ObjectId, protocol::wl_surface::WlSurface, Display, DisplayHandle, Resource,
|
||||
},
|
||||
output::Output,
|
||||
reexports::wayland_server::{self, protocol::wl_surface::WlSurface, DisplayHandle, Resource},
|
||||
wayland::compositor::{self, SurfaceData},
|
||||
};
|
||||
use std::sync::{Arc, Weak};
|
||||
use std::{cell::RefCell, ffi::c_void, sync::Arc, time::Duration};
|
||||
use stereokit::{
|
||||
material::{Material, Transparency},
|
||||
shader::Shader,
|
||||
texture::{Texture as SKTexture, TextureAddress, TextureFormat, TextureSample, TextureType},
|
||||
StereoKit,
|
||||
Material, Shader, StereoKitDraw, Tex, TextureAddress, TextureFormat, TextureSample,
|
||||
TextureType, Transparency,
|
||||
};
|
||||
|
||||
pub static CORE_SURFACES: Registry<CoreSurface> = Registry::new();
|
||||
|
||||
pub struct CoreSurfaceData {
|
||||
wl_tex: Option<SendWrapper<Gles2Texture>>,
|
||||
sk_tex: Option<SendWrapper<SKTexture>>,
|
||||
sk_mat: Option<Arc<SendWrapper<Material>>>,
|
||||
wl_tex: Option<SendWrapper<GlesTexture>>,
|
||||
pub size: Vector2<u32>,
|
||||
}
|
||||
impl CoreSurfaceData {
|
||||
fn new(sk: &StereoKit) -> Self {
|
||||
let sk_tex = SendWrapper::new(
|
||||
SKTexture::create(sk, TextureType::ImageNoMips, TextureFormat::RGBA32).unwrap(),
|
||||
);
|
||||
let sk_mat = {
|
||||
let shader = Shader::from_mem(sk, PANEL_SHADER_BYTES).unwrap();
|
||||
let mat = Material::create(sk, &shader).unwrap();
|
||||
mat.set_parameter("diffuse", &*sk_tex);
|
||||
mat.set_transparency(Transparency::Blend);
|
||||
Arc::new(SendWrapper::new(mat))
|
||||
};
|
||||
CoreSurfaceData {
|
||||
wl_tex: None,
|
||||
sk_tex: Some(sk_tex),
|
||||
sk_mat: Some(sk_mat),
|
||||
size: Vector2::from([0, 0]),
|
||||
}
|
||||
}
|
||||
fn update_tex(&mut self, data: &RendererSurfaceStateUserData, renderer: &Gles2Renderer) {
|
||||
if let Some(surface_size) = data.borrow().surface_size() {
|
||||
self.size = Vector2::from([surface_size.w as u32, surface_size.h as u32]);
|
||||
}
|
||||
self.wl_tex = data
|
||||
.borrow()
|
||||
.texture(renderer)
|
||||
.cloned()
|
||||
.map(SendWrapper::new);
|
||||
if let Some(smithay_tex) = self.wl_tex.as_ref() {
|
||||
let sk_tex = self.sk_tex.as_ref().unwrap();
|
||||
unsafe {
|
||||
sk_tex.set_native(
|
||||
smithay_tex.tex_id() as usize,
|
||||
smithay::backend::renderer::gles2::ffi::RGBA8.into(),
|
||||
TextureType::Image,
|
||||
smithay_tex.width(),
|
||||
smithay_tex.height(),
|
||||
false,
|
||||
);
|
||||
sk_tex.set_sample(TextureSample::Point);
|
||||
sk_tex.set_address_mode(TextureAddress::Clamp);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for CoreSurfaceData {
|
||||
fn drop(&mut self) {
|
||||
destroy_queue::add(self.wl_tex.take());
|
||||
destroy_queue::add(self.sk_tex.take());
|
||||
destroy_queue::add(self.sk_mat.take());
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CoreSurface {
|
||||
display: Weak<Mutex<Display<WaylandState>>>,
|
||||
pub state: Weak<Mutex<WaylandState>>,
|
||||
pub dh: DisplayHandle,
|
||||
pub surface_id: ObjectId,
|
||||
pub mapped_data: Mutex<Option<CoreSurfaceData>>,
|
||||
pub pending_material_applications: Mutex<Vec<(Arc<Model>, u32)>>,
|
||||
pub weak_surface: wayland_server::Weak<WlSurface>,
|
||||
mapped_data: Mutex<Option<CoreSurfaceData>>,
|
||||
sk_tex: OnceCell<Tex>,
|
||||
sk_mat: OnceCell<Arc<Material>>,
|
||||
material_offset: Mutex<Delta<u32>>,
|
||||
on_mapped: Box<dyn Fn() + Send + Sync>,
|
||||
on_commit: Box<dyn Fn(u32) + Send + Sync>,
|
||||
pub pending_material_applications: Registry<ModelPart>,
|
||||
}
|
||||
|
||||
impl CoreSurface {
|
||||
pub fn new(
|
||||
state: &Arc<Mutex<WaylandState>>,
|
||||
display: &Arc<Mutex<Display<WaylandState>>>,
|
||||
pub fn add_to(
|
||||
dh: DisplayHandle,
|
||||
surface: &WlSurface,
|
||||
) -> Arc<Self> {
|
||||
CORE_SURFACES.add(CoreSurface {
|
||||
display: Arc::downgrade(display),
|
||||
state: Arc::downgrade(state),
|
||||
dh,
|
||||
surface_id: surface.id(),
|
||||
mapped_data: Mutex::new(None),
|
||||
pending_material_applications: Mutex::new(Vec::new()),
|
||||
})
|
||||
on_mapped: impl Fn() + Send + Sync + 'static,
|
||||
on_commit: impl Fn(u32) + Send + Sync + 'static,
|
||||
) {
|
||||
compositor::with_states(surface, |data| {
|
||||
data.data_map.insert_if_missing_threadsafe(|| {
|
||||
CORE_SURFACES.add(CoreSurface {
|
||||
dh,
|
||||
weak_surface: surface.downgrade(),
|
||||
mapped_data: Mutex::new(None),
|
||||
sk_tex: OnceCell::new(),
|
||||
sk_mat: OnceCell::new(),
|
||||
material_offset: Mutex::new(Delta::new(0)),
|
||||
on_mapped: Box::new(on_mapped) as Box<dyn Fn() + Send + Sync>,
|
||||
on_commit: Box::new(on_commit) as Box<dyn Fn(u32) + Send + Sync>,
|
||||
pending_material_applications: Registry::new(),
|
||||
})
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
pub fn process<F: FnOnce(&SurfaceData), M: FnOnce(&SurfaceData)>(
|
||||
&self,
|
||||
sk: &StereoKit,
|
||||
renderer: &mut Gles2Renderer,
|
||||
time_ms: u32,
|
||||
log: &Logger,
|
||||
on_mapped: F,
|
||||
if_mapped: M,
|
||||
) {
|
||||
// Let Smithay handle all the buffer maintenance
|
||||
on_commit_buffer_handler(&self.wl_surface());
|
||||
// Import all surface buffers into textures
|
||||
import_surface_tree(renderer, &self.wl_surface(), log).unwrap();
|
||||
pub fn commit(&self, count: u32) {
|
||||
(self.on_commit)(count);
|
||||
}
|
||||
|
||||
let mapped = compositor::with_states(&self.wl_surface(), |data| {
|
||||
pub fn from_wl_surface(surf: &WlSurface) -> Option<Arc<CoreSurface>> {
|
||||
get_data(surf)
|
||||
}
|
||||
|
||||
pub fn process(&self, sk: &impl StereoKitDraw, renderer: &mut GlesRenderer) {
|
||||
let Some(wl_surface) = self.wl_surface() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let sk_tex = self
|
||||
.sk_tex
|
||||
.get_or_init(|| sk.tex_create(TextureType::IMAGE_NO_MIPS, TextureFormat::RGBA32));
|
||||
self.sk_mat.get_or_init(|| {
|
||||
let shader = sk.shader_create_mem(&PANEL_SHADER_BYTES);
|
||||
// let _ = renderer.with_context(|c| unsafe {
|
||||
// shader_inject(c, &mut shader, SIMULA_VERT_STR, SIMULA_FRAG_STR)
|
||||
// });
|
||||
|
||||
let mat = sk.material_create(shader.as_ref().unwrap_or(Shader::UI.as_ref()));
|
||||
sk.material_set_texture(&mat, "diffuse", sk_tex.as_ref());
|
||||
sk.material_set_transparency(&mat, Transparency::Blend);
|
||||
Arc::new(mat)
|
||||
});
|
||||
|
||||
// Let smithay handle buffer management (has to be done here as RendererSurfaceStates is not thread safe)
|
||||
on_commit_buffer_handler::<WaylandState>(&wl_surface);
|
||||
// Import all surface buffers into textures
|
||||
if import_surface_tree(renderer, &wl_surface).is_err() {
|
||||
return;
|
||||
}
|
||||
|
||||
let mapped = compositor::with_states(&wl_surface, |data| {
|
||||
data.data_map
|
||||
.get::<RendererSurfaceStateUserData>()
|
||||
.map(|surface_states| surface_states.borrow().wl_buffer().is_some())
|
||||
.map(|surface_states| surface_states.borrow().buffer().is_some())
|
||||
.unwrap_or(false)
|
||||
});
|
||||
|
||||
@@ -141,80 +120,110 @@ impl CoreSurface {
|
||||
|
||||
let mut mapped_data = self.mapped_data.lock();
|
||||
let just_mapped = mapped_data.is_none();
|
||||
if just_mapped {
|
||||
*mapped_data = Some(CoreSurfaceData::new(sk));
|
||||
}
|
||||
drop(mapped_data);
|
||||
self.with_states(|data| {
|
||||
self.with_data(|mapped_data| {
|
||||
mapped_data.update_tex(
|
||||
data.data_map.get::<RendererSurfaceStateUserData>().unwrap(),
|
||||
renderer,
|
||||
let Some(renderer_surface_state) = data
|
||||
.data_map
|
||||
.get::<RendererSurfaceStateUserData>()
|
||||
.map(RefCell::borrow)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let Some(smithay_tex) = renderer_surface_state
|
||||
.texture::<GlesRenderer>(renderer.id())
|
||||
.cloned()
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
let Some(sk_tex) = self.sk_tex.get() else {
|
||||
return;
|
||||
};
|
||||
let Some(sk_mat) = self.sk_mat.get() else {
|
||||
return;
|
||||
};
|
||||
unsafe {
|
||||
sk.tex_set_surface(
|
||||
sk_tex.as_ref(),
|
||||
smithay_tex.tex_id() as usize as *mut c_void,
|
||||
TextureType::IMAGE_NO_MIPS,
|
||||
smithay::backend::renderer::gles::ffi::RGBA8.into(),
|
||||
smithay_tex.width() as i32,
|
||||
smithay_tex.height() as i32,
|
||||
1,
|
||||
false,
|
||||
);
|
||||
});
|
||||
self.apply_surface_materials();
|
||||
|
||||
if just_mapped {
|
||||
on_mapped(data);
|
||||
sk.tex_set_sample(sk_tex.as_ref(), TextureSample::Point);
|
||||
sk.tex_set_address(sk_tex.as_ref(), TextureAddress::Clamp);
|
||||
}
|
||||
if let Some(material_offset) = self.material_offset.lock().delta() {
|
||||
sk.material_set_queue_offset(sk_mat.as_ref().as_ref(), *material_offset as i32);
|
||||
}
|
||||
if_mapped(data);
|
||||
});
|
||||
|
||||
send_frames_surface_tree(&self.wl_surface(), time_ms);
|
||||
let Some(surface_size) = renderer_surface_state.surface_size() else {
|
||||
return;
|
||||
};
|
||||
let new_mapped_data = CoreSurfaceData {
|
||||
size: Vector2::from([surface_size.w as u32, surface_size.h as u32]),
|
||||
wl_tex: Some(SendWrapper::new(smithay_tex)),
|
||||
};
|
||||
*mapped_data = Some(new_mapped_data);
|
||||
});
|
||||
drop(mapped_data);
|
||||
if just_mapped {
|
||||
(self.on_mapped)();
|
||||
}
|
||||
self.apply_surface_materials();
|
||||
}
|
||||
|
||||
pub fn apply_material(&self, model: Arc<Model>, material_idx: u32) {
|
||||
self.pending_material_applications
|
||||
.lock()
|
||||
.push((model, material_idx));
|
||||
pub fn frame(&self, sk: &impl StereoKitDraw, output: Output) {
|
||||
let Some(wl_surface) = self.wl_surface() else {
|
||||
return;
|
||||
};
|
||||
|
||||
send_frames_surface_tree(
|
||||
&wl_surface,
|
||||
&output,
|
||||
Duration::from_secs_f64(sk.time_get()),
|
||||
None,
|
||||
|_, _| Some(output.clone()),
|
||||
);
|
||||
}
|
||||
|
||||
pub fn set_material_offset(&self, material_offset: u32) {
|
||||
*self.material_offset.lock().value_mut() = material_offset;
|
||||
}
|
||||
|
||||
pub fn apply_material(&self, model_part: &Arc<ModelPart>) {
|
||||
self.pending_material_applications.add_raw(model_part)
|
||||
}
|
||||
|
||||
fn apply_surface_materials(&self) {
|
||||
self.with_data(|mapped_data| {
|
||||
let mut pending_material_applications = self.pending_material_applications.lock();
|
||||
for (model, material_idx) in &*pending_material_applications {
|
||||
model
|
||||
.pending_material_replacements
|
||||
.lock()
|
||||
.insert(*material_idx, mapped_data.sk_mat.clone().unwrap());
|
||||
if let Some(sk_mat) = self.sk_mat.get() {
|
||||
for model_node in self.pending_material_applications.get_valid_contents() {
|
||||
model_node.replace_material(sk_mat.clone());
|
||||
}
|
||||
pending_material_applications.clear();
|
||||
});
|
||||
self.pending_material_applications.clear();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn wayland_state(&self) -> Arc<Mutex<WaylandState>> {
|
||||
self.state.upgrade().unwrap()
|
||||
pub fn wl_surface(&self) -> Option<WlSurface> {
|
||||
self.weak_surface.upgrade().ok()
|
||||
}
|
||||
|
||||
pub fn wl_surface(&self) -> WlSurface {
|
||||
WlSurface::from_id(&self.dh, self.surface_id.clone()).unwrap()
|
||||
pub fn with_states<T, F: FnOnce(&SurfaceData) -> T>(&self, f: F) -> Option<T> {
|
||||
self.wl_surface()
|
||||
.map(|wl_surface| compositor::with_states(&wl_surface, f))
|
||||
}
|
||||
|
||||
pub fn with_states<F, T>(&self, f: F) -> T
|
||||
where
|
||||
F: FnOnce(&SurfaceData) -> T,
|
||||
{
|
||||
compositor::with_states(&self.wl_surface(), f)
|
||||
}
|
||||
|
||||
pub fn with_data<F, T>(&self, f: F) -> Option<T>
|
||||
where
|
||||
F: FnOnce(&mut CoreSurfaceData) -> T,
|
||||
{
|
||||
self.mapped_data.lock().as_mut().map(f)
|
||||
}
|
||||
|
||||
pub fn flush_clients(&self) {
|
||||
self.display
|
||||
.upgrade()
|
||||
.unwrap()
|
||||
.lock()
|
||||
.flush_clients()
|
||||
.unwrap();
|
||||
pub fn size(&self) -> Option<Vector2<u32>> {
|
||||
self.mapped_data.lock().as_ref().map(|d| d.size)
|
||||
}
|
||||
}
|
||||
impl Drop for CoreSurface {
|
||||
fn drop(&mut self) {
|
||||
CORE_SURFACES.remove(self);
|
||||
|
||||
destroy_queue::add(self.sk_tex.take());
|
||||
destroy_queue::add(self.sk_mat.take());
|
||||
}
|
||||
}
|
||||
|
||||
14
src/wayland/utils.rs
Normal file
14
src/wayland/utils.rs
Normal file
@@ -0,0 +1,14 @@
|
||||
use smithay::{reexports::wayland_server::protocol::wl_surface::WlSurface, wayland::compositor};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn insert_data<T: Send + Sync + 'static>(wl_surface: &WlSurface, data: T) {
|
||||
insert_data_raw(wl_surface, Arc::new(data))
|
||||
}
|
||||
pub fn insert_data_raw<T: Send + Sync + 'static>(wl_surface: &WlSurface, data: Arc<T>) {
|
||||
compositor::with_states(wl_surface, |d| {
|
||||
d.data_map.insert_if_missing_threadsafe(move || data)
|
||||
});
|
||||
}
|
||||
pub fn get_data<T: Send + Sync + 'static>(wl_surface: &WlSurface) -> Option<Arc<T>> {
|
||||
compositor::with_states(wl_surface, |d| d.data_map.get::<Arc<T>>().cloned())
|
||||
}
|
||||
189
src/wayland/wayland-drm.xml
Normal file
189
src/wayland/wayland-drm.xml
Normal file
@@ -0,0 +1,189 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<protocol name="drm">
|
||||
|
||||
<copyright>
|
||||
Copyright © 2008-2011 Kristian Høgsberg
|
||||
Copyright © 2010-2011 Intel Corporation
|
||||
|
||||
Permission to use, copy, modify, distribute, and sell this
|
||||
software and its documentation for any purpose is hereby granted
|
||||
without fee, provided that\n the above copyright notice appear in
|
||||
all copies and that both that copyright notice and this permission
|
||||
notice appear in supporting documentation, and that the name of
|
||||
the copyright holders not be used in advertising or publicity
|
||||
pertaining to distribution of the software without specific,
|
||||
written prior permission. The copyright holders make no
|
||||
representations about the suitability of this software for any
|
||||
purpose. It is provided "as is" without express or implied
|
||||
warranty.
|
||||
|
||||
THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
|
||||
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||
FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
|
||||
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
|
||||
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
|
||||
THIS SOFTWARE.
|
||||
</copyright>
|
||||
|
||||
<!-- drm support. This object is created by the server and published
|
||||
using the display's global event. -->
|
||||
<interface name="wl_drm" version="2">
|
||||
<enum name="error">
|
||||
<entry name="authenticate_fail" value="0" />
|
||||
<entry name="invalid_format" value="1" />
|
||||
<entry name="invalid_name" value="2" />
|
||||
</enum>
|
||||
|
||||
<enum name="format">
|
||||
<!-- The drm format codes match the #defines in drm_fourcc.h.
|
||||
The formats actually supported by the compositor will be
|
||||
reported by the format event. New codes must not be added,
|
||||
unless directly taken from drm_fourcc.h. -->
|
||||
<entry name="c8" value="0x20203843" />
|
||||
<entry name="rgb332" value="0x38424752" />
|
||||
<entry name="bgr233" value="0x38524742" />
|
||||
<entry name="xrgb4444" value="0x32315258" />
|
||||
<entry name="xbgr4444" value="0x32314258" />
|
||||
<entry name="rgbx4444" value="0x32315852" />
|
||||
<entry name="bgrx4444" value="0x32315842" />
|
||||
<entry name="argb4444" value="0x32315241" />
|
||||
<entry name="abgr4444" value="0x32314241" />
|
||||
<entry name="rgba4444" value="0x32314152" />
|
||||
<entry name="bgra4444" value="0x32314142" />
|
||||
<entry name="xrgb1555" value="0x35315258" />
|
||||
<entry name="xbgr1555" value="0x35314258" />
|
||||
<entry name="rgbx5551" value="0x35315852" />
|
||||
<entry name="bgrx5551" value="0x35315842" />
|
||||
<entry name="argb1555" value="0x35315241" />
|
||||
<entry name="abgr1555" value="0x35314241" />
|
||||
<entry name="rgba5551" value="0x35314152" />
|
||||
<entry name="bgra5551" value="0x35314142" />
|
||||
<entry name="rgb565" value="0x36314752" />
|
||||
<entry name="bgr565" value="0x36314742" />
|
||||
<entry name="rgb888" value="0x34324752" />
|
||||
<entry name="bgr888" value="0x34324742" />
|
||||
<entry name="xrgb8888" value="0x34325258" />
|
||||
<entry name="xbgr8888" value="0x34324258" />
|
||||
<entry name="rgbx8888" value="0x34325852" />
|
||||
<entry name="bgrx8888" value="0x34325842" />
|
||||
<entry name="argb8888" value="0x34325241" />
|
||||
<entry name="abgr8888" value="0x34324241" />
|
||||
<entry name="rgba8888" value="0x34324152" />
|
||||
<entry name="bgra8888" value="0x34324142" />
|
||||
<entry name="xrgb2101010" value="0x30335258" />
|
||||
<entry name="xbgr2101010" value="0x30334258" />
|
||||
<entry name="rgbx1010102" value="0x30335852" />
|
||||
<entry name="bgrx1010102" value="0x30335842" />
|
||||
<entry name="argb2101010" value="0x30335241" />
|
||||
<entry name="abgr2101010" value="0x30334241" />
|
||||
<entry name="rgba1010102" value="0x30334152" />
|
||||
<entry name="bgra1010102" value="0x30334142" />
|
||||
<entry name="yuyv" value="0x56595559" />
|
||||
<entry name="yvyu" value="0x55595659" />
|
||||
<entry name="uyvy" value="0x59565955" />
|
||||
<entry name="vyuy" value="0x59555956" />
|
||||
<entry name="ayuv" value="0x56555941" />
|
||||
<entry name="xyuv8888" value="0x56555958" />
|
||||
<entry name="nv12" value="0x3231564e" />
|
||||
<entry name="nv21" value="0x3132564e" />
|
||||
<entry name="nv16" value="0x3631564e" />
|
||||
<entry name="nv61" value="0x3136564e" />
|
||||
<entry name="yuv410" value="0x39565559" />
|
||||
<entry name="yvu410" value="0x39555659" />
|
||||
<entry name="yuv411" value="0x31315559" />
|
||||
<entry name="yvu411" value="0x31315659" />
|
||||
<entry name="yuv420" value="0x32315559" />
|
||||
<entry name="yvu420" value="0x32315659" />
|
||||
<entry name="yuv422" value="0x36315559" />
|
||||
<entry name="yvu422" value="0x36315659" />
|
||||
<entry name="yuv444" value="0x34325559" />
|
||||
<entry name="yvu444" value="0x34325659" />
|
||||
<entry name="abgr16f" value="0x48344241" />
|
||||
<entry name="xbgr16f" value="0x48344258" />
|
||||
</enum>
|
||||
|
||||
<!-- Call this request with the magic received from drmGetMagic().
|
||||
It will be passed on to the drmAuthMagic() or
|
||||
DRIAuthConnection() call. This authentication must be
|
||||
completed before create_buffer could be used. -->
|
||||
<request name="authenticate">
|
||||
<arg name="id" type="uint" />
|
||||
</request>
|
||||
|
||||
<!-- Create a wayland buffer for the named DRM buffer. The DRM
|
||||
surface must have a name using the flink ioctl -->
|
||||
<request name="create_buffer">
|
||||
<arg name="id" type="new_id" interface="wl_buffer" />
|
||||
<arg name="name" type="uint" />
|
||||
<arg name="width" type="int" />
|
||||
<arg name="height" type="int" />
|
||||
<arg name="stride" type="uint" />
|
||||
<arg name="format" type="uint" />
|
||||
</request>
|
||||
|
||||
<!-- Create a wayland buffer for the named DRM buffer. The DRM
|
||||
surface must have a name using the flink ioctl -->
|
||||
<request name="create_planar_buffer">
|
||||
<arg name="id" type="new_id" interface="wl_buffer" />
|
||||
<arg name="name" type="uint" />
|
||||
<arg name="width" type="int" />
|
||||
<arg name="height" type="int" />
|
||||
<arg name="format" type="uint" />
|
||||
<arg name="offset0" type="int" />
|
||||
<arg name="stride0" type="int" />
|
||||
<arg name="offset1" type="int" />
|
||||
<arg name="stride1" type="int" />
|
||||
<arg name="offset2" type="int" />
|
||||
<arg name="stride2" type="int" />
|
||||
</request>
|
||||
|
||||
<!-- Notification of the path of the drm device which is used by
|
||||
the server. The client should use this device for creating
|
||||
local buffers. Only buffers created from this device should
|
||||
be be passed to the server using this drm object's
|
||||
create_buffer request. -->
|
||||
<event name="device">
|
||||
<arg name="name" type="string" />
|
||||
</event>
|
||||
|
||||
<event name="format">
|
||||
<arg name="format" type="uint" />
|
||||
</event>
|
||||
|
||||
<!-- Raised if the authenticate request succeeded -->
|
||||
<event name="authenticated" />
|
||||
|
||||
<enum name="capability" since="2">
|
||||
<description summary="wl_drm capability bitmask">
|
||||
Bitmask of capabilities.
|
||||
</description>
|
||||
<entry name="prime" value="1" summary="wl_drm prime available" />
|
||||
</enum>
|
||||
|
||||
<event name="capabilities">
|
||||
<arg name="value" type="uint" />
|
||||
</event>
|
||||
|
||||
<!-- Version 2 additions -->
|
||||
|
||||
<!-- Create a wayland buffer for the prime fd. Use for regular and planar
|
||||
buffers. Pass 0 for offset and stride for unused planes. -->
|
||||
<request name="create_prime_buffer" since="2">
|
||||
<arg name="id" type="new_id" interface="wl_buffer" />
|
||||
<arg name="name" type="fd" />
|
||||
<arg name="width" type="int" />
|
||||
<arg name="height" type="int" />
|
||||
<arg name="format" type="uint" />
|
||||
<arg name="offset0" type="int" />
|
||||
<arg name="stride0" type="int" />
|
||||
<arg name="offset1" type="int" />
|
||||
<arg name="stride1" type="int" />
|
||||
<arg name="offset2" type="int" />
|
||||
<arg name="stride2" type="int" />
|
||||
</request>
|
||||
|
||||
</interface>
|
||||
|
||||
</protocol>
|
||||
@@ -1,69 +0,0 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::nodes::Node;
|
||||
|
||||
use super::{panel_item::PanelItem, state::WaylandState, surface::CoreSurface};
|
||||
use smithay::{
|
||||
delegate_xdg_shell,
|
||||
reexports::{
|
||||
wayland_protocols::xdg::{
|
||||
decoration::zv1::server::zxdg_toplevel_decoration_v1::Mode,
|
||||
shell::server::xdg_toplevel::State,
|
||||
},
|
||||
wayland_server::protocol::{wl_seat::WlSeat, wl_surface::WlSurface},
|
||||
},
|
||||
utils::Serial,
|
||||
wayland::{
|
||||
compositor,
|
||||
shell::xdg::{
|
||||
Configure, PopupSurface, PositionerState, ToplevelSurface, XdgShellHandler,
|
||||
XdgShellState,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
impl XdgShellHandler for WaylandState {
|
||||
fn xdg_shell_state(&mut self) -> &mut XdgShellState {
|
||||
&mut self.xdg_shell_state
|
||||
}
|
||||
|
||||
fn new_toplevel(&mut self, surface: ToplevelSurface) {
|
||||
self.output
|
||||
.enter(&self.display_handle, surface.wl_surface());
|
||||
surface.with_pending_state(|state| {
|
||||
state.states.set(State::Maximized);
|
||||
state.states.set(State::Activated);
|
||||
state.decoration_mode = Some(Mode::ServerSide);
|
||||
});
|
||||
surface.send_configure();
|
||||
}
|
||||
fn ack_configure(&mut self, surface: WlSurface, configure: Configure) {
|
||||
match configure {
|
||||
Configure::Toplevel(config) => {
|
||||
if let Some(size) = config.state.size {
|
||||
compositor::with_states(&surface, |data| {
|
||||
if let Some(panel_node) = data.data_map.get::<Arc<Node>>() {
|
||||
if let Some(core_surface) = data.data_map.get::<Arc<CoreSurface>>() {
|
||||
let panel_item = PanelItem::from_node(panel_node);
|
||||
let has_data = core_surface
|
||||
.with_data(|data| {
|
||||
data.size.x = size.w as u32;
|
||||
data.size.y = size.h as u32;
|
||||
})
|
||||
.is_some();
|
||||
if has_data {
|
||||
panel_item.resize();
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Configure::Popup(_) => (),
|
||||
}
|
||||
}
|
||||
|
||||
fn new_popup(&mut self, _surface: PopupSurface, _positioner: PositionerState) {}
|
||||
fn grab(&mut self, _surface: PopupSurface, _seat: WlSeat, _serial: Serial) {}
|
||||
}
|
||||
delegate_xdg_shell!(WaylandState);
|
||||
310
src/wayland/xdg_shell/backend.rs
Normal file
310
src/wayland/xdg_shell/backend.rs
Normal file
@@ -0,0 +1,310 @@
|
||||
use super::{popup::PopupData, surface::XdgSurfaceData, ToplevelData};
|
||||
use crate::{
|
||||
nodes::{
|
||||
data::KEYMAPS,
|
||||
drawable::model::ModelPart,
|
||||
items::panel::{Backend, ChildInfo, PanelItem, PanelItemInitData, SurfaceID},
|
||||
},
|
||||
wayland::{
|
||||
seat::{CursorInfo, KeyboardEvent, PointerEvent, SeatData},
|
||||
state::ClientState,
|
||||
surface::CoreSurface,
|
||||
utils, SERIAL_COUNTER,
|
||||
},
|
||||
};
|
||||
use color_eyre::eyre::{eyre, Result};
|
||||
use mint::Vector2;
|
||||
use parking_lot::Mutex;
|
||||
use rustc_hash::FxHashMap;
|
||||
use smithay::reexports::{
|
||||
wayland_protocols::xdg::shell::server::xdg_toplevel::XdgToplevel,
|
||||
wayland_server::{protocol::wl_surface::WlSurface, Resource, Weak},
|
||||
};
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::watch;
|
||||
use tracing::debug;
|
||||
|
||||
pub struct XdgToplevelState {
|
||||
pub fullscreen: bool,
|
||||
pub activated: bool,
|
||||
}
|
||||
|
||||
pub struct XdgBackend {
|
||||
toplevel: Weak<XdgToplevel>,
|
||||
toplevel_wl_surface: Weak<WlSurface>,
|
||||
pub toplevel_state: Mutex<XdgToplevelState>,
|
||||
popups: Mutex<FxHashMap<String, Weak<WlSurface>>>,
|
||||
pub cursor: watch::Receiver<Option<CursorInfo>>,
|
||||
pub seat: Arc<SeatData>,
|
||||
pointer_grab: Mutex<Option<SurfaceID>>,
|
||||
keyboard_grab: Mutex<Option<SurfaceID>>,
|
||||
}
|
||||
impl XdgBackend {
|
||||
pub fn create(
|
||||
toplevel_wl_surface: WlSurface,
|
||||
toplevel: XdgToplevel,
|
||||
seat: Arc<SeatData>,
|
||||
) -> Self {
|
||||
let cursor = seat.new_surface(&toplevel_wl_surface);
|
||||
XdgBackend {
|
||||
toplevel: toplevel.downgrade(),
|
||||
toplevel_wl_surface: toplevel_wl_surface.downgrade(),
|
||||
toplevel_state: Mutex::new(XdgToplevelState {
|
||||
fullscreen: false,
|
||||
activated: false,
|
||||
}),
|
||||
popups: Mutex::new(FxHashMap::default()),
|
||||
cursor,
|
||||
seat,
|
||||
pointer_grab: Mutex::new(None),
|
||||
keyboard_grab: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
fn wl_surface_from_id(&self, id: &SurfaceID) -> Option<WlSurface> {
|
||||
match id {
|
||||
SurfaceID::Cursor => self.cursor.borrow().as_ref()?.surface.upgrade().ok(),
|
||||
SurfaceID::Toplevel => self.toplevel_wl_surface(),
|
||||
SurfaceID::Child(popup) => {
|
||||
let popups = self.popups.lock();
|
||||
popups.get(popup)?.upgrade().ok()
|
||||
}
|
||||
}
|
||||
}
|
||||
fn toplevel_wl_surface(&self) -> Option<WlSurface> {
|
||||
self.toplevel_wl_surface.upgrade().ok()
|
||||
}
|
||||
|
||||
pub fn configure(&self, size: Option<Vector2<u32>>) {
|
||||
let Ok(xdg_toplevel) = self.toplevel.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let Some(wl_surface) = self.toplevel_wl_surface() else {
|
||||
return;
|
||||
};
|
||||
let Some(xdg_surface_data) = wl_surface.data::<XdgSurfaceData>() else {
|
||||
return;
|
||||
};
|
||||
let Some(core_surface) = CoreSurface::from_wl_surface(&wl_surface) else {
|
||||
return;
|
||||
};
|
||||
let Some(surface_size) = core_surface.size() else {
|
||||
return;
|
||||
};
|
||||
|
||||
xdg_toplevel.configure(
|
||||
size.unwrap_or(surface_size).x as i32,
|
||||
size.unwrap_or(surface_size).y as i32,
|
||||
self.states()
|
||||
.into_iter()
|
||||
.flat_map(|state| state.to_ne_bytes())
|
||||
.collect(),
|
||||
);
|
||||
xdg_surface_data.xdg_surface.configure(SERIAL_COUNTER.inc());
|
||||
self.flush_client();
|
||||
}
|
||||
fn states(&self) -> Vec<u32> {
|
||||
let mut states = vec![1, 5, 6, 7, 8]; // maximized always and tiled
|
||||
let toplevel_state = self.toplevel_state.lock();
|
||||
if toplevel_state.fullscreen {
|
||||
states.push(2);
|
||||
}
|
||||
if toplevel_state.activated {
|
||||
states.push(4);
|
||||
}
|
||||
states
|
||||
}
|
||||
|
||||
pub fn new_popup(
|
||||
&self,
|
||||
panel_item: &PanelItem<XdgBackend>,
|
||||
popup_wl_surface: &WlSurface,
|
||||
data: &PopupData,
|
||||
) {
|
||||
self.popups
|
||||
.lock()
|
||||
.insert(data.uid.clone(), popup_wl_surface.downgrade());
|
||||
|
||||
let Some(geometry) = data.geometry() else {
|
||||
return;
|
||||
};
|
||||
panel_item.new_child(
|
||||
&data.uid,
|
||||
ChildInfo {
|
||||
parent: utils::get_data::<SurfaceID>(&data.parent())
|
||||
.unwrap()
|
||||
.as_ref()
|
||||
.clone(),
|
||||
geometry,
|
||||
},
|
||||
)
|
||||
}
|
||||
pub fn reposition_popup(&self, panel_item: &PanelItem<XdgBackend>, popup_state: &PopupData) {
|
||||
let Some(geometry) = popup_state.geometry() else {
|
||||
return;
|
||||
};
|
||||
panel_item.reposition_child(&popup_state.uid, geometry)
|
||||
}
|
||||
pub fn drop_popup(&self, panel_item: &PanelItem<XdgBackend>, uid: &str) {
|
||||
panel_item.drop_child(uid);
|
||||
let Some(popup) = self.popups.lock().remove(uid) else {
|
||||
return;
|
||||
};
|
||||
let Some(wl_surface) = popup.upgrade().ok() else {
|
||||
return;
|
||||
};
|
||||
self.seat.drop_surface(&wl_surface);
|
||||
}
|
||||
|
||||
fn child_data(&self) -> FxHashMap<String, ChildInfo> {
|
||||
FxHashMap::from_iter(self.popups.lock().iter().filter_map(|(uid, v)| {
|
||||
let wl_surface = v.upgrade().ok()?;
|
||||
let popup_data = utils::get_data::<PopupData>(&wl_surface)?;
|
||||
let parent = utils::get_data::<SurfaceID>(&popup_data.parent())?
|
||||
.as_ref()
|
||||
.clone();
|
||||
let geometry = utils::get_data::<XdgSurfaceData>(&wl_surface)?
|
||||
.geometry
|
||||
.lock()
|
||||
.clone()?;
|
||||
Some((uid.clone(), ChildInfo { parent, geometry }))
|
||||
}))
|
||||
}
|
||||
|
||||
fn flush_client(&self) {
|
||||
let Some(client) = self.toplevel_wl_surface().and_then(|s| s.client()) else {
|
||||
return;
|
||||
};
|
||||
if let Some(client_state) = client.get_data::<ClientState>() {
|
||||
client_state.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for XdgBackend {
|
||||
fn drop(&mut self) {
|
||||
debug!("Dropped panel item gracefully");
|
||||
}
|
||||
}
|
||||
impl Backend for XdgBackend {
|
||||
fn start_data(&self) -> Result<PanelItemInitData> {
|
||||
let toplevel = self.toplevel_wl_surface();
|
||||
let toplevel_data = toplevel.as_ref().and_then(utils::get_data::<ToplevelData>);
|
||||
let toplevel_data = toplevel_data
|
||||
.as_deref()
|
||||
.clone()
|
||||
.ok_or_else(|| eyre!("Could not get toplevel"))?;
|
||||
|
||||
let pointer_grab = self.pointer_grab.lock().clone();
|
||||
let keyboard_grab = self.keyboard_grab.lock().clone();
|
||||
|
||||
Ok(PanelItemInitData {
|
||||
cursor: self.cursor.borrow().as_ref().and_then(|c| c.cursor_data()),
|
||||
toplevel: toplevel_data.into(),
|
||||
children: self.child_data(),
|
||||
pointer_grab,
|
||||
keyboard_grab,
|
||||
})
|
||||
}
|
||||
|
||||
fn apply_surface_material(&self, surface: SurfaceID, model_part: &Arc<ModelPart>) {
|
||||
let Some(wl_surface) = self.wl_surface_from_id(&surface) else {
|
||||
return;
|
||||
};
|
||||
let Some(core_surface) = CoreSurface::from_wl_surface(&wl_surface) else {
|
||||
return;
|
||||
};
|
||||
|
||||
core_surface.apply_material(model_part);
|
||||
}
|
||||
|
||||
fn close_toplevel(&self) {
|
||||
let Ok(xdg_toplevel) = self.toplevel.upgrade() else {
|
||||
return;
|
||||
};
|
||||
xdg_toplevel.close();
|
||||
}
|
||||
fn auto_size_toplevel(&self) {
|
||||
self.configure(Some([0, 0].into()));
|
||||
}
|
||||
fn set_toplevel_size(&self, size: Vector2<u32>) {
|
||||
self.configure(Some(size));
|
||||
}
|
||||
fn set_toplevel_focused_visuals(&self, focused: bool) {
|
||||
self.toplevel_state.lock().activated = focused;
|
||||
self.configure(None);
|
||||
}
|
||||
|
||||
fn pointer_motion(&self, surface: &SurfaceID, position: Vector2<f32>) {
|
||||
let Some(surface) = self.wl_surface_from_id(surface) else {
|
||||
return;
|
||||
};
|
||||
self.seat
|
||||
.pointer_event(&surface, PointerEvent::Motion(position));
|
||||
}
|
||||
fn pointer_button(&self, surface: &SurfaceID, button: u32, pressed: bool) {
|
||||
let Some(surface) = self.wl_surface_from_id(surface) else {
|
||||
return;
|
||||
};
|
||||
self.seat.pointer_event(
|
||||
&surface,
|
||||
PointerEvent::Button {
|
||||
button,
|
||||
state: if pressed { 1 } else { 0 },
|
||||
},
|
||||
)
|
||||
}
|
||||
fn pointer_scroll(
|
||||
&self,
|
||||
surface: &SurfaceID,
|
||||
scroll_distance: Option<Vector2<f32>>,
|
||||
scroll_steps: Option<Vector2<f32>>,
|
||||
) {
|
||||
let Some(surface) = self.wl_surface_from_id(surface) else {
|
||||
return;
|
||||
};
|
||||
self.seat.pointer_event(
|
||||
&surface,
|
||||
PointerEvent::Scroll {
|
||||
axis_continuous: scroll_distance,
|
||||
axis_discrete: scroll_steps,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn keyboard_keys(&self, surface: &SurfaceID, keymap_id: &str, keys: Vec<i32>) {
|
||||
let Some(surface) = self.wl_surface_from_id(surface) else {
|
||||
return;
|
||||
};
|
||||
let keymaps = KEYMAPS.lock();
|
||||
let Some(keymap) = keymaps.get(keymap_id).cloned() else {
|
||||
return;
|
||||
};
|
||||
if self.seat.set_keymap(keymap, vec![surface.clone()]).is_err() {
|
||||
return;
|
||||
}
|
||||
for key in keys {
|
||||
self.seat.keyboard_event(
|
||||
&surface,
|
||||
KeyboardEvent::Key {
|
||||
key: key.abs() as u32,
|
||||
state: key > 0,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn touch_down(&self, surface: &SurfaceID, id: u32, position: Vector2<f32>) {
|
||||
let Some(surface) = self.wl_surface_from_id(surface) else {
|
||||
return;
|
||||
};
|
||||
self.seat.touch_down(&surface, id, position)
|
||||
}
|
||||
fn touch_move(&self, id: u32, position: Vector2<f32>) {
|
||||
self.seat.touch_move(id, position)
|
||||
}
|
||||
fn touch_up(&self, id: u32) {
|
||||
self.seat.touch_up(id)
|
||||
}
|
||||
fn reset_touches(&self) {
|
||||
self.seat.reset_touches()
|
||||
}
|
||||
}
|
||||
69
src/wayland/xdg_shell/mod.rs
Normal file
69
src/wayland/xdg_shell/mod.rs
Normal file
@@ -0,0 +1,69 @@
|
||||
use self::{backend::XdgBackend, toplevel::ToplevelData};
|
||||
use super::state::WaylandState;
|
||||
use crate::wayland::{
|
||||
utils::insert_data,
|
||||
xdg_shell::{positioner::PositionerData, surface::XdgSurfaceData},
|
||||
};
|
||||
use parking_lot::Mutex;
|
||||
use smithay::reexports::{
|
||||
wayland_protocols::xdg::shell::server::xdg_wm_base::{self, XdgWmBase},
|
||||
wayland_server::{Client, DataInit, Dispatch, DisplayHandle, GlobalDispatch, New, Resource},
|
||||
};
|
||||
use tracing::debug;
|
||||
|
||||
mod backend;
|
||||
mod popup;
|
||||
mod positioner;
|
||||
mod surface;
|
||||
mod toplevel;
|
||||
|
||||
impl GlobalDispatch<XdgWmBase, (), WaylandState> for WaylandState {
|
||||
fn bind(
|
||||
_state: &mut WaylandState,
|
||||
_handle: &DisplayHandle,
|
||||
_client: &Client,
|
||||
resource: New<XdgWmBase>,
|
||||
_global_data: &(),
|
||||
data_init: &mut DataInit<'_, WaylandState>,
|
||||
) {
|
||||
data_init.init(resource, ());
|
||||
}
|
||||
}
|
||||
|
||||
impl Dispatch<XdgWmBase, (), WaylandState> for WaylandState {
|
||||
fn request(
|
||||
_state: &mut WaylandState,
|
||||
_client: &Client,
|
||||
_resource: &XdgWmBase,
|
||||
request: xdg_wm_base::Request,
|
||||
_data: &(),
|
||||
_dhandle: &DisplayHandle,
|
||||
data_init: &mut DataInit<'_, WaylandState>,
|
||||
) {
|
||||
match request {
|
||||
xdg_wm_base::Request::CreatePositioner { id } => {
|
||||
let positioner = data_init.init(id, Mutex::new(PositionerData::default()));
|
||||
debug!(?positioner, "Create XDG positioner");
|
||||
}
|
||||
xdg_wm_base::Request::GetXdgSurface { id, surface } => {
|
||||
let xdg_surface = data_init.init(id, surface.downgrade());
|
||||
debug!(?xdg_surface, "Create XDG surface");
|
||||
insert_data(
|
||||
&surface,
|
||||
XdgSurfaceData {
|
||||
wl_surface: surface.downgrade(),
|
||||
xdg_surface,
|
||||
geometry: Mutex::new(None),
|
||||
},
|
||||
);
|
||||
}
|
||||
xdg_wm_base::Request::Pong { serial } => {
|
||||
debug!(serial, "Client pong");
|
||||
}
|
||||
xdg_wm_base::Request::Destroy => {
|
||||
debug!("Destroy XDG WM base");
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
119
src/wayland/xdg_shell/popup.rs
Normal file
119
src/wayland/xdg_shell/popup.rs
Normal file
@@ -0,0 +1,119 @@
|
||||
use super::{backend::XdgBackend, positioner::PositionerData};
|
||||
use crate::{
|
||||
nodes::items::panel::{Geometry, PanelItem, SurfaceID},
|
||||
wayland::{state::WaylandState, utils::get_data},
|
||||
};
|
||||
use parking_lot::Mutex;
|
||||
use smithay::reexports::{
|
||||
wayland_protocols::xdg::shell::server::{
|
||||
xdg_popup::{self, XdgPopup},
|
||||
xdg_positioner::XdgPositioner,
|
||||
},
|
||||
wayland_server::{
|
||||
protocol::wl_surface::WlSurface, Client, DataInit, Dispatch, DisplayHandle, Resource,
|
||||
Weak as WlWeak,
|
||||
},
|
||||
};
|
||||
use std::sync::{Arc, Weak};
|
||||
use tracing::{debug, error};
|
||||
use wayland_backend::server::ClientId;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct PopupData {
|
||||
pub uid: String,
|
||||
grabbed: Mutex<bool>,
|
||||
parent: Mutex<WlWeak<WlSurface>>,
|
||||
panel_item: Weak<PanelItem<XdgBackend>>,
|
||||
positioner: Mutex<XdgPositioner>,
|
||||
}
|
||||
impl PopupData {
|
||||
pub fn new(
|
||||
uid: impl ToString,
|
||||
parent: WlSurface,
|
||||
panel_item: &Arc<PanelItem<XdgBackend>>,
|
||||
positioner: XdgPositioner,
|
||||
) -> Self {
|
||||
PopupData {
|
||||
uid: uid.to_string(),
|
||||
grabbed: Mutex::new(false),
|
||||
parent: Mutex::new(parent.downgrade()),
|
||||
panel_item: Arc::downgrade(panel_item),
|
||||
positioner: Mutex::new(positioner),
|
||||
}
|
||||
}
|
||||
pub fn geometry(&self) -> Option<Geometry> {
|
||||
let positioner = self.positioner.lock().clone();
|
||||
let positioner_data = positioner.data::<Mutex<PositionerData>>()?.lock();
|
||||
Some(positioner_data.clone().into())
|
||||
}
|
||||
pub fn parent(&self) -> WlSurface {
|
||||
self.parent.lock().upgrade().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl Dispatch<XdgPopup, WlWeak<WlSurface>, WaylandState> for WaylandState {
|
||||
fn request(
|
||||
_state: &mut WaylandState,
|
||||
_client: &Client,
|
||||
xdg_popup: &XdgPopup,
|
||||
request: xdg_popup::Request,
|
||||
wl_surface_resource: &WlWeak<WlSurface>,
|
||||
_dhandle: &DisplayHandle,
|
||||
_data_init: &mut DataInit<'_, WaylandState>,
|
||||
) {
|
||||
let Ok(wl_surface) = wl_surface_resource.upgrade() else {
|
||||
error!("Couldn't get the wayland surface of the xdg popup");
|
||||
return;
|
||||
};
|
||||
let Some(popup_data) = get_data::<PopupData>(&wl_surface) else {
|
||||
error!("Couldn't get the XdgPopup");
|
||||
return;
|
||||
};
|
||||
let Some(panel_item) = popup_data.panel_item.upgrade() else {
|
||||
error!("Couldn't get the panel item");
|
||||
return;
|
||||
};
|
||||
match request {
|
||||
xdg_popup::Request::Grab { seat, serial } => {
|
||||
*popup_data.grabbed.lock() = true;
|
||||
debug!(?xdg_popup, ?seat, serial, "XDG popup grab");
|
||||
panel_item.grab_keyboard(Some(SurfaceID::Child(popup_data.uid.clone())));
|
||||
}
|
||||
xdg_popup::Request::Reposition { positioner, token } => {
|
||||
debug!(?xdg_popup, ?positioner, token, "XDG popup reposition");
|
||||
*popup_data.positioner.lock() = positioner;
|
||||
panel_item
|
||||
.backend
|
||||
.reposition_popup(&panel_item, &popup_data);
|
||||
}
|
||||
xdg_popup::Request::Destroy => {
|
||||
debug!(?xdg_popup, "Destroy XDG popup");
|
||||
if *popup_data.grabbed.lock() {
|
||||
panel_item.grab_keyboard(None);
|
||||
}
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
fn destroyed(
|
||||
_state: &mut WaylandState,
|
||||
_client: ClientId,
|
||||
_popup: &XdgPopup,
|
||||
data: &WlWeak<WlSurface>,
|
||||
) {
|
||||
let Ok(wl_surface) = data.upgrade() else {
|
||||
error!("Couldn't get the wayland surface of the xdg popup");
|
||||
return;
|
||||
};
|
||||
let Some(popup_data) = get_data::<PopupData>(&wl_surface) else {
|
||||
error!("Couldn't get the XdgPopup");
|
||||
return;
|
||||
};
|
||||
let Some(panel_item) = popup_data.panel_item.upgrade() else {
|
||||
error!("Couldn't get the panel item");
|
||||
return;
|
||||
};
|
||||
panel_item.backend.drop_popup(&panel_item, &popup_data.uid);
|
||||
}
|
||||
}
|
||||
226
src/wayland/xdg_shell/positioner.rs
Normal file
226
src/wayland/xdg_shell/positioner.rs
Normal file
@@ -0,0 +1,226 @@
|
||||
use crate::{nodes::items::panel::Geometry, wayland::state::WaylandState};
|
||||
use mint::Vector2;
|
||||
use parking_lot::Mutex;
|
||||
use smithay::reexports::{
|
||||
wayland_protocols::xdg::shell::server::xdg_positioner::{
|
||||
self, Anchor, ConstraintAdjustment, Gravity, XdgPositioner,
|
||||
},
|
||||
wayland_server::{Client, DataInit, Dispatch, DisplayHandle, Resource},
|
||||
};
|
||||
use tracing::{debug, warn};
|
||||
use wayland_backend::protocol::WEnum;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct PositionerData {
|
||||
size: Vector2<u32>,
|
||||
anchor_rect_pos: Vector2<i32>,
|
||||
anchor_rect_size: Vector2<u32>,
|
||||
anchor: Anchor,
|
||||
gravity: Gravity,
|
||||
constraint_adjustment: ConstraintAdjustment,
|
||||
offset: Vector2<i32>,
|
||||
reactive: bool,
|
||||
}
|
||||
impl Default for PositionerData {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
size: Vector2::from([0; 2]),
|
||||
anchor_rect_pos: Vector2::from([0; 2]),
|
||||
anchor_rect_size: Vector2::from([0; 2]),
|
||||
anchor: Anchor::None,
|
||||
gravity: Gravity::None,
|
||||
constraint_adjustment: ConstraintAdjustment::None,
|
||||
offset: Vector2::from([0; 2]),
|
||||
reactive: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PositionerData {
|
||||
fn anchor_has_edge(&self, edge: Anchor) -> bool {
|
||||
match edge {
|
||||
Anchor::Top => {
|
||||
self.anchor == Anchor::Top
|
||||
|| self.anchor == Anchor::TopLeft
|
||||
|| self.anchor == Anchor::TopRight
|
||||
}
|
||||
Anchor::Bottom => {
|
||||
self.anchor == Anchor::Bottom
|
||||
|| self.anchor == Anchor::BottomLeft
|
||||
|| self.anchor == Anchor::BottomRight
|
||||
}
|
||||
Anchor::Left => {
|
||||
self.anchor == Anchor::Left
|
||||
|| self.anchor == Anchor::TopLeft
|
||||
|| self.anchor == Anchor::BottomLeft
|
||||
}
|
||||
Anchor::Right => {
|
||||
self.anchor == Anchor::Right
|
||||
|| self.anchor == Anchor::TopRight
|
||||
|| self.anchor == Anchor::BottomRight
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
fn gravity_has_edge(&self, edge: Gravity) -> bool {
|
||||
match edge {
|
||||
Gravity::Top => {
|
||||
self.gravity == Gravity::Top
|
||||
|| self.gravity == Gravity::TopLeft
|
||||
|| self.gravity == Gravity::TopRight
|
||||
}
|
||||
Gravity::Bottom => {
|
||||
self.gravity == Gravity::Bottom
|
||||
|| self.gravity == Gravity::BottomLeft
|
||||
|| self.gravity == Gravity::BottomRight
|
||||
}
|
||||
Gravity::Left => {
|
||||
self.gravity == Gravity::Left
|
||||
|| self.gravity == Gravity::TopLeft
|
||||
|| self.gravity == Gravity::BottomLeft
|
||||
}
|
||||
Gravity::Right => {
|
||||
self.gravity == Gravity::Right
|
||||
|| self.gravity == Gravity::TopRight
|
||||
|| self.gravity == Gravity::BottomRight
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_pos(&self) -> Vector2<i32> {
|
||||
let mut pos = self.offset;
|
||||
|
||||
if self.anchor_has_edge(Anchor::Top) {
|
||||
pos.y += self.anchor_rect_pos.y;
|
||||
} else if self.anchor_has_edge(Anchor::Bottom) {
|
||||
pos.y += self.anchor_rect_pos.y + self.anchor_rect_size.y as i32;
|
||||
} else {
|
||||
pos.y += self.anchor_rect_pos.y + self.anchor_rect_size.y as i32 / 2;
|
||||
}
|
||||
|
||||
if self.anchor_has_edge(Anchor::Left) {
|
||||
pos.x += self.anchor_rect_pos.x;
|
||||
} else if self.anchor_has_edge(Anchor::Right) {
|
||||
pos.x += self.anchor_rect_pos.x + self.anchor_rect_size.x as i32;
|
||||
} else {
|
||||
pos.x += self.anchor_rect_pos.x + self.anchor_rect_size.x as i32 / 2;
|
||||
}
|
||||
|
||||
if self.gravity_has_edge(Gravity::Top) {
|
||||
pos.y -= self.size.y as i32;
|
||||
} else if !self.gravity_has_edge(Gravity::Bottom) {
|
||||
pos.y -= self.size.y as i32 / 2;
|
||||
}
|
||||
|
||||
if self.gravity_has_edge(Gravity::Left) {
|
||||
pos.x -= self.size.x as i32;
|
||||
} else if !self.gravity_has_edge(Gravity::Right) {
|
||||
pos.x -= self.size.x as i32 / 2;
|
||||
}
|
||||
|
||||
pos
|
||||
}
|
||||
}
|
||||
impl From<PositionerData> for Geometry {
|
||||
fn from(value: PositionerData) -> Self {
|
||||
Geometry {
|
||||
origin: value.get_pos(),
|
||||
size: value.size,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Dispatch<XdgPositioner, Mutex<PositionerData>, WaylandState> for WaylandState {
|
||||
fn request(
|
||||
_state: &mut WaylandState,
|
||||
_client: &Client,
|
||||
positioner: &XdgPositioner,
|
||||
request: xdg_positioner::Request,
|
||||
data: &Mutex<PositionerData>,
|
||||
_dhandle: &DisplayHandle,
|
||||
_data_init: &mut DataInit<'_, WaylandState>,
|
||||
) {
|
||||
match request {
|
||||
xdg_positioner::Request::SetSize { width, height } => {
|
||||
debug!(?positioner, width, height, "Set positioner size");
|
||||
data.lock().size = Vector2::from([width as u32, height as u32]);
|
||||
}
|
||||
xdg_positioner::Request::SetAnchorRect {
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
} => {
|
||||
if width < 1 || height < 1 {
|
||||
positioner.post_error(
|
||||
xdg_positioner::Error::InvalidInput,
|
||||
"Invalid size for positioner's anchor rectangle.",
|
||||
);
|
||||
warn!(
|
||||
?positioner,
|
||||
width, height, "Invalid size for positioner's anchor rectangle"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
debug!(
|
||||
?positioner,
|
||||
x, y, width, height, "Set positioner anchor rectangle"
|
||||
);
|
||||
let mut data = data.lock();
|
||||
data.anchor_rect_pos = [x, y].into();
|
||||
data.anchor_rect_size = [width as u32, height as u32].into();
|
||||
}
|
||||
xdg_positioner::Request::SetAnchor { anchor } => {
|
||||
if let WEnum::Value(anchor) = anchor {
|
||||
debug!(?positioner, ?anchor, "Set positioner anchor");
|
||||
data.lock().anchor = anchor;
|
||||
}
|
||||
}
|
||||
xdg_positioner::Request::SetGravity { gravity } => {
|
||||
if let WEnum::Value(gravity) = gravity {
|
||||
debug!(?positioner, ?gravity, "Set positioner gravity");
|
||||
data.lock().gravity = gravity;
|
||||
}
|
||||
}
|
||||
xdg_positioner::Request::SetConstraintAdjustment {
|
||||
constraint_adjustment,
|
||||
} => {
|
||||
debug!(
|
||||
?positioner,
|
||||
constraint_adjustment, "Set positioner constraint adjustment"
|
||||
);
|
||||
let Some(constraint_adjustment) =
|
||||
ConstraintAdjustment::from_bits(constraint_adjustment)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
data.lock().constraint_adjustment = constraint_adjustment;
|
||||
}
|
||||
xdg_positioner::Request::SetOffset { x, y } => {
|
||||
debug!(?positioner, x, y, "Set positioner offset");
|
||||
data.lock().offset = [x, y].into();
|
||||
}
|
||||
xdg_positioner::Request::SetReactive => {
|
||||
debug!(?positioner, "Set positioner reactive");
|
||||
data.lock().reactive = true;
|
||||
}
|
||||
xdg_positioner::Request::SetParentSize {
|
||||
parent_width,
|
||||
parent_height,
|
||||
} => {
|
||||
debug!(
|
||||
?positioner,
|
||||
parent_width, parent_height, "Set positioner parent size"
|
||||
);
|
||||
}
|
||||
xdg_positioner::Request::SetParentConfigure { serial } => {
|
||||
debug!(?positioner, serial, "Set positioner parent size");
|
||||
}
|
||||
xdg_positioner::Request::Destroy => (),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
236
src/wayland/xdg_shell/surface.rs
Normal file
236
src/wayland/xdg_shell/surface.rs
Normal file
@@ -0,0 +1,236 @@
|
||||
use crate::{
|
||||
nodes::items::panel::{Geometry, PanelItem, SurfaceID},
|
||||
wayland::{
|
||||
seat::handle_cursor,
|
||||
state::{ClientState, WaylandState},
|
||||
surface::CoreSurface,
|
||||
utils,
|
||||
xdg_shell::{popup::PopupData, toplevel::ToplevelData, XdgBackend},
|
||||
SERIAL_COUNTER,
|
||||
},
|
||||
};
|
||||
use nanoid::nanoid;
|
||||
use parking_lot::Mutex;
|
||||
use smithay::reexports::{
|
||||
wayland_protocols::xdg::shell::server::{
|
||||
xdg_surface::{self, XdgSurface},
|
||||
xdg_toplevel::{XdgToplevel, EVT_WM_CAPABILITIES_SINCE},
|
||||
},
|
||||
wayland_server::{
|
||||
protocol::wl_surface::WlSurface, Client, DataInit, Dispatch, DisplayHandle, Resource,
|
||||
Weak as WlWeak,
|
||||
},
|
||||
};
|
||||
use std::sync::{Arc, Weak};
|
||||
use tracing::{debug, error};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct XdgSurfaceData {
|
||||
pub wl_surface: WlWeak<WlSurface>,
|
||||
pub xdg_surface: XdgSurface,
|
||||
pub geometry: Mutex<Option<Geometry>>,
|
||||
}
|
||||
|
||||
impl Dispatch<XdgSurface, WlWeak<WlSurface>, WaylandState> for WaylandState {
|
||||
fn request(
|
||||
state: &mut WaylandState,
|
||||
client: &Client,
|
||||
xdg_surface: &XdgSurface,
|
||||
request: xdg_surface::Request,
|
||||
wl_surface_resource: &WlWeak<WlSurface>,
|
||||
_dhandle: &DisplayHandle,
|
||||
data_init: &mut DataInit<'_, WaylandState>,
|
||||
) {
|
||||
let Ok(wl_surface) = wl_surface_resource.upgrade() else {
|
||||
error!("Couldn't get the wayland surface of the xdg surface");
|
||||
return;
|
||||
};
|
||||
let Some(xdg_surface_data) = utils::get_data::<XdgSurfaceData>(&wl_surface) else {
|
||||
error!("Couldn't get the XdgSurface");
|
||||
return;
|
||||
};
|
||||
match request {
|
||||
xdg_surface::Request::GetToplevel { id } => {
|
||||
let toplevel = data_init.init(id, wl_surface_resource.clone());
|
||||
utils::insert_data(&wl_surface, SurfaceID::Toplevel);
|
||||
utils::insert_data(&wl_surface, toplevel.clone());
|
||||
utils::insert_data(&wl_surface, ToplevelData::new(&wl_surface));
|
||||
debug!(?toplevel, ?xdg_surface, "Create XDG toplevel");
|
||||
|
||||
if toplevel.version() >= EVT_WM_CAPABILITIES_SINCE {
|
||||
toplevel.wm_capabilities(vec![3]);
|
||||
}
|
||||
toplevel.configure(
|
||||
0,
|
||||
0,
|
||||
if toplevel.version() >= 2 {
|
||||
vec![1, 5, 6, 7, 8]
|
||||
.into_iter()
|
||||
.flat_map(u32::to_ne_bytes)
|
||||
.collect()
|
||||
} else {
|
||||
vec![]
|
||||
},
|
||||
);
|
||||
xdg_surface.configure(SERIAL_COUNTER.inc());
|
||||
|
||||
let client_credentials = client.get_credentials(&state.display_handle).ok();
|
||||
let Some(seat_data) = client.get_data::<ClientState>().map(|s| s.seat.clone())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
let xdg_surface = xdg_surface.clone();
|
||||
CoreSurface::add_to(
|
||||
state.display_handle.clone(),
|
||||
&wl_surface,
|
||||
{
|
||||
let wl_surface_resource = wl_surface_resource.clone();
|
||||
move || {
|
||||
let wl_surface = wl_surface_resource.upgrade().unwrap();
|
||||
|
||||
let backend = XdgBackend::create(
|
||||
wl_surface.clone(),
|
||||
toplevel.clone(),
|
||||
seat_data.clone(),
|
||||
);
|
||||
let (node, panel_item) = PanelItem::create(
|
||||
Box::new(backend),
|
||||
client_credentials.map(|c| c.pid),
|
||||
);
|
||||
utils::insert_data(&wl_surface, Arc::downgrade(&panel_item));
|
||||
utils::insert_data_raw(&wl_surface, node);
|
||||
handle_cursor(&panel_item, panel_item.backend.cursor.clone());
|
||||
}
|
||||
},
|
||||
{
|
||||
let wl_surface_resource = wl_surface_resource.clone();
|
||||
move |_| {
|
||||
let wl_surface = wl_surface_resource.upgrade().unwrap();
|
||||
|
||||
let Some(panel_item) =
|
||||
utils::get_data::<PanelItem<XdgBackend>>(&wl_surface)
|
||||
else {
|
||||
let Some(toplevel) = utils::get_data::<XdgToplevel>(&wl_surface)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
// if the wayland toplevel isn't mapped, hammer it again with a configure until it cooperates
|
||||
toplevel.configure(
|
||||
0,
|
||||
0,
|
||||
if toplevel.version() >= 2 {
|
||||
vec![5, 6, 7, 8]
|
||||
.into_iter()
|
||||
.flat_map(u32::to_ne_bytes)
|
||||
.collect()
|
||||
} else {
|
||||
vec![]
|
||||
},
|
||||
);
|
||||
xdg_surface.configure(SERIAL_COUNTER.inc());
|
||||
return;
|
||||
};
|
||||
let Some(core_surface) = CoreSurface::from_wl_surface(&wl_surface)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let Some(size) = core_surface.size() else {
|
||||
return;
|
||||
};
|
||||
panel_item.toplevel_size_changed(size);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
xdg_surface::Request::GetPopup {
|
||||
id,
|
||||
parent,
|
||||
positioner,
|
||||
} => {
|
||||
let Some(parent) = parent else { return };
|
||||
let Some(parent_wl_surface) = parent
|
||||
.data::<WlWeak<WlSurface>>()
|
||||
.map(WlWeak::upgrade)
|
||||
.map(Result::ok)
|
||||
.flatten()
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let Some(panel_item) =
|
||||
utils::get_data::<Weak<PanelItem<XdgBackend>>>(&parent_wl_surface)
|
||||
.as_deref()
|
||||
.and_then(Weak::upgrade)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
let uid = nanoid!();
|
||||
let popup_data = PopupData::new(
|
||||
uid.clone(),
|
||||
parent_wl_surface.clone(),
|
||||
&panel_item,
|
||||
positioner,
|
||||
);
|
||||
handle_cursor(
|
||||
&panel_item,
|
||||
panel_item.backend.seat.new_surface(&wl_surface),
|
||||
);
|
||||
let xdg_popup = data_init.init(id, wl_surface.downgrade());
|
||||
utils::insert_data(&wl_surface, SurfaceID::Child(uid));
|
||||
utils::insert_data(&wl_surface, Arc::downgrade(&panel_item));
|
||||
utils::insert_data(&wl_surface, popup_data);
|
||||
utils::insert_data(&wl_surface, xdg_popup.clone());
|
||||
debug!(?xdg_popup, ?xdg_surface, "Create XDG popup");
|
||||
|
||||
let xdg_surface = xdg_surface.downgrade();
|
||||
let popup_wl_surface = wl_surface.downgrade();
|
||||
CoreSurface::add_to(
|
||||
state.display_handle.clone(),
|
||||
&wl_surface,
|
||||
move || {
|
||||
let Ok(wl_surface) = popup_wl_surface.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let Some(popup_data) = utils::get_data::<PopupData>(&wl_surface) else {
|
||||
return;
|
||||
};
|
||||
panel_item
|
||||
.backend
|
||||
.new_popup(&panel_item, &wl_surface, &*popup_data);
|
||||
},
|
||||
move |commit_count| {
|
||||
if commit_count == 0 {
|
||||
if let Ok(xdg_surface) = xdg_surface.upgrade() {
|
||||
xdg_surface.configure(SERIAL_COUNTER.inc())
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
xdg_surface::Request::SetWindowGeometry {
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
} => {
|
||||
debug!(
|
||||
?xdg_surface,
|
||||
x, y, width, height, "Set XDG surface geometry"
|
||||
);
|
||||
let geometry = Geometry {
|
||||
origin: [x, y].into(),
|
||||
size: [width as u32, height as u32].into(),
|
||||
};
|
||||
xdg_surface_data.geometry.lock().replace(geometry);
|
||||
}
|
||||
xdg_surface::Request::AckConfigure { serial } => {
|
||||
debug!(?xdg_surface, serial, "Acknowledge XDG surface configure");
|
||||
}
|
||||
xdg_surface::Request::Destroy => {
|
||||
debug!(?xdg_surface, "Destroy XDG surface");
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
239
src/wayland/xdg_shell/toplevel.rs
Normal file
239
src/wayland/xdg_shell/toplevel.rs
Normal file
@@ -0,0 +1,239 @@
|
||||
use super::{backend::XdgBackend, surface::XdgSurfaceData};
|
||||
use crate::{
|
||||
nodes::items::panel::{Geometry, PanelItem, ToplevelInfo},
|
||||
wayland::{
|
||||
state::WaylandState,
|
||||
surface::CoreSurface,
|
||||
utils::{self, get_data},
|
||||
},
|
||||
};
|
||||
use mint::Vector2;
|
||||
use once_cell::sync::OnceCell;
|
||||
use parking_lot::Mutex;
|
||||
use smithay::reexports::{
|
||||
wayland_protocols::xdg::shell::server::xdg_toplevel::{self, ResizeEdge, XdgToplevel},
|
||||
wayland_server::{
|
||||
protocol::wl_surface::WlSurface, Client, DataInit, Dispatch, DisplayHandle, Resource,
|
||||
Weak as WlWeak,
|
||||
},
|
||||
};
|
||||
use std::sync::Weak;
|
||||
use tracing::{debug, error};
|
||||
use wayland_backend::protocol::WEnum;
|
||||
|
||||
pub struct ToplevelData {
|
||||
panel_item: OnceCell<Weak<PanelItem<XdgBackend>>>,
|
||||
wl_surface: WlWeak<WlSurface>,
|
||||
parent: Mutex<Option<WlWeak<WlSurface>>>,
|
||||
title: Mutex<Option<String>>,
|
||||
app_id: Mutex<Option<String>>,
|
||||
max_size: Mutex<Option<Vector2<u32>>>,
|
||||
min_size: Mutex<Option<Vector2<u32>>>,
|
||||
}
|
||||
impl ToplevelData {
|
||||
pub fn new(wl_surface: &WlSurface) -> Self {
|
||||
ToplevelData {
|
||||
panel_item: OnceCell::new(),
|
||||
wl_surface: wl_surface.downgrade(),
|
||||
parent: Mutex::new(None),
|
||||
title: Mutex::new(None),
|
||||
app_id: Mutex::new(None),
|
||||
max_size: Mutex::new(None),
|
||||
min_size: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
pub fn parent(&self) -> Option<WlSurface> {
|
||||
self.parent
|
||||
.lock()
|
||||
.as_ref()
|
||||
.map(WlWeak::upgrade)
|
||||
.map(Result::ok)
|
||||
.flatten()
|
||||
}
|
||||
}
|
||||
impl From<&ToplevelData> for ToplevelInfo {
|
||||
fn from(value: &ToplevelData) -> Self {
|
||||
let wl_surface = value.wl_surface.upgrade().ok();
|
||||
let size = CoreSurface::from_wl_surface(wl_surface.as_ref().unwrap())
|
||||
.unwrap()
|
||||
.size()
|
||||
.unwrap();
|
||||
let logical_rectangle = wl_surface
|
||||
.as_ref()
|
||||
.and_then(utils::get_data::<XdgSurfaceData>)
|
||||
.and_then(|d| d.geometry.lock().clone())
|
||||
.unwrap_or_else(|| Geometry {
|
||||
origin: [0, 0].into(),
|
||||
size,
|
||||
});
|
||||
let parent = value
|
||||
.parent()
|
||||
.as_ref()
|
||||
.and_then(utils::get_data::<Weak<PanelItem<XdgBackend>>>)
|
||||
.as_deref()
|
||||
.and_then(Weak::upgrade)
|
||||
.map(|i| i.uid.clone());
|
||||
ToplevelInfo {
|
||||
parent,
|
||||
title: value.title.lock().clone(),
|
||||
app_id: value.app_id.lock().clone(),
|
||||
size,
|
||||
min_size: value.min_size.lock().clone(),
|
||||
max_size: value.max_size.lock().clone(),
|
||||
logical_rectangle,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for ToplevelData {
|
||||
fn drop(&mut self) {
|
||||
// let Some(panel_item) = self.panel_item.get().and_then(Weak::upgrade) else {
|
||||
// return;
|
||||
// };
|
||||
// panel_item.drop_toplevel();
|
||||
}
|
||||
}
|
||||
|
||||
impl Dispatch<XdgToplevel, WlWeak<WlSurface>, WaylandState> for WaylandState {
|
||||
fn request(
|
||||
_state: &mut WaylandState,
|
||||
_client: &Client,
|
||||
xdg_toplevel: &XdgToplevel,
|
||||
request: xdg_toplevel::Request,
|
||||
wl_surface_resource: &WlWeak<WlSurface>,
|
||||
_dhandle: &DisplayHandle,
|
||||
_data_init: &mut DataInit<'_, WaylandState>,
|
||||
) {
|
||||
let Ok(wl_surface) = wl_surface_resource.upgrade() else {
|
||||
error!("Couldn't get the wayland surface of the xdg toplevel");
|
||||
return;
|
||||
};
|
||||
let Some(toplevel_data) = utils::get_data::<ToplevelData>(&wl_surface) else {
|
||||
error!("Couldn't get the XdgToplevel");
|
||||
return;
|
||||
};
|
||||
match request {
|
||||
xdg_toplevel::Request::SetParent { parent } => {
|
||||
debug!(?xdg_toplevel, ?parent, "Set XDG Toplevel parent");
|
||||
let Some(parent_xdg_toplevel) = parent else {
|
||||
*toplevel_data.parent.lock() = None;
|
||||
return;
|
||||
};
|
||||
let Some(parent_toplevel_data) = parent_xdg_toplevel.data::<ToplevelData>() else {
|
||||
error!("Couldn't get XDG toplevel parent data");
|
||||
return;
|
||||
};
|
||||
let Ok(parent_wl_surface) = parent_toplevel_data.wl_surface.upgrade() else {
|
||||
error!("Couldn't get XDG toplevel parent wl surface");
|
||||
return;
|
||||
};
|
||||
*toplevel_data.parent.lock() = Some(parent_wl_surface.downgrade());
|
||||
let Some(parent_panel_item) = parent_toplevel_data
|
||||
.panel_item
|
||||
.get()
|
||||
.and_then(Weak::upgrade)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let Some(panel_item) = get_data::<PanelItem<XdgBackend>>(&wl_surface) else {
|
||||
error!("Couldn't get the panel item");
|
||||
return;
|
||||
};
|
||||
panel_item.toplevel_parent_changed(&parent_panel_item.uid);
|
||||
}
|
||||
xdg_toplevel::Request::SetTitle { title } => {
|
||||
debug!(?xdg_toplevel, ?title, "Set XDG Toplevel title");
|
||||
*toplevel_data.title.lock() = (!title.is_empty()).then_some(title.clone());
|
||||
let Some(panel_item) = get_data::<PanelItem<XdgBackend>>(&wl_surface) else {
|
||||
error!("Couldn't get the panel item");
|
||||
return;
|
||||
};
|
||||
panel_item.toplevel_title_changed(&title);
|
||||
}
|
||||
xdg_toplevel::Request::SetAppId { app_id } => {
|
||||
debug!(?xdg_toplevel, ?app_id, "Set XDG Toplevel app ID");
|
||||
*toplevel_data.app_id.lock() = (!app_id.is_empty()).then_some(app_id.clone());
|
||||
let Some(panel_item) = get_data::<PanelItem<XdgBackend>>(&wl_surface) else {
|
||||
error!("Couldn't get the panel item");
|
||||
return;
|
||||
};
|
||||
panel_item.toplevel_app_id_changed(&app_id);
|
||||
}
|
||||
xdg_toplevel::Request::Move { seat, serial } => {
|
||||
debug!(?xdg_toplevel, ?seat, serial, "XDG Toplevel move request");
|
||||
let Some(panel_item) = get_data::<PanelItem<XdgBackend>>(&wl_surface) else {
|
||||
error!("Couldn't get the panel item");
|
||||
return;
|
||||
};
|
||||
panel_item.toplevel_move_request();
|
||||
}
|
||||
xdg_toplevel::Request::Resize {
|
||||
seat,
|
||||
serial,
|
||||
edges,
|
||||
} => {
|
||||
let WEnum::Value(edges) = edges else { return };
|
||||
debug!(
|
||||
?xdg_toplevel,
|
||||
?seat,
|
||||
serial,
|
||||
?edges,
|
||||
"XDG Toplevel resize request"
|
||||
);
|
||||
let (up, down, left, right) = match edges {
|
||||
ResizeEdge::Top => (true, false, false, false),
|
||||
ResizeEdge::Bottom => (false, true, false, false),
|
||||
ResizeEdge::Left => (false, false, true, false),
|
||||
ResizeEdge::TopLeft => (true, false, true, false),
|
||||
ResizeEdge::BottomLeft => (false, true, true, false),
|
||||
ResizeEdge::Right => (false, false, false, true),
|
||||
ResizeEdge::TopRight => (true, false, false, true),
|
||||
ResizeEdge::BottomRight => (false, true, false, true),
|
||||
_ => (false, false, false, false),
|
||||
};
|
||||
let Some(panel_item) = get_data::<PanelItem<XdgBackend>>(&wl_surface) else {
|
||||
error!("Couldn't get the panel item");
|
||||
return;
|
||||
};
|
||||
panel_item.toplevel_resize_request(up, down, left, right)
|
||||
}
|
||||
xdg_toplevel::Request::SetMaxSize { width, height } => {
|
||||
debug!(?xdg_toplevel, width, height, "Set XDG Toplevel max size");
|
||||
*toplevel_data.max_size.lock() = (width > 1 || height > 1)
|
||||
.then_some(Vector2::from([width as u32, height as u32]));
|
||||
}
|
||||
xdg_toplevel::Request::SetMinSize { width, height } => {
|
||||
debug!(?xdg_toplevel, width, height, "Set XDG Toplevel min size");
|
||||
*toplevel_data.min_size.lock() = (width > 1 || height > 1)
|
||||
.then_some(Vector2::from([width as u32, height as u32]));
|
||||
}
|
||||
xdg_toplevel::Request::SetFullscreen { output: _ } => {
|
||||
let Some(panel_item) = get_data::<PanelItem<XdgBackend>>(&wl_surface) else {
|
||||
error!("Couldn't get the panel item");
|
||||
return;
|
||||
};
|
||||
panel_item.backend.toplevel_state.lock().fullscreen = true;
|
||||
panel_item.backend.configure(None);
|
||||
panel_item.toplevel_fullscreen_active(true);
|
||||
}
|
||||
xdg_toplevel::Request::UnsetFullscreen => {
|
||||
let Some(panel_item) = get_data::<PanelItem<XdgBackend>>(&wl_surface) else {
|
||||
error!("Couldn't get the panel item");
|
||||
return;
|
||||
};
|
||||
panel_item.backend.toplevel_state.lock().fullscreen = false;
|
||||
panel_item.backend.configure(None);
|
||||
panel_item.toplevel_fullscreen_active(false);
|
||||
}
|
||||
xdg_toplevel::Request::Destroy => {
|
||||
debug!(?xdg_toplevel, "Destroy XDG Toplevel");
|
||||
let Some(panel_item) = get_data::<PanelItem<XdgBackend>>(&wl_surface) else {
|
||||
error!("Couldn't get the panel item");
|
||||
return;
|
||||
};
|
||||
panel_item.backend.seat.drop_surface(&wl_surface);
|
||||
panel_item.drop_toplevel();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
267
src/wayland/xwayland_rootful.rs
Normal file
267
src/wayland/xwayland_rootful.rs
Normal file
@@ -0,0 +1,267 @@
|
||||
use crate::core::{client::get_env, task};
|
||||
use crate::STOP_NOTIFIER;
|
||||
use smithay::reexports::rustix;
|
||||
use smithay::reexports::rustix::io::{fcntl_setfd, Errno, FdFlags};
|
||||
use smithay::reexports::rustix::net::SocketAddrUnix;
|
||||
use std::io::{Read, Write};
|
||||
use std::{
|
||||
io::ErrorKind,
|
||||
os::{
|
||||
fd::{AsRawFd, BorrowedFd, RawFd},
|
||||
unix::process::CommandExt,
|
||||
},
|
||||
process::{ChildStdout, Command, Stdio},
|
||||
};
|
||||
use tokio::net::{UnixListener, UnixStream};
|
||||
use tokio::task::AbortHandle;
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
use super::X_DISPLAY;
|
||||
|
||||
pub fn start_xwayland(wayland_socket: RawFd) -> std::io::Result<X11Lock> {
|
||||
let (mut lock, listener) = bind_socket()?;
|
||||
|
||||
let abort_handle = task::new(|| "X11 Client Acceptor", async move {
|
||||
loop {
|
||||
let Ok((stream, _)) = tokio::select! {
|
||||
_ = STOP_NOTIFIER.notified() => break,
|
||||
e = listener.accept() => e,
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let Ok((x_wm_x11, _x_wm_me)) = UnixStream::pair() else {
|
||||
continue;
|
||||
};
|
||||
let Ok(env) = stream
|
||||
.peer_cred()
|
||||
.and_then(|c| c.pid().ok_or(ErrorKind::Other.into()))
|
||||
.and_then(get_env)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let _ = spawn_xwayland(
|
||||
lock.display,
|
||||
wayland_socket,
|
||||
x_wm_x11,
|
||||
stream.as_raw_fd(),
|
||||
env.get("STARDUST_STARTUP_TOKEN").cloned(),
|
||||
);
|
||||
}
|
||||
})
|
||||
.map_err(|_| ErrorKind::Other)?
|
||||
.abort_handle();
|
||||
lock.x_abort_handle.replace(abort_handle);
|
||||
let _ = X_DISPLAY.set(lock.display);
|
||||
Ok(lock)
|
||||
}
|
||||
|
||||
/// Find a free X11 display slot and setup
|
||||
pub(crate) fn bind_socket() -> Result<(X11Lock, UnixListener), std::io::Error> {
|
||||
for d in 0..33 {
|
||||
// if fails, try the next one
|
||||
if let Ok(lock) = X11Lock::grab(d) {
|
||||
// we got a lockfile, try and create the socket
|
||||
match open_x11_socket_for_display(d) {
|
||||
Ok(socket) => return Ok((lock, socket)),
|
||||
Err(err) => warn!(display = d, "Failed to create sockets: {}", err),
|
||||
}
|
||||
}
|
||||
}
|
||||
// If we reach here, all values from 0 to 32 failed
|
||||
// we need to stop trying at some point
|
||||
|
||||
Err(std::io::Error::new(
|
||||
std::io::ErrorKind::AddrInUse,
|
||||
"Could not find a free socket for the XServer.",
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct X11Lock {
|
||||
display: u32,
|
||||
x_abort_handle: Option<AbortHandle>,
|
||||
}
|
||||
|
||||
impl X11Lock {
|
||||
/// Try to grab a lockfile for given X display number
|
||||
fn grab(number: u32) -> Result<X11Lock, ()> {
|
||||
debug!(display = number, "Attempting to aquire an X11 display lock");
|
||||
let filename = format!("/tmp/.X{}-lock", number);
|
||||
let lockfile = ::std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&filename);
|
||||
match lockfile {
|
||||
Ok(mut file) => {
|
||||
// we got it, write our PID in it and we're good
|
||||
let ret = file.write_fmt(format_args!(
|
||||
"{:>10}\n",
|
||||
rustix::process::Pid::as_raw(Some(rustix::process::getpid()))
|
||||
));
|
||||
if ret.is_err() {
|
||||
// write to the file failed ? we abandon
|
||||
::std::mem::drop(file);
|
||||
let _ = ::std::fs::remove_file(&filename);
|
||||
Err(())
|
||||
} else {
|
||||
debug!(display = number, "X11 lock acquired");
|
||||
// we got the lockfile and wrote our pid to it, all is good
|
||||
Ok(X11Lock {
|
||||
display: number,
|
||||
x_abort_handle: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
debug!(display = number, "Failed to acquire lock");
|
||||
// we could not open the file, now we try to read it
|
||||
// and if it contains the pid of a process that no longer
|
||||
// exist (so if a previous x server claimed it and did not
|
||||
// exit gracefully and remove it), we claim it
|
||||
// if we can't open it, give up
|
||||
let mut file = ::std::fs::File::open(&filename).map_err(|_| ())?;
|
||||
let mut spid = [0u8; 11];
|
||||
file.read_exact(&mut spid).map_err(|_| ())?;
|
||||
::std::mem::drop(file);
|
||||
let pid = rustix::process::Pid::from_raw(
|
||||
::std::str::from_utf8(&spid)
|
||||
.map_err(|_| ())?
|
||||
.trim()
|
||||
.parse::<i32>()
|
||||
.map_err(|_| ())?,
|
||||
)
|
||||
.ok_or(())?;
|
||||
if let Err(Errno::SRCH) = rustix::process::test_kill_process(pid) {
|
||||
// no process whose pid equals the contents of the lockfile exists
|
||||
// remove the lockfile and try grabbing it again
|
||||
if let Ok(()) = ::std::fs::remove_file(filename) {
|
||||
debug!(
|
||||
display = number,
|
||||
"Lock was blocked by a defunct X11 server, trying again"
|
||||
);
|
||||
return X11Lock::grab(number);
|
||||
} else {
|
||||
// we could not remove the lockfile, abort
|
||||
return Err(());
|
||||
}
|
||||
}
|
||||
// if we reach here, this lockfile exists and is probably in use, give up
|
||||
Err(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn display(&self) -> u32 {
|
||||
self.display
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for X11Lock {
|
||||
fn drop(&mut self) {
|
||||
info!("Cleaning up X11 lock.");
|
||||
// Cleanup all the X11 files
|
||||
if let Err(e) = ::std::fs::remove_file(format!("/tmp/.X11-unix/X{}", self.display)) {
|
||||
warn!(error = ?e, "Failed to remove X11 socket");
|
||||
}
|
||||
if let Err(e) = ::std::fs::remove_file(format!("/tmp/.X{}-lock", self.display)) {
|
||||
warn!(error = ?e, "Failed to remove X11 lockfile");
|
||||
}
|
||||
if let Some(join_handle) = self.x_abort_handle.take() {
|
||||
join_handle.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Open the two unix sockets an X server listens on
|
||||
///
|
||||
/// Should only be done after the associated lockfile is acquired!
|
||||
fn open_x11_socket_for_display(display: u32) -> rustix::io::Result<UnixListener> {
|
||||
let path = format!("/tmp/.X11-unix/X{}", display);
|
||||
let _ = ::std::fs::remove_file(&path);
|
||||
// We know this path is not too long, these unwrap cannot fail
|
||||
let fs_addr = SocketAddrUnix::new(path.as_bytes()).unwrap();
|
||||
open_socket(fs_addr)
|
||||
}
|
||||
|
||||
/// Open an unix socket for listening and bind it to given path
|
||||
fn open_socket(addr: SocketAddrUnix) -> rustix::io::Result<UnixListener> {
|
||||
// create an unix stream socket
|
||||
let fd = rustix::net::socket_with(
|
||||
rustix::net::AddressFamily::UNIX,
|
||||
rustix::net::SocketType::STREAM,
|
||||
rustix::net::SocketFlags::CLOEXEC,
|
||||
None,
|
||||
)?;
|
||||
// bind it to requested address
|
||||
rustix::net::bind_unix(&fd, &addr)?;
|
||||
rustix::net::listen(&fd, 1)?;
|
||||
Ok(UnixListener::from_std(std::os::unix::net::UnixListener::from(fd)).unwrap())
|
||||
}
|
||||
|
||||
fn spawn_xwayland(
|
||||
display: u32,
|
||||
wayland_socket: RawFd,
|
||||
wm_socket: UnixStream,
|
||||
listen_socket: RawFd,
|
||||
stardust_startup_token: Option<String>,
|
||||
) -> std::io::Result<ChildStdout> {
|
||||
let mut command = Command::new("sh");
|
||||
|
||||
// We use output stream to communicate because FD is easier to handle than exit code.
|
||||
command.stdout(Stdio::piped());
|
||||
|
||||
let mut xwayland_args = format!(":{} -geometry 1920x1080", display);
|
||||
xwayland_args.push_str(&format!(" -listenfd {}", listen_socket));
|
||||
|
||||
// This command let sh to:
|
||||
// * Set up signal handler for USR1
|
||||
// * Launch Xwayland with USR1 ignored so Xwayland will signal us when it is ready (also redirect
|
||||
// Xwayland's STDOUT to STDERR so its output, if any, won't distract us)
|
||||
// * Print "S" and exit if USR1 is received
|
||||
command.arg("-c").arg(format!(
|
||||
"trap 'echo S' USR1; (trap '' USR1; exec Xwayland {}) 1>&2 & wait",
|
||||
xwayland_args
|
||||
));
|
||||
|
||||
// Setup the environment: clear everything except PATH and XDG_RUNTIME_DIR
|
||||
command.env_clear();
|
||||
for (key, value) in std::env::vars_os() {
|
||||
if key.to_str() == Some("PATH") || key.to_str() == Some("XDG_RUNTIME_DIR") {
|
||||
command.env(key, value);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
command.env("WAYLAND_SOCKET", format!("{}", wayland_socket.as_raw_fd()));
|
||||
command.env(
|
||||
"STARDUST_STARTUP_TOKEN",
|
||||
stardust_startup_token.unwrap_or_default(),
|
||||
);
|
||||
|
||||
unsafe {
|
||||
let wayland_socket_fd = wayland_socket.as_raw_fd();
|
||||
let wm_socket_fd = wm_socket.as_raw_fd();
|
||||
command.pre_exec(move || {
|
||||
// unset the CLOEXEC flag from the sockets we need to pass
|
||||
// to xwayland
|
||||
unset_cloexec(wayland_socket_fd)?;
|
||||
unset_cloexec(wm_socket_fd)?;
|
||||
unset_cloexec(listen_socket)?;
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
|
||||
let mut child = command.spawn()?;
|
||||
Ok(child.stdout.take().expect("stdout should be piped"))
|
||||
}
|
||||
|
||||
/// Remove the `O_CLOEXEC` flag from this `Fd`
|
||||
///
|
||||
/// This means that the `Fd` will *not* be automatically
|
||||
/// closed when we `exec()` into XWayland
|
||||
unsafe fn unset_cloexec(fd: RawFd) -> std::io::Result<()> {
|
||||
let fd = BorrowedFd::borrow_raw(fd);
|
||||
fcntl_setfd(fd, FdFlags::empty())?;
|
||||
Ok(())
|
||||
}
|
||||
430
src/wayland/xwayland_rootless.rs
Normal file
430
src/wayland/xwayland_rootless.rs
Normal file
@@ -0,0 +1,430 @@
|
||||
use super::{
|
||||
seat::{KeyboardEvent, PointerEvent, SeatData},
|
||||
X_DISPLAY,
|
||||
};
|
||||
use crate::{
|
||||
nodes::{
|
||||
data::KEYMAPS,
|
||||
drawable::model::ModelPart,
|
||||
items::panel::{Backend, Geometry, PanelItem, PanelItemInitData, SurfaceID, ToplevelInfo},
|
||||
},
|
||||
wayland::surface::CoreSurface,
|
||||
};
|
||||
use color_eyre::eyre::Result;
|
||||
use mint::Vector2;
|
||||
use once_cell::sync::OnceCell;
|
||||
use parking_lot::Mutex;
|
||||
use rustc_hash::FxHashMap;
|
||||
use smithay::{
|
||||
reexports::{
|
||||
calloop::{EventLoop, LoopSignal},
|
||||
wayland_server::{protocol::wl_surface::WlSurface, DisplayHandle, Resource},
|
||||
x11rb::protocol::xproto::Window,
|
||||
},
|
||||
utils::{Logical, Rectangle},
|
||||
wayland::compositor,
|
||||
xwayland::{
|
||||
xwm::{Reorder, ResizeEdge, XwmId},
|
||||
X11Surface, X11Wm, XWayland, XWaylandEvent, XwmHandler,
|
||||
},
|
||||
};
|
||||
use std::{ffi::OsStr, iter::empty, sync::Arc, time::Duration};
|
||||
use tokio::sync::oneshot;
|
||||
use tracing::debug;
|
||||
|
||||
pub struct XWaylandState {
|
||||
pub display: u32,
|
||||
event_loop_signal: LoopSignal,
|
||||
}
|
||||
impl XWaylandState {
|
||||
pub fn create(dh: &DisplayHandle) -> Result<Self> {
|
||||
let dh = dh.clone();
|
||||
|
||||
let (tx, rx) = oneshot::channel();
|
||||
|
||||
std::thread::spawn(move || {
|
||||
let mut event_loop: EventLoop<XWaylandHandler> = EventLoop::try_new()?;
|
||||
let (xwayland, connection) = XWayland::new(&dh);
|
||||
let handle = event_loop.handle();
|
||||
event_loop
|
||||
.handle()
|
||||
.insert_source(connection, {
|
||||
let dh = dh.clone();
|
||||
move |event, _, handler| match event {
|
||||
XWaylandEvent::Ready {
|
||||
connection,
|
||||
client,
|
||||
client_fd: _,
|
||||
display: _,
|
||||
} => {
|
||||
handler.seat.client.set(client.id()).unwrap();
|
||||
handler
|
||||
.wm
|
||||
.set(
|
||||
X11Wm::start_wm(handle.clone(), dh.clone(), connection, client)
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
XWaylandEvent::Exited => (),
|
||||
}
|
||||
})
|
||||
.map_err(|e| e.error)?;
|
||||
|
||||
let display = xwayland.start(
|
||||
event_loop.handle(),
|
||||
None,
|
||||
empty::<(&OsStr, &OsStr)>(),
|
||||
true,
|
||||
|_| (),
|
||||
)?;
|
||||
let _ = tx.send(XWaylandState {
|
||||
display,
|
||||
event_loop_signal: event_loop.get_signal(),
|
||||
});
|
||||
let mut handler = XWaylandHandler {
|
||||
wm: OnceCell::new(),
|
||||
seat: SeatData::new(&dh),
|
||||
wayland_display_handle: dh,
|
||||
};
|
||||
event_loop.run(Duration::from_millis(100), &mut handler, |_| ())
|
||||
});
|
||||
|
||||
let state = rx.blocking_recv()?;
|
||||
let _ = X_DISPLAY.set(state.display);
|
||||
|
||||
Ok(state)
|
||||
}
|
||||
}
|
||||
impl Drop for XWaylandState {
|
||||
fn drop(&mut self) {
|
||||
self.event_loop_signal.stop();
|
||||
}
|
||||
}
|
||||
|
||||
struct XWaylandHandler {
|
||||
wayland_display_handle: DisplayHandle,
|
||||
wm: OnceCell<X11Wm>,
|
||||
seat: Arc<SeatData>,
|
||||
}
|
||||
impl XWaylandHandler {
|
||||
fn panel_item(&self, window: &X11Surface) -> Option<Arc<PanelItem<X11Backend>>> {
|
||||
compositor::with_states(&window.wl_surface()?, |s| {
|
||||
s.data_map.get::<Arc<PanelItem<X11Backend>>>().cloned()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl XwmHandler for XWaylandHandler {
|
||||
fn xwm_state(&mut self, _xwm: XwmId) -> &mut X11Wm {
|
||||
self.wm.get_mut().unwrap()
|
||||
}
|
||||
|
||||
fn new_window(&mut self, _xwm: XwmId, window: X11Surface) {
|
||||
debug!(?window, "New X window");
|
||||
}
|
||||
|
||||
fn new_override_redirect_window(&mut self, _xwm: XwmId, window: X11Surface) {
|
||||
debug!(?window, "New X override redirect window");
|
||||
}
|
||||
|
||||
fn map_window_request(&mut self, _xwm: XwmId, window: X11Surface) {
|
||||
debug!(?window, "X map window request");
|
||||
window.set_mapped(true).unwrap();
|
||||
}
|
||||
fn map_window_notify(&mut self, _xwm: XwmId, window: X11Surface) {
|
||||
debug!(?window, "X map window notify");
|
||||
|
||||
let _ = window.set_maximized(true);
|
||||
|
||||
let dh = self.wayland_display_handle.clone();
|
||||
let seat = self.seat.clone();
|
||||
CoreSurface::add_to(
|
||||
self.wayland_display_handle.clone(),
|
||||
&window.wl_surface().unwrap(),
|
||||
{
|
||||
let window = window.clone();
|
||||
move || {
|
||||
let Some(wl_surface) = window.wl_surface() else {
|
||||
return;
|
||||
};
|
||||
let seat = seat.clone();
|
||||
window.user_data().insert_if_missing_threadsafe(|| {
|
||||
let panel_item = PanelItem::create(
|
||||
Box::new(X11Backend {
|
||||
toplevel_parent: None,
|
||||
toplevel: window.clone(),
|
||||
seat,
|
||||
_pointer_grab: Mutex::new(None),
|
||||
_keyboard_grab: Mutex::new(None),
|
||||
}),
|
||||
wl_surface
|
||||
.client()
|
||||
.and_then(|c| c.get_credentials(&dh).ok())
|
||||
.map(|c| c.pid),
|
||||
);
|
||||
panel_item
|
||||
});
|
||||
}
|
||||
},
|
||||
move |_| {
|
||||
let Some(panel_item) = window.user_data().get::<Arc<PanelItem<X11Backend>>>()
|
||||
else {
|
||||
return;
|
||||
};
|
||||
panel_item.toplevel_size_changed(
|
||||
[
|
||||
window.geometry().size.w as u32,
|
||||
window.geometry().size.h as u32,
|
||||
]
|
||||
.into(),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
fn mapped_override_redirect_window(&mut self, _xwm: XwmId, window: X11Surface) {
|
||||
debug!(?window, "X map override redirect window");
|
||||
}
|
||||
|
||||
fn unmapped_window(&mut self, _xwm: XwmId, window: X11Surface) {
|
||||
debug!(?window, "Unmap X window");
|
||||
if let Some(panel_item) = window.user_data().get::<Arc<PanelItem<X11Backend>>>() {
|
||||
panel_item.drop_toplevel();
|
||||
}
|
||||
}
|
||||
fn destroyed_window(&mut self, _xwm: XwmId, window: X11Surface) {
|
||||
debug!(?window, "Destroy X window");
|
||||
}
|
||||
|
||||
fn configure_request(
|
||||
&mut self,
|
||||
_xwm: XwmId,
|
||||
window: X11Surface,
|
||||
x: Option<i32>,
|
||||
y: Option<i32>,
|
||||
w: Option<u32>,
|
||||
h: Option<u32>,
|
||||
reorder: Option<Reorder>,
|
||||
) {
|
||||
debug!(?window, x, y, w, h, ?reorder, "Configure X window");
|
||||
}
|
||||
|
||||
fn configure_notify(
|
||||
&mut self,
|
||||
_xwm: XwmId,
|
||||
window: X11Surface,
|
||||
geometry: Rectangle<i32, Logical>,
|
||||
above: Option<Window>,
|
||||
) {
|
||||
debug!(?window, ?geometry, above, "Configure X window");
|
||||
}
|
||||
|
||||
fn move_request(&mut self, _xwm: XwmId, window: X11Surface, button: u32) {
|
||||
let Some(panel_item) = self.panel_item(&window) else {
|
||||
return;
|
||||
};
|
||||
debug!(?window, button, "X window requests move");
|
||||
panel_item.toplevel_move_request();
|
||||
}
|
||||
fn resize_request(
|
||||
&mut self,
|
||||
_xwm: XwmId,
|
||||
window: X11Surface,
|
||||
button: u32,
|
||||
resize_edge: ResizeEdge,
|
||||
) {
|
||||
let Some(panel_item) = self.panel_item(&window) else {
|
||||
return;
|
||||
};
|
||||
debug!(?window, button, ?resize_edge, "X window requests resize");
|
||||
let (up, down, left, right) = match resize_edge {
|
||||
ResizeEdge::Top => (true, false, false, false),
|
||||
ResizeEdge::Bottom => (false, true, false, false),
|
||||
ResizeEdge::Left => (false, false, true, false),
|
||||
ResizeEdge::TopLeft => (true, false, true, false),
|
||||
ResizeEdge::BottomLeft => (false, true, true, false),
|
||||
ResizeEdge::Right => (false, false, false, true),
|
||||
ResizeEdge::TopRight => (true, false, false, true),
|
||||
ResizeEdge::BottomRight => (false, true, false, true),
|
||||
// _ => (false, false, false, false),
|
||||
};
|
||||
panel_item.toplevel_resize_request(up, down, left, right)
|
||||
}
|
||||
|
||||
fn fullscreen_request(&mut self, _xwm: XwmId, window: X11Surface) {
|
||||
let _ = window.set_fullscreen(true);
|
||||
let Some(panel_item) = self.panel_item(&window) else {
|
||||
return;
|
||||
};
|
||||
panel_item.toplevel_fullscreen_active(true);
|
||||
}
|
||||
fn unfullscreen_request(&mut self, _xwm: XwmId, window: X11Surface) {
|
||||
let _ = window.set_fullscreen(false);
|
||||
let Some(panel_item) = self.panel_item(&window) else {
|
||||
return;
|
||||
};
|
||||
panel_item.toplevel_fullscreen_active(true);
|
||||
}
|
||||
}
|
||||
|
||||
pub struct X11Backend {
|
||||
pub toplevel_parent: Option<X11Surface>,
|
||||
pub toplevel: X11Surface,
|
||||
pub seat: Arc<SeatData>,
|
||||
_pointer_grab: Mutex<Option<SurfaceID>>,
|
||||
_keyboard_grab: Mutex<Option<SurfaceID>>,
|
||||
}
|
||||
impl X11Backend {
|
||||
fn wl_surface_from_id(&self, id: &SurfaceID) -> Option<WlSurface> {
|
||||
match id {
|
||||
SurfaceID::Cursor => None,
|
||||
SurfaceID::Toplevel => self.toplevel.wl_surface(),
|
||||
SurfaceID::Child(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
// fn flush_client(&self) {
|
||||
// let Some(client) = self.toplevel.wl_surface().and_then(|s| s.client()) else {return};
|
||||
// if let Some(client_state) = client.get_data::<ClientState>() {
|
||||
// client_state.flush();
|
||||
// }
|
||||
// }
|
||||
}
|
||||
impl Backend for X11Backend {
|
||||
fn start_data(&self) -> Result<PanelItemInitData> {
|
||||
Ok(PanelItemInitData {
|
||||
cursor: None,
|
||||
toplevel: ToplevelInfo {
|
||||
parent: None,
|
||||
title: Some(self.toplevel.title()),
|
||||
app_id: Some(self.toplevel.instance()),
|
||||
size: [
|
||||
self.toplevel.geometry().size.w as u32,
|
||||
self.toplevel.geometry().size.h as u32,
|
||||
]
|
||||
.into(),
|
||||
min_size: self
|
||||
.toplevel
|
||||
.min_size()
|
||||
.map(|s| [s.w as u32, s.h as u32].into()),
|
||||
max_size: self
|
||||
.toplevel
|
||||
.max_size()
|
||||
.map(|s| [s.w as u32, s.h as u32].into()),
|
||||
logical_rectangle: Geometry {
|
||||
origin: [0, 0].into(),
|
||||
size: [
|
||||
self.toplevel.geometry().size.w as u32,
|
||||
self.toplevel.geometry().size.h as u32,
|
||||
]
|
||||
.into(),
|
||||
},
|
||||
},
|
||||
children: FxHashMap::default(),
|
||||
pointer_grab: self._pointer_grab.lock().clone(),
|
||||
keyboard_grab: self._keyboard_grab.lock().clone(),
|
||||
})
|
||||
}
|
||||
fn close_toplevel(&self) {
|
||||
let _ = self.toplevel.close();
|
||||
}
|
||||
|
||||
fn auto_size_toplevel(&self) {
|
||||
let _ = self.toplevel.configure(None);
|
||||
}
|
||||
fn set_toplevel_size(&self, size: Vector2<u32>) {
|
||||
let _ = self.toplevel.configure(Some(Rectangle {
|
||||
loc: self.toplevel.geometry().loc,
|
||||
size: (size.x as i32, size.y as i32).into(),
|
||||
}));
|
||||
}
|
||||
fn set_toplevel_focused_visuals(&self, focused: bool) {
|
||||
let _ = self.toplevel.set_activated(focused);
|
||||
}
|
||||
|
||||
fn apply_surface_material(&self, surface: SurfaceID, model_part: &Arc<ModelPart>) {
|
||||
let Some(wl_surface) = self.wl_surface_from_id(&surface) else {
|
||||
return;
|
||||
};
|
||||
let Some(core_surface) = CoreSurface::from_wl_surface(&wl_surface) else {
|
||||
return;
|
||||
};
|
||||
|
||||
core_surface.apply_material(model_part);
|
||||
}
|
||||
|
||||
fn pointer_motion(&self, surface: &SurfaceID, position: Vector2<f32>) {
|
||||
let Some(surface) = self.wl_surface_from_id(surface) else {
|
||||
return;
|
||||
};
|
||||
self.seat
|
||||
.pointer_event(&surface, PointerEvent::Motion(position));
|
||||
}
|
||||
fn pointer_button(&self, surface: &SurfaceID, button: u32, pressed: bool) {
|
||||
let Some(surface) = self.wl_surface_from_id(surface) else {
|
||||
return;
|
||||
};
|
||||
self.seat.pointer_event(
|
||||
&surface,
|
||||
PointerEvent::Button {
|
||||
button,
|
||||
state: if pressed { 1 } else { 0 },
|
||||
},
|
||||
)
|
||||
}
|
||||
fn pointer_scroll(
|
||||
&self,
|
||||
surface: &SurfaceID,
|
||||
scroll_distance: Option<Vector2<f32>>,
|
||||
scroll_steps: Option<Vector2<f32>>,
|
||||
) {
|
||||
let Some(surface) = self.wl_surface_from_id(surface) else {
|
||||
return;
|
||||
};
|
||||
self.seat.pointer_event(
|
||||
&surface,
|
||||
PointerEvent::Scroll {
|
||||
axis_continuous: scroll_distance,
|
||||
axis_discrete: scroll_steps,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn keyboard_keys(&self, surface: &SurfaceID, keymap_id: &str, keys: Vec<i32>) {
|
||||
let Some(surface) = self.wl_surface_from_id(surface) else {
|
||||
return;
|
||||
};
|
||||
let keymaps = KEYMAPS.lock();
|
||||
let Some(keymap) = keymaps.get(keymap_id).cloned() else {
|
||||
return;
|
||||
};
|
||||
if self.seat.set_keymap(keymap, vec![surface.clone()]).is_err() {
|
||||
return;
|
||||
}
|
||||
for key in keys {
|
||||
self.seat.keyboard_event(
|
||||
&surface,
|
||||
KeyboardEvent::Key {
|
||||
key: key.abs() as u32,
|
||||
state: key < 0,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn touch_down(&self, surface: &SurfaceID, id: u32, position: Vector2<f32>) {
|
||||
let Some(surface) = self.wl_surface_from_id(surface) else {
|
||||
return;
|
||||
};
|
||||
self.seat.touch_down(&surface, id, position)
|
||||
}
|
||||
fn touch_move(&self, id: u32, position: Vector2<f32>) {
|
||||
self.seat.touch_move(id, position)
|
||||
}
|
||||
fn touch_up(&self, id: u32) {
|
||||
self.seat.touch_up(id)
|
||||
}
|
||||
fn reset_touches(&self) {
|
||||
self.seat.reset_touches()
|
||||
}
|
||||
}
|
||||
5
stardust-xr-server.desktop
Normal file
5
stardust-xr-server.desktop
Normal file
@@ -0,0 +1,5 @@
|
||||
[Desktop Entry]
|
||||
Name=Stardust XR
|
||||
Comment=FOSS XR system UI (display server) project
|
||||
Exec=stardust-xr-server
|
||||
Type=Application
|
||||
Reference in New Issue
Block a user