Compare commits
233
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6ef376763c
|
||
|
|
f50a3f127f
|
||
|
|
f0f3f972ce
|
||
|
|
b2d2533acb
|
||
|
|
4b499288e2
|
||
|
|
aa3b31deb5 | ||
|
|
f784ccd774
|
||
|
|
7cced0709b
|
||
|
|
e2a5a67621
|
||
|
|
fbe4d0cac0
|
||
|
|
4c0f1cb9ad
|
||
|
|
94ffd241bd
|
||
|
|
a415c172c7
|
||
|
|
c89116b6f8
|
||
|
|
dc279fe72b
|
||
|
|
01221769cd
|
||
|
|
3cce8a2b25 | ||
|
|
de53eb5ad7
|
||
|
|
49cb16b6cb
|
||
|
|
3aec829c70
|
||
|
|
73c8246c8d
|
||
|
|
fa0a768b84
|
||
|
|
62573e9574
|
||
|
|
c814e057dc
|
||
|
|
8d719843c7
|
||
|
|
d6afa6ae6b
|
||
|
|
3df8227ebf
|
||
|
|
b30ff73e3d
|
||
|
|
dcd3479b1d
|
||
|
|
0ffb3467b1
|
||
|
|
313b896e7b | ||
|
|
6dc8cb5372
|
||
|
|
c34bbaf936
|
||
|
|
e613ab43c9
|
||
|
|
4e05daf280
|
||
|
|
8098dbd7f4
|
||
|
|
e01b463e1f
|
||
|
|
b8fc5a0534
|
||
|
|
f26731413f
|
||
|
|
fa2e329d4b
|
||
|
|
c3d6b70b0c
|
||
|
|
49a676ff86
|
||
|
|
23a181de46
|
||
|
|
bd27f5eb63
|
||
|
|
6646ccfbb5
|
||
|
|
0ecab2910b
|
||
|
|
3eeda25e97
|
||
|
|
a22215392d
|
||
|
|
e19409a2ef
|
||
|
|
a517a24978
|
||
|
|
a771f6320e
|
||
|
|
d645bbb7bd
|
||
|
|
5ff273f167
|
||
|
|
33f70d1c6e
|
||
|
|
999136fef3
|
||
|
|
1b29b2f985
|
||
|
|
29e002c5f3
|
||
|
|
57c9af939b
|
||
|
|
d54dadf2a5
|
||
|
|
126bffa37d
|
||
|
|
4bc9ce2b73 | ||
|
|
95465869b1
|
||
|
|
377cb41a3f
|
||
|
|
6593581954
|
||
|
|
badc9b8874
|
||
|
|
f49accc796
|
||
|
|
46b2fae514
|
||
|
|
7307870414
|
||
|
|
5137592cdd
|
||
|
|
68fd3bcd65
|
||
|
|
d39e03c7d9
|
||
|
|
2ab5c43334
|
||
|
|
23d3ed641e | ||
|
|
5d3db4c22a
|
||
|
|
b84946a3a0
|
||
|
|
0adec90f23
|
||
|
|
8747c4f4cf
|
||
|
|
961557583b
|
||
|
|
30c24a4ea7
|
||
|
|
7598a15782
|
||
|
|
54dad3b398
|
||
|
|
8f37d971cd
|
||
|
|
bd147938a0
|
||
|
|
443b1d7cfb | ||
|
|
21b5d59a7d
|
||
|
|
aa917cf44e
|
||
|
|
850ca8691b
|
||
|
|
67a629dbe4
|
||
|
|
6b5b27d068
|
||
|
|
cfb5b1ac89
|
||
|
|
0c6a669e6e
|
||
|
|
4b890850aa
|
||
|
|
28105c2bf2
|
||
|
|
76d4e9c8ce
|
||
|
|
57bf2b84d3
|
||
|
|
4c48b92f3b
|
||
|
|
12d314a62d
|
||
|
|
3916a652b2
|
||
|
|
cafbc42018
|
||
|
|
1022750c12
|
||
|
|
373f842bef
|
||
|
|
a761e73587
|
||
|
|
b4f7b4f3c0
|
||
|
|
9cf9fa6163
|
||
|
|
117a18ee72
|
||
|
|
f45b3a38cb
|
||
|
|
5381ae02b1
|
||
|
|
1d6b799960
|
||
|
|
d0a2682366
|
||
|
|
c62aef51ba
|
||
|
|
d2bace2612
|
||
|
|
6f3df74e79
|
||
|
|
18cfeedbff
|
||
|
|
a268bd0b75
|
||
|
|
9b03d13a0a
|
||
|
|
80a36a3e7a
|
||
|
|
26e038e195
|
||
|
|
df0d7949c8
|
||
|
|
8cd218dc04
|
||
|
|
e4c1390614
|
||
|
|
8c43d85ce8
|
||
|
|
f01822bd53
|
||
|
|
c88c927fee
|
||
|
|
3521eec319
|
||
|
|
dcfc258aeb
|
||
|
|
84daa5fd70
|
||
|
|
d2a53d0efa
|
||
|
|
b06462111a
|
||
|
|
51f6a36b1d
|
||
|
|
6cb0918715
|
||
|
|
38a3edc0fd
|
||
|
|
261d9561a4 | ||
|
|
5ba47eb20a
|
||
|
|
91fab7de96
|
||
|
|
232fb7106d
|
||
|
|
d79c11faa8
|
||
|
|
295666b310
|
||
|
|
41266d3fd5
|
||
|
|
74df4b89ac
|
||
|
|
ae85ed4eff
|
||
|
|
5e00f6bb0d
|
||
|
|
57439846c5
|
||
|
|
5e3cb87b57
|
||
|
|
7c35edcb84
|
||
|
|
c3396f5a61
|
||
|
|
105a6de11e
|
||
|
|
96a23e5419
|
||
|
|
2b69be0f11
|
||
|
|
38544ed3f1
|
||
|
|
ab0e577c6f
|
||
|
|
d2fbe62f7a | ||
|
|
a07104aad1
|
||
|
|
d9c208ad4f
|
||
|
|
f9a86fafb0
|
||
|
|
537096057a
|
||
|
|
f273745589
|
||
|
|
c4c2dfb017
|
||
|
|
668a061964
|
||
|
|
1256d33a72
|
||
|
|
4d5818c244
|
||
|
|
88ac752d9e
|
||
|
|
70c6bd17c8
|
||
|
|
eb398846a0
|
||
|
|
74ef393294
|
||
|
|
13fc1bdbe4
|
||
|
|
2e214b544b
|
||
|
|
8f74bd2b22
|
||
|
|
c16c5a426c
|
||
|
|
1393eeb54f
|
||
|
|
414bdd0333
|
||
|
|
edfac5a99b
|
||
|
|
f62be06dc5
|
||
|
|
fa485ff0a2 | ||
|
|
82a3380426
|
||
|
|
c2698e6a22
|
||
|
|
d929f8e2f1
|
||
|
|
32b838f9c4
|
||
|
|
2154dba080
|
||
|
|
a8e3040d1e
|
||
|
|
1663ab5413
|
||
|
|
15615f3b54
|
||
|
|
a0601fe816
|
||
|
|
4207a193e8 | ||
|
|
4d2ea6400d
|
||
|
|
bfe900797f
|
||
|
|
f36fd1ed7c | ||
|
|
aebebcae04
|
||
|
|
df9f82fcd2
|
||
|
|
569707d002
|
||
|
|
fbebd8887a
|
||
|
|
5282089c7d | ||
|
|
deaababb1e
|
||
|
|
446044c4e6
|
||
|
|
d1f4547e44
|
||
|
|
ab825d3274
|
||
|
|
28cb21118b
|
||
|
|
cccbd48e57
|
||
|
|
c1f5691cd8 | ||
|
|
be684ab0f9
|
||
|
|
6694bd2dd1 | ||
|
|
2bfbe3b2be
|
||
|
|
6de583c9d4
|
||
|
|
20e8439416
|
||
|
|
bea3f76aa7
|
||
|
|
da908ffcb4
|
||
|
|
e3ac3dfd06
|
||
|
|
4d34e08c6c
|
||
|
|
673df0ae6f
|
||
|
|
d4106253e8 | ||
|
|
29d531f622
|
||
|
|
983e4cfc29 | ||
|
|
1bd64e6bc5
|
||
|
|
eda9c6e613
|
||
|
|
b82363d065
|
||
|
|
38fc71f739
|
||
|
|
1ab2898f5e
|
||
|
|
6a681ba4bc
|
||
|
|
4ca53046bf
|
||
|
|
d10d5aa7db
|
||
|
|
b0762c776a | ||
|
|
1c91d1c2df
|
||
|
|
0c8de434cf
|
||
|
|
92be3b90fb
|
||
|
|
41801a8e7a
|
||
|
|
4227d26101
|
||
|
|
0d6ff430a0
|
||
|
|
26686c288c
|
||
|
|
c52f196b7a
|
||
|
|
5984eaaf24
|
||
|
|
15e1e2321e
|
||
|
|
401a56a4c6
|
||
|
|
6ed3f24b1c
|
||
|
|
7b1c3f256a |
@@ -1,4 +1,5 @@
|
|||||||
# ===== Rust / Cargo =====
|
# ===== Rust / Cargo =====
|
||||||
|
.cargo/config.toml
|
||||||
/target/
|
/target/
|
||||||
**/target/
|
**/target/
|
||||||
|
|
||||||
@@ -10,6 +11,7 @@
|
|||||||
# RustRover / IntelliJ
|
# RustRover / IntelliJ
|
||||||
.idea/
|
.idea/
|
||||||
*.iml
|
*.iml
|
||||||
|
.junie
|
||||||
|
|
||||||
# VS Code
|
# VS Code
|
||||||
.vscode/
|
.vscode/
|
||||||
@@ -61,3 +63,6 @@ temp/**
|
|||||||
**/node_modules/**
|
**/node_modules/**
|
||||||
|
|
||||||
AGENTS.md
|
AGENTS.md
|
||||||
|
|
||||||
|
.python-version
|
||||||
|
.venv
|
||||||
|
|||||||
Generated
+10
@@ -1469,6 +1469,16 @@ version = "1.0.15"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
|
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pbxgen-dummy-boy"
|
||||||
|
version = "0.1.0"
|
||||||
|
dependencies = [
|
||||||
|
"anyhow",
|
||||||
|
"prometeu-bytecode",
|
||||||
|
"prometeu-hal",
|
||||||
|
"serde_json",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pbxgen-stress"
|
name = "pbxgen-stress"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
|
|||||||
+2
-4
@@ -1,16 +1,14 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
members = [
|
members = [
|
||||||
"crates/console/prometeu-bytecode",
|
"crates/console/prometeu-bytecode",
|
||||||
|
|
||||||
"crates/console/prometeu-drivers",
|
"crates/console/prometeu-drivers",
|
||||||
"crates/console/prometeu-firmware",
|
"crates/console/prometeu-firmware",
|
||||||
"crates/console/prometeu-hal",
|
"crates/console/prometeu-hal",
|
||||||
"crates/console/prometeu-system",
|
"crates/console/prometeu-system",
|
||||||
"crates/console/prometeu-vm",
|
"crates/console/prometeu-vm",
|
||||||
|
|
||||||
"crates/host/prometeu-host-desktop-winit",
|
"crates/host/prometeu-host-desktop-winit",
|
||||||
|
|
||||||
"crates/tools/prometeu-cli",
|
"crates/tools/prometeu-cli",
|
||||||
|
"crates/tools/pbxgen-dummy-boy",
|
||||||
"crates/tools/pbxgen-stress",
|
"crates/tools/pbxgen-stress",
|
||||||
"crates/dev/prometeu-test-support",
|
"crates/dev/prometeu-test-support",
|
||||||
"crates/dev/prometeu-layer-tests",
|
"crates/dev/prometeu-layer-tests",
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
.PHONY: fmt fmt-check clippy test-local test-debugger-socket clean coverage coverage-xml coverage-json coverage-report-json coverage-domain-list coverage-domain-evidence test ci cobertura
|
.PHONY: fmt fmt-check clippy test-local test-debugger-socket clean coverage coverage-xml coverage-json coverage-report-json coverage-domain-list coverage-domain-evidence coverage-domain-gate test ci ci-domains cobertura
|
||||||
|
|
||||||
fmt:
|
fmt:
|
||||||
cargo fmt
|
cargo fmt
|
||||||
@@ -40,6 +40,10 @@ coverage-domain-evidence:
|
|||||||
fi
|
fi
|
||||||
./scripts/coverage-domain-evidence.sh "$(DOMAIN)"
|
./scripts/coverage-domain-evidence.sh "$(DOMAIN)"
|
||||||
|
|
||||||
|
coverage-domain-gate:
|
||||||
|
./scripts/coverage-domain-evidence.sh --check-all
|
||||||
|
|
||||||
test: fmt-check clippy test-local test-debugger-socket
|
test: fmt-check clippy test-local test-debugger-socket
|
||||||
ci: clean fmt-check clippy coverage coverage-report-json
|
ci: clean fmt-check clippy coverage coverage-report-json
|
||||||
|
ci-domains: clean fmt-check clippy coverage coverage-report-json coverage-xml coverage-json coverage-domain-gate
|
||||||
cobertura: coverage-xml coverage-json
|
cobertura: coverage-xml coverage-json
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# PROMETEU Runtime
|
# PROMETEU Runtime
|
||||||
|
|
||||||
PROMETEU is an educational and experimental fantasy handheld / fantasy console.
|
PROMETEU is an educational and experimental fantasy handheld / fantasy console.
|
||||||
This repository contains the Rust runtime workspace for the machine: VM-facing components, virtual peripherals, host integration, CLI entrypoints, development utilities, specs, and discussion artifacts.
|
This repository contains the Rust runtime workspace for the machine: VM-facing components, virtual peripherals, firmware/system services, host integration, CLI entrypoints, development utilities, specs, and discussion artifacts.
|
||||||
|
|
||||||
The VM is only one subsystem of the machine. The canonical docs in this repository intentionally distinguish:
|
The VM is only one subsystem of the machine. The canonical docs in this repository intentionally distinguish:
|
||||||
|
|
||||||
@@ -41,21 +41,29 @@ This repository is a Rust workspace rooted at [Cargo.toml](Cargo.toml) with memb
|
|||||||
- `crates/dev`
|
- `crates/dev`
|
||||||
|
|
||||||
The main user-facing dispatcher binary is `prometeu`, built from `crates/tools/prometeu-cli`.
|
The main user-facing dispatcher binary is `prometeu`, built from `crates/tools/prometeu-cli`.
|
||||||
|
The same package also builds `prometeu-runtime`, which embeds the current desktop host runtime.
|
||||||
|
|
||||||
Current CLI surface:
|
Current CLI surface:
|
||||||
|
|
||||||
- `prometeu run <cart>`
|
- `prometeu run <cart>`
|
||||||
- `prometeu debug <cart> --port <port>`
|
- `prometeu debug <cart> --port <port>`
|
||||||
- `prometeu build <project-dir>`
|
|
||||||
- `prometeu pack <cart-dir>`
|
|
||||||
- `prometeu verify ...`
|
|
||||||
|
|
||||||
Not every command is fully implemented in every distribution path yet. Today, the runtime flow is the most concrete and the dispatcher forwards execution to specialized binaries when they are available.
|
The dispatcher forwards runtime execution to `prometeu-runtime`.
|
||||||
|
For lower-level local runs, `prometeu-runtime` also accepts:
|
||||||
|
|
||||||
|
- `--run <cart>`
|
||||||
|
- `--debug <cart> --port <port>`
|
||||||
|
- `--fs-root <path>`
|
||||||
|
- `--cap <path>`
|
||||||
|
|
||||||
|
Other ecosystem commands, such as build, pack, and verification tooling, are not part of the current dispatcher surface in this workspace.
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
- Rust toolchain from [rust-toolchain.toml](rust-toolchain.toml)
|
- Rust toolchain from [rust-toolchain.toml](rust-toolchain.toml)
|
||||||
- `rustup` for toolchain installation and management
|
- `rustup` for toolchain installation and management
|
||||||
|
- `cargo-llvm-cov` for coverage targets such as `make coverage` and `make ci-domains`
|
||||||
|
- a local graphical environment for desktop runtime commands
|
||||||
|
|
||||||
## Quick Start
|
## Quick Start
|
||||||
|
|
||||||
@@ -77,13 +85,47 @@ Run the current stress cartridge fixture:
|
|||||||
cargo run -q -p prometeu-cli --bin prometeu -- run test-cartridges/stress-console
|
cargo run -q -p prometeu-cli --bin prometeu -- run test-cartridges/stress-console
|
||||||
```
|
```
|
||||||
|
|
||||||
The desktop runtime opens a native window through the host layer, so this last command is intended for a local graphical environment.
|
Run the embedded runtime binary directly:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cargo run -q -p prometeu-cli --bin prometeu-runtime -- --run test-cartridges/stress-console
|
||||||
|
```
|
||||||
|
|
||||||
|
Regenerate and run the stress cartridge fixture:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./scripts/run-stress.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
The desktop runtime opens a native window through the host layer, so runtime commands are intended for a local graphical environment.
|
||||||
|
|
||||||
|
## Validation
|
||||||
|
|
||||||
|
Format, lint, and test the workspace:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make test
|
||||||
|
```
|
||||||
|
|
||||||
|
Run the CI-oriented non-domain gate:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make ci
|
||||||
|
```
|
||||||
|
|
||||||
|
Run the CI-oriented domain coverage gate:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make ci-domains
|
||||||
|
```
|
||||||
|
|
||||||
|
The debugger socket tests bind localhost sockets and are marked ignored in Rust test metadata; `make test` includes them through the dedicated `test-debugger-socket` target.
|
||||||
|
|
||||||
## Coverage Governance
|
## Coverage Governance
|
||||||
|
|
||||||
The repository uses a two-layer runtime-edge coverage model:
|
The repository uses a two-layer runtime-edge coverage model:
|
||||||
|
|
||||||
- a mandatory global workspace coverage gate in CI;
|
- a mandatory CI gate based on canonical runtime-edge domains;
|
||||||
- domain-oriented review evidence for the canonical runtime-edge domains.
|
- domain-oriented review evidence for the canonical runtime-edge domains.
|
||||||
|
|
||||||
Current canonical domains:
|
Current canonical domains:
|
||||||
@@ -99,6 +141,7 @@ Global coverage artifacts:
|
|||||||
```bash
|
```bash
|
||||||
make ci
|
make ci
|
||||||
make cobertura
|
make cobertura
|
||||||
|
make ci-domains
|
||||||
```
|
```
|
||||||
|
|
||||||
This produces:
|
This produces:
|
||||||
@@ -116,9 +159,13 @@ make coverage-domain-evidence DOMAIN=firmware
|
|||||||
make coverage-domain-evidence DOMAIN=host-dependent
|
make coverage-domain-evidence DOMAIN=host-dependent
|
||||||
```
|
```
|
||||||
|
|
||||||
Per-domain baselines currently start at `0`.
|
Per-domain baselines currently start around `60`.
|
||||||
That does not waive test obligations. It means the project is adopting explicit domain evidence immediately while tightening quantitative expectations incrementally over time.
|
That does not waive test obligations. It means the project is adopting explicit domain evidence immediately while tightening quantitative expectations incrementally over time.
|
||||||
|
|
||||||
|
`make ci-domains` is the CI entrypoint used by Jenkins.
|
||||||
|
It runs the standard coverage pipeline, produces the HTML/XML/JSON artifacts, and fails when any canonical domain falls below its configured `baseline_percent`.
|
||||||
|
The CI gate currently compares domain `lines` coverage against each domain baseline.
|
||||||
|
|
||||||
When a PR changes the observable contract of a canonical domain, it is expected to:
|
When a PR changes the observable contract of a canonical domain, it is expected to:
|
||||||
|
|
||||||
- add or adjust tests for that domain; or
|
- add or adjust tests for that domain; or
|
||||||
@@ -132,7 +179,7 @@ The project is still in active architectural and implementation convergence.
|
|||||||
|
|
||||||
- the machine contract is being clarified through the specs and discussion workflow;
|
- the machine contract is being clarified through the specs and discussion workflow;
|
||||||
- the workspace already contains concrete runtime and host code;
|
- the workspace already contains concrete runtime and host code;
|
||||||
- some CLI subcommands still act as dispatcher placeholders for binaries that are not always present in a local build or distribution.
|
- the CLI dispatcher currently exposes the runtime paths that are backed by binaries in this workspace.
|
||||||
|
|
||||||
Treat APIs, file formats, and execution flows as evolving unless the relevant spec explicitly defines them as stable.
|
Treat APIs, file formats, and execution flows as evolving unless the relevant spec explicitly defines them as stable.
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1 +1 @@
|
|||||||
|
0.1.0
|
||||||
|
|||||||
@@ -19,6 +19,6 @@ pub use assembler::{assemble, AsmError};
|
|||||||
pub use decoder::{decode_next, DecodeError};
|
pub use decoder::{decode_next, DecodeError};
|
||||||
pub use disassembler::disassemble;
|
pub use disassembler::disassemble;
|
||||||
pub use layout::{compute_function_layouts, FunctionLayout};
|
pub use layout::{compute_function_layouts, FunctionLayout};
|
||||||
pub use model::{BytecodeLoader, FunctionMeta, LoadError, SyscallDecl};
|
pub use model::{BytecodeLoader, FunctionMeta, LoadError, SyscallDecl, PBX_MAGIC};
|
||||||
pub use program_image::ProgramImage;
|
pub use program_image::ProgramImage;
|
||||||
pub use value::{string_materialization_count, HeapRef, Value};
|
pub use value::{string_materialization_count, HeapRef, Value};
|
||||||
|
|||||||
@@ -80,9 +80,11 @@ const SECTION_KIND_DEBUG: u32 = 3;
|
|||||||
const SECTION_KIND_EXPORTS: u32 = 4;
|
const SECTION_KIND_EXPORTS: u32 = 4;
|
||||||
const SECTION_KIND_SYSCALLS: u32 = 5;
|
const SECTION_KIND_SYSCALLS: u32 = 5;
|
||||||
|
|
||||||
/// Represents the final serialized format of a PBS v0 module.
|
pub const PBX_MAGIC: [u8; 4] = *b"PBX\0";
|
||||||
|
|
||||||
|
/// Represents the final serialized format of a PBX v0 module.
|
||||||
///
|
///
|
||||||
/// This structure is a pure data container for the PBS format. It does NOT
|
/// This structure is a pure data container for the PBX format. It does NOT
|
||||||
/// contain any linker-like logic (symbol resolution, patching, etc.).
|
/// contain any linker-like logic (symbol resolution, patching, etc.).
|
||||||
/// All multi-module programs must be flattened and linked by the compiler
|
/// All multi-module programs must be flattened and linked by the compiler
|
||||||
/// before being serialized into this format.
|
/// before being serialized into this format.
|
||||||
@@ -126,8 +128,8 @@ impl BytecodeModule {
|
|||||||
final_sections.push((SECTION_KIND_SYSCALLS, syscall_data));
|
final_sections.push((SECTION_KIND_SYSCALLS, syscall_data));
|
||||||
|
|
||||||
let mut out = Vec::new();
|
let mut out = Vec::new();
|
||||||
// Magic "PBS\0"
|
// Magic "PBX\0"
|
||||||
out.extend_from_slice(b"PBS\0");
|
out.extend_from_slice(&PBX_MAGIC);
|
||||||
// Version 0
|
// Version 0
|
||||||
out.extend_from_slice(&0u16.to_le_bytes());
|
out.extend_from_slice(&0u16.to_le_bytes());
|
||||||
// Endianness 0 (Little Endian), Reserved
|
// Endianness 0 (Little Endian), Reserved
|
||||||
@@ -272,8 +274,8 @@ impl BytecodeLoader {
|
|||||||
return Err(LoadError::UnexpectedEof);
|
return Err(LoadError::UnexpectedEof);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Magic "PBS\0"
|
// Magic "PBX\0"
|
||||||
if &bytes[0..4] != b"PBS\0" {
|
if bytes[0..4] != PBX_MAGIC[..] {
|
||||||
return Err(LoadError::InvalidMagic);
|
return Err(LoadError::InvalidMagic);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -708,7 +710,7 @@ mod tests {
|
|||||||
|
|
||||||
fn create_header(section_count: u32) -> Vec<u8> {
|
fn create_header(section_count: u32) -> Vec<u8> {
|
||||||
let mut h = vec![0u8; 32];
|
let mut h = vec![0u8; 32];
|
||||||
h[0..4].copy_from_slice(b"PBS\0");
|
h[0..4].copy_from_slice(&PBX_MAGIC);
|
||||||
h[4..6].copy_from_slice(&0u16.to_le_bytes()); // version
|
h[4..6].copy_from_slice(&0u16.to_le_bytes()); // version
|
||||||
h[6] = 0; // endianness
|
h[6] = 0; // endianness
|
||||||
h[8..12].copy_from_slice(§ion_count.to_le_bytes());
|
h[8..12].copy_from_slice(§ion_count.to_le_bytes());
|
||||||
@@ -727,7 +729,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn build_pbs_with_sections(sections: Vec<(u32, Vec<u8>)>) -> Vec<u8> {
|
fn build_pbx_with_sections(sections: Vec<(u32, Vec<u8>)>) -> Vec<u8> {
|
||||||
let mut data = create_header(sections.len() as u32);
|
let mut data = create_header(sections.len() as u32);
|
||||||
let mut offset = 32 + (sections.len() as u32 * 12);
|
let mut offset = 32 + (sections.len() as u32 * 12);
|
||||||
|
|
||||||
@@ -748,7 +750,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_invalid_magic() {
|
fn test_invalid_magic() {
|
||||||
let mut data = create_header(0);
|
let mut data = create_header(0);
|
||||||
data[0] = b'X';
|
data[0..4].copy_from_slice(b"PBS\0");
|
||||||
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidMagic));
|
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidMagic));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -882,7 +884,7 @@ mod tests {
|
|||||||
fn test_valid_sysc_roundtrip() {
|
fn test_valid_sysc_roundtrip() {
|
||||||
let mut module = minimal_module();
|
let mut module = minimal_module();
|
||||||
module.syscalls = vec![SyscallDecl {
|
module.syscalls = vec![SyscallDecl {
|
||||||
module: "gfx".into(),
|
module: "gfx2d".into(),
|
||||||
name: "draw_line".into(),
|
name: "draw_line".into(),
|
||||||
version: 1,
|
version: 1,
|
||||||
arg_slots: 4,
|
arg_slots: 4,
|
||||||
@@ -897,7 +899,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_malformed_sysc_section_is_rejected() {
|
fn test_malformed_sysc_section_is_rejected() {
|
||||||
let data = build_pbs_with_sections(vec![(SECTION_KIND_SYSCALLS, vec![1, 0, 0])]);
|
let data = build_pbx_with_sections(vec![(SECTION_KIND_SYSCALLS, vec![1, 0, 0])]);
|
||||||
|
|
||||||
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::MalformedSection));
|
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::MalformedSection));
|
||||||
}
|
}
|
||||||
@@ -914,7 +916,7 @@ mod tests {
|
|||||||
sysc.extend_from_slice(&0u16.to_le_bytes());
|
sysc.extend_from_slice(&0u16.to_le_bytes());
|
||||||
sysc.extend_from_slice(&0u16.to_le_bytes());
|
sysc.extend_from_slice(&0u16.to_le_bytes());
|
||||||
|
|
||||||
let data = build_pbs_with_sections(vec![(SECTION_KIND_SYSCALLS, sysc)]);
|
let data = build_pbx_with_sections(vec![(SECTION_KIND_SYSCALLS, sysc)]);
|
||||||
|
|
||||||
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidUtf8));
|
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidUtf8));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ use crate::value::Value;
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
/// Represents a fully linked, executable PBS program image.
|
/// Represents a fully linked, executable PBX program image.
|
||||||
///
|
///
|
||||||
/// Under the Prometeu architecture, the ProgramImage is a "closed-world" artifact
|
/// Under the Prometeu architecture, the ProgramImage is a "closed-world" artifact
|
||||||
/// produced by the compiler. All linking, relocation, and symbol resolution
|
/// produced by the compiler. All linking, relocation, and symbol resolution
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ fn roundtrip_disasm_assemble_byte_equal_with_closures_and_coroutines() {
|
|||||||
emit(CoreOpCode::Sleep, Some(&3u32.to_le_bytes()), &mut prog);
|
emit(CoreOpCode::Sleep, Some(&3u32.to_le_bytes()), &mut prog);
|
||||||
// HOSTCALL sysc[2]
|
// HOSTCALL sysc[2]
|
||||||
emit(CoreOpCode::Hostcall, Some(&2u32.to_le_bytes()), &mut prog);
|
emit(CoreOpCode::Hostcall, Some(&2u32.to_le_bytes()), &mut prog);
|
||||||
// SYSCALL gfx.draw_line (0x1003)
|
// SYSCALL gfx2d.draw_line (0x1003)
|
||||||
emit(CoreOpCode::Syscall, Some(&0x1003u32.to_le_bytes()), &mut prog);
|
emit(CoreOpCode::Syscall, Some(&0x1003u32.to_le_bytes()), &mut prog);
|
||||||
// FRAME_SYNC
|
// FRAME_SYNC
|
||||||
emit(CoreOpCode::FrameSync, None, &mut prog);
|
emit(CoreOpCode::FrameSync, None, &mut prog);
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,10 +1,16 @@
|
|||||||
|
use crate::asset::GlyphAssetSlotIndex;
|
||||||
use crate::memory_banks::SceneBankPoolAccess;
|
use crate::memory_banks::SceneBankPoolAccess;
|
||||||
use prometeu_hal::GfxBridge;
|
|
||||||
use prometeu_hal::glyph::Glyph;
|
use prometeu_hal::glyph::Glyph;
|
||||||
use prometeu_hal::scene_bank::SceneBank;
|
use prometeu_hal::scene_bank::SceneBank;
|
||||||
use prometeu_hal::scene_viewport_cache::SceneViewportCache;
|
use prometeu_hal::scene_viewport_cache::SceneViewportCache;
|
||||||
use prometeu_hal::scene_viewport_resolver::{CacheRefreshRequest, SceneViewportResolver};
|
use prometeu_hal::scene_viewport_resolver::{
|
||||||
|
CacheRefreshRequest, ResolverUpdate, SceneViewportResolver,
|
||||||
|
};
|
||||||
use prometeu_hal::sprite::Sprite;
|
use prometeu_hal::sprite::Sprite;
|
||||||
|
use prometeu_hal::{
|
||||||
|
BoundScenePacket, Camera2D, ComposerFramePacket, ComposerOpStatus, Game2DFrameComposer,
|
||||||
|
Game2DFramePacket, GameSpritePacket, GfxBridge, HudPacket,
|
||||||
|
};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
const EMPTY_SPRITE: Sprite = Sprite {
|
const EMPTY_SPRITE: Sprite = Sprite {
|
||||||
@@ -116,6 +122,7 @@ impl SpriteController {
|
|||||||
|
|
||||||
pub struct FrameComposer {
|
pub struct FrameComposer {
|
||||||
scene_bank_pool: Arc<dyn SceneBankPoolAccess>,
|
scene_bank_pool: Arc<dyn SceneBankPoolAccess>,
|
||||||
|
glyph_slot_index: GlyphAssetSlotIndex,
|
||||||
viewport_width_px: usize,
|
viewport_width_px: usize,
|
||||||
viewport_height_px: usize,
|
viewport_height_px: usize,
|
||||||
active_scene_id: Option<usize>,
|
active_scene_id: Option<usize>,
|
||||||
@@ -128,14 +135,38 @@ pub struct FrameComposer {
|
|||||||
sprite_controller: SpriteController,
|
sprite_controller: SpriteController,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||||
|
pub struct ComposerBuffer {
|
||||||
|
pub bound_scene: Option<BoundScenePacket>,
|
||||||
|
pub camera: Camera2D,
|
||||||
|
pub sprites: Vec<GameSpritePacket>,
|
||||||
|
pub hud: HudPacket,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ComposerBuffer {
|
||||||
|
pub fn close(self) -> Game2DFramePacket {
|
||||||
|
Game2DFramePacket::new(
|
||||||
|
ComposerFramePacket {
|
||||||
|
bound_scene: self.bound_scene,
|
||||||
|
camera: self.camera,
|
||||||
|
sprites: self.sprites,
|
||||||
|
hud: self.hud,
|
||||||
|
},
|
||||||
|
Vec::new(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl FrameComposer {
|
impl FrameComposer {
|
||||||
pub fn new(
|
pub fn new(
|
||||||
viewport_width_px: usize,
|
viewport_width_px: usize,
|
||||||
viewport_height_px: usize,
|
viewport_height_px: usize,
|
||||||
scene_bank_pool: Arc<dyn SceneBankPoolAccess>,
|
scene_bank_pool: Arc<dyn SceneBankPoolAccess>,
|
||||||
|
glyph_slot_index: GlyphAssetSlotIndex,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
scene_bank_pool,
|
scene_bank_pool,
|
||||||
|
glyph_slot_index,
|
||||||
viewport_width_px,
|
viewport_width_px,
|
||||||
viewport_height_px,
|
viewport_height_px,
|
||||||
active_scene_id: None,
|
active_scene_id: None,
|
||||||
@@ -187,6 +218,8 @@ impl FrameComposer {
|
|||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let _ = self.resolve_glyph_slots(&scene, scene_bank_id, "bind_scene");
|
||||||
|
|
||||||
let (cache, resolver) =
|
let (cache, resolver) =
|
||||||
Self::build_scene_runtime(self.viewport_width_px, self.viewport_height_px, &scene);
|
Self::build_scene_runtime(self.viewport_width_px, self.viewport_height_px, &scene);
|
||||||
self.active_scene_id = Some(scene_bank_id);
|
self.active_scene_id = Some(scene_bank_id);
|
||||||
@@ -238,19 +271,54 @@ impl FrameComposer {
|
|||||||
self.sprite_controller.ordered_sprites()
|
self.sprite_controller.ordered_sprites()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn composer_buffer_snapshot(&self) -> ComposerBuffer {
|
||||||
|
ComposerBuffer {
|
||||||
|
bound_scene: self
|
||||||
|
.active_scene_id
|
||||||
|
.map(|scene_bank_id| BoundScenePacket { bank_id: scene_bank_id as i32 }),
|
||||||
|
camera: Camera2D { x: self.camera_x_px, y: self.camera_y_px },
|
||||||
|
sprites: self
|
||||||
|
.ordered_sprites()
|
||||||
|
.into_iter()
|
||||||
|
.map(|sprite| GameSpritePacket {
|
||||||
|
glyph_id: sprite.glyph.glyph_id as i32,
|
||||||
|
palette_id: sprite.glyph.palette_id as i32,
|
||||||
|
x: sprite.x,
|
||||||
|
y: sprite.y,
|
||||||
|
layer: sprite.layer as i32,
|
||||||
|
bank_id: sprite.bank_id as i32,
|
||||||
|
flip_x: sprite.flip_x,
|
||||||
|
flip_y: sprite.flip_y,
|
||||||
|
priority: sprite.priority as i32,
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
hud: HudPacket::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn close_game2d_packet(&self) -> Game2DFramePacket {
|
||||||
|
self.composer_buffer_snapshot().close()
|
||||||
|
}
|
||||||
|
|
||||||
pub fn render_frame(&mut self, gfx: &mut dyn GfxBridge) {
|
pub fn render_frame(&mut self, gfx: &mut dyn GfxBridge) {
|
||||||
let ordered_sprites = self.ordered_sprites();
|
let ordered_sprites = self.ordered_sprites();
|
||||||
gfx.load_frame_sprites(&ordered_sprites);
|
gfx.load_frame_sprites(&ordered_sprites);
|
||||||
|
|
||||||
if let (Some(scene), Some(cache), Some(resolver)) =
|
if let Some(scene) = self.active_scene.as_deref() {
|
||||||
(self.active_scene.as_deref(), self.cache.as_mut(), self.resolver.as_mut())
|
let scene_bank_id = self.active_scene_id.expect("active scene id must exist");
|
||||||
{
|
let resolved_glyph_slots =
|
||||||
|
self.resolve_glyph_slots(scene, scene_bank_id, "render_frame");
|
||||||
|
let (Some(cache), Some(resolver)) = (self.cache.as_mut(), self.resolver.as_mut())
|
||||||
|
else {
|
||||||
|
panic!("SCENE runtime invariant broken: active scene without cache/resolver");
|
||||||
|
};
|
||||||
let update = resolver.update(scene, self.camera_x_px, self.camera_y_px);
|
let update = resolver.update(scene, self.camera_x_px, self.camera_y_px);
|
||||||
|
Self::sync_cache_windows(cache, &update);
|
||||||
Self::apply_refresh_requests(cache, scene, &update.refresh_requests);
|
Self::apply_refresh_requests(cache, scene, &update.refresh_requests);
|
||||||
// `FrameComposer` owns only canonical game-frame composition.
|
// `FrameComposer` owns only canonical game-frame composition.
|
||||||
// Deferred `gfx.*` primitives are drained later by a separate
|
// Deferred `gfx.*` primitives are drained later by a separate
|
||||||
// overlay/debug stage outside this service boundary.
|
// overlay/debug stage outside this service boundary.
|
||||||
gfx.render_scene_from_cache(cache, &update);
|
gfx.render_scene_from_cache(cache, &update, &resolved_glyph_slots);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -259,6 +327,55 @@ impl FrameComposer {
|
|||||||
gfx.render_no_scene_frame();
|
gfx.render_no_scene_frame();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn render_game2d_frame_packet(
|
||||||
|
&mut self,
|
||||||
|
packet: &Game2DFramePacket,
|
||||||
|
gfx: &mut dyn GfxBridge,
|
||||||
|
) {
|
||||||
|
let sprites: Vec<Sprite> =
|
||||||
|
packet.composer.sprites.iter().map(Self::sprite_from_packet).collect();
|
||||||
|
gfx.load_frame_sprites(&sprites);
|
||||||
|
|
||||||
|
let Some(bound_scene) = packet.composer.bound_scene else {
|
||||||
|
gfx.render_no_scene_frame();
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
let scene_bank_id = bound_scene.bank_id as usize;
|
||||||
|
if self.active_scene_id != Some(scene_bank_id) && !self.bind_scene(scene_bank_id) {
|
||||||
|
gfx.render_no_scene_frame();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.camera_x_px = packet.composer.camera.x;
|
||||||
|
self.camera_y_px = packet.composer.camera.y;
|
||||||
|
|
||||||
|
let scene =
|
||||||
|
self.active_scene.as_deref().expect("active scene should exist after packet bind");
|
||||||
|
let resolved_glyph_slots = self.resolve_glyph_slots(scene, scene_bank_id, "render_packet");
|
||||||
|
let (Some(cache), Some(resolver)) = (self.cache.as_mut(), self.resolver.as_mut()) else {
|
||||||
|
panic!("SCENE runtime invariant broken: packet scene without cache/resolver");
|
||||||
|
};
|
||||||
|
let update = resolver.update(scene, self.camera_x_px, self.camera_y_px);
|
||||||
|
Self::sync_cache_windows(cache, &update);
|
||||||
|
Self::apply_refresh_requests(cache, scene, &update.refresh_requests);
|
||||||
|
gfx.render_scene_from_cache(cache, &update, &resolved_glyph_slots);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sprite_from_packet(sprite: &GameSpritePacket) -> Sprite {
|
||||||
|
Sprite {
|
||||||
|
glyph: Glyph { glyph_id: sprite.glyph_id as u16, palette_id: sprite.palette_id as u8 },
|
||||||
|
x: sprite.x,
|
||||||
|
y: sprite.y,
|
||||||
|
layer: sprite.layer as u8,
|
||||||
|
bank_id: sprite.bank_id as u8,
|
||||||
|
active: true,
|
||||||
|
flip_x: sprite.flip_x,
|
||||||
|
flip_y: sprite.flip_y,
|
||||||
|
priority: sprite.priority as u8,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn build_scene_runtime(
|
fn build_scene_runtime(
|
||||||
viewport_width_px: usize,
|
viewport_width_px: usize,
|
||||||
viewport_height_px: usize,
|
viewport_height_px: usize,
|
||||||
@@ -284,6 +401,23 @@ impl FrameComposer {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn resolve_glyph_slots(
|
||||||
|
&self,
|
||||||
|
scene: &SceneBank,
|
||||||
|
scene_bank_id: usize,
|
||||||
|
phase: &str,
|
||||||
|
) -> [usize; 4] {
|
||||||
|
std::array::from_fn(|layer_index| {
|
||||||
|
let layer = &scene.layers[layer_index];
|
||||||
|
self.glyph_slot_index.glyph_slot_for_asset(layer.glyph_asset_id).unwrap_or_else(|| {
|
||||||
|
panic!(
|
||||||
|
"SCENE dependency fatal during {}: scene_bank_id={}, layer={}, glyph_asset_id={}",
|
||||||
|
phase, scene_bank_id, layer_index, layer.glyph_asset_id
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
fn apply_refresh_requests(
|
fn apply_refresh_requests(
|
||||||
cache: &mut SceneViewportCache,
|
cache: &mut SceneViewportCache,
|
||||||
scene: &SceneBank,
|
scene: &SceneBank,
|
||||||
@@ -306,38 +440,96 @@ impl FrameComposer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn sync_cache_windows(cache: &mut SceneViewportCache, update: &ResolverUpdate) {
|
||||||
|
for request in &update.copy_requests {
|
||||||
|
cache.move_layer_window_to(
|
||||||
|
request.layer_index,
|
||||||
|
request.cache_origin_tile_x,
|
||||||
|
request.cache_origin_tile_y,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Game2DFrameComposer for FrameComposer {
|
||||||
|
fn begin_frame(&mut self) {
|
||||||
|
FrameComposer::begin_frame(self);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bind_scene(&mut self, scene_bank_id: usize) -> ComposerOpStatus {
|
||||||
|
if FrameComposer::bind_scene(self, scene_bank_id) {
|
||||||
|
ComposerOpStatus::Ok
|
||||||
|
} else {
|
||||||
|
ComposerOpStatus::SceneUnavailable
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unbind_scene(&mut self) {
|
||||||
|
FrameComposer::unbind_scene(self);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_camera(&mut self, x: i32, y: i32) -> ComposerOpStatus {
|
||||||
|
FrameComposer::set_camera(self, x, y);
|
||||||
|
ComposerOpStatus::Ok
|
||||||
|
}
|
||||||
|
|
||||||
|
fn emit_sprite(&mut self, sprite: Sprite) -> ComposerOpStatus {
|
||||||
|
if FrameComposer::emit_sprite(self, sprite) {
|
||||||
|
ComposerOpStatus::Ok
|
||||||
|
} else {
|
||||||
|
ComposerOpStatus::SpriteOverflow
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn close_game2d_packet(&self) -> Game2DFramePacket {
|
||||||
|
FrameComposer::close_game2d_packet(self)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::gfx::Gfx;
|
use crate::gfx::Gfx;
|
||||||
|
use crate::hardware::Hardware;
|
||||||
use crate::memory_banks::{
|
use crate::memory_banks::{
|
||||||
GlyphBankPoolAccess, GlyphBankPoolInstaller, MemoryBanks, SceneBankPoolInstaller,
|
GlyphBankPoolAccess, GlyphBankPoolInstaller, MemoryBanks, SceneBankPoolInstaller,
|
||||||
};
|
};
|
||||||
|
use prometeu_hal::asset::AssetId;
|
||||||
use prometeu_hal::color::Color;
|
use prometeu_hal::color::Color;
|
||||||
use prometeu_hal::glyph_bank::{GlyphBank, TileSize};
|
use prometeu_hal::glyph_bank::{GlyphBank, TileSize};
|
||||||
use prometeu_hal::scene_layer::{ParallaxFactor, SceneLayer};
|
use prometeu_hal::scene_layer::{ParallaxFactor, SceneLayer};
|
||||||
use prometeu_hal::tile::Tile;
|
use prometeu_hal::tile::Tile;
|
||||||
use prometeu_hal::tilemap::TileMap;
|
use prometeu_hal::tilemap::TileMap;
|
||||||
|
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||||
|
|
||||||
fn make_scene() -> SceneBank {
|
fn make_scene() -> SceneBank {
|
||||||
make_scene_with_palette(1, 1, TileSize::Size8)
|
make_scene_with_palette(1, 1, TileSize::Size8)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn make_scene_with_palette(
|
fn make_scene_with_palette(
|
||||||
glyph_bank_id: u8,
|
glyph_asset_id: AssetId,
|
||||||
palette_id: u8,
|
palette_id: u8,
|
||||||
tile_size: TileSize,
|
tile_size: TileSize,
|
||||||
|
) -> SceneBank {
|
||||||
|
make_scene_grid(glyph_asset_id, palette_id, tile_size, 2, 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn make_scene_grid(
|
||||||
|
glyph_asset_id: AssetId,
|
||||||
|
palette_id: u8,
|
||||||
|
tile_size: TileSize,
|
||||||
|
width: usize,
|
||||||
|
height: usize,
|
||||||
) -> SceneBank {
|
) -> SceneBank {
|
||||||
let layer = SceneLayer {
|
let layer = SceneLayer {
|
||||||
active: true,
|
active: true,
|
||||||
glyph_bank_id,
|
glyph_asset_id,
|
||||||
tile_size,
|
tile_size,
|
||||||
parallax_factor: ParallaxFactor { x: 1.0, y: 0.5 },
|
parallax_factor: ParallaxFactor { x: 1.0, y: 0.5 },
|
||||||
tilemap: TileMap {
|
tilemap: TileMap {
|
||||||
width: 2,
|
width,
|
||||||
height: 2,
|
height,
|
||||||
tiles: vec![
|
tiles: vec![
|
||||||
Tile {
|
Tile {
|
||||||
active: true,
|
active: true,
|
||||||
@@ -345,7 +537,7 @@ mod tests {
|
|||||||
flip_x: false,
|
flip_x: false,
|
||||||
flip_y: false,
|
flip_y: false,
|
||||||
};
|
};
|
||||||
4
|
width * height
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@@ -353,10 +545,21 @@ mod tests {
|
|||||||
SceneBank { layers: std::array::from_fn(|_| layer.clone()) }
|
SceneBank { layers: std::array::from_fn(|_| layer.clone()) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn make_glyph_slot_index(bindings: &[(AssetId, usize)]) -> GlyphAssetSlotIndex {
|
||||||
|
let index = GlyphAssetSlotIndex::new();
|
||||||
|
let mut slots = [None; 16];
|
||||||
|
for (asset_id, slot) in bindings {
|
||||||
|
slots[*slot] = Some(*asset_id);
|
||||||
|
}
|
||||||
|
index.rebuild_from_slots(&slots);
|
||||||
|
index
|
||||||
|
}
|
||||||
|
|
||||||
fn make_glyph_bank(tile_size: TileSize, palette_id: u8, color: Color) -> GlyphBank {
|
fn make_glyph_bank(tile_size: TileSize, palette_id: u8, color: Color) -> GlyphBank {
|
||||||
let size = tile_size as usize;
|
let size = tile_size as usize;
|
||||||
let mut bank = GlyphBank::new(tile_size, size, size);
|
let mut bank =
|
||||||
bank.palettes[palette_id as usize][1] = color;
|
GlyphBank::with_palette_count(tile_size, size, size, palette_id as usize + 1);
|
||||||
|
bank.palette_mut(palette_id).unwrap()[1] = color;
|
||||||
for pixel in &mut bank.pixel_indices {
|
for pixel in &mut bank.pixel_indices {
|
||||||
*pixel = 1;
|
*pixel = 1;
|
||||||
}
|
}
|
||||||
@@ -365,9 +568,14 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn frame_composer_starts_unbound_with_empty_owned_state() {
|
fn frame_composer_starts_unbound_with_empty_owned_state() {
|
||||||
let frame_composer = FrameComposer::new(320, 180, Arc::new(MemoryBanks::new()));
|
let frame_composer = FrameComposer::new(
|
||||||
|
Hardware::W,
|
||||||
|
Hardware::H,
|
||||||
|
Arc::new(MemoryBanks::new()),
|
||||||
|
make_glyph_slot_index(&[]),
|
||||||
|
);
|
||||||
|
|
||||||
assert_eq!(frame_composer.viewport_size(), (320, 180));
|
assert_eq!(frame_composer.viewport_size(), (Hardware::W, Hardware::H));
|
||||||
assert_eq!(frame_composer.active_scene_id(), None);
|
assert_eq!(frame_composer.active_scene_id(), None);
|
||||||
assert!(frame_composer.active_scene().is_none());
|
assert!(frame_composer.active_scene().is_none());
|
||||||
assert_eq!(frame_composer.scene_status(), SceneStatus::Unbound);
|
assert_eq!(frame_composer.scene_status(), SceneStatus::Unbound);
|
||||||
@@ -384,7 +592,8 @@ mod tests {
|
|||||||
let banks = Arc::new(MemoryBanks::new());
|
let banks = Arc::new(MemoryBanks::new());
|
||||||
banks.install_scene_bank(3, Arc::new(make_scene()));
|
banks.install_scene_bank(3, Arc::new(make_scene()));
|
||||||
|
|
||||||
let frame_composer = FrameComposer::new(320, 180, banks);
|
let frame_composer =
|
||||||
|
FrameComposer::new(Hardware::W, Hardware::H, banks, make_glyph_slot_index(&[(1, 0)]));
|
||||||
let scene =
|
let scene =
|
||||||
frame_composer.scene_bank_slot(3).expect("scene bank slot 3 should be resident");
|
frame_composer.scene_bank_slot(3).expect("scene bank slot 3 should be resident");
|
||||||
|
|
||||||
@@ -400,7 +609,8 @@ mod tests {
|
|||||||
|
|
||||||
let expected_scene =
|
let expected_scene =
|
||||||
banks.scene_bank_slot(3).expect("scene bank slot 3 should be resident");
|
banks.scene_bank_slot(3).expect("scene bank slot 3 should be resident");
|
||||||
let mut frame_composer = FrameComposer::new(320, 180, banks);
|
let mut frame_composer =
|
||||||
|
FrameComposer::new(Hardware::W, Hardware::H, banks, make_glyph_slot_index(&[(1, 0)]));
|
||||||
|
|
||||||
assert!(frame_composer.bind_scene(3));
|
assert!(frame_composer.bind_scene(3));
|
||||||
|
|
||||||
@@ -419,7 +629,8 @@ mod tests {
|
|||||||
let banks = Arc::new(MemoryBanks::new());
|
let banks = Arc::new(MemoryBanks::new());
|
||||||
banks.install_scene_bank(1, Arc::new(make_scene()));
|
banks.install_scene_bank(1, Arc::new(make_scene()));
|
||||||
|
|
||||||
let mut frame_composer = FrameComposer::new(320, 180, banks);
|
let mut frame_composer =
|
||||||
|
FrameComposer::new(Hardware::W, Hardware::H, banks, make_glyph_slot_index(&[(1, 0)]));
|
||||||
assert!(frame_composer.bind_scene(1));
|
assert!(frame_composer.bind_scene(1));
|
||||||
|
|
||||||
frame_composer.unbind_scene();
|
frame_composer.unbind_scene();
|
||||||
@@ -433,7 +644,12 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn set_camera_stores_top_left_pixel_coordinates() {
|
fn set_camera_stores_top_left_pixel_coordinates() {
|
||||||
let mut frame_composer = FrameComposer::new(320, 180, Arc::new(MemoryBanks::new()));
|
let mut frame_composer = FrameComposer::new(
|
||||||
|
Hardware::W,
|
||||||
|
Hardware::H,
|
||||||
|
Arc::new(MemoryBanks::new()),
|
||||||
|
make_glyph_slot_index(&[]),
|
||||||
|
);
|
||||||
|
|
||||||
frame_composer.set_camera(-12, 48);
|
frame_composer.set_camera(-12, 48);
|
||||||
|
|
||||||
@@ -445,16 +661,22 @@ mod tests {
|
|||||||
let banks = Arc::new(MemoryBanks::new());
|
let banks = Arc::new(MemoryBanks::new());
|
||||||
banks.install_scene_bank(0, Arc::new(make_scene()));
|
banks.install_scene_bank(0, Arc::new(make_scene()));
|
||||||
|
|
||||||
let mut frame_composer = FrameComposer::new(320, 180, banks);
|
let mut frame_composer =
|
||||||
|
FrameComposer::new(Hardware::W, Hardware::H, banks, make_glyph_slot_index(&[(1, 0)]));
|
||||||
assert!(frame_composer.bind_scene(0));
|
assert!(frame_composer.bind_scene(0));
|
||||||
|
|
||||||
let cache = frame_composer.cache().expect("cache should exist for bound scene");
|
let cache = frame_composer.cache().expect("cache should exist for bound scene");
|
||||||
assert_eq!((cache.width(), cache.height()), (45, 27));
|
assert_eq!((cache.width(), cache.height()), (65, 38));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn missing_scene_binding_falls_back_to_no_scene_state() {
|
fn missing_scene_binding_falls_back_to_no_scene_state() {
|
||||||
let mut frame_composer = FrameComposer::new(320, 180, Arc::new(MemoryBanks::new()));
|
let mut frame_composer = FrameComposer::new(
|
||||||
|
Hardware::W,
|
||||||
|
Hardware::H,
|
||||||
|
Arc::new(MemoryBanks::new()),
|
||||||
|
make_glyph_slot_index(&[]),
|
||||||
|
);
|
||||||
|
|
||||||
assert!(!frame_composer.bind_scene(7));
|
assert!(!frame_composer.bind_scene(7));
|
||||||
|
|
||||||
@@ -463,6 +685,28 @@ mod tests {
|
|||||||
assert!(frame_composer.resolver().is_none());
|
assert!(frame_composer.resolver().is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bind_scene_panics_when_scene_dependency_is_not_resident() {
|
||||||
|
let banks = Arc::new(MemoryBanks::new());
|
||||||
|
banks.install_scene_bank(0, Arc::new(make_scene()));
|
||||||
|
|
||||||
|
let mut frame_composer =
|
||||||
|
FrameComposer::new(Hardware::W, Hardware::H, banks, make_glyph_slot_index(&[]));
|
||||||
|
|
||||||
|
let panic = catch_unwind(AssertUnwindSafe(|| frame_composer.bind_scene(0)))
|
||||||
|
.expect_err("bind_scene should panic when dependency is missing");
|
||||||
|
let message = if let Some(message) = panic.downcast_ref::<String>() {
|
||||||
|
message.clone()
|
||||||
|
} else if let Some(message) = panic.downcast_ref::<&str>() {
|
||||||
|
(*message).to_string()
|
||||||
|
} else {
|
||||||
|
String::new()
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(message.contains("SCENE dependency fatal during bind_scene"));
|
||||||
|
assert!(message.contains("glyph_asset_id=1"));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn sprite_controller_begin_frame_resets_sprite_count_and_buckets() {
|
fn sprite_controller_begin_frame_resets_sprite_count_and_buckets() {
|
||||||
let mut controller = SpriteController::new();
|
let mut controller = SpriteController::new();
|
||||||
@@ -582,7 +826,12 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn frame_composer_emits_ordered_sprites_for_rendering() {
|
fn frame_composer_emits_ordered_sprites_for_rendering() {
|
||||||
let mut frame_composer = FrameComposer::new(320, 180, Arc::new(MemoryBanks::new()));
|
let mut frame_composer = FrameComposer::new(
|
||||||
|
Hardware::W,
|
||||||
|
Hardware::H,
|
||||||
|
Arc::new(MemoryBanks::new()),
|
||||||
|
make_glyph_slot_index(&[]),
|
||||||
|
);
|
||||||
frame_composer.begin_frame();
|
frame_composer.begin_frame();
|
||||||
|
|
||||||
assert!(frame_composer.emit_sprite(Sprite {
|
assert!(frame_composer.emit_sprite(Sprite {
|
||||||
@@ -620,8 +869,12 @@ mod tests {
|
|||||||
let banks = Arc::new(MemoryBanks::new());
|
let banks = Arc::new(MemoryBanks::new());
|
||||||
banks.install_glyph_bank(1, Arc::new(make_glyph_bank(TileSize::Size8, 3, Color::WHITE)));
|
banks.install_glyph_bank(1, Arc::new(make_glyph_bank(TileSize::Size8, 3, Color::WHITE)));
|
||||||
|
|
||||||
let mut frame_composer =
|
let mut frame_composer = FrameComposer::new(
|
||||||
FrameComposer::new(16, 16, Arc::clone(&banks) as Arc<dyn SceneBankPoolAccess>);
|
16,
|
||||||
|
16,
|
||||||
|
Arc::clone(&banks) as Arc<dyn SceneBankPoolAccess>,
|
||||||
|
make_glyph_slot_index(&[]),
|
||||||
|
);
|
||||||
frame_composer.begin_frame();
|
frame_composer.begin_frame();
|
||||||
assert!(frame_composer.emit_sprite(Sprite {
|
assert!(frame_composer.emit_sprite(Sprite {
|
||||||
glyph: Glyph { glyph_id: 0, palette_id: 3 },
|
glyph: Glyph { glyph_id: 0, palette_id: 3 },
|
||||||
@@ -636,8 +889,6 @@ mod tests {
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
let mut gfx = Gfx::new(16, 16, Arc::clone(&banks) as Arc<dyn GlyphBankPoolAccess>);
|
let mut gfx = Gfx::new(16, 16, Arc::clone(&banks) as Arc<dyn GlyphBankPoolAccess>);
|
||||||
gfx.scene_fade_level = 31;
|
|
||||||
gfx.hud_fade_level = 31;
|
|
||||||
|
|
||||||
frame_composer.render_frame(&mut gfx);
|
frame_composer.render_frame(&mut gfx);
|
||||||
gfx.present();
|
gfx.present();
|
||||||
@@ -645,19 +896,127 @@ mod tests {
|
|||||||
assert_eq!(gfx.front_buffer()[0], Color::WHITE.raw());
|
assert_eq!(gfx.front_buffer()[0], Color::WHITE.raw());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn composer_buffer_snapshot_closes_into_game2d_packet_without_fade_state() {
|
||||||
|
let mut frame_composer = FrameComposer::new(
|
||||||
|
Hardware::W,
|
||||||
|
Hardware::H,
|
||||||
|
Arc::new(MemoryBanks::default()),
|
||||||
|
make_glyph_slot_index(&[]),
|
||||||
|
);
|
||||||
|
|
||||||
|
frame_composer.set_camera(10, 20);
|
||||||
|
frame_composer.begin_frame();
|
||||||
|
assert!(frame_composer.emit_sprite(Sprite {
|
||||||
|
glyph: Glyph { glyph_id: 7, palette_id: 3 },
|
||||||
|
x: 4,
|
||||||
|
y: 5,
|
||||||
|
layer: 2,
|
||||||
|
bank_id: 1,
|
||||||
|
active: false,
|
||||||
|
flip_x: true,
|
||||||
|
flip_y: false,
|
||||||
|
priority: 9,
|
||||||
|
}));
|
||||||
|
|
||||||
|
let packet = frame_composer.close_game2d_packet();
|
||||||
|
|
||||||
|
assert_eq!(packet.composer.bound_scene, None);
|
||||||
|
assert_eq!(packet.composer.camera, Camera2D { x: 10, y: 20 });
|
||||||
|
assert_eq!(packet.composer.sprites.len(), 1);
|
||||||
|
assert_eq!(packet.composer.sprites[0].glyph_id, 7);
|
||||||
|
assert_eq!(packet.composer.sprites[0].palette_id, 3);
|
||||||
|
assert_eq!(packet.composer.sprites[0].layer, 2);
|
||||||
|
assert!(packet.composer.sprites[0].flip_x);
|
||||||
|
assert!(packet.composer.hud.commands.is_empty());
|
||||||
|
assert!(packet.gfx2d.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn game2d_frame_composer_facade_closes_equivalent_packet() {
|
||||||
|
let mut frame_composer = FrameComposer::new(
|
||||||
|
Hardware::W,
|
||||||
|
Hardware::H,
|
||||||
|
Arc::new(MemoryBanks::default()),
|
||||||
|
make_glyph_slot_index(&[]),
|
||||||
|
);
|
||||||
|
|
||||||
|
let composer: &mut dyn Game2DFrameComposer = &mut frame_composer;
|
||||||
|
assert_eq!(composer.set_camera(10, 20), ComposerOpStatus::Ok);
|
||||||
|
composer.begin_frame();
|
||||||
|
assert_eq!(
|
||||||
|
composer.emit_sprite(Sprite {
|
||||||
|
glyph: Glyph { glyph_id: 7, palette_id: 3 },
|
||||||
|
x: 4,
|
||||||
|
y: 5,
|
||||||
|
layer: 2,
|
||||||
|
bank_id: 1,
|
||||||
|
active: false,
|
||||||
|
flip_x: true,
|
||||||
|
flip_y: false,
|
||||||
|
priority: 9,
|
||||||
|
}),
|
||||||
|
ComposerOpStatus::Ok
|
||||||
|
);
|
||||||
|
|
||||||
|
let packet = composer.close_game2d_packet();
|
||||||
|
|
||||||
|
assert_eq!(packet.composer.bound_scene, None);
|
||||||
|
assert_eq!(packet.composer.camera, Camera2D { x: 10, y: 20 });
|
||||||
|
assert_eq!(packet.composer.sprites.len(), 1);
|
||||||
|
assert_eq!(packet.composer.sprites[0].glyph_id, 7);
|
||||||
|
assert_eq!(packet.composer.sprites[0].palette_id, 3);
|
||||||
|
assert_eq!(packet.composer.sprites[0].layer, 2);
|
||||||
|
assert!(packet.composer.sprites[0].flip_x);
|
||||||
|
assert!(packet.gfx2d.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn composer_buffer_preserves_integer_layer_ordering() {
|
||||||
|
let mut frame_composer = FrameComposer::new(
|
||||||
|
Hardware::W,
|
||||||
|
Hardware::H,
|
||||||
|
Arc::new(MemoryBanks::default()),
|
||||||
|
make_glyph_slot_index(&[]),
|
||||||
|
);
|
||||||
|
frame_composer.begin_frame();
|
||||||
|
|
||||||
|
for (glyph_id, layer, priority) in [(1, 3, 1), (2, 1, 2), (3, 1, 1), (4, 0, 9)] {
|
||||||
|
assert!(frame_composer.emit_sprite(Sprite {
|
||||||
|
glyph: Glyph { glyph_id, palette_id: 0 },
|
||||||
|
x: 0,
|
||||||
|
y: 0,
|
||||||
|
layer,
|
||||||
|
bank_id: 0,
|
||||||
|
active: false,
|
||||||
|
flip_x: false,
|
||||||
|
flip_y: false,
|
||||||
|
priority,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
let packet = frame_composer.close_game2d_packet();
|
||||||
|
let glyph_order: Vec<i32> =
|
||||||
|
packet.composer.sprites.iter().map(|sprite| sprite.glyph_id).collect();
|
||||||
|
|
||||||
|
assert_eq!(glyph_order, vec![4, 3, 2, 1]);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn render_frame_with_scene_applies_refreshes_before_composition() {
|
fn render_frame_with_scene_applies_refreshes_before_composition() {
|
||||||
let banks = Arc::new(MemoryBanks::new());
|
let banks = Arc::new(MemoryBanks::new());
|
||||||
banks.install_glyph_bank(0, Arc::new(make_glyph_bank(TileSize::Size8, 2, Color::BLUE)));
|
banks.install_glyph_bank(0, Arc::new(make_glyph_bank(TileSize::Size8, 2, Color::BLUE)));
|
||||||
banks.install_scene_bank(0, Arc::new(make_scene_with_palette(0, 2, TileSize::Size8)));
|
banks.install_scene_bank(0, Arc::new(make_scene_with_palette(0, 2, TileSize::Size8)));
|
||||||
|
|
||||||
let mut frame_composer =
|
let mut frame_composer = FrameComposer::new(
|
||||||
FrameComposer::new(16, 16, Arc::clone(&banks) as Arc<dyn SceneBankPoolAccess>);
|
16,
|
||||||
|
16,
|
||||||
|
Arc::clone(&banks) as Arc<dyn SceneBankPoolAccess>,
|
||||||
|
make_glyph_slot_index(&[(0, 0)]),
|
||||||
|
);
|
||||||
assert!(frame_composer.bind_scene(0));
|
assert!(frame_composer.bind_scene(0));
|
||||||
|
|
||||||
let mut gfx = Gfx::new(16, 16, Arc::clone(&banks) as Arc<dyn GlyphBankPoolAccess>);
|
let mut gfx = Gfx::new(16, 16, Arc::clone(&banks) as Arc<dyn GlyphBankPoolAccess>);
|
||||||
gfx.scene_fade_level = 31;
|
|
||||||
gfx.hud_fade_level = 31;
|
|
||||||
|
|
||||||
frame_composer.render_frame(&mut gfx);
|
frame_composer.render_frame(&mut gfx);
|
||||||
gfx.present();
|
gfx.present();
|
||||||
@@ -673,6 +1032,41 @@ mod tests {
|
|||||||
assert_eq!(gfx.front_buffer()[0], Color::BLUE.raw());
|
assert_eq!(gfx.front_buffer()[0], Color::BLUE.raw());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn render_frame_realigns_cache_window_before_refresh_when_camera_moves() {
|
||||||
|
let banks = Arc::new(MemoryBanks::new());
|
||||||
|
let scene = Arc::new(make_scene_grid(0, 2, TileSize::Size8, 16, 16));
|
||||||
|
banks.install_glyph_bank(0, Arc::new(make_glyph_bank(TileSize::Size8, 2, Color::BLUE)));
|
||||||
|
banks.install_scene_bank(0, Arc::clone(&scene));
|
||||||
|
|
||||||
|
let mut frame_composer = FrameComposer::new(
|
||||||
|
16,
|
||||||
|
16,
|
||||||
|
Arc::clone(&banks) as Arc<dyn SceneBankPoolAccess>,
|
||||||
|
make_glyph_slot_index(&[(0, 0)]),
|
||||||
|
);
|
||||||
|
assert!(frame_composer.bind_scene(0));
|
||||||
|
|
||||||
|
let mut expected_resolver = FrameComposer::build_scene_runtime(16, 16, &scene).1;
|
||||||
|
expected_resolver.update(&scene, 0, 0);
|
||||||
|
let expected_update = expected_resolver.update(&scene, 40, 0);
|
||||||
|
|
||||||
|
let mut gfx = Gfx::new(16, 16, Arc::clone(&banks) as Arc<dyn GlyphBankPoolAccess>);
|
||||||
|
|
||||||
|
frame_composer.render_frame(&mut gfx);
|
||||||
|
frame_composer.set_camera(40, 0);
|
||||||
|
frame_composer.render_frame(&mut gfx);
|
||||||
|
|
||||||
|
let cache = frame_composer.cache().expect("cache should exist");
|
||||||
|
assert_eq!(
|
||||||
|
cache.layers[0].logical_origin(),
|
||||||
|
(
|
||||||
|
expected_update.copy_requests[0].cache_origin_tile_x,
|
||||||
|
expected_update.copy_requests[0].cache_origin_tile_y,
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn render_frame_survives_scene_transition_through_unbind_and_rebind() {
|
fn render_frame_survives_scene_transition_through_unbind_and_rebind() {
|
||||||
let banks = Arc::new(MemoryBanks::new());
|
let banks = Arc::new(MemoryBanks::new());
|
||||||
@@ -682,11 +1076,13 @@ mod tests {
|
|||||||
banks.install_scene_bank(0, Arc::new(make_scene_with_palette(0, 1, TileSize::Size8)));
|
banks.install_scene_bank(0, Arc::new(make_scene_with_palette(0, 1, TileSize::Size8)));
|
||||||
banks.install_scene_bank(1, Arc::new(make_scene_with_palette(1, 2, TileSize::Size8)));
|
banks.install_scene_bank(1, Arc::new(make_scene_with_palette(1, 2, TileSize::Size8)));
|
||||||
|
|
||||||
let mut frame_composer =
|
let mut frame_composer = FrameComposer::new(
|
||||||
FrameComposer::new(16, 16, Arc::clone(&banks) as Arc<dyn SceneBankPoolAccess>);
|
16,
|
||||||
|
16,
|
||||||
|
Arc::clone(&banks) as Arc<dyn SceneBankPoolAccess>,
|
||||||
|
make_glyph_slot_index(&[(0, 0), (1, 1)]),
|
||||||
|
);
|
||||||
let mut gfx = Gfx::new(16, 16, Arc::clone(&banks) as Arc<dyn GlyphBankPoolAccess>);
|
let mut gfx = Gfx::new(16, 16, Arc::clone(&banks) as Arc<dyn GlyphBankPoolAccess>);
|
||||||
gfx.scene_fade_level = 31;
|
|
||||||
gfx.hud_fade_level = 31;
|
|
||||||
|
|
||||||
assert!(frame_composer.bind_scene(0));
|
assert!(frame_composer.bind_scene(0));
|
||||||
frame_composer.render_frame(&mut gfx);
|
frame_composer.render_frame(&mut gfx);
|
||||||
@@ -716,4 +1112,57 @@ mod tests {
|
|||||||
gfx.present();
|
gfx.present();
|
||||||
assert_eq!(gfx.front_buffer()[0], Color::BLUE.raw());
|
assert_eq!(gfx.front_buffer()[0], Color::BLUE.raw());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn render_frame_panics_when_dependency_disappears_after_bind() {
|
||||||
|
let banks = Arc::new(MemoryBanks::new());
|
||||||
|
banks.install_glyph_bank(0, Arc::new(make_glyph_bank(TileSize::Size8, 1, Color::RED)));
|
||||||
|
banks.install_scene_bank(0, Arc::new(make_scene_with_palette(1, 1, TileSize::Size8)));
|
||||||
|
|
||||||
|
let glyph_slot_index = make_glyph_slot_index(&[(1, 0)]);
|
||||||
|
let mut frame_composer = FrameComposer::new(
|
||||||
|
16,
|
||||||
|
16,
|
||||||
|
Arc::clone(&banks) as Arc<dyn SceneBankPoolAccess>,
|
||||||
|
glyph_slot_index.clone(),
|
||||||
|
);
|
||||||
|
assert!(frame_composer.bind_scene(0));
|
||||||
|
|
||||||
|
glyph_slot_index.rebuild_from_slots(&[None; 16]);
|
||||||
|
|
||||||
|
let mut gfx = Gfx::new(16, 16, Arc::clone(&banks) as Arc<dyn GlyphBankPoolAccess>);
|
||||||
|
let panic = catch_unwind(AssertUnwindSafe(|| frame_composer.render_frame(&mut gfx)))
|
||||||
|
.expect_err("render_frame should panic when dependency disappears");
|
||||||
|
let message = if let Some(message) = panic.downcast_ref::<String>() {
|
||||||
|
message.clone()
|
||||||
|
} else if let Some(message) = panic.downcast_ref::<&str>() {
|
||||||
|
(*message).to_string()
|
||||||
|
} else {
|
||||||
|
String::new()
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(message.contains("SCENE dependency fatal during render_frame"));
|
||||||
|
assert!(message.contains("glyph_asset_id=1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn render_frame_resolves_glyph_dependency_by_asset_id_not_by_slot_number() {
|
||||||
|
let banks = Arc::new(MemoryBanks::new());
|
||||||
|
banks.install_glyph_bank(7, Arc::new(make_glyph_bank(TileSize::Size8, 2, Color::BLUE)));
|
||||||
|
banks.install_scene_bank(0, Arc::new(make_scene_with_palette(42, 2, TileSize::Size8)));
|
||||||
|
|
||||||
|
let mut frame_composer = FrameComposer::new(
|
||||||
|
16,
|
||||||
|
16,
|
||||||
|
Arc::clone(&banks) as Arc<dyn SceneBankPoolAccess>,
|
||||||
|
make_glyph_slot_index(&[(42, 7)]),
|
||||||
|
);
|
||||||
|
assert!(frame_composer.bind_scene(0));
|
||||||
|
|
||||||
|
let mut gfx = Gfx::new(16, 16, Arc::clone(&banks) as Arc<dyn GlyphBankPoolAccess>);
|
||||||
|
frame_composer.render_frame(&mut gfx);
|
||||||
|
gfx.present();
|
||||||
|
|
||||||
|
assert_eq!(gfx.front_buffer()[0], Color::BLUE.raw());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,39 +0,0 @@
|
|||||||
use crate::gfx::BlendMode;
|
|
||||||
use prometeu_hal::color::Color;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub enum OverlayCommand {
|
|
||||||
FillRectBlend { x: i32, y: i32, w: i32, h: i32, color: Color, mode: BlendMode },
|
|
||||||
DrawLine { x0: i32, y0: i32, x1: i32, y1: i32, color: Color },
|
|
||||||
DrawCircle { x: i32, y: i32, r: i32, color: Color },
|
|
||||||
DrawDisc { x: i32, y: i32, r: i32, border_color: Color, fill_color: Color },
|
|
||||||
DrawSquare { x: i32, y: i32, w: i32, h: i32, border_color: Color, fill_color: Color },
|
|
||||||
DrawText { x: i32, y: i32, text: String, color: Color },
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default)]
|
|
||||||
pub struct DeferredGfxOverlay {
|
|
||||||
commands: Vec<OverlayCommand>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DeferredGfxOverlay {
|
|
||||||
pub fn begin_frame(&mut self) {
|
|
||||||
self.commands.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn push(&mut self, command: OverlayCommand) {
|
|
||||||
self.commands.push(command);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn commands(&self) -> &[OverlayCommand] {
|
|
||||||
&self.commands
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn command_count(&self) -> usize {
|
|
||||||
self.commands.len()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn take_commands(&mut self) -> Vec<OverlayCommand> {
|
|
||||||
std::mem::take(&mut self.commands)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -10,7 +10,14 @@ use crate::pad::Pad;
|
|||||||
use crate::touch::Touch;
|
use crate::touch::Touch;
|
||||||
use prometeu_hal::cartridge::AssetsPayloadSource;
|
use prometeu_hal::cartridge::AssetsPayloadSource;
|
||||||
use prometeu_hal::sprite::Sprite;
|
use prometeu_hal::sprite::Sprite;
|
||||||
use prometeu_hal::{AssetBridge, AudioBridge, GfxBridge, HardwareBridge, PadBridge, TouchBridge};
|
use prometeu_hal::{
|
||||||
|
AssetBridge, AudioBridge, InputPlatform, NoopTelemetryPlatform, PadBridge, RenderBackend,
|
||||||
|
RuntimePlatform, TelemetryPlatform, TouchBridge,
|
||||||
|
};
|
||||||
|
use prometeu_hal::{
|
||||||
|
Game2DFrameComposer, Game2DFramePacket, RenderSubmission, RenderSubmissionPacket,
|
||||||
|
};
|
||||||
|
use prometeu_hal::{RenderSubmissionSink, RenderSubmitError};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
/// Aggregate structure for all virtual hardware peripherals.
|
/// Aggregate structure for all virtual hardware peripherals.
|
||||||
@@ -21,11 +28,13 @@ use std::sync::Arc;
|
|||||||
/// for easier testing and different host implementations (Desktop, Web, etc.).
|
/// for easier testing and different host implementations (Desktop, Web, etc.).
|
||||||
///
|
///
|
||||||
/// ### Console Specifications:
|
/// ### Console Specifications:
|
||||||
/// - **Resolution**: 320x180 (16:9 Aspect Ratio).
|
/// - **Resolution**: 480x270 (16:9 Aspect Ratio).
|
||||||
/// - **Color Depth**: RGB565 (16-bit).
|
/// - **Color Format**: RGBA8888.
|
||||||
/// - **Audio**: Stereo, Command-based mixing.
|
/// - **Audio**: Stereo, Command-based mixing.
|
||||||
/// - **Input**: 12-button Digital Gamepad + Absolute Touch/Mouse.
|
/// - **Input**: 12-button Digital Gamepad + Absolute Touch/Mouse.
|
||||||
pub struct Hardware {
|
pub struct Hardware {
|
||||||
|
/// Shared physical memory bank ownership used by peripherals and worker backends.
|
||||||
|
pub memory_banks: Arc<MemoryBanks>,
|
||||||
/// The Graphics Processing Unit (GPU). Handles drawing primitives, sprites, and tilemaps.
|
/// The Graphics Processing Unit (GPU). Handles drawing primitives, sprites, and tilemaps.
|
||||||
pub gfx: Gfx,
|
pub gfx: Gfx,
|
||||||
/// Canonical frame orchestration owner for scene/camera/cache/resolver/sprites.
|
/// Canonical frame orchestration owner for scene/camera/cache/resolver/sprites.
|
||||||
@@ -46,54 +55,94 @@ impl Default for Hardware {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl HardwareBridge for Hardware {
|
impl Hardware {
|
||||||
|
fn consume_render_submission(&mut self, submission: &RenderSubmission) {
|
||||||
|
match &submission.packet {
|
||||||
|
RenderSubmissionPacket::Game2D(packet) => {
|
||||||
|
if packet.composer.bound_scene.is_none() {
|
||||||
|
self.gfx.render_game2d_frame_packet(packet);
|
||||||
|
} else {
|
||||||
|
self.frame_composer.render_game2d_frame_packet(packet, &mut self.gfx);
|
||||||
|
self.gfx.apply_gfx2d_commands(&packet.gfx2d);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
RenderSubmissionPacket::ShellUi(packet) => {
|
||||||
|
self.gfx.render_shell_ui_frame_packet(packet);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.gfx.present();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RenderSubmissionSink for Hardware {
|
||||||
|
fn submit_render_submission(
|
||||||
|
&mut self,
|
||||||
|
submission: RenderSubmission,
|
||||||
|
) -> Result<(), RenderSubmitError> {
|
||||||
|
self.consume_render_submission(&submission);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RenderBackend for Hardware {
|
||||||
|
fn render_frame(&mut self) {
|
||||||
|
if self.frame_composer.active_scene_id().is_none() {
|
||||||
|
let packet = self.frame_composer.close_game2d_packet();
|
||||||
|
self.gfx.render_game2d_frame_packet(&packet);
|
||||||
|
} else {
|
||||||
|
self.frame_composer.render_frame(&mut self.gfx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Game2DFrameComposer for Hardware {
|
||||||
fn begin_frame(&mut self) {
|
fn begin_frame(&mut self) {
|
||||||
self.gfx.begin_overlay_frame();
|
|
||||||
self.frame_composer.begin_frame();
|
self.frame_composer.begin_frame();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn bind_scene(&mut self, scene_bank_id: usize) -> bool {
|
fn bind_scene(&mut self, scene_bank_id: usize) -> prometeu_hal::ComposerOpStatus {
|
||||||
self.frame_composer.bind_scene(scene_bank_id)
|
if self.frame_composer.bind_scene(scene_bank_id) {
|
||||||
|
prometeu_hal::ComposerOpStatus::Ok
|
||||||
|
} else {
|
||||||
|
prometeu_hal::ComposerOpStatus::SceneUnavailable
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn unbind_scene(&mut self) {
|
fn unbind_scene(&mut self) {
|
||||||
self.frame_composer.unbind_scene();
|
self.frame_composer.unbind_scene();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_camera(&mut self, x: i32, y: i32) {
|
fn set_camera(&mut self, x: i32, y: i32) -> prometeu_hal::ComposerOpStatus {
|
||||||
self.frame_composer.set_camera(x, y);
|
self.frame_composer.set_camera(x, y);
|
||||||
|
prometeu_hal::ComposerOpStatus::Ok
|
||||||
}
|
}
|
||||||
|
|
||||||
fn emit_sprite(&mut self, sprite: Sprite) -> bool {
|
fn emit_sprite(&mut self, sprite: Sprite) -> prometeu_hal::ComposerOpStatus {
|
||||||
self.frame_composer.emit_sprite(sprite)
|
let Some(bank) = self.gfx.glyph_banks.glyph_bank_slot(sprite.bank_id as usize) else {
|
||||||
|
return prometeu_hal::ComposerOpStatus::BankInvalid;
|
||||||
|
};
|
||||||
|
|
||||||
|
if !bank.contains_palette(sprite.glyph.palette_id) {
|
||||||
|
return prometeu_hal::ComposerOpStatus::BankInvalid;
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.frame_composer.emit_sprite(sprite) {
|
||||||
|
prometeu_hal::ComposerOpStatus::Ok
|
||||||
|
} else {
|
||||||
|
prometeu_hal::ComposerOpStatus::SpriteOverflow
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn render_frame(&mut self) {
|
fn close_game2d_packet(&self) -> Game2DFramePacket {
|
||||||
self.frame_composer.render_frame(&mut self.gfx);
|
self.frame_composer.close_game2d_packet()
|
||||||
self.gfx.drain_overlay_debug();
|
|
||||||
}
|
|
||||||
|
|
||||||
fn has_glyph_bank(&self, bank_id: usize) -> bool {
|
|
||||||
self.gfx.glyph_banks.glyph_bank_slot(bank_id).is_some()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn gfx(&self) -> &dyn GfxBridge {
|
|
||||||
&self.gfx
|
|
||||||
}
|
|
||||||
fn gfx_mut(&mut self) -> &mut dyn GfxBridge {
|
|
||||||
&mut self.gfx
|
|
||||||
}
|
|
||||||
|
|
||||||
fn audio(&self) -> &dyn AudioBridge {
|
|
||||||
&self.audio
|
|
||||||
}
|
|
||||||
fn audio_mut(&mut self) -> &mut dyn AudioBridge {
|
|
||||||
&mut self.audio
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl InputPlatform for Hardware {
|
||||||
fn pad(&self) -> &dyn PadBridge {
|
fn pad(&self) -> &dyn PadBridge {
|
||||||
&self.pad
|
&self.pad
|
||||||
}
|
}
|
||||||
|
|
||||||
fn pad_mut(&mut self) -> &mut dyn PadBridge {
|
fn pad_mut(&mut self) -> &mut dyn PadBridge {
|
||||||
&mut self.pad
|
&mut self.pad
|
||||||
}
|
}
|
||||||
@@ -101,23 +150,61 @@ impl HardwareBridge for Hardware {
|
|||||||
fn touch(&self) -> &dyn TouchBridge {
|
fn touch(&self) -> &dyn TouchBridge {
|
||||||
&self.touch
|
&self.touch
|
||||||
}
|
}
|
||||||
|
|
||||||
fn touch_mut(&mut self) -> &mut dyn TouchBridge {
|
fn touch_mut(&mut self) -> &mut dyn TouchBridge {
|
||||||
&mut self.touch
|
&mut self.touch
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static NOOP_TELEMETRY: NoopTelemetryPlatform = NoopTelemetryPlatform;
|
||||||
|
|
||||||
|
impl RuntimePlatform for Hardware {
|
||||||
|
fn render_submission_sink(&mut self) -> &mut dyn RenderSubmissionSink {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_backend(&mut self) -> &mut dyn RenderBackend {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
fn game2d_frame_composer(&mut self) -> &mut dyn Game2DFrameComposer {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
fn audio(&self) -> &dyn AudioBridge {
|
||||||
|
&self.audio
|
||||||
|
}
|
||||||
|
|
||||||
|
fn audio_mut(&mut self) -> &mut dyn AudioBridge {
|
||||||
|
&mut self.audio
|
||||||
|
}
|
||||||
|
|
||||||
|
fn input(&self) -> &dyn InputPlatform {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
fn input_mut(&mut self) -> &mut dyn InputPlatform {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
fn assets(&self) -> &dyn AssetBridge {
|
fn assets(&self) -> &dyn AssetBridge {
|
||||||
&self.assets
|
&self.assets
|
||||||
}
|
}
|
||||||
|
|
||||||
fn assets_mut(&mut self) -> &mut dyn AssetBridge {
|
fn assets_mut(&mut self) -> &mut dyn AssetBridge {
|
||||||
&mut self.assets
|
&mut self.assets
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn telemetry(&self) -> &dyn TelemetryPlatform {
|
||||||
|
&NOOP_TELEMETRY
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Hardware {
|
impl Hardware {
|
||||||
/// Internal hardware width in pixels.
|
/// Internal hardware width in pixels.
|
||||||
pub const W: usize = 320;
|
pub const W: usize = 480;
|
||||||
/// Internal hardware height in pixels.
|
/// Internal hardware height in pixels.
|
||||||
pub const H: usize = 180;
|
pub const H: usize = 270;
|
||||||
|
|
||||||
/// Creates a fresh hardware instance with default settings.
|
/// Creates a fresh hardware instance with default settings.
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
@@ -126,7 +213,16 @@ impl Hardware {
|
|||||||
|
|
||||||
/// Creates hardware with explicit shared bank ownership.
|
/// Creates hardware with explicit shared bank ownership.
|
||||||
pub fn new_with_memory_banks(memory_banks: Arc<MemoryBanks>) -> Self {
|
pub fn new_with_memory_banks(memory_banks: Arc<MemoryBanks>) -> Self {
|
||||||
|
let assets = AssetManager::new(
|
||||||
|
vec![],
|
||||||
|
AssetsPayloadSource::empty(),
|
||||||
|
Arc::clone(&memory_banks) as Arc<dyn GlyphBankPoolInstaller>,
|
||||||
|
Arc::clone(&memory_banks) as Arc<dyn SoundBankPoolInstaller>,
|
||||||
|
Arc::clone(&memory_banks) as Arc<dyn SceneBankPoolInstaller>,
|
||||||
|
);
|
||||||
|
let glyph_slot_index = assets.glyph_asset_slot_index();
|
||||||
Self {
|
Self {
|
||||||
|
memory_banks: Arc::clone(&memory_banks),
|
||||||
gfx: Gfx::new(
|
gfx: Gfx::new(
|
||||||
Self::W,
|
Self::W,
|
||||||
Self::H,
|
Self::H,
|
||||||
@@ -136,17 +232,12 @@ impl Hardware {
|
|||||||
Self::W,
|
Self::W,
|
||||||
Self::H,
|
Self::H,
|
||||||
Arc::clone(&memory_banks) as Arc<dyn SceneBankPoolAccess>,
|
Arc::clone(&memory_banks) as Arc<dyn SceneBankPoolAccess>,
|
||||||
|
glyph_slot_index,
|
||||||
),
|
),
|
||||||
audio: Audio::new(Arc::clone(&memory_banks) as Arc<dyn SoundBankPoolAccess>),
|
audio: Audio::new(Arc::clone(&memory_banks) as Arc<dyn SoundBankPoolAccess>),
|
||||||
pad: Pad::default(),
|
pad: Pad::default(),
|
||||||
touch: Touch::default(),
|
touch: Touch::default(),
|
||||||
assets: AssetManager::new(
|
assets,
|
||||||
vec![],
|
|
||||||
AssetsPayloadSource::empty(),
|
|
||||||
Arc::clone(&memory_banks) as Arc<dyn GlyphBankPoolInstaller>,
|
|
||||||
Arc::clone(&memory_banks) as Arc<dyn SoundBankPoolInstaller>,
|
|
||||||
Arc::clone(&memory_banks) as Arc<dyn SceneBankPoolInstaller>,
|
|
||||||
),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -160,16 +251,21 @@ mod tests {
|
|||||||
use prometeu_hal::color::Color;
|
use prometeu_hal::color::Color;
|
||||||
use prometeu_hal::glyph::Glyph;
|
use prometeu_hal::glyph::Glyph;
|
||||||
use prometeu_hal::glyph_bank::{GlyphBank, TileSize};
|
use prometeu_hal::glyph_bank::{GlyphBank, TileSize};
|
||||||
|
use prometeu_hal::primitives::Rect;
|
||||||
use prometeu_hal::scene_bank::SceneBank;
|
use prometeu_hal::scene_bank::SceneBank;
|
||||||
use prometeu_hal::scene_layer::{ParallaxFactor, SceneLayer};
|
use prometeu_hal::scene_layer::{ParallaxFactor, SceneLayer};
|
||||||
use prometeu_hal::scene_viewport_cache::SceneViewportCache;
|
use prometeu_hal::scene_viewport_cache::SceneViewportCache;
|
||||||
use prometeu_hal::scene_viewport_resolver::SceneViewportResolver;
|
use prometeu_hal::scene_viewport_resolver::SceneViewportResolver;
|
||||||
use prometeu_hal::tile::Tile;
|
use prometeu_hal::tile::Tile;
|
||||||
use prometeu_hal::tilemap::TileMap;
|
use prometeu_hal::tilemap::TileMap;
|
||||||
|
use prometeu_hal::{
|
||||||
|
BoundScenePacket, Camera2D, ComposerFramePacket, FrameId, GameSpritePacket, Gfx2dCommand,
|
||||||
|
GfxUiCommand, ShellUiFramePacket,
|
||||||
|
};
|
||||||
|
|
||||||
fn make_glyph_bank() -> GlyphBank {
|
fn make_glyph_bank() -> GlyphBank {
|
||||||
let mut bank = GlyphBank::new(TileSize::Size8, 8, 8);
|
let mut bank = GlyphBank::new(TileSize::Size8, 8, 8);
|
||||||
bank.palettes[0][1] = Color::RED;
|
bank.palette_mut(0).unwrap()[1] = Color::RED;
|
||||||
for pixel in &mut bank.pixel_indices {
|
for pixel in &mut bank.pixel_indices {
|
||||||
*pixel = 1;
|
*pixel = 1;
|
||||||
}
|
}
|
||||||
@@ -177,9 +273,13 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn make_scene() -> SceneBank {
|
fn make_scene() -> SceneBank {
|
||||||
|
make_scene_with_glyph_asset_id(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn make_scene_with_glyph_asset_id(glyph_asset_id: i32) -> SceneBank {
|
||||||
let layer = SceneLayer {
|
let layer = SceneLayer {
|
||||||
active: true,
|
active: true,
|
||||||
glyph_bank_id: 0,
|
glyph_asset_id,
|
||||||
tile_size: TileSize::Size8,
|
tile_size: TileSize::Size8,
|
||||||
parallax_factor: ParallaxFactor { x: 1.0, y: 1.0 },
|
parallax_factor: ParallaxFactor { x: 1.0, y: 1.0 },
|
||||||
tilemap: TileMap {
|
tilemap: TileMap {
|
||||||
@@ -204,7 +304,7 @@ mod tests {
|
|||||||
fn hardware_can_render_scene_from_shared_scene_bank_pipeline() {
|
fn hardware_can_render_scene_from_shared_scene_bank_pipeline() {
|
||||||
let banks = Arc::new(MemoryBanks::new());
|
let banks = Arc::new(MemoryBanks::new());
|
||||||
banks.install_glyph_bank(0, Arc::new(make_glyph_bank()));
|
banks.install_glyph_bank(0, Arc::new(make_glyph_bank()));
|
||||||
banks.install_scene_bank(0, Arc::new(make_scene()));
|
banks.install_scene_bank(0, Arc::new(make_scene_with_glyph_asset_id(0)));
|
||||||
|
|
||||||
let mut hardware = Hardware::new_with_memory_banks(Arc::clone(&banks));
|
let mut hardware = Hardware::new_with_memory_banks(Arc::clone(&banks));
|
||||||
let scene = banks.scene_bank_slot(0).expect("scene bank slot 0 should be resident");
|
let scene = banks.scene_bank_slot(0).expect("scene bank slot 0 should be resident");
|
||||||
@@ -214,9 +314,7 @@ mod tests {
|
|||||||
let mut resolver = SceneViewportResolver::new(16, 16, 4, 4, 12, 20);
|
let mut resolver = SceneViewportResolver::new(16, 16, 4, 4, 12, 20);
|
||||||
let update = resolver.update(&scene, 0, 0);
|
let update = resolver.update(&scene, 0, 0);
|
||||||
|
|
||||||
hardware.gfx.scene_fade_level = 31;
|
hardware.gfx.render_scene_from_cache(&cache, &update, &[0, 0, 0, 0]);
|
||||||
hardware.gfx.hud_fade_level = 31;
|
|
||||||
hardware.gfx.render_scene_from_cache(&cache, &update);
|
|
||||||
hardware.gfx.present();
|
hardware.gfx.present();
|
||||||
|
|
||||||
assert_eq!(hardware.gfx.front_buffer()[0], Color::RED.raw());
|
assert_eq!(hardware.gfx.front_buffer()[0], Color::RED.raw());
|
||||||
@@ -237,4 +335,130 @@ mod tests {
|
|||||||
assert_eq!(hardware.frame_composer.scene_bank_slot_count(), 16);
|
assert_eq!(hardware.frame_composer.scene_bank_slot_count(), 16);
|
||||||
assert_eq!(scene.layers[0].tile_size, TileSize::Size8);
|
assert_eq!(scene.layers[0].tile_size, TileSize::Size8);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn publish_game2d_submission_applies_gfx2d_overlay_after_active_scene() {
|
||||||
|
let banks = Arc::new(MemoryBanks::new());
|
||||||
|
banks.install_glyph_bank(0, Arc::new(make_glyph_bank()));
|
||||||
|
banks.install_scene_bank(0, Arc::new(make_scene_with_glyph_asset_id(0)));
|
||||||
|
|
||||||
|
let mut hardware = Hardware::new_with_memory_banks(banks);
|
||||||
|
let mut glyph_slots = [None; 16];
|
||||||
|
glyph_slots[0] = Some(0);
|
||||||
|
hardware.assets.glyph_asset_slot_index().rebuild_from_slots(&glyph_slots);
|
||||||
|
assert_eq!(
|
||||||
|
Game2DFrameComposer::bind_scene(&mut hardware, 0),
|
||||||
|
prometeu_hal::ComposerOpStatus::Ok
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut packet = Game2DFrameComposer::close_game2d_packet(&hardware);
|
||||||
|
packet.gfx2d = vec![Gfx2dCommand::FillRect {
|
||||||
|
rect: Rect { x: 0, y: 0, w: 1, h: 1 },
|
||||||
|
color: Color::BLUE,
|
||||||
|
}];
|
||||||
|
|
||||||
|
RenderSubmissionSink::submit_render_submission(
|
||||||
|
&mut hardware,
|
||||||
|
RenderSubmission::game2d(FrameId::ZERO, packet),
|
||||||
|
)
|
||||||
|
.expect("local sink should publish Game2D packet");
|
||||||
|
|
||||||
|
assert_eq!(hardware.gfx.front_buffer()[0], Color::BLUE.raw());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn publish_game2d_submission_uses_packet_scene_and_sprites_not_live_frame_state() {
|
||||||
|
let banks = Arc::new(MemoryBanks::new());
|
||||||
|
banks.install_glyph_bank(0, Arc::new(make_glyph_bank()));
|
||||||
|
banks.install_scene_bank(0, Arc::new(make_scene_with_glyph_asset_id(0)));
|
||||||
|
|
||||||
|
let mut hardware = Hardware::new_with_memory_banks(banks);
|
||||||
|
let mut glyph_slots = [None; 16];
|
||||||
|
glyph_slots[0] = Some(0);
|
||||||
|
hardware.assets.glyph_asset_slot_index().rebuild_from_slots(&glyph_slots);
|
||||||
|
assert_eq!(
|
||||||
|
Game2DFrameComposer::bind_scene(&mut hardware, 0),
|
||||||
|
prometeu_hal::ComposerOpStatus::Ok
|
||||||
|
);
|
||||||
|
|
||||||
|
let packet = Game2DFramePacket::new(
|
||||||
|
ComposerFramePacket {
|
||||||
|
bound_scene: Some(BoundScenePacket { bank_id: 0 }),
|
||||||
|
camera: Camera2D::default(),
|
||||||
|
sprites: vec![GameSpritePacket {
|
||||||
|
glyph_id: 0,
|
||||||
|
palette_id: 0,
|
||||||
|
x: 0,
|
||||||
|
y: 0,
|
||||||
|
layer: 0,
|
||||||
|
bank_id: 0,
|
||||||
|
flip_x: false,
|
||||||
|
flip_y: false,
|
||||||
|
priority: 0,
|
||||||
|
}],
|
||||||
|
hud: Default::default(),
|
||||||
|
},
|
||||||
|
Vec::new(),
|
||||||
|
);
|
||||||
|
|
||||||
|
Game2DFrameComposer::begin_frame(&mut hardware);
|
||||||
|
RenderSubmissionSink::submit_render_submission(
|
||||||
|
&mut hardware,
|
||||||
|
RenderSubmission::game2d(FrameId::ZERO, packet),
|
||||||
|
)
|
||||||
|
.expect("local sink should publish Game2D packet");
|
||||||
|
|
||||||
|
assert_eq!(hardware.gfx.front_buffer()[0], Color::RED.raw());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn render_submission_sink_accepts_owned_game2d_submission() {
|
||||||
|
let mut hardware = Hardware::new();
|
||||||
|
let packet = Game2DFramePacket::new(
|
||||||
|
ComposerFramePacket::default(),
|
||||||
|
vec![Gfx2dCommand::Clear { color: Color::BLUE }],
|
||||||
|
);
|
||||||
|
let submission = RenderSubmission::game2d(FrameId::ZERO, packet);
|
||||||
|
|
||||||
|
RenderSubmissionSink::submit_render_submission(&mut hardware, submission)
|
||||||
|
.expect("local sink should accept owned Game2D submissions");
|
||||||
|
|
||||||
|
assert_eq!(hardware.gfx.front_buffer()[0], Color::BLUE.raw());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn render_submission_sink_accepts_owned_shell_ui_submission() {
|
||||||
|
let mut hardware = Hardware::new();
|
||||||
|
let packet = ShellUiFramePacket::new(vec![GfxUiCommand::Clear { color: Color::RED }]);
|
||||||
|
let submission = RenderSubmission::shell_ui(FrameId::ZERO, packet);
|
||||||
|
|
||||||
|
RenderSubmissionSink::submit_render_submission(&mut hardware, submission)
|
||||||
|
.expect("local sink should accept owned ShellUi submissions");
|
||||||
|
|
||||||
|
assert_eq!(hardware.gfx.front_buffer()[0], Color::RED.raw());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn emit_sprite_rejects_palette_id_outside_loaded_glyph_bank() {
|
||||||
|
let banks = Arc::new(MemoryBanks::new());
|
||||||
|
banks.install_glyph_bank(0, Arc::new(make_glyph_bank()));
|
||||||
|
let mut hardware = Hardware::new_with_memory_banks(banks);
|
||||||
|
|
||||||
|
let status = Game2DFrameComposer::emit_sprite(
|
||||||
|
&mut hardware,
|
||||||
|
Sprite {
|
||||||
|
glyph: Glyph { glyph_id: 0, palette_id: 1 },
|
||||||
|
x: 0,
|
||||||
|
y: 0,
|
||||||
|
layer: 0,
|
||||||
|
bank_id: 0,
|
||||||
|
active: false,
|
||||||
|
flip_x: false,
|
||||||
|
flip_y: false,
|
||||||
|
priority: 0,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(status, prometeu_hal::ComposerOpStatus::BankInvalid);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,19 +2,21 @@ mod asset;
|
|||||||
mod audio;
|
mod audio;
|
||||||
mod frame_composer;
|
mod frame_composer;
|
||||||
mod gfx;
|
mod gfx;
|
||||||
mod gfx_overlay;
|
|
||||||
pub mod hardware;
|
pub mod hardware;
|
||||||
|
mod local_render_backend;
|
||||||
mod memory_banks;
|
mod memory_banks;
|
||||||
mod pad;
|
mod pad;
|
||||||
|
mod test_platform;
|
||||||
mod touch;
|
mod touch;
|
||||||
|
|
||||||
pub use crate::asset::AssetManager;
|
pub use crate::asset::AssetManager;
|
||||||
pub use crate::audio::{Audio, AudioCommand, Channel, MAX_CHANNELS, OUTPUT_SAMPLE_RATE};
|
pub use crate::audio::{Audio, AudioCommand, Channel, MAX_CHANNELS, OUTPUT_SAMPLE_RATE};
|
||||||
pub use crate::frame_composer::{FrameComposer, SceneStatus, SpriteController};
|
pub use crate::frame_composer::{ComposerBuffer, FrameComposer, SceneStatus, SpriteController};
|
||||||
pub use crate::gfx::Gfx;
|
pub use crate::gfx::Gfx;
|
||||||
pub use crate::gfx_overlay::{DeferredGfxOverlay, OverlayCommand};
|
pub use crate::local_render_backend::LocalFramebufferRenderBackend;
|
||||||
pub use crate::memory_banks::{
|
pub use crate::memory_banks::{
|
||||||
GlyphBankPoolAccess, GlyphBankPoolInstaller, MemoryBanks, SceneBankPoolAccess,
|
GlyphBankPoolAccess, GlyphBankPoolInstaller, MemoryBanks, SceneBankPoolAccess,
|
||||||
SceneBankPoolInstaller, SoundBankPoolAccess, SoundBankPoolInstaller,
|
SceneBankPoolInstaller, SoundBankPoolAccess, SoundBankPoolInstaller,
|
||||||
};
|
};
|
||||||
pub use crate::pad::Pad;
|
pub use crate::pad::Pad;
|
||||||
|
pub use crate::test_platform::TestPlatform;
|
||||||
|
|||||||
@@ -0,0 +1,164 @@
|
|||||||
|
use crate::asset::GlyphAssetSlotIndex;
|
||||||
|
use crate::frame_composer::FrameComposer;
|
||||||
|
use crate::gfx::Gfx;
|
||||||
|
use crate::memory_banks::{GlyphBankPoolAccess, MemoryBanks, SceneBankPoolAccess};
|
||||||
|
use prometeu_hal::app_mode::AppMode;
|
||||||
|
use prometeu_hal::{
|
||||||
|
OwnedRgba8888Frame, RenderSubmission, RenderSubmissionPacket, RenderWorkerBackend,
|
||||||
|
RenderWorkerError,
|
||||||
|
};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
pub struct LocalFramebufferRenderBackend {
|
||||||
|
gfx: Mutex<Gfx>,
|
||||||
|
frame_composer: Mutex<FrameComposer>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LocalFramebufferRenderBackend {
|
||||||
|
pub fn new(width: usize, height: usize, glyph_banks: Arc<dyn GlyphBankPoolAccess>) -> Self {
|
||||||
|
Self::new_with_parts(
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
glyph_banks,
|
||||||
|
Arc::new(MemoryBanks::new()),
|
||||||
|
GlyphAssetSlotIndex::new(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new_with_memory_banks(
|
||||||
|
width: usize,
|
||||||
|
height: usize,
|
||||||
|
memory_banks: Arc<MemoryBanks>,
|
||||||
|
glyph_slot_index: GlyphAssetSlotIndex,
|
||||||
|
) -> Self {
|
||||||
|
Self::new_with_parts(
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
Arc::clone(&memory_banks) as Arc<dyn GlyphBankPoolAccess>,
|
||||||
|
memory_banks,
|
||||||
|
glyph_slot_index,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn new_with_parts(
|
||||||
|
width: usize,
|
||||||
|
height: usize,
|
||||||
|
glyph_banks: Arc<dyn GlyphBankPoolAccess>,
|
||||||
|
scene_banks: Arc<dyn SceneBankPoolAccess>,
|
||||||
|
glyph_slot_index: GlyphAssetSlotIndex,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
gfx: Mutex::new(Gfx::new(width, height, glyph_banks)),
|
||||||
|
frame_composer: Mutex::new(FrameComposer::new(
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
scene_banks,
|
||||||
|
glyph_slot_index,
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn render_submission(
|
||||||
|
&self,
|
||||||
|
submission: &RenderSubmission,
|
||||||
|
) -> Result<OwnedRgba8888Frame, RenderWorkerError> {
|
||||||
|
let mut gfx = self.gfx.lock().map_err(|_| RenderWorkerError::InternalFailure)?;
|
||||||
|
match &submission.packet {
|
||||||
|
RenderSubmissionPacket::Game2D(packet) if submission.app_mode == AppMode::Game => {
|
||||||
|
if packet.composer.bound_scene.is_none() {
|
||||||
|
gfx.render_game2d_frame_packet(packet);
|
||||||
|
} else {
|
||||||
|
let mut frame_composer = self
|
||||||
|
.frame_composer
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| RenderWorkerError::InternalFailure)?;
|
||||||
|
frame_composer.render_game2d_frame_packet(packet, &mut *gfx);
|
||||||
|
gfx.apply_gfx2d_commands(&packet.gfx2d);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
RenderSubmissionPacket::ShellUi(packet) if submission.app_mode == AppMode::Shell => {
|
||||||
|
gfx.render_shell_ui_frame_packet(packet);
|
||||||
|
}
|
||||||
|
_ => return Err(RenderWorkerError::RenderFailed),
|
||||||
|
}
|
||||||
|
|
||||||
|
gfx.present();
|
||||||
|
let (width, height) = gfx.size();
|
||||||
|
OwnedRgba8888Frame::packed(
|
||||||
|
submission.frame_id,
|
||||||
|
submission.ownership,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
gfx.front_buffer().to_vec(),
|
||||||
|
)
|
||||||
|
.map_err(|_| RenderWorkerError::InternalFailure)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RenderWorkerBackend for LocalFramebufferRenderBackend {
|
||||||
|
fn render(
|
||||||
|
&self,
|
||||||
|
submission: &RenderSubmission,
|
||||||
|
) -> Result<OwnedRgba8888Frame, RenderWorkerError> {
|
||||||
|
self.render_submission(submission)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::memory_banks::MemoryBanks;
|
||||||
|
use prometeu_hal::app_mode::AppMode;
|
||||||
|
use prometeu_hal::color::Color;
|
||||||
|
use prometeu_hal::primitives::Rect;
|
||||||
|
use prometeu_hal::{
|
||||||
|
FrameId, Game2DFramePacket, Gfx2dCommand, GfxUiCommand, RenderOwnership, ShellUiFramePacket,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn backend() -> LocalFramebufferRenderBackend {
|
||||||
|
let banks = Arc::new(MemoryBanks::new());
|
||||||
|
LocalFramebufferRenderBackend::new(4, 4, banks)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn local_backend_renders_game2d_submission_to_owned_frame() {
|
||||||
|
let backend = backend();
|
||||||
|
let packet = Game2DFramePacket {
|
||||||
|
gfx2d: vec![Gfx2dCommand::FillRect {
|
||||||
|
rect: Rect { x: 1, y: 1, w: 2, h: 2 },
|
||||||
|
color: Color::RED,
|
||||||
|
}],
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let ownership = RenderOwnership::new(3, AppMode::Game, 9);
|
||||||
|
let submission =
|
||||||
|
RenderSubmission::game2d(FrameId::new(5), packet).with_ownership(ownership);
|
||||||
|
|
||||||
|
let frame = backend.render(&submission).expect("game frame should render");
|
||||||
|
|
||||||
|
assert_eq!(frame.frame_id, FrameId::new(5));
|
||||||
|
assert_eq!(frame.ownership, ownership);
|
||||||
|
assert_eq!(frame.width, 4);
|
||||||
|
assert_eq!(frame.height, 4);
|
||||||
|
assert_eq!(frame.pixels[1 + 4], Color::RED.raw());
|
||||||
|
assert_eq!(frame.pixels[2 + 2 * 4], Color::RED.raw());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn local_backend_renders_shell_ui_submission_to_owned_frame() {
|
||||||
|
let backend = backend();
|
||||||
|
let packet = ShellUiFramePacket::new(vec![GfxUiCommand::FillRect {
|
||||||
|
rect: Rect { x: 0, y: 0, w: 1, h: 1 },
|
||||||
|
color: Color::GREEN,
|
||||||
|
}]);
|
||||||
|
let ownership = RenderOwnership::new(4, AppMode::Shell, 10);
|
||||||
|
let submission =
|
||||||
|
RenderSubmission::shell_ui(FrameId::new(6), packet).with_ownership(ownership);
|
||||||
|
|
||||||
|
let frame = backend.render(&submission).expect("shell frame should render");
|
||||||
|
|
||||||
|
assert_eq!(frame.frame_id, FrameId::new(6));
|
||||||
|
assert_eq!(frame.ownership, ownership);
|
||||||
|
assert_eq!(frame.pixels[0], Color::GREEN.raw());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,13 @@
|
|||||||
|
//! Memory bank access boundary.
|
||||||
|
//!
|
||||||
|
//! Render consumers must cross this boundary through small, read-only traits.
|
||||||
|
//! Frame packets carry resource IDs; large resident resources stay in banks and
|
||||||
|
//! are read in place through a narrow HAL callback contract. Installation and
|
||||||
|
//! slot replacement remain separate owner-side operations and are not part of
|
||||||
|
//! the render read surface.
|
||||||
|
|
||||||
use prometeu_hal::glyph_bank::GlyphBank;
|
use prometeu_hal::glyph_bank::GlyphBank;
|
||||||
|
use prometeu_hal::render_resources::RenderResourceAccess as HalRenderResourceAccess;
|
||||||
use prometeu_hal::scene_bank::SceneBank;
|
use prometeu_hal::scene_bank::SceneBank;
|
||||||
use prometeu_hal::sound_bank::SoundBank;
|
use prometeu_hal::sound_bank::SoundBank;
|
||||||
use std::sync::{Arc, RwLock};
|
use std::sync::{Arc, RwLock};
|
||||||
@@ -15,6 +24,8 @@ pub trait GlyphBankPoolAccess: Send + Sync {
|
|||||||
pub trait GlyphBankPoolInstaller: Send + Sync {
|
pub trait GlyphBankPoolInstaller: Send + Sync {
|
||||||
/// Atomically swaps the resident GlyphBank in the specified slot.
|
/// Atomically swaps the resident GlyphBank in the specified slot.
|
||||||
fn install_glyph_bank(&self, slot: usize, bank: Arc<GlyphBank>);
|
fn install_glyph_bank(&self, slot: usize, bank: Arc<GlyphBank>);
|
||||||
|
/// Clears all resident GlyphBank slots.
|
||||||
|
fn clear_glyph_banks(&self);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Non-generic interface for peripherals to access sound banks.
|
/// Non-generic interface for peripherals to access sound banks.
|
||||||
@@ -29,6 +40,8 @@ pub trait SoundBankPoolAccess: Send + Sync {
|
|||||||
pub trait SoundBankPoolInstaller: Send + Sync {
|
pub trait SoundBankPoolInstaller: Send + Sync {
|
||||||
/// Atomically swaps the resident SoundBank in the specified slot.
|
/// Atomically swaps the resident SoundBank in the specified slot.
|
||||||
fn install_sound_bank(&self, slot: usize, bank: Arc<SoundBank>);
|
fn install_sound_bank(&self, slot: usize, bank: Arc<SoundBank>);
|
||||||
|
/// Clears all resident SoundBank slots.
|
||||||
|
fn clear_sound_banks(&self);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Non-generic interface for peripherals to access scene banks.
|
/// Non-generic interface for peripherals to access scene banks.
|
||||||
@@ -43,6 +56,8 @@ pub trait SceneBankPoolAccess: Send + Sync {
|
|||||||
pub trait SceneBankPoolInstaller: Send + Sync {
|
pub trait SceneBankPoolInstaller: Send + Sync {
|
||||||
/// Atomically swaps the resident SceneBank in the specified slot.
|
/// Atomically swaps the resident SceneBank in the specified slot.
|
||||||
fn install_scene_bank(&self, slot: usize, bank: Arc<SceneBank>);
|
fn install_scene_bank(&self, slot: usize, bank: Arc<SceneBank>);
|
||||||
|
/// Clears all resident SceneBank slots.
|
||||||
|
fn clear_scene_banks(&self);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Centralized container for all hardware memory banks.
|
/// Centralized container for all hardware memory banks.
|
||||||
@@ -91,6 +106,10 @@ impl GlyphBankPoolInstaller for MemoryBanks {
|
|||||||
pool[slot] = Some(bank);
|
pool[slot] = Some(bank);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn clear_glyph_banks(&self) {
|
||||||
|
self.glyph_bank_pool.write().unwrap().fill(None);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SoundBankPoolAccess for MemoryBanks {
|
impl SoundBankPoolAccess for MemoryBanks {
|
||||||
@@ -111,6 +130,10 @@ impl SoundBankPoolInstaller for MemoryBanks {
|
|||||||
pool[slot] = Some(bank);
|
pool[slot] = Some(bank);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn clear_sound_banks(&self) {
|
||||||
|
self.sound_bank_pool.write().unwrap().fill(None);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SceneBankPoolAccess for MemoryBanks {
|
impl SceneBankPoolAccess for MemoryBanks {
|
||||||
@@ -131,4 +154,95 @@ impl SceneBankPoolInstaller for MemoryBanks {
|
|||||||
pool[slot] = Some(bank);
|
pool[slot] = Some(bank);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn clear_scene_banks(&self) {
|
||||||
|
self.scene_bank_pool.write().unwrap().fill(None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HalRenderResourceAccess for MemoryBanks {
|
||||||
|
fn with_glyph_bank<R>(&self, bank_id: usize, read: impl FnOnce(&GlyphBank) -> R) -> Option<R> {
|
||||||
|
let pool = self.glyph_bank_pool.read().unwrap();
|
||||||
|
let bank = pool.get(bank_id)?.as_deref()?;
|
||||||
|
Some(read(bank))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn glyph_bank_count(&self) -> usize {
|
||||||
|
16
|
||||||
|
}
|
||||||
|
|
||||||
|
fn with_scene_bank<R>(&self, bank_id: usize, read: impl FnOnce(&SceneBank) -> R) -> Option<R> {
|
||||||
|
let pool = self.scene_bank_pool.read().unwrap();
|
||||||
|
let bank = pool.get(bank_id)?.as_deref()?;
|
||||||
|
Some(read(bank))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn scene_bank_count(&self) -> usize {
|
||||||
|
16
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use prometeu_hal::color::Color;
|
||||||
|
use prometeu_hal::glyph::Glyph;
|
||||||
|
use prometeu_hal::glyph_bank::TileSize;
|
||||||
|
use prometeu_hal::scene_layer::{ParallaxFactor, SceneLayer};
|
||||||
|
use prometeu_hal::tile::Tile;
|
||||||
|
use prometeu_hal::tilemap::TileMap;
|
||||||
|
|
||||||
|
fn assert_send_sync<T: Send + Sync>() {}
|
||||||
|
|
||||||
|
fn make_glyph_bank() -> GlyphBank {
|
||||||
|
let mut bank = GlyphBank::new(TileSize::Size8, 8, 8);
|
||||||
|
bank.palette_mut(0).unwrap()[1] = Color::WHITE;
|
||||||
|
bank
|
||||||
|
}
|
||||||
|
|
||||||
|
fn make_scene_bank() -> SceneBank {
|
||||||
|
let layer = SceneLayer {
|
||||||
|
active: true,
|
||||||
|
glyph_asset_id: 0,
|
||||||
|
tile_size: TileSize::Size8,
|
||||||
|
parallax_factor: ParallaxFactor { x: 1.0, y: 1.0 },
|
||||||
|
tilemap: TileMap {
|
||||||
|
width: 1,
|
||||||
|
height: 1,
|
||||||
|
tiles: vec![Tile {
|
||||||
|
active: true,
|
||||||
|
glyph: Glyph { glyph_id: 0, palette_id: 0 },
|
||||||
|
flip_x: false,
|
||||||
|
flip_y: false,
|
||||||
|
}],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
SceneBank { layers: std::array::from_fn(|_| layer.clone()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn render_resource_access_traits_are_thread_safe() {
|
||||||
|
assert_send_sync::<MemoryBanks>();
|
||||||
|
assert_send_sync::<Arc<dyn GlyphBankPoolAccess>>();
|
||||||
|
assert_send_sync::<Arc<dyn SceneBankPoolAccess>>();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn render_resource_access_exposes_read_only_glyph_and_scene_banks_without_arc_contract() {
|
||||||
|
let banks = MemoryBanks::new();
|
||||||
|
banks.install_glyph_bank(0, Arc::new(make_glyph_bank()));
|
||||||
|
banks.install_scene_bank(1, Arc::new(make_scene_bank()));
|
||||||
|
|
||||||
|
let glyph_tile_size =
|
||||||
|
HalRenderResourceAccess::with_glyph_bank(&banks, 0, |bank| bank.tile_size);
|
||||||
|
let scene_tile_size =
|
||||||
|
HalRenderResourceAccess::with_scene_bank(&banks, 1, |bank| bank.layers[0].tile_size);
|
||||||
|
|
||||||
|
assert_eq!(glyph_tile_size, Some(TileSize::Size8));
|
||||||
|
assert_eq!(scene_tile_size, Some(TileSize::Size8));
|
||||||
|
assert_eq!(HalRenderResourceAccess::with_glyph_bank(&banks, 15, |_| ()), None);
|
||||||
|
assert_eq!(HalRenderResourceAccess::with_scene_bank(&banks, 15, |_| ()), None);
|
||||||
|
assert_eq!(HalRenderResourceAccess::glyph_bank_count(&banks), 16);
|
||||||
|
assert_eq!(HalRenderResourceAccess::scene_bank_count(&banks), 16);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,100 @@
|
|||||||
|
use crate::hardware::Hardware;
|
||||||
|
use crate::memory_banks::MemoryBanks;
|
||||||
|
use prometeu_hal::{
|
||||||
|
AssetBridge, AudioBridge, Game2DFrameComposer, InputPlatform, RenderBackend,
|
||||||
|
RenderSubmissionSink, RuntimePlatform, TelemetryPlatform,
|
||||||
|
};
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
pub struct TestPlatform {
|
||||||
|
hardware: Hardware,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for TestPlatform {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TestPlatform {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self { hardware: Hardware::new() }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new_with_memory_banks(memory_banks: Arc<MemoryBanks>) -> Self {
|
||||||
|
Self { hardware: Hardware::new_with_memory_banks(memory_banks) }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn local_hardware(&self) -> &Hardware {
|
||||||
|
&self.hardware
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn local_hardware_mut(&mut self) -> &mut Hardware {
|
||||||
|
&mut self.hardware
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RuntimePlatform for TestPlatform {
|
||||||
|
fn render_submission_sink(&mut self) -> &mut dyn RenderSubmissionSink {
|
||||||
|
self.hardware.render_submission_sink()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_backend(&mut self) -> &mut dyn RenderBackend {
|
||||||
|
self.hardware.render_backend()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn game2d_frame_composer(&mut self) -> &mut dyn Game2DFrameComposer {
|
||||||
|
self.hardware.game2d_frame_composer()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn audio(&self) -> &dyn AudioBridge {
|
||||||
|
self.hardware.audio()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn audio_mut(&mut self) -> &mut dyn AudioBridge {
|
||||||
|
self.hardware.audio_mut()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn input(&self) -> &dyn InputPlatform {
|
||||||
|
self.hardware.input()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn input_mut(&mut self) -> &mut dyn InputPlatform {
|
||||||
|
self.hardware.input_mut()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn assets(&self) -> &dyn AssetBridge {
|
||||||
|
self.hardware.assets()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn assets_mut(&mut self) -> &mut dyn AssetBridge {
|
||||||
|
self.hardware.assets_mut()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn telemetry(&self) -> &dyn TelemetryPlatform {
|
||||||
|
self.hardware.telemetry()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use prometeu_hal::{FrameId, Game2DFramePacket, RenderSubmission};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_platform_initializes_required_facades() {
|
||||||
|
let mut platform = TestPlatform::new();
|
||||||
|
|
||||||
|
platform.game2d_frame_composer().begin_frame();
|
||||||
|
platform
|
||||||
|
.render_submission_sink()
|
||||||
|
.submit_render_submission(RenderSubmission::game2d(
|
||||||
|
FrameId::ZERO,
|
||||||
|
Game2DFramePacket::default(),
|
||||||
|
))
|
||||||
|
.expect("test platform render sink should accept local submission");
|
||||||
|
assert!(!platform.audio().is_playing(0));
|
||||||
|
assert!(!platform.input().pad().any());
|
||||||
|
assert!(platform.telemetry().telemetry_snapshot().is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -4,6 +4,7 @@ pub use crate::firmware::firmware_step_hub_home::HubHomeStep;
|
|||||||
pub use crate::firmware::firmware_step_launch_hub::LaunchHubStep;
|
pub use crate::firmware::firmware_step_launch_hub::LaunchHubStep;
|
||||||
pub use crate::firmware::firmware_step_load_cartridge::LoadCartridgeStep;
|
pub use crate::firmware::firmware_step_load_cartridge::LoadCartridgeStep;
|
||||||
pub use crate::firmware::firmware_step_reset::ResetStep;
|
pub use crate::firmware::firmware_step_reset::ResetStep;
|
||||||
|
pub use crate::firmware::firmware_step_shell_running::ShellRunningStep;
|
||||||
pub use crate::firmware::firmware_step_splash_screen::SplashScreenStep;
|
pub use crate::firmware::firmware_step_splash_screen::SplashScreenStep;
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
@@ -13,6 +14,8 @@ pub enum FirmwareState {
|
|||||||
LaunchHub(LaunchHubStep),
|
LaunchHub(LaunchHubStep),
|
||||||
HubHome(HubHomeStep),
|
HubHome(HubHomeStep),
|
||||||
LoadCartridge(LoadCartridgeStep),
|
LoadCartridge(LoadCartridgeStep),
|
||||||
|
ResumeResidentGame,
|
||||||
GameRunning(GameRunningStep),
|
GameRunning(GameRunningStep),
|
||||||
|
ShellRunning(ShellRunningStep),
|
||||||
AppCrashes(AppCrashesStep),
|
AppCrashes(AppCrashesStep),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ use crate::firmware::firmware_state::{FirmwareState, LaunchHubStep};
|
|||||||
use crate::firmware::prometeu_context::PrometeuContext;
|
use crate::firmware::prometeu_context::PrometeuContext;
|
||||||
use prometeu_hal::color::Color;
|
use prometeu_hal::color::Color;
|
||||||
use prometeu_hal::log::{LogLevel, LogSource};
|
use prometeu_hal::log::{LogLevel, LogSource};
|
||||||
|
use prometeu_hal::{FrameId, GfxUiCommand, RenderSubmission, ShellUiFramePacket};
|
||||||
use prometeu_system::CrashReport;
|
use prometeu_system::CrashReport;
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
@@ -20,16 +21,16 @@ impl AppCrashesStep {
|
|||||||
|
|
||||||
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
||||||
// Update peripherals for input on the crash screen
|
// Update peripherals for input on the crash screen
|
||||||
ctx.hw.pad_mut().begin_frame(ctx.signals);
|
ctx.platform.input_mut().pad_mut().begin_frame(ctx.signals);
|
||||||
|
|
||||||
// Error screen: red background, white text
|
let packet = ShellUiFramePacket::new(vec![GfxUiCommand::Clear { color: Color::RED }]);
|
||||||
ctx.hw.gfx_mut().clear(Color::RED);
|
ctx.platform
|
||||||
// For now we just log or show something simple
|
.render_submission_sink()
|
||||||
// In the future, use draw_text
|
.submit_render_submission(RenderSubmission::shell_ui(FrameId::ZERO, packet))
|
||||||
ctx.hw.gfx_mut().present();
|
.expect("firmware crash render submission should publish");
|
||||||
|
|
||||||
// If START is pressed, return to the Hub
|
// If START is pressed, return to the Hub
|
||||||
if ctx.hw.pad().start().down {
|
if ctx.platform.input().pad().start().down {
|
||||||
return Some(FirmwareState::LaunchHub(LaunchHubStep));
|
return Some(FirmwareState::LaunchHub(LaunchHubStep));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,23 +1,72 @@
|
|||||||
use crate::firmware::firmware_state::{AppCrashesStep, FirmwareState};
|
use crate::firmware::firmware_state::{AppCrashesStep, FirmwareState, HubHomeStep};
|
||||||
use crate::firmware::prometeu_context::PrometeuContext;
|
use crate::firmware::prometeu_context::PrometeuContext;
|
||||||
|
use prometeu_hal::app_mode::AppMode;
|
||||||
use prometeu_hal::log::{LogLevel, LogSource};
|
use prometeu_hal::log::{LogLevel, LogSource};
|
||||||
|
use prometeu_system::task::{TaskId, TaskState};
|
||||||
|
use prometeu_system::{CrashReport, ResidentGameState};
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct GameRunningStep;
|
pub struct GameRunningStep {
|
||||||
|
pub task_id: TaskId,
|
||||||
|
}
|
||||||
|
|
||||||
impl GameRunningStep {
|
impl GameRunningStep {
|
||||||
|
pub fn new(task_id: TaskId) -> Self {
|
||||||
|
Self { task_id }
|
||||||
|
}
|
||||||
|
|
||||||
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
||||||
ctx.os.log(LogLevel::Info, LogSource::Pos, 0, "Entering GameRunning".to_string());
|
ctx.os.log(LogLevel::Info, LogSource::Pos, 0, "Entering GameRunning".to_string());
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
||||||
let result = ctx.os.tick(ctx.vm, ctx.signals, ctx.hw);
|
let Some(task_state) = ctx.os.lifecycle().task_state(self.task_id) else {
|
||||||
|
// TODO: is it panic?
|
||||||
|
let report =
|
||||||
|
CrashReport::VmPanic { message: "task is gone, panic!".to_string(), pc: None };
|
||||||
|
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||||
|
};
|
||||||
|
|
||||||
if !ctx.os.logical_frame_active {
|
if task_state != TaskState::Foreground {
|
||||||
ctx.hw.gfx_mut().present();
|
// TODO: is it panic?
|
||||||
|
let report = CrashReport::VmPanic {
|
||||||
|
message: "should be running as foreground, panic!".to_string(),
|
||||||
|
pc: None,
|
||||||
|
};
|
||||||
|
let _ = ctx.os.lifecycle().crash_task(self.task_id, Some(&report));
|
||||||
|
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||||
}
|
}
|
||||||
|
|
||||||
result.map(|report| FirmwareState::AppCrashes(AppCrashesStep { report }))
|
let pause_requested = matches!(
|
||||||
|
ctx.os.lifecycle().resident_game().map(|game| game.state),
|
||||||
|
Some(ResidentGameState::PauseRequested { .. })
|
||||||
|
);
|
||||||
|
let result = ctx.os.vm().tick_session(self.task_id, ctx.signals, ctx.platform);
|
||||||
|
|
||||||
|
if let Some(report) = result {
|
||||||
|
let _ = ctx.os.lifecycle().crash_task(self.task_id, Some(&report));
|
||||||
|
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||||
|
}
|
||||||
|
|
||||||
|
if pause_requested {
|
||||||
|
match ctx.os.lifecycle().advance_game_pause_budget(self.task_id) {
|
||||||
|
Ok(true) => {
|
||||||
|
ctx.os.vm().transition_render_owner(AppMode::Shell, 0);
|
||||||
|
return Some(FirmwareState::HubHome(HubHomeStep));
|
||||||
|
}
|
||||||
|
Ok(false) => {}
|
||||||
|
Err(_) => {
|
||||||
|
let report = CrashReport::VmPanic {
|
||||||
|
message: "failed to advance game pause budget".to_string(),
|
||||||
|
pc: None,
|
||||||
|
};
|
||||||
|
let _ = ctx.os.lifecycle().crash_task(self.task_id, Some(&report));
|
||||||
|
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn on_exit(&mut self, _ctx: &mut PrometeuContext) {}
|
pub fn on_exit(&mut self, _ctx: &mut PrometeuContext) {}
|
||||||
|
|||||||
@@ -1,6 +1,14 @@
|
|||||||
use crate::firmware::firmware_state::{AppCrashesStep, FirmwareState};
|
use crate::firmware::firmware_state::{
|
||||||
|
AppCrashesStep, FirmwareState, LoadCartridgeStep, ShellRunningStep,
|
||||||
|
};
|
||||||
use crate::firmware::prometeu_context::PrometeuContext;
|
use crate::firmware::prometeu_context::PrometeuContext;
|
||||||
|
use crate::firmware::resident_game_termination;
|
||||||
|
use prometeu_hal::app_mode::AppMode;
|
||||||
|
use prometeu_hal::cartridge_loader::CartridgeLoader;
|
||||||
use prometeu_hal::log::{LogLevel, LogSource};
|
use prometeu_hal::log::{LogLevel, LogSource};
|
||||||
|
use prometeu_hal::primitives::Rect;
|
||||||
|
use prometeu_system::SystemProfileAction;
|
||||||
|
use prometeu_system::windows::WindowOwner;
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct HubHomeStep;
|
pub struct HubHomeStep;
|
||||||
@@ -8,30 +16,109 @@ pub struct HubHomeStep;
|
|||||||
impl HubHomeStep {
|
impl HubHomeStep {
|
||||||
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
||||||
ctx.os.log(LogLevel::Info, LogSource::Hub, 0, "Entering HubHome".to_string());
|
ctx.os.log(LogLevel::Info, LogSource::Hub, 0, "Entering HubHome".to_string());
|
||||||
|
ctx.os.windows().remove_all_windows();
|
||||||
|
ctx.hub.init();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
||||||
let mut error = None;
|
let outcome = ctx.hub.update_shell_profile(ctx.os, ctx.platform);
|
||||||
|
if let Some(report) = outcome.crash {
|
||||||
// Always updates the Hub GUI (clears screen and processes input if no focus)
|
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||||
ctx.hub.gui_update(ctx.os, ctx.hw);
|
|
||||||
|
|
||||||
if let Some(focused_id) = ctx.hub.window_manager.focused {
|
|
||||||
if ctx.hw.pad().start().down {
|
|
||||||
ctx.hub.window_manager.remove_window(focused_id);
|
|
||||||
} else {
|
|
||||||
// System App runs here, drawing over the Hub background
|
|
||||||
error = ctx.os.tick(ctx.vm, ctx.signals, ctx.hw);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Renders the System App window borders
|
match outcome.action {
|
||||||
ctx.hub.render(ctx.os, ctx.hw);
|
Some(SystemProfileAction::LaunchNativeShell(app)) => {
|
||||||
|
let task_id = match ctx
|
||||||
|
.os
|
||||||
|
.sessions()
|
||||||
|
.try_create_native_shell_task(app.app_id(), app.title())
|
||||||
|
{
|
||||||
|
Ok(task_id) => task_id,
|
||||||
|
Err(error) => {
|
||||||
|
ctx.os.log(
|
||||||
|
LogLevel::Warn,
|
||||||
|
LogSource::Hub,
|
||||||
|
0,
|
||||||
|
format!("Failed to launch native shell {}: {:?}", app.title(), error),
|
||||||
|
);
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let id = ctx.os.windows().add_window(
|
||||||
|
app.title().to_string(),
|
||||||
|
WindowOwner::Task(task_id),
|
||||||
|
Rect { x: 40, y: 20, w: 400, h: 220 },
|
||||||
|
app.color(),
|
||||||
|
);
|
||||||
|
ctx.os.windows().set_focus(id);
|
||||||
|
return Some(FirmwareState::ShellRunning(ShellRunningStep::new(task_id)));
|
||||||
|
}
|
||||||
|
Some(SystemProfileAction::LaunchGame { target }) => {
|
||||||
|
match CartridgeLoader::load(&target.path) {
|
||||||
|
Ok(cartridge) => {
|
||||||
|
if cartridge.app_mode == AppMode::Game
|
||||||
|
&& let Some(resident_task_id) = ctx.os.lifecycle().resident_game_task()
|
||||||
|
{
|
||||||
|
let resident_app_id = ctx
|
||||||
|
.os
|
||||||
|
.sessions()
|
||||||
|
.vm_session_for_task(resident_task_id)
|
||||||
|
.map(|session| session.app_id)
|
||||||
|
.unwrap_or(0);
|
||||||
|
|
||||||
ctx.hw.gfx_mut().present();
|
if resident_app_id == cartridge.app_id {
|
||||||
|
return Some(FirmwareState::ResumeResidentGame);
|
||||||
|
}
|
||||||
|
|
||||||
if let Some(report) = error {
|
if let Err(error) = resident_game_termination::terminate_resident_game(
|
||||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
ctx.os,
|
||||||
|
ctx.platform,
|
||||||
|
false,
|
||||||
|
) {
|
||||||
|
ctx.os.log(
|
||||||
|
LogLevel::Error,
|
||||||
|
LogSource::Hub,
|
||||||
|
0,
|
||||||
|
format!(
|
||||||
|
"Failed to terminate resident game app_id {} before launching {}: {:?}",
|
||||||
|
resident_app_id, cartridge.title, error
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Some(FirmwareState::LoadCartridge(
|
||||||
|
LoadCartridgeStep::new_game_switch(cartridge),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
ctx.os.log(
|
||||||
|
LogLevel::Error,
|
||||||
|
LogSource::Hub,
|
||||||
|
0,
|
||||||
|
format!(
|
||||||
|
"Failed to launch Home game {}: {:?}",
|
||||||
|
target.path.display(),
|
||||||
|
error
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(SystemProfileAction::KillResidentGame) => {
|
||||||
|
if let Err(error) =
|
||||||
|
resident_game_termination::terminate_resident_game(ctx.os, ctx.platform, true)
|
||||||
|
{
|
||||||
|
ctx.os.log(
|
||||||
|
LogLevel::Error,
|
||||||
|
LogSource::Hub,
|
||||||
|
0,
|
||||||
|
format!("Failed to kill resident game from Hub: {error:?}"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(SystemProfileAction::CloseShell) | None => {}
|
||||||
}
|
}
|
||||||
|
|
||||||
None
|
None
|
||||||
|
|||||||
@@ -1,22 +1,44 @@
|
|||||||
use crate::firmware::firmware_state::{
|
use crate::firmware::firmware_state::{
|
||||||
AppCrashesStep, FirmwareState, GameRunningStep, HubHomeStep,
|
AppCrashesStep, FirmwareState, GameRunningStep, HubHomeStep, ShellRunningStep,
|
||||||
};
|
};
|
||||||
use crate::firmware::prometeu_context::PrometeuContext;
|
use crate::firmware::prometeu_context::PrometeuContext;
|
||||||
use prometeu_hal::cartridge::{AppMode, Cartridge};
|
use crate::firmware::resident_game_termination;
|
||||||
|
use prometeu_hal::app_mode::AppMode;
|
||||||
|
use prometeu_hal::cartridge::Cartridge;
|
||||||
use prometeu_hal::color::Color;
|
use prometeu_hal::color::Color;
|
||||||
use prometeu_hal::log::{LogLevel, LogSource};
|
use prometeu_hal::log::{LogLevel, LogSource};
|
||||||
use prometeu_hal::window::Rect;
|
use prometeu_hal::primitives::Rect;
|
||||||
use prometeu_system::CrashReport;
|
use prometeu_system::CrashReport;
|
||||||
|
use prometeu_system::windows::WindowOwner;
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct LoadCartridgeStep {
|
pub struct LoadCartridgeStep {
|
||||||
pub cartridge: Cartridge,
|
pub cartridge: Cartridge,
|
||||||
init_error: Option<CrashReport>,
|
init_error: Option<CrashReport>,
|
||||||
|
loaded_task_id: Option<prometeu_system::task::TaskId>,
|
||||||
|
loaded_app_mode: Option<AppMode>,
|
||||||
|
failure_recovery: LoadCartridgeFailureRecovery,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
enum LoadCartridgeFailureRecovery {
|
||||||
|
AppCrash,
|
||||||
|
ReturnToHub,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl LoadCartridgeStep {
|
impl LoadCartridgeStep {
|
||||||
pub fn new(cartridge: Cartridge) -> Self {
|
pub fn new(cartridge: Cartridge) -> Self {
|
||||||
Self { cartridge, init_error: None }
|
Self {
|
||||||
|
cartridge,
|
||||||
|
init_error: None,
|
||||||
|
loaded_task_id: None,
|
||||||
|
loaded_app_mode: None,
|
||||||
|
failure_recovery: LoadCartridgeFailureRecovery::AppCrash,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new_game_switch(cartridge: Cartridge) -> Self {
|
||||||
|
Self { failure_recovery: LoadCartridgeFailureRecovery::ReturnToHub, ..Self::new(cartridge) }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
||||||
@@ -27,35 +49,86 @@ impl LoadCartridgeStep {
|
|||||||
format!("Loading cartridge: {}", self.cartridge.title),
|
format!("Loading cartridge: {}", self.cartridge.title),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
ctx.platform.game2d_frame_composer().unbind_scene();
|
||||||
|
|
||||||
// Initialize Asset Manager
|
// Initialize Asset Manager
|
||||||
ctx.hw.assets_mut().initialize_for_cartridge(
|
ctx.platform.assets_mut().initialize_for_cartridge(
|
||||||
self.cartridge.asset_table.clone(),
|
self.cartridge.asset_table.clone(),
|
||||||
self.cartridge.preload.clone(),
|
self.cartridge.preload.clone(),
|
||||||
self.cartridge.assets.clone(),
|
self.cartridge.assets.clone(),
|
||||||
);
|
);
|
||||||
|
|
||||||
self.init_error = ctx.os.initialize_vm(ctx.vm, &self.cartridge).err();
|
match ctx.os.sessions().load_vm_cartridge(&self.cartridge) {
|
||||||
|
Ok(loaded) => {
|
||||||
|
self.loaded_task_id = Some(loaded.task_id);
|
||||||
|
self.loaded_app_mode = Some(loaded.app_mode);
|
||||||
|
}
|
||||||
|
Err(report) => {
|
||||||
|
self.init_error = Some(report.into_crash_report("load VM cartridge into session"));
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
||||||
if let Some(report) = self.init_error.take() {
|
if let Some(report) = self.init_error.take() {
|
||||||
|
if self.failure_recovery == LoadCartridgeFailureRecovery::ReturnToHub {
|
||||||
|
if self.cartridge.app_mode == AppMode::Game
|
||||||
|
&& let Some(task_id) = ctx.os.lifecycle().resident_game_task()
|
||||||
|
{
|
||||||
|
let is_partial_target = ctx
|
||||||
|
.os
|
||||||
|
.sessions()
|
||||||
|
.vm_session_for_task(task_id)
|
||||||
|
.map(|session| session.app_id == self.cartridge.app_id)
|
||||||
|
.unwrap_or(false);
|
||||||
|
|
||||||
|
if is_partial_target {
|
||||||
|
let _ = resident_game_termination::terminate_resident_game(
|
||||||
|
ctx.os,
|
||||||
|
ctx.platform,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.os.log(
|
||||||
|
LogLevel::Error,
|
||||||
|
LogSource::Hub,
|
||||||
|
0,
|
||||||
|
format!(
|
||||||
|
"Failed to switch to game {} app_id {}; returning to Home: {:?}",
|
||||||
|
self.cartridge.title, self.cartridge.app_id, report
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return Some(FirmwareState::HubHome(HubHomeStep));
|
||||||
|
}
|
||||||
|
|
||||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||||
}
|
}
|
||||||
|
|
||||||
if self.cartridge.app_mode == AppMode::System {
|
let Some(task_id) = self.loaded_task_id.take() else {
|
||||||
let id = ctx.hub.window_manager.add_window(
|
let report = CrashReport::VmPanic {
|
||||||
|
message: format!(
|
||||||
|
"cartridge {} was not loaded into a VM session",
|
||||||
|
self.cartridge.title
|
||||||
|
),
|
||||||
|
pc: None,
|
||||||
|
};
|
||||||
|
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||||
|
};
|
||||||
|
|
||||||
|
if self.loaded_app_mode == Some(AppMode::Shell) {
|
||||||
|
let id = ctx.os.windows().add_window(
|
||||||
self.cartridge.title.clone(),
|
self.cartridge.title.clone(),
|
||||||
|
WindowOwner::Task(task_id),
|
||||||
Rect { x: 40, y: 20, w: 240, h: 140 },
|
Rect { x: 40, y: 20, w: 240, h: 140 },
|
||||||
Color::WHITE,
|
Color::WHITE,
|
||||||
);
|
);
|
||||||
ctx.hub.window_manager.set_focus(id);
|
ctx.os.windows().set_focus(id);
|
||||||
|
return Some(FirmwareState::ShellRunning(ShellRunningStep::new(task_id)));
|
||||||
// System apps do not change the firmware state to GameRunning.
|
|
||||||
// They run in the background or via windows in the Hub.
|
|
||||||
return Some(FirmwareState::HubHome(HubHomeStep));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Some(FirmwareState::GameRunning(GameRunningStep))
|
Some(FirmwareState::GameRunning(GameRunningStep::new(task_id)))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn on_exit(&mut self, _ctx: &mut PrometeuContext) {}
|
pub fn on_exit(&mut self, _ctx: &mut PrometeuContext) {}
|
||||||
|
|||||||
@@ -9,7 +9,8 @@ pub struct ResetStep;
|
|||||||
impl ResetStep {
|
impl ResetStep {
|
||||||
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
||||||
ctx.os.log(LogLevel::Info, LogSource::Pos, 0, "Firmware Reset".to_string());
|
ctx.os.log(LogLevel::Info, LogSource::Pos, 0, "Firmware Reset".to_string());
|
||||||
ctx.os.reset(ctx.vm);
|
ctx.os.sessions().clear_vm_sessions();
|
||||||
|
ctx.os.vm().reset_global_runtime_state();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
||||||
|
|||||||
@@ -0,0 +1,131 @@
|
|||||||
|
use crate::firmware::firmware_state::{AppCrashesStep, FirmwareState, HubHomeStep};
|
||||||
|
use crate::firmware::prometeu_context::PrometeuContext;
|
||||||
|
use prometeu_hal::log::LogSource;
|
||||||
|
use prometeu_system::process::ProcessKind;
|
||||||
|
use prometeu_system::task::{TaskId, TaskState};
|
||||||
|
use prometeu_system::{CrashReport, SystemProfileAction};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ShellRunningStep {
|
||||||
|
pub task_id: TaskId,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ShellRunningStep {
|
||||||
|
pub fn new(task_id: TaskId) -> Self {
|
||||||
|
Self { task_id }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
||||||
|
ctx.os.info(LogSource::Hub, "Entering ShellRunning".to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
||||||
|
let Some(task_state) = ctx.os.lifecycle().task_state(self.task_id) else {
|
||||||
|
let report = CrashReport::VmPanic {
|
||||||
|
message: format!("ShellRunningStep has no task for {:?}", self.task_id),
|
||||||
|
pc: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||||
|
};
|
||||||
|
|
||||||
|
match task_state {
|
||||||
|
TaskState::Foreground => {
|
||||||
|
// Continue below.
|
||||||
|
}
|
||||||
|
|
||||||
|
TaskState::Closed => {
|
||||||
|
return Some(FirmwareState::HubHome(HubHomeStep));
|
||||||
|
}
|
||||||
|
|
||||||
|
TaskState::Crashed => {
|
||||||
|
let report = CrashReport::VmPanic {
|
||||||
|
message: format!("Shell task {:?} is already crashed", self.task_id),
|
||||||
|
pc: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||||
|
}
|
||||||
|
|
||||||
|
TaskState::Suspended | TaskState::Background => {
|
||||||
|
let report = CrashReport::VmPanic {
|
||||||
|
message: format!(
|
||||||
|
"ShellRunningStep expected foreground task {:?}, got {:?}",
|
||||||
|
self.task_id, task_state,
|
||||||
|
),
|
||||||
|
pc: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let process_kind = match ctx.os.lifecycle().process_kind_for_task(self.task_id) {
|
||||||
|
Ok(process_kind) => process_kind,
|
||||||
|
Err(error) => {
|
||||||
|
let report = CrashReport::VmPanic {
|
||||||
|
message: format!(
|
||||||
|
"ShellRunningStep cannot resolve process for {:?}: {:?}",
|
||||||
|
self.task_id, error,
|
||||||
|
),
|
||||||
|
pc: None,
|
||||||
|
};
|
||||||
|
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let outcome = match process_kind {
|
||||||
|
ProcessKind::VmShell => {
|
||||||
|
ctx.hub.update_vm_shell_profile(ctx.os, self.task_id, ctx.signals, ctx.platform)
|
||||||
|
}
|
||||||
|
ProcessKind::NativeShell => ctx.hub.update_native_shell_profile(ctx.os, ctx.platform),
|
||||||
|
ProcessKind::VmGame => {
|
||||||
|
let report = CrashReport::VmPanic {
|
||||||
|
message: format!(
|
||||||
|
"ShellRunningStep expected shell process for {:?}, got VmGame",
|
||||||
|
self.task_id,
|
||||||
|
),
|
||||||
|
pc: None,
|
||||||
|
};
|
||||||
|
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(report) = outcome.crash {
|
||||||
|
let _ = ctx.os.lifecycle().crash_task(self.task_id, Some(&report));
|
||||||
|
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||||
|
}
|
||||||
|
|
||||||
|
if outcome.action == Some(SystemProfileAction::CloseShell) {
|
||||||
|
self.close_current_shell(ctx);
|
||||||
|
return Some(FirmwareState::HubHome(HubHomeStep));
|
||||||
|
}
|
||||||
|
|
||||||
|
if !ctx.os.windows().focused_window_belongs_to_task(self.task_id) {
|
||||||
|
ctx.os.info(
|
||||||
|
LogSource::Hub,
|
||||||
|
format!(
|
||||||
|
"Closing shell task {:?}: focused window does not belong to task",
|
||||||
|
self.task_id,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
self.close_current_shell(ctx);
|
||||||
|
return Some(FirmwareState::HubHome(HubHomeStep));
|
||||||
|
}
|
||||||
|
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
fn close_current_shell(&mut self, ctx: &mut PrometeuContext) {
|
||||||
|
if let Err(error) = ctx.os.lifecycle().close_task(self.task_id) {
|
||||||
|
ctx.os.error(
|
||||||
|
LogSource::Hub,
|
||||||
|
format!("Failed to close shell task {:?}: {:?}", self.task_id, error),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn on_exit(&mut self, ctx: &mut PrometeuContext) {
|
||||||
|
ctx.os.info(LogSource::Hub, "Exiting ShellRunning".to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,8 @@ use crate::firmware::firmware_state::{FirmwareState, LaunchHubStep};
|
|||||||
use crate::firmware::prometeu_context::PrometeuContext;
|
use crate::firmware::prometeu_context::PrometeuContext;
|
||||||
use prometeu_hal::color::Color;
|
use prometeu_hal::color::Color;
|
||||||
use prometeu_hal::log::{LogLevel, LogSource};
|
use prometeu_hal::log::{LogLevel, LogSource};
|
||||||
|
use prometeu_hal::primitives::Rect;
|
||||||
|
use prometeu_hal::{FrameId, GfxUiCommand, RenderSubmission, ShellUiFramePacket};
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct SplashScreenStep {
|
pub struct SplashScreenStep {
|
||||||
@@ -12,7 +14,7 @@ impl SplashScreenStep {
|
|||||||
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
||||||
ctx.os.log(LogLevel::Info, LogSource::Pos, 0, "Showing SplashScreen".to_string());
|
ctx.os.log(LogLevel::Info, LogSource::Pos, 0, "Showing SplashScreen".to_string());
|
||||||
// Play sound on enter
|
// Play sound on enter
|
||||||
// ctx.hw.audio_mut().play(0, 0, 0, 255, 127, 1.0, 0, LoopMode::Off);
|
// ctx.platform.audio_mut().play(0, 0, 0, 255, 127, 1.0, 0, LoopMode::Off);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
||||||
@@ -20,13 +22,10 @@ impl SplashScreenStep {
|
|||||||
const TOTAL_DURATION: u32 = 240; // 4 seconds total (updated from 2s based on total_duration logic)
|
const TOTAL_DURATION: u32 = 240; // 4 seconds total (updated from 2s based on total_duration logic)
|
||||||
|
|
||||||
// Update peripherals for input
|
// Update peripherals for input
|
||||||
ctx.hw.pad_mut().begin_frame(ctx.signals);
|
ctx.platform.input_mut().pad_mut().begin_frame(ctx.signals);
|
||||||
|
|
||||||
// Clear screen
|
|
||||||
ctx.hw.gfx_mut().clear(Color::BLACK);
|
|
||||||
|
|
||||||
// Draw expanding square
|
// Draw expanding square
|
||||||
let (sw, sh) = ctx.hw.gfx().size();
|
let (sw, sh) = ctx.platform.display_size();
|
||||||
let max_size = (sw.min(sh) as i32 / 2).max(1);
|
let max_size = (sw.min(sh) as i32 / 2).max(1);
|
||||||
|
|
||||||
let current_size = if self.frame < ANIMATION_DURATION {
|
let current_size = if self.frame < ANIMATION_DURATION {
|
||||||
@@ -38,12 +37,21 @@ impl SplashScreenStep {
|
|||||||
let x = (sw as i32 - current_size) / 2;
|
let x = (sw as i32 - current_size) / 2;
|
||||||
let y = (sh as i32 - current_size) / 2;
|
let y = (sh as i32 - current_size) / 2;
|
||||||
|
|
||||||
ctx.hw.gfx_mut().fill_rect(x, y, current_size, current_size, Color::WHITE);
|
let packet = ShellUiFramePacket::new(vec![
|
||||||
ctx.hw.gfx_mut().present();
|
GfxUiCommand::Clear { color: Color::ORANGE },
|
||||||
|
GfxUiCommand::FillRect {
|
||||||
|
rect: Rect { x, y, w: current_size, h: current_size },
|
||||||
|
color: Color::WHITE,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
ctx.platform
|
||||||
|
.render_submission_sink()
|
||||||
|
.submit_render_submission(RenderSubmission::shell_ui(FrameId::ZERO, packet))
|
||||||
|
.expect("firmware splash render submission should publish");
|
||||||
|
|
||||||
// Transition logic
|
// Transition logic
|
||||||
// If any button is pressed at any time after the animation ends
|
// If any button is pressed at any time after the animation ends
|
||||||
if self.frame >= ANIMATION_DURATION && ctx.hw.pad().any() {
|
if self.frame >= ANIMATION_DURATION && ctx.platform.input().pad().any() {
|
||||||
return Some(FirmwareState::LaunchHub(LaunchHubStep));
|
return Some(FirmwareState::LaunchHub(LaunchHubStep));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,8 +9,10 @@ pub(crate) mod firmware_step_hub_home;
|
|||||||
pub(crate) mod firmware_step_launch_hub;
|
pub(crate) mod firmware_step_launch_hub;
|
||||||
pub(crate) mod firmware_step_load_cartridge;
|
pub(crate) mod firmware_step_load_cartridge;
|
||||||
pub(crate) mod firmware_step_reset;
|
pub(crate) mod firmware_step_reset;
|
||||||
|
pub(crate) mod firmware_step_shell_running;
|
||||||
pub(crate) mod firmware_step_splash_screen;
|
pub(crate) mod firmware_step_splash_screen;
|
||||||
mod prometeu_context;
|
mod prometeu_context;
|
||||||
|
pub(crate) mod resident_game_termination;
|
||||||
|
|
||||||
pub use boot_target::BootTarget;
|
pub use boot_target::BootTarget;
|
||||||
pub use firmware::Firmware;
|
pub use firmware::Firmware;
|
||||||
|
|||||||
@@ -1,13 +1,11 @@
|
|||||||
use crate::firmware::boot_target::BootTarget;
|
use crate::firmware::boot_target::BootTarget;
|
||||||
use prometeu_hal::{HardwareBridge, InputSignals};
|
use prometeu_hal::{InputSignals, RuntimePlatform};
|
||||||
use prometeu_system::{PrometeuHub, VirtualMachineRuntime};
|
use prometeu_system::{PrometeuHub, SystemOS};
|
||||||
use prometeu_vm::VirtualMachine;
|
|
||||||
|
|
||||||
pub struct PrometeuContext<'a> {
|
pub struct PrometeuContext<'a> {
|
||||||
pub vm: &'a mut VirtualMachine,
|
pub os: &'a mut SystemOS,
|
||||||
pub os: &'a mut VirtualMachineRuntime,
|
|
||||||
pub hub: &'a mut PrometeuHub,
|
pub hub: &'a mut PrometeuHub,
|
||||||
pub boot_target: &'a BootTarget,
|
pub boot_target: &'a BootTarget,
|
||||||
pub signals: &'a InputSignals,
|
pub signals: &'a InputSignals,
|
||||||
pub hw: &'a mut dyn HardwareBridge,
|
pub platform: &'a mut dyn RuntimePlatform,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
use prometeu_hal::RuntimePlatform;
|
||||||
|
use prometeu_hal::app_mode::AppMode;
|
||||||
|
use prometeu_hal::log::LogSource;
|
||||||
|
use prometeu_system::task::TaskId;
|
||||||
|
use prometeu_system::{LifecycleError, SystemOS};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub(crate) enum ResidentGameTerminationOutcome {
|
||||||
|
NoResidentGame,
|
||||||
|
Terminated { task_id: TaskId, title: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn terminate_resident_game(
|
||||||
|
os: &mut SystemOS,
|
||||||
|
platform: &mut dyn RuntimePlatform,
|
||||||
|
log_manual_hub_kill: bool,
|
||||||
|
) -> Result<ResidentGameTerminationOutcome, LifecycleError> {
|
||||||
|
let Some(task_id) = os.lifecycle().resident_game_task() else {
|
||||||
|
return Ok(ResidentGameTerminationOutcome::NoResidentGame);
|
||||||
|
};
|
||||||
|
|
||||||
|
let title = os
|
||||||
|
.sessions()
|
||||||
|
.vm_session_for_task(task_id)
|
||||||
|
.map(|session| session.title.clone())
|
||||||
|
.unwrap_or_else(|| "<unknown>".to_string());
|
||||||
|
|
||||||
|
let terminated = os.lifecycle().terminate_resident_game()?;
|
||||||
|
let Some(task_id) = terminated else {
|
||||||
|
return Ok(ResidentGameTerminationOutcome::NoResidentGame);
|
||||||
|
};
|
||||||
|
|
||||||
|
os.vm().transition_render_owner(AppMode::Shell, 0);
|
||||||
|
platform.game2d_frame_composer().unbind_scene();
|
||||||
|
platform.assets_mut().shutdown();
|
||||||
|
|
||||||
|
if log_manual_hub_kill {
|
||||||
|
os.info(LogSource::Hub, format!("Resident game killed from Hub: {title}"));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(ResidentGameTerminationOutcome::Terminated { task_id, title })
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
|
||||||
|
pub enum AppMode {
|
||||||
|
Game,
|
||||||
|
Shell,
|
||||||
|
}
|
||||||
@@ -53,7 +53,11 @@ pub const SCENE_PAYLOAD_MAGIC_V1: [u8; 4] = *b"SCNE";
|
|||||||
pub const SCENE_PAYLOAD_VERSION_V1: u16 = 1;
|
pub const SCENE_PAYLOAD_VERSION_V1: u16 = 1;
|
||||||
pub const SCENE_LAYER_COUNT_V1: usize = 4;
|
pub const SCENE_LAYER_COUNT_V1: usize = 4;
|
||||||
pub const SCENE_HEADER_BYTES_V1: usize = 12;
|
pub const SCENE_HEADER_BYTES_V1: usize = 12;
|
||||||
pub const SCENE_LAYER_HEADER_BYTES_V1: usize = 28;
|
// Per-layer header:
|
||||||
|
// flags:u8 + glyph_asset_id:i32 + tile_size:u8 + reserved:u16
|
||||||
|
// + parallax_x:f32 + parallax_y:f32 + width:u32 + height:u32
|
||||||
|
// + tile_count:u32 + reserved:u32
|
||||||
|
pub const SCENE_LAYER_HEADER_BYTES_V1: usize = 32;
|
||||||
pub const SCENE_TILE_RECORD_BYTES_V1: usize = 4;
|
pub const SCENE_TILE_RECORD_BYTES_V1: usize = 4;
|
||||||
pub const SCENE_DECODED_LAYER_OVERHEAD_BYTES_V1: usize = 16;
|
pub const SCENE_DECODED_LAYER_OVERHEAD_BYTES_V1: usize = 16;
|
||||||
|
|
||||||
@@ -108,6 +112,12 @@ pub enum LoadStatus {
|
|||||||
CANCELED = 4,
|
CANCELED = 4,
|
||||||
ERROR = 5,
|
ERROR = 5,
|
||||||
UnknownHandle = 6,
|
UnknownHandle = 6,
|
||||||
|
QUEUED = 7,
|
||||||
|
ACTIVE = 8,
|
||||||
|
SUPERSEDED = 9,
|
||||||
|
EMPTY = 10,
|
||||||
|
INVALID = 11,
|
||||||
|
BackendUnavailable = 12,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
@@ -125,6 +135,36 @@ pub enum AssetOpStatus {
|
|||||||
Ok = 0,
|
Ok = 0,
|
||||||
UnknownHandle = 1,
|
UnknownHandle = 1,
|
||||||
InvalidState = 2,
|
InvalidState = 2,
|
||||||
|
Superseded = 3,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct AssetBacklogInfo {
|
||||||
|
pub status: AssetOpStatus,
|
||||||
|
pub pending_count: u32,
|
||||||
|
pub active_handle: HandleId,
|
||||||
|
pub active_asset_id: Option<AssetId>,
|
||||||
|
pub active_bank_type: Option<BankType>,
|
||||||
|
pub active_slot: Option<usize>,
|
||||||
|
pub active_progress: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct AssetBacklogPosition {
|
||||||
|
pub status: AssetOpStatus,
|
||||||
|
pub state: LoadStatus,
|
||||||
|
pub position: u32,
|
||||||
|
pub progress: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct AssetTargetStatus {
|
||||||
|
pub status: AssetOpStatus,
|
||||||
|
pub asset_id: Option<AssetId>,
|
||||||
|
pub handle: HandleId,
|
||||||
|
pub state: LoadStatus,
|
||||||
|
pub position: u32,
|
||||||
|
pub progress: u16,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
use crate::asset::{
|
use crate::asset::{
|
||||||
AssetEntry, AssetId, AssetLoadError, AssetOpStatus, BankTelemetry, HandleId, LoadStatus,
|
AssetBacklogInfo, AssetBacklogPosition, AssetEntry, AssetId, AssetLoadError, AssetOpStatus,
|
||||||
PreloadEntry, SlotRef, SlotStats,
|
AssetTargetStatus, BankTelemetry, BankType, HandleId, LoadStatus, PreloadEntry, SlotRef,
|
||||||
|
SlotStats,
|
||||||
};
|
};
|
||||||
use crate::cartridge::AssetsPayloadSource;
|
use crate::cartridge::AssetsPayloadSource;
|
||||||
|
|
||||||
@@ -15,6 +16,12 @@ pub trait AssetBridge {
|
|||||||
fn status(&self, handle: HandleId) -> LoadStatus;
|
fn status(&self, handle: HandleId) -> LoadStatus;
|
||||||
fn commit(&self, handle: HandleId) -> AssetOpStatus;
|
fn commit(&self, handle: HandleId) -> AssetOpStatus;
|
||||||
fn cancel(&self, handle: HandleId) -> AssetOpStatus;
|
fn cancel(&self, handle: HandleId) -> AssetOpStatus;
|
||||||
|
fn backlog_info(&self) -> AssetBacklogInfo;
|
||||||
|
fn backlog_position(&self, handle: HandleId) -> AssetBacklogPosition;
|
||||||
|
fn backlog_move(&self, handle: HandleId, new_position: usize) -> AssetOpStatus;
|
||||||
|
fn backlog_promote(&self, handle: HandleId) -> AssetOpStatus;
|
||||||
|
fn backlog_demote(&self, handle: HandleId) -> AssetOpStatus;
|
||||||
|
fn target_status(&self, bank_type: BankType, slot: usize) -> AssetTargetStatus;
|
||||||
fn apply_commits(&self);
|
fn apply_commits(&self);
|
||||||
fn bank_telemetry(&self) -> Vec<BankTelemetry>;
|
fn bank_telemetry(&self) -> Vec<BankTelemetry>;
|
||||||
fn slot_info(&self, slot: SlotRef) -> SlotStats;
|
fn slot_info(&self, slot: SlotRef) -> SlotStats;
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
use crate::app_mode::AppMode;
|
||||||
use crate::asset::{AssetEntry, PreloadEntry};
|
use crate::asset::{AssetEntry, PreloadEntry};
|
||||||
use crate::syscalls::CapFlags;
|
use crate::syscalls::CapFlags;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
@@ -10,12 +11,6 @@ pub const ASSETS_PA_MAGIC: [u8; 4] = *b"ASPA";
|
|||||||
pub const ASSETS_PA_SCHEMA_VERSION: u32 = 1;
|
pub const ASSETS_PA_SCHEMA_VERSION: u32 = 1;
|
||||||
pub const ASSETS_PA_PRELUDE_SIZE: usize = 32;
|
pub const ASSETS_PA_PRELUDE_SIZE: usize = 32;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
|
|
||||||
pub enum AppMode {
|
|
||||||
Game,
|
|
||||||
System,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct Cartridge {
|
pub struct Cartridge {
|
||||||
pub app_id: u32,
|
pub app_id: u32,
|
||||||
@@ -291,6 +286,9 @@ pub enum Capability {
|
|||||||
None,
|
None,
|
||||||
System,
|
System,
|
||||||
Gfx,
|
Gfx,
|
||||||
|
Composer,
|
||||||
|
Gfx2d,
|
||||||
|
Gfxui,
|
||||||
Audio,
|
Audio,
|
||||||
Fs,
|
Fs,
|
||||||
Log,
|
Log,
|
||||||
@@ -299,7 +297,7 @@ pub enum Capability {
|
|||||||
All,
|
All,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
pub struct CartridgeManifest {
|
pub struct CartridgeManifest {
|
||||||
pub magic: String,
|
pub magic: String,
|
||||||
pub cartridge_version: u32,
|
pub cartridge_version: u32,
|
||||||
|
|||||||
@@ -117,6 +117,9 @@ fn normalize_capabilities(capabilities: &[Capability]) -> Result<CapFlags, Cartr
|
|||||||
Capability::None => caps::NONE,
|
Capability::None => caps::NONE,
|
||||||
Capability::System => caps::SYSTEM,
|
Capability::System => caps::SYSTEM,
|
||||||
Capability::Gfx => caps::GFX,
|
Capability::Gfx => caps::GFX,
|
||||||
|
Capability::Composer => caps::COMPOSER,
|
||||||
|
Capability::Gfx2d => caps::GFX2D,
|
||||||
|
Capability::Gfxui => caps::GFXUI,
|
||||||
Capability::Audio => caps::AUDIO,
|
Capability::Audio => caps::AUDIO,
|
||||||
Capability::Fs => caps::FS,
|
Capability::Fs => caps::FS,
|
||||||
Capability::Log => caps::LOG,
|
Capability::Log => caps::LOG,
|
||||||
@@ -200,7 +203,7 @@ mod tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
use crate::asset::{AssetCodec, AssetEntry, BankType, PreloadEntry};
|
use crate::asset::{AssetCodec, AssetEntry, BankType, PreloadEntry};
|
||||||
use crate::cartridge::{ASSETS_PA_MAGIC, ASSETS_PA_SCHEMA_VERSION, AssetsPackPrelude};
|
use crate::cartridge::{ASSETS_PA_MAGIC, ASSETS_PA_SCHEMA_VERSION, AssetsPackPrelude};
|
||||||
use crate::glyph_bank::GLYPH_BANK_PALETTE_COUNT_V1;
|
use crate::glyph_bank::GLYPH_BANK_MAX_PALETTE_COUNT_V1;
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::atomic::{AtomicU64, Ordering};
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
@@ -366,14 +369,14 @@ mod tests {
|
|||||||
bank_type: BankType::GLYPH,
|
bank_type: BankType::GLYPH,
|
||||||
offset,
|
offset,
|
||||||
size,
|
size,
|
||||||
decoded_size: 16 * 16 + (GLYPH_BANK_PALETTE_COUNT_V1 as u64 * 16 * 2),
|
decoded_size: 16 * 16 + (GLYPH_BANK_MAX_PALETTE_COUNT_V1 as u64 * 16 * 4),
|
||||||
codec: AssetCodec::None,
|
codec: AssetCodec::None,
|
||||||
metadata: json!({
|
metadata: json!({
|
||||||
"tile_size": 16,
|
"tile_size": 16,
|
||||||
"width": 16,
|
"width": 16,
|
||||||
"height": 16,
|
"height": 16,
|
||||||
"palette_count": GLYPH_BANK_PALETTE_COUNT_V1,
|
"palette_count": GLYPH_BANK_MAX_PALETTE_COUNT_V1,
|
||||||
"palette_authored": GLYPH_BANK_PALETTE_COUNT_V1
|
"palette_authored": GLYPH_BANK_MAX_PALETTE_COUNT_V1
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -449,14 +452,14 @@ mod tests {
|
|||||||
bank_type: BankType::GLYPH,
|
bank_type: BankType::GLYPH,
|
||||||
offset: 4,
|
offset: 4,
|
||||||
size: 4,
|
size: 4,
|
||||||
decoded_size: 16 * 16 + (GLYPH_BANK_PALETTE_COUNT_V1 as u64 * 16 * 2),
|
decoded_size: 16 * 16 + (GLYPH_BANK_MAX_PALETTE_COUNT_V1 as u64 * 16 * 4),
|
||||||
codec: AssetCodec::None,
|
codec: AssetCodec::None,
|
||||||
metadata: json!({
|
metadata: json!({
|
||||||
"tile_size": 16,
|
"tile_size": 16,
|
||||||
"width": 16,
|
"width": 16,
|
||||||
"height": 16,
|
"height": 16,
|
||||||
"palette_count": GLYPH_BANK_PALETTE_COUNT_V1,
|
"palette_count": GLYPH_BANK_MAX_PALETTE_COUNT_V1,
|
||||||
"palette_authored": GLYPH_BANK_PALETTE_COUNT_V1
|
"palette_authored": GLYPH_BANK_MAX_PALETTE_COUNT_V1
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
@@ -516,8 +519,8 @@ mod tests {
|
|||||||
"tile_size": 16,
|
"tile_size": 16,
|
||||||
"width": 16,
|
"width": 16,
|
||||||
"height": 16,
|
"height": 16,
|
||||||
"palette_count": GLYPH_BANK_PALETTE_COUNT_V1,
|
"palette_count": GLYPH_BANK_MAX_PALETTE_COUNT_V1,
|
||||||
"palette_authored": GLYPH_BANK_PALETTE_COUNT_V1
|
"palette_authored": GLYPH_BANK_MAX_PALETTE_COUNT_V1
|
||||||
}
|
}
|
||||||
}],
|
}],
|
||||||
"preload": []
|
"preload": []
|
||||||
@@ -558,8 +561,8 @@ mod tests {
|
|||||||
"tile_size": 16,
|
"tile_size": 16,
|
||||||
"width": 16,
|
"width": 16,
|
||||||
"height": 16,
|
"height": 16,
|
||||||
"palette_count": GLYPH_BANK_PALETTE_COUNT_V1,
|
"palette_count": GLYPH_BANK_MAX_PALETTE_COUNT_V1,
|
||||||
"palette_authored": GLYPH_BANK_PALETTE_COUNT_V1
|
"palette_authored": GLYPH_BANK_MAX_PALETTE_COUNT_V1
|
||||||
}
|
}
|
||||||
}],
|
}],
|
||||||
"preload": []
|
"preload": []
|
||||||
|
|||||||
@@ -1,75 +1,67 @@
|
|||||||
/// Represents a 16-bit color in the RGB565 format.
|
/// Represents a canonical RGBA8888 color in RGBA channel order.
|
||||||
///
|
|
||||||
/// The RGB565 format is a common high-color representation for embedded systems:
|
|
||||||
/// - **Red**: 5 bits (0..31)
|
|
||||||
/// - **Green**: 6 bits (0..63)
|
|
||||||
/// - **Blue**: 5 bits (0..31)
|
|
||||||
///
|
|
||||||
/// Prometeu does not have a hardware alpha channel. Transparency is achieved
|
|
||||||
/// by using a specific color key (Magenta / 0xF81F) which the GFX engine
|
|
||||||
/// skips during rendering.
|
|
||||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||||
pub struct Color(pub u16);
|
pub struct Color(pub u32);
|
||||||
|
|
||||||
impl Color {
|
impl Color {
|
||||||
pub const BLACK: Self = Self::rgb(0, 0, 0); // 0x0000
|
pub const BLACK: Self = Self::rgb(0, 0, 0);
|
||||||
pub const WHITE: Self = Self::rgb(255, 255, 255); // 0xFFFF
|
pub const WHITE: Self = Self::rgb(255, 255, 255);
|
||||||
pub const RED: Self = Self::rgb(255, 0, 0); // 0xF800
|
pub const RED: Self = Self::rgb(255, 0, 0);
|
||||||
pub const GREEN: Self = Self::rgb(0, 255, 0); // 0x07E0
|
pub const GREEN: Self = Self::rgb(0, 255, 0);
|
||||||
pub const BLUE: Self = Self::rgb(0, 0, 255); // 0x001F
|
pub const BLUE: Self = Self::rgb(0, 0, 255);
|
||||||
pub const YELLOW: Self = Self::rgb(255, 255, 0); // 0xFFE0
|
pub const YELLOW: Self = Self::rgb(255, 255, 0);
|
||||||
pub const ORANGE: Self = Self::rgb(255, 128, 0);
|
pub const ORANGE: Self = Self::rgb(255, 128, 0);
|
||||||
pub const INDIGO: Self = Self::rgb(75, 0, 130);
|
pub const INDIGO: Self = Self::rgb(75, 0, 130);
|
||||||
pub const GRAY: Self = Self::rgb(128, 128, 128);
|
pub const GRAY: Self = Self::rgb(128, 128, 128);
|
||||||
pub const CYAN: Self = Self::rgb(0, 255, 255); // 0x07FF
|
pub const CYAN: Self = Self::rgb(0, 255, 255);
|
||||||
pub const MAGENTA: Self = Self::rgb(255, 0, 255); // 0xF81F
|
pub const MAGENTA: Self = Self::rgb(255, 0, 255);
|
||||||
pub const COLOR_KEY: Self = Self::MAGENTA;
|
pub const TRANSPARENT: Self = Self::rgba(0, 0, 0, 0);
|
||||||
pub const TRANSPARENT: Self = Self::MAGENTA;
|
#[deprecated(note = "Use RGBA alpha transparency; COLOR_KEY is temporary migration residue.")]
|
||||||
|
pub const COLOR_KEY: Self = Self::TRANSPARENT;
|
||||||
|
|
||||||
/// Extracts channels in the native RGB565 range:
|
/// Extracts RGBA8888 channels from canonical RGBA raw order.
|
||||||
/// R: 0..31, G: 0..63, B: 0..31
|
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub const fn unpack_to_native(px: u16) -> (u8, u8, u8) {
|
pub const fn unpack_to_native(px: u32) -> (u8, u8, u8, u8) {
|
||||||
let r = ((px >> 11) & 0x1F) as u8;
|
let r = ((px >> 24) & 0xFF) as u8;
|
||||||
let g = ((px >> 5) & 0x3F) as u8;
|
let g = ((px >> 16) & 0xFF) as u8;
|
||||||
let b = (px & 0x1F) as u8;
|
let b = ((px >> 8) & 0xFF) as u8;
|
||||||
(r, g, b)
|
let a = (px & 0xFF) as u8;
|
||||||
|
(r, g, b, a)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Packs channels from the native RGB565 range into a pixel:
|
/// Packs RGBA8888 channels into canonical RGBA raw order.
|
||||||
/// R: 0..31, G: 0..63, B: 0..31
|
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub const fn pack_from_native(r: u8, g: u8, b: u8) -> u16 {
|
pub const fn pack_from_native(r: u8, g: u8, b: u8, a: u8) -> u32 {
|
||||||
((r as u16 & 0x1F) << 11) | ((g as u16 & 0x3F) << 5) | (b as u16 & 0x1F)
|
((r as u32) << 24) | ((g as u32) << 16) | ((b as u32) << 8) | a as u32
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Creates an RGB565 color from 8-bit components (0..255).
|
/// Creates an opaque RGBA8888 color from 8-bit RGB components.
|
||||||
pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
|
pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
|
||||||
let r5 = (r as u16 >> 3) & 0x1F;
|
Self::rgba(r, g, b, 255)
|
||||||
let g6 = (g as u16 >> 2) & 0x3F;
|
}
|
||||||
let b5 = (b as u16 >> 3) & 0x1F;
|
|
||||||
|
|
||||||
Self((r5 << 11) | (g6 << 5) | b5)
|
pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Self {
|
||||||
|
Self(Self::pack_from_native(r, g, b, a))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub const fn gray_scale(c: u8) -> Self {
|
pub const fn gray_scale(c: u8) -> Self {
|
||||||
Self::rgb(c, c, c)
|
Self::rgb(c, c, c)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub const fn from_raw(raw: u16) -> Self {
|
pub const fn from_raw(raw: u32) -> Self {
|
||||||
Self(raw)
|
Self(raw)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub const fn raw(self) -> u16 {
|
pub const fn raw(self) -> u32 {
|
||||||
self.0
|
self.0
|
||||||
}
|
}
|
||||||
|
|
||||||
pub const fn hex(self) -> i32 {
|
pub const fn hex(self) -> i32 {
|
||||||
let (r5, g6, b5) = Self::unpack_to_native(self.0);
|
let (r, g, b, _) = Self::unpack_to_native(self.0);
|
||||||
let r8 = ((r5 as u32) << 3) | ((r5 as u32) >> 2);
|
let hex = (r as u32) << 16 | (g as u32) << 8 | b as u32;
|
||||||
let g8 = ((g6 as u32) << 2) | ((g6 as u32) >> 4);
|
|
||||||
let b8 = ((b5 as u32) << 3) | ((b5 as u32) >> 2);
|
|
||||||
let hex = r8 << 16 | g8 << 8 | b8;
|
|
||||||
hex as i32
|
hex as i32
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub const fn alpha(self) -> u8 {
|
||||||
|
(self.0 & 0xFF) as u8
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::cartridge::AppMode;
|
use crate::app_mode::AppMode;
|
||||||
use prometeu_bytecode::Value;
|
use prometeu_bytecode::Value;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
@@ -40,7 +40,7 @@ pub enum DebugResponse {
|
|||||||
Breakpoints { pcs: Vec<usize> },
|
Breakpoints { pcs: Vec<usize> },
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct HandshakeCartridge {
|
pub struct HandshakeCartridge {
|
||||||
pub app_id: u32,
|
pub app_id: u32,
|
||||||
pub title: String,
|
pub title: String,
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ pub enum GfxOpStatus {
|
|||||||
|
|
||||||
pub trait GfxBridge {
|
pub trait GfxBridge {
|
||||||
fn size(&self) -> (usize, usize);
|
fn size(&self) -> (usize, usize);
|
||||||
fn front_buffer(&self) -> &[u16];
|
fn front_buffer(&self) -> &[u32];
|
||||||
fn clear(&mut self, color: Color);
|
fn clear(&mut self, color: Color);
|
||||||
fn fill_rect_blend(&mut self, x: i32, y: i32, w: i32, h: i32, color: Color, mode: BlendMode);
|
fn fill_rect_blend(&mut self, x: i32, y: i32, w: i32, h: i32, color: Color, mode: BlendMode);
|
||||||
fn fill_rect(&mut self, x: i32, y: i32, w: i32, h: i32, color: Color);
|
fn fill_rect(&mut self, x: i32, y: i32, w: i32, h: i32, color: Color);
|
||||||
@@ -57,7 +57,12 @@ pub trait GfxBridge {
|
|||||||
///
|
///
|
||||||
/// Deferred `gfx.*` overlay/debug primitives are intentionally outside this
|
/// Deferred `gfx.*` overlay/debug primitives are intentionally outside this
|
||||||
/// contract and are drained by a separate final overlay stage.
|
/// contract and are drained by a separate final overlay stage.
|
||||||
fn render_scene_from_cache(&mut self, cache: &SceneViewportCache, update: &ResolverUpdate);
|
fn render_scene_from_cache(
|
||||||
|
&mut self,
|
||||||
|
cache: &SceneViewportCache,
|
||||||
|
update: &ResolverUpdate,
|
||||||
|
resolved_glyph_slots: &[usize; 4],
|
||||||
|
);
|
||||||
fn load_frame_sprites(&mut self, sprites: &[Sprite]);
|
fn load_frame_sprites(&mut self, sprites: &[Sprite]);
|
||||||
/// Submit text into the `gfx.*` primitive path.
|
/// Submit text into the `gfx.*` primitive path.
|
||||||
///
|
///
|
||||||
@@ -68,13 +73,4 @@ pub trait GfxBridge {
|
|||||||
|
|
||||||
fn sprite(&self, index: usize) -> &Sprite;
|
fn sprite(&self, index: usize) -> &Sprite;
|
||||||
fn sprite_mut(&mut self, index: usize) -> &mut Sprite;
|
fn sprite_mut(&mut self, index: usize) -> &mut Sprite;
|
||||||
|
|
||||||
fn scene_fade_level(&self) -> u8;
|
|
||||||
fn set_scene_fade_level(&mut self, level: u8);
|
|
||||||
fn scene_fade_color(&self) -> Color;
|
|
||||||
fn set_scene_fade_color(&mut self, color: Color);
|
|
||||||
fn hud_fade_level(&self) -> u8;
|
|
||||||
fn set_hud_fade_level(&mut self, level: u8);
|
|
||||||
fn hud_fade_color(&self) -> Color;
|
|
||||||
fn set_hud_fade_color(&mut self, color: Color);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use crate::color::Color;
|
use crate::color::Color;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
pub const GLYPH_BANK_PALETTE_COUNT_V1: usize = 64;
|
pub const GLYPH_BANK_MAX_PALETTE_COUNT_V1: usize = 64;
|
||||||
pub const GLYPH_BANK_COLORS_PER_PALETTE: usize = 16;
|
pub const GLYPH_BANK_COLORS_PER_PALETTE: usize = 16;
|
||||||
|
|
||||||
/// Standard sizes for square tiles.
|
/// Standard sizes for square tiles.
|
||||||
@@ -32,24 +32,62 @@ pub struct GlyphBank {
|
|||||||
|
|
||||||
/// Decoded pixel data stored as one palette index per pixel.
|
/// Decoded pixel data stored as one palette index per pixel.
|
||||||
/// Serialized payloads are packed; runtime memory is expanded.
|
/// Serialized payloads are packed; runtime memory is expanded.
|
||||||
/// Index 0 is always reserved for transparency.
|
/// Palette indices are ordinary indices; transparency is resolved through
|
||||||
|
/// the RGBA alpha channel of the palette entry.
|
||||||
pub pixel_indices: Vec<u8>,
|
pub pixel_indices: Vec<u8>,
|
||||||
/// Runtime-facing v1 palette table: 64 palettes of 16 RGB565 colors each.
|
/// Runtime-facing v1 palette table.
|
||||||
pub palettes: [[Color; GLYPH_BANK_COLORS_PER_PALETTE]; GLYPH_BANK_PALETTE_COUNT_V1],
|
///
|
||||||
|
/// Palette identity is the direct index in this vector. A resident glyph
|
||||||
|
/// bank carries exactly the palettes materialized from its payload.
|
||||||
|
pub palettes: Vec<[Color; GLYPH_BANK_COLORS_PER_PALETTE]>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GlyphBank {
|
impl GlyphBank {
|
||||||
/// Creates an empty glyph bank with the specified dimensions.
|
/// Creates an empty glyph bank with one palette.
|
||||||
pub fn new(tile_size: TileSize, width: usize, height: usize) -> Self {
|
pub fn new(tile_size: TileSize, width: usize, height: usize) -> Self {
|
||||||
|
Self::with_palette_count(tile_size, width, height, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates an empty glyph bank with the specified resident palette count.
|
||||||
|
pub fn with_palette_count(
|
||||||
|
tile_size: TileSize,
|
||||||
|
width: usize,
|
||||||
|
height: usize,
|
||||||
|
palette_count: usize,
|
||||||
|
) -> Self {
|
||||||
|
assert!(
|
||||||
|
(1..=GLYPH_BANK_MAX_PALETTE_COUNT_V1).contains(&palette_count),
|
||||||
|
"glyph bank palette_count must be in 1..={}",
|
||||||
|
GLYPH_BANK_MAX_PALETTE_COUNT_V1
|
||||||
|
);
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
tile_size,
|
tile_size,
|
||||||
width,
|
width,
|
||||||
height,
|
height,
|
||||||
pixel_indices: vec![0; width * height], // Index 0 = Transparent
|
pixel_indices: vec![0; width * height],
|
||||||
palettes: [[Color::BLACK; GLYPH_BANK_COLORS_PER_PALETTE]; GLYPH_BANK_PALETTE_COUNT_V1],
|
palettes: vec![[Color::BLACK; GLYPH_BANK_COLORS_PER_PALETTE]; palette_count],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns the number of resident palettes.
|
||||||
|
pub fn palette_count(&self) -> usize {
|
||||||
|
self.palettes.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns true when the palette id is valid for this resident bank.
|
||||||
|
pub fn contains_palette(&self, palette_id: u8) -> bool {
|
||||||
|
(palette_id as usize) < self.palette_count()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a mutable palette slot when the palette exists.
|
||||||
|
pub fn palette_mut(
|
||||||
|
&mut self,
|
||||||
|
palette_id: u8,
|
||||||
|
) -> Option<&mut [Color; GLYPH_BANK_COLORS_PER_PALETTE]> {
|
||||||
|
self.palettes.get_mut(palette_id as usize)
|
||||||
|
}
|
||||||
|
|
||||||
/// Resolves a global tile ID and local pixel coordinates to a palette index.
|
/// Resolves a global tile ID and local pixel coordinates to a palette index.
|
||||||
/// tile_id: the tile index in the bank
|
/// tile_id: the tile index in the bank
|
||||||
/// local_x, local_y: the pixel position inside the tile (0 to tile_size-1)
|
/// local_x, local_y: the pixel position inside the tile (0 to tile_size-1)
|
||||||
@@ -65,22 +103,53 @@ impl GlyphBank {
|
|||||||
if pixel_x < self.width && pixel_y < self.height {
|
if pixel_x < self.width && pixel_y < self.height {
|
||||||
self.pixel_indices[pixel_y * self.width + pixel_x]
|
self.pixel_indices[pixel_y * self.width + pixel_x]
|
||||||
} else {
|
} else {
|
||||||
0 // Default to transparent if out of bounds
|
0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Maps a 4-bit index to a real RGB565 Color using the specified palette.
|
/// Maps a 4-bit index to a real RGBA8888 Color using the specified palette.
|
||||||
pub fn resolve_color(&self, palette_id: u8, pixel_index: u8) -> Color {
|
pub fn resolve_color(&self, palette_id: u8, pixel_index: u8) -> Option<Color> {
|
||||||
// Hardware Rule: Index 0 is always transparent.
|
|
||||||
// We use Magenta as the 'transparent' signal color during composition.
|
|
||||||
if pixel_index == 0 {
|
|
||||||
return Color::COLOR_KEY;
|
|
||||||
}
|
|
||||||
|
|
||||||
self.palettes
|
self.palettes
|
||||||
.get(palette_id as usize)
|
.get(palette_id as usize)
|
||||||
.and_then(|palette| palette.get(pixel_index as usize))
|
.and_then(|palette| palette.get(pixel_index as usize))
|
||||||
.copied()
|
.copied()
|
||||||
.unwrap_or(Color::COLOR_KEY)
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn new_glyph_bank_uses_single_resident_palette() {
|
||||||
|
let bank = GlyphBank::new(TileSize::Size8, 8, 8);
|
||||||
|
|
||||||
|
assert_eq!(bank.palette_count(), 1);
|
||||||
|
assert!(bank.contains_palette(0));
|
||||||
|
assert!(!bank.contains_palette(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn glyph_bank_can_materialize_v1_max_palette_count() {
|
||||||
|
let bank =
|
||||||
|
GlyphBank::with_palette_count(TileSize::Size8, 8, 8, GLYPH_BANK_MAX_PALETTE_COUNT_V1);
|
||||||
|
|
||||||
|
assert_eq!(bank.palette_count(), GLYPH_BANK_MAX_PALETTE_COUNT_V1);
|
||||||
|
assert!(bank.contains_palette((GLYPH_BANK_MAX_PALETTE_COUNT_V1 - 1) as u8));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn invalid_palette_lookup_is_distinct_from_transparent_color() {
|
||||||
|
let mut bank = GlyphBank::new(TileSize::Size8, 8, 8);
|
||||||
|
bank.palette_mut(0).unwrap()[1] = Color::TRANSPARENT;
|
||||||
|
|
||||||
|
assert_eq!(bank.resolve_color(0, 1), Some(Color::TRANSPARENT));
|
||||||
|
assert_eq!(bank.resolve_color(1, 1), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[should_panic(expected = "glyph bank palette_count must be in 1..=64")]
|
||||||
|
fn glyph_bank_rejects_zero_resident_palettes() {
|
||||||
|
let _ = GlyphBank::with_palette_count(TileSize::Size8, 8, 8, 0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,31 +0,0 @@
|
|||||||
use crate::asset_bridge::AssetBridge;
|
|
||||||
use crate::audio_bridge::AudioBridge;
|
|
||||||
use crate::gfx_bridge::GfxBridge;
|
|
||||||
use crate::pad_bridge::PadBridge;
|
|
||||||
use crate::sprite::Sprite;
|
|
||||||
use crate::touch_bridge::TouchBridge;
|
|
||||||
|
|
||||||
pub trait HardwareBridge {
|
|
||||||
fn begin_frame(&mut self);
|
|
||||||
fn bind_scene(&mut self, scene_bank_id: usize) -> bool;
|
|
||||||
fn unbind_scene(&mut self);
|
|
||||||
fn set_camera(&mut self, x: i32, y: i32);
|
|
||||||
fn emit_sprite(&mut self, sprite: Sprite) -> bool;
|
|
||||||
fn render_frame(&mut self);
|
|
||||||
fn has_glyph_bank(&self, bank_id: usize) -> bool;
|
|
||||||
|
|
||||||
fn gfx(&self) -> &dyn GfxBridge;
|
|
||||||
fn gfx_mut(&mut self) -> &mut dyn GfxBridge;
|
|
||||||
|
|
||||||
fn audio(&self) -> &dyn AudioBridge;
|
|
||||||
fn audio_mut(&mut self) -> &mut dyn AudioBridge;
|
|
||||||
|
|
||||||
fn pad(&self) -> &dyn PadBridge;
|
|
||||||
fn pad_mut(&mut self) -> &mut dyn PadBridge;
|
|
||||||
|
|
||||||
fn touch(&self) -> &dyn TouchBridge;
|
|
||||||
fn touch_mut(&mut self) -> &mut dyn TouchBridge;
|
|
||||||
|
|
||||||
fn assets(&self) -> &dyn AssetBridge;
|
|
||||||
fn assets_mut(&mut self) -> &mut dyn AssetBridge;
|
|
||||||
}
|
|
||||||
@@ -1,19 +1,23 @@
|
|||||||
use crate::hardware_bridge::HardwareBridge;
|
use crate::platform::RuntimePlatform;
|
||||||
use crate::vm_fault::VmFault;
|
use crate::vm_fault::VmFault;
|
||||||
|
|
||||||
pub struct HostContext<'a> {
|
pub struct HostContext<'a> {
|
||||||
pub hw: Option<&'a mut dyn HardwareBridge>,
|
pub platform: Option<&'a mut dyn RuntimePlatform>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> HostContext<'a> {
|
impl<'a> HostContext<'a> {
|
||||||
pub fn new(hw: Option<&'a mut dyn HardwareBridge>) -> Self {
|
pub fn new(platform: Option<&'a mut dyn RuntimePlatform>) -> Self {
|
||||||
Self { hw }
|
Self { platform }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new_platform(platform: Option<&'a mut dyn RuntimePlatform>) -> Self {
|
||||||
|
Self::new(platform)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn require_hw(&mut self) -> Result<&mut dyn HardwareBridge, VmFault> {
|
pub fn require_platform(&mut self) -> Result<&mut dyn RuntimePlatform, VmFault> {
|
||||||
match &mut self.hw {
|
match &mut self.platform {
|
||||||
Some(hw) => Ok(*hw),
|
Some(platform) => Ok(*platform),
|
||||||
None => Err(VmFault::Unavailable),
|
None => Err(VmFault::Unavailable),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
pub mod app_mode;
|
||||||
pub mod asset;
|
pub mod asset;
|
||||||
pub mod asset_bridge;
|
pub mod asset_bridge;
|
||||||
pub mod audio_bridge;
|
pub mod audio_bridge;
|
||||||
@@ -10,14 +11,19 @@ pub mod debugger_protocol;
|
|||||||
pub mod gfx_bridge;
|
pub mod gfx_bridge;
|
||||||
pub mod glyph;
|
pub mod glyph;
|
||||||
pub mod glyph_bank;
|
pub mod glyph_bank;
|
||||||
pub mod hardware_bridge;
|
|
||||||
pub mod host_context;
|
pub mod host_context;
|
||||||
pub mod host_return;
|
pub mod host_return;
|
||||||
pub mod input_signals;
|
pub mod input_signals;
|
||||||
pub mod log;
|
pub mod log;
|
||||||
pub mod native_helpers;
|
pub mod native_helpers;
|
||||||
pub mod native_interface;
|
pub mod native_interface;
|
||||||
|
pub mod owned_frame;
|
||||||
pub mod pad_bridge;
|
pub mod pad_bridge;
|
||||||
|
pub mod platform;
|
||||||
|
pub mod primitives;
|
||||||
|
pub mod render_resources;
|
||||||
|
pub mod render_submission;
|
||||||
|
pub mod render_worker;
|
||||||
pub mod sample;
|
pub mod sample;
|
||||||
pub mod scene_bank;
|
pub mod scene_bank;
|
||||||
pub mod scene_layer;
|
pub mod scene_layer;
|
||||||
@@ -31,17 +37,30 @@ pub mod tile;
|
|||||||
pub mod tilemap;
|
pub mod tilemap;
|
||||||
pub mod touch_bridge;
|
pub mod touch_bridge;
|
||||||
pub mod vm_fault;
|
pub mod vm_fault;
|
||||||
pub mod window;
|
|
||||||
|
|
||||||
pub use asset_bridge::AssetBridge;
|
pub use asset_bridge::AssetBridge;
|
||||||
pub use audio_bridge::{AudioBridge, AudioOpStatus, LoopMode};
|
pub use audio_bridge::{AudioBridge, AudioOpStatus, LoopMode};
|
||||||
pub use composer_status::ComposerOpStatus;
|
pub use composer_status::ComposerOpStatus;
|
||||||
pub use gfx_bridge::{BlendMode, GfxBridge, GfxOpStatus};
|
pub use gfx_bridge::{BlendMode, GfxBridge, GfxOpStatus};
|
||||||
pub use hardware_bridge::HardwareBridge;
|
|
||||||
pub use host_context::{HostContext, HostContextProvider};
|
pub use host_context::{HostContext, HostContextProvider};
|
||||||
pub use host_return::HostReturn;
|
pub use host_return::HostReturn;
|
||||||
pub use input_signals::InputSignals;
|
pub use input_signals::InputSignals;
|
||||||
pub use native_helpers::{expect_bool, expect_int};
|
pub use native_helpers::{expect_bool, expect_int};
|
||||||
pub use native_interface::{NativeInterface, SyscallId};
|
pub use native_interface::{NativeInterface, SyscallId};
|
||||||
|
pub use owned_frame::{OwnedRgba8888Frame, OwnedRgba8888FrameError};
|
||||||
pub use pad_bridge::PadBridge;
|
pub use pad_bridge::PadBridge;
|
||||||
|
pub use platform::{
|
||||||
|
AssetStoragePlatform, AudioPlatform, ClockPacingPlatform, Game2DFrameComposer, InputPlatform,
|
||||||
|
NoopTelemetryPlatform, RenderBackend, RenderSubmissionSink, RenderSubmitError, RuntimePlatform,
|
||||||
|
TelemetryPlatform, TestPlatform,
|
||||||
|
};
|
||||||
|
pub use render_resources::RenderResourceAccess;
|
||||||
|
pub use render_submission::{
|
||||||
|
BoundScenePacket, Camera2D, ComposerFramePacket, FrameId, Game2DFramePacket, GameSpritePacket,
|
||||||
|
Gfx2dCommand, GfxUiCommand, HudCommand, HudPacket, RenderOwnership, RenderSubmission,
|
||||||
|
RenderSubmissionPacket, ShellUiFramePacket,
|
||||||
|
};
|
||||||
|
pub use render_worker::{
|
||||||
|
RenderWorkerBackend, RenderWorkerError, RenderWorkerFrameSink, RenderWorkerTelemetry,
|
||||||
|
};
|
||||||
pub use touch_bridge::TouchBridge;
|
pub use touch_bridge::TouchBridge;
|
||||||
|
|||||||
@@ -0,0 +1,127 @@
|
|||||||
|
use crate::render_submission::{FrameId, RenderOwnership};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct OwnedRgba8888Frame {
|
||||||
|
pub frame_id: FrameId,
|
||||||
|
pub ownership: RenderOwnership,
|
||||||
|
pub width: usize,
|
||||||
|
pub height: usize,
|
||||||
|
pub stride_pixels: usize,
|
||||||
|
pub pixels: Vec<u32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum OwnedRgba8888FrameError {
|
||||||
|
EmptyDimensions,
|
||||||
|
StrideTooSmall,
|
||||||
|
PixelBufferTooSmall,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OwnedRgba8888Frame {
|
||||||
|
pub fn new(
|
||||||
|
frame_id: FrameId,
|
||||||
|
ownership: RenderOwnership,
|
||||||
|
width: usize,
|
||||||
|
height: usize,
|
||||||
|
stride_pixels: usize,
|
||||||
|
pixels: Vec<u32>,
|
||||||
|
) -> Result<Self, OwnedRgba8888FrameError> {
|
||||||
|
if width == 0 || height == 0 {
|
||||||
|
return Err(OwnedRgba8888FrameError::EmptyDimensions);
|
||||||
|
}
|
||||||
|
if stride_pixels < width {
|
||||||
|
return Err(OwnedRgba8888FrameError::StrideTooSmall);
|
||||||
|
}
|
||||||
|
let required_len = stride_pixels
|
||||||
|
.checked_mul(height)
|
||||||
|
.ok_or(OwnedRgba8888FrameError::PixelBufferTooSmall)?;
|
||||||
|
if pixels.len() < required_len {
|
||||||
|
return Err(OwnedRgba8888FrameError::PixelBufferTooSmall);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Self { frame_id, ownership, width, height, stride_pixels, pixels })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn packed(
|
||||||
|
frame_id: FrameId,
|
||||||
|
ownership: RenderOwnership,
|
||||||
|
width: usize,
|
||||||
|
height: usize,
|
||||||
|
pixels: Vec<u32>,
|
||||||
|
) -> Result<Self, OwnedRgba8888FrameError> {
|
||||||
|
Self::new(frame_id, ownership, width, height, width, pixels)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn required_pixel_len(&self) -> usize {
|
||||||
|
self.stride_pixels * self.height
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn row(&self, y: usize) -> Option<&[u32]> {
|
||||||
|
if y >= self.height {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let start = y * self.stride_pixels;
|
||||||
|
Some(&self.pixels[start..start + self.width])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::app_mode::AppMode;
|
||||||
|
|
||||||
|
fn ownership() -> RenderOwnership {
|
||||||
|
RenderOwnership::new(11, AppMode::Game, 42)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn owned_rgba8888_frame_preserves_metadata_and_pixels() {
|
||||||
|
let pixels = vec![0x11223344, 0x55667788, 0x99AABBCC, 0xDDEEFF00];
|
||||||
|
let frame = OwnedRgba8888Frame::packed(FrameId::new(7), ownership(), 2, 2, pixels.clone())
|
||||||
|
.expect("valid packed RGBA8888 frame");
|
||||||
|
|
||||||
|
assert_eq!(frame.frame_id, FrameId::new(7));
|
||||||
|
assert_eq!(frame.ownership, ownership());
|
||||||
|
assert_eq!(frame.width, 2);
|
||||||
|
assert_eq!(frame.height, 2);
|
||||||
|
assert_eq!(frame.stride_pixels, 2);
|
||||||
|
assert_eq!(frame.pixels, pixels);
|
||||||
|
assert_eq!(frame.required_pixel_len(), 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn checked_constructor_rejects_empty_dimensions() {
|
||||||
|
let err = OwnedRgba8888Frame::new(FrameId::ZERO, ownership(), 0, 1, 1, vec![0])
|
||||||
|
.expect_err("zero width should be rejected");
|
||||||
|
|
||||||
|
assert_eq!(err, OwnedRgba8888FrameError::EmptyDimensions);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn checked_constructor_rejects_stride_smaller_than_width() {
|
||||||
|
let err = OwnedRgba8888Frame::new(FrameId::ZERO, ownership(), 3, 1, 2, vec![0, 0, 0])
|
||||||
|
.expect_err("stride smaller than width should be rejected");
|
||||||
|
|
||||||
|
assert_eq!(err, OwnedRgba8888FrameError::StrideTooSmall);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn checked_constructor_rejects_short_pixel_buffer() {
|
||||||
|
let err = OwnedRgba8888Frame::new(FrameId::ZERO, ownership(), 2, 2, 3, vec![0; 5])
|
||||||
|
.expect_err("buffer shorter than stride * height should be rejected");
|
||||||
|
|
||||||
|
assert_eq!(err, OwnedRgba8888FrameError::PixelBufferTooSmall);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn row_returns_visible_width_without_stride_padding() {
|
||||||
|
let frame =
|
||||||
|
OwnedRgba8888Frame::new(FrameId::ZERO, ownership(), 2, 2, 3, vec![1, 2, 99, 3, 4, 88])
|
||||||
|
.expect("valid padded frame");
|
||||||
|
|
||||||
|
assert_eq!(frame.row(0), Some(&[1, 2][..]));
|
||||||
|
assert_eq!(frame.row(1), Some(&[3, 4][..]));
|
||||||
|
assert_eq!(frame.row(2), None);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
use crate::asset_bridge::AssetBridge;
|
||||||
|
use crate::audio_bridge::AudioBridge;
|
||||||
|
use crate::composer_status::ComposerOpStatus;
|
||||||
|
use crate::pad_bridge::PadBridge;
|
||||||
|
use crate::render_submission::{Game2DFramePacket, RenderSubmission};
|
||||||
|
use crate::sprite::Sprite;
|
||||||
|
use crate::telemetry::TelemetryFrame;
|
||||||
|
use crate::touch_bridge::TouchBridge;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum RenderSubmitError {
|
||||||
|
BackendUnavailable,
|
||||||
|
SubmissionRejected,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait RenderSubmissionSink {
|
||||||
|
fn submit_render_submission(
|
||||||
|
&mut self,
|
||||||
|
submission: RenderSubmission,
|
||||||
|
) -> Result<(), RenderSubmitError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait RenderBackend {
|
||||||
|
fn render_frame(&mut self);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait Game2DFrameComposer {
|
||||||
|
fn begin_frame(&mut self);
|
||||||
|
fn bind_scene(&mut self, scene_bank_id: usize) -> ComposerOpStatus;
|
||||||
|
fn unbind_scene(&mut self);
|
||||||
|
fn set_camera(&mut self, x: i32, y: i32) -> ComposerOpStatus;
|
||||||
|
fn emit_sprite(&mut self, sprite: Sprite) -> ComposerOpStatus;
|
||||||
|
fn close_game2d_packet(&self) -> Game2DFramePacket;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait AudioPlatform: AudioBridge {}
|
||||||
|
impl<T: AudioBridge + ?Sized> AudioPlatform for T {}
|
||||||
|
|
||||||
|
pub trait InputPlatform {
|
||||||
|
fn pad(&self) -> &dyn PadBridge;
|
||||||
|
fn pad_mut(&mut self) -> &mut dyn PadBridge;
|
||||||
|
fn touch(&self) -> &dyn TouchBridge;
|
||||||
|
fn touch_mut(&mut self) -> &mut dyn TouchBridge;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait AssetStoragePlatform: AssetBridge {}
|
||||||
|
impl<T: AssetBridge + ?Sized> AssetStoragePlatform for T {}
|
||||||
|
|
||||||
|
pub trait ClockPacingPlatform {}
|
||||||
|
|
||||||
|
pub trait TelemetryPlatform {
|
||||||
|
fn telemetry_snapshot(&self) -> Option<TelemetryFrame> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
pub struct NoopTelemetryPlatform;
|
||||||
|
|
||||||
|
impl TelemetryPlatform for NoopTelemetryPlatform {}
|
||||||
|
|
||||||
|
pub trait RuntimePlatform {
|
||||||
|
fn display_size(&self) -> (usize, usize) {
|
||||||
|
(480, 270)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_submission_sink(&mut self) -> &mut dyn RenderSubmissionSink;
|
||||||
|
fn render_backend(&mut self) -> &mut dyn RenderBackend;
|
||||||
|
fn game2d_frame_composer(&mut self) -> &mut dyn Game2DFrameComposer;
|
||||||
|
fn audio(&self) -> &dyn AudioBridge;
|
||||||
|
fn audio_mut(&mut self) -> &mut dyn AudioBridge;
|
||||||
|
fn input(&self) -> &dyn InputPlatform;
|
||||||
|
fn input_mut(&mut self) -> &mut dyn InputPlatform;
|
||||||
|
fn assets(&self) -> &dyn AssetBridge;
|
||||||
|
fn assets_mut(&mut self) -> &mut dyn AssetBridge;
|
||||||
|
fn telemetry(&self) -> &dyn TelemetryPlatform;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait TestPlatform: RuntimePlatform {}
|
||||||
|
impl<T: RuntimePlatform + ?Sized> TestPlatform for T {}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn assert_render_sink_object(_: &mut dyn RenderSubmissionSink) {}
|
||||||
|
fn assert_backend_object(_: &mut dyn RenderBackend) {}
|
||||||
|
fn assert_composer_object(_: &mut dyn Game2DFrameComposer) {}
|
||||||
|
|
||||||
|
struct CompileOnly;
|
||||||
|
|
||||||
|
impl RenderSubmissionSink for CompileOnly {
|
||||||
|
fn submit_render_submission(
|
||||||
|
&mut self,
|
||||||
|
_submission: RenderSubmission,
|
||||||
|
) -> Result<(), RenderSubmitError> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RenderBackend for CompileOnly {
|
||||||
|
fn render_frame(&mut self) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Game2DFrameComposer for CompileOnly {
|
||||||
|
fn begin_frame(&mut self) {}
|
||||||
|
|
||||||
|
fn bind_scene(&mut self, _scene_bank_id: usize) -> ComposerOpStatus {
|
||||||
|
ComposerOpStatus::Ok
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unbind_scene(&mut self) {}
|
||||||
|
|
||||||
|
fn set_camera(&mut self, _x: i32, _y: i32) -> ComposerOpStatus {
|
||||||
|
ComposerOpStatus::Ok
|
||||||
|
}
|
||||||
|
|
||||||
|
fn emit_sprite(&mut self, _sprite: Sprite) -> ComposerOpStatus {
|
||||||
|
ComposerOpStatus::Ok
|
||||||
|
}
|
||||||
|
|
||||||
|
fn close_game2d_packet(&self) -> Game2DFramePacket {
|
||||||
|
Game2DFramePacket::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn core_platform_facades_are_object_safe() {
|
||||||
|
let mut compile_only = CompileOnly;
|
||||||
|
|
||||||
|
assert_render_sink_object(&mut compile_only);
|
||||||
|
assert_backend_object(&mut compile_only);
|
||||||
|
assert_composer_object(&mut compile_only);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn render_submit_error_is_typed_and_debuggable() {
|
||||||
|
assert_eq!(format!("{:?}", RenderSubmitError::BackendUnavailable), "BackendUnavailable");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct Rect {
|
||||||
|
pub x: i32,
|
||||||
|
pub y: i32,
|
||||||
|
pub w: i32,
|
||||||
|
pub h: i32,
|
||||||
|
}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
use crate::glyph_bank::GlyphBank;
|
||||||
|
use crate::scene_bank::SceneBank;
|
||||||
|
|
||||||
|
/// Read-only render resource lookup used by render backends.
|
||||||
|
///
|
||||||
|
/// Resource ids are stable bank slots carried by render submissions. The
|
||||||
|
/// callback shape keeps bank ownership inside the provider while exposing only
|
||||||
|
/// borrowed read access to the caller.
|
||||||
|
pub trait RenderResourceAccess {
|
||||||
|
/// Reads a resident glyph bank by id.
|
||||||
|
fn with_glyph_bank<R>(&self, bank_id: usize, read: impl FnOnce(&GlyphBank) -> R) -> Option<R>;
|
||||||
|
|
||||||
|
/// Returns the number of glyph bank ids accepted by this provider.
|
||||||
|
fn glyph_bank_count(&self) -> usize;
|
||||||
|
|
||||||
|
/// Reads a resident scene bank by id.
|
||||||
|
fn with_scene_bank<R>(&self, bank_id: usize, read: impl FnOnce(&SceneBank) -> R) -> Option<R>;
|
||||||
|
|
||||||
|
/// Returns the number of scene bank ids accepted by this provider.
|
||||||
|
fn scene_bank_count(&self) -> usize;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::glyph::Glyph;
|
||||||
|
use crate::glyph_bank::TileSize;
|
||||||
|
use crate::scene_layer::{ParallaxFactor, SceneLayer};
|
||||||
|
use crate::tile::Tile;
|
||||||
|
use crate::tilemap::TileMap;
|
||||||
|
|
||||||
|
struct TestRenderResources {
|
||||||
|
glyph_banks: Vec<Option<GlyphBank>>,
|
||||||
|
scene_banks: Vec<Option<SceneBank>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RenderResourceAccess for TestRenderResources {
|
||||||
|
fn with_glyph_bank<R>(
|
||||||
|
&self,
|
||||||
|
bank_id: usize,
|
||||||
|
read: impl FnOnce(&GlyphBank) -> R,
|
||||||
|
) -> Option<R> {
|
||||||
|
self.glyph_banks.get(bank_id)?.as_ref().map(read)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn glyph_bank_count(&self) -> usize {
|
||||||
|
self.glyph_banks.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn with_scene_bank<R>(
|
||||||
|
&self,
|
||||||
|
bank_id: usize,
|
||||||
|
read: impl FnOnce(&SceneBank) -> R,
|
||||||
|
) -> Option<R> {
|
||||||
|
self.scene_banks.get(bank_id)?.as_ref().map(read)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn scene_bank_count(&self) -> usize {
|
||||||
|
self.scene_banks.len()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn scene_bank(tile_size: TileSize) -> SceneBank {
|
||||||
|
let layer = SceneLayer {
|
||||||
|
active: true,
|
||||||
|
glyph_asset_id: 7,
|
||||||
|
tile_size,
|
||||||
|
parallax_factor: ParallaxFactor { x: 1.0, y: 1.0 },
|
||||||
|
tilemap: TileMap {
|
||||||
|
width: 1,
|
||||||
|
height: 1,
|
||||||
|
tiles: vec![Tile {
|
||||||
|
active: true,
|
||||||
|
glyph: Glyph { glyph_id: 3, palette_id: 0 },
|
||||||
|
flip_x: false,
|
||||||
|
flip_y: false,
|
||||||
|
}],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
SceneBank { layers: std::array::from_fn(|_| layer.clone()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reads_resident_resources_by_id() {
|
||||||
|
let resources = TestRenderResources {
|
||||||
|
glyph_banks: vec![None, Some(GlyphBank::new(TileSize::Size16, 16, 16)), None],
|
||||||
|
scene_banks: vec![Some(scene_bank(TileSize::Size8)), None],
|
||||||
|
};
|
||||||
|
|
||||||
|
assert_eq!(resources.glyph_bank_count(), 3);
|
||||||
|
assert_eq!(resources.scene_bank_count(), 2);
|
||||||
|
assert_eq!(resources.with_glyph_bank(1, |bank| bank.tile_size), Some(TileSize::Size16));
|
||||||
|
assert_eq!(
|
||||||
|
resources.with_scene_bank(0, |bank| bank.layers[0].tile_size),
|
||||||
|
Some(TileSize::Size8)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn missing_resources_return_none() {
|
||||||
|
let resources = TestRenderResources { glyph_banks: vec![None], scene_banks: vec![None] };
|
||||||
|
|
||||||
|
assert_eq!(resources.with_glyph_bank(0, |bank| bank.width), None);
|
||||||
|
assert_eq!(resources.with_glyph_bank(9, |bank| bank.width), None);
|
||||||
|
assert_eq!(resources.with_scene_bank(0, |bank| bank.layers[0].active), None);
|
||||||
|
assert_eq!(resources.with_scene_bank(9, |bank| bank.layers[0].active), None);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,241 @@
|
|||||||
|
use crate::app_mode::AppMode;
|
||||||
|
use crate::color::Color;
|
||||||
|
use crate::primitives::Rect;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
|
||||||
|
pub struct FrameId(pub u64);
|
||||||
|
|
||||||
|
impl FrameId {
|
||||||
|
pub const ZERO: Self = Self(0);
|
||||||
|
|
||||||
|
pub const fn new(value: u64) -> Self {
|
||||||
|
Self(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const fn get(self) -> u64 {
|
||||||
|
self.0
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const fn next(self) -> Self {
|
||||||
|
Self(self.0.wrapping_add(1))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct RenderSubmission {
|
||||||
|
pub frame_id: FrameId,
|
||||||
|
pub app_mode: AppMode,
|
||||||
|
pub ownership: RenderOwnership,
|
||||||
|
pub packet: RenderSubmissionPacket,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RenderSubmission {
|
||||||
|
pub const fn game2d(frame_id: FrameId, packet: Game2DFramePacket) -> Self {
|
||||||
|
Self {
|
||||||
|
frame_id,
|
||||||
|
app_mode: AppMode::Game,
|
||||||
|
ownership: RenderOwnership::new(0, AppMode::Game, 0),
|
||||||
|
packet: RenderSubmissionPacket::Game2D(packet),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const fn shell_ui(frame_id: FrameId, packet: ShellUiFramePacket) -> Self {
|
||||||
|
Self {
|
||||||
|
frame_id,
|
||||||
|
app_mode: AppMode::Shell,
|
||||||
|
ownership: RenderOwnership::new(0, AppMode::Shell, 0),
|
||||||
|
packet: RenderSubmissionPacket::ShellUi(packet),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const fn with_ownership(mut self, ownership: RenderOwnership) -> Self {
|
||||||
|
self.ownership = ownership;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const fn is_coherent(&self) -> bool {
|
||||||
|
matches!(
|
||||||
|
(self.app_mode, &self.packet),
|
||||||
|
(AppMode::Game, RenderSubmissionPacket::Game2D(_))
|
||||||
|
| (AppMode::Shell, RenderSubmissionPacket::ShellUi(_))
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct RenderOwnership {
|
||||||
|
pub epoch: u64,
|
||||||
|
pub app_mode: AppMode,
|
||||||
|
pub app_id: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RenderOwnership {
|
||||||
|
pub const fn new(epoch: u64, app_mode: AppMode, app_id: u32) -> Self {
|
||||||
|
Self { epoch, app_mode, app_id }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum RenderSubmissionPacket {
|
||||||
|
Game2D(Game2DFramePacket),
|
||||||
|
ShellUi(ShellUiFramePacket),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||||
|
pub struct Game2DFramePacket {
|
||||||
|
pub composer: ComposerFramePacket,
|
||||||
|
pub gfx2d: Vec<Gfx2dCommand>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Game2DFramePacket {
|
||||||
|
pub fn new(composer: ComposerFramePacket, gfx2d: Vec<Gfx2dCommand>) -> Self {
|
||||||
|
Self { composer, gfx2d }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct ShellUiFramePacket {
|
||||||
|
pub commands: Vec<GfxUiCommand>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ShellUiFramePacket {
|
||||||
|
pub fn new(commands: Vec<GfxUiCommand>) -> Self {
|
||||||
|
Self { commands }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||||
|
pub struct ComposerFramePacket {
|
||||||
|
pub bound_scene: Option<BoundScenePacket>,
|
||||||
|
pub camera: Camera2D,
|
||||||
|
pub sprites: Vec<GameSpritePacket>,
|
||||||
|
pub hud: HudPacket,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct BoundScenePacket {
|
||||||
|
pub bank_id: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||||
|
pub struct Camera2D {
|
||||||
|
pub x: i32,
|
||||||
|
pub y: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct GameSpritePacket {
|
||||||
|
pub glyph_id: i32,
|
||||||
|
pub palette_id: i32,
|
||||||
|
pub x: i32,
|
||||||
|
pub y: i32,
|
||||||
|
pub layer: i32,
|
||||||
|
pub bank_id: i32,
|
||||||
|
pub flip_x: bool,
|
||||||
|
pub flip_y: bool,
|
||||||
|
pub priority: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||||
|
pub struct HudPacket {
|
||||||
|
pub commands: Vec<HudCommand>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum HudCommand {
|
||||||
|
Clear { color: Color },
|
||||||
|
FillRect { rect: Rect, color: Color },
|
||||||
|
DrawText { x: i32, y: i32, text: String, color: Color },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum Gfx2dCommand {
|
||||||
|
Clear { color: Color },
|
||||||
|
FillRect { rect: Rect, color: Color },
|
||||||
|
DrawLine { x0: i32, y0: i32, x1: i32, y1: i32, color: Color },
|
||||||
|
DrawCircle { x: i32, y: i32, radius: i32, color: Color },
|
||||||
|
DrawDisc { x: i32, y: i32, radius: i32, border_color: Color, fill_color: Color },
|
||||||
|
DrawSquare { rect: Rect, border_color: Color, fill_color: Color },
|
||||||
|
DrawText { x: i32, y: i32, text: String, color: Color },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum GfxUiCommand {
|
||||||
|
Clear { color: Color },
|
||||||
|
FillRect { rect: Rect, color: Color },
|
||||||
|
DrawLine { x0: i32, y0: i32, x1: i32, y1: i32, color: Color },
|
||||||
|
DrawCircle { x: i32, y: i32, radius: i32, color: Color },
|
||||||
|
DrawDisc { x: i32, y: i32, radius: i32, border_color: Color, fill_color: Color },
|
||||||
|
DrawSquare { rect: Rect, border_color: Color, fill_color: Color },
|
||||||
|
DrawText { x: i32, y: i32, text: String, color: Color },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn constructors_pin_app_mode_to_packet_kind() {
|
||||||
|
let game = RenderSubmission::game2d(FrameId::new(7), Game2DFramePacket::default());
|
||||||
|
assert_eq!(game.app_mode, AppMode::Game);
|
||||||
|
assert!(matches!(game.packet, RenderSubmissionPacket::Game2D(_)));
|
||||||
|
assert!(game.is_coherent());
|
||||||
|
|
||||||
|
let shell =
|
||||||
|
RenderSubmission::shell_ui(FrameId::new(8), ShellUiFramePacket::new(Vec::new()));
|
||||||
|
assert_eq!(shell.app_mode, AppMode::Shell);
|
||||||
|
assert!(matches!(shell.packet, RenderSubmissionPacket::ShellUi(_)));
|
||||||
|
assert!(shell.is_coherent());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn coherence_check_rejects_mismatched_envelope() {
|
||||||
|
let submission = RenderSubmission {
|
||||||
|
frame_id: FrameId::new(1),
|
||||||
|
app_mode: AppMode::Game,
|
||||||
|
ownership: RenderOwnership::new(0, AppMode::Game, 0),
|
||||||
|
packet: RenderSubmissionPacket::ShellUi(ShellUiFramePacket::new(Vec::new())),
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(!submission.is_coherent());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ownership_can_be_stamped_by_runtime() {
|
||||||
|
let submission = RenderSubmission::game2d(FrameId::new(3), Game2DFramePacket::default())
|
||||||
|
.with_ownership(RenderOwnership::new(9, AppMode::Game, 42));
|
||||||
|
|
||||||
|
assert_eq!(submission.ownership, RenderOwnership::new(9, AppMode::Game, 42));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn closed_submission_owns_command_payload() {
|
||||||
|
let mut commands = vec![Gfx2dCommand::DrawText {
|
||||||
|
x: 1,
|
||||||
|
y: 2,
|
||||||
|
text: "before".to_string(),
|
||||||
|
color: Color::WHITE,
|
||||||
|
}];
|
||||||
|
let submission = RenderSubmission::game2d(
|
||||||
|
FrameId::new(2),
|
||||||
|
Game2DFramePacket::new(Default::default(), commands.clone()),
|
||||||
|
);
|
||||||
|
|
||||||
|
commands.push(Gfx2dCommand::Clear { color: Color::BLACK });
|
||||||
|
|
||||||
|
let RenderSubmissionPacket::Game2D(packet) = submission.packet else {
|
||||||
|
panic!("expected game packet");
|
||||||
|
};
|
||||||
|
assert_eq!(packet.gfx2d.len(), 1);
|
||||||
|
assert_eq!(
|
||||||
|
packet.gfx2d[0],
|
||||||
|
Gfx2dCommand::DrawText { x: 1, y: 2, text: "before".to_string(), color: Color::WHITE }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn frame_id_advances_monotonically_with_wrapping_arithmetic() {
|
||||||
|
assert_eq!(FrameId::new(41).next(), FrameId::new(42));
|
||||||
|
assert_eq!(FrameId::new(u64::MAX).next(), FrameId::ZERO);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
use std::fmt;
|
||||||
|
|
||||||
|
use crate::{OwnedRgba8888Frame, RenderSubmission};
|
||||||
|
|
||||||
|
/// Typed failure surface for the real render worker and its backend.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum RenderWorkerError {
|
||||||
|
BackendUnavailable,
|
||||||
|
RenderFailed,
|
||||||
|
PublishFailed,
|
||||||
|
PresentFailed,
|
||||||
|
ShutdownTimeout,
|
||||||
|
StaleSubmissionDiscarded,
|
||||||
|
WorkerPanic,
|
||||||
|
InternalFailure,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for RenderWorkerError {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::BackendUnavailable => f.write_str("render backend unavailable"),
|
||||||
|
Self::RenderFailed => f.write_str("render failed"),
|
||||||
|
Self::PublishFailed => f.write_str("render publish failed"),
|
||||||
|
Self::PresentFailed => f.write_str("render present failed"),
|
||||||
|
Self::ShutdownTimeout => f.write_str("render worker shutdown timed out"),
|
||||||
|
Self::StaleSubmissionDiscarded => f.write_str("stale render submission discarded"),
|
||||||
|
Self::WorkerPanic => f.write_str("render worker panicked"),
|
||||||
|
Self::InternalFailure => f.write_str("internal render worker failure"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::error::Error for RenderWorkerError {}
|
||||||
|
|
||||||
|
pub trait RenderWorkerBackend: Send + 'static {
|
||||||
|
fn render(
|
||||||
|
&self,
|
||||||
|
submission: &RenderSubmission,
|
||||||
|
) -> Result<OwnedRgba8888Frame, RenderWorkerError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait RenderWorkerFrameSink: Send + 'static {
|
||||||
|
fn publish(&self, frame: OwnedRgba8888Frame) -> Result<(), RenderWorkerError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Snapshot of render worker handoff, render, publish, and shutdown counters.
|
||||||
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||||
|
pub struct RenderWorkerTelemetry {
|
||||||
|
pub produced_submissions: u64,
|
||||||
|
pub replaced_before_consume: u64,
|
||||||
|
pub consumed_submissions: u64,
|
||||||
|
pub published_frames: u64,
|
||||||
|
pub presented_frames: u64,
|
||||||
|
pub repeated_frames: u64,
|
||||||
|
pub stale_submission_discards: u64,
|
||||||
|
pub render_failures: u64,
|
||||||
|
pub publish_failures: u64,
|
||||||
|
pub present_failures: u64,
|
||||||
|
pub shutdown_timeouts: u64,
|
||||||
|
pub worker_panics: u64,
|
||||||
|
pub last_produced_frame_id: u64,
|
||||||
|
pub last_consumed_frame_id: u64,
|
||||||
|
pub last_published_frame_id: u64,
|
||||||
|
pub last_presented_frame_id: u64,
|
||||||
|
pub last_dropped_frame_id: u64,
|
||||||
|
pub last_error_frame_id: u64,
|
||||||
|
pub active_render_epoch: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RenderWorkerTelemetry {
|
||||||
|
pub fn record_produced(&mut self, frame_id: u64) {
|
||||||
|
self.produced_submissions += 1;
|
||||||
|
self.last_produced_frame_id = frame_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn record_replaced_before_consume(&mut self, frame_id: u64) {
|
||||||
|
self.replaced_before_consume += 1;
|
||||||
|
self.last_dropped_frame_id = frame_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn record_consumed(&mut self, frame_id: u64) {
|
||||||
|
self.consumed_submissions += 1;
|
||||||
|
self.last_consumed_frame_id = frame_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn record_published(&mut self, frame_id: u64) {
|
||||||
|
self.published_frames += 1;
|
||||||
|
self.last_published_frame_id = frame_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn record_presented(&mut self, frame_id: u64) {
|
||||||
|
self.presented_frames += 1;
|
||||||
|
self.last_presented_frame_id = frame_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn record_repeated_frame(&mut self, frame_id: u64) {
|
||||||
|
self.repeated_frames += 1;
|
||||||
|
self.last_presented_frame_id = frame_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn record_stale_submission_discarded(&mut self, frame_id: u64) {
|
||||||
|
self.stale_submission_discards += 1;
|
||||||
|
self.last_dropped_frame_id = frame_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn record_error(&mut self, error: RenderWorkerError, frame_id: u64) {
|
||||||
|
match error {
|
||||||
|
RenderWorkerError::BackendUnavailable | RenderWorkerError::RenderFailed => {
|
||||||
|
self.render_failures += 1;
|
||||||
|
}
|
||||||
|
RenderWorkerError::PublishFailed => {
|
||||||
|
self.publish_failures += 1;
|
||||||
|
}
|
||||||
|
RenderWorkerError::PresentFailed => {
|
||||||
|
self.present_failures += 1;
|
||||||
|
}
|
||||||
|
RenderWorkerError::ShutdownTimeout => {
|
||||||
|
self.shutdown_timeouts += 1;
|
||||||
|
}
|
||||||
|
RenderWorkerError::WorkerPanic => {
|
||||||
|
self.worker_panics += 1;
|
||||||
|
}
|
||||||
|
RenderWorkerError::StaleSubmissionDiscarded => {
|
||||||
|
self.stale_submission_discards += 1;
|
||||||
|
self.last_dropped_frame_id = frame_id;
|
||||||
|
}
|
||||||
|
RenderWorkerError::InternalFailure => {
|
||||||
|
self.render_failures += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.last_error_frame_id = frame_id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn render_worker_error_is_copy_equatable_and_debuggable() {
|
||||||
|
let error = RenderWorkerError::ShutdownTimeout;
|
||||||
|
let copied = error;
|
||||||
|
|
||||||
|
assert_eq!(copied, RenderWorkerError::ShutdownTimeout);
|
||||||
|
assert_eq!(format!("{:?}", error), "ShutdownTimeout");
|
||||||
|
assert_eq!(error.to_string(), "render worker shutdown timed out");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn render_worker_telemetry_defaults_to_zero() {
|
||||||
|
assert_eq!(
|
||||||
|
RenderWorkerTelemetry::default(),
|
||||||
|
RenderWorkerTelemetry {
|
||||||
|
produced_submissions: 0,
|
||||||
|
replaced_before_consume: 0,
|
||||||
|
consumed_submissions: 0,
|
||||||
|
published_frames: 0,
|
||||||
|
presented_frames: 0,
|
||||||
|
repeated_frames: 0,
|
||||||
|
stale_submission_discards: 0,
|
||||||
|
render_failures: 0,
|
||||||
|
publish_failures: 0,
|
||||||
|
present_failures: 0,
|
||||||
|
shutdown_timeouts: 0,
|
||||||
|
worker_panics: 0,
|
||||||
|
last_produced_frame_id: 0,
|
||||||
|
last_consumed_frame_id: 0,
|
||||||
|
last_published_frame_id: 0,
|
||||||
|
last_presented_frame_id: 0,
|
||||||
|
last_dropped_frame_id: 0,
|
||||||
|
last_error_frame_id: 0,
|
||||||
|
active_render_epoch: 0,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn render_worker_telemetry_records_counters_and_frame_ids() {
|
||||||
|
let mut telemetry = RenderWorkerTelemetry::default();
|
||||||
|
|
||||||
|
telemetry.record_produced(10);
|
||||||
|
telemetry.record_replaced_before_consume(10);
|
||||||
|
telemetry.record_consumed(11);
|
||||||
|
telemetry.record_published(11);
|
||||||
|
telemetry.record_presented(11);
|
||||||
|
telemetry.record_repeated_frame(11);
|
||||||
|
telemetry.record_error(RenderWorkerError::PublishFailed, 12);
|
||||||
|
telemetry.record_error(RenderWorkerError::WorkerPanic, 13);
|
||||||
|
telemetry.record_stale_submission_discarded(14);
|
||||||
|
|
||||||
|
assert_eq!(telemetry.produced_submissions, 1);
|
||||||
|
assert_eq!(telemetry.replaced_before_consume, 1);
|
||||||
|
assert_eq!(telemetry.consumed_submissions, 1);
|
||||||
|
assert_eq!(telemetry.published_frames, 1);
|
||||||
|
assert_eq!(telemetry.presented_frames, 1);
|
||||||
|
assert_eq!(telemetry.repeated_frames, 1);
|
||||||
|
assert_eq!(telemetry.publish_failures, 1);
|
||||||
|
assert_eq!(telemetry.worker_panics, 1);
|
||||||
|
assert_eq!(telemetry.stale_submission_discards, 1);
|
||||||
|
assert_eq!(telemetry.last_error_frame_id, 13);
|
||||||
|
assert_eq!(telemetry.last_dropped_frame_id, 14);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,16 +8,22 @@ pub struct SceneBank {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use crate::asset::AssetId;
|
||||||
use crate::glyph::Glyph;
|
use crate::glyph::Glyph;
|
||||||
use crate::glyph_bank::TileSize;
|
use crate::glyph_bank::TileSize;
|
||||||
use crate::scene_layer::ParallaxFactor;
|
use crate::scene_layer::ParallaxFactor;
|
||||||
use crate::tile::Tile;
|
use crate::tile::Tile;
|
||||||
use crate::tilemap::TileMap;
|
use crate::tilemap::TileMap;
|
||||||
|
|
||||||
fn layer(glyph_bank_id: u8, parallax_x: f32, parallax_y: f32, glyph_id: u16) -> SceneLayer {
|
fn layer(
|
||||||
|
glyph_asset_id: AssetId,
|
||||||
|
parallax_x: f32,
|
||||||
|
parallax_y: f32,
|
||||||
|
glyph_id: u16,
|
||||||
|
) -> SceneLayer {
|
||||||
SceneLayer {
|
SceneLayer {
|
||||||
active: true,
|
active: true,
|
||||||
glyph_bank_id,
|
glyph_asset_id,
|
||||||
tile_size: TileSize::Size16,
|
tile_size: TileSize::Size16,
|
||||||
parallax_factor: ParallaxFactor { x: parallax_x, y: parallax_y },
|
parallax_factor: ParallaxFactor { x: parallax_x, y: parallax_y },
|
||||||
tilemap: TileMap {
|
tilemap: TileMap {
|
||||||
@@ -25,7 +31,7 @@ mod tests {
|
|||||||
height: 1,
|
height: 1,
|
||||||
tiles: vec![Tile {
|
tiles: vec![Tile {
|
||||||
active: true,
|
active: true,
|
||||||
glyph: Glyph { glyph_id, palette_id: glyph_bank_id },
|
glyph: Glyph { glyph_id, palette_id: 1 },
|
||||||
flip_x: false,
|
flip_x: false,
|
||||||
flip_y: false,
|
flip_y: false,
|
||||||
}],
|
}],
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
use crate::asset::AssetId;
|
||||||
use crate::glyph_bank::TileSize;
|
use crate::glyph_bank::TileSize;
|
||||||
use crate::tilemap::TileMap;
|
use crate::tilemap::TileMap;
|
||||||
|
|
||||||
@@ -10,7 +11,7 @@ pub struct ParallaxFactor {
|
|||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct SceneLayer {
|
pub struct SceneLayer {
|
||||||
pub active: bool,
|
pub active: bool,
|
||||||
pub glyph_bank_id: u8,
|
pub glyph_asset_id: AssetId,
|
||||||
pub tile_size: TileSize,
|
pub tile_size: TileSize,
|
||||||
pub parallax_factor: ParallaxFactor,
|
pub parallax_factor: ParallaxFactor,
|
||||||
pub tilemap: TileMap,
|
pub tilemap: TileMap,
|
||||||
@@ -26,7 +27,7 @@ mod tests {
|
|||||||
fn scene_layer_preserves_parallax_factor_and_tilemap_ownership() {
|
fn scene_layer_preserves_parallax_factor_and_tilemap_ownership() {
|
||||||
let layer = SceneLayer {
|
let layer = SceneLayer {
|
||||||
active: true,
|
active: true,
|
||||||
glyph_bank_id: 7,
|
glyph_asset_id: 7,
|
||||||
tile_size: TileSize::Size16,
|
tile_size: TileSize::Size16,
|
||||||
parallax_factor: ParallaxFactor { x: 0.5, y: 0.75 },
|
parallax_factor: ParallaxFactor { x: 0.5, y: 0.75 },
|
||||||
tilemap: TileMap {
|
tilemap: TileMap {
|
||||||
@@ -49,7 +50,7 @@ mod tests {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
assert_eq!(layer.glyph_bank_id, 7);
|
assert_eq!(layer.glyph_asset_id, 7);
|
||||||
assert_eq!(layer.parallax_factor.x, 0.5);
|
assert_eq!(layer.parallax_factor.x, 0.5);
|
||||||
assert_eq!(layer.parallax_factor.y, 0.75);
|
assert_eq!(layer.parallax_factor.y, 0.75);
|
||||||
assert_eq!(layer.tilemap.width, 2);
|
assert_eq!(layer.tilemap.width, 2);
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
use crate::asset::AssetId;
|
||||||
use crate::glyph_bank::TileSize;
|
use crate::glyph_bank::TileSize;
|
||||||
use crate::scene_bank::SceneBank;
|
use crate::scene_bank::SceneBank;
|
||||||
use crate::scene_layer::SceneLayer;
|
use crate::scene_layer::SceneLayer;
|
||||||
@@ -12,7 +13,7 @@ pub struct CachedTileEntry {
|
|||||||
pub glyph_id: u16,
|
pub glyph_id: u16,
|
||||||
pub palette_id: u8,
|
pub palette_id: u8,
|
||||||
pub flags: u8,
|
pub flags: u8,
|
||||||
pub glyph_bank_id: u8,
|
pub glyph_asset_id: AssetId,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CachedTileEntry {
|
impl CachedTileEntry {
|
||||||
@@ -38,7 +39,7 @@ impl CachedTileEntry {
|
|||||||
glyph_id: tile.glyph.glyph_id,
|
glyph_id: tile.glyph.glyph_id,
|
||||||
palette_id: tile.glyph.palette_id,
|
palette_id: tile.glyph.palette_id,
|
||||||
flags,
|
flags,
|
||||||
glyph_bank_id: layer.glyph_bank_id,
|
glyph_asset_id: layer.glyph_asset_id,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -65,7 +66,7 @@ pub struct SceneViewportLayerCache {
|
|||||||
logical_origin_y: i32,
|
logical_origin_y: i32,
|
||||||
ring_origin_x: usize,
|
ring_origin_x: usize,
|
||||||
ring_origin_y: usize,
|
ring_origin_y: usize,
|
||||||
pub glyph_bank_id: u8,
|
pub glyph_asset_id: AssetId,
|
||||||
pub tile_size: TileSize,
|
pub tile_size: TileSize,
|
||||||
entries: Vec<CachedTileEntry>,
|
entries: Vec<CachedTileEntry>,
|
||||||
pub valid: bool,
|
pub valid: bool,
|
||||||
@@ -80,7 +81,7 @@ impl SceneViewportLayerCache {
|
|||||||
logical_origin_y: 0,
|
logical_origin_y: 0,
|
||||||
ring_origin_x: 0,
|
ring_origin_x: 0,
|
||||||
ring_origin_y: 0,
|
ring_origin_y: 0,
|
||||||
glyph_bank_id: layer.glyph_bank_id,
|
glyph_asset_id: layer.glyph_asset_id,
|
||||||
tile_size: layer.tile_size,
|
tile_size: layer.tile_size,
|
||||||
entries: vec![CachedTileEntry::default(); width * height],
|
entries: vec![CachedTileEntry::default(); width * height],
|
||||||
valid: false,
|
valid: false,
|
||||||
@@ -136,7 +137,7 @@ impl SceneViewportLayerCache {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn refresh_region(&mut self, layer: &SceneLayer, region: ViewportRegion) {
|
pub fn refresh_region(&mut self, layer: &SceneLayer, region: ViewportRegion) {
|
||||||
self.glyph_bank_id = layer.glyph_bank_id;
|
self.glyph_asset_id = layer.glyph_asset_id;
|
||||||
self.tile_size = layer.tile_size;
|
self.tile_size = layer.tile_size;
|
||||||
|
|
||||||
let max_x = region.x.saturating_add(region.width).min(self.width);
|
let max_x = region.x.saturating_add(region.width).min(self.width);
|
||||||
@@ -268,6 +269,7 @@ impl SceneViewportCache {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use crate::asset::AssetId;
|
||||||
use crate::glyph::Glyph;
|
use crate::glyph::Glyph;
|
||||||
use crate::glyph_bank::TileSize;
|
use crate::glyph_bank::TileSize;
|
||||||
use crate::scene_layer::ParallaxFactor;
|
use crate::scene_layer::ParallaxFactor;
|
||||||
@@ -278,22 +280,17 @@ mod tests {
|
|||||||
Tile { active: true, glyph: Glyph { glyph_id, palette_id }, flip_x, flip_y }
|
Tile { active: true, glyph: Glyph { glyph_id, palette_id }, flip_x, flip_y }
|
||||||
}
|
}
|
||||||
|
|
||||||
fn make_layer(glyph_bank_id: u8, base_glyph: u16) -> SceneLayer {
|
fn make_layer(glyph_asset_id: AssetId, base_glyph: u16) -> SceneLayer {
|
||||||
let mut tiles = Vec::new();
|
let mut tiles = Vec::new();
|
||||||
for y in 0..4 {
|
for y in 0..4 {
|
||||||
for x in 0..4 {
|
for x in 0..4 {
|
||||||
tiles.push(make_tile(
|
tiles.push(make_tile(base_glyph + (y * 4 + x) as u16, 1, x % 2 == 0, y % 2 == 1));
|
||||||
base_glyph + (y * 4 + x) as u16,
|
|
||||||
glyph_bank_id,
|
|
||||||
x % 2 == 0,
|
|
||||||
y % 2 == 1,
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
SceneLayer {
|
SceneLayer {
|
||||||
active: true,
|
active: true,
|
||||||
glyph_bank_id,
|
glyph_asset_id,
|
||||||
tile_size: TileSize::Size16,
|
tile_size: TileSize::Size16,
|
||||||
parallax_factor: ParallaxFactor { x: 1.0, y: 1.0 },
|
parallax_factor: ParallaxFactor { x: 1.0, y: 1.0 },
|
||||||
tilemap: TileMap { width: 4, height: 4, tiles },
|
tilemap: TileMap { width: 4, height: 4, tiles },
|
||||||
@@ -364,7 +361,7 @@ mod tests {
|
|||||||
assert!(entry.active);
|
assert!(entry.active);
|
||||||
assert_eq!(entry.glyph_id, 105);
|
assert_eq!(entry.glyph_id, 105);
|
||||||
assert_eq!(entry.palette_id, 1);
|
assert_eq!(entry.palette_id, 1);
|
||||||
assert_eq!(entry.glyph_bank_id, 1);
|
assert_eq!(entry.glyph_asset_id, 1);
|
||||||
assert!(!entry.flip_x());
|
assert!(!entry.flip_x());
|
||||||
assert!(entry.flip_y());
|
assert!(entry.flip_y());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -386,6 +386,7 @@ impl SceneViewportResolver {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use crate::asset::AssetId;
|
||||||
use crate::glyph::Glyph;
|
use crate::glyph::Glyph;
|
||||||
use crate::glyph_bank::TileSize;
|
use crate::glyph_bank::TileSize;
|
||||||
use crate::scene_layer::{ParallaxFactor, SceneLayer};
|
use crate::scene_layer::{ParallaxFactor, SceneLayer};
|
||||||
@@ -411,7 +412,7 @@ mod tests {
|
|||||||
|
|
||||||
SceneLayer {
|
SceneLayer {
|
||||||
active: true,
|
active: true,
|
||||||
glyph_bank_id: 1,
|
glyph_asset_id: 1 as AssetId,
|
||||||
tile_size,
|
tile_size,
|
||||||
parallax_factor: ParallaxFactor { x: parallax_x, y: parallax_y },
|
parallax_factor: ParallaxFactor { x: parallax_x, y: parallax_y },
|
||||||
tilemap: TileMap { width, height, tiles },
|
tilemap: TileMap { width, height, tiles },
|
||||||
@@ -432,20 +433,20 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn first_update_initializes_master_and_layer_anchors() {
|
fn first_update_initializes_master_and_layer_anchors() {
|
||||||
let scene = make_scene();
|
let scene = make_scene();
|
||||||
let mut resolver = SceneViewportResolver::new(320, 180, 25, 16, 12, 20);
|
let mut resolver = SceneViewportResolver::new(480, 270, 35, 21, 12, 20);
|
||||||
|
|
||||||
let update = resolver.update(&scene, 0, 0);
|
let update = resolver.update(&scene, 0, 0);
|
||||||
|
|
||||||
assert_eq!(update.master_anchor, TileAnchor { x: 12, y: 8 });
|
assert_eq!(update.master_anchor, TileAnchor { x: 17, y: 10 });
|
||||||
assert_eq!(update.layer_anchors[0], TileAnchor { x: 12, y: 8 });
|
assert_eq!(update.layer_anchors[0], TileAnchor { x: 17, y: 10 });
|
||||||
assert_eq!(update.layer_anchors[1], TileAnchor { x: 12, y: 8 });
|
assert_eq!(update.layer_anchors[1], TileAnchor { x: 17, y: 10 });
|
||||||
assert_eq!(update.refresh_requests.len(), 4);
|
assert_eq!(update.refresh_requests.len(), 4);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn per_layer_copy_requests_follow_parallax_factor() {
|
fn per_layer_copy_requests_follow_parallax_factor() {
|
||||||
let scene = make_scene();
|
let scene = make_scene();
|
||||||
let mut resolver = SceneViewportResolver::new(320, 180, 25, 16, 12, 20);
|
let mut resolver = SceneViewportResolver::new(480, 270, 35, 21, 12, 20);
|
||||||
|
|
||||||
let update = resolver.update(&scene, 32, 48);
|
let update = resolver.update(&scene, 32, 48);
|
||||||
|
|
||||||
@@ -460,24 +461,24 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn hysteresis_prevents_small_back_and_forth_refresh_churn() {
|
fn hysteresis_prevents_small_back_and_forth_refresh_churn() {
|
||||||
let scene = make_scene();
|
let scene = make_scene();
|
||||||
let mut resolver = SceneViewportResolver::new(320, 180, 25, 16, 12, 20);
|
let mut resolver = SceneViewportResolver::new(480, 270, 35, 21, 12, 20);
|
||||||
|
|
||||||
let _ = resolver.update(&scene, 0, 0);
|
let _ = resolver.update(&scene, 0, 0);
|
||||||
let update = resolver.update(&scene, 8, 0);
|
let update = resolver.update(&scene, 8, 0);
|
||||||
|
|
||||||
assert!(update.refresh_requests.is_empty());
|
assert!(update.refresh_requests.is_empty());
|
||||||
assert_eq!(update.master_anchor, TileAnchor { x: 12, y: 8 });
|
assert_eq!(update.master_anchor, TileAnchor { x: 17, y: 10 });
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn repeated_high_speed_movement_advances_in_tile_steps() {
|
fn repeated_high_speed_movement_advances_in_tile_steps() {
|
||||||
let scene = make_scene();
|
let scene = make_scene();
|
||||||
let mut resolver = SceneViewportResolver::new(320, 180, 25, 16, 12, 20);
|
let mut resolver = SceneViewportResolver::new(480, 270, 35, 21, 12, 20);
|
||||||
|
|
||||||
let _ = resolver.update(&scene, 0, 0);
|
let _ = resolver.update(&scene, 0, 0);
|
||||||
let update = resolver.update(&scene, 64, 0);
|
let update = resolver.update(&scene, 64, 0);
|
||||||
|
|
||||||
assert!(update.master_anchor.x > 12);
|
assert!(update.master_anchor.x > 17);
|
||||||
assert!(update.refresh_requests.iter().any(|request| matches!(
|
assert!(update.refresh_requests.iter().any(|request| matches!(
|
||||||
request,
|
request,
|
||||||
CacheRefreshRequest::RefreshColumn { layer_index: 0, .. }
|
CacheRefreshRequest::RefreshColumn { layer_index: 0, .. }
|
||||||
@@ -488,18 +489,18 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn anchors_clamp_near_scene_edges() {
|
fn anchors_clamp_near_scene_edges() {
|
||||||
let scene = make_scene();
|
let scene = make_scene();
|
||||||
let mut resolver = SceneViewportResolver::new(320, 180, 25, 16, 12, 20);
|
let mut resolver = SceneViewportResolver::new(480, 270, 35, 21, 12, 20);
|
||||||
|
|
||||||
let update = resolver.update(&scene, 10_000, 10_000);
|
let update = resolver.update(&scene, 10_000, 10_000);
|
||||||
|
|
||||||
assert_eq!(update.master_anchor, TileAnchor { x: 51, y: 56 });
|
assert_eq!(update.master_anchor, TileAnchor { x: 46, y: 53 });
|
||||||
assert_eq!(update.layer_anchors[0], TileAnchor { x: 51, y: 56 });
|
assert_eq!(update.layer_anchors[0], TileAnchor { x: 46, y: 53 });
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn corner_trigger_converts_to_non_overlapping_region_requests() {
|
fn corner_trigger_converts_to_non_overlapping_region_requests() {
|
||||||
let scene = make_scene();
|
let scene = make_scene();
|
||||||
let mut resolver = SceneViewportResolver::new(320, 180, 25, 16, 12, 20);
|
let mut resolver = SceneViewportResolver::new(480, 270, 35, 21, 12, 20);
|
||||||
|
|
||||||
let _ = resolver.update(&scene, 0, 0);
|
let _ = resolver.update(&scene, 0, 0);
|
||||||
let update = resolver.update(&scene, 64, 80);
|
let update = resolver.update(&scene, 64, 80);
|
||||||
@@ -514,15 +515,15 @@ mod tests {
|
|||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
assert_eq!(regions.len(), 2);
|
assert_eq!(regions.len(), 2);
|
||||||
assert_eq!(regions[0].x + regions[0].width, 25);
|
assert_eq!(regions[0].x + regions[0].width, 35);
|
||||||
assert_eq!(regions[0].height, 16);
|
assert_eq!(regions[0].height, 21);
|
||||||
assert_eq!(regions[1].width, 24);
|
assert_eq!(regions[1].width, 34);
|
||||||
assert_eq!(regions[1].height, 1);
|
assert_eq!(regions[1].height, 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn reset_scene_requests_full_invalidation_for_all_layers() {
|
fn reset_scene_requests_full_invalidation_for_all_layers() {
|
||||||
let mut resolver = SceneViewportResolver::new(320, 180, 25, 16, 12, 20);
|
let mut resolver = SceneViewportResolver::new(480, 270, 35, 21, 12, 20);
|
||||||
|
|
||||||
let requests = resolver.reset_scene();
|
let requests = resolver.reset_scene();
|
||||||
|
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ pub use resolver::{
|
|||||||
///
|
///
|
||||||
/// Each Syscall has a unique 32-bit ID. The IDs are grouped by category:
|
/// Each Syscall has a unique 32-bit ID. The IDs are grouped by category:
|
||||||
/// - **0x0xxx**: System & OS Control
|
/// - **0x0xxx**: System & OS Control
|
||||||
/// - **0x1xxx**: Graphics (GFX)
|
/// - **0x1xxx**: Game 2D primitives (`gfx2d`) and Shell UI primitives (`gfxui`)
|
||||||
/// - **0x11xx**: Frame Composer orchestration
|
/// - **0x11xx**: Frame Composer orchestration
|
||||||
/// - **0x2xxx**: Reserved for legacy input syscalls (disabled for v1 VM-owned input)
|
/// - **0x2xxx**: Reserved for legacy input syscalls (disabled for v1 VM-owned input)
|
||||||
/// - **0x3xxx**: Audio (PCM & Mixing)
|
/// - **0x3xxx**: Audio (PCM & Mixing)
|
||||||
@@ -29,7 +29,6 @@ pub use resolver::{
|
|||||||
#[repr(u32)]
|
#[repr(u32)]
|
||||||
pub enum Syscall {
|
pub enum Syscall {
|
||||||
SystemHasCart = 0x0001,
|
SystemHasCart = 0x0001,
|
||||||
SystemRunCart = 0x0002,
|
|
||||||
GfxClear = 0x1001,
|
GfxClear = 0x1001,
|
||||||
GfxFillRect = 0x1002,
|
GfxFillRect = 0x1002,
|
||||||
GfxDrawLine = 0x1003,
|
GfxDrawLine = 0x1003,
|
||||||
@@ -37,7 +36,13 @@ pub enum Syscall {
|
|||||||
GfxDrawDisc = 0x1005,
|
GfxDrawDisc = 0x1005,
|
||||||
GfxDrawSquare = 0x1006,
|
GfxDrawSquare = 0x1006,
|
||||||
GfxDrawText = 0x1008,
|
GfxDrawText = 0x1008,
|
||||||
GfxClear565 = 0x1010,
|
GfxUiClear = 0x1201,
|
||||||
|
GfxUiFillRect = 0x1202,
|
||||||
|
GfxUiDrawLine = 0x1203,
|
||||||
|
GfxUiDrawCircle = 0x1204,
|
||||||
|
GfxUiDrawDisc = 0x1205,
|
||||||
|
GfxUiDrawSquare = 0x1206,
|
||||||
|
GfxUiDrawText = 0x1208,
|
||||||
ComposerBindScene = 0x1101,
|
ComposerBindScene = 0x1101,
|
||||||
ComposerUnbindScene = 0x1102,
|
ComposerUnbindScene = 0x1102,
|
||||||
ComposerSetCamera = 0x1103,
|
ComposerSetCamera = 0x1103,
|
||||||
@@ -63,6 +68,12 @@ pub enum Syscall {
|
|||||||
AssetStatus = 0x6002,
|
AssetStatus = 0x6002,
|
||||||
AssetCommit = 0x6003,
|
AssetCommit = 0x6003,
|
||||||
AssetCancel = 0x6004,
|
AssetCancel = 0x6004,
|
||||||
|
AssetBacklogInfo = 0x6005,
|
||||||
|
AssetBacklogPosition = 0x6006,
|
||||||
|
AssetBacklogMove = 0x6007,
|
||||||
|
AssetBacklogPromote = 0x6008,
|
||||||
|
AssetBacklogDemote = 0x6009,
|
||||||
|
AssetTargetStatus = 0x600A,
|
||||||
BankInfo = 0x6101,
|
BankInfo = 0x6101,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,10 +2,13 @@ use super::CapFlags;
|
|||||||
|
|
||||||
pub const NONE: CapFlags = 0;
|
pub const NONE: CapFlags = 0;
|
||||||
pub const SYSTEM: CapFlags = 1 << 0;
|
pub const SYSTEM: CapFlags = 1 << 0;
|
||||||
pub const GFX: CapFlags = 1 << 1;
|
pub const COMPOSER: CapFlags = 1 << 1;
|
||||||
pub const AUDIO: CapFlags = 1 << 2;
|
pub const AUDIO: CapFlags = 1 << 2;
|
||||||
pub const FS: CapFlags = 1 << 3;
|
pub const FS: CapFlags = 1 << 3;
|
||||||
pub const LOG: CapFlags = 1 << 4;
|
pub const LOG: CapFlags = 1 << 4;
|
||||||
pub const ASSET: CapFlags = 1 << 5;
|
pub const ASSET: CapFlags = 1 << 5;
|
||||||
pub const BANK: CapFlags = 1 << 6;
|
pub const BANK: CapFlags = 1 << 6;
|
||||||
pub const ALL: CapFlags = SYSTEM | GFX | AUDIO | FS | LOG | ASSET | BANK;
|
pub const GFX2D: CapFlags = 1 << 7;
|
||||||
|
pub const GFXUI: CapFlags = 1 << 8;
|
||||||
|
pub const GFX: CapFlags = COMPOSER | GFX2D;
|
||||||
|
pub const ALL: CapFlags = SYSTEM | COMPOSER | AUDIO | FS | LOG | ASSET | BANK | GFX2D | GFXUI;
|
||||||
|
|||||||
@@ -24,4 +24,40 @@ pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
|
|||||||
.caps(caps::ASSET)
|
.caps(caps::ASSET)
|
||||||
.non_deterministic()
|
.non_deterministic()
|
||||||
.cost(20),
|
.cost(20),
|
||||||
|
SyscallRegistryEntry::builder(Syscall::AssetBacklogInfo, "asset", "backlog_info")
|
||||||
|
.args(0)
|
||||||
|
.rets(7)
|
||||||
|
.caps(caps::ASSET)
|
||||||
|
.non_deterministic()
|
||||||
|
.cost(5),
|
||||||
|
SyscallRegistryEntry::builder(Syscall::AssetBacklogPosition, "asset", "backlog_position")
|
||||||
|
.args(1)
|
||||||
|
.rets(4)
|
||||||
|
.caps(caps::ASSET)
|
||||||
|
.non_deterministic()
|
||||||
|
.cost(5),
|
||||||
|
SyscallRegistryEntry::builder(Syscall::AssetBacklogMove, "asset", "backlog_move")
|
||||||
|
.args(2)
|
||||||
|
.rets(1)
|
||||||
|
.caps(caps::ASSET)
|
||||||
|
.non_deterministic()
|
||||||
|
.cost(10),
|
||||||
|
SyscallRegistryEntry::builder(Syscall::AssetBacklogPromote, "asset", "backlog_promote")
|
||||||
|
.args(1)
|
||||||
|
.rets(1)
|
||||||
|
.caps(caps::ASSET)
|
||||||
|
.non_deterministic()
|
||||||
|
.cost(10),
|
||||||
|
SyscallRegistryEntry::builder(Syscall::AssetBacklogDemote, "asset", "backlog_demote")
|
||||||
|
.args(1)
|
||||||
|
.rets(1)
|
||||||
|
.caps(caps::ASSET)
|
||||||
|
.non_deterministic()
|
||||||
|
.cost(10),
|
||||||
|
SyscallRegistryEntry::builder(Syscall::AssetTargetStatus, "asset", "target_status")
|
||||||
|
.args(2)
|
||||||
|
.rets(6)
|
||||||
|
.caps(caps::ASSET)
|
||||||
|
.non_deterministic()
|
||||||
|
.cost(5),
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -4,19 +4,19 @@ pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
|
|||||||
SyscallRegistryEntry::builder(Syscall::ComposerBindScene, "composer", "bind_scene")
|
SyscallRegistryEntry::builder(Syscall::ComposerBindScene, "composer", "bind_scene")
|
||||||
.args(1)
|
.args(1)
|
||||||
.rets(1)
|
.rets(1)
|
||||||
.caps(caps::GFX)
|
.caps(caps::COMPOSER)
|
||||||
.cost(5),
|
.cost(5),
|
||||||
SyscallRegistryEntry::builder(Syscall::ComposerUnbindScene, "composer", "unbind_scene")
|
SyscallRegistryEntry::builder(Syscall::ComposerUnbindScene, "composer", "unbind_scene")
|
||||||
.rets(1)
|
.rets(1)
|
||||||
.caps(caps::GFX)
|
.caps(caps::COMPOSER)
|
||||||
.cost(2),
|
.cost(2),
|
||||||
SyscallRegistryEntry::builder(Syscall::ComposerSetCamera, "composer", "set_camera")
|
SyscallRegistryEntry::builder(Syscall::ComposerSetCamera, "composer", "set_camera")
|
||||||
.args(2)
|
.args(2)
|
||||||
.caps(caps::GFX)
|
.caps(caps::COMPOSER)
|
||||||
.cost(2),
|
.cost(2),
|
||||||
SyscallRegistryEntry::builder(Syscall::ComposerEmitSprite, "composer", "emit_sprite")
|
SyscallRegistryEntry::builder(Syscall::ComposerEmitSprite, "composer", "emit_sprite")
|
||||||
.args(9)
|
.args(9)
|
||||||
.rets(1)
|
.rets(1)
|
||||||
.caps(caps::GFX)
|
.caps(caps::COMPOSER)
|
||||||
.cost(5),
|
.cost(5),
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -1,36 +1,32 @@
|
|||||||
use crate::syscalls::{Syscall, SyscallRegistryEntry, caps};
|
use crate::syscalls::{Syscall, SyscallRegistryEntry, caps};
|
||||||
|
|
||||||
pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
|
pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
|
||||||
SyscallRegistryEntry::builder(Syscall::GfxClear, "gfx", "clear")
|
SyscallRegistryEntry::builder(Syscall::GfxClear, "gfx2d", "clear")
|
||||||
.args(1)
|
.args(1)
|
||||||
.caps(caps::GFX)
|
.caps(caps::GFX2D)
|
||||||
.cost(20),
|
.cost(20),
|
||||||
SyscallRegistryEntry::builder(Syscall::GfxFillRect, "gfx", "fill_rect")
|
SyscallRegistryEntry::builder(Syscall::GfxFillRect, "gfx2d", "fill_rect")
|
||||||
.args(5)
|
.args(5)
|
||||||
.caps(caps::GFX)
|
.caps(caps::GFX2D)
|
||||||
.cost(20),
|
.cost(20),
|
||||||
SyscallRegistryEntry::builder(Syscall::GfxDrawLine, "gfx", "draw_line")
|
SyscallRegistryEntry::builder(Syscall::GfxDrawLine, "gfx2d", "draw_line")
|
||||||
.args(5)
|
.args(5)
|
||||||
.caps(caps::GFX)
|
.caps(caps::GFX2D)
|
||||||
.cost(5),
|
.cost(5),
|
||||||
SyscallRegistryEntry::builder(Syscall::GfxDrawCircle, "gfx", "draw_circle")
|
SyscallRegistryEntry::builder(Syscall::GfxDrawCircle, "gfx2d", "draw_circle")
|
||||||
.args(4)
|
.args(4)
|
||||||
.caps(caps::GFX)
|
.caps(caps::GFX2D)
|
||||||
.cost(5),
|
.cost(5),
|
||||||
SyscallRegistryEntry::builder(Syscall::GfxDrawDisc, "gfx", "draw_disc")
|
SyscallRegistryEntry::builder(Syscall::GfxDrawDisc, "gfx2d", "draw_disc")
|
||||||
.args(5)
|
.args(5)
|
||||||
.caps(caps::GFX)
|
.caps(caps::GFX2D)
|
||||||
.cost(5),
|
.cost(5),
|
||||||
SyscallRegistryEntry::builder(Syscall::GfxDrawSquare, "gfx", "draw_square")
|
SyscallRegistryEntry::builder(Syscall::GfxDrawSquare, "gfx2d", "draw_square")
|
||||||
.args(6)
|
.args(6)
|
||||||
.caps(caps::GFX)
|
.caps(caps::GFX2D)
|
||||||
.cost(5),
|
.cost(5),
|
||||||
SyscallRegistryEntry::builder(Syscall::GfxDrawText, "gfx", "draw_text")
|
SyscallRegistryEntry::builder(Syscall::GfxDrawText, "gfx2d", "draw_text")
|
||||||
.args(4)
|
.args(4)
|
||||||
.caps(caps::GFX)
|
.caps(caps::GFX2D)
|
||||||
.cost(20),
|
|
||||||
SyscallRegistryEntry::builder(Syscall::GfxClear565, "gfx", "clear_565")
|
|
||||||
.args(1)
|
|
||||||
.caps(caps::GFX)
|
|
||||||
.cost(20),
|
.cost(20),
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
use crate::syscalls::{Syscall, SyscallRegistryEntry, caps};
|
||||||
|
|
||||||
|
pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
|
||||||
|
SyscallRegistryEntry::builder(Syscall::GfxUiClear, "gfxui", "clear")
|
||||||
|
.args(1)
|
||||||
|
.caps(caps::GFXUI)
|
||||||
|
.cost(20),
|
||||||
|
SyscallRegistryEntry::builder(Syscall::GfxUiFillRect, "gfxui", "fill_rect")
|
||||||
|
.args(5)
|
||||||
|
.caps(caps::GFXUI)
|
||||||
|
.cost(20),
|
||||||
|
SyscallRegistryEntry::builder(Syscall::GfxUiDrawLine, "gfxui", "draw_line")
|
||||||
|
.args(5)
|
||||||
|
.caps(caps::GFXUI)
|
||||||
|
.cost(5),
|
||||||
|
SyscallRegistryEntry::builder(Syscall::GfxUiDrawCircle, "gfxui", "draw_circle")
|
||||||
|
.args(4)
|
||||||
|
.caps(caps::GFXUI)
|
||||||
|
.cost(5),
|
||||||
|
SyscallRegistryEntry::builder(Syscall::GfxUiDrawDisc, "gfxui", "draw_disc")
|
||||||
|
.args(5)
|
||||||
|
.caps(caps::GFXUI)
|
||||||
|
.cost(5),
|
||||||
|
SyscallRegistryEntry::builder(Syscall::GfxUiDrawSquare, "gfxui", "draw_square")
|
||||||
|
.args(6)
|
||||||
|
.caps(caps::GFXUI)
|
||||||
|
.cost(5),
|
||||||
|
SyscallRegistryEntry::builder(Syscall::GfxUiDrawText, "gfxui", "draw_text")
|
||||||
|
.args(4)
|
||||||
|
.caps(caps::GFXUI)
|
||||||
|
.cost(20),
|
||||||
|
];
|
||||||
@@ -4,6 +4,7 @@ mod bank;
|
|||||||
mod composer;
|
mod composer;
|
||||||
mod fs;
|
mod fs;
|
||||||
mod gfx;
|
mod gfx;
|
||||||
|
mod gfxui;
|
||||||
mod log;
|
mod log;
|
||||||
mod system;
|
mod system;
|
||||||
|
|
||||||
@@ -13,6 +14,7 @@ pub(crate) fn all_entries() -> impl Iterator<Item = &'static SyscallRegistryEntr
|
|||||||
system::ENTRIES
|
system::ENTRIES
|
||||||
.iter()
|
.iter()
|
||||||
.chain(gfx::ENTRIES.iter())
|
.chain(gfx::ENTRIES.iter())
|
||||||
|
.chain(gfxui::ENTRIES.iter())
|
||||||
.chain(composer::ENTRIES.iter())
|
.chain(composer::ENTRIES.iter())
|
||||||
.chain(audio::ENTRIES.iter())
|
.chain(audio::ENTRIES.iter())
|
||||||
.chain(fs::ENTRIES.iter())
|
.chain(fs::ENTRIES.iter())
|
||||||
|
|||||||
@@ -1,11 +1,6 @@
|
|||||||
use crate::syscalls::{Syscall, SyscallRegistryEntry, caps};
|
use crate::syscalls::{Syscall, SyscallRegistryEntry, caps};
|
||||||
|
|
||||||
pub(crate) const ENTRIES: &[SyscallRegistryEntry] = &[
|
pub(crate) const ENTRIES: &[SyscallRegistryEntry] =
|
||||||
SyscallRegistryEntry::builder(Syscall::SystemHasCart, "system", "has_cart")
|
&[SyscallRegistryEntry::builder(Syscall::SystemHasCart, "system", "has_cart")
|
||||||
.rets(1)
|
.rets(1)
|
||||||
.caps(caps::SYSTEM),
|
.caps(caps::SYSTEM)];
|
||||||
SyscallRegistryEntry::builder(Syscall::SystemRunCart, "system", "run_cart")
|
|
||||||
.caps(caps::SYSTEM)
|
|
||||||
.non_deterministic()
|
|
||||||
.cost(50),
|
|
||||||
];
|
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ impl Syscall {
|
|||||||
pub fn from_u32(id: u32) -> Option<Self> {
|
pub fn from_u32(id: u32) -> Option<Self> {
|
||||||
match id {
|
match id {
|
||||||
0x0001 => Some(Self::SystemHasCart),
|
0x0001 => Some(Self::SystemHasCart),
|
||||||
0x0002 => Some(Self::SystemRunCart),
|
|
||||||
0x1001 => Some(Self::GfxClear),
|
0x1001 => Some(Self::GfxClear),
|
||||||
0x1002 => Some(Self::GfxFillRect),
|
0x1002 => Some(Self::GfxFillRect),
|
||||||
0x1003 => Some(Self::GfxDrawLine),
|
0x1003 => Some(Self::GfxDrawLine),
|
||||||
@@ -21,7 +20,13 @@ impl Syscall {
|
|||||||
0x1005 => Some(Self::GfxDrawDisc),
|
0x1005 => Some(Self::GfxDrawDisc),
|
||||||
0x1006 => Some(Self::GfxDrawSquare),
|
0x1006 => Some(Self::GfxDrawSquare),
|
||||||
0x1008 => Some(Self::GfxDrawText),
|
0x1008 => Some(Self::GfxDrawText),
|
||||||
0x1010 => Some(Self::GfxClear565),
|
0x1201 => Some(Self::GfxUiClear),
|
||||||
|
0x1202 => Some(Self::GfxUiFillRect),
|
||||||
|
0x1203 => Some(Self::GfxUiDrawLine),
|
||||||
|
0x1204 => Some(Self::GfxUiDrawCircle),
|
||||||
|
0x1205 => Some(Self::GfxUiDrawDisc),
|
||||||
|
0x1206 => Some(Self::GfxUiDrawSquare),
|
||||||
|
0x1208 => Some(Self::GfxUiDrawText),
|
||||||
0x1101 => Some(Self::ComposerBindScene),
|
0x1101 => Some(Self::ComposerBindScene),
|
||||||
0x1102 => Some(Self::ComposerUnbindScene),
|
0x1102 => Some(Self::ComposerUnbindScene),
|
||||||
0x1103 => Some(Self::ComposerSetCamera),
|
0x1103 => Some(Self::ComposerSetCamera),
|
||||||
@@ -47,6 +52,12 @@ impl Syscall {
|
|||||||
0x6002 => Some(Self::AssetStatus),
|
0x6002 => Some(Self::AssetStatus),
|
||||||
0x6003 => Some(Self::AssetCommit),
|
0x6003 => Some(Self::AssetCommit),
|
||||||
0x6004 => Some(Self::AssetCancel),
|
0x6004 => Some(Self::AssetCancel),
|
||||||
|
0x6005 => Some(Self::AssetBacklogInfo),
|
||||||
|
0x6006 => Some(Self::AssetBacklogPosition),
|
||||||
|
0x6007 => Some(Self::AssetBacklogMove),
|
||||||
|
0x6008 => Some(Self::AssetBacklogPromote),
|
||||||
|
0x6009 => Some(Self::AssetBacklogDemote),
|
||||||
|
0x600A => Some(Self::AssetTargetStatus),
|
||||||
0x6101 => Some(Self::BankInfo),
|
0x6101 => Some(Self::BankInfo),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
@@ -63,7 +74,6 @@ impl Syscall {
|
|||||||
pub fn name(&self) -> &'static str {
|
pub fn name(&self) -> &'static str {
|
||||||
match self {
|
match self {
|
||||||
Self::SystemHasCart => "SystemHasCart",
|
Self::SystemHasCart => "SystemHasCart",
|
||||||
Self::SystemRunCart => "SystemRunCart",
|
|
||||||
Self::GfxClear => "GfxClear",
|
Self::GfxClear => "GfxClear",
|
||||||
Self::GfxFillRect => "GfxFillRect",
|
Self::GfxFillRect => "GfxFillRect",
|
||||||
Self::GfxDrawLine => "GfxDrawLine",
|
Self::GfxDrawLine => "GfxDrawLine",
|
||||||
@@ -71,7 +81,13 @@ impl Syscall {
|
|||||||
Self::GfxDrawDisc => "GfxDrawDisc",
|
Self::GfxDrawDisc => "GfxDrawDisc",
|
||||||
Self::GfxDrawSquare => "GfxDrawSquare",
|
Self::GfxDrawSquare => "GfxDrawSquare",
|
||||||
Self::GfxDrawText => "GfxDrawText",
|
Self::GfxDrawText => "GfxDrawText",
|
||||||
Self::GfxClear565 => "GfxClear565",
|
Self::GfxUiClear => "GfxUiClear",
|
||||||
|
Self::GfxUiFillRect => "GfxUiFillRect",
|
||||||
|
Self::GfxUiDrawLine => "GfxUiDrawLine",
|
||||||
|
Self::GfxUiDrawCircle => "GfxUiDrawCircle",
|
||||||
|
Self::GfxUiDrawDisc => "GfxUiDrawDisc",
|
||||||
|
Self::GfxUiDrawSquare => "GfxUiDrawSquare",
|
||||||
|
Self::GfxUiDrawText => "GfxUiDrawText",
|
||||||
Self::ComposerBindScene => "ComposerBindScene",
|
Self::ComposerBindScene => "ComposerBindScene",
|
||||||
Self::ComposerUnbindScene => "ComposerUnbindScene",
|
Self::ComposerUnbindScene => "ComposerUnbindScene",
|
||||||
Self::ComposerSetCamera => "ComposerSetCamera",
|
Self::ComposerSetCamera => "ComposerSetCamera",
|
||||||
@@ -97,6 +113,12 @@ impl Syscall {
|
|||||||
Self::AssetStatus => "AssetStatus",
|
Self::AssetStatus => "AssetStatus",
|
||||||
Self::AssetCommit => "AssetCommit",
|
Self::AssetCommit => "AssetCommit",
|
||||||
Self::AssetCancel => "AssetCancel",
|
Self::AssetCancel => "AssetCancel",
|
||||||
|
Self::AssetBacklogInfo => "AssetBacklogInfo",
|
||||||
|
Self::AssetBacklogPosition => "AssetBacklogPosition",
|
||||||
|
Self::AssetBacklogMove => "AssetBacklogMove",
|
||||||
|
Self::AssetBacklogPromote => "AssetBacklogPromote",
|
||||||
|
Self::AssetBacklogDemote => "AssetBacklogDemote",
|
||||||
|
Self::AssetTargetStatus => "AssetTargetStatus",
|
||||||
Self::BankInfo => "BankInfo",
|
Self::BankInfo => "BankInfo",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,23 +39,23 @@ fn every_syscall_has_metadata() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn resolver_returns_expected_id_for_known_identity() {
|
fn resolver_returns_expected_id_for_known_identity() {
|
||||||
let id = resolve_syscall("gfx", "clear", 1).expect("known identity must resolve");
|
let id = resolve_syscall("gfx2d", "clear", 1).expect("known identity must resolve");
|
||||||
assert_eq!(id.id, 0x1001);
|
assert_eq!(id.id, 0x1001);
|
||||||
assert_eq!(id.meta.module, "gfx");
|
assert_eq!(id.meta.module, "gfx2d");
|
||||||
assert_eq!(id.meta.name, "clear");
|
assert_eq!(id.meta.name, "clear");
|
||||||
assert_eq!(id.meta.version, 1);
|
assert_eq!(id.meta.version, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn resolver_rejects_unknown_identity() {
|
fn resolver_rejects_unknown_identity() {
|
||||||
let res = resolve_syscall("gfx", "nonexistent", 1);
|
let res = resolve_syscall("gfx2d", "nonexistent", 1);
|
||||||
assert!(res.is_none());
|
assert!(res.is_none());
|
||||||
|
|
||||||
let requested = [SyscallIdentity { module: "gfx", name: "nonexistent", version: 1 }];
|
let requested = [SyscallIdentity { module: "gfx2d", name: "nonexistent", version: 1 }];
|
||||||
let err = resolve_program_syscalls(&requested, 0).unwrap_err();
|
let err = resolve_program_syscalls(&requested, 0).unwrap_err();
|
||||||
match err {
|
match err {
|
||||||
LoadError::UnknownSyscall { module, name, version } => {
|
LoadError::UnknownSyscall { module, name, version } => {
|
||||||
assert_eq!(module, "gfx");
|
assert_eq!(module, "gfx2d");
|
||||||
assert_eq!(name, "nonexistent");
|
assert_eq!(name, "nonexistent");
|
||||||
assert_eq!(version, 1);
|
assert_eq!(version, 1);
|
||||||
}
|
}
|
||||||
@@ -65,23 +65,47 @@ fn resolver_rejects_unknown_identity() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn resolver_rejects_removed_legacy_gfx_set_sprite_identity() {
|
fn resolver_rejects_removed_legacy_gfx_set_sprite_identity() {
|
||||||
assert!(resolve_syscall("gfx", "set_sprite", 1).is_none());
|
assert!(resolve_syscall("gfx2d", "set_sprite", 1).is_none());
|
||||||
|
|
||||||
let requested = [SyscallIdentity { module: "gfx", name: "set_sprite", version: 1 }];
|
let requested = [SyscallIdentity { module: "gfx2d", name: "set_sprite", version: 1 }];
|
||||||
let err = resolve_program_syscalls(&requested, caps::ALL).unwrap_err();
|
let err = resolve_program_syscalls(&requested, caps::ALL).unwrap_err();
|
||||||
|
assert_eq!(err, LoadError::UnknownSyscall { module: "gfx2d", name: "set_sprite", version: 1 });
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolver_rejects_userland_system_run_cart_identity() {
|
||||||
|
assert!(Syscall::from_u32(0x0002).is_none());
|
||||||
|
assert!(resolve_syscall("system", "run_cart", 1).is_none());
|
||||||
|
|
||||||
|
let requested = [SyscallIdentity { module: "system", name: "run_cart", version: 1 }];
|
||||||
|
let err = resolve_program_syscalls(&requested, caps::ALL).unwrap_err();
|
||||||
|
assert_eq!(err, LoadError::UnknownSyscall { module: "system", name: "run_cart", version: 1 });
|
||||||
|
|
||||||
|
let declared = [prometeu_bytecode::SyscallDecl {
|
||||||
|
module: "system".into(),
|
||||||
|
name: "run_cart".into(),
|
||||||
|
version: 1,
|
||||||
|
arg_slots: 0,
|
||||||
|
ret_slots: 0,
|
||||||
|
}];
|
||||||
|
let err = resolve_declared_program_syscalls(&declared, caps::ALL).unwrap_err();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
err,
|
err,
|
||||||
LoadError::UnknownSyscall { module: "gfx".into(), name: "set_sprite".into(), version: 1 }
|
DeclaredLoadError::UnknownSyscall {
|
||||||
|
module: "system".into(),
|
||||||
|
name: "run_cart".into(),
|
||||||
|
version: 1,
|
||||||
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn resolver_enforces_capabilities() {
|
fn resolver_enforces_capabilities() {
|
||||||
let requested = [SyscallIdentity { module: "gfx", name: "clear", version: 1 }];
|
let requested = [SyscallIdentity { module: "gfx2d", name: "clear", version: 1 }];
|
||||||
let err = resolve_program_syscalls(&requested, 0).unwrap_err();
|
let err = resolve_program_syscalls(&requested, 0).unwrap_err();
|
||||||
match err {
|
match err {
|
||||||
LoadError::MissingCapability { required, provided, module, name, version } => {
|
LoadError::MissingCapability { required, provided, module, name, version } => {
|
||||||
assert_eq!(module, "gfx");
|
assert_eq!(module, "gfx2d");
|
||||||
assert_eq!(name, "clear");
|
assert_eq!(name, "clear");
|
||||||
assert_eq!(version, 1);
|
assert_eq!(version, 1);
|
||||||
assert_ne!(required, 0);
|
assert_ne!(required, 0);
|
||||||
@@ -90,15 +114,30 @@ fn resolver_enforces_capabilities() {
|
|||||||
_ => panic!("expected MissingCapability error"),
|
_ => panic!("expected MissingCapability error"),
|
||||||
}
|
}
|
||||||
|
|
||||||
let ok = resolve_program_syscalls(&requested, caps::GFX).expect("must resolve with caps");
|
let ok = resolve_program_syscalls(&requested, caps::GFX2D).expect("must resolve with caps");
|
||||||
assert_eq!(ok.len(), 1);
|
assert_eq!(ok.len(), 1);
|
||||||
assert_eq!(ok[0].id, 0x1001);
|
assert_eq!(ok[0].id, 0x1001);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolver_exposes_split_render_capabilities() {
|
||||||
|
let composer = resolve_syscall("composer", "bind_scene", 1).expect("composer resolves");
|
||||||
|
assert_eq!(composer.meta.caps, caps::COMPOSER);
|
||||||
|
|
||||||
|
let gfx2d = resolve_syscall("gfx2d", "clear", 1).expect("gfx2d resolves");
|
||||||
|
assert_eq!(gfx2d.meta.caps, caps::GFX2D);
|
||||||
|
|
||||||
|
let gfxui = resolve_syscall("gfxui", "clear", 1).expect("gfxui resolves");
|
||||||
|
assert_eq!(gfxui.id, 0x1201);
|
||||||
|
assert_eq!(gfxui.meta.caps, caps::GFXUI);
|
||||||
|
|
||||||
|
assert!(resolve_syscall("gfx", "clear", 1).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn declared_resolver_returns_expected_id_for_known_identity() {
|
fn declared_resolver_returns_expected_id_for_known_identity() {
|
||||||
let declared = [prometeu_bytecode::SyscallDecl {
|
let declared = [prometeu_bytecode::SyscallDecl {
|
||||||
module: "gfx".into(),
|
module: "gfx2d".into(),
|
||||||
name: "clear".into(),
|
name: "clear".into(),
|
||||||
version: 1,
|
version: 1,
|
||||||
arg_slots: 1,
|
arg_slots: 1,
|
||||||
@@ -106,7 +145,7 @@ fn declared_resolver_returns_expected_id_for_known_identity() {
|
|||||||
}];
|
}];
|
||||||
|
|
||||||
let ok =
|
let ok =
|
||||||
resolve_declared_program_syscalls(&declared, caps::GFX).expect("must resolve with ABI");
|
resolve_declared_program_syscalls(&declared, caps::GFX2D).expect("must resolve with ABI");
|
||||||
assert_eq!(ok.len(), 1);
|
assert_eq!(ok.len(), 1);
|
||||||
assert_eq!(ok[0].id, 0x1001);
|
assert_eq!(ok[0].id, 0x1001);
|
||||||
}
|
}
|
||||||
@@ -114,18 +153,18 @@ fn declared_resolver_returns_expected_id_for_known_identity() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn declared_resolver_rejects_unknown_identity() {
|
fn declared_resolver_rejects_unknown_identity() {
|
||||||
let declared = [prometeu_bytecode::SyscallDecl {
|
let declared = [prometeu_bytecode::SyscallDecl {
|
||||||
module: "gfx".into(),
|
module: "gfx2d".into(),
|
||||||
name: "nonexistent".into(),
|
name: "nonexistent".into(),
|
||||||
version: 1,
|
version: 1,
|
||||||
arg_slots: 1,
|
arg_slots: 1,
|
||||||
ret_slots: 0,
|
ret_slots: 0,
|
||||||
}];
|
}];
|
||||||
|
|
||||||
let err = resolve_declared_program_syscalls(&declared, caps::GFX).unwrap_err();
|
let err = resolve_declared_program_syscalls(&declared, caps::GFX2D).unwrap_err();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
err,
|
err,
|
||||||
DeclaredLoadError::UnknownSyscall {
|
DeclaredLoadError::UnknownSyscall {
|
||||||
module: "gfx".into(),
|
module: "gfx2d".into(),
|
||||||
name: "nonexistent".into(),
|
name: "nonexistent".into(),
|
||||||
version: 1,
|
version: 1,
|
||||||
}
|
}
|
||||||
@@ -135,7 +174,7 @@ fn declared_resolver_rejects_unknown_identity() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn declared_resolver_rejects_missing_capability() {
|
fn declared_resolver_rejects_missing_capability() {
|
||||||
let declared = [prometeu_bytecode::SyscallDecl {
|
let declared = [prometeu_bytecode::SyscallDecl {
|
||||||
module: "gfx".into(),
|
module: "gfx2d".into(),
|
||||||
name: "clear".into(),
|
name: "clear".into(),
|
||||||
version: 1,
|
version: 1,
|
||||||
arg_slots: 1,
|
arg_slots: 1,
|
||||||
@@ -146,9 +185,9 @@ fn declared_resolver_rejects_missing_capability() {
|
|||||||
assert_eq!(
|
assert_eq!(
|
||||||
err,
|
err,
|
||||||
DeclaredLoadError::MissingCapability {
|
DeclaredLoadError::MissingCapability {
|
||||||
required: caps::GFX,
|
required: caps::GFX2D,
|
||||||
provided: caps::NONE,
|
provided: caps::NONE,
|
||||||
module: "gfx".into(),
|
module: "gfx2d".into(),
|
||||||
name: "clear".into(),
|
name: "clear".into(),
|
||||||
version: 1,
|
version: 1,
|
||||||
}
|
}
|
||||||
@@ -158,18 +197,18 @@ fn declared_resolver_rejects_missing_capability() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn declared_resolver_rejects_abi_mismatch() {
|
fn declared_resolver_rejects_abi_mismatch() {
|
||||||
let declared = [prometeu_bytecode::SyscallDecl {
|
let declared = [prometeu_bytecode::SyscallDecl {
|
||||||
module: "gfx".into(),
|
module: "gfx2d".into(),
|
||||||
name: "draw_line".into(),
|
name: "draw_line".into(),
|
||||||
version: 1,
|
version: 1,
|
||||||
arg_slots: 4,
|
arg_slots: 4,
|
||||||
ret_slots: 0,
|
ret_slots: 0,
|
||||||
}];
|
}];
|
||||||
|
|
||||||
let err = resolve_declared_program_syscalls(&declared, caps::GFX).unwrap_err();
|
let err = resolve_declared_program_syscalls(&declared, caps::GFX2D).unwrap_err();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
err,
|
err,
|
||||||
DeclaredLoadError::AbiMismatch {
|
DeclaredLoadError::AbiMismatch {
|
||||||
module: "gfx".into(),
|
module: "gfx2d".into(),
|
||||||
name: "draw_line".into(),
|
name: "draw_line".into(),
|
||||||
version: 1,
|
version: 1,
|
||||||
declared_arg_slots: 4,
|
declared_arg_slots: 4,
|
||||||
@@ -210,10 +249,6 @@ fn status_first_syscall_signatures_are_pinned() {
|
|||||||
assert_eq!(draw_text.arg_slots, 4);
|
assert_eq!(draw_text.arg_slots, 4);
|
||||||
assert_eq!(draw_text.ret_slots, 0);
|
assert_eq!(draw_text.ret_slots, 0);
|
||||||
|
|
||||||
let clear_565 = meta_for(Syscall::GfxClear565);
|
|
||||||
assert_eq!(clear_565.arg_slots, 1);
|
|
||||||
assert_eq!(clear_565.ret_slots, 0);
|
|
||||||
|
|
||||||
let bind_scene = meta_for(Syscall::ComposerBindScene);
|
let bind_scene = meta_for(Syscall::ComposerBindScene);
|
||||||
assert_eq!(bind_scene.arg_slots, 1);
|
assert_eq!(bind_scene.arg_slots, 1);
|
||||||
assert_eq!(bind_scene.ret_slots, 1);
|
assert_eq!(bind_scene.ret_slots, 1);
|
||||||
@@ -250,6 +285,30 @@ fn status_first_syscall_signatures_are_pinned() {
|
|||||||
assert_eq!(asset_cancel.arg_slots, 1);
|
assert_eq!(asset_cancel.arg_slots, 1);
|
||||||
assert_eq!(asset_cancel.ret_slots, 1);
|
assert_eq!(asset_cancel.ret_slots, 1);
|
||||||
|
|
||||||
|
let asset_backlog_info = meta_for(Syscall::AssetBacklogInfo);
|
||||||
|
assert_eq!(asset_backlog_info.arg_slots, 0);
|
||||||
|
assert_eq!(asset_backlog_info.ret_slots, 7);
|
||||||
|
|
||||||
|
let asset_backlog_position = meta_for(Syscall::AssetBacklogPosition);
|
||||||
|
assert_eq!(asset_backlog_position.arg_slots, 1);
|
||||||
|
assert_eq!(asset_backlog_position.ret_slots, 4);
|
||||||
|
|
||||||
|
let asset_backlog_move = meta_for(Syscall::AssetBacklogMove);
|
||||||
|
assert_eq!(asset_backlog_move.arg_slots, 2);
|
||||||
|
assert_eq!(asset_backlog_move.ret_slots, 1);
|
||||||
|
|
||||||
|
let asset_backlog_promote = meta_for(Syscall::AssetBacklogPromote);
|
||||||
|
assert_eq!(asset_backlog_promote.arg_slots, 1);
|
||||||
|
assert_eq!(asset_backlog_promote.ret_slots, 1);
|
||||||
|
|
||||||
|
let asset_backlog_demote = meta_for(Syscall::AssetBacklogDemote);
|
||||||
|
assert_eq!(asset_backlog_demote.arg_slots, 1);
|
||||||
|
assert_eq!(asset_backlog_demote.ret_slots, 1);
|
||||||
|
|
||||||
|
let asset_target_status = meta_for(Syscall::AssetTargetStatus);
|
||||||
|
assert_eq!(asset_target_status.arg_slots, 2);
|
||||||
|
assert_eq!(asset_target_status.ret_slots, 6);
|
||||||
|
|
||||||
let bank_info = meta_for(Syscall::BankInfo);
|
let bank_info = meta_for(Syscall::BankInfo);
|
||||||
assert_eq!(bank_info.arg_slots, 1);
|
assert_eq!(bank_info.arg_slots, 1);
|
||||||
assert_eq!(bank_info.ret_slots, 2);
|
assert_eq!(bank_info.ret_slots, 2);
|
||||||
@@ -261,10 +320,7 @@ fn resolver_rejects_removed_bank_slot_info_identity() {
|
|||||||
|
|
||||||
let requested = [SyscallIdentity { module: "bank", name: "slot_info", version: 1 }];
|
let requested = [SyscallIdentity { module: "bank", name: "slot_info", version: 1 }];
|
||||||
let err = resolve_program_syscalls(&requested, caps::ALL).unwrap_err();
|
let err = resolve_program_syscalls(&requested, caps::ALL).unwrap_err();
|
||||||
assert_eq!(
|
assert_eq!(err, LoadError::UnknownSyscall { module: "bank", name: "slot_info", version: 1 });
|
||||||
err,
|
|
||||||
LoadError::UnknownSyscall { module: "bank".into(), name: "slot_info".into(), version: 1 }
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -390,7 +446,7 @@ fn declared_resolver_accepts_mixed_status_first_surface_as_a_single_module() {
|
|||||||
];
|
];
|
||||||
|
|
||||||
let resolved =
|
let resolved =
|
||||||
resolve_declared_program_syscalls(&declared, caps::GFX | caps::AUDIO | caps::ASSET)
|
resolve_declared_program_syscalls(&declared, caps::COMPOSER | caps::AUDIO | caps::ASSET)
|
||||||
.expect("mixed status-first surface must resolve together");
|
.expect("mixed status-first surface must resolve together");
|
||||||
|
|
||||||
assert_eq!(resolved.len(), declared.len());
|
assert_eq!(resolved.len(), declared.len());
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
use crate::log::{LogLevel, LogService, LogSource};
|
use crate::log::{LogLevel, LogService, LogSource};
|
||||||
|
use crate::render_worker::RenderWorkerTelemetry;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::sync::atomic::{AtomicU32, AtomicU64, AtomicUsize, Ordering};
|
use std::sync::atomic::{AtomicU32, AtomicU64, AtomicUsize, Ordering};
|
||||||
|
|
||||||
@@ -29,6 +30,54 @@ pub struct TelemetryFrame {
|
|||||||
|
|
||||||
// Log Pressure from the last completed logical frame
|
// Log Pressure from the last completed logical frame
|
||||||
pub logs_count: u32,
|
pub logs_count: u32,
|
||||||
|
|
||||||
|
// Render handoff/presentation telemetry
|
||||||
|
pub produced_submissions: u64,
|
||||||
|
pub replaced_before_consume: u64,
|
||||||
|
pub consumed_submissions: u64,
|
||||||
|
pub published_frames: u64,
|
||||||
|
pub presented_frames: u64,
|
||||||
|
pub repeated_presents: u64,
|
||||||
|
pub render_errors: u64,
|
||||||
|
pub publish_errors: u64,
|
||||||
|
pub present_errors: u64,
|
||||||
|
pub stale_epoch_discards: u64,
|
||||||
|
pub shutdown_discards: u64,
|
||||||
|
pub shutdown_timeouts: u64,
|
||||||
|
pub worker_panics: u64,
|
||||||
|
pub last_produced_frame_id: u64,
|
||||||
|
pub last_consumed_frame_id: u64,
|
||||||
|
pub last_published_frame_id: u64,
|
||||||
|
pub last_presented_frame_id: u64,
|
||||||
|
pub last_dropped_frame_id: u64,
|
||||||
|
pub last_error_frame_id: u64,
|
||||||
|
pub active_render_epoch: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TelemetryFrame {
|
||||||
|
pub fn render_worker_telemetry(&self) -> RenderWorkerTelemetry {
|
||||||
|
RenderWorkerTelemetry {
|
||||||
|
produced_submissions: self.produced_submissions,
|
||||||
|
replaced_before_consume: self.replaced_before_consume,
|
||||||
|
consumed_submissions: self.consumed_submissions,
|
||||||
|
published_frames: self.published_frames,
|
||||||
|
presented_frames: self.presented_frames,
|
||||||
|
repeated_frames: self.repeated_presents,
|
||||||
|
stale_submission_discards: self.stale_epoch_discards,
|
||||||
|
render_failures: self.render_errors,
|
||||||
|
publish_failures: self.publish_errors,
|
||||||
|
present_failures: self.present_errors,
|
||||||
|
shutdown_timeouts: self.shutdown_timeouts,
|
||||||
|
worker_panics: self.worker_panics,
|
||||||
|
last_produced_frame_id: self.last_produced_frame_id,
|
||||||
|
last_consumed_frame_id: self.last_consumed_frame_id,
|
||||||
|
last_published_frame_id: self.last_published_frame_id,
|
||||||
|
last_presented_frame_id: self.last_presented_frame_id,
|
||||||
|
last_dropped_frame_id: self.last_dropped_frame_id,
|
||||||
|
last_error_frame_id: self.last_error_frame_id,
|
||||||
|
active_render_epoch: self.active_render_epoch,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Thread-safe, atomic telemetry storage for real-time monitoring by the host.
|
/// Thread-safe, atomic telemetry storage for real-time monitoring by the host.
|
||||||
@@ -62,6 +111,28 @@ pub struct AtomicTelemetry {
|
|||||||
pub current_logs_count: Arc<AtomicU32>,
|
pub current_logs_count: Arc<AtomicU32>,
|
||||||
// Persisted log count from the last completed logical frame
|
// Persisted log count from the last completed logical frame
|
||||||
pub logs_count: AtomicU32,
|
pub logs_count: AtomicU32,
|
||||||
|
|
||||||
|
// Render handoff/presentation telemetry
|
||||||
|
pub produced_submissions: AtomicU64,
|
||||||
|
pub replaced_before_consume: AtomicU64,
|
||||||
|
pub consumed_submissions: AtomicU64,
|
||||||
|
pub published_frames: AtomicU64,
|
||||||
|
pub presented_frames: AtomicU64,
|
||||||
|
pub repeated_presents: AtomicU64,
|
||||||
|
pub render_errors: AtomicU64,
|
||||||
|
pub publish_errors: AtomicU64,
|
||||||
|
pub present_errors: AtomicU64,
|
||||||
|
pub stale_epoch_discards: AtomicU64,
|
||||||
|
pub shutdown_discards: AtomicU64,
|
||||||
|
pub shutdown_timeouts: AtomicU64,
|
||||||
|
pub worker_panics: AtomicU64,
|
||||||
|
pub last_produced_frame_id: AtomicU64,
|
||||||
|
pub last_consumed_frame_id: AtomicU64,
|
||||||
|
pub last_published_frame_id: AtomicU64,
|
||||||
|
pub last_presented_frame_id: AtomicU64,
|
||||||
|
pub last_dropped_frame_id: AtomicU64,
|
||||||
|
pub last_error_frame_id: AtomicU64,
|
||||||
|
pub active_render_epoch: AtomicU64,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AtomicTelemetry {
|
impl AtomicTelemetry {
|
||||||
@@ -91,6 +162,26 @@ impl AtomicTelemetry {
|
|||||||
vm_string_materializations: self.vm_string_materializations.load(Ordering::Relaxed),
|
vm_string_materializations: self.vm_string_materializations.load(Ordering::Relaxed),
|
||||||
logs_count: self.logs_count.load(Ordering::Relaxed),
|
logs_count: self.logs_count.load(Ordering::Relaxed),
|
||||||
vm_steps: self.vm_steps.load(Ordering::Relaxed),
|
vm_steps: self.vm_steps.load(Ordering::Relaxed),
|
||||||
|
produced_submissions: self.produced_submissions.load(Ordering::Relaxed),
|
||||||
|
replaced_before_consume: self.replaced_before_consume.load(Ordering::Relaxed),
|
||||||
|
consumed_submissions: self.consumed_submissions.load(Ordering::Relaxed),
|
||||||
|
published_frames: self.published_frames.load(Ordering::Relaxed),
|
||||||
|
presented_frames: self.presented_frames.load(Ordering::Relaxed),
|
||||||
|
repeated_presents: self.repeated_presents.load(Ordering::Relaxed),
|
||||||
|
render_errors: self.render_errors.load(Ordering::Relaxed),
|
||||||
|
publish_errors: self.publish_errors.load(Ordering::Relaxed),
|
||||||
|
present_errors: self.present_errors.load(Ordering::Relaxed),
|
||||||
|
stale_epoch_discards: self.stale_epoch_discards.load(Ordering::Relaxed),
|
||||||
|
shutdown_discards: self.shutdown_discards.load(Ordering::Relaxed),
|
||||||
|
shutdown_timeouts: self.shutdown_timeouts.load(Ordering::Relaxed),
|
||||||
|
worker_panics: self.worker_panics.load(Ordering::Relaxed),
|
||||||
|
last_produced_frame_id: self.last_produced_frame_id.load(Ordering::Relaxed),
|
||||||
|
last_consumed_frame_id: self.last_consumed_frame_id.load(Ordering::Relaxed),
|
||||||
|
last_published_frame_id: self.last_published_frame_id.load(Ordering::Relaxed),
|
||||||
|
last_presented_frame_id: self.last_presented_frame_id.load(Ordering::Relaxed),
|
||||||
|
last_dropped_frame_id: self.last_dropped_frame_id.load(Ordering::Relaxed),
|
||||||
|
last_error_frame_id: self.last_error_frame_id.load(Ordering::Relaxed),
|
||||||
|
active_render_epoch: self.active_render_epoch.load(Ordering::Relaxed),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -113,6 +204,26 @@ impl AtomicTelemetry {
|
|||||||
self.vm_steps.store(0, Ordering::Relaxed);
|
self.vm_steps.store(0, Ordering::Relaxed);
|
||||||
self.logs_count.store(0, Ordering::Relaxed);
|
self.logs_count.store(0, Ordering::Relaxed);
|
||||||
self.current_logs_count.store(0, Ordering::Relaxed);
|
self.current_logs_count.store(0, Ordering::Relaxed);
|
||||||
|
self.produced_submissions.store(0, Ordering::Relaxed);
|
||||||
|
self.replaced_before_consume.store(0, Ordering::Relaxed);
|
||||||
|
self.consumed_submissions.store(0, Ordering::Relaxed);
|
||||||
|
self.published_frames.store(0, Ordering::Relaxed);
|
||||||
|
self.presented_frames.store(0, Ordering::Relaxed);
|
||||||
|
self.repeated_presents.store(0, Ordering::Relaxed);
|
||||||
|
self.render_errors.store(0, Ordering::Relaxed);
|
||||||
|
self.publish_errors.store(0, Ordering::Relaxed);
|
||||||
|
self.present_errors.store(0, Ordering::Relaxed);
|
||||||
|
self.stale_epoch_discards.store(0, Ordering::Relaxed);
|
||||||
|
self.shutdown_discards.store(0, Ordering::Relaxed);
|
||||||
|
self.shutdown_timeouts.store(0, Ordering::Relaxed);
|
||||||
|
self.worker_panics.store(0, Ordering::Relaxed);
|
||||||
|
self.last_produced_frame_id.store(0, Ordering::Relaxed);
|
||||||
|
self.last_consumed_frame_id.store(0, Ordering::Relaxed);
|
||||||
|
self.last_published_frame_id.store(0, Ordering::Relaxed);
|
||||||
|
self.last_presented_frame_id.store(0, Ordering::Relaxed);
|
||||||
|
self.last_dropped_frame_id.store(0, Ordering::Relaxed);
|
||||||
|
self.last_error_frame_id.store(0, Ordering::Relaxed);
|
||||||
|
self.active_render_epoch.store(0, Ordering::Relaxed);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -294,11 +405,13 @@ mod tests {
|
|||||||
};
|
};
|
||||||
let cert = Certifier::new(config);
|
let cert = Certifier::new(config);
|
||||||
|
|
||||||
let mut tel = TelemetryFrame::default();
|
let tel = TelemetryFrame {
|
||||||
tel.cycles_used = 150;
|
cycles_used: 150,
|
||||||
tel.syscalls = 10;
|
syscalls: 10,
|
||||||
tel.host_cpu_time_us = 500;
|
host_cpu_time_us: 500,
|
||||||
tel.glyph_slots_used = 2;
|
glyph_slots_used: 2,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
let violations = cert.evaluate(&tel, &mut ls, 1000);
|
let violations = cert.evaluate(&tel, &mut ls, 1000);
|
||||||
assert_eq!(violations, 3);
|
assert_eq!(violations, 3);
|
||||||
@@ -334,4 +447,51 @@ mod tests {
|
|||||||
assert_eq!(snapshot.vm_heap_allocations, 2);
|
assert_eq!(snapshot.vm_heap_allocations, 2);
|
||||||
assert_eq!(snapshot.vm_string_materializations, 5);
|
assert_eq!(snapshot.vm_string_materializations, 5);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn snapshot_maps_render_worker_telemetry() {
|
||||||
|
let current = Arc::new(AtomicU32::new(0));
|
||||||
|
let tel = AtomicTelemetry::new(current);
|
||||||
|
tel.produced_submissions.store(2, Ordering::Relaxed);
|
||||||
|
tel.replaced_before_consume.store(1, Ordering::Relaxed);
|
||||||
|
tel.consumed_submissions.store(1, Ordering::Relaxed);
|
||||||
|
tel.published_frames.store(1, Ordering::Relaxed);
|
||||||
|
tel.presented_frames.store(1, Ordering::Relaxed);
|
||||||
|
tel.repeated_presents.store(3, Ordering::Relaxed);
|
||||||
|
tel.render_errors.store(4, Ordering::Relaxed);
|
||||||
|
tel.publish_errors.store(5, Ordering::Relaxed);
|
||||||
|
tel.present_errors.store(6, Ordering::Relaxed);
|
||||||
|
tel.stale_epoch_discards.store(7, Ordering::Relaxed);
|
||||||
|
tel.shutdown_timeouts.store(8, Ordering::Relaxed);
|
||||||
|
tel.worker_panics.store(9, Ordering::Relaxed);
|
||||||
|
tel.last_produced_frame_id.store(10, Ordering::Relaxed);
|
||||||
|
tel.last_consumed_frame_id.store(11, Ordering::Relaxed);
|
||||||
|
tel.last_published_frame_id.store(12, Ordering::Relaxed);
|
||||||
|
tel.last_presented_frame_id.store(13, Ordering::Relaxed);
|
||||||
|
tel.last_dropped_frame_id.store(14, Ordering::Relaxed);
|
||||||
|
tel.last_error_frame_id.store(15, Ordering::Relaxed);
|
||||||
|
tel.active_render_epoch.store(16, Ordering::Relaxed);
|
||||||
|
|
||||||
|
let worker = tel.snapshot().render_worker_telemetry();
|
||||||
|
|
||||||
|
assert_eq!(worker.produced_submissions, 2);
|
||||||
|
assert_eq!(worker.replaced_before_consume, 1);
|
||||||
|
assert_eq!(worker.consumed_submissions, 1);
|
||||||
|
assert_eq!(worker.published_frames, 1);
|
||||||
|
assert_eq!(worker.presented_frames, 1);
|
||||||
|
assert_eq!(worker.repeated_frames, 3);
|
||||||
|
assert_eq!(worker.render_failures, 4);
|
||||||
|
assert_eq!(worker.publish_failures, 5);
|
||||||
|
assert_eq!(worker.present_failures, 6);
|
||||||
|
assert_eq!(worker.stale_submission_discards, 7);
|
||||||
|
assert_eq!(worker.shutdown_timeouts, 8);
|
||||||
|
assert_eq!(worker.worker_panics, 9);
|
||||||
|
assert_eq!(worker.last_produced_frame_id, 10);
|
||||||
|
assert_eq!(worker.last_consumed_frame_id, 11);
|
||||||
|
assert_eq!(worker.last_published_frame_id, 12);
|
||||||
|
assert_eq!(worker.last_presented_frame_id, 13);
|
||||||
|
assert_eq!(worker.last_dropped_frame_id, 14);
|
||||||
|
assert_eq!(worker.last_error_frame_id, 15);
|
||||||
|
assert_eq!(worker.active_render_epoch, 16);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,36 @@
|
|||||||
mod crash_report;
|
mod crash_report;
|
||||||
|
mod os;
|
||||||
mod programs;
|
mod programs;
|
||||||
mod services;
|
mod services;
|
||||||
mod virtual_machine_runtime;
|
|
||||||
|
|
||||||
pub use crash_report::CrashReport;
|
pub use crash_report::CrashReport;
|
||||||
pub use programs::PrometeuHub;
|
pub use os::{
|
||||||
|
DEFAULT_GAME_PAUSE_BUDGET_TICKS, GameLifecycleEvent, GameLifecycleEventKind, LifecycleError,
|
||||||
|
LifecycleOperation, SessionError, SystemOS,
|
||||||
|
};
|
||||||
|
pub use programs::{
|
||||||
|
HUB_SUSPENDED_GAME_KILL_CONTROL, NativeShellApp, PrometeuHub, SystemProfileAction,
|
||||||
|
SystemProfileUpdate,
|
||||||
|
};
|
||||||
|
pub use prometeu_hal::{RenderWorkerBackend, RenderWorkerFrameSink};
|
||||||
|
pub use services::async_work::{
|
||||||
|
AsyncWorkActiveJob, AsyncWorkCancelToken, AsyncWorkJobContext, AsyncWorkJobId,
|
||||||
|
AsyncWorkJobKind, AsyncWorkJobOutcome, AsyncWorkLane, AsyncWorkLaneConfig,
|
||||||
|
AsyncWorkLaneController, AsyncWorkLaneError, AsyncWorkLaneTelemetry, AsyncWorkPriority,
|
||||||
|
};
|
||||||
|
pub use services::foreground::{
|
||||||
|
ForegroundOwner, ForegroundStack, ForegroundStackError, ResidentGame, ResidentGameState,
|
||||||
|
};
|
||||||
pub use services::fs;
|
pub use services::fs;
|
||||||
pub use virtual_machine_runtime::VirtualMachineRuntime;
|
pub use services::game_library::{
|
||||||
|
GameLibrary, GameLibraryDiagnostic, GameLibraryEntry, GameSwitchTarget, discover_games_root,
|
||||||
|
};
|
||||||
|
pub use services::memcard::MemcardAsyncLaneOperation;
|
||||||
|
pub use services::process;
|
||||||
|
pub use services::task;
|
||||||
|
pub use services::vm_runtime::{
|
||||||
|
LatestRenderFrameStore, RenderWorkerConfig, RenderWorkerController, RenderWorkerHandoff,
|
||||||
|
RenderWorkerHandoffWait, RenderWorkerOwnership, VirtualMachineRuntime,
|
||||||
|
};
|
||||||
|
pub use services::vm_session;
|
||||||
|
pub use services::windows;
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
use crate::fs::{FsBackend, FsState};
|
||||||
|
use crate::os::SystemOS;
|
||||||
|
|
||||||
|
pub struct FsFacade<'a> {
|
||||||
|
pub(in crate::os) os: &'a mut SystemOS,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> FsFacade<'a> {
|
||||||
|
pub fn needs_mount(&self) -> bool {
|
||||||
|
matches!(self.os.fs_state, FsState::Unmounted | FsState::Error(_))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mount(&mut self, backend: Box<dyn FsBackend>) {
|
||||||
|
self.os.vm_runtime.mount_fs(
|
||||||
|
&mut self.os.log_service,
|
||||||
|
&mut self.os.fs,
|
||||||
|
&mut self.os.fs_state,
|
||||||
|
backend,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn unmount(&mut self) {
|
||||||
|
self.os.fs.unmount();
|
||||||
|
self.os.fs_state = FsState::Unmounted;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,299 @@
|
|||||||
|
use crate::CrashReport;
|
||||||
|
use crate::os::SystemOS;
|
||||||
|
use crate::os::{
|
||||||
|
DEFAULT_GAME_PAUSE_BUDGET_TICKS, GameLifecycleEvent, GameLifecycleEventKind, LifecycleError,
|
||||||
|
LifecycleOperation,
|
||||||
|
};
|
||||||
|
use crate::process::{Process, ProcessId, ProcessKind, ProcessState};
|
||||||
|
use crate::services::foreground::{
|
||||||
|
ForegroundOwner, ForegroundStackError, ResidentGame, ResidentGameState,
|
||||||
|
};
|
||||||
|
use crate::task::{TaskId, TaskKind, TaskState};
|
||||||
|
|
||||||
|
pub struct LifecycleFacade<'a> {
|
||||||
|
pub(in crate::os) os: &'a mut SystemOS,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> LifecycleFacade<'a> {
|
||||||
|
pub fn task_state(&self, task_id: TaskId) -> Option<TaskState> {
|
||||||
|
self.os.task_manager.get(task_id).map(|task| task.state)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn process_state_for_task(&self, task_id: TaskId) -> Result<ProcessState, LifecycleError> {
|
||||||
|
process_for_task(self.os, task_id).map(|process| process.state)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn process_kind_for_task(&self, task_id: TaskId) -> Result<ProcessKind, LifecycleError> {
|
||||||
|
process_for_task(self.os, task_id).map(|process| process.kind)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_foreground_task(&mut self, task_id: TaskId) -> Result<(), LifecycleError> {
|
||||||
|
match task_kind_for_task(self.os, task_id)? {
|
||||||
|
TaskKind::Game => self.set_game_foreground_task(task_id),
|
||||||
|
TaskKind::Shell => self.set_shell_foreground_task(task_id),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_game_foreground_task(&mut self, task_id: TaskId) -> Result<(), LifecycleError> {
|
||||||
|
let process_id = process_id_for_task(self.os, task_id)?;
|
||||||
|
|
||||||
|
if task_kind_for_task(self.os, task_id)? != TaskKind::Game {
|
||||||
|
return Err(LifecycleError::InvalidTransition {
|
||||||
|
task_id,
|
||||||
|
from: self.task_state(task_id).unwrap_or(TaskState::Closed),
|
||||||
|
operation: LifecycleOperation::SetForeground,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
self.os.foreground_stack.set_game_foreground(task_id).map_err(map_foreground_error)?;
|
||||||
|
self.os.task_manager.set_foreground(task_id);
|
||||||
|
self.os.process_manager.mark_running(process_id);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_shell_foreground_task(&mut self, task_id: TaskId) -> Result<(), LifecycleError> {
|
||||||
|
let process_id = process_id_for_task(self.os, task_id)?;
|
||||||
|
|
||||||
|
if task_kind_for_task(self.os, task_id)? != TaskKind::Shell {
|
||||||
|
return Err(LifecycleError::InvalidTransition {
|
||||||
|
task_id,
|
||||||
|
from: self.task_state(task_id).unwrap_or(TaskState::Closed),
|
||||||
|
operation: LifecycleOperation::SetForeground,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(game_task_id) = self.os.foreground_stack.resident_game_task()
|
||||||
|
&& game_task_id != task_id
|
||||||
|
&& self.task_state(game_task_id) != Some(TaskState::Suspended)
|
||||||
|
{
|
||||||
|
let game_process_id = process_id_for_task(self.os, game_task_id)?;
|
||||||
|
self.os.task_manager.mark_suspended(game_task_id);
|
||||||
|
self.os.process_manager.mark_suspended(game_process_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
self.os.foreground_stack.set_shell_foreground(task_id).map_err(map_foreground_error)?;
|
||||||
|
self.os.task_manager.set_foreground(task_id);
|
||||||
|
self.os.process_manager.mark_running(process_id);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn foreground_owner(&self) -> ForegroundOwner {
|
||||||
|
self.os.foreground_stack.owner()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn resident_game(&self) -> Option<ResidentGame> {
|
||||||
|
self.os.foreground_stack.resident_game()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn resident_game_task(&self) -> Option<TaskId> {
|
||||||
|
self.os.foreground_stack.resident_game_task()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn request_home_from_game(&mut self, task_id: TaskId) -> Result<(), LifecycleError> {
|
||||||
|
let _process_id = process_id_for_task(self.os, task_id)?;
|
||||||
|
let previous = self.os.foreground_stack.resident_game();
|
||||||
|
|
||||||
|
self.os
|
||||||
|
.foreground_stack
|
||||||
|
.request_home_from_game(task_id, DEFAULT_GAME_PAUSE_BUDGET_TICKS)
|
||||||
|
.map_err(map_foreground_error)?;
|
||||||
|
|
||||||
|
if !matches!(
|
||||||
|
previous.map(|game| game.state),
|
||||||
|
Some(ResidentGameState::PauseRequested { .. } | ResidentGameState::PausedSuspended)
|
||||||
|
) {
|
||||||
|
self.os
|
||||||
|
.game_lifecycle_events
|
||||||
|
.push(GameLifecycleEvent { task_id, kind: GameLifecycleEventKind::Pause });
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn advance_game_pause_budget(&mut self, task_id: TaskId) -> Result<bool, LifecycleError> {
|
||||||
|
let expired =
|
||||||
|
self.os.foreground_stack.advance_pause_budget(task_id).map_err(map_foreground_error)?;
|
||||||
|
|
||||||
|
if expired {
|
||||||
|
let process_id = process_id_for_task(self.os, task_id)?;
|
||||||
|
self.os.task_manager.mark_suspended(task_id);
|
||||||
|
self.os.process_manager.mark_suspended(process_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(expired)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn pending_game_lifecycle_events(&self) -> &[GameLifecycleEvent] {
|
||||||
|
&self.os.game_lifecycle_events
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn take_game_lifecycle_events(&mut self) -> Vec<GameLifecycleEvent> {
|
||||||
|
std::mem::take(&mut self.os.game_lifecycle_events)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn return_to_hub(&mut self) {
|
||||||
|
self.os.foreground_stack.return_to_hub();
|
||||||
|
self.os.task_manager.clear_foreground();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn suspend_task(&mut self, task_id: TaskId) -> Result<(), LifecycleError> {
|
||||||
|
let process_id = process_id_for_task(self.os, task_id)?;
|
||||||
|
|
||||||
|
self.os.task_manager.mark_suspended(task_id);
|
||||||
|
self.os.process_manager.mark_suspended(process_id);
|
||||||
|
match self.os.foreground_stack.owner() {
|
||||||
|
ForegroundOwner::Game(owner) if owner == task_id => {
|
||||||
|
self.os
|
||||||
|
.foreground_stack
|
||||||
|
.request_home_from_game(task_id, DEFAULT_GAME_PAUSE_BUDGET_TICKS)
|
||||||
|
.map_err(map_foreground_error)?;
|
||||||
|
self.os
|
||||||
|
.foreground_stack
|
||||||
|
.advance_pause_budget(task_id)
|
||||||
|
.map_err(map_foreground_error)?;
|
||||||
|
}
|
||||||
|
ForegroundOwner::Shell(owner) if owner == task_id => {
|
||||||
|
self.os.foreground_stack.return_to_hub();
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn resume_task(&mut self, task_id: TaskId) -> Result<(), LifecycleError> {
|
||||||
|
let task =
|
||||||
|
self.os.task_manager.get(task_id).ok_or(LifecycleError::TaskNotFound(task_id))?;
|
||||||
|
|
||||||
|
if task.state != TaskState::Suspended {
|
||||||
|
return Err(LifecycleError::InvalidTransition {
|
||||||
|
task_id,
|
||||||
|
from: task.state,
|
||||||
|
operation: LifecycleOperation::Resume,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let process_id = process_id_for_task(self.os, task_id)?;
|
||||||
|
|
||||||
|
match task_kind_for_task(self.os, task_id)? {
|
||||||
|
TaskKind::Game => {
|
||||||
|
self.os
|
||||||
|
.foreground_stack
|
||||||
|
.request_resume_game(task_id)
|
||||||
|
.map_err(map_foreground_error)?;
|
||||||
|
self.os.task_manager.set_foreground(task_id);
|
||||||
|
self.os.process_manager.mark_running(process_id);
|
||||||
|
self.os.game_lifecycle_events.push(GameLifecycleEvent {
|
||||||
|
task_id,
|
||||||
|
kind: GameLifecycleEventKind::ResumeForeground,
|
||||||
|
});
|
||||||
|
self.os
|
||||||
|
.foreground_stack
|
||||||
|
.complete_resume_game(task_id)
|
||||||
|
.map_err(map_foreground_error)?;
|
||||||
|
}
|
||||||
|
TaskKind::Shell => {
|
||||||
|
self.os
|
||||||
|
.foreground_stack
|
||||||
|
.set_shell_foreground(task_id)
|
||||||
|
.map_err(map_foreground_error)?;
|
||||||
|
self.os.task_manager.set_foreground(task_id);
|
||||||
|
self.os.process_manager.mark_running(process_id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn close_task(&mut self, task_id: TaskId) -> Result<(), LifecycleError> {
|
||||||
|
let process_id = process_id_for_task(self.os, task_id)?;
|
||||||
|
|
||||||
|
self.os.task_manager.close_task(task_id);
|
||||||
|
self.os.process_manager.mark_stopped(process_id);
|
||||||
|
if self.os.foreground_stack.resident_game_task() == Some(task_id) {
|
||||||
|
self.os.foreground_stack.clear_resident_game(task_id);
|
||||||
|
} else if matches!(self.os.foreground_stack.owner(), ForegroundOwner::Shell(owner) if owner == task_id)
|
||||||
|
{
|
||||||
|
self.os.foreground_stack.return_to_hub();
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn terminate_resident_game(&mut self) -> Result<Option<TaskId>, LifecycleError> {
|
||||||
|
let Some(task_id) = self.os.foreground_stack.resident_game_task() else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
|
||||||
|
let process_id = process_id_for_task(self.os, task_id)?;
|
||||||
|
|
||||||
|
self.os.task_manager.close_task(task_id);
|
||||||
|
self.os.process_manager.mark_stopped(process_id);
|
||||||
|
self.os.foreground_stack.clear_resident_game(task_id);
|
||||||
|
self.os.vm_sessions.remove_for_task(task_id);
|
||||||
|
self.os.game_lifecycle_events.retain(|event| event.task_id != task_id);
|
||||||
|
|
||||||
|
if matches!(self.os.foreground_stack.owner(), ForegroundOwner::Game(owner) if owner == task_id)
|
||||||
|
{
|
||||||
|
self.os.foreground_stack.return_to_hub();
|
||||||
|
self.os.task_manager.clear_foreground();
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Some(task_id))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn crash_task(
|
||||||
|
&mut self,
|
||||||
|
task_id: TaskId,
|
||||||
|
_report: Option<&CrashReport>,
|
||||||
|
) -> Result<(), LifecycleError> {
|
||||||
|
let process_id = process_id_for_task(self.os, task_id)?;
|
||||||
|
|
||||||
|
self.os.task_manager.mark_crashed(task_id);
|
||||||
|
self.os.process_manager.mark_crashed(process_id);
|
||||||
|
if self.os.foreground_stack.resident_game_task() == Some(task_id) {
|
||||||
|
self.os.foreground_stack.clear_resident_game(task_id);
|
||||||
|
} else if matches!(self.os.foreground_stack.owner(), ForegroundOwner::Shell(owner) if owner == task_id)
|
||||||
|
{
|
||||||
|
self.os.foreground_stack.return_to_hub();
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn task_kind_for_task(os: &SystemOS, task_id: TaskId) -> Result<TaskKind, LifecycleError> {
|
||||||
|
let task = os.task_manager.get(task_id).ok_or(LifecycleError::TaskNotFound(task_id))?;
|
||||||
|
Ok(task.kind)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn process_id_for_task(os: &SystemOS, task_id: TaskId) -> Result<ProcessId, LifecycleError> {
|
||||||
|
let task = os.task_manager.get(task_id).ok_or(LifecycleError::TaskNotFound(task_id))?;
|
||||||
|
|
||||||
|
if !os.process_manager.contains(task.process_id) {
|
||||||
|
return Err(LifecycleError::ProcessNotFound(task.process_id));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(task.process_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn process_for_task(os: &SystemOS, task_id: TaskId) -> Result<&Process, LifecycleError> {
|
||||||
|
let process_id = process_id_for_task(os, task_id)?;
|
||||||
|
os.process_manager.get(process_id).ok_or(LifecycleError::ProcessNotFound(process_id))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn map_foreground_error(error: ForegroundStackError) -> LifecycleError {
|
||||||
|
match error {
|
||||||
|
ForegroundStackError::ResidentGameAlreadyExists { existing, requested } => {
|
||||||
|
LifecycleError::ResidentGameAlreadyExists { existing, requested }
|
||||||
|
}
|
||||||
|
ForegroundStackError::ForegroundShellAlreadyExists { existing, requested } => {
|
||||||
|
LifecycleError::ForegroundShellAlreadyExists { existing, requested }
|
||||||
|
}
|
||||||
|
ForegroundStackError::TaskIsNotResidentGame(task_id) => {
|
||||||
|
LifecycleError::TaskIsNotResidentGame(task_id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
mod fs;
|
||||||
|
mod lifecycle;
|
||||||
|
mod sessions;
|
||||||
|
mod vm;
|
||||||
|
mod window;
|
||||||
|
|
||||||
|
pub use fs::FsFacade;
|
||||||
|
pub use lifecycle::LifecycleFacade;
|
||||||
|
pub use sessions::{SessionError, SessionsFacade};
|
||||||
|
pub use vm::VmFacade;
|
||||||
|
pub use window::WindowFacade;
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
use crate::CrashReport;
|
||||||
|
use crate::os::LifecycleError;
|
||||||
|
use crate::os::SystemOS;
|
||||||
|
use crate::process::ProcessId;
|
||||||
|
use crate::task::TaskId;
|
||||||
|
use crate::vm_session::{VmSession, VmSessionError};
|
||||||
|
use prometeu_hal::app_mode::AppMode;
|
||||||
|
use prometeu_hal::cartridge::Cartridge;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct LoadedVmCartridge {
|
||||||
|
pub task_id: TaskId,
|
||||||
|
pub app_mode: AppMode,
|
||||||
|
pub reused_existing_session: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum SessionError {
|
||||||
|
Lifecycle(LifecycleError),
|
||||||
|
VmSession(VmSessionError),
|
||||||
|
TaskNotFound(TaskId),
|
||||||
|
ProcessNotFound(ProcessId),
|
||||||
|
MissingVmSession(TaskId),
|
||||||
|
Initialization(CrashReport),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SessionError {
|
||||||
|
pub fn into_crash_report(self, operation: &str) -> CrashReport {
|
||||||
|
match self {
|
||||||
|
Self::Initialization(report) => report,
|
||||||
|
error => {
|
||||||
|
CrashReport::VmPanic { message: format!("{operation} failed: {error:?}"), pc: None }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<LifecycleError> for SessionError {
|
||||||
|
fn from(error: LifecycleError) -> Self {
|
||||||
|
Self::Lifecycle(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<VmSessionError> for SessionError {
|
||||||
|
fn from(error: VmSessionError) -> Self {
|
||||||
|
Self::VmSession(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct SessionsFacade<'a> {
|
||||||
|
pub(in crate::os) os: &'a mut SystemOS,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> SessionsFacade<'a> {
|
||||||
|
#[cfg(test)]
|
||||||
|
pub fn create_vm_game_task(&mut self, app_id: u32, title: impl Into<String>) -> TaskId {
|
||||||
|
self.try_create_vm_game_task(app_id, title)
|
||||||
|
.expect("test/setup VM game creation should succeed")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn try_create_vm_game_task(
|
||||||
|
&mut self,
|
||||||
|
app_id: u32,
|
||||||
|
title: impl Into<String>,
|
||||||
|
) -> Result<TaskId, SessionError> {
|
||||||
|
if let Some(session) = self.os.vm_sessions.resident_game_for_app(app_id) {
|
||||||
|
return Ok(session.task_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
let title = title.into();
|
||||||
|
let process_id = self.os.process_manager.spawn_vm_game(app_id, title.clone());
|
||||||
|
let task_id = self.os.task_manager.create_game_task(process_id, app_id, title);
|
||||||
|
self.os.lifecycle().set_game_foreground_task(task_id)?;
|
||||||
|
self.try_create_vm_session_for_task(task_id)?;
|
||||||
|
|
||||||
|
Ok(task_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
pub fn create_vm_shell_task(&mut self, app_id: u32, title: impl Into<String>) -> TaskId {
|
||||||
|
self.try_create_vm_shell_task(app_id, title)
|
||||||
|
.expect("test/setup VM shell creation should succeed")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn try_create_vm_shell_task(
|
||||||
|
&mut self,
|
||||||
|
app_id: u32,
|
||||||
|
title: impl Into<String>,
|
||||||
|
) -> Result<TaskId, SessionError> {
|
||||||
|
let title = title.into();
|
||||||
|
let process_id = self.os.process_manager.spawn_vm_shell(app_id, title.clone());
|
||||||
|
let task_id = self.os.task_manager.create_shell_task(process_id, app_id, title);
|
||||||
|
self.os.lifecycle().set_shell_foreground_task(task_id)?;
|
||||||
|
self.try_create_vm_session_for_task(task_id)?;
|
||||||
|
|
||||||
|
Ok(task_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
pub fn create_native_shell_task(&mut self, app_id: u32, title: impl Into<String>) -> TaskId {
|
||||||
|
self.try_create_native_shell_task(app_id, title)
|
||||||
|
.expect("test/setup native shell creation should succeed")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn try_create_native_shell_task(
|
||||||
|
&mut self,
|
||||||
|
app_id: u32,
|
||||||
|
title: impl Into<String>,
|
||||||
|
) -> Result<TaskId, SessionError> {
|
||||||
|
let title = title.into();
|
||||||
|
let process_id = self.os.process_manager.spawn_native_shell(app_id, title.clone());
|
||||||
|
let task_id = self.os.task_manager.create_shell_task(process_id, app_id, title);
|
||||||
|
self.os.lifecycle().set_shell_foreground_task(task_id)?;
|
||||||
|
|
||||||
|
Ok(task_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load_vm_cartridge(
|
||||||
|
&mut self,
|
||||||
|
cartridge: &Cartridge,
|
||||||
|
) -> Result<LoadedVmCartridge, SessionError> {
|
||||||
|
let existing_game_task = if cartridge.app_mode == AppMode::Game {
|
||||||
|
self.os
|
||||||
|
.vm_sessions
|
||||||
|
.resident_game_for_app(cartridge.app_id)
|
||||||
|
.map(|session| session.task_id)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
let (task_id, reused_existing_session) = if let Some(task_id) = existing_game_task {
|
||||||
|
(task_id, true)
|
||||||
|
} else if cartridge.app_mode == AppMode::Shell {
|
||||||
|
(self.try_create_vm_shell_task(cartridge.app_id, cartridge.title.clone())?, false)
|
||||||
|
} else {
|
||||||
|
let task_id =
|
||||||
|
self.try_create_vm_game_task(cartridge.app_id, cartridge.title.clone())?;
|
||||||
|
(task_id, false)
|
||||||
|
};
|
||||||
|
|
||||||
|
if !reused_existing_session {
|
||||||
|
self.try_initialize_session_cartridge(task_id, cartridge)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(LoadedVmCartridge { task_id, app_mode: cartridge.app_mode, reused_existing_session })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn vm_session_for_task(&self, task_id: TaskId) -> Option<&VmSession> {
|
||||||
|
self.os.vm_sessions.for_task(task_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn vm_session_for_task_mut(&mut self, task_id: TaskId) -> Option<&mut VmSession> {
|
||||||
|
self.os.vm_sessions.for_task_mut(task_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn resident_game_session_for_app(&self, app_id: u32) -> Option<&VmSession> {
|
||||||
|
self.os.vm_sessions.resident_game_for_app(app_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn vm_session_count(&self) -> usize {
|
||||||
|
self.os.vm_sessions.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clear_vm_sessions(&mut self) {
|
||||||
|
self.os.vm_sessions.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn try_create_vm_session_for_task(&mut self, task_id: TaskId) -> Result<(), SessionError> {
|
||||||
|
let task =
|
||||||
|
self.os.task_manager.get(task_id).ok_or(SessionError::TaskNotFound(task_id))?.clone();
|
||||||
|
let process = self
|
||||||
|
.os
|
||||||
|
.process_manager
|
||||||
|
.get(task.process_id)
|
||||||
|
.ok_or(SessionError::ProcessNotFound(task.process_id))?
|
||||||
|
.clone();
|
||||||
|
|
||||||
|
let cap_config = self.os.vm_runtime.certifier.config;
|
||||||
|
let logs_count = Arc::clone(&self.os.log_service.logs_count);
|
||||||
|
self.os
|
||||||
|
.vm_sessions
|
||||||
|
.create_for_task(&task, &process, "", Some(cap_config), logs_count)
|
||||||
|
.map(|_| ())
|
||||||
|
.map_err(SessionError::from)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn try_initialize_session_cartridge(
|
||||||
|
&mut self,
|
||||||
|
task_id: TaskId,
|
||||||
|
cartridge: &Cartridge,
|
||||||
|
) -> Result<(), SessionError> {
|
||||||
|
let session = self
|
||||||
|
.os
|
||||||
|
.vm_sessions
|
||||||
|
.for_task_mut(task_id)
|
||||||
|
.ok_or(SessionError::MissingVmSession(task_id))?;
|
||||||
|
|
||||||
|
session.app_id = cartridge.app_id;
|
||||||
|
session.title = cartridge.title.clone();
|
||||||
|
session.app_version = cartridge.app_version.clone();
|
||||||
|
session.app_mode = cartridge.app_mode;
|
||||||
|
session.clear_cartridge_service_state();
|
||||||
|
session
|
||||||
|
.runtime
|
||||||
|
.initialize_vm(&mut self.os.log_service, &mut session.vm, cartridge)
|
||||||
|
.map_err(SessionError::Initialization)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,330 @@
|
|||||||
|
use crate::CrashReport;
|
||||||
|
use crate::os::{GameLifecycleEvent, SystemOS};
|
||||||
|
use crate::task::TaskId;
|
||||||
|
use crate::vm_session::VmSession;
|
||||||
|
use crate::{RenderWorkerConfig, RenderWorkerController};
|
||||||
|
use prometeu_bytecode::Value;
|
||||||
|
use prometeu_hal::app_mode::AppMode;
|
||||||
|
use prometeu_hal::telemetry::{CertificationConfig, TelemetryFrame};
|
||||||
|
use prometeu_hal::{
|
||||||
|
FrameId, InputSignals, RenderOwnership, RenderWorkerBackend, RenderWorkerError,
|
||||||
|
RenderWorkerFrameSink, RuntimePlatform,
|
||||||
|
};
|
||||||
|
use std::sync::atomic::Ordering;
|
||||||
|
|
||||||
|
pub struct VmFacade<'a> {
|
||||||
|
pub(in crate::os) os: &'a mut SystemOS,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> VmFacade<'a> {
|
||||||
|
pub fn tick_session(
|
||||||
|
&mut self,
|
||||||
|
task_id: TaskId,
|
||||||
|
signals: &InputSignals,
|
||||||
|
platform: &mut dyn RuntimePlatform,
|
||||||
|
) -> Option<CrashReport> {
|
||||||
|
self.deliver_pending_game_lifecycle_events_to_session(task_id);
|
||||||
|
|
||||||
|
let Some(session) = self.os.vm_sessions.for_task_mut(task_id) else {
|
||||||
|
return Some(CrashReport::VmPanic {
|
||||||
|
message: format!("task {:?} has no VM session", task_id),
|
||||||
|
pc: None,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
session.runtime.tick(
|
||||||
|
&mut self.os.log_service,
|
||||||
|
&mut self.os.fs,
|
||||||
|
&mut session.fs_state,
|
||||||
|
&mut self.os.memcard,
|
||||||
|
&mut session.open_files,
|
||||||
|
&mut session.next_handle,
|
||||||
|
&mut session.vm,
|
||||||
|
signals,
|
||||||
|
platform,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn deliver_pending_game_lifecycle_events_to_session(&mut self, task_id: TaskId) {
|
||||||
|
let Some(session) = self.os.vm_sessions.for_task(task_id) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
if session.runtime.current_cartridge_app_mode != AppMode::Game {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut retained = Vec::new();
|
||||||
|
let mut delivered = Vec::new();
|
||||||
|
|
||||||
|
for event in self.os.game_lifecycle_events.drain(..) {
|
||||||
|
if event.task_id == task_id {
|
||||||
|
delivered.push(event);
|
||||||
|
} else {
|
||||||
|
retained.push(event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
self.os.game_lifecycle_events = retained;
|
||||||
|
if let Some(session) = self.os.vm_sessions.for_task_mut(task_id) {
|
||||||
|
session.runtime.deliver_game_lifecycle_events(delivered);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn reset_global_runtime_state(&mut self) {
|
||||||
|
self.os.clear_cartridge_service_state();
|
||||||
|
self.os.vm_runtime.clear_cartridge_state();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn debug_step_active_session(
|
||||||
|
&mut self,
|
||||||
|
platform: &mut dyn RuntimePlatform,
|
||||||
|
) -> Option<CrashReport> {
|
||||||
|
let Some(task_id) = self.active_session_task_id() else {
|
||||||
|
return Some(CrashReport::VmPanic {
|
||||||
|
message: "debug step requested without an active VM session".to_string(),
|
||||||
|
pc: None,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
let Some(session) = self.os.vm_sessions.for_task_mut(task_id) else {
|
||||||
|
return Some(CrashReport::VmPanic {
|
||||||
|
message: format!("active debug task {:?} has no VM session", task_id),
|
||||||
|
pc: None,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
session.runtime.debug_step_instruction(&mut self.os.log_service, &mut session.vm, platform)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn active_pc(&self) -> Option<usize> {
|
||||||
|
self.active_session().map(|session| session.vm.pc())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn active_operand_stack_top(&self, n: usize) -> Vec<Value> {
|
||||||
|
self.active_session().map(|session| session.vm.operand_stack_top(n)).unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn insert_active_breakpoint(&mut self, pc: usize) -> bool {
|
||||||
|
if let Some(session) = self.active_session_mut() {
|
||||||
|
session.vm.insert_breakpoint(pc);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove_active_breakpoint(&mut self, pc: usize) -> bool {
|
||||||
|
if let Some(session) = self.active_session_mut() {
|
||||||
|
session.vm.remove_breakpoint(pc);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn active_breakpoints_list(&self) -> Vec<usize> {
|
||||||
|
self.active_session().map(|session| session.vm.breakpoints_list()).unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn paused(&self) -> bool {
|
||||||
|
self.active_session()
|
||||||
|
.map(|session| session.runtime.paused)
|
||||||
|
.unwrap_or(self.os.vm_runtime.paused)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_paused(&mut self, paused: bool) {
|
||||||
|
if let Some(session) = self.active_session_mut() {
|
||||||
|
session.runtime.paused = paused;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.os.vm_runtime.paused = paused;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_inspection_active(&mut self, active: bool) {
|
||||||
|
if let Some(session) = self.active_session_mut() {
|
||||||
|
session.runtime.inspection_active = active;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.os.vm_runtime.inspection_active = active;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn request_debug_step(&mut self) {
|
||||||
|
if let Some(session) = self.active_session_mut() {
|
||||||
|
session.runtime.debug_step_request = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.os.vm_runtime.debug_step_request = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn debug_step_requested(&self) -> bool {
|
||||||
|
self.active_session()
|
||||||
|
.map(|session| session.runtime.debug_step_request)
|
||||||
|
.unwrap_or(self.os.vm_runtime.debug_step_request)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn logical_frame_active(&self) -> bool {
|
||||||
|
self.active_session()
|
||||||
|
.map(|session| session.runtime.logical_frame_active)
|
||||||
|
.unwrap_or(self.os.vm_runtime.logical_frame_active)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn delivered_game_lifecycle_events(&self) -> &[GameLifecycleEvent] {
|
||||||
|
self.active_session()
|
||||||
|
.map(|session| session.runtime.delivered_game_lifecycle_events())
|
||||||
|
.unwrap_or_else(|| self.os.vm_runtime.delivered_game_lifecycle_events())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn take_delivered_game_lifecycle_events(&mut self) -> Vec<GameLifecycleEvent> {
|
||||||
|
if let Some(session) = self.active_session_mut() {
|
||||||
|
return session.runtime.take_delivered_game_lifecycle_events();
|
||||||
|
}
|
||||||
|
|
||||||
|
self.os.vm_runtime.take_delivered_game_lifecycle_events()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn tick_index(&self) -> u64 {
|
||||||
|
self.active_session()
|
||||||
|
.map(|session| session.runtime.tick_index)
|
||||||
|
.unwrap_or(self.os.vm_runtime.tick_index)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn logical_frame_index(&self) -> u64 {
|
||||||
|
self.active_session()
|
||||||
|
.map(|session| session.runtime.logical_frame_index)
|
||||||
|
.unwrap_or(self.os.vm_runtime.logical_frame_index)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn last_frame_cpu_time_us(&self) -> u64 {
|
||||||
|
self.active_session()
|
||||||
|
.map(|session| session.runtime.last_frame_cpu_time_us)
|
||||||
|
.unwrap_or(self.os.vm_runtime.last_frame_cpu_time_us)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn completed_logical_frames(&self) -> u64 {
|
||||||
|
self.active_session()
|
||||||
|
.map(|session| {
|
||||||
|
session
|
||||||
|
.runtime
|
||||||
|
.atomic_telemetry
|
||||||
|
.completed_logical_frames
|
||||||
|
.load(Ordering::Relaxed)
|
||||||
|
.into()
|
||||||
|
})
|
||||||
|
.unwrap_or_else(|| {
|
||||||
|
self.os
|
||||||
|
.vm_runtime
|
||||||
|
.atomic_telemetry
|
||||||
|
.completed_logical_frames
|
||||||
|
.load(Ordering::Relaxed)
|
||||||
|
.into()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn telemetry_snapshot(&self) -> TelemetryFrame {
|
||||||
|
self.active_session()
|
||||||
|
.map(|session| session.runtime.atomic_telemetry.snapshot())
|
||||||
|
.unwrap_or_else(|| self.os.vm_runtime.atomic_telemetry.snapshot())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn start_render_worker<B, S>(&mut self, config: RenderWorkerConfig, backend: B, sink: S)
|
||||||
|
where
|
||||||
|
B: RenderWorkerBackend,
|
||||||
|
S: RenderWorkerFrameSink,
|
||||||
|
{
|
||||||
|
self.os.vm_runtime.start_render_worker(config, backend, sink);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn stop_render_worker(&mut self) -> Result<(), RenderWorkerError> {
|
||||||
|
self.os.vm_runtime.stop_render_worker()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn render_worker_controller(&self) -> Option<&RenderWorkerController> {
|
||||||
|
self.os.vm_runtime.render_worker_controller.as_ref()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn record_repeated_render_worker_frame(&self, frame_id: FrameId) {
|
||||||
|
self.os.vm_runtime.record_repeated_render_worker_frame(frame_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn active_render_ownership(&self) -> RenderOwnership {
|
||||||
|
if let Some(task_id) = self.foreground_session_task_id()
|
||||||
|
&& let Some(session) = self.os.vm_sessions.for_task(task_id)
|
||||||
|
{
|
||||||
|
return session.runtime.render_manager.active_ownership();
|
||||||
|
}
|
||||||
|
|
||||||
|
self.os.vm_runtime.render_manager.active_ownership()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn transition_render_owner(&mut self, app_mode: AppMode, app_id: u32) {
|
||||||
|
self.os.vm_runtime.render_manager.transition_render_owner(app_mode, app_id);
|
||||||
|
self.os.vm_runtime.sync_render_worker_ownership();
|
||||||
|
self.os.vm_runtime.render_manager.sync_telemetry(&self.os.vm_runtime.atomic_telemetry);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn cert_config(&self) -> &CertificationConfig {
|
||||||
|
&self.os.vm_runtime.certifier.config
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn last_crash_report(&self) -> Option<&CrashReport> {
|
||||||
|
self.active_session()
|
||||||
|
.and_then(|session| session.runtime.last_crash_report.as_ref())
|
||||||
|
.or(self.os.vm_runtime.last_crash_report.as_ref())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn current_app_id(&self) -> u32 {
|
||||||
|
self.active_session()
|
||||||
|
.map(|session| session.runtime.current_app_id)
|
||||||
|
.unwrap_or(self.os.vm_runtime.current_app_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn current_cartridge_title(&self) -> String {
|
||||||
|
self.active_session()
|
||||||
|
.map(|session| session.runtime.current_cartridge_title.clone())
|
||||||
|
.unwrap_or_else(|| self.os.vm_runtime.current_cartridge_title.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn current_cartridge_app_version(&self) -> String {
|
||||||
|
self.active_session()
|
||||||
|
.map(|session| session.runtime.current_cartridge_app_version.clone())
|
||||||
|
.unwrap_or_else(|| self.os.vm_runtime.current_cartridge_app_version.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn current_cartridge_app_mode(&self) -> AppMode {
|
||||||
|
self.active_session()
|
||||||
|
.map(|session| session.runtime.current_cartridge_app_mode)
|
||||||
|
.unwrap_or(self.os.vm_runtime.current_cartridge_app_mode)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn active_session(&self) -> Option<&VmSession> {
|
||||||
|
self.os
|
||||||
|
.task_manager
|
||||||
|
.foreground_task()
|
||||||
|
.and_then(|task_id| self.os.vm_sessions.for_task(task_id))
|
||||||
|
.or_else(|| {
|
||||||
|
self.os
|
||||||
|
.foreground_stack
|
||||||
|
.resident_game_task()
|
||||||
|
.and_then(|task_id| self.os.vm_sessions.for_task(task_id))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn active_session_mut(&mut self) -> Option<&mut VmSession> {
|
||||||
|
let task_id = self.active_session_task_id()?;
|
||||||
|
self.os.vm_sessions.for_task_mut(task_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn active_session_task_id(&self) -> Option<TaskId> {
|
||||||
|
self.os
|
||||||
|
.task_manager
|
||||||
|
.foreground_task()
|
||||||
|
.or_else(|| self.os.foreground_stack.resident_game_task())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn foreground_session_task_id(&self) -> Option<TaskId> {
|
||||||
|
self.os.task_manager.foreground_task()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
use crate::os::SystemOS;
|
||||||
|
use crate::task::TaskId;
|
||||||
|
use crate::windows::{Window, WindowId, WindowOwner};
|
||||||
|
use prometeu_hal::color::Color;
|
||||||
|
use prometeu_hal::primitives::Rect;
|
||||||
|
|
||||||
|
pub struct WindowFacade<'a> {
|
||||||
|
pub(in crate::os) os: &'a mut SystemOS,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> WindowFacade<'a> {
|
||||||
|
pub fn add_window(
|
||||||
|
&mut self,
|
||||||
|
title: String,
|
||||||
|
owner: WindowOwner,
|
||||||
|
viewport: Rect,
|
||||||
|
color: Color,
|
||||||
|
) -> WindowId {
|
||||||
|
self.os.window_manager.add_window(title, owner, viewport, color)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_focus(&mut self, id: WindowId) {
|
||||||
|
self.os.window_manager.set_focus(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn focused_window(&self) -> Option<WindowId> {
|
||||||
|
self.os.window_manager.focused
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn focused_window_belongs_to_task(&self, task_id: TaskId) -> bool {
|
||||||
|
self.os.window_manager.focused_window_belongs_to_task(task_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn close_window(&mut self, id: WindowId) {
|
||||||
|
self.os.window_manager.remove_window(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove_all_windows(&mut self) {
|
||||||
|
self.os.window_manager.remove_all_windows();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn windows(&self) -> &[Window] {
|
||||||
|
&self.os.window_manager.windows
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn window_count(&self) -> usize {
|
||||||
|
self.os.window_manager.windows.len()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
use crate::process::ProcessId;
|
||||||
|
use crate::task::{TaskId, TaskState};
|
||||||
|
|
||||||
|
pub const DEFAULT_GAME_PAUSE_BUDGET_TICKS: u8 = 1;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum GameLifecycleEventKind {
|
||||||
|
Pause,
|
||||||
|
ResumeForeground,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct GameLifecycleEvent {
|
||||||
|
pub task_id: TaskId,
|
||||||
|
pub kind: GameLifecycleEventKind,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum LifecycleOperation {
|
||||||
|
SetForeground,
|
||||||
|
Suspend,
|
||||||
|
Resume,
|
||||||
|
Close,
|
||||||
|
Crash,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum LifecycleError {
|
||||||
|
TaskNotFound(TaskId),
|
||||||
|
ProcessNotFound(ProcessId),
|
||||||
|
InvalidTransition { task_id: TaskId, from: TaskState, operation: LifecycleOperation },
|
||||||
|
ResidentGameAlreadyExists { existing: TaskId, requested: TaskId },
|
||||||
|
ForegroundShellAlreadyExists { existing: TaskId, requested: TaskId },
|
||||||
|
TaskIsNotResidentGame(TaskId),
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
mod facades;
|
||||||
|
mod lifecycle;
|
||||||
|
mod system_os;
|
||||||
|
|
||||||
|
pub use facades::{
|
||||||
|
FsFacade, LifecycleFacade, SessionError, SessionsFacade, VmFacade, WindowFacade,
|
||||||
|
};
|
||||||
|
pub use lifecycle::{
|
||||||
|
DEFAULT_GAME_PAUSE_BUDGET_TICKS, GameLifecycleEvent, GameLifecycleEventKind, LifecycleError,
|
||||||
|
LifecycleOperation,
|
||||||
|
};
|
||||||
|
pub use system_os::SystemOS;
|
||||||
@@ -0,0 +1,680 @@
|
|||||||
|
use crate::VirtualMachineRuntime;
|
||||||
|
use crate::fs::{FsState, VirtualFS};
|
||||||
|
use crate::os::{
|
||||||
|
FsFacade, GameLifecycleEvent, LifecycleFacade, SessionsFacade, VmFacade, WindowFacade,
|
||||||
|
};
|
||||||
|
use crate::process::ProcessManager;
|
||||||
|
use crate::services::foreground::ForegroundStack;
|
||||||
|
use crate::services::memcard::MemcardService;
|
||||||
|
use crate::services::vm_session::VmSessionRegistry;
|
||||||
|
use crate::services::windows::WindowManager;
|
||||||
|
use crate::task::TaskManager;
|
||||||
|
use prometeu_hal::log::{LogEvent, LogLevel, LogService, LogSource};
|
||||||
|
use prometeu_hal::telemetry::CertificationConfig;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
pub struct SystemOS {
|
||||||
|
pub(super) vm_runtime: VirtualMachineRuntime,
|
||||||
|
pub(super) process_manager: ProcessManager,
|
||||||
|
pub(super) task_manager: TaskManager,
|
||||||
|
pub(super) foreground_stack: ForegroundStack,
|
||||||
|
pub(super) vm_sessions: VmSessionRegistry,
|
||||||
|
pub(super) game_lifecycle_events: Vec<GameLifecycleEvent>,
|
||||||
|
pub(super) window_manager: WindowManager,
|
||||||
|
pub(super) log_service: LogService,
|
||||||
|
pub(super) fs: VirtualFS,
|
||||||
|
pub(super) fs_state: FsState,
|
||||||
|
pub(super) memcard: MemcardService,
|
||||||
|
pub(super) open_files: HashMap<u32, String>,
|
||||||
|
pub(super) next_handle: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SystemOS {
|
||||||
|
pub fn new(cap_config: Option<CertificationConfig>) -> Self {
|
||||||
|
let log_service = LogService::new(4096);
|
||||||
|
let mut os = Self {
|
||||||
|
vm_runtime: VirtualMachineRuntime::new_with_log_counter(
|
||||||
|
cap_config,
|
||||||
|
Arc::clone(&log_service.logs_count),
|
||||||
|
),
|
||||||
|
process_manager: ProcessManager::new(),
|
||||||
|
task_manager: TaskManager::new(),
|
||||||
|
foreground_stack: ForegroundStack::new(),
|
||||||
|
vm_sessions: VmSessionRegistry::new(),
|
||||||
|
game_lifecycle_events: Vec::new(),
|
||||||
|
window_manager: WindowManager::new(),
|
||||||
|
log_service,
|
||||||
|
fs: VirtualFS::new(),
|
||||||
|
fs_state: FsState::Unmounted,
|
||||||
|
memcard: MemcardService::new(),
|
||||||
|
open_files: HashMap::new(),
|
||||||
|
next_handle: 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
os.log(LogLevel::Info, LogSource::Pos, 0, "PrometeuOS starting...".to_string());
|
||||||
|
|
||||||
|
os
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn log(&mut self, level: LogLevel, source: LogSource, tag: u16, msg: String) {
|
||||||
|
self.vm_runtime.log(&mut self.log_service, level, source, tag, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn trace(&mut self, source: LogSource, msg: String) {
|
||||||
|
self.log(LogLevel::Trace, source, 0, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn trace_tag(&mut self, source: LogSource, tag: u16, msg: String) {
|
||||||
|
self.log(LogLevel::Trace, source, tag, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn debug(&mut self, source: LogSource, msg: String) {
|
||||||
|
self.log(LogLevel::Debug, source, 0, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn debug_tag(&mut self, source: LogSource, tag: u16, msg: String) {
|
||||||
|
self.log(LogLevel::Debug, source, tag, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn info(&mut self, source: LogSource, msg: String) {
|
||||||
|
self.log(LogLevel::Info, source, 0, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn info_tag(&mut self, source: LogSource, tag: u16, msg: String) {
|
||||||
|
self.log(LogLevel::Info, source, tag, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn warn(&mut self, source: LogSource, msg: String) {
|
||||||
|
self.log(LogLevel::Warn, source, 0, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn warn_tag(&mut self, source: LogSource, tag: u16, msg: String) {
|
||||||
|
self.log(LogLevel::Warn, source, tag, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn error(&mut self, source: LogSource, msg: String) {
|
||||||
|
self.log(LogLevel::Error, source, 0, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn error_tag(&mut self, source: LogSource, tag: u16, msg: String) {
|
||||||
|
self.log(LogLevel::Error, source, tag, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn recent_logs(&self, n: usize) -> Vec<LogEvent> {
|
||||||
|
self.log_service.get_recent(n)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn logs_after(&self, seq: u64) -> Vec<LogEvent> {
|
||||||
|
self.log_service.get_after(seq)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn frame_index(&mut self) -> u64 {
|
||||||
|
self.vm().logical_frame_index()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn lifecycle(&mut self) -> LifecycleFacade<'_> {
|
||||||
|
LifecycleFacade { os: self }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn sessions(&mut self) -> SessionsFacade<'_> {
|
||||||
|
SessionsFacade { os: self }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn vm(&mut self) -> VmFacade<'_> {
|
||||||
|
VmFacade { os: self }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fs(&mut self) -> FsFacade<'_> {
|
||||||
|
FsFacade { os: self }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn windows(&mut self) -> WindowFacade<'_> {
|
||||||
|
WindowFacade { os: self }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn clear_cartridge_service_state(&mut self) {
|
||||||
|
self.open_files.clear();
|
||||||
|
self.next_handle = 1;
|
||||||
|
self.memcard.clear_all_staging();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::os::{GameLifecycleEventKind, LifecycleError, LifecycleOperation, SessionError};
|
||||||
|
use crate::process::{ProcessId, ProcessKind, ProcessState};
|
||||||
|
use crate::services::foreground::{ForegroundOwner, ResidentGame, ResidentGameState};
|
||||||
|
use crate::task::{TaskId, TaskState};
|
||||||
|
use prometeu_hal::app_mode::AppMode;
|
||||||
|
use prometeu_hal::cartridge::{AssetsPayloadSource, Cartridge};
|
||||||
|
use prometeu_hal::syscalls::caps;
|
||||||
|
|
||||||
|
fn process_state_for_task(os: &SystemOS, task_id: TaskId) -> ProcessState {
|
||||||
|
let task = os.task_manager.get(task_id).expect("task should exist");
|
||||||
|
os.process_manager.get(task.process_id).expect("process should exist").state
|
||||||
|
}
|
||||||
|
|
||||||
|
fn session_test_cartridge(app_mode: AppMode, app_id: u32, title: &str) -> Cartridge {
|
||||||
|
Cartridge {
|
||||||
|
app_id,
|
||||||
|
title: title.to_string(),
|
||||||
|
app_version: "1.0.0".to_string(),
|
||||||
|
app_mode,
|
||||||
|
capabilities: caps::NONE,
|
||||||
|
program: vec![],
|
||||||
|
assets: AssetsPayloadSource::empty(),
|
||||||
|
asset_table: vec![],
|
||||||
|
preload: vec![],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn set_foreground_task_marks_task_and_process_running() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
let task_id = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
||||||
|
|
||||||
|
os.lifecycle().suspend_task(task_id).expect("suspend should succeed");
|
||||||
|
os.lifecycle().set_foreground_task(task_id).expect("foreground should succeed");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
os.task_manager.get(task_id).expect("task should exist").state,
|
||||||
|
TaskState::Foreground
|
||||||
|
);
|
||||||
|
assert_eq!(process_state_for_task(&os, task_id), ProcessState::Running);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn foreground_stack_starts_at_hub() {
|
||||||
|
let os = SystemOS::new(None);
|
||||||
|
|
||||||
|
assert_eq!(os.foreground_stack.owner(), ForegroundOwner::Hub);
|
||||||
|
assert_eq!(os.foreground_stack.resident_game(), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn game_session_registers_single_resident_game() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
let task_id = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
||||||
|
|
||||||
|
assert_eq!(os.lifecycle().foreground_owner(), ForegroundOwner::Game(task_id));
|
||||||
|
assert_eq!(
|
||||||
|
os.lifecycle().resident_game(),
|
||||||
|
Some(ResidentGame { task_id, state: ResidentGameState::Foreground })
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn second_resident_game_is_rejected() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
let first = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
||||||
|
let process_id = os.process_manager.spawn_vm_game(43, "Second");
|
||||||
|
let second = os.task_manager.create_game_task(process_id, 43, "Second");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
os.lifecycle().set_game_foreground_task(second),
|
||||||
|
Err(LifecycleError::ResidentGameAlreadyExists { existing: first, requested: second })
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn terminate_resident_game_closes_task_and_removes_vm_session() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
let game = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
||||||
|
|
||||||
|
os.lifecycle().request_home_from_game(game).expect("home request should succeed");
|
||||||
|
assert_eq!(os.lifecycle().pending_game_lifecycle_events().len(), 1);
|
||||||
|
|
||||||
|
assert_eq!(os.lifecycle().terminate_resident_game(), Ok(Some(game)));
|
||||||
|
|
||||||
|
assert_eq!(os.lifecycle().resident_game(), None);
|
||||||
|
assert_eq!(os.lifecycle().foreground_owner(), ForegroundOwner::Hub);
|
||||||
|
assert_eq!(os.lifecycle().task_state(game), Some(TaskState::Closed));
|
||||||
|
assert_eq!(process_state_for_task(&os, game), ProcessState::Stopped);
|
||||||
|
assert_eq!(os.sessions().vm_session_for_task(game).map(|session| session.task_id), None);
|
||||||
|
assert!(os.lifecycle().pending_game_lifecycle_events().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn terminate_resident_game_preserves_foreground_shell() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
let game = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
||||||
|
os.lifecycle().request_home_from_game(game).expect("home request should succeed");
|
||||||
|
os.lifecycle().advance_game_pause_budget(game).expect("budget should expire");
|
||||||
|
let shell = os.sessions().create_vm_shell_task(7, "Settings");
|
||||||
|
|
||||||
|
assert_eq!(os.lifecycle().terminate_resident_game(), Ok(Some(game)));
|
||||||
|
|
||||||
|
assert_eq!(os.lifecycle().foreground_owner(), ForegroundOwner::Shell(shell));
|
||||||
|
assert_eq!(os.lifecycle().resident_game(), None);
|
||||||
|
assert_eq!(os.lifecycle().task_state(game), Some(TaskState::Closed));
|
||||||
|
assert_eq!(process_state_for_task(&os, game), ProcessState::Stopped);
|
||||||
|
assert_eq!(os.sessions().vm_session_for_task(game).map(|session| session.task_id), None);
|
||||||
|
assert_eq!(os.lifecycle().task_state(shell), Some(TaskState::Foreground));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn vm_game_task_creates_vm_session() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
let task_id = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
||||||
|
|
||||||
|
let sessions = os.sessions();
|
||||||
|
let session = sessions.vm_session_for_task(task_id).expect("VM session should exist");
|
||||||
|
|
||||||
|
assert_eq!(session.task_id, task_id);
|
||||||
|
assert_eq!(session.app_id, 42);
|
||||||
|
assert_eq!(session.title, "Sector Crawl");
|
||||||
|
assert_eq!(session.app_mode, AppMode::Game);
|
||||||
|
assert_eq!(sessions.vm_session_count(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn vm_shell_task_creates_vm_session() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
let task_id = os.sessions().create_vm_shell_task(7, "Settings");
|
||||||
|
|
||||||
|
let sessions = os.sessions();
|
||||||
|
let session = sessions.vm_session_for_task(task_id).expect("VM session should exist");
|
||||||
|
|
||||||
|
assert_eq!(session.task_id, task_id);
|
||||||
|
assert_eq!(session.app_id, 7);
|
||||||
|
assert_eq!(session.title, "Settings");
|
||||||
|
assert_eq!(session.app_mode, AppMode::Shell);
|
||||||
|
assert_eq!(sessions.vm_session_count(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn native_shell_task_does_not_create_vm_session() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
let task_id = os.sessions().create_native_shell_task(7, "Settings");
|
||||||
|
|
||||||
|
let sessions = os.sessions();
|
||||||
|
|
||||||
|
assert!(sessions.vm_session_for_task(task_id).is_none());
|
||||||
|
assert_eq!(sessions.vm_session_count(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn same_resident_game_app_reuses_existing_vm_session() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
let first = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
||||||
|
let second = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
||||||
|
|
||||||
|
let sessions = os.sessions();
|
||||||
|
|
||||||
|
assert_eq!(second, first);
|
||||||
|
assert_eq!(
|
||||||
|
sessions.resident_game_session_for_app(42).map(|session| session.task_id),
|
||||||
|
Some(first)
|
||||||
|
);
|
||||||
|
assert_eq!(sessions.vm_session_count(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn vm_sessions_hold_independent_runtime_state() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
let game = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
||||||
|
os.lifecycle().request_home_from_game(game).expect("home request should succeed");
|
||||||
|
os.lifecycle().advance_game_pause_budget(game).expect("budget should expire");
|
||||||
|
let shell = os.sessions().create_vm_shell_task(7, "Settings");
|
||||||
|
|
||||||
|
{
|
||||||
|
let mut sessions = os.sessions();
|
||||||
|
let game_session =
|
||||||
|
sessions.vm_session_for_task_mut(game).expect("game VM session should exist");
|
||||||
|
game_session.runtime.tick_index = 100;
|
||||||
|
game_session.open_files.insert(1, "/game.dat".to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
let mut sessions = os.sessions();
|
||||||
|
let shell_session =
|
||||||
|
sessions.vm_session_for_task_mut(shell).expect("shell VM session should exist");
|
||||||
|
shell_session.runtime.tick_index = 5;
|
||||||
|
shell_session.open_files.insert(1, "/shell.dat".to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
let sessions = os.sessions();
|
||||||
|
let game_session =
|
||||||
|
sessions.vm_session_for_task(game).expect("game VM session should exist");
|
||||||
|
let shell_session =
|
||||||
|
sessions.vm_session_for_task(shell).expect("shell VM session should exist");
|
||||||
|
|
||||||
|
assert_eq!(game_session.runtime.tick_index, 100);
|
||||||
|
assert_eq!(shell_session.runtime.tick_index, 5);
|
||||||
|
assert_eq!(game_session.open_files.get(&1).map(String::as_str), Some("/game.dat"));
|
||||||
|
assert_eq!(shell_session.open_files.get(&1).map(String::as_str), Some("/shell.dat"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn vm_debug_operations_target_foreground_shell_before_resident_game() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
let game = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
||||||
|
os.lifecycle().request_home_from_game(game).expect("home request should succeed");
|
||||||
|
os.lifecycle().advance_game_pause_budget(game).expect("budget should expire");
|
||||||
|
let shell = os.sessions().create_vm_shell_task(7, "Settings");
|
||||||
|
|
||||||
|
{
|
||||||
|
let mut sessions = os.sessions();
|
||||||
|
let game_session =
|
||||||
|
sessions.vm_session_for_task_mut(game).expect("game VM session should exist");
|
||||||
|
game_session.vm.insert_breakpoint(10);
|
||||||
|
}
|
||||||
|
|
||||||
|
assert!(os.vm().insert_active_breakpoint(20));
|
||||||
|
assert_eq!(os.vm().active_breakpoints_list(), vec![20]);
|
||||||
|
|
||||||
|
let sessions = os.sessions();
|
||||||
|
assert_eq!(
|
||||||
|
sessions
|
||||||
|
.vm_session_for_task(game)
|
||||||
|
.expect("game VM session should exist")
|
||||||
|
.vm
|
||||||
|
.breakpoints_list(),
|
||||||
|
vec![10]
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
sessions
|
||||||
|
.vm_session_for_task(shell)
|
||||||
|
.expect("shell VM session should exist")
|
||||||
|
.vm
|
||||||
|
.breakpoints_list(),
|
||||||
|
vec![20]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn home_request_notifies_game_before_budget_suspends_it() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
let task_id = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
||||||
|
|
||||||
|
os.lifecycle().request_home_from_game(task_id).expect("home request should succeed");
|
||||||
|
|
||||||
|
assert_eq!(os.lifecycle().foreground_owner(), ForegroundOwner::Game(task_id));
|
||||||
|
assert_eq!(
|
||||||
|
os.lifecycle().resident_game(),
|
||||||
|
Some(ResidentGame {
|
||||||
|
task_id,
|
||||||
|
state: ResidentGameState::PauseRequested { remaining_ticks: 1 },
|
||||||
|
})
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
os.lifecycle().pending_game_lifecycle_events()[0].kind,
|
||||||
|
GameLifecycleEventKind::Pause
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
os.task_manager.get(task_id).expect("task should exist").state,
|
||||||
|
TaskState::Foreground
|
||||||
|
);
|
||||||
|
|
||||||
|
assert!(os.lifecycle().advance_game_pause_budget(task_id).expect("budget should advance"));
|
||||||
|
assert_eq!(os.lifecycle().foreground_owner(), ForegroundOwner::Hub);
|
||||||
|
assert_eq!(
|
||||||
|
os.lifecycle().resident_game(),
|
||||||
|
Some(ResidentGame { task_id, state: ResidentGameState::PausedSuspended })
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
os.task_manager.get(task_id).expect("task should exist").state,
|
||||||
|
TaskState::Suspended
|
||||||
|
);
|
||||||
|
assert_eq!(process_state_for_task(&os, task_id), ProcessState::Suspended);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn shell_foreground_keeps_game_resident_and_marks_it_suspended() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
let game = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
||||||
|
os.lifecycle().request_home_from_game(game).expect("home request should succeed");
|
||||||
|
os.lifecycle().advance_game_pause_budget(game).expect("budget should expire");
|
||||||
|
let shell = os.sessions().create_vm_shell_task(7, "Settings");
|
||||||
|
|
||||||
|
assert_eq!(os.lifecycle().foreground_owner(), ForegroundOwner::Shell(shell));
|
||||||
|
assert_eq!(
|
||||||
|
os.lifecycle().resident_game(),
|
||||||
|
Some(ResidentGame { task_id: game, state: ResidentGameState::PausedSuspended })
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn vm_shell_foreground_suspends_foreground_resident_game() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
let game = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
||||||
|
|
||||||
|
let shell = os.sessions().create_vm_shell_task(7, "Settings");
|
||||||
|
|
||||||
|
assert_eq!(os.lifecycle().foreground_owner(), ForegroundOwner::Shell(shell));
|
||||||
|
assert_eq!(
|
||||||
|
os.lifecycle().resident_game(),
|
||||||
|
Some(ResidentGame { task_id: game, state: ResidentGameState::PausedSuspended })
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
os.task_manager.get(game).expect("game should exist").state,
|
||||||
|
TaskState::Suspended
|
||||||
|
);
|
||||||
|
assert_eq!(process_state_for_task(&os, game), ProcessState::Suspended);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn native_shell_foreground_suspends_foreground_resident_game() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
let game = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
||||||
|
|
||||||
|
let shell = os.sessions().create_native_shell_task(7, "Settings");
|
||||||
|
|
||||||
|
assert_eq!(os.lifecycle().foreground_owner(), ForegroundOwner::Shell(shell));
|
||||||
|
assert_eq!(
|
||||||
|
os.lifecycle().resident_game(),
|
||||||
|
Some(ResidentGame { task_id: game, state: ResidentGameState::PausedSuspended })
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
os.task_manager.get(game).expect("game should exist").state,
|
||||||
|
TaskState::Suspended
|
||||||
|
);
|
||||||
|
assert_eq!(process_state_for_task(&os, game), ProcessState::Suspended);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn lifecycle_exposes_process_kind_for_shell_tasks() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
let vm_shell = os.sessions().create_vm_shell_task(7, "Settings");
|
||||||
|
os.lifecycle().close_task(vm_shell).expect("vm shell should close");
|
||||||
|
|
||||||
|
let native_shell = os.sessions().create_native_shell_task(8, "Files");
|
||||||
|
|
||||||
|
assert_eq!(os.lifecycle().process_kind_for_task(vm_shell), Ok(ProcessKind::VmShell));
|
||||||
|
assert_eq!(
|
||||||
|
os.lifecycle().process_kind_for_task(native_shell),
|
||||||
|
Ok(ProcessKind::NativeShell)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn second_foreground_shell_is_rejected() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
let first = os.sessions().create_vm_shell_task(7, "Settings");
|
||||||
|
let process_id = os.process_manager.spawn_vm_shell(8, "Files");
|
||||||
|
let second = os.task_manager.create_shell_task(process_id, 8, "Files");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
os.lifecycle().set_shell_foreground_task(second),
|
||||||
|
Err(LifecycleError::ForegroundShellAlreadyExists {
|
||||||
|
existing: first,
|
||||||
|
requested: second,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn vm_shell_load_returns_typed_error_when_foreground_shell_exists() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
let first = os.sessions().create_vm_shell_task(7, "Settings");
|
||||||
|
let cartridge = session_test_cartridge(AppMode::Shell, 8, "Files");
|
||||||
|
|
||||||
|
let error = os.sessions().load_vm_cartridge(&cartridge).expect_err("load should fail");
|
||||||
|
|
||||||
|
match error {
|
||||||
|
SessionError::Lifecycle(LifecycleError::ForegroundShellAlreadyExists {
|
||||||
|
existing,
|
||||||
|
requested,
|
||||||
|
}) => {
|
||||||
|
assert_eq!(existing, first);
|
||||||
|
assert_ne!(requested, first);
|
||||||
|
}
|
||||||
|
other => panic!("expected foreground shell lifecycle error, got {:?}", other),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn vm_session_creation_returns_typed_error_for_missing_task() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
os.sessions().try_create_vm_session_for_task(TaskId(999)),
|
||||||
|
Err(SessionError::TaskNotFound(TaskId(999)))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn vm_session_creation_returns_typed_error_for_missing_process() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
let task_id = os.task_manager.create_game_task(ProcessId(999), 42, "Broken");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
os.sessions().try_create_vm_session_for_task(task_id),
|
||||||
|
Err(SessionError::ProcessNotFound(ProcessId(999)))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn session_cartridge_initialization_returns_typed_error_for_missing_session() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
let process_id = os.process_manager.spawn_vm_game(42, "Sector Crawl");
|
||||||
|
let task_id = os.task_manager.create_game_task(process_id, 42, "Sector Crawl");
|
||||||
|
let cartridge = session_test_cartridge(AppMode::Game, 42, "Sector Crawl");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
os.sessions().try_initialize_session_cartridge(task_id, &cartridge),
|
||||||
|
Err(SessionError::MissingVmSession(task_id))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn closing_foreground_shell_returns_to_hub() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
let shell = os.sessions().create_vm_shell_task(7, "Settings");
|
||||||
|
|
||||||
|
os.lifecycle().close_task(shell).expect("close should succeed");
|
||||||
|
|
||||||
|
assert_eq!(os.lifecycle().foreground_owner(), ForegroundOwner::Hub);
|
||||||
|
assert_eq!(
|
||||||
|
os.task_manager.get(shell).expect("shell should remain").state,
|
||||||
|
TaskState::Closed
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn suspend_task_marks_task_and_process_suspended() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
let task_id = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
||||||
|
|
||||||
|
os.lifecycle().suspend_task(task_id).expect("suspend should succeed");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
os.task_manager.get(task_id).expect("task should exist").state,
|
||||||
|
TaskState::Suspended
|
||||||
|
);
|
||||||
|
assert_eq!(process_state_for_task(&os, task_id), ProcessState::Suspended);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resume_task_marks_suspended_task_foreground_and_process_running() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
let task_id = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
||||||
|
|
||||||
|
os.lifecycle().suspend_task(task_id).expect("suspend should succeed");
|
||||||
|
os.lifecycle().resume_task(task_id).expect("resume should succeed");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
os.task_manager.get(task_id).expect("task should exist").state,
|
||||||
|
TaskState::Foreground
|
||||||
|
);
|
||||||
|
assert_eq!(process_state_for_task(&os, task_id), ProcessState::Running);
|
||||||
|
assert_eq!(
|
||||||
|
os.lifecycle().pending_game_lifecycle_events().last().map(|event| event.kind),
|
||||||
|
Some(GameLifecycleEventKind::ResumeForeground)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn close_task_marks_task_closed_and_process_stopped_without_removing_entities() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
let task_id = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
||||||
|
let process_id = os.task_manager.get(task_id).expect("task should exist").process_id;
|
||||||
|
|
||||||
|
os.lifecycle().close_task(task_id).expect("close should succeed");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
os.task_manager.get(task_id).expect("task should remain").state,
|
||||||
|
TaskState::Closed
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
os.process_manager.get(process_id).expect("process should remain").state,
|
||||||
|
ProcessState::Stopped
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn crash_task_marks_task_and_process_crashed() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
let task_id = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
||||||
|
|
||||||
|
os.lifecycle().crash_task(task_id, None).expect("crash should succeed");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
os.task_manager.get(task_id).expect("task should exist").state,
|
||||||
|
TaskState::Crashed
|
||||||
|
);
|
||||||
|
assert_eq!(process_state_for_task(&os, task_id), ProcessState::Crashed);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn lifecycle_operation_missing_task_returns_typed_error() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
os.lifecycle().suspend_task(TaskId(999)),
|
||||||
|
Err(LifecycleError::TaskNotFound(TaskId(999)))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn lifecycle_operation_missing_process_returns_typed_error() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
let task_id = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
||||||
|
let process_id = os.task_manager.get(task_id).expect("task should exist").process_id;
|
||||||
|
|
||||||
|
os.process_manager.mark_stopped(process_id);
|
||||||
|
os.process_manager.remove_stopped();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
os.lifecycle().suspend_task(task_id),
|
||||||
|
Err(LifecycleError::ProcessNotFound(process_id))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resume_task_from_non_suspended_state_returns_invalid_transition() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
let task_id = os.sessions().create_vm_game_task(42, "Sector Crawl");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
os.lifecycle().resume_task(task_id),
|
||||||
|
Err(LifecycleError::InvalidTransition {
|
||||||
|
task_id,
|
||||||
|
from: TaskState::Foreground,
|
||||||
|
operation: LifecycleOperation::Resume,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,6 @@
|
|||||||
mod prometeu_hub;
|
mod prometeu_hub;
|
||||||
|
|
||||||
pub use prometeu_hub::PrometeuHub;
|
pub use prometeu_hub::{
|
||||||
|
HUB_SUSPENDED_GAME_KILL_CONTROL, NativeShellApp, PrometeuHub, SystemProfileAction,
|
||||||
|
SystemProfileUpdate,
|
||||||
|
};
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
#[allow(clippy::module_inception)]
|
#[allow(clippy::module_inception)]
|
||||||
mod prometeu_hub;
|
mod prometeu_hub;
|
||||||
mod window_manager;
|
|
||||||
|
|
||||||
pub use prometeu_hub::PrometeuHub;
|
pub use prometeu_hub::{
|
||||||
|
HUB_SUSPENDED_GAME_KILL_CONTROL, NativeShellApp, PrometeuHub, SystemProfileAction,
|
||||||
|
SystemProfileUpdate,
|
||||||
|
};
|
||||||
|
|||||||
@@ -1,13 +1,99 @@
|
|||||||
use crate::VirtualMachineRuntime;
|
use crate::task::TaskId;
|
||||||
use crate::programs::prometeu_hub::window_manager::WindowManager;
|
use crate::{CrashReport, GameLibrary, GameSwitchTarget, SystemOS};
|
||||||
use prometeu_hal::HardwareBridge;
|
use prometeu_hal::app_mode::AppMode;
|
||||||
use prometeu_hal::color::Color;
|
use prometeu_hal::color::Color;
|
||||||
use prometeu_hal::log::{LogLevel, LogSource};
|
use prometeu_hal::primitives::Rect;
|
||||||
use prometeu_hal::window::Rect;
|
use prometeu_hal::{
|
||||||
|
FrameId, GfxUiCommand, InputPlatform, InputSignals, RenderSubmission, RuntimePlatform,
|
||||||
|
ShellUiFramePacket,
|
||||||
|
};
|
||||||
|
|
||||||
|
const SHELL_A_BUTTON: Rect = Rect { x: 112, y: 172, w: 112, h: 32 };
|
||||||
|
const SHELL_B_BUTTON: Rect = Rect { x: 256, y: 172, w: 112, h: 32 };
|
||||||
|
const CLOSE_BUTTON: Rect = Rect { x: 420, y: 24, w: 16, h: 16 };
|
||||||
|
const VIEWPORT: Rect = Rect { x: 0, y: 0, w: 480, h: 270 };
|
||||||
|
const HOME_PANEL: Rect = Rect { x: 48, y: 58, w: 384, h: 154 };
|
||||||
|
const TITLE_PANEL: Rect = Rect { x: 72, y: 34, w: 336, h: 28 };
|
||||||
|
const GAME_ROW_X: i32 = 72;
|
||||||
|
const GAME_ROW_Y: i32 = 90;
|
||||||
|
const GAME_ROW_W: i32 = 336;
|
||||||
|
const GAME_ROW_H: i32 = 22;
|
||||||
|
const GAME_ROW_GAP: i32 = 6;
|
||||||
|
const MAX_HOME_GAME_ROWS: usize = 3;
|
||||||
|
pub const HUB_SUSPENDED_GAME_KILL_CONTROL: Rect = Rect { x: 288, y: 230, w: 168, h: 24 };
|
||||||
|
#[cfg(test)]
|
||||||
|
const SHELL_FRAME: Rect = Rect { x: 40, y: 20, w: 400, h: 220 };
|
||||||
|
|
||||||
|
const COLOR_BG: Color = Color::rgb(12, 14, 22);
|
||||||
|
const COLOR_PANEL: Color = Color::rgb(25, 31, 48);
|
||||||
|
const COLOR_PANEL_DARK: Color = Color::rgb(8, 10, 16);
|
||||||
|
const COLOR_BORDER: Color = Color::rgb(180, 218, 222);
|
||||||
|
const COLOR_HILITE: Color = Color::rgb(252, 226, 122);
|
||||||
|
const COLOR_TEXT: Color = Color::rgb(230, 236, 224);
|
||||||
|
const COLOR_MUTED: Color = Color::rgb(91, 112, 128);
|
||||||
|
const COLOR_BUTTON: Color = Color::rgb(45, 59, 82);
|
||||||
|
const COLOR_BUTTON_ACTIVE: Color = Color::rgb(72, 91, 122);
|
||||||
|
const COLOR_KILL: Color = Color::rgb(164, 32, 40);
|
||||||
|
const COLOR_KILL_ACTIVE: Color = Color::rgb(206, 46, 54);
|
||||||
|
|
||||||
/// PrometeuHub: Launcher and system UI environment.
|
/// PrometeuHub: Launcher and system UI environment.
|
||||||
pub struct PrometeuHub {
|
pub struct PrometeuHub {
|
||||||
pub window_manager: WindowManager,
|
home_input_armed: bool,
|
||||||
|
game_library: GameLibrary,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum NativeShellApp {
|
||||||
|
ShellA,
|
||||||
|
ShellB,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
struct HubButtonSpec {
|
||||||
|
app: NativeShellApp,
|
||||||
|
rect: Rect,
|
||||||
|
label: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
const HOME_BUTTONS: [HubButtonSpec; 2] = [
|
||||||
|
HubButtonSpec { app: NativeShellApp::ShellA, rect: SHELL_A_BUTTON, label: "ShellA" },
|
||||||
|
HubButtonSpec { app: NativeShellApp::ShellB, rect: SHELL_B_BUTTON, label: "ShellB" },
|
||||||
|
];
|
||||||
|
|
||||||
|
impl NativeShellApp {
|
||||||
|
pub fn app_id(self) -> u32 {
|
||||||
|
match self {
|
||||||
|
Self::ShellA => 10_001,
|
||||||
|
Self::ShellB => 10_002,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn title(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::ShellA => "ShellA",
|
||||||
|
Self::ShellB => "ShellB",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn color(self) -> Color {
|
||||||
|
match self {
|
||||||
|
Self::ShellA => Color::GREEN,
|
||||||
|
Self::ShellB => Color::BLUE,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum SystemProfileAction {
|
||||||
|
LaunchNativeShell(NativeShellApp),
|
||||||
|
LaunchGame { target: GameSwitchTarget },
|
||||||
|
KillResidentGame,
|
||||||
|
CloseShell,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct SystemProfileUpdate {
|
||||||
|
pub crash: Option<CrashReport>,
|
||||||
|
pub action: Option<SystemProfileAction>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for PrometeuHub {
|
impl Default for PrometeuHub {
|
||||||
@@ -18,61 +104,729 @@ impl Default for PrometeuHub {
|
|||||||
|
|
||||||
impl PrometeuHub {
|
impl PrometeuHub {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self { window_manager: WindowManager::new() }
|
Self { home_input_armed: false, game_library: GameLibrary::empty() }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn init(&mut self) {
|
pub fn init(&mut self) {
|
||||||
// Initializes the Window System and lists apps
|
self.home_input_armed = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn gui_update(&mut self, os: &mut VirtualMachineRuntime, hw: &mut dyn HardwareBridge) {
|
pub fn set_game_library(&mut self, game_library: GameLibrary) {
|
||||||
hw.gfx_mut().clear(Color::BLACK);
|
self.game_library = game_library;
|
||||||
|
|
||||||
let mut next_window = None;
|
|
||||||
|
|
||||||
if hw.pad().a().pressed {
|
|
||||||
os.log(LogLevel::Debug, LogSource::Hub, 0, "window A opened".to_string());
|
|
||||||
next_window = Some((
|
|
||||||
"Green Window".to_string(),
|
|
||||||
Rect { x: 0, y: 0, w: 160, h: 90 },
|
|
||||||
Color::GREEN,
|
|
||||||
));
|
|
||||||
} else if hw.pad().b().pressed {
|
|
||||||
os.log(LogLevel::Debug, LogSource::Hub, 0, "window B opened".to_string());
|
|
||||||
next_window = Some((
|
|
||||||
"Indigo Window".to_string(),
|
|
||||||
Rect { x: 160, y: 0, w: 160, h: 90 },
|
|
||||||
Color::INDIGO,
|
|
||||||
));
|
|
||||||
} else if hw.pad().x().pressed {
|
|
||||||
os.log(LogLevel::Debug, LogSource::Hub, 0, "window X opened".to_string());
|
|
||||||
next_window = Some((
|
|
||||||
"Yellow Window".to_string(),
|
|
||||||
Rect { x: 0, y: 90, w: 160, h: 90 },
|
|
||||||
Color::YELLOW,
|
|
||||||
));
|
|
||||||
} else if hw.pad().y().pressed {
|
|
||||||
os.log(LogLevel::Debug, LogSource::Hub, 0, "window Y opened".to_string());
|
|
||||||
next_window =
|
|
||||||
Some(("Red Window".to_string(), Rect { x: 160, y: 90, w: 160, h: 90 }, Color::RED));
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some((title, rect, color)) = next_window {
|
|
||||||
self.window_manager.remove_all_windows();
|
|
||||||
let id = self.window_manager.add_window(title, rect, color);
|
|
||||||
self.window_manager.set_focus(id);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn render(&mut self, _os: &mut VirtualMachineRuntime, hw: &mut dyn HardwareBridge) {
|
pub fn game_library(&self) -> &GameLibrary {
|
||||||
for window in &self.window_manager.windows {
|
&self.game_library
|
||||||
hw.gfx_mut().fill_rect(
|
}
|
||||||
window.viewport.x,
|
|
||||||
window.viewport.y,
|
pub fn gui_update(
|
||||||
window.viewport.w,
|
&mut self,
|
||||||
window.viewport.h,
|
os: &mut SystemOS,
|
||||||
window.color,
|
platform: &mut dyn RuntimePlatform,
|
||||||
);
|
) -> Option<SystemProfileAction> {
|
||||||
|
let in_shell = os.windows().focused_window().is_some();
|
||||||
|
|
||||||
|
if !in_shell {
|
||||||
|
if !self.home_input_armed {
|
||||||
|
self.home_input_armed = !activation_input_down(platform.input());
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
self.home_input_armed = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let input = platform.input();
|
||||||
|
let suspended_game = if in_shell { None } else { resident_game_indicator(os) };
|
||||||
|
if let Some(action) = action_for_click(
|
||||||
|
in_shell,
|
||||||
|
input.touch().x(),
|
||||||
|
input.touch().y(),
|
||||||
|
input.touch().f().pressed,
|
||||||
|
self.game_library.entries(),
|
||||||
|
suspended_game.as_ref(),
|
||||||
|
) {
|
||||||
|
return Some(action);
|
||||||
|
}
|
||||||
|
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn render(&mut self, os: &mut SystemOS, platform: &mut dyn RuntimePlatform) {
|
||||||
|
let pointer_x = platform.input().touch().x();
|
||||||
|
let pointer_y = platform.input().touch().y();
|
||||||
|
|
||||||
|
let packet = if os.windows().window_count() == 0 {
|
||||||
|
let suspended_game = resident_game_indicator(os);
|
||||||
|
render_home_packet(
|
||||||
|
pointer_x,
|
||||||
|
pointer_y,
|
||||||
|
self.game_library.entries(),
|
||||||
|
suspended_game.as_ref(),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
let mut commands = Vec::new();
|
||||||
|
for window in os.windows().windows() {
|
||||||
|
append_shell_window_commands(
|
||||||
|
&mut commands,
|
||||||
|
window.viewport,
|
||||||
|
window.color,
|
||||||
|
&window.title,
|
||||||
|
pointer_x,
|
||||||
|
pointer_y,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
ShellUiFramePacket::new(commands)
|
||||||
|
};
|
||||||
|
platform
|
||||||
|
.render_submission_sink()
|
||||||
|
.submit_render_submission(RenderSubmission::shell_ui(FrameId::ZERO, packet))
|
||||||
|
.expect("hub render submission should publish");
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update_shell_profile(
|
||||||
|
&mut self,
|
||||||
|
os: &mut SystemOS,
|
||||||
|
platform: &mut dyn RuntimePlatform,
|
||||||
|
) -> SystemProfileUpdate {
|
||||||
|
let mut action = self.gui_update(os, platform);
|
||||||
|
|
||||||
|
if os.windows().focused_window().is_some() && platform.input().pad().start().down {
|
||||||
|
action = Some(SystemProfileAction::CloseShell);
|
||||||
|
}
|
||||||
|
|
||||||
|
self.render(os, platform);
|
||||||
|
|
||||||
|
SystemProfileUpdate { crash: None, action }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update_vm_shell_profile(
|
||||||
|
&mut self,
|
||||||
|
os: &mut SystemOS,
|
||||||
|
task_id: TaskId,
|
||||||
|
signals: &InputSignals,
|
||||||
|
platform: &mut dyn RuntimePlatform,
|
||||||
|
) -> SystemProfileUpdate {
|
||||||
|
let mut crash = None;
|
||||||
|
let mut action = self.gui_update(os, platform);
|
||||||
|
|
||||||
|
if os.windows().focused_window().is_some() {
|
||||||
|
if platform.input().pad().start().down {
|
||||||
|
action = Some(SystemProfileAction::CloseShell);
|
||||||
|
} else if action != Some(SystemProfileAction::CloseShell) {
|
||||||
|
crash = os.vm().tick_session(task_id, signals, platform);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
self.render(os, platform);
|
||||||
|
|
||||||
|
SystemProfileUpdate { crash, action }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update_native_shell_profile(
|
||||||
|
&mut self,
|
||||||
|
os: &mut SystemOS,
|
||||||
|
platform: &mut dyn RuntimePlatform,
|
||||||
|
) -> SystemProfileUpdate {
|
||||||
|
let mut action = self.gui_update(os, platform);
|
||||||
|
|
||||||
|
if os.windows().focused_window().is_some() && platform.input().pad().start().down {
|
||||||
|
action = Some(SystemProfileAction::CloseShell);
|
||||||
|
}
|
||||||
|
|
||||||
|
self.render(os, platform);
|
||||||
|
|
||||||
|
SystemProfileUpdate { crash: None, action }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn action_for_click(
|
||||||
|
in_shell: bool,
|
||||||
|
x: i32,
|
||||||
|
y: i32,
|
||||||
|
pressed: bool,
|
||||||
|
game_entries: &[crate::GameLibraryEntry],
|
||||||
|
suspended_game: Option<&SuspendedGameIndicator>,
|
||||||
|
) -> Option<SystemProfileAction> {
|
||||||
|
if !pressed {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
if in_shell {
|
||||||
|
return rect_contains(CLOSE_BUTTON, x, y).then_some(SystemProfileAction::CloseShell);
|
||||||
|
}
|
||||||
|
|
||||||
|
if suspended_game.is_some() && rect_contains(HUB_SUSPENDED_GAME_KILL_CONTROL, x, y) {
|
||||||
|
return Some(SystemProfileAction::KillResidentGame);
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(entry) = game_entries
|
||||||
|
.iter()
|
||||||
|
.take(MAX_HOME_GAME_ROWS)
|
||||||
|
.enumerate()
|
||||||
|
.find(|(index, _entry)| rect_contains(game_row_rect(*index), x, y))
|
||||||
|
.map(|(_index, entry)| entry)
|
||||||
|
{
|
||||||
|
return Some(SystemProfileAction::LaunchGame { target: entry.switch_target() });
|
||||||
|
}
|
||||||
|
|
||||||
|
HOME_BUTTONS
|
||||||
|
.iter()
|
||||||
|
.find(|button| rect_contains(button.rect, x, y))
|
||||||
|
.map(|button| SystemProfileAction::LaunchNativeShell(button.app))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
struct SuspendedGameIndicator {
|
||||||
|
title: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resident_game_indicator(os: &mut SystemOS) -> Option<SuspendedGameIndicator> {
|
||||||
|
let task_id = os.lifecycle().resident_game_task()?;
|
||||||
|
let sessions = os.sessions();
|
||||||
|
let session = sessions.vm_session_for_task(task_id)?;
|
||||||
|
|
||||||
|
if session.app_mode != AppMode::Game {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
Some(SuspendedGameIndicator { title: session.title.clone() })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn game_row_rect(index: usize) -> Rect {
|
||||||
|
Rect {
|
||||||
|
x: GAME_ROW_X,
|
||||||
|
y: GAME_ROW_Y + (GAME_ROW_H + GAME_ROW_GAP) * index as i32,
|
||||||
|
w: GAME_ROW_W,
|
||||||
|
h: GAME_ROW_H,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rect_contains(rect: Rect, x: i32, y: i32) -> bool {
|
||||||
|
x >= rect.x && x < rect.x + rect.w && y >= rect.y && y < rect.y + rect.h
|
||||||
|
}
|
||||||
|
|
||||||
|
fn activation_input_down(input: &dyn InputPlatform) -> bool {
|
||||||
|
input.touch().f().down
|
||||||
|
|| input.pad().a().down
|
||||||
|
|| input.pad().b().down
|
||||||
|
|| input.pad().start().down
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_home_packet(
|
||||||
|
pointer_x: i32,
|
||||||
|
pointer_y: i32,
|
||||||
|
game_entries: &[crate::GameLibraryEntry],
|
||||||
|
suspended_game: Option<&SuspendedGameIndicator>,
|
||||||
|
) -> ShellUiFramePacket {
|
||||||
|
let mut commands = Vec::new();
|
||||||
|
commands.push(GfxUiCommand::Clear { color: COLOR_BG });
|
||||||
|
fill_rect(&mut commands, VIEWPORT, COLOR_BG);
|
||||||
|
draw_panel(&mut commands, TITLE_PANEL, COLOR_PANEL_DARK, COLOR_BORDER);
|
||||||
|
draw_buffer_text(
|
||||||
|
&mut commands,
|
||||||
|
TITLE_PANEL.x + 58,
|
||||||
|
TITLE_PANEL.y + 9,
|
||||||
|
"PROMETEU HUB",
|
||||||
|
COLOR_TEXT,
|
||||||
|
);
|
||||||
|
|
||||||
|
draw_panel(&mut commands, HOME_PANEL, COLOR_PANEL, COLOR_BORDER);
|
||||||
|
draw_buffer_text(&mut commands, HOME_PANEL.x + 26, HOME_PANEL.y + 22, "Games", COLOR_TEXT);
|
||||||
|
draw_buffer_text(
|
||||||
|
&mut commands,
|
||||||
|
HOME_PANEL.x + 26,
|
||||||
|
HOME_PANEL.y + 40,
|
||||||
|
"local library",
|
||||||
|
COLOR_MUTED,
|
||||||
|
);
|
||||||
|
|
||||||
|
if game_entries.is_empty() {
|
||||||
|
draw_buffer_text(&mut commands, GAME_ROW_X, GAME_ROW_Y + 6, "No games found", COLOR_MUTED);
|
||||||
|
} else {
|
||||||
|
for (index, entry) in game_entries.iter().take(MAX_HOME_GAME_ROWS).enumerate() {
|
||||||
|
let rect = game_row_rect(index);
|
||||||
|
let hovered = rect_contains(rect, pointer_x, pointer_y);
|
||||||
|
let text = format!("{} #{} {}", entry.title, entry.app_id, entry.app_version);
|
||||||
|
draw_game_row(&mut commands, rect, &text, hovered);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for button in HOME_BUTTONS {
|
||||||
|
let hovered = rect_contains(button.rect, pointer_x, pointer_y);
|
||||||
|
draw_button(&mut commands, button.rect, button.label, hovered);
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(suspended_game) = suspended_game {
|
||||||
|
let hovered = rect_contains(HUB_SUSPENDED_GAME_KILL_CONTROL, pointer_x, pointer_y);
|
||||||
|
draw_suspended_game_kill_control(&mut commands, suspended_game, hovered);
|
||||||
|
}
|
||||||
|
|
||||||
|
ShellUiFramePacket::new(commands)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn append_shell_window_commands(
|
||||||
|
commands: &mut Vec<GfxUiCommand>,
|
||||||
|
viewport: Rect,
|
||||||
|
color: Color,
|
||||||
|
title: &str,
|
||||||
|
pointer_x: i32,
|
||||||
|
pointer_y: i32,
|
||||||
|
) {
|
||||||
|
fill_rect(commands, VIEWPORT, COLOR_BG);
|
||||||
|
draw_panel(commands, viewport, COLOR_PANEL_DARK, COLOR_BORDER);
|
||||||
|
fill_rect(
|
||||||
|
commands,
|
||||||
|
Rect { x: viewport.x + 4, y: viewport.y + 24, w: viewport.w - 8, h: viewport.h - 28 },
|
||||||
|
color,
|
||||||
|
);
|
||||||
|
draw_buffer_text(commands, viewport.x + 10, viewport.y + 8, title, COLOR_TEXT);
|
||||||
|
draw_buffer_text(
|
||||||
|
commands,
|
||||||
|
viewport.x + 18,
|
||||||
|
viewport.y + 44,
|
||||||
|
"native fake shell",
|
||||||
|
COLOR_PANEL_DARK,
|
||||||
|
);
|
||||||
|
|
||||||
|
let close_hovered = rect_contains(CLOSE_BUTTON, pointer_x, pointer_y);
|
||||||
|
let close_fill = if close_hovered { COLOR_HILITE } else { COLOR_BUTTON };
|
||||||
|
fill_rect(commands, CLOSE_BUTTON, close_fill);
|
||||||
|
draw_rect(commands, CLOSE_BUTTON, COLOR_BORDER);
|
||||||
|
draw_buffer_text(commands, CLOSE_BUTTON.x + 5, CLOSE_BUTTON.y + 4, "x", COLOR_TEXT);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fill_rect(commands: &mut Vec<GfxUiCommand>, rect: Rect, color: Color) {
|
||||||
|
commands.push(GfxUiCommand::FillRect { rect, color });
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_rect(commands: &mut Vec<GfxUiCommand>, rect: Rect, color: Color) {
|
||||||
|
commands.push(GfxUiCommand::DrawLine {
|
||||||
|
x0: rect.x,
|
||||||
|
y0: rect.y,
|
||||||
|
x1: rect.x + rect.w - 1,
|
||||||
|
y1: rect.y,
|
||||||
|
color,
|
||||||
|
});
|
||||||
|
commands.push(GfxUiCommand::DrawLine {
|
||||||
|
x0: rect.x,
|
||||||
|
y0: rect.y + rect.h - 1,
|
||||||
|
x1: rect.x + rect.w - 1,
|
||||||
|
y1: rect.y + rect.h - 1,
|
||||||
|
color,
|
||||||
|
});
|
||||||
|
commands.push(GfxUiCommand::DrawLine {
|
||||||
|
x0: rect.x,
|
||||||
|
y0: rect.y,
|
||||||
|
x1: rect.x,
|
||||||
|
y1: rect.y + rect.h - 1,
|
||||||
|
color,
|
||||||
|
});
|
||||||
|
commands.push(GfxUiCommand::DrawLine {
|
||||||
|
x0: rect.x + rect.w - 1,
|
||||||
|
y0: rect.y,
|
||||||
|
x1: rect.x + rect.w - 1,
|
||||||
|
y1: rect.y + rect.h - 1,
|
||||||
|
color,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_panel(commands: &mut Vec<GfxUiCommand>, rect: Rect, fill: Color, border: Color) {
|
||||||
|
fill_rect(commands, rect, fill);
|
||||||
|
draw_rect(commands, rect, border);
|
||||||
|
draw_rect(
|
||||||
|
commands,
|
||||||
|
Rect { x: rect.x + 2, y: rect.y + 2, w: rect.w - 4, h: rect.h - 4 },
|
||||||
|
COLOR_MUTED,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_button(commands: &mut Vec<GfxUiCommand>, rect: Rect, label: &str, hovered: bool) {
|
||||||
|
let fill = if hovered { COLOR_BUTTON_ACTIVE } else { COLOR_BUTTON };
|
||||||
|
let border = if hovered { COLOR_HILITE } else { COLOR_BORDER };
|
||||||
|
fill_rect(commands, rect, fill);
|
||||||
|
draw_rect(commands, rect, border);
|
||||||
|
draw_rect(
|
||||||
|
commands,
|
||||||
|
Rect { x: rect.x + 3, y: rect.y + 3, w: rect.w - 6, h: rect.h - 6 },
|
||||||
|
COLOR_MUTED,
|
||||||
|
);
|
||||||
|
fill_rect(commands, Rect { x: rect.x + 12, y: rect.y + 8, w: 14, h: 16 }, border);
|
||||||
|
draw_rect(commands, Rect { x: rect.x + 34, y: rect.y + 8, w: 62, h: 16 }, COLOR_PANEL_DARK);
|
||||||
|
draw_buffer_text(commands, rect.x + 40, rect.y + 13, label, COLOR_TEXT);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_game_row(commands: &mut Vec<GfxUiCommand>, rect: Rect, label: &str, hovered: bool) {
|
||||||
|
let fill = if hovered { COLOR_BUTTON_ACTIVE } else { COLOR_PANEL_DARK };
|
||||||
|
let border = if hovered { COLOR_HILITE } else { COLOR_MUTED };
|
||||||
|
fill_rect(commands, rect, fill);
|
||||||
|
draw_rect(commands, rect, border);
|
||||||
|
draw_buffer_text(commands, rect.x + 8, rect.y + 7, label, COLOR_TEXT);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_suspended_game_kill_control(
|
||||||
|
commands: &mut Vec<GfxUiCommand>,
|
||||||
|
suspended_game: &SuspendedGameIndicator,
|
||||||
|
hovered: bool,
|
||||||
|
) {
|
||||||
|
let fill = if hovered { COLOR_KILL_ACTIVE } else { COLOR_KILL };
|
||||||
|
let border = if hovered { COLOR_HILITE } else { COLOR_BORDER };
|
||||||
|
fill_rect(commands, HUB_SUSPENDED_GAME_KILL_CONTROL, fill);
|
||||||
|
draw_rect(commands, HUB_SUSPENDED_GAME_KILL_CONTROL, border);
|
||||||
|
draw_buffer_text(
|
||||||
|
commands,
|
||||||
|
HUB_SUSPENDED_GAME_KILL_CONTROL.x + 8,
|
||||||
|
HUB_SUSPENDED_GAME_KILL_CONTROL.y + 8,
|
||||||
|
&fit_text_to_control(&suspended_game.title, HUB_SUSPENDED_GAME_KILL_CONTROL.w - 16),
|
||||||
|
COLOR_TEXT,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fit_text_to_control(text: &str, max_width: i32) -> String {
|
||||||
|
let max_chars = (max_width / 8).max(0) as usize;
|
||||||
|
if text.chars().count() <= max_chars {
|
||||||
|
return text.to_string();
|
||||||
|
}
|
||||||
|
|
||||||
|
if max_chars <= 2 {
|
||||||
|
return text.chars().take(max_chars).collect();
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut fitted: String = text.chars().take(max_chars - 2).collect();
|
||||||
|
fitted.push_str("..");
|
||||||
|
fitted
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_buffer_text(commands: &mut Vec<GfxUiCommand>, x: i32, y: i32, text: &str, color: Color) {
|
||||||
|
commands.push(GfxUiCommand::DrawText { x, y, text: text.to_string(), color });
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::task::TaskId;
|
||||||
|
use crate::windows::WindowOwner;
|
||||||
|
use prometeu_drivers::TestPlatform;
|
||||||
|
use prometeu_hal::{InputSignals, RuntimePlatform};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
fn focused_native_shell_fixture(
|
||||||
|
signals: &InputSignals,
|
||||||
|
) -> (PrometeuHub, SystemOS, TestPlatform) {
|
||||||
|
let hub = PrometeuHub::new();
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
let mut platform = TestPlatform::new();
|
||||||
|
|
||||||
|
{
|
||||||
|
let mut windows = os.windows();
|
||||||
|
let id = windows.add_window(
|
||||||
|
"ShellA".to_string(),
|
||||||
|
WindowOwner::Task(TaskId(7)),
|
||||||
|
SHELL_FRAME,
|
||||||
|
Color::GREEN,
|
||||||
|
);
|
||||||
|
windows.set_focus(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
platform.input_mut().pad_mut().begin_frame(signals);
|
||||||
|
platform.input_mut().touch_mut().begin_frame(signals);
|
||||||
|
|
||||||
|
(hub, os, platform)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn shell_a_button_click_emits_launch_action() {
|
||||||
|
assert_eq!(
|
||||||
|
action_for_click(
|
||||||
|
false,
|
||||||
|
HOME_BUTTONS[0].rect.x,
|
||||||
|
HOME_BUTTONS[0].rect.y,
|
||||||
|
true,
|
||||||
|
&[],
|
||||||
|
None
|
||||||
|
),
|
||||||
|
Some(SystemProfileAction::LaunchNativeShell(NativeShellApp::ShellA))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn shell_b_button_click_emits_launch_action() {
|
||||||
|
assert_eq!(
|
||||||
|
action_for_click(
|
||||||
|
false,
|
||||||
|
SHELL_B_BUTTON.x + SHELL_B_BUTTON.w - 1,
|
||||||
|
SHELL_B_BUTTON.y,
|
||||||
|
true,
|
||||||
|
&[],
|
||||||
|
None
|
||||||
|
),
|
||||||
|
Some(SystemProfileAction::LaunchNativeShell(NativeShellApp::ShellB))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn button_hit_test_excludes_right_and_bottom_edges() {
|
||||||
|
assert_eq!(
|
||||||
|
action_for_click(
|
||||||
|
false,
|
||||||
|
SHELL_A_BUTTON.x + SHELL_A_BUTTON.w,
|
||||||
|
SHELL_A_BUTTON.y,
|
||||||
|
true,
|
||||||
|
&[],
|
||||||
|
None
|
||||||
|
),
|
||||||
|
None
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
action_for_click(
|
||||||
|
false,
|
||||||
|
SHELL_A_BUTTON.x,
|
||||||
|
SHELL_A_BUTTON.y + SHELL_A_BUTTON.h,
|
||||||
|
true,
|
||||||
|
&[],
|
||||||
|
None
|
||||||
|
),
|
||||||
|
None
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn held_pointer_does_not_emit_click_action() {
|
||||||
|
assert_eq!(
|
||||||
|
action_for_click(false, SHELL_A_BUTTON.x, SHELL_A_BUTTON.y, false, &[], None),
|
||||||
|
None
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hub_starts_with_home_input_disarmed() {
|
||||||
|
let hub = PrometeuHub::new();
|
||||||
|
assert!(!hub.home_input_armed);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn game_row_click_emits_launch_game_action() {
|
||||||
|
let entry = crate::GameLibraryEntry {
|
||||||
|
manifest: prometeu_hal::cartridge::CartridgeManifest {
|
||||||
|
magic: "PMTU".to_string(),
|
||||||
|
cartridge_version: 1,
|
||||||
|
app_id: 42,
|
||||||
|
title: "Stress".to_string(),
|
||||||
|
app_version: "1.0.0".to_string(),
|
||||||
|
app_mode: prometeu_hal::app_mode::AppMode::Game,
|
||||||
|
capabilities: vec![],
|
||||||
|
},
|
||||||
|
title: "Stress".to_string(),
|
||||||
|
app_id: 42,
|
||||||
|
app_version: "1.0.0".to_string(),
|
||||||
|
path: PathBuf::from("test-cartridges/stress-console"),
|
||||||
|
discovered_at: std::time::SystemTime::UNIX_EPOCH,
|
||||||
|
};
|
||||||
|
|
||||||
|
let action = action_for_click(
|
||||||
|
false,
|
||||||
|
GAME_ROW_X,
|
||||||
|
GAME_ROW_Y,
|
||||||
|
true,
|
||||||
|
std::slice::from_ref(&entry),
|
||||||
|
None,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
action,
|
||||||
|
Some(SystemProfileAction::LaunchGame {
|
||||||
|
target: GameSwitchTarget {
|
||||||
|
path: entry.path.clone(),
|
||||||
|
app_id: 42,
|
||||||
|
title: "Stress".to_string(),
|
||||||
|
app_version: "1.0.0".to_string(),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn close_button_click_emits_close_only_in_shell() {
|
||||||
|
assert_eq!(
|
||||||
|
action_for_click(true, CLOSE_BUTTON.x, CLOSE_BUTTON.y, true, &[], None),
|
||||||
|
Some(SystemProfileAction::CloseShell)
|
||||||
|
);
|
||||||
|
assert_eq!(action_for_click(false, CLOSE_BUTTON.x, CLOSE_BUTTON.y, true, &[], None), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn home_layout_exposes_exactly_two_manual_shell_buttons() {
|
||||||
|
assert_eq!(HOME_BUTTONS.len(), 2);
|
||||||
|
assert_eq!(HOME_BUTTONS[0].label, "ShellA");
|
||||||
|
assert_eq!(HOME_BUTTONS[0].app, NativeShellApp::ShellA);
|
||||||
|
assert_eq!(HOME_BUTTONS[1].label, "ShellB");
|
||||||
|
assert_eq!(HOME_BUTTONS[1].app, NativeShellApp::ShellB);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn home_render_produces_shell_ui_packet_commands() {
|
||||||
|
let packet = render_home_packet(SHELL_A_BUTTON.x, SHELL_A_BUTTON.y, &[], None);
|
||||||
|
|
||||||
|
assert!(matches!(packet.commands.first(), Some(GfxUiCommand::Clear { .. })));
|
||||||
|
assert!(packet.commands.iter().any(|command| {
|
||||||
|
matches!(command, GfxUiCommand::DrawText { text, .. } if text == "PROMETEU HUB")
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resident_game_indicator_uses_only_resident_game_sessions() {
|
||||||
|
let mut os = SystemOS::new(None);
|
||||||
|
assert_eq!(resident_game_indicator(&mut os), None);
|
||||||
|
|
||||||
|
let shell = os.sessions().create_vm_shell_task(7, "VM Shell");
|
||||||
|
assert_eq!(resident_game_indicator(&mut os), None);
|
||||||
|
os.lifecycle().suspend_task(shell).expect("shell suspend should succeed");
|
||||||
|
assert_eq!(resident_game_indicator(&mut os), None);
|
||||||
|
|
||||||
|
let game = os.sessions().create_vm_game_task(42, "Stress Console");
|
||||||
|
os.lifecycle().suspend_task(game).expect("game suspend should succeed");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
resident_game_indicator(&mut os),
|
||||||
|
Some(SuspendedGameIndicator { title: "Stress Console".to_string() })
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn home_render_shows_suspended_game_kill_control_when_game_is_resident() {
|
||||||
|
let suspended_game = SuspendedGameIndicator { title: "Stress Console".to_string() };
|
||||||
|
let packet = render_home_packet(
|
||||||
|
HUB_SUSPENDED_GAME_KILL_CONTROL.x,
|
||||||
|
HUB_SUSPENDED_GAME_KILL_CONTROL.y,
|
||||||
|
&[],
|
||||||
|
Some(&suspended_game),
|
||||||
|
);
|
||||||
|
|
||||||
|
assert!(packet.commands.iter().any(|command| {
|
||||||
|
matches!(
|
||||||
|
command,
|
||||||
|
GfxUiCommand::FillRect { rect, color }
|
||||||
|
if *rect == HUB_SUSPENDED_GAME_KILL_CONTROL && *color == COLOR_KILL_ACTIVE
|
||||||
|
)
|
||||||
|
}));
|
||||||
|
assert!(packet.commands.iter().any(|command| {
|
||||||
|
matches!(
|
||||||
|
command,
|
||||||
|
GfxUiCommand::DrawText { x, y, text, .. }
|
||||||
|
if *x == HUB_SUSPENDED_GAME_KILL_CONTROL.x + 8
|
||||||
|
&& *y == HUB_SUSPENDED_GAME_KILL_CONTROL.y + 8
|
||||||
|
&& text == "Stress Console"
|
||||||
|
)
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn home_render_omits_suspended_game_kill_control_without_resident_game() {
|
||||||
|
let packet = render_home_packet(
|
||||||
|
HUB_SUSPENDED_GAME_KILL_CONTROL.x,
|
||||||
|
HUB_SUSPENDED_GAME_KILL_CONTROL.y,
|
||||||
|
&[],
|
||||||
|
None,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert!(!packet.commands.iter().any(|command| {
|
||||||
|
matches!(
|
||||||
|
command,
|
||||||
|
GfxUiCommand::FillRect { rect, color }
|
||||||
|
if *rect == HUB_SUSPENDED_GAME_KILL_CONTROL
|
||||||
|
&& (*color == COLOR_KILL || *color == COLOR_KILL_ACTIVE)
|
||||||
|
)
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn suspended_game_kill_control_click_emits_kill_action() {
|
||||||
|
let suspended_game = SuspendedGameIndicator { title: "Stress Console".to_string() };
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
action_for_click(
|
||||||
|
false,
|
||||||
|
HUB_SUSPENDED_GAME_KILL_CONTROL.x,
|
||||||
|
HUB_SUSPENDED_GAME_KILL_CONTROL.y,
|
||||||
|
true,
|
||||||
|
&[],
|
||||||
|
Some(&suspended_game),
|
||||||
|
),
|
||||||
|
Some(SystemProfileAction::KillResidentGame)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
action_for_click(
|
||||||
|
false,
|
||||||
|
HUB_SUSPENDED_GAME_KILL_CONTROL.x,
|
||||||
|
HUB_SUSPENDED_GAME_KILL_CONTROL.y,
|
||||||
|
true,
|
||||||
|
&[],
|
||||||
|
None,
|
||||||
|
),
|
||||||
|
None
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn suspended_game_kill_control_truncates_long_titles() {
|
||||||
|
let long_title =
|
||||||
|
SuspendedGameIndicator { title: "Extremely Long Resident Game Title".to_string() };
|
||||||
|
let packet = render_home_packet(0, 0, &[], Some(&long_title));
|
||||||
|
let label = packet
|
||||||
|
.commands
|
||||||
|
.iter()
|
||||||
|
.find_map(|command| match command {
|
||||||
|
GfxUiCommand::DrawText { x, y, text, .. }
|
||||||
|
if *x == HUB_SUSPENDED_GAME_KILL_CONTROL.x + 8
|
||||||
|
&& *y == HUB_SUSPENDED_GAME_KILL_CONTROL.y + 8 =>
|
||||||
|
{
|
||||||
|
Some(text)
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.expect("kill control text should render");
|
||||||
|
|
||||||
|
assert!(label.ends_with(".."));
|
||||||
|
assert!(label.chars().count() <= ((HUB_SUSPENDED_GAME_KILL_CONTROL.w - 16) / 8) as usize);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn shell_close_button_sits_inside_shell_frame() {
|
||||||
|
assert!(rect_contains(SHELL_FRAME, CLOSE_BUTTON.x, CLOSE_BUTTON.y));
|
||||||
|
assert!(rect_contains(
|
||||||
|
SHELL_FRAME,
|
||||||
|
CLOSE_BUTTON.x + CLOSE_BUTTON.w - 1,
|
||||||
|
CLOSE_BUTTON.y + CLOSE_BUTTON.h - 1
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn native_shell_profile_start_close_does_not_tick_vm() {
|
||||||
|
let signals = InputSignals { start_signal: true, ..Default::default() };
|
||||||
|
let (mut hub, mut os, mut platform) = focused_native_shell_fixture(&signals);
|
||||||
|
|
||||||
|
let tick_index_before_update = os.vm().tick_index();
|
||||||
|
let outcome = hub.update_native_shell_profile(&mut os, &mut platform);
|
||||||
|
|
||||||
|
assert_eq!(outcome.action, Some(SystemProfileAction::CloseShell));
|
||||||
|
assert!(outcome.crash.is_none());
|
||||||
|
assert_eq!(os.vm().tick_index(), tick_index_before_update);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn native_shell_profile_close_button_does_not_tick_vm() {
|
||||||
|
let signals = InputSignals {
|
||||||
|
f_signal: true,
|
||||||
|
x_pos: CLOSE_BUTTON.x,
|
||||||
|
y_pos: CLOSE_BUTTON.y,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let (mut hub, mut os, mut platform) = focused_native_shell_fixture(&signals);
|
||||||
|
|
||||||
|
let tick_index_before_update = os.vm().tick_index();
|
||||||
|
let outcome = hub.update_native_shell_profile(&mut os, &mut platform);
|
||||||
|
|
||||||
|
assert_eq!(outcome.action, Some(SystemProfileAction::CloseShell));
|
||||||
|
assert!(outcome.crash.is_none());
|
||||||
|
assert_eq!(os.vm().tick_index(), tick_index_before_update);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,83 +0,0 @@
|
|||||||
use prometeu_hal::color::Color;
|
|
||||||
use prometeu_hal::window::{Rect, Window, WindowId};
|
|
||||||
|
|
||||||
/// PROMETEU Window Manager.
|
|
||||||
pub struct WindowManager {
|
|
||||||
pub windows: Vec<Window>,
|
|
||||||
pub focused: Option<WindowId>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WindowManager {
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Self { windows: Vec::new(), focused: None }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn add_window(&mut self, title: String, viewport: Rect, color: Color) -> WindowId {
|
|
||||||
let id = WindowId(self.windows.len() as u32);
|
|
||||||
let window = Window { id, viewport, has_focus: false, title, color };
|
|
||||||
self.windows.push(window);
|
|
||||||
id
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn remove_window(&mut self, id: WindowId) {
|
|
||||||
self.windows.retain(|w| w.id != id);
|
|
||||||
if self.focused == Some(id) {
|
|
||||||
self.focused = None;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn remove_all_windows(&mut self) {
|
|
||||||
self.windows.clear();
|
|
||||||
self.focused = None;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_focus(&mut self, id: WindowId) {
|
|
||||||
self.focused = Some(id);
|
|
||||||
for window in &mut self.windows {
|
|
||||||
window.has_focus = window.id == id;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_window_manager_focus() {
|
|
||||||
let mut wm = WindowManager::new();
|
|
||||||
let id1 =
|
|
||||||
wm.add_window("Window 1".to_string(), Rect { x: 0, y: 0, w: 10, h: 10 }, Color::WHITE);
|
|
||||||
let id2 = wm.add_window(
|
|
||||||
"Window 2".to_string(),
|
|
||||||
Rect { x: 10, y: 10, w: 10, h: 10 },
|
|
||||||
Color::WHITE,
|
|
||||||
);
|
|
||||||
|
|
||||||
assert_eq!(wm.windows.len(), 2);
|
|
||||||
assert_eq!(wm.focused, None);
|
|
||||||
|
|
||||||
wm.set_focus(id1);
|
|
||||||
assert_eq!(wm.focused, Some(id1));
|
|
||||||
assert!(wm.windows[0].has_focus);
|
|
||||||
assert!(!wm.windows[1].has_focus);
|
|
||||||
|
|
||||||
wm.set_focus(id2);
|
|
||||||
assert_eq!(wm.focused, Some(id2));
|
|
||||||
assert!(!wm.windows[0].has_focus);
|
|
||||||
assert!(wm.windows[1].has_focus);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_window_manager_remove_window() {
|
|
||||||
let mut wm = WindowManager::new();
|
|
||||||
let id =
|
|
||||||
wm.add_window("Window".to_string(), Rect { x: 0, y: 0, w: 10, h: 10 }, Color::WHITE);
|
|
||||||
wm.set_focus(id);
|
|
||||||
assert_eq!(wm.focused, Some(id));
|
|
||||||
|
|
||||||
wm.remove_window(id);
|
|
||||||
assert_eq!(wm.windows.len(), 0);
|
|
||||||
assert_eq!(wm.focused, None);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,601 @@
|
|||||||
|
use std::collections::VecDeque;
|
||||||
|
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use std::sync::mpsc::{self, Receiver, RecvTimeoutError};
|
||||||
|
use std::sync::{Arc, Condvar, Mutex};
|
||||||
|
use std::thread::{self, JoinHandle};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
pub struct AsyncWorkJobId(u64);
|
||||||
|
|
||||||
|
impl AsyncWorkJobId {
|
||||||
|
pub const ZERO: Self = Self(0);
|
||||||
|
|
||||||
|
pub fn new(value: u64) -> Self {
|
||||||
|
Self(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get(self) -> u64 {
|
||||||
|
self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum AsyncWorkJobKind {
|
||||||
|
Asset,
|
||||||
|
Memcard,
|
||||||
|
Fs,
|
||||||
|
Test,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum AsyncWorkPriority {
|
||||||
|
MemcardCommitWrite,
|
||||||
|
FsWriteConfig,
|
||||||
|
AssetLoad,
|
||||||
|
NonCriticalReadList,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AsyncWorkPriority {
|
||||||
|
const fn rank(self) -> u8 {
|
||||||
|
match self {
|
||||||
|
Self::MemcardCommitWrite => 0,
|
||||||
|
Self::FsWriteConfig => 1,
|
||||||
|
Self::AssetLoad => 2,
|
||||||
|
Self::NonCriticalReadList => 3,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AsyncWorkJobKind {
|
||||||
|
pub const fn default_priority(self) -> AsyncWorkPriority {
|
||||||
|
match self {
|
||||||
|
Self::Memcard => AsyncWorkPriority::MemcardCommitWrite,
|
||||||
|
Self::Fs => AsyncWorkPriority::FsWriteConfig,
|
||||||
|
Self::Asset => AsyncWorkPriority::AssetLoad,
|
||||||
|
Self::Test => AsyncWorkPriority::NonCriticalReadList,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum AsyncWorkJobOutcome {
|
||||||
|
Completed,
|
||||||
|
Canceled,
|
||||||
|
Failed,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum AsyncWorkLaneError {
|
||||||
|
Shutdown,
|
||||||
|
WorkerPanic,
|
||||||
|
ShutdownTimeout,
|
||||||
|
InternalFailure,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct AsyncWorkLaneConfig {
|
||||||
|
pub shutdown_timeout: Duration,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for AsyncWorkLaneConfig {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self { shutdown_timeout: Duration::from_millis(250) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct AsyncWorkActiveJob {
|
||||||
|
pub id: AsyncWorkJobId,
|
||||||
|
pub kind: AsyncWorkJobKind,
|
||||||
|
pub priority: AsyncWorkPriority,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||||
|
pub struct AsyncWorkLaneTelemetry {
|
||||||
|
pub submitted_jobs: u64,
|
||||||
|
pub started_jobs: u64,
|
||||||
|
pub completed_jobs: u64,
|
||||||
|
pub canceled_jobs: u64,
|
||||||
|
pub failed_jobs: u64,
|
||||||
|
pub shutdown_discards: u64,
|
||||||
|
pub pending_depth: usize,
|
||||||
|
pub max_pending_depth: usize,
|
||||||
|
pub active_job_id: Option<AsyncWorkJobId>,
|
||||||
|
pub last_submitted_job_id: Option<AsyncWorkJobId>,
|
||||||
|
pub last_started_job_id: Option<AsyncWorkJobId>,
|
||||||
|
pub last_closed_job_id: Option<AsyncWorkJobId>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AsyncWorkLaneTelemetry {
|
||||||
|
fn record_submitted(&mut self, job_id: AsyncWorkJobId, pending_depth: usize) {
|
||||||
|
self.submitted_jobs += 1;
|
||||||
|
self.pending_depth = pending_depth;
|
||||||
|
self.max_pending_depth = self.max_pending_depth.max(pending_depth);
|
||||||
|
self.last_submitted_job_id = Some(job_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn record_started(&mut self, job_id: AsyncWorkJobId, pending_depth: usize) {
|
||||||
|
self.started_jobs += 1;
|
||||||
|
self.pending_depth = pending_depth;
|
||||||
|
self.active_job_id = Some(job_id);
|
||||||
|
self.last_started_job_id = Some(job_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn record_closed(&mut self, job_id: AsyncWorkJobId, outcome: AsyncWorkJobOutcome) {
|
||||||
|
match outcome {
|
||||||
|
AsyncWorkJobOutcome::Completed => self.completed_jobs += 1,
|
||||||
|
AsyncWorkJobOutcome::Canceled => self.canceled_jobs += 1,
|
||||||
|
AsyncWorkJobOutcome::Failed => self.failed_jobs += 1,
|
||||||
|
}
|
||||||
|
self.active_job_id = None;
|
||||||
|
self.last_closed_job_id = Some(job_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn record_shutdown_discards(&mut self, count: usize) {
|
||||||
|
self.shutdown_discards += count as u64;
|
||||||
|
self.pending_depth = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct AsyncWorkCancelToken {
|
||||||
|
canceled: Arc<AtomicBool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AsyncWorkCancelToken {
|
||||||
|
fn new() -> Self {
|
||||||
|
Self { canceled: Arc::new(AtomicBool::new(false)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn cancel(&self) {
|
||||||
|
self.canceled.store(true, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_canceled(&self) -> bool {
|
||||||
|
self.canceled.load(Ordering::Relaxed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct AsyncWorkJobContext {
|
||||||
|
pub job_id: AsyncWorkJobId,
|
||||||
|
pub kind: AsyncWorkJobKind,
|
||||||
|
pub priority: AsyncWorkPriority,
|
||||||
|
cancel_token: AsyncWorkCancelToken,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AsyncWorkJobContext {
|
||||||
|
pub fn is_canceled(&self) -> bool {
|
||||||
|
self.cancel_token.is_canceled()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type AsyncWorkFn = Box<dyn FnOnce(AsyncWorkJobContext) -> AsyncWorkJobOutcome + Send + 'static>;
|
||||||
|
|
||||||
|
struct PendingAsyncWorkJob {
|
||||||
|
id: AsyncWorkJobId,
|
||||||
|
kind: AsyncWorkJobKind,
|
||||||
|
priority: AsyncWorkPriority,
|
||||||
|
cancel_token: AsyncWorkCancelToken,
|
||||||
|
work: AsyncWorkFn,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct RunningAsyncWorkJob {
|
||||||
|
id: AsyncWorkJobId,
|
||||||
|
kind: AsyncWorkJobKind,
|
||||||
|
priority: AsyncWorkPriority,
|
||||||
|
cancel_token: AsyncWorkCancelToken,
|
||||||
|
work: AsyncWorkFn,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct AsyncWorkLaneState {
|
||||||
|
next_job_id: u64,
|
||||||
|
pending: VecDeque<PendingAsyncWorkJob>,
|
||||||
|
active: Option<AsyncWorkActiveJob>,
|
||||||
|
active_cancel_token: Option<AsyncWorkCancelToken>,
|
||||||
|
shutdown_requested: bool,
|
||||||
|
telemetry: AsyncWorkLaneTelemetry,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct AsyncWorkLane {
|
||||||
|
state: Mutex<AsyncWorkLaneState>,
|
||||||
|
ready: Condvar,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AsyncWorkLane {
|
||||||
|
pub fn submit(
|
||||||
|
&self,
|
||||||
|
kind: AsyncWorkJobKind,
|
||||||
|
work: impl FnOnce(AsyncWorkJobContext) -> AsyncWorkJobOutcome + Send + 'static,
|
||||||
|
) -> Result<AsyncWorkJobId, AsyncWorkLaneError> {
|
||||||
|
self.submit_with_priority(kind, kind.default_priority(), work)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn submit_with_priority(
|
||||||
|
&self,
|
||||||
|
kind: AsyncWorkJobKind,
|
||||||
|
priority: AsyncWorkPriority,
|
||||||
|
work: impl FnOnce(AsyncWorkJobContext) -> AsyncWorkJobOutcome + Send + 'static,
|
||||||
|
) -> Result<AsyncWorkJobId, AsyncWorkLaneError> {
|
||||||
|
let mut state = self.state.lock().map_err(|_| AsyncWorkLaneError::InternalFailure)?;
|
||||||
|
if state.shutdown_requested {
|
||||||
|
return Err(AsyncWorkLaneError::Shutdown);
|
||||||
|
}
|
||||||
|
|
||||||
|
state.next_job_id += 1;
|
||||||
|
let id = AsyncWorkJobId::new(state.next_job_id);
|
||||||
|
let cancel_token = AsyncWorkCancelToken::new();
|
||||||
|
let job = PendingAsyncWorkJob { id, kind, priority, cancel_token, work: Box::new(work) };
|
||||||
|
let insert_at = state
|
||||||
|
.pending
|
||||||
|
.iter()
|
||||||
|
.position(|pending| priority.rank() < pending.priority.rank())
|
||||||
|
.unwrap_or(state.pending.len());
|
||||||
|
state.pending.insert(insert_at, job);
|
||||||
|
let pending_depth = state.pending.len();
|
||||||
|
state.telemetry.record_submitted(id, pending_depth);
|
||||||
|
self.ready.notify_one();
|
||||||
|
Ok(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn submit_memcard_commit_write(
|
||||||
|
&self,
|
||||||
|
work: impl FnOnce(AsyncWorkJobContext) -> AsyncWorkJobOutcome + Send + 'static,
|
||||||
|
) -> Result<AsyncWorkJobId, AsyncWorkLaneError> {
|
||||||
|
self.submit_with_priority(
|
||||||
|
AsyncWorkJobKind::Memcard,
|
||||||
|
AsyncWorkPriority::MemcardCommitWrite,
|
||||||
|
work,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn submit_fs_write_config(
|
||||||
|
&self,
|
||||||
|
work: impl FnOnce(AsyncWorkJobContext) -> AsyncWorkJobOutcome + Send + 'static,
|
||||||
|
) -> Result<AsyncWorkJobId, AsyncWorkLaneError> {
|
||||||
|
self.submit_with_priority(AsyncWorkJobKind::Fs, AsyncWorkPriority::FsWriteConfig, work)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn submit_asset_load(
|
||||||
|
&self,
|
||||||
|
work: impl FnOnce(AsyncWorkJobContext) -> AsyncWorkJobOutcome + Send + 'static,
|
||||||
|
) -> Result<AsyncWorkJobId, AsyncWorkLaneError> {
|
||||||
|
self.submit_with_priority(AsyncWorkJobKind::Asset, AsyncWorkPriority::AssetLoad, work)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn submit_non_critical_read_list(
|
||||||
|
&self,
|
||||||
|
kind: AsyncWorkJobKind,
|
||||||
|
work: impl FnOnce(AsyncWorkJobContext) -> AsyncWorkJobOutcome + Send + 'static,
|
||||||
|
) -> Result<AsyncWorkJobId, AsyncWorkLaneError> {
|
||||||
|
self.submit_with_priority(kind, AsyncWorkPriority::NonCriticalReadList, work)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn request_cancel(&self, job_id: AsyncWorkJobId) -> bool {
|
||||||
|
let state = self.state.lock().unwrap();
|
||||||
|
if let Some(token) = state
|
||||||
|
.active
|
||||||
|
.filter(|active| active.id == job_id)
|
||||||
|
.and(state.active_cancel_token.as_ref())
|
||||||
|
{
|
||||||
|
token.cancel();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
for pending in &state.pending {
|
||||||
|
if pending.id == job_id {
|
||||||
|
pending.cancel_token.cancel();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn active_job(&self) -> Option<AsyncWorkActiveJob> {
|
||||||
|
self.state.lock().unwrap().active
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn pending_depth(&self) -> usize {
|
||||||
|
self.state.lock().unwrap().pending.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn telemetry(&self) -> AsyncWorkLaneTelemetry {
|
||||||
|
self.state.lock().unwrap().telemetry
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn request_shutdown(&self) {
|
||||||
|
let mut state = self.state.lock().unwrap();
|
||||||
|
state.shutdown_requested = true;
|
||||||
|
if let Some(token) = &state.active_cancel_token {
|
||||||
|
token.cancel();
|
||||||
|
}
|
||||||
|
self.ready.notify_all();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wait_take(&self) -> Option<RunningAsyncWorkJob> {
|
||||||
|
self.wait_take_with_hook(|| {})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wait_take_with_hook(&self, mut before_wait: impl FnMut()) -> Option<RunningAsyncWorkJob> {
|
||||||
|
let mut state = self.state.lock().unwrap();
|
||||||
|
loop {
|
||||||
|
if state.shutdown_requested {
|
||||||
|
let discarded = state.pending.len();
|
||||||
|
state.pending.clear();
|
||||||
|
state.telemetry.record_shutdown_discards(discarded);
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(pending) = state.pending.pop_front() {
|
||||||
|
let active = AsyncWorkActiveJob {
|
||||||
|
id: pending.id,
|
||||||
|
kind: pending.kind,
|
||||||
|
priority: pending.priority,
|
||||||
|
};
|
||||||
|
state.active = Some(active);
|
||||||
|
state.active_cancel_token = Some(pending.cancel_token.clone());
|
||||||
|
let pending_depth = state.pending.len();
|
||||||
|
state.telemetry.record_started(pending.id, pending_depth);
|
||||||
|
return Some(RunningAsyncWorkJob {
|
||||||
|
id: pending.id,
|
||||||
|
kind: pending.kind,
|
||||||
|
priority: pending.priority,
|
||||||
|
cancel_token: pending.cancel_token,
|
||||||
|
work: pending.work,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
before_wait();
|
||||||
|
state = self.ready.wait(state).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn record_finished(&self, job_id: AsyncWorkJobId, outcome: AsyncWorkJobOutcome) {
|
||||||
|
let mut state = self.state.lock().unwrap();
|
||||||
|
if state.active.is_some_and(|active| active.id == job_id) {
|
||||||
|
state.active = None;
|
||||||
|
state.active_cancel_token = None;
|
||||||
|
}
|
||||||
|
state.telemetry.record_closed(job_id, outcome);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct AsyncWorkLaneController {
|
||||||
|
config: AsyncWorkLaneConfig,
|
||||||
|
lane: Arc<AsyncWorkLane>,
|
||||||
|
handle: Option<JoinHandle<()>>,
|
||||||
|
done_rx: Receiver<Result<(), AsyncWorkLaneError>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AsyncWorkLaneController {
|
||||||
|
pub fn start(config: AsyncWorkLaneConfig, lane: Arc<AsyncWorkLane>) -> Self {
|
||||||
|
let worker_lane = Arc::clone(&lane);
|
||||||
|
let (done_tx, done_rx) = mpsc::channel();
|
||||||
|
let handle = thread::spawn(move || {
|
||||||
|
let result = catch_unwind(AssertUnwindSafe(|| run_async_work_loop(worker_lane)))
|
||||||
|
.map_err(|_| AsyncWorkLaneError::WorkerPanic);
|
||||||
|
let _ = done_tx.send(result);
|
||||||
|
});
|
||||||
|
|
||||||
|
Self { config, lane, handle: Some(handle), done_rx }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn lane(&self) -> Arc<AsyncWorkLane> {
|
||||||
|
Arc::clone(&self.lane)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn stop(&mut self) -> Result<(), AsyncWorkLaneError> {
|
||||||
|
self.lane.request_shutdown();
|
||||||
|
match self.done_rx.recv_timeout(self.config.shutdown_timeout) {
|
||||||
|
Ok(result) => {
|
||||||
|
if let Some(handle) = self.handle.take()
|
||||||
|
&& handle.join().is_err()
|
||||||
|
{
|
||||||
|
return Err(AsyncWorkLaneError::WorkerPanic);
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
Err(RecvTimeoutError::Timeout) => Err(AsyncWorkLaneError::ShutdownTimeout),
|
||||||
|
Err(RecvTimeoutError::Disconnected) => Err(AsyncWorkLaneError::InternalFailure),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for AsyncWorkLaneController {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if self.handle.is_some() {
|
||||||
|
let _ = self.stop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run_async_work_loop(lane: Arc<AsyncWorkLane>) {
|
||||||
|
while let Some(job) = lane.wait_take() {
|
||||||
|
let context = AsyncWorkJobContext {
|
||||||
|
job_id: job.id,
|
||||||
|
kind: job.kind,
|
||||||
|
priority: job.priority,
|
||||||
|
cancel_token: job.cancel_token,
|
||||||
|
};
|
||||||
|
let result = catch_unwind(AssertUnwindSafe(|| (job.work)(context)))
|
||||||
|
.unwrap_or(AsyncWorkJobOutcome::Failed);
|
||||||
|
lane.record_finished(job.id, result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::sync::mpsc;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn async_work_lane_runs_jobs_in_submission_order() {
|
||||||
|
let lane = Arc::new(AsyncWorkLane::default());
|
||||||
|
let mut controller =
|
||||||
|
AsyncWorkLaneController::start(AsyncWorkLaneConfig::default(), Arc::clone(&lane));
|
||||||
|
let (tx, rx) = mpsc::channel();
|
||||||
|
|
||||||
|
lane.submit(AsyncWorkJobKind::Test, {
|
||||||
|
let tx = tx.clone();
|
||||||
|
move |_| {
|
||||||
|
tx.send(1).unwrap();
|
||||||
|
AsyncWorkJobOutcome::Completed
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
lane.submit(AsyncWorkJobKind::Test, {
|
||||||
|
let tx = tx.clone();
|
||||||
|
move |_| {
|
||||||
|
tx.send(2).unwrap();
|
||||||
|
AsyncWorkJobOutcome::Completed
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(rx.recv().unwrap(), 1);
|
||||||
|
assert_eq!(rx.recv().unwrap(), 2);
|
||||||
|
controller.stop().unwrap();
|
||||||
|
|
||||||
|
let telemetry = lane.telemetry();
|
||||||
|
assert_eq!(telemetry.submitted_jobs, 2);
|
||||||
|
assert_eq!(telemetry.started_jobs, 2);
|
||||||
|
assert_eq!(telemetry.completed_jobs, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn async_work_lane_runs_higher_priority_io_before_assets() {
|
||||||
|
let lane = Arc::new(AsyncWorkLane::default());
|
||||||
|
let (tx, rx) = mpsc::channel();
|
||||||
|
|
||||||
|
lane.submit_asset_load({
|
||||||
|
let tx = tx.clone();
|
||||||
|
move |ctx| {
|
||||||
|
tx.send((ctx.kind, ctx.priority)).unwrap();
|
||||||
|
AsyncWorkJobOutcome::Completed
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
lane.submit_non_critical_read_list(AsyncWorkJobKind::Fs, {
|
||||||
|
let tx = tx.clone();
|
||||||
|
move |ctx| {
|
||||||
|
tx.send((ctx.kind, ctx.priority)).unwrap();
|
||||||
|
AsyncWorkJobOutcome::Completed
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
lane.submit_memcard_commit_write({
|
||||||
|
let tx = tx.clone();
|
||||||
|
move |ctx| {
|
||||||
|
tx.send((ctx.kind, ctx.priority)).unwrap();
|
||||||
|
AsyncWorkJobOutcome::Completed
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
lane.submit_fs_write_config({
|
||||||
|
let tx = tx.clone();
|
||||||
|
move |ctx| {
|
||||||
|
tx.send((ctx.kind, ctx.priority)).unwrap();
|
||||||
|
AsyncWorkJobOutcome::Completed
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let mut controller =
|
||||||
|
AsyncWorkLaneController::start(AsyncWorkLaneConfig::default(), Arc::clone(&lane));
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
rx.recv().unwrap(),
|
||||||
|
(AsyncWorkJobKind::Memcard, AsyncWorkPriority::MemcardCommitWrite)
|
||||||
|
);
|
||||||
|
assert_eq!(rx.recv().unwrap(), (AsyncWorkJobKind::Fs, AsyncWorkPriority::FsWriteConfig));
|
||||||
|
assert_eq!(rx.recv().unwrap(), (AsyncWorkJobKind::Asset, AsyncWorkPriority::AssetLoad));
|
||||||
|
assert_eq!(
|
||||||
|
rx.recv().unwrap(),
|
||||||
|
(AsyncWorkJobKind::Fs, AsyncWorkPriority::NonCriticalReadList)
|
||||||
|
);
|
||||||
|
controller.stop().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn async_work_lane_has_one_active_job() {
|
||||||
|
let lane = Arc::new(AsyncWorkLane::default());
|
||||||
|
let mut controller =
|
||||||
|
AsyncWorkLaneController::start(AsyncWorkLaneConfig::default(), Arc::clone(&lane));
|
||||||
|
let (first_started_tx, first_started_rx) = mpsc::channel();
|
||||||
|
let (release_first_tx, release_first_rx) = mpsc::channel();
|
||||||
|
let (second_started_tx, second_started_rx) = mpsc::channel();
|
||||||
|
|
||||||
|
let first = lane
|
||||||
|
.submit(AsyncWorkJobKind::Test, move |_| {
|
||||||
|
first_started_tx.send(()).unwrap();
|
||||||
|
release_first_rx.recv().unwrap();
|
||||||
|
AsyncWorkJobOutcome::Completed
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
let second = lane
|
||||||
|
.submit(AsyncWorkJobKind::Test, move |_| {
|
||||||
|
second_started_tx.send(()).unwrap();
|
||||||
|
AsyncWorkJobOutcome::Completed
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
first_started_rx.recv().unwrap();
|
||||||
|
assert_eq!(lane.active_job().unwrap().id, first);
|
||||||
|
assert_eq!(lane.pending_depth(), 1);
|
||||||
|
assert!(second_started_rx.try_recv().is_err());
|
||||||
|
|
||||||
|
release_first_tx.send(()).unwrap();
|
||||||
|
second_started_rx.recv().unwrap();
|
||||||
|
assert_eq!(lane.telemetry().last_started_job_id, Some(second));
|
||||||
|
controller.stop().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn async_work_lane_supports_cooperative_cancellation() {
|
||||||
|
let lane = Arc::new(AsyncWorkLane::default());
|
||||||
|
let mut controller =
|
||||||
|
AsyncWorkLaneController::start(AsyncWorkLaneConfig::default(), Arc::clone(&lane));
|
||||||
|
let (started_tx, started_rx) = mpsc::channel();
|
||||||
|
|
||||||
|
let job_id = lane
|
||||||
|
.submit(AsyncWorkJobKind::Test, move |ctx| {
|
||||||
|
started_tx.send(()).unwrap();
|
||||||
|
while !ctx.is_canceled() {
|
||||||
|
std::thread::yield_now();
|
||||||
|
}
|
||||||
|
AsyncWorkJobOutcome::Canceled
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
started_rx.recv().unwrap();
|
||||||
|
assert!(lane.request_cancel(job_id));
|
||||||
|
controller.stop().unwrap();
|
||||||
|
assert_eq!(lane.telemetry().canceled_jobs, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn async_work_lane_rejects_submit_after_shutdown() {
|
||||||
|
let lane = Arc::new(AsyncWorkLane::default());
|
||||||
|
lane.request_shutdown();
|
||||||
|
|
||||||
|
let result = lane.submit(AsyncWorkJobKind::Test, |_| AsyncWorkJobOutcome::Completed);
|
||||||
|
assert_eq!(result, Err(AsyncWorkLaneError::Shutdown));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn async_work_lane_shutdown_discards_pending_jobs() {
|
||||||
|
let lane = Arc::new(AsyncWorkLane::default());
|
||||||
|
lane.submit(AsyncWorkJobKind::Test, |_| AsyncWorkJobOutcome::Completed).unwrap();
|
||||||
|
assert_eq!(lane.pending_depth(), 1);
|
||||||
|
|
||||||
|
lane.request_shutdown();
|
||||||
|
assert!(lane.wait_take().is_none());
|
||||||
|
assert_eq!(lane.pending_depth(), 0);
|
||||||
|
assert_eq!(lane.telemetry().shutdown_discards, 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,330 @@
|
|||||||
|
use crate::task::TaskId;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum ForegroundOwner {
|
||||||
|
Hub,
|
||||||
|
Game(TaskId),
|
||||||
|
Shell(TaskId),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum ResidentGameState {
|
||||||
|
Foreground,
|
||||||
|
PauseRequested { remaining_ticks: u8 },
|
||||||
|
ResumeRequested,
|
||||||
|
PausedSuspended,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct ResidentGame {
|
||||||
|
pub task_id: TaskId,
|
||||||
|
pub state: ResidentGameState,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum ForegroundStackError {
|
||||||
|
ResidentGameAlreadyExists { existing: TaskId, requested: TaskId },
|
||||||
|
ForegroundShellAlreadyExists { existing: TaskId, requested: TaskId },
|
||||||
|
TaskIsNotResidentGame(TaskId),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct ForegroundStack {
|
||||||
|
owner: ForegroundOwner,
|
||||||
|
resident_game: Option<ResidentGame>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for ForegroundStack {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self { owner: ForegroundOwner::Hub, resident_game: None }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ForegroundStack {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn owner(&self) -> ForegroundOwner {
|
||||||
|
self.owner
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn resident_game(&self) -> Option<ResidentGame> {
|
||||||
|
self.resident_game
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn resident_game_task(&self) -> Option<TaskId> {
|
||||||
|
self.resident_game.map(|game| game.task_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_game_foreground(&mut self, task_id: TaskId) -> Result<(), ForegroundStackError> {
|
||||||
|
if let Some(game) = self.resident_game
|
||||||
|
&& game.task_id != task_id
|
||||||
|
{
|
||||||
|
return Err(ForegroundStackError::ResidentGameAlreadyExists {
|
||||||
|
existing: game.task_id,
|
||||||
|
requested: task_id,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
self.resident_game = Some(ResidentGame { task_id, state: ResidentGameState::Foreground });
|
||||||
|
self.owner = ForegroundOwner::Game(task_id);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn request_home_from_game(
|
||||||
|
&mut self,
|
||||||
|
task_id: TaskId,
|
||||||
|
pause_budget_ticks: u8,
|
||||||
|
) -> Result<(), ForegroundStackError> {
|
||||||
|
match self.resident_game {
|
||||||
|
Some(game) if game.task_id == task_id => {
|
||||||
|
if !matches!(
|
||||||
|
game.state,
|
||||||
|
ResidentGameState::PauseRequested { .. } | ResidentGameState::PausedSuspended
|
||||||
|
) {
|
||||||
|
self.resident_game = Some(ResidentGame {
|
||||||
|
task_id,
|
||||||
|
state: ResidentGameState::PauseRequested {
|
||||||
|
remaining_ticks: pause_budget_ticks.max(1),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
_ => Err(ForegroundStackError::TaskIsNotResidentGame(task_id)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn advance_pause_budget(&mut self, task_id: TaskId) -> Result<bool, ForegroundStackError> {
|
||||||
|
match self.resident_game {
|
||||||
|
Some(game)
|
||||||
|
if game.task_id == task_id
|
||||||
|
&& matches!(
|
||||||
|
game.state,
|
||||||
|
ResidentGameState::PauseRequested { remaining_ticks: 1 }
|
||||||
|
) =>
|
||||||
|
{
|
||||||
|
self.resident_game =
|
||||||
|
Some(ResidentGame { task_id, state: ResidentGameState::PausedSuspended });
|
||||||
|
self.owner = ForegroundOwner::Hub;
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
Some(game)
|
||||||
|
if game.task_id == task_id
|
||||||
|
&& matches!(game.state, ResidentGameState::PauseRequested { .. }) =>
|
||||||
|
{
|
||||||
|
let ResidentGameState::PauseRequested { remaining_ticks } = game.state else {
|
||||||
|
unreachable!();
|
||||||
|
};
|
||||||
|
self.resident_game = Some(ResidentGame {
|
||||||
|
task_id,
|
||||||
|
state: ResidentGameState::PauseRequested {
|
||||||
|
remaining_ticks: remaining_ticks.saturating_sub(1).max(1),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
Ok(false)
|
||||||
|
}
|
||||||
|
Some(game) if game.task_id == task_id => Ok(false),
|
||||||
|
_ => Err(ForegroundStackError::TaskIsNotResidentGame(task_id)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn request_resume_game(&mut self, task_id: TaskId) -> Result<(), ForegroundStackError> {
|
||||||
|
match self.resident_game {
|
||||||
|
Some(game) if game.task_id == task_id => {
|
||||||
|
self.resident_game =
|
||||||
|
Some(ResidentGame { task_id, state: ResidentGameState::ResumeRequested });
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
_ => Err(ForegroundStackError::TaskIsNotResidentGame(task_id)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn complete_resume_game(&mut self, task_id: TaskId) -> Result<(), ForegroundStackError> {
|
||||||
|
match self.resident_game {
|
||||||
|
Some(game) if game.task_id == task_id => {
|
||||||
|
self.resident_game =
|
||||||
|
Some(ResidentGame { task_id, state: ResidentGameState::Foreground });
|
||||||
|
self.owner = ForegroundOwner::Game(task_id);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
_ => Err(ForegroundStackError::TaskIsNotResidentGame(task_id)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_shell_foreground(&mut self, task_id: TaskId) -> Result<(), ForegroundStackError> {
|
||||||
|
if let ForegroundOwner::Shell(existing) = self.owner
|
||||||
|
&& existing != task_id
|
||||||
|
{
|
||||||
|
return Err(ForegroundStackError::ForegroundShellAlreadyExists {
|
||||||
|
existing,
|
||||||
|
requested: task_id,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(game) = self.resident_game {
|
||||||
|
self.resident_game = Some(ResidentGame {
|
||||||
|
task_id: game.task_id,
|
||||||
|
state: ResidentGameState::PausedSuspended,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
self.owner = ForegroundOwner::Shell(task_id);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn return_to_hub(&mut self) {
|
||||||
|
self.owner = ForegroundOwner::Hub;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clear_resident_game(&mut self, task_id: TaskId) {
|
||||||
|
if self.resident_game_task() == Some(task_id) {
|
||||||
|
self.resident_game = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.owner == ForegroundOwner::Game(task_id) {
|
||||||
|
self.owner = ForegroundOwner::Hub;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn foreground_stack_starts_at_hub() {
|
||||||
|
let stack = ForegroundStack::new();
|
||||||
|
|
||||||
|
assert_eq!(stack.owner(), ForegroundOwner::Hub);
|
||||||
|
assert_eq!(stack.resident_game(), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn setting_game_foreground_registers_resident_game() {
|
||||||
|
let mut stack = ForegroundStack::new();
|
||||||
|
let game = TaskId(7);
|
||||||
|
|
||||||
|
stack.set_game_foreground(game).expect("game should become foreground");
|
||||||
|
|
||||||
|
assert_eq!(stack.owner(), ForegroundOwner::Game(game));
|
||||||
|
assert_eq!(
|
||||||
|
stack.resident_game(),
|
||||||
|
Some(ResidentGame { task_id: game, state: ResidentGameState::Foreground })
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn second_resident_game_is_rejected() {
|
||||||
|
let mut stack = ForegroundStack::new();
|
||||||
|
|
||||||
|
stack.set_game_foreground(TaskId(1)).expect("first game should be accepted");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
stack.set_game_foreground(TaskId(2)),
|
||||||
|
Err(ForegroundStackError::ResidentGameAlreadyExists {
|
||||||
|
existing: TaskId(1),
|
||||||
|
requested: TaskId(2),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn home_request_moves_resident_game_to_pause_requested() {
|
||||||
|
let mut stack = ForegroundStack::new();
|
||||||
|
let game = TaskId(3);
|
||||||
|
|
||||||
|
stack.set_game_foreground(game).expect("game should be foreground");
|
||||||
|
stack.request_home_from_game(game, 2).expect("home request should pause game");
|
||||||
|
|
||||||
|
assert_eq!(stack.owner(), ForegroundOwner::Game(game));
|
||||||
|
assert_eq!(
|
||||||
|
stack.resident_game(),
|
||||||
|
Some(ResidentGame {
|
||||||
|
task_id: game,
|
||||||
|
state: ResidentGameState::PauseRequested { remaining_ticks: 2 },
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pause_budget_expiry_suspends_game_and_returns_to_hub() {
|
||||||
|
let mut stack = ForegroundStack::new();
|
||||||
|
let game = TaskId(3);
|
||||||
|
|
||||||
|
stack.set_game_foreground(game).expect("game should be foreground");
|
||||||
|
stack.request_home_from_game(game, 1).expect("home request should pause game");
|
||||||
|
|
||||||
|
assert!(stack.advance_pause_budget(game).expect("budget should advance"));
|
||||||
|
assert_eq!(stack.owner(), ForegroundOwner::Hub);
|
||||||
|
assert_eq!(
|
||||||
|
stack.resident_game(),
|
||||||
|
Some(ResidentGame { task_id: game, state: ResidentGameState::PausedSuspended })
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pause_budget_decrements_before_expiry() {
|
||||||
|
let mut stack = ForegroundStack::new();
|
||||||
|
let game = TaskId(3);
|
||||||
|
|
||||||
|
stack.set_game_foreground(game).expect("game should be foreground");
|
||||||
|
stack.request_home_from_game(game, 2).expect("home request should pause game");
|
||||||
|
|
||||||
|
assert!(!stack.advance_pause_budget(game).expect("budget should advance"));
|
||||||
|
assert_eq!(stack.owner(), ForegroundOwner::Game(game));
|
||||||
|
assert_eq!(
|
||||||
|
stack.resident_game(),
|
||||||
|
Some(ResidentGame {
|
||||||
|
task_id: game,
|
||||||
|
state: ResidentGameState::PauseRequested { remaining_ticks: 1 },
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
assert!(stack.advance_pause_budget(game).expect("budget should expire"));
|
||||||
|
assert_eq!(stack.owner(), ForegroundOwner::Hub);
|
||||||
|
assert_eq!(
|
||||||
|
stack.resident_game(),
|
||||||
|
Some(ResidentGame { task_id: game, state: ResidentGameState::PausedSuspended })
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resume_request_precedes_game_foreground_restore() {
|
||||||
|
let mut stack = ForegroundStack::new();
|
||||||
|
let game = TaskId(3);
|
||||||
|
|
||||||
|
stack.set_game_foreground(game).expect("game should be foreground");
|
||||||
|
stack.request_home_from_game(game, 1).expect("home request should pause game");
|
||||||
|
stack.advance_pause_budget(game).expect("budget should expire");
|
||||||
|
|
||||||
|
stack.request_resume_game(game).expect("resume should be requested");
|
||||||
|
assert_eq!(stack.owner(), ForegroundOwner::Hub);
|
||||||
|
assert_eq!(
|
||||||
|
stack.resident_game(),
|
||||||
|
Some(ResidentGame { task_id: game, state: ResidentGameState::ResumeRequested })
|
||||||
|
);
|
||||||
|
|
||||||
|
stack.complete_resume_game(game).expect("resume should complete");
|
||||||
|
assert_eq!(stack.owner(), ForegroundOwner::Game(game));
|
||||||
|
assert_eq!(
|
||||||
|
stack.resident_game(),
|
||||||
|
Some(ResidentGame { task_id: game, state: ResidentGameState::Foreground })
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn shell_foreground_keeps_resident_game() {
|
||||||
|
let mut stack = ForegroundStack::new();
|
||||||
|
let game = TaskId(3);
|
||||||
|
let shell = TaskId(4);
|
||||||
|
|
||||||
|
stack.set_game_foreground(game).expect("game should be foreground");
|
||||||
|
stack.request_home_from_game(game, 1).expect("home request should suspend game");
|
||||||
|
stack.advance_pause_budget(game).expect("budget should expire");
|
||||||
|
stack.set_shell_foreground(shell).expect("shell should become foreground");
|
||||||
|
|
||||||
|
assert_eq!(stack.owner(), ForegroundOwner::Shell(shell));
|
||||||
|
assert_eq!(stack.resident_game_task(), Some(game));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,4 +8,4 @@ pub use fs_backend::FsBackend;
|
|||||||
pub use fs_entry::FsEntry;
|
pub use fs_entry::FsEntry;
|
||||||
pub use fs_error::FsError;
|
pub use fs_error::FsError;
|
||||||
pub use fs_state::FsState;
|
pub use fs_state::FsState;
|
||||||
pub use virtual_fs::VirtualFS;
|
pub use virtual_fs::{FsAsyncLaneOperation, VirtualFS};
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
use crate::fs::{FsBackend, FsEntry, FsError};
|
use crate::fs::{FsBackend, FsEntry, FsError};
|
||||||
|
use crate::services::async_work::{AsyncWorkJobKind, AsyncWorkPriority};
|
||||||
|
|
||||||
/// Virtual Filesystem (VFS) interface for Prometeu.
|
/// Virtual Filesystem (VFS) interface for Prometeu.
|
||||||
///
|
///
|
||||||
@@ -13,6 +14,29 @@ pub struct VirtualFS {
|
|||||||
backend: Option<Box<dyn FsBackend>>,
|
backend: Option<Box<dyn FsBackend>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum FsAsyncLaneOperation {
|
||||||
|
Write,
|
||||||
|
Delete,
|
||||||
|
Config,
|
||||||
|
Read,
|
||||||
|
ListDir,
|
||||||
|
Exists,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FsAsyncLaneOperation {
|
||||||
|
pub const fn job_kind(self) -> AsyncWorkJobKind {
|
||||||
|
AsyncWorkJobKind::Fs
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const fn priority(self) -> AsyncWorkPriority {
|
||||||
|
match self {
|
||||||
|
Self::Write | Self::Delete | Self::Config => AsyncWorkPriority::FsWriteConfig,
|
||||||
|
Self::Read | Self::ListDir | Self::Exists => AsyncWorkPriority::NonCriticalReadList,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl Default for VirtualFS {
|
impl Default for VirtualFS {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self::new()
|
Self::new()
|
||||||
@@ -242,4 +266,18 @@ mod tests {
|
|||||||
assert!(matches!(vfs.delete("/"), Err(FsError::PermissionDenied)));
|
assert!(matches!(vfs.delete("/"), Err(FsError::PermissionDenied)));
|
||||||
assert_eq!(calls.delete.load(Ordering::Relaxed), 0);
|
assert_eq!(calls.delete.load(Ordering::Relaxed), 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fs_async_lane_operations_classify_priority_without_public_api_changes() {
|
||||||
|
assert_eq!(FsAsyncLaneOperation::Write.job_kind(), AsyncWorkJobKind::Fs);
|
||||||
|
assert_eq!(FsAsyncLaneOperation::Write.priority(), AsyncWorkPriority::FsWriteConfig);
|
||||||
|
assert_eq!(FsAsyncLaneOperation::Delete.priority(), AsyncWorkPriority::FsWriteConfig);
|
||||||
|
assert_eq!(FsAsyncLaneOperation::Config.priority(), AsyncWorkPriority::FsWriteConfig);
|
||||||
|
assert_eq!(FsAsyncLaneOperation::Read.priority(), AsyncWorkPriority::NonCriticalReadList);
|
||||||
|
assert_eq!(
|
||||||
|
FsAsyncLaneOperation::ListDir.priority(),
|
||||||
|
AsyncWorkPriority::NonCriticalReadList
|
||||||
|
);
|
||||||
|
assert_eq!(FsAsyncLaneOperation::Exists.priority(), AsyncWorkPriority::NonCriticalReadList);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,336 @@
|
|||||||
|
use prometeu_hal::app_mode::AppMode;
|
||||||
|
use prometeu_hal::cartridge::CartridgeManifest;
|
||||||
|
use std::fs;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::time::SystemTime;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct GameLibraryEntry {
|
||||||
|
pub manifest: CartridgeManifest,
|
||||||
|
pub title: String,
|
||||||
|
pub app_id: u32,
|
||||||
|
pub app_version: String,
|
||||||
|
pub path: PathBuf,
|
||||||
|
pub discovered_at: SystemTime,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GameLibraryEntry {
|
||||||
|
fn new(path: PathBuf, manifest: CartridgeManifest, discovered_at: SystemTime) -> Self {
|
||||||
|
Self {
|
||||||
|
title: manifest.title.clone(),
|
||||||
|
app_id: manifest.app_id,
|
||||||
|
app_version: manifest.app_version.clone(),
|
||||||
|
manifest,
|
||||||
|
path,
|
||||||
|
discovered_at,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn switch_target(&self) -> GameSwitchTarget {
|
||||||
|
GameSwitchTarget::from_entry(self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct GameSwitchTarget {
|
||||||
|
pub path: PathBuf,
|
||||||
|
pub app_id: u32,
|
||||||
|
pub title: String,
|
||||||
|
pub app_version: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GameSwitchTarget {
|
||||||
|
pub fn from_entry(entry: &GameLibraryEntry) -> Self {
|
||||||
|
Self {
|
||||||
|
path: entry.path.clone(),
|
||||||
|
app_id: entry.app_id,
|
||||||
|
title: entry.title.clone(),
|
||||||
|
app_version: entry.app_version.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct GameLibraryDiagnostic {
|
||||||
|
pub path: PathBuf,
|
||||||
|
pub reason: GameLibraryDiagnosticReason,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum GameLibraryDiagnosticReason {
|
||||||
|
RootNotDirectory,
|
||||||
|
CandidateReadFailed,
|
||||||
|
MissingManifest,
|
||||||
|
InvalidManifest,
|
||||||
|
UnsupportedVersion,
|
||||||
|
MissingProgram,
|
||||||
|
NonGameAppMode,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default)]
|
||||||
|
pub struct GameLibrary {
|
||||||
|
entries: Vec<GameLibraryEntry>,
|
||||||
|
diagnostics: Vec<GameLibraryDiagnostic>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GameLibrary {
|
||||||
|
pub fn empty() -> Self {
|
||||||
|
Self::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn entries(&self) -> &[GameLibraryEntry] {
|
||||||
|
&self.entries
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn diagnostics(&self) -> &[GameLibraryDiagnostic] {
|
||||||
|
&self.diagnostics
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.entries.is_empty()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn discover_games_root(root: impl AsRef<Path>) -> GameLibrary {
|
||||||
|
let root = root.as_ref();
|
||||||
|
let discovered_at = SystemTime::now();
|
||||||
|
|
||||||
|
if !root.is_dir() {
|
||||||
|
return GameLibrary {
|
||||||
|
entries: Vec::new(),
|
||||||
|
diagnostics: vec![GameLibraryDiagnostic {
|
||||||
|
path: root.to_path_buf(),
|
||||||
|
reason: GameLibraryDiagnosticReason::RootNotDirectory,
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let read_dir = match fs::read_dir(root) {
|
||||||
|
Ok(read_dir) => read_dir,
|
||||||
|
Err(_) => {
|
||||||
|
return GameLibrary {
|
||||||
|
entries: Vec::new(),
|
||||||
|
diagnostics: vec![GameLibraryDiagnostic {
|
||||||
|
path: root.to_path_buf(),
|
||||||
|
reason: GameLibraryDiagnosticReason::CandidateReadFailed,
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut entries = Vec::new();
|
||||||
|
let mut diagnostics = Vec::new();
|
||||||
|
|
||||||
|
for item in read_dir {
|
||||||
|
let Ok(item) = item else {
|
||||||
|
diagnostics.push(GameLibraryDiagnostic {
|
||||||
|
path: root.to_path_buf(),
|
||||||
|
reason: GameLibraryDiagnosticReason::CandidateReadFailed,
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
|
||||||
|
let path = item.path();
|
||||||
|
if !path.is_dir() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
match discover_candidate(&path, discovered_at) {
|
||||||
|
Ok(entry) => entries.push(entry),
|
||||||
|
Err(reason) => diagnostics.push(GameLibraryDiagnostic { path, reason }),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
entries.sort_by(|left, right| {
|
||||||
|
left.title
|
||||||
|
.cmp(&right.title)
|
||||||
|
.then_with(|| left.app_id.cmp(&right.app_id))
|
||||||
|
.then_with(|| left.path.cmp(&right.path))
|
||||||
|
});
|
||||||
|
|
||||||
|
GameLibrary { entries, diagnostics }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn discover_candidate(
|
||||||
|
path: &Path,
|
||||||
|
discovered_at: SystemTime,
|
||||||
|
) -> Result<GameLibraryEntry, GameLibraryDiagnosticReason> {
|
||||||
|
let manifest_path = path.join("manifest.json");
|
||||||
|
if !manifest_path.exists() {
|
||||||
|
return Err(GameLibraryDiagnosticReason::MissingManifest);
|
||||||
|
}
|
||||||
|
|
||||||
|
let manifest_content = fs::read_to_string(manifest_path)
|
||||||
|
.map_err(|_| GameLibraryDiagnosticReason::InvalidManifest)?;
|
||||||
|
let manifest: CartridgeManifest = serde_json::from_str(&manifest_content)
|
||||||
|
.map_err(|_| GameLibraryDiagnosticReason::InvalidManifest)?;
|
||||||
|
|
||||||
|
if manifest.magic != "PMTU" {
|
||||||
|
return Err(GameLibraryDiagnosticReason::InvalidManifest);
|
||||||
|
}
|
||||||
|
if manifest.cartridge_version != 1 {
|
||||||
|
return Err(GameLibraryDiagnosticReason::UnsupportedVersion);
|
||||||
|
}
|
||||||
|
if manifest.app_mode != AppMode::Game {
|
||||||
|
return Err(GameLibraryDiagnosticReason::NonGameAppMode);
|
||||||
|
}
|
||||||
|
if !path.join("program.pbx").exists() {
|
||||||
|
return Err(GameLibraryDiagnosticReason::MissingProgram);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(GameLibraryEntry::new(path.to_path_buf(), manifest, discovered_at))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use serde_json::json;
|
||||||
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
|
use std::time::UNIX_EPOCH;
|
||||||
|
|
||||||
|
static TEST_DIR_COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||||
|
|
||||||
|
struct TestRoot {
|
||||||
|
path: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TestRoot {
|
||||||
|
fn new() -> Self {
|
||||||
|
let unique = TEST_DIR_COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||||
|
let path = std::env::temp_dir().join(format!(
|
||||||
|
"prometeu-game-library-test-{}-{}",
|
||||||
|
std::process::id(),
|
||||||
|
unique
|
||||||
|
));
|
||||||
|
fs::create_dir_all(&path).expect("test root should be created");
|
||||||
|
Self { path }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add_candidate(&self, name: &str, manifest: serde_json::Value, with_program: bool) {
|
||||||
|
let candidate = self.path.join(name);
|
||||||
|
fs::create_dir_all(&candidate).expect("candidate should be created");
|
||||||
|
fs::write(candidate.join("manifest.json"), manifest.to_string())
|
||||||
|
.expect("manifest should be written");
|
||||||
|
if with_program {
|
||||||
|
fs::write(candidate.join("program.pbx"), [0_u8])
|
||||||
|
.expect("program should be written");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for TestRoot {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let _ = fs::remove_dir_all(&self.path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn manifest(title: &str, app_id: u32, app_mode: &str) -> serde_json::Value {
|
||||||
|
json!({
|
||||||
|
"magic": "PMTU",
|
||||||
|
"cartridge_version": 1,
|
||||||
|
"app_id": app_id,
|
||||||
|
"title": title,
|
||||||
|
"app_version": "1.0.0",
|
||||||
|
"app_mode": app_mode
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn discovery_returns_only_immediate_valid_game_directories() {
|
||||||
|
let root = TestRoot::new();
|
||||||
|
root.add_candidate("zeta", manifest("Zeta", 2, "Game"), true);
|
||||||
|
root.add_candidate("alpha", manifest("Alpha", 1, "Game"), true);
|
||||||
|
root.add_candidate("shell", manifest("Shell", 3, "Shell"), true);
|
||||||
|
root.add_candidate("missing-program", manifest("Missing Program", 4, "Game"), false);
|
||||||
|
fs::write(root.path.join("loose-file.txt"), "ignored").expect("file should be written");
|
||||||
|
|
||||||
|
let nested_parent = root.path.join("nested-parent");
|
||||||
|
fs::create_dir_all(nested_parent.join("nested-game")).expect("nested dir should exist");
|
||||||
|
fs::write(
|
||||||
|
nested_parent.join("nested-game").join("manifest.json"),
|
||||||
|
manifest("Nested", 5, "Game").to_string(),
|
||||||
|
)
|
||||||
|
.expect("nested manifest should be written");
|
||||||
|
fs::write(nested_parent.join("nested-game").join("program.pbx"), [0_u8])
|
||||||
|
.expect("nested program should be written");
|
||||||
|
|
||||||
|
let library = discover_games_root(&root.path);
|
||||||
|
|
||||||
|
assert_eq!(library.entries().len(), 2);
|
||||||
|
assert_eq!(library.entries()[0].title, "Alpha");
|
||||||
|
assert_eq!(library.entries()[0].app_id, 1);
|
||||||
|
assert_eq!(library.entries()[0].app_version, "1.0.0");
|
||||||
|
assert_eq!(library.entries()[0].manifest.app_mode, AppMode::Game);
|
||||||
|
assert!(library.entries()[0].path.ends_with("alpha"));
|
||||||
|
assert!(library.entries()[0].discovered_at >= UNIX_EPOCH);
|
||||||
|
assert_eq!(library.entries()[1].title, "Zeta");
|
||||||
|
|
||||||
|
assert!(library.diagnostics().iter().any(|diagnostic| {
|
||||||
|
diagnostic.path.ends_with("shell")
|
||||||
|
&& diagnostic.reason == GameLibraryDiagnosticReason::NonGameAppMode
|
||||||
|
}));
|
||||||
|
assert!(library.diagnostics().iter().any(|diagnostic| {
|
||||||
|
diagnostic.path.ends_with("missing-program")
|
||||||
|
&& diagnostic.reason == GameLibraryDiagnosticReason::MissingProgram
|
||||||
|
}));
|
||||||
|
assert!(library.diagnostics().iter().any(|diagnostic| {
|
||||||
|
diagnostic.path.ends_with("nested-parent")
|
||||||
|
&& diagnostic.reason == GameLibraryDiagnosticReason::MissingManifest
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn switch_target_preserves_resolved_identity() {
|
||||||
|
let path = PathBuf::from("test-cartridges/stress-console");
|
||||||
|
let entry = GameLibraryEntry::new(
|
||||||
|
path.clone(),
|
||||||
|
CartridgeManifest {
|
||||||
|
magic: "PMTU".to_string(),
|
||||||
|
cartridge_version: 1,
|
||||||
|
app_id: 42,
|
||||||
|
title: "Stress".to_string(),
|
||||||
|
app_version: "1.0.0".to_string(),
|
||||||
|
app_mode: AppMode::Game,
|
||||||
|
capabilities: vec![],
|
||||||
|
},
|
||||||
|
UNIX_EPOCH,
|
||||||
|
);
|
||||||
|
|
||||||
|
let target = entry.switch_target();
|
||||||
|
|
||||||
|
assert_eq!(target.path, path);
|
||||||
|
assert_eq!(target.app_id, 42);
|
||||||
|
assert_eq!(target.title, "Stress");
|
||||||
|
assert_eq!(target.app_version, "1.0.0");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn missing_root_returns_diagnostic_and_no_entries() {
|
||||||
|
let root = TestRoot::new();
|
||||||
|
let missing = root.path.join("missing");
|
||||||
|
|
||||||
|
let library = discover_games_root(&missing);
|
||||||
|
|
||||||
|
assert!(library.is_empty());
|
||||||
|
assert_eq!(library.diagnostics().len(), 1);
|
||||||
|
assert_eq!(library.diagnostics()[0].reason, GameLibraryDiagnosticReason::RootNotDirectory);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn repository_test_cartridges_include_stress_and_dummy_boy() {
|
||||||
|
let games_root =
|
||||||
|
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../..").join("test-cartridges");
|
||||||
|
|
||||||
|
let library = discover_games_root(games_root);
|
||||||
|
let entries = library.entries();
|
||||||
|
|
||||||
|
assert!(entries.iter().any(|entry| {
|
||||||
|
entry.app_id == 1
|
||||||
|
&& entry.title == "Stress Console"
|
||||||
|
&& entry.path.ends_with("stress-console")
|
||||||
|
}));
|
||||||
|
assert!(entries.iter().any(|entry| {
|
||||||
|
entry.app_id == 2 && entry.title == "Dummy Boy" && entry.path.ends_with("dummy-boy")
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
use crate::fs::{FsError, VirtualFS};
|
use crate::fs::{FsError, VirtualFS};
|
||||||
|
use crate::services::async_work::{AsyncWorkJobKind, AsyncWorkPriority};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
pub const MEMCARD_SLOT_COUNT: usize = 32;
|
pub const MEMCARD_SLOT_COUNT: usize = 32;
|
||||||
@@ -50,6 +51,30 @@ pub struct MemcardWriteResult {
|
|||||||
pub bytes_written: u32,
|
pub bytes_written: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum MemcardAsyncLaneOperation {
|
||||||
|
SlotWrite,
|
||||||
|
SlotCommit,
|
||||||
|
SlotClear,
|
||||||
|
SlotRead,
|
||||||
|
SlotStat,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MemcardAsyncLaneOperation {
|
||||||
|
pub const fn job_kind(self) -> AsyncWorkJobKind {
|
||||||
|
AsyncWorkJobKind::Memcard
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const fn priority(self) -> AsyncWorkPriority {
|
||||||
|
match self {
|
||||||
|
Self::SlotWrite | Self::SlotCommit | Self::SlotClear => {
|
||||||
|
AsyncWorkPriority::MemcardCommitWrite
|
||||||
|
}
|
||||||
|
Self::SlotRead | Self::SlotStat => AsyncWorkPriority::NonCriticalReadList,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
struct SlotImage {
|
struct SlotImage {
|
||||||
payload: Vec<u8>,
|
payload: Vec<u8>,
|
||||||
@@ -428,4 +453,29 @@ mod tests {
|
|||||||
let stat = mem.slot_stat(&fs, 7, 2);
|
let stat = mem.slot_stat(&fs, 7, 2);
|
||||||
assert_eq!(stat.state, MemcardSlotState::Corrupt);
|
assert_eq!(stat.state, MemcardSlotState::Corrupt);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn memcard_async_lane_operations_classify_priority_without_changing_public_api() {
|
||||||
|
assert_eq!(MemcardAsyncLaneOperation::SlotWrite.job_kind(), AsyncWorkJobKind::Memcard);
|
||||||
|
assert_eq!(
|
||||||
|
MemcardAsyncLaneOperation::SlotWrite.priority(),
|
||||||
|
AsyncWorkPriority::MemcardCommitWrite
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
MemcardAsyncLaneOperation::SlotCommit.priority(),
|
||||||
|
AsyncWorkPriority::MemcardCommitWrite
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
MemcardAsyncLaneOperation::SlotClear.priority(),
|
||||||
|
AsyncWorkPriority::MemcardCommitWrite
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
MemcardAsyncLaneOperation::SlotRead.priority(),
|
||||||
|
AsyncWorkPriority::NonCriticalReadList
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
MemcardAsyncLaneOperation::SlotStat.priority(),
|
||||||
|
AsyncWorkPriority::NonCriticalReadList
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,2 +1,10 @@
|
|||||||
|
pub mod async_work;
|
||||||
|
pub mod foreground;
|
||||||
pub mod fs;
|
pub mod fs;
|
||||||
|
pub mod game_library;
|
||||||
pub mod memcard;
|
pub mod memcard;
|
||||||
|
pub mod process;
|
||||||
|
pub mod task;
|
||||||
|
pub mod vm_runtime;
|
||||||
|
pub mod vm_session;
|
||||||
|
pub mod windows;
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
mod model;
|
||||||
|
mod process_kind;
|
||||||
|
pub mod process_manager;
|
||||||
|
mod process_state;
|
||||||
|
|
||||||
|
pub use model::{Process, ProcessId};
|
||||||
|
pub use process_kind::ProcessKind;
|
||||||
|
pub use process_manager::ProcessManager;
|
||||||
|
pub use process_state::ProcessState;
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
use crate::process::{ProcessKind, ProcessState};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
pub struct ProcessId(pub u32);
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Process {
|
||||||
|
pub id: ProcessId,
|
||||||
|
pub app_id: u32,
|
||||||
|
pub title: String,
|
||||||
|
pub kind: ProcessKind,
|
||||||
|
pub state: ProcessState,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Process {
|
||||||
|
pub fn new(id: ProcessId, app_id: u32, title: impl Into<String>, kind: ProcessKind) -> Self {
|
||||||
|
Self { id, app_id, title: title.into(), kind, state: ProcessState::Created }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mark_running(&mut self) {
|
||||||
|
self.state = ProcessState::Running;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mark_suspended(&mut self) {
|
||||||
|
self.state = ProcessState::Suspended;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mark_stopped(&mut self) {
|
||||||
|
self.state = ProcessState::Stopped;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mark_crashed(&mut self) {
|
||||||
|
self.state = ProcessState::Crashed;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_alive(&self) -> bool {
|
||||||
|
matches!(
|
||||||
|
self.state,
|
||||||
|
ProcessState::Created | ProcessState::Running | ProcessState::Suspended
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum ProcessKind {
|
||||||
|
/// VM-backed fullscreen game cartridge.
|
||||||
|
VmGame,
|
||||||
|
|
||||||
|
/// VM-backed app hosted by the Prometeu Shell.
|
||||||
|
VmShell,
|
||||||
|
|
||||||
|
/// Native Rust app/component hosted by the Prometeu Shell.
|
||||||
|
NativeShell,
|
||||||
|
}
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
use crate::process::{Process, ProcessId, ProcessKind, ProcessState};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
pub struct ProcessManager {
|
||||||
|
next_id: u32,
|
||||||
|
processes: HashMap<ProcessId, Process>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ProcessManager {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self { next_id: 1, processes: HashMap::new() }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn spawn_vm_game(&mut self, app_id: u32, title: impl Into<String>) -> ProcessId {
|
||||||
|
self.spawn(app_id, title, ProcessKind::VmGame)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn spawn_vm_shell(&mut self, app_id: u32, title: impl Into<String>) -> ProcessId {
|
||||||
|
self.spawn(app_id, title, ProcessKind::VmShell)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn spawn_native_shell(&mut self, app_id: u32, title: impl Into<String>) -> ProcessId {
|
||||||
|
self.spawn(app_id, title, ProcessKind::NativeShell)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn spawn(&mut self, app_id: u32, title: impl Into<String>, kind: ProcessKind) -> ProcessId {
|
||||||
|
let id = ProcessId(self.next_id);
|
||||||
|
self.next_id += 1;
|
||||||
|
|
||||||
|
let mut process = Process::new(id, app_id, title, kind);
|
||||||
|
process.mark_running();
|
||||||
|
|
||||||
|
self.processes.insert(id, process);
|
||||||
|
|
||||||
|
id
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get(&self, id: ProcessId) -> Option<&Process> {
|
||||||
|
self.processes.get(&id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_mut(&mut self, id: ProcessId) -> Option<&mut Process> {
|
||||||
|
self.processes.get_mut(&id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn contains(&self, id: ProcessId) -> bool {
|
||||||
|
self.processes.contains_key(&id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn all(&self) -> impl Iterator<Item = &Process> {
|
||||||
|
self.processes.values()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mark_running(&mut self, id: ProcessId) -> bool {
|
||||||
|
self.transition(id, ProcessState::Running)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mark_suspended(&mut self, id: ProcessId) -> bool {
|
||||||
|
self.transition(id, ProcessState::Suspended)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mark_stopped(&mut self, id: ProcessId) -> bool {
|
||||||
|
self.transition(id, ProcessState::Stopped)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mark_crashed(&mut self, id: ProcessId) -> bool {
|
||||||
|
self.transition(id, ProcessState::Crashed)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove_stopped(&mut self) {
|
||||||
|
self.processes.retain(|_, process| process.state != ProcessState::Stopped);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn transition(&mut self, id: ProcessId, state: ProcessState) -> bool {
|
||||||
|
let Some(process) = self.get_mut(id) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
process.state = state;
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn spawn_vm_game_creates_running_process() {
|
||||||
|
let mut manager = ProcessManager::new();
|
||||||
|
|
||||||
|
let id = manager.spawn_vm_game(42, "Amazing Game");
|
||||||
|
|
||||||
|
let process = manager.get(id).expect("process should exist");
|
||||||
|
|
||||||
|
assert_eq!(process.id, id);
|
||||||
|
assert_eq!(process.app_id, 42);
|
||||||
|
assert_eq!(process.title, "Amazing Game");
|
||||||
|
assert_eq!(process.kind, ProcessKind::VmGame);
|
||||||
|
assert_eq!(process.state, ProcessState::Running);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn spawn_vm_shell_creates_running_process() {
|
||||||
|
let mut manager = ProcessManager::new();
|
||||||
|
|
||||||
|
let id = manager.spawn_vm_shell(42, "Amazing Shell");
|
||||||
|
|
||||||
|
let process = manager.get(id).expect("process should exist");
|
||||||
|
|
||||||
|
assert_eq!(process.id, id);
|
||||||
|
assert_eq!(process.app_id, 42);
|
||||||
|
assert_eq!(process.title, "Amazing Shell");
|
||||||
|
assert_eq!(process.kind, ProcessKind::VmShell);
|
||||||
|
assert_eq!(process.state, ProcessState::Running);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn spawn_native_shell_creates_running_process() {
|
||||||
|
let mut manager = ProcessManager::new();
|
||||||
|
|
||||||
|
let id = manager.spawn_native_shell(42, "Amazing Shell");
|
||||||
|
|
||||||
|
let process = manager.get(id).expect("process should exist");
|
||||||
|
|
||||||
|
assert_eq!(process.id, id);
|
||||||
|
assert_eq!(process.app_id, 42);
|
||||||
|
assert_eq!(process.title, "Amazing Shell");
|
||||||
|
assert_eq!(process.kind, ProcessKind::NativeShell);
|
||||||
|
assert_eq!(process.state, ProcessState::Running);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn mark_suspended_updates_process_state() {
|
||||||
|
let mut manager = ProcessManager::new();
|
||||||
|
|
||||||
|
let id = manager.spawn_vm_game(42, "Amazing Game");
|
||||||
|
|
||||||
|
assert!(manager.mark_suspended(id));
|
||||||
|
|
||||||
|
let process = manager.get(id).expect("process should exist");
|
||||||
|
|
||||||
|
assert_eq!(process.state, ProcessState::Suspended);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn mark_stopped_updates_process_state() {
|
||||||
|
let mut manager = ProcessManager::new();
|
||||||
|
|
||||||
|
let id = manager.spawn_vm_game(42, "Amazing Game");
|
||||||
|
|
||||||
|
assert!(manager.mark_stopped(id));
|
||||||
|
|
||||||
|
let process = manager.get(id).expect("process should exist");
|
||||||
|
|
||||||
|
assert_eq!(process.state, ProcessState::Stopped);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unknown_process_transition_returns_false() {
|
||||||
|
let mut manager = ProcessManager::new();
|
||||||
|
|
||||||
|
assert!(!manager.mark_stopped(ProcessId(999)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn remove_stopped_keeps_running_processes() {
|
||||||
|
let mut manager = ProcessManager::new();
|
||||||
|
|
||||||
|
let running = manager.spawn_vm_game(1, "Running");
|
||||||
|
let stopped = manager.spawn_vm_game(2, "Stopped");
|
||||||
|
|
||||||
|
manager.mark_stopped(stopped);
|
||||||
|
manager.remove_stopped();
|
||||||
|
|
||||||
|
assert!(manager.get(running).is_some());
|
||||||
|
assert!(manager.get(stopped).is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum ProcessState {
|
||||||
|
Created,
|
||||||
|
Running,
|
||||||
|
Stopped,
|
||||||
|
Suspended,
|
||||||
|
Crashed,
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
mod model;
|
||||||
|
mod task_kind;
|
||||||
|
mod task_manager;
|
||||||
|
mod task_state;
|
||||||
|
|
||||||
|
pub use model::Task;
|
||||||
|
pub use model::TaskId;
|
||||||
|
pub use task_kind::TaskKind;
|
||||||
|
pub use task_manager::TaskManager;
|
||||||
|
pub use task_state::TaskState;
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
use crate::process::ProcessId;
|
||||||
|
use crate::task::{TaskKind, TaskState};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
pub struct TaskId(pub u32);
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Task {
|
||||||
|
pub id: TaskId,
|
||||||
|
pub process_id: ProcessId,
|
||||||
|
pub app_id: u32,
|
||||||
|
pub title: String,
|
||||||
|
pub kind: TaskKind,
|
||||||
|
pub state: TaskState,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Task {
|
||||||
|
pub fn new(
|
||||||
|
id: TaskId,
|
||||||
|
process_id: ProcessId,
|
||||||
|
app_id: u32,
|
||||||
|
title: impl Into<String>,
|
||||||
|
kind: TaskKind,
|
||||||
|
) -> Self {
|
||||||
|
Self { id, process_id, app_id, title: title.into(), kind, state: TaskState::Background }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mark_foreground(&mut self) {
|
||||||
|
self.state = TaskState::Foreground;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mark_background(&mut self) {
|
||||||
|
self.state = TaskState::Background;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mark_suspended(&mut self) {
|
||||||
|
self.state = TaskState::Suspended;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mark_closed(&mut self) {
|
||||||
|
self.state = TaskState::Closed;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mark_crashed(&mut self) {
|
||||||
|
self.state = TaskState::Crashed;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_active(&self) -> bool {
|
||||||
|
matches!(self.state, TaskState::Foreground | TaskState::Background | TaskState::Suspended)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum TaskKind {
|
||||||
|
Game,
|
||||||
|
Shell,
|
||||||
|
}
|
||||||
@@ -0,0 +1,282 @@
|
|||||||
|
use super::{Task, TaskId, TaskKind, TaskState};
|
||||||
|
use crate::services::process::ProcessId;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
pub struct TaskManager {
|
||||||
|
next_id: u32,
|
||||||
|
tasks: HashMap<TaskId, Task>,
|
||||||
|
foreground_task: Option<TaskId>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TaskManager {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self { next_id: 1, tasks: HashMap::new(), foreground_task: None }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn create_game_task(
|
||||||
|
&mut self,
|
||||||
|
process_id: ProcessId,
|
||||||
|
app_id: u32,
|
||||||
|
title: impl Into<String>,
|
||||||
|
) -> TaskId {
|
||||||
|
self.create(process_id, app_id, title, TaskKind::Game)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn create_shell_task(
|
||||||
|
&mut self,
|
||||||
|
process_id: ProcessId,
|
||||||
|
app_id: u32,
|
||||||
|
title: impl Into<String>,
|
||||||
|
) -> TaskId {
|
||||||
|
self.create(process_id, app_id, title, TaskKind::Shell)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create(
|
||||||
|
&mut self,
|
||||||
|
process_id: ProcessId,
|
||||||
|
app_id: u32,
|
||||||
|
title: impl Into<String>,
|
||||||
|
kind: TaskKind,
|
||||||
|
) -> TaskId {
|
||||||
|
let id = TaskId(self.next_id);
|
||||||
|
self.next_id += 1;
|
||||||
|
|
||||||
|
let task = Task::new(id, process_id, app_id, title, kind);
|
||||||
|
self.tasks.insert(id, task);
|
||||||
|
|
||||||
|
id
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get(&self, id: TaskId) -> Option<&Task> {
|
||||||
|
self.tasks.get(&id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_mut(&mut self, id: TaskId) -> Option<&mut Task> {
|
||||||
|
self.tasks.get_mut(&id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn contains(&self, id: TaskId) -> bool {
|
||||||
|
self.tasks.contains_key(&id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn all(&self) -> impl Iterator<Item = &Task> {
|
||||||
|
self.tasks.values()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn foreground_task(&self) -> Option<TaskId> {
|
||||||
|
self.foreground_task
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn foreground(&self) -> Option<&Task> {
|
||||||
|
self.foreground_task.and_then(|id| self.get(id))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_foreground(&mut self, id: TaskId) -> bool {
|
||||||
|
if !self.tasks.contains_key(&id) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(current_id) = self.foreground_task
|
||||||
|
&& current_id != id
|
||||||
|
&& let Some(current) = self.tasks.get_mut(¤t_id)
|
||||||
|
&& current.state == TaskState::Foreground
|
||||||
|
{
|
||||||
|
current.mark_background();
|
||||||
|
}
|
||||||
|
|
||||||
|
let Some(task) = self.tasks.get_mut(&id) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
task.mark_foreground();
|
||||||
|
self.foreground_task = Some(id);
|
||||||
|
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clear_foreground(&mut self) {
|
||||||
|
if let Some(id) = self.foreground_task.take()
|
||||||
|
&& let Some(task) = self.tasks.get_mut(&id)
|
||||||
|
&& task.state == TaskState::Foreground
|
||||||
|
{
|
||||||
|
task.mark_background();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mark_background(&mut self, id: TaskId) -> bool {
|
||||||
|
let Some(task) = self.tasks.get_mut(&id) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
task.mark_background();
|
||||||
|
|
||||||
|
if self.foreground_task == Some(id) {
|
||||||
|
self.foreground_task = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mark_suspended(&mut self, id: TaskId) -> bool {
|
||||||
|
let Some(task) = self.tasks.get_mut(&id) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
task.mark_suspended();
|
||||||
|
|
||||||
|
if self.foreground_task == Some(id) {
|
||||||
|
self.foreground_task = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn close_task(&mut self, id: TaskId) -> bool {
|
||||||
|
let Some(task) = self.tasks.get_mut(&id) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
task.mark_closed();
|
||||||
|
|
||||||
|
if self.foreground_task == Some(id) {
|
||||||
|
self.foreground_task = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mark_crashed(&mut self, id: TaskId) -> bool {
|
||||||
|
let Some(task) = self.tasks.get_mut(&id) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
task.mark_crashed();
|
||||||
|
|
||||||
|
if self.foreground_task == Some(id) {
|
||||||
|
self.foreground_task = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove_closed(&mut self) {
|
||||||
|
self.tasks.retain(|id, task| {
|
||||||
|
let should_keep = task.state != TaskState::Closed;
|
||||||
|
if !should_keep && self.foreground_task == Some(*id) {
|
||||||
|
self.foreground_task = None;
|
||||||
|
}
|
||||||
|
should_keep
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::services::process::ProcessId;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn create_game_task_registers_task() {
|
||||||
|
let mut manager = TaskManager::new();
|
||||||
|
let process_id = ProcessId(7);
|
||||||
|
|
||||||
|
let task_id = manager.create_game_task(process_id, 42, "Sector Crawl");
|
||||||
|
|
||||||
|
let task = manager.get(task_id).expect("task should exist");
|
||||||
|
|
||||||
|
assert_eq!(task.id, task_id);
|
||||||
|
assert_eq!(task.process_id, process_id);
|
||||||
|
assert_eq!(task.app_id, 42);
|
||||||
|
assert_eq!(task.title, "Sector Crawl");
|
||||||
|
assert_eq!(task.kind, TaskKind::Game);
|
||||||
|
assert_eq!(task.state, TaskState::Background);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn set_foreground_marks_task_as_foreground() {
|
||||||
|
let mut manager = TaskManager::new();
|
||||||
|
let task_id = manager.create_game_task(ProcessId(1), 42, "Sector Crawl");
|
||||||
|
|
||||||
|
assert!(manager.set_foreground(task_id));
|
||||||
|
|
||||||
|
let task = manager.get(task_id).expect("task should exist");
|
||||||
|
|
||||||
|
assert_eq!(manager.foreground_task(), Some(task_id));
|
||||||
|
assert_eq!(task.state, TaskState::Foreground);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn set_foreground_moves_previous_task_to_background() {
|
||||||
|
let mut manager = TaskManager::new();
|
||||||
|
|
||||||
|
let first = manager.create_game_task(ProcessId(1), 1, "First");
|
||||||
|
let second = manager.create_game_task(ProcessId(2), 2, "Second");
|
||||||
|
|
||||||
|
assert!(manager.set_foreground(first));
|
||||||
|
assert!(manager.set_foreground(second));
|
||||||
|
|
||||||
|
assert_eq!(manager.foreground_task(), Some(second));
|
||||||
|
assert_eq!(
|
||||||
|
manager.get(first).expect("first task should exist").state,
|
||||||
|
TaskState::Background
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
manager.get(second).expect("second task should exist").state,
|
||||||
|
TaskState::Foreground
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn set_foreground_unknown_task_returns_false() {
|
||||||
|
let mut manager = TaskManager::new();
|
||||||
|
|
||||||
|
assert!(!manager.set_foreground(TaskId(999)));
|
||||||
|
assert_eq!(manager.foreground_task(), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn close_foreground_task_clears_foreground() {
|
||||||
|
let mut manager = TaskManager::new();
|
||||||
|
|
||||||
|
let task_id = manager.create_game_task(ProcessId(1), 42, "Sector Crawl");
|
||||||
|
|
||||||
|
assert!(manager.set_foreground(task_id));
|
||||||
|
assert!(manager.close_task(task_id));
|
||||||
|
|
||||||
|
let task = manager.get(task_id).expect("task should exist");
|
||||||
|
|
||||||
|
assert_eq!(task.state, TaskState::Closed);
|
||||||
|
assert_eq!(manager.foreground_task(), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn suspend_foreground_task_clears_foreground() {
|
||||||
|
let mut manager = TaskManager::new();
|
||||||
|
|
||||||
|
let task_id = manager.create_game_task(ProcessId(1), 42, "Sector Crawl");
|
||||||
|
|
||||||
|
assert!(manager.set_foreground(task_id));
|
||||||
|
assert!(manager.mark_suspended(task_id));
|
||||||
|
|
||||||
|
let task = manager.get(task_id).expect("task should exist");
|
||||||
|
|
||||||
|
assert_eq!(task.state, TaskState::Suspended);
|
||||||
|
assert_eq!(manager.foreground_task(), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn crashed_foreground_task_clears_foreground() {
|
||||||
|
let mut manager = TaskManager::new();
|
||||||
|
|
||||||
|
let task_id = manager.create_game_task(ProcessId(1), 42, "Sector Crawl");
|
||||||
|
|
||||||
|
assert!(manager.set_foreground(task_id));
|
||||||
|
assert!(manager.mark_crashed(task_id));
|
||||||
|
|
||||||
|
let task = manager.get(task_id).expect("task should exist");
|
||||||
|
|
||||||
|
assert_eq!(task.state, TaskState::Crashed);
|
||||||
|
assert_eq!(manager.foreground_task(), None);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum TaskState {
|
||||||
|
Foreground,
|
||||||
|
Background,
|
||||||
|
Suspended,
|
||||||
|
Closed,
|
||||||
|
Crashed,
|
||||||
|
}
|
||||||
+236
@@ -0,0 +1,236 @@
|
|||||||
|
use super::FrameScheduler;
|
||||||
|
use super::frame_scheduler::FrameAuthorizationError;
|
||||||
|
use super::render_manager::{
|
||||||
|
LocalRenderWorker, RenderConsumeOutcome, RenderConsumerPath, RenderExecutionPolicy,
|
||||||
|
RenderPacingPolicy, RenderPolicy, RenderRuntimeCapabilities, RenderSurface,
|
||||||
|
};
|
||||||
|
use prometeu_hal::app_mode::AppMode;
|
||||||
|
use prometeu_hal::telemetry::AtomicTelemetry;
|
||||||
|
use prometeu_hal::{
|
||||||
|
FrameId, Game2DFramePacket, RenderOwnership, RenderSubmission, RenderSubmissionPacket,
|
||||||
|
ShellUiFramePacket,
|
||||||
|
};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::AtomicU32;
|
||||||
|
|
||||||
|
use super::render_manager::RenderManager;
|
||||||
|
|
||||||
|
struct ContractMatrixRow {
|
||||||
|
invariant: &'static str,
|
||||||
|
validations: &'static [&'static str],
|
||||||
|
}
|
||||||
|
|
||||||
|
const ASYNC_RENDER_CONTRACT_MATRIX: &[ContractMatrixRow] = &[
|
||||||
|
ContractMatrixRow {
|
||||||
|
invariant: "complete packet and AppMode policy are explicit",
|
||||||
|
validations: &["matrix_packet_policy_and_pacing_are_mode_specific"],
|
||||||
|
},
|
||||||
|
ContractMatrixRow {
|
||||||
|
invariant: "handoff is single-slot latest-wins in sync and worker-capable paths",
|
||||||
|
validations: &["matrix_sync_and_worker_paths_share_latest_wins_handoff_contract"],
|
||||||
|
},
|
||||||
|
ContractMatrixRow {
|
||||||
|
invariant: "render consumers see resource banks through read-only access",
|
||||||
|
validations: &[
|
||||||
|
"prometeu-drivers::render_resource_access_traits_are_thread_safe",
|
||||||
|
"prometeu-drivers::render_resource_access_exposes_read_only_glyph_and_scene_banks",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
ContractMatrixRow {
|
||||||
|
invariant: "Game pacing is frame scheduled and does not catch up skipped frames",
|
||||||
|
validations: &["matrix_packet_policy_and_pacing_are_mode_specific"],
|
||||||
|
},
|
||||||
|
ContractMatrixRow {
|
||||||
|
invariant: "ownership epoch prevents obsolete work from presenting",
|
||||||
|
validations: &["matrix_epoch_stale_discard_and_telemetry_sync_remain_consistent"],
|
||||||
|
},
|
||||||
|
ContractMatrixRow {
|
||||||
|
invariant: "telemetry exposes production, drops, consumes, presents, repeats, and errors",
|
||||||
|
validations: &[
|
||||||
|
"matrix_epoch_stale_discard_and_telemetry_sync_remain_consistent",
|
||||||
|
"matrix_shutdown_failure_and_repeat_are_observable",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
ContractMatrixRow {
|
||||||
|
invariant: "shutdown discards pending work and bounded local worker failure is contained",
|
||||||
|
validations: &["matrix_shutdown_failure_and_repeat_are_observable"],
|
||||||
|
},
|
||||||
|
ContractMatrixRow {
|
||||||
|
invariant: "active-scene Game2D overlay is composed after layer blit",
|
||||||
|
validations: &[
|
||||||
|
"prometeu-drivers::publish_game2d_submission_applies_gfx2d_overlay_after_active_scene",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct RecordingSurface {
|
||||||
|
seen: Vec<FrameId>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RenderSurface for RecordingSurface {
|
||||||
|
fn consume_submission(&mut self, submission: &RenderSubmission) {
|
||||||
|
self.seen.push(submission.frame_id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct PanickingSurface;
|
||||||
|
|
||||||
|
impl RenderSurface for PanickingSurface {
|
||||||
|
fn consume_submission(&mut self, _submission: &RenderSubmission) {
|
||||||
|
panic!("matrix present failure");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn close_game(manager: &mut RenderManager) {
|
||||||
|
manager
|
||||||
|
.close_frame_with_packet(RenderSubmissionPacket::Game2D(Game2DFramePacket::default()))
|
||||||
|
.expect("game packet must match Game mode");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn close_shell(manager: &mut RenderManager) {
|
||||||
|
manager
|
||||||
|
.close_frame_with_packet(RenderSubmissionPacket::ShellUi(ShellUiFramePacket::new(
|
||||||
|
Vec::new(),
|
||||||
|
)))
|
||||||
|
.expect("shell packet must match Shell mode");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn async_render_contract_matrix_rows_have_validation() {
|
||||||
|
assert!(ASYNC_RENDER_CONTRACT_MATRIX.len() >= 7);
|
||||||
|
for row in ASYNC_RENDER_CONTRACT_MATRIX {
|
||||||
|
assert!(!row.invariant.is_empty());
|
||||||
|
assert!(!row.validations.is_empty(), "missing validation for {}", row.invariant);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn matrix_packet_policy_and_pacing_are_mode_specific() {
|
||||||
|
let game_policy = RenderPolicy::for_app_mode(AppMode::Game);
|
||||||
|
assert_eq!(game_policy.pacing, RenderPacingPolicy::FrameScheduled);
|
||||||
|
assert_eq!(game_policy.execution, RenderExecutionPolicy::WorkerCapableWithLocalFallback);
|
||||||
|
assert_eq!(
|
||||||
|
game_policy.resolve_consumer_path(RenderRuntimeCapabilities { game_render_worker: true }),
|
||||||
|
RenderConsumerPath::RealWorker
|
||||||
|
);
|
||||||
|
|
||||||
|
let shell_policy = RenderPolicy::for_app_mode(AppMode::Shell);
|
||||||
|
assert_eq!(shell_policy.pacing, RenderPacingPolicy::LifecycleDriven);
|
||||||
|
assert_eq!(shell_policy.execution, RenderExecutionPolicy::LocalSynchronous);
|
||||||
|
assert_eq!(
|
||||||
|
shell_policy.resolve_consumer_path(RenderRuntimeCapabilities { game_render_worker: true }),
|
||||||
|
RenderConsumerPath::LocalSynchronous
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut game_manager = RenderManager::new(AppMode::Game);
|
||||||
|
close_game(&mut game_manager);
|
||||||
|
assert!(
|
||||||
|
game_manager
|
||||||
|
.close_frame_with_packet(RenderSubmissionPacket::ShellUi(ShellUiFramePacket::new(
|
||||||
|
Vec::new()
|
||||||
|
)))
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut shell_manager = RenderManager::new(AppMode::Shell);
|
||||||
|
close_shell(&mut shell_manager);
|
||||||
|
assert!(
|
||||||
|
shell_manager
|
||||||
|
.close_frame_with_packet(RenderSubmissionPacket::Game2D(Game2DFramePacket::default()))
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut scheduler = FrameScheduler::default();
|
||||||
|
assert_eq!(scheduler.authorize_game_frame(), Ok(FrameId::ZERO));
|
||||||
|
scheduler.record_logical_frame_overrun();
|
||||||
|
assert_eq!(
|
||||||
|
scheduler.authorize_game_frame(),
|
||||||
|
Err(FrameAuthorizationError::GameFrameAlreadyActive { active_frame_id: FrameId::ZERO })
|
||||||
|
);
|
||||||
|
assert_eq!(scheduler.complete_game_frame(), Some(FrameId::ZERO));
|
||||||
|
assert_eq!(scheduler.authorize_game_frame(), Ok(FrameId::new(1)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn matrix_sync_and_worker_paths_share_latest_wins_handoff_contract() {
|
||||||
|
fn consume_with(path: RenderConsumerPath) -> (RenderConsumeOutcome, Vec<FrameId>, u64) {
|
||||||
|
let mut manager = RenderManager::new(AppMode::Game);
|
||||||
|
let mut surface = RecordingSurface::default();
|
||||||
|
|
||||||
|
close_game(&mut manager);
|
||||||
|
close_game(&mut manager);
|
||||||
|
|
||||||
|
let outcome = match path {
|
||||||
|
RenderConsumerPath::LocalSynchronous => manager.consume_latest(&mut surface),
|
||||||
|
RenderConsumerPath::RealWorker => {
|
||||||
|
let mut worker = LocalRenderWorker;
|
||||||
|
worker.consume_latest(&mut manager, &mut surface)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
(outcome, surface.seen, manager.render_telemetry().replaced_before_consume)
|
||||||
|
}
|
||||||
|
|
||||||
|
for path in [RenderConsumerPath::LocalSynchronous, RenderConsumerPath::RealWorker] {
|
||||||
|
let (outcome, seen, replaced) = consume_with(path);
|
||||||
|
assert_eq!(outcome, RenderConsumeOutcome::Presented { frame_id: FrameId::new(1) });
|
||||||
|
assert_eq!(seen, vec![FrameId::new(1)]);
|
||||||
|
assert_eq!(replaced, 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn matrix_epoch_stale_discard_and_telemetry_sync_remain_consistent() {
|
||||||
|
let mut manager = RenderManager::new(AppMode::Game);
|
||||||
|
let mut surface = RecordingSurface::default();
|
||||||
|
let atomic = AtomicTelemetry::new(Arc::new(AtomicU32::new(0)));
|
||||||
|
|
||||||
|
manager.transition_render_owner(AppMode::Game, 7);
|
||||||
|
close_game(&mut manager);
|
||||||
|
manager.transition_render_owner(AppMode::Game, 8);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
manager.consume_latest(&mut surface),
|
||||||
|
RenderConsumeOutcome::DiscardedStaleEpoch { frame_id: FrameId::ZERO }
|
||||||
|
);
|
||||||
|
assert!(surface.seen.is_empty());
|
||||||
|
|
||||||
|
manager.sync_telemetry(&atomic);
|
||||||
|
let snapshot = atomic.snapshot();
|
||||||
|
assert_eq!(snapshot.produced_submissions, 1);
|
||||||
|
assert_eq!(snapshot.stale_epoch_discards, 1);
|
||||||
|
assert_eq!(snapshot.presented_frames, 0);
|
||||||
|
assert_eq!(snapshot.last_dropped_frame_id, 0);
|
||||||
|
assert_eq!(snapshot.active_render_epoch, 2);
|
||||||
|
assert_eq!(manager.active_ownership(), RenderOwnership::new(2, AppMode::Game, 8));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn matrix_shutdown_failure_and_repeat_are_observable() {
|
||||||
|
let mut manager = RenderManager::new(AppMode::Game);
|
||||||
|
|
||||||
|
close_game(&mut manager);
|
||||||
|
let discarded = manager.request_shutdown().expect("pending frame discarded");
|
||||||
|
assert_eq!(discarded.frame_id, FrameId::ZERO);
|
||||||
|
|
||||||
|
manager.resume_consumer();
|
||||||
|
close_game(&mut manager);
|
||||||
|
let mut surface = PanickingSurface;
|
||||||
|
assert_eq!(
|
||||||
|
manager.consume_latest(&mut surface),
|
||||||
|
RenderConsumeOutcome::PresentFailed {
|
||||||
|
frame_id: FrameId::new(1),
|
||||||
|
message: "matrix present failure".to_string()
|
||||||
|
}
|
||||||
|
);
|
||||||
|
manager.record_repeated_present(FrameId::new(1));
|
||||||
|
|
||||||
|
let telemetry = manager.render_telemetry();
|
||||||
|
assert_eq!(telemetry.shutdown_discards, 1);
|
||||||
|
assert_eq!(telemetry.present_errors, 1);
|
||||||
|
assert_eq!(telemetry.presented_frames, 0);
|
||||||
|
assert_eq!(telemetry.repeated_presents, 1);
|
||||||
|
assert_eq!(telemetry.last_error_frame_id, 1);
|
||||||
|
assert_eq!(telemetry.last_presented_frame_id, 1);
|
||||||
|
}
|
||||||
+337
-78
@@ -1,21 +1,64 @@
|
|||||||
use super::*;
|
use super::*;
|
||||||
use crate::services::memcard::{MemcardSlotState, MemcardStatus};
|
use crate::fs::{FsState, VirtualFS};
|
||||||
|
use crate::services::memcard::{MemcardService, MemcardSlotState, MemcardStatus};
|
||||||
use prometeu_bytecode::{TRAP_INVALID_SYSCALL, TRAP_OOB, TRAP_TYPE, Value};
|
use prometeu_bytecode::{TRAP_INVALID_SYSCALL, TRAP_OOB, TRAP_TYPE, Value};
|
||||||
|
use prometeu_hal::app_mode::AppMode;
|
||||||
use prometeu_hal::asset::{AssetId, AssetOpStatus, BankType, SlotRef};
|
use prometeu_hal::asset::{AssetId, AssetOpStatus, BankType, SlotRef};
|
||||||
use prometeu_hal::cartridge::AppMode;
|
|
||||||
use prometeu_hal::color::Color;
|
use prometeu_hal::color::Color;
|
||||||
use prometeu_hal::glyph::Glyph;
|
use prometeu_hal::glyph::Glyph;
|
||||||
use prometeu_hal::log::{LogLevel, LogSource};
|
use prometeu_hal::log::{LogLevel, LogSource};
|
||||||
|
use prometeu_hal::primitives::Rect;
|
||||||
use prometeu_hal::sprite::Sprite;
|
use prometeu_hal::sprite::Sprite;
|
||||||
use prometeu_hal::syscalls::Syscall;
|
use prometeu_hal::syscalls::Syscall;
|
||||||
use prometeu_hal::vm_fault::VmFault;
|
use prometeu_hal::vm_fault::VmFault;
|
||||||
use prometeu_hal::{
|
use prometeu_hal::{
|
||||||
AudioOpStatus, ComposerOpStatus, HostContext, HostReturn, NativeInterface, SyscallId,
|
AudioOpStatus, ComposerOpStatus, Gfx2dCommand, GfxUiCommand, HostContext, HostReturn,
|
||||||
expect_bool, expect_int,
|
NativeInterface, SyscallId, expect_bool, expect_int,
|
||||||
};
|
};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::ops::{Deref, DerefMut};
|
||||||
|
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||||
use std::sync::atomic::Ordering;
|
use std::sync::atomic::Ordering;
|
||||||
|
|
||||||
impl VirtualMachineRuntime {
|
pub(crate) struct VmRuntimeHost<'a> {
|
||||||
|
pub runtime: &'a mut VirtualMachineRuntime,
|
||||||
|
pub log_service: &'a mut LogService,
|
||||||
|
pub fs: &'a mut VirtualFS,
|
||||||
|
pub fs_state: &'a mut FsState,
|
||||||
|
pub memcard: &'a mut MemcardService,
|
||||||
|
pub open_files: &'a mut HashMap<u32, String>,
|
||||||
|
pub next_handle: &'a mut u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Deref for VmRuntimeHost<'_> {
|
||||||
|
type Target = VirtualMachineRuntime;
|
||||||
|
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
self.runtime
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DerefMut for VmRuntimeHost<'_> {
|
||||||
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||||
|
self.runtime
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VmRuntimeHost<'_> {
|
||||||
|
fn log(&mut self, level: LogLevel, source: LogSource, tag: u16, msg: String) {
|
||||||
|
self.runtime.log(self.log_service, level, source, tag, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn panic_payload_to_string(payload: Box<dyn std::any::Any + Send>) -> String {
|
||||||
|
if let Some(message) = payload.downcast_ref::<String>() {
|
||||||
|
return message.clone();
|
||||||
|
}
|
||||||
|
if let Some(message) = payload.downcast_ref::<&str>() {
|
||||||
|
return (*message).to_string();
|
||||||
|
}
|
||||||
|
"host panic without string payload".to_string()
|
||||||
|
}
|
||||||
|
|
||||||
fn syscall_log_write(&mut self, level_val: i64, tag: u16, msg: String) -> Result<(), VmFault> {
|
fn syscall_log_write(&mut self, level_val: i64, tag: u16, msg: String) -> Result<(), VmFault> {
|
||||||
let level = match level_val {
|
let level = match level_val {
|
||||||
0 => LogLevel::Trace,
|
0 => LogLevel::Trace,
|
||||||
@@ -29,8 +72,8 @@ impl VirtualMachineRuntime {
|
|||||||
let app_id = self.current_app_id;
|
let app_id = self.current_app_id;
|
||||||
let count = *self.logs_written_this_frame.get(&app_id).unwrap_or(&0);
|
let count = *self.logs_written_this_frame.get(&app_id).unwrap_or(&0);
|
||||||
|
|
||||||
if count >= Self::MAX_LOGS_PER_FRAME {
|
if count >= VirtualMachineRuntime::MAX_LOGS_PER_FRAME {
|
||||||
if count == Self::MAX_LOGS_PER_FRAME {
|
if count == VirtualMachineRuntime::MAX_LOGS_PER_FRAME {
|
||||||
self.logs_written_this_frame.insert(app_id, count + 1);
|
self.logs_written_this_frame.insert(app_id, count + 1);
|
||||||
self.log(
|
self.log(
|
||||||
LogLevel::Warn,
|
LogLevel::Warn,
|
||||||
@@ -45,16 +88,18 @@ impl VirtualMachineRuntime {
|
|||||||
self.logs_written_this_frame.insert(app_id, count + 1);
|
self.logs_written_this_frame.insert(app_id, count + 1);
|
||||||
|
|
||||||
let mut final_msg = msg;
|
let mut final_msg = msg;
|
||||||
if final_msg.len() > Self::MAX_LOG_LEN {
|
if final_msg.len() > VirtualMachineRuntime::MAX_LOG_LEN {
|
||||||
final_msg.truncate(Self::MAX_LOG_LEN);
|
final_msg.truncate(VirtualMachineRuntime::MAX_LOG_LEN);
|
||||||
}
|
}
|
||||||
|
|
||||||
self.log(level, LogSource::App { app_id }, tag, final_msg);
|
self.log(level, LogSource::App { app_id }, tag, final_msg);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn get_color(&self, value: i64) -> Color {
|
pub(crate) fn get_color(&self, value: i64) -> Result<Color, VmFault> {
|
||||||
Color::from_raw(value as u16)
|
let raw = u32::try_from(value)
|
||||||
|
.map_err(|_| VmFault::Trap(TRAP_OOB, "Color value out of bounds".into()))?;
|
||||||
|
Ok(Color::from_raw(raw))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn int_arg_to_usize_status(value: i64) -> Result<usize, ComposerOpStatus> {
|
fn int_arg_to_usize_status(value: i64) -> Result<usize, ComposerOpStatus> {
|
||||||
@@ -73,9 +118,44 @@ impl VirtualMachineRuntime {
|
|||||||
fn int_arg_to_u16_status(value: i64) -> Result<u16, ComposerOpStatus> {
|
fn int_arg_to_u16_status(value: i64) -> Result<u16, ComposerOpStatus> {
|
||||||
u16::try_from(value).map_err(|_| ComposerOpStatus::ArgRangeInvalid)
|
u16::try_from(value).map_err(|_| ComposerOpStatus::ArgRangeInvalid)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn is_game_profile_syscall(syscall: Syscall) -> bool {
|
||||||
|
matches!(
|
||||||
|
syscall,
|
||||||
|
Syscall::GfxClear
|
||||||
|
| Syscall::GfxFillRect
|
||||||
|
| Syscall::GfxDrawLine
|
||||||
|
| Syscall::GfxDrawCircle
|
||||||
|
| Syscall::GfxDrawDisc
|
||||||
|
| Syscall::GfxDrawSquare
|
||||||
|
| Syscall::GfxDrawText
|
||||||
|
| Syscall::ComposerBindScene
|
||||||
|
| Syscall::ComposerUnbindScene
|
||||||
|
| Syscall::ComposerSetCamera
|
||||||
|
| Syscall::ComposerEmitSprite
|
||||||
|
| Syscall::AssetLoad
|
||||||
|
| Syscall::AssetStatus
|
||||||
|
| Syscall::AssetCommit
|
||||||
|
| Syscall::AssetCancel
|
||||||
|
| Syscall::BankInfo
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ensure_game_profile_syscall(&self, syscall: Syscall) -> Result<(), VmFault> {
|
||||||
|
if Self::is_game_profile_syscall(syscall)
|
||||||
|
&& self.current_cartridge_app_mode != AppMode::Game
|
||||||
|
{
|
||||||
|
return Err(VmFault::Trap(
|
||||||
|
TRAP_INVALID_SYSCALL,
|
||||||
|
format!("{} is only available to the Game profile", syscall.name()),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl NativeInterface for VirtualMachineRuntime {
|
impl NativeInterface for VmRuntimeHost<'_> {
|
||||||
fn syscall(
|
fn syscall(
|
||||||
&mut self,
|
&mut self,
|
||||||
id: SyscallId,
|
id: SyscallId,
|
||||||
@@ -88,23 +168,31 @@ impl NativeInterface for VirtualMachineRuntime {
|
|||||||
VmFault::Trap(TRAP_INVALID_SYSCALL, format!("Unknown syscall: 0x{:08X}", id))
|
VmFault::Trap(TRAP_INVALID_SYSCALL, format!("Unknown syscall: 0x{:08X}", id))
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
match syscall {
|
if syscall == Syscall::SystemHasCart {
|
||||||
Syscall::SystemHasCart => {
|
ret.push_bool(true);
|
||||||
ret.push_bool(true);
|
return Ok(());
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
Syscall::SystemRunCart => return Ok(()),
|
|
||||||
_ => {}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let hw = ctx.require_hw()?;
|
self.ensure_game_profile_syscall(syscall)?;
|
||||||
|
|
||||||
|
let platform = ctx.require_platform()?;
|
||||||
|
|
||||||
match syscall {
|
match syscall {
|
||||||
Syscall::SystemHasCart => unreachable!(),
|
Syscall::SystemHasCart => unreachable!(),
|
||||||
Syscall::SystemRunCart => unreachable!(),
|
|
||||||
Syscall::GfxClear => {
|
Syscall::GfxClear => {
|
||||||
let color = self.get_color(expect_int(args, 0)?);
|
let color = self.get_color(expect_int(args, 0)?)?;
|
||||||
hw.gfx_mut().clear(color);
|
self.gfx2d_commands.push(Gfx2dCommand::Clear { color });
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Syscall::GfxUiClear => {
|
||||||
|
if self.current_cartridge_app_mode != AppMode::Shell {
|
||||||
|
return Err(VmFault::Trap(
|
||||||
|
TRAP_INVALID_SYSCALL,
|
||||||
|
format!("{} is only available to the Shell profile", syscall.name()),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let color = self.get_color(expect_int(args, 0)?)?;
|
||||||
|
self.gfxui_commands.push(GfxUiCommand::Clear { color });
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
Syscall::GfxFillRect => {
|
Syscall::GfxFillRect => {
|
||||||
@@ -112,8 +200,25 @@ impl NativeInterface for VirtualMachineRuntime {
|
|||||||
let y = expect_int(args, 1)? as i32;
|
let y = expect_int(args, 1)? as i32;
|
||||||
let w = expect_int(args, 2)? as i32;
|
let w = expect_int(args, 2)? as i32;
|
||||||
let h = expect_int(args, 3)? as i32;
|
let h = expect_int(args, 3)? as i32;
|
||||||
let color = self.get_color(expect_int(args, 4)?);
|
let color = self.get_color(expect_int(args, 4)?)?;
|
||||||
hw.gfx_mut().fill_rect(x, y, w, h, color);
|
self.gfx2d_commands
|
||||||
|
.push(Gfx2dCommand::FillRect { rect: Rect { x, y, w, h }, color });
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Syscall::GfxUiFillRect => {
|
||||||
|
if self.current_cartridge_app_mode != AppMode::Shell {
|
||||||
|
return Err(VmFault::Trap(
|
||||||
|
TRAP_INVALID_SYSCALL,
|
||||||
|
format!("{} is only available to the Shell profile", syscall.name()),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let x = expect_int(args, 0)? as i32;
|
||||||
|
let y = expect_int(args, 1)? as i32;
|
||||||
|
let w = expect_int(args, 2)? as i32;
|
||||||
|
let h = expect_int(args, 3)? as i32;
|
||||||
|
let color = self.get_color(expect_int(args, 4)?)?;
|
||||||
|
self.gfxui_commands
|
||||||
|
.push(GfxUiCommand::FillRect { rect: Rect { x, y, w, h }, color });
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
Syscall::GfxDrawLine => {
|
Syscall::GfxDrawLine => {
|
||||||
@@ -121,25 +226,93 @@ impl NativeInterface for VirtualMachineRuntime {
|
|||||||
let y1 = expect_int(args, 1)? as i32;
|
let y1 = expect_int(args, 1)? as i32;
|
||||||
let x2 = expect_int(args, 2)? as i32;
|
let x2 = expect_int(args, 2)? as i32;
|
||||||
let y2 = expect_int(args, 3)? as i32;
|
let y2 = expect_int(args, 3)? as i32;
|
||||||
let color = self.get_color(expect_int(args, 4)?);
|
let color = self.get_color(expect_int(args, 4)?)?;
|
||||||
hw.gfx_mut().draw_line(x1, y1, x2, y2, color);
|
self.gfx2d_commands.push(Gfx2dCommand::DrawLine {
|
||||||
|
x0: x1,
|
||||||
|
y0: y1,
|
||||||
|
x1: x2,
|
||||||
|
y1: y2,
|
||||||
|
color,
|
||||||
|
});
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Syscall::GfxUiDrawLine => {
|
||||||
|
if self.current_cartridge_app_mode != AppMode::Shell {
|
||||||
|
return Err(VmFault::Trap(
|
||||||
|
TRAP_INVALID_SYSCALL,
|
||||||
|
format!("{} is only available to the Shell profile", syscall.name()),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let x1 = expect_int(args, 0)? as i32;
|
||||||
|
let y1 = expect_int(args, 1)? as i32;
|
||||||
|
let x2 = expect_int(args, 2)? as i32;
|
||||||
|
let y2 = expect_int(args, 3)? as i32;
|
||||||
|
let color = self.get_color(expect_int(args, 4)?)?;
|
||||||
|
self.gfxui_commands.push(GfxUiCommand::DrawLine {
|
||||||
|
x0: x1,
|
||||||
|
y0: y1,
|
||||||
|
x1: x2,
|
||||||
|
y1: y2,
|
||||||
|
color,
|
||||||
|
});
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
Syscall::GfxDrawCircle => {
|
Syscall::GfxDrawCircle => {
|
||||||
let x = expect_int(args, 0)? as i32;
|
let x = expect_int(args, 0)? as i32;
|
||||||
let y = expect_int(args, 1)? as i32;
|
let y = expect_int(args, 1)? as i32;
|
||||||
let r = expect_int(args, 2)? as i32;
|
let r = expect_int(args, 2)? as i32;
|
||||||
let color = self.get_color(expect_int(args, 3)?);
|
let color = self.get_color(expect_int(args, 3)?)?;
|
||||||
hw.gfx_mut().draw_circle(x, y, r, color);
|
self.gfx2d_commands.push(Gfx2dCommand::DrawCircle { x, y, radius: r, color });
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Syscall::GfxUiDrawCircle => {
|
||||||
|
if self.current_cartridge_app_mode != AppMode::Shell {
|
||||||
|
return Err(VmFault::Trap(
|
||||||
|
TRAP_INVALID_SYSCALL,
|
||||||
|
format!("{} is only available to the Shell profile", syscall.name()),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let x = expect_int(args, 0)? as i32;
|
||||||
|
let y = expect_int(args, 1)? as i32;
|
||||||
|
let r = expect_int(args, 2)? as i32;
|
||||||
|
let color = self.get_color(expect_int(args, 3)?)?;
|
||||||
|
self.gfxui_commands.push(GfxUiCommand::DrawCircle { x, y, radius: r, color });
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
Syscall::GfxDrawDisc => {
|
Syscall::GfxDrawDisc => {
|
||||||
let x = expect_int(args, 0)? as i32;
|
let x = expect_int(args, 0)? as i32;
|
||||||
let y = expect_int(args, 1)? as i32;
|
let y = expect_int(args, 1)? as i32;
|
||||||
let r = expect_int(args, 2)? as i32;
|
let r = expect_int(args, 2)? as i32;
|
||||||
let border_color = self.get_color(expect_int(args, 3)?);
|
let border_color = self.get_color(expect_int(args, 3)?)?;
|
||||||
let fill_color = self.get_color(expect_int(args, 4)?);
|
let fill_color = self.get_color(expect_int(args, 4)?)?;
|
||||||
hw.gfx_mut().draw_disc(x, y, r, border_color, fill_color);
|
self.gfx2d_commands.push(Gfx2dCommand::DrawDisc {
|
||||||
|
x,
|
||||||
|
y,
|
||||||
|
radius: r,
|
||||||
|
border_color,
|
||||||
|
fill_color,
|
||||||
|
});
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Syscall::GfxUiDrawDisc => {
|
||||||
|
if self.current_cartridge_app_mode != AppMode::Shell {
|
||||||
|
return Err(VmFault::Trap(
|
||||||
|
TRAP_INVALID_SYSCALL,
|
||||||
|
format!("{} is only available to the Shell profile", syscall.name()),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let x = expect_int(args, 0)? as i32;
|
||||||
|
let y = expect_int(args, 1)? as i32;
|
||||||
|
let r = expect_int(args, 2)? as i32;
|
||||||
|
let border_color = self.get_color(expect_int(args, 3)?)?;
|
||||||
|
let fill_color = self.get_color(expect_int(args, 4)?)?;
|
||||||
|
self.gfxui_commands.push(GfxUiCommand::DrawDisc {
|
||||||
|
x,
|
||||||
|
y,
|
||||||
|
radius: r,
|
||||||
|
border_color,
|
||||||
|
fill_color,
|
||||||
|
});
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
Syscall::GfxDrawSquare => {
|
Syscall::GfxDrawSquare => {
|
||||||
@@ -147,25 +320,55 @@ impl NativeInterface for VirtualMachineRuntime {
|
|||||||
let y = expect_int(args, 1)? as i32;
|
let y = expect_int(args, 1)? as i32;
|
||||||
let w = expect_int(args, 2)? as i32;
|
let w = expect_int(args, 2)? as i32;
|
||||||
let h = expect_int(args, 3)? as i32;
|
let h = expect_int(args, 3)? as i32;
|
||||||
let border_color = self.get_color(expect_int(args, 4)?);
|
let border_color = self.get_color(expect_int(args, 4)?)?;
|
||||||
let fill_color = self.get_color(expect_int(args, 5)?);
|
let fill_color = self.get_color(expect_int(args, 5)?)?;
|
||||||
hw.gfx_mut().draw_square(x, y, w, h, border_color, fill_color);
|
self.gfx2d_commands.push(Gfx2dCommand::DrawSquare {
|
||||||
|
rect: Rect { x, y, w, h },
|
||||||
|
border_color,
|
||||||
|
fill_color,
|
||||||
|
});
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Syscall::GfxUiDrawSquare => {
|
||||||
|
if self.current_cartridge_app_mode != AppMode::Shell {
|
||||||
|
return Err(VmFault::Trap(
|
||||||
|
TRAP_INVALID_SYSCALL,
|
||||||
|
format!("{} is only available to the Shell profile", syscall.name()),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let x = expect_int(args, 0)? as i32;
|
||||||
|
let y = expect_int(args, 1)? as i32;
|
||||||
|
let w = expect_int(args, 2)? as i32;
|
||||||
|
let h = expect_int(args, 3)? as i32;
|
||||||
|
let border_color = self.get_color(expect_int(args, 4)?)?;
|
||||||
|
let fill_color = self.get_color(expect_int(args, 5)?)?;
|
||||||
|
self.gfxui_commands.push(GfxUiCommand::DrawSquare {
|
||||||
|
rect: Rect { x, y, w, h },
|
||||||
|
border_color,
|
||||||
|
fill_color,
|
||||||
|
});
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
Syscall::GfxDrawText => {
|
Syscall::GfxDrawText => {
|
||||||
let x = expect_int(args, 0)? as i32;
|
let x = expect_int(args, 0)? as i32;
|
||||||
let y = expect_int(args, 1)? as i32;
|
let y = expect_int(args, 1)? as i32;
|
||||||
let msg = expect_string(args, 2, "message")?;
|
let msg = expect_string(args, 2, "message")?;
|
||||||
let color = self.get_color(expect_int(args, 3)?);
|
let color = self.get_color(expect_int(args, 3)?)?;
|
||||||
hw.gfx_mut().draw_text(x, y, &msg, color);
|
self.gfx2d_commands.push(Gfx2dCommand::DrawText { x, y, text: msg.clone(), color });
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
Syscall::GfxClear565 => {
|
Syscall::GfxUiDrawText => {
|
||||||
let color_val = expect_int(args, 0)? as u32;
|
if self.current_cartridge_app_mode != AppMode::Shell {
|
||||||
if color_val > 0xFFFF {
|
return Err(VmFault::Trap(
|
||||||
return Err(VmFault::Trap(TRAP_OOB, "Color value out of bounds".into()));
|
TRAP_INVALID_SYSCALL,
|
||||||
|
format!("{} is only available to the Shell profile", syscall.name()),
|
||||||
|
));
|
||||||
}
|
}
|
||||||
hw.gfx_mut().clear(Color::from_raw(color_val as u16));
|
let x = expect_int(args, 0)? as i32;
|
||||||
|
let y = expect_int(args, 1)? as i32;
|
||||||
|
let msg = expect_string(args, 2, "message")?;
|
||||||
|
let color = self.get_color(expect_int(args, 3)?)?;
|
||||||
|
self.gfxui_commands.push(GfxUiCommand::DrawText { x, y, text: msg.clone(), color });
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
Syscall::ComposerBindScene => {
|
Syscall::ComposerBindScene => {
|
||||||
@@ -177,23 +380,23 @@ impl NativeInterface for VirtualMachineRuntime {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let status = if hw.bind_scene(scene_bank_id) {
|
let status = catch_unwind(AssertUnwindSafe(|| {
|
||||||
ComposerOpStatus::Ok
|
platform.game2d_frame_composer().bind_scene(scene_bank_id)
|
||||||
} else {
|
}))
|
||||||
ComposerOpStatus::SceneUnavailable
|
.map_err(|payload| VmFault::Panic(Self::panic_payload_to_string(payload)))?;
|
||||||
};
|
|
||||||
ret.push_int(status as i64);
|
ret.push_int(status as i64);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
Syscall::ComposerUnbindScene => {
|
Syscall::ComposerUnbindScene => {
|
||||||
hw.unbind_scene();
|
platform.game2d_frame_composer().unbind_scene();
|
||||||
ret.push_int(ComposerOpStatus::Ok as i64);
|
ret.push_int(ComposerOpStatus::Ok as i64);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
Syscall::ComposerSetCamera => {
|
Syscall::ComposerSetCamera => {
|
||||||
let x = Self::int_arg_to_i32_trap(expect_int(args, 0)?, "camera x")?;
|
let x = Self::int_arg_to_i32_trap(expect_int(args, 0)?, "camera x")?;
|
||||||
let y = Self::int_arg_to_i32_trap(expect_int(args, 1)?, "camera y")?;
|
let y = Self::int_arg_to_i32_trap(expect_int(args, 1)?, "camera y")?;
|
||||||
hw.set_camera(x, y);
|
platform.game2d_frame_composer().set_camera(x, y);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
Syscall::ComposerEmitSprite => {
|
Syscall::ComposerEmitSprite => {
|
||||||
@@ -241,12 +444,7 @@ impl NativeInterface for VirtualMachineRuntime {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if !hw.has_glyph_bank(bank_id as usize) {
|
let status = platform.game2d_frame_composer().emit_sprite(Sprite {
|
||||||
ret.push_int(ComposerOpStatus::BankInvalid as i64);
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
let emitted = hw.emit_sprite(Sprite {
|
|
||||||
glyph: Glyph { glyph_id, palette_id },
|
glyph: Glyph { glyph_id, palette_id },
|
||||||
x,
|
x,
|
||||||
y,
|
y,
|
||||||
@@ -257,8 +455,6 @@ impl NativeInterface for VirtualMachineRuntime {
|
|||||||
flip_y,
|
flip_y,
|
||||||
priority,
|
priority,
|
||||||
});
|
});
|
||||||
let status =
|
|
||||||
if emitted { ComposerOpStatus::Ok } else { ComposerOpStatus::SpriteOverflow };
|
|
||||||
ret.push_int(status as i64);
|
ret.push_int(status as i64);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -285,7 +481,7 @@ impl NativeInterface for VirtualMachineRuntime {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
let status = hw.audio_mut().play(
|
let status = platform.audio_mut().play(
|
||||||
0,
|
0,
|
||||||
sample_id_raw as u16,
|
sample_id_raw as u16,
|
||||||
voice_id_raw as usize,
|
voice_id_raw as usize,
|
||||||
@@ -315,7 +511,8 @@ impl NativeInterface for VirtualMachineRuntime {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
if hw.assets().slot_info(SlotRef::audio(bank_id as usize)).asset_id.is_none() {
|
if platform.assets().slot_info(SlotRef::audio(bank_id as usize)).asset_id.is_none()
|
||||||
|
{
|
||||||
ret.push_int(AudioOpStatus::BankInvalid as i64);
|
ret.push_int(AudioOpStatus::BankInvalid as i64);
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
@@ -331,7 +528,7 @@ impl NativeInterface for VirtualMachineRuntime {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
let status = hw.audio_mut().play(
|
let status = platform.audio_mut().play(
|
||||||
bank_id,
|
bank_id,
|
||||||
sample_id_raw as u16,
|
sample_id_raw as u16,
|
||||||
voice_id_raw as usize,
|
voice_id_raw as usize,
|
||||||
@@ -346,13 +543,13 @@ impl NativeInterface for VirtualMachineRuntime {
|
|||||||
}
|
}
|
||||||
Syscall::FsOpen => {
|
Syscall::FsOpen => {
|
||||||
let path = expect_string(args, 0, "path")?;
|
let path = expect_string(args, 0, "path")?;
|
||||||
if self.fs_state != FsState::Mounted {
|
if *self.fs_state != FsState::Mounted {
|
||||||
ret.push_int(-1);
|
ret.push_int(-1);
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
let handle = self.next_handle;
|
let handle = *self.next_handle;
|
||||||
self.open_files.insert(handle, path);
|
self.open_files.insert(handle, path);
|
||||||
self.next_handle += 1;
|
*self.next_handle += 1;
|
||||||
ret.push_int(handle as i64);
|
ret.push_int(handle as i64);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -361,8 +558,9 @@ impl NativeInterface for VirtualMachineRuntime {
|
|||||||
let path = self
|
let path = self
|
||||||
.open_files
|
.open_files
|
||||||
.get(&handle)
|
.get(&handle)
|
||||||
.ok_or_else(|| VmFault::Panic("Invalid handle".into()))?;
|
.ok_or_else(|| VmFault::Panic("Invalid handle".into()))?
|
||||||
match self.fs.read_file(path) {
|
.clone();
|
||||||
|
match self.fs.read_file(&path) {
|
||||||
Ok(data) => ret.push_string(String::from_utf8_lossy(&data).into_owned()),
|
Ok(data) => ret.push_string(String::from_utf8_lossy(&data).into_owned()),
|
||||||
Err(_) => ret.push_null(),
|
Err(_) => ret.push_null(),
|
||||||
}
|
}
|
||||||
@@ -374,8 +572,9 @@ impl NativeInterface for VirtualMachineRuntime {
|
|||||||
let path = self
|
let path = self
|
||||||
.open_files
|
.open_files
|
||||||
.get(&handle)
|
.get(&handle)
|
||||||
.ok_or_else(|| VmFault::Panic("Invalid handle".into()))?;
|
.ok_or_else(|| VmFault::Panic("Invalid handle".into()))?
|
||||||
match self.fs.write_file(path, &content) {
|
.clone();
|
||||||
|
match self.fs.write_file(&path, &content) {
|
||||||
Ok(_) => ret.push_bool(true),
|
Ok(_) => ret.push_bool(true),
|
||||||
Err(_) => ret.push_bool(false),
|
Err(_) => ret.push_bool(false),
|
||||||
}
|
}
|
||||||
@@ -427,7 +626,7 @@ impl NativeInterface for VirtualMachineRuntime {
|
|||||||
ret.push_int(0);
|
ret.push_int(0);
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
let stat = self.memcard.slot_stat(&self.fs, self.current_app_id, slot);
|
let stat = self.memcard.slot_stat(self.fs, self.current_app_id, slot);
|
||||||
let status = if stat.state == MemcardSlotState::Corrupt {
|
let status = if stat.state == MemcardSlotState::Corrupt {
|
||||||
MemcardStatus::Corrupt
|
MemcardStatus::Corrupt
|
||||||
} else {
|
} else {
|
||||||
@@ -451,7 +650,7 @@ impl NativeInterface for VirtualMachineRuntime {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
let read =
|
let read =
|
||||||
self.memcard.slot_read(&self.fs, self.current_app_id, slot, offset, max_bytes);
|
self.memcard.slot_read(self.fs, self.current_app_id, slot, offset, max_bytes);
|
||||||
ret.push_int(read.status as i64);
|
ret.push_int(read.status as i64);
|
||||||
ret.push_string(hex_encode(&read.bytes));
|
ret.push_string(hex_encode(&read.bytes));
|
||||||
ret.push_int(read.bytes_read as i64);
|
ret.push_int(read.bytes_read as i64);
|
||||||
@@ -467,8 +666,8 @@ impl NativeInterface for VirtualMachineRuntime {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
let payload = hex_decode(&payload_hex)?;
|
let payload = hex_decode(&payload_hex)?;
|
||||||
let write =
|
let app_id = self.current_app_id;
|
||||||
self.memcard.slot_write(&self.fs, self.current_app_id, slot, offset, &payload);
|
let write = self.memcard.slot_write(self.fs, app_id, slot, offset, &payload);
|
||||||
ret.push_int(write.status as i64);
|
ret.push_int(write.status as i64);
|
||||||
ret.push_int(write.bytes_written as i64);
|
ret.push_int(write.bytes_written as i64);
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -480,9 +679,10 @@ impl NativeInterface for VirtualMachineRuntime {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
let status = {
|
let status = {
|
||||||
|
let app_id = self.current_app_id;
|
||||||
let memcard = &mut self.memcard;
|
let memcard = &mut self.memcard;
|
||||||
let fs = &mut self.fs;
|
let fs = &mut self.fs;
|
||||||
memcard.slot_commit(fs, self.current_app_id, slot)
|
memcard.slot_commit(fs, app_id, slot)
|
||||||
};
|
};
|
||||||
ret.push_int(status as i64);
|
ret.push_int(status as i64);
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -494,9 +694,10 @@ impl NativeInterface for VirtualMachineRuntime {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
let status = {
|
let status = {
|
||||||
|
let app_id = self.current_app_id;
|
||||||
let memcard = &mut self.memcard;
|
let memcard = &mut self.memcard;
|
||||||
let fs = &mut self.fs;
|
let fs = &mut self.fs;
|
||||||
memcard.slot_clear(fs, self.current_app_id, slot)
|
memcard.slot_clear(fs, app_id, slot)
|
||||||
};
|
};
|
||||||
ret.push_int(status as i64);
|
ret.push_int(status as i64);
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -524,7 +725,7 @@ impl NativeInterface for VirtualMachineRuntime {
|
|||||||
})?;
|
})?;
|
||||||
let slot_index = expect_int(args, 1)? as usize;
|
let slot_index = expect_int(args, 1)? as usize;
|
||||||
|
|
||||||
match hw.assets().load(asset_id, slot_index) {
|
match platform.assets().load(asset_id, slot_index) {
|
||||||
Ok(handle) => {
|
Ok(handle) => {
|
||||||
ret.push_int(AssetOpStatus::Ok as i64);
|
ret.push_int(AssetOpStatus::Ok as i64);
|
||||||
ret.push_int(handle as i64);
|
ret.push_int(handle as i64);
|
||||||
@@ -538,26 +739,84 @@ impl NativeInterface for VirtualMachineRuntime {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Syscall::AssetStatus => {
|
Syscall::AssetStatus => {
|
||||||
ret.push_int(hw.assets().status(expect_int(args, 0)? as u32) as i64);
|
ret.push_int(platform.assets().status(expect_int(args, 0)? as u32) as i64);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
Syscall::AssetCommit => {
|
Syscall::AssetCommit => {
|
||||||
let status = hw.assets().commit(expect_int(args, 0)? as u32);
|
let status = platform.assets().commit(expect_int(args, 0)? as u32);
|
||||||
ret.push_int(status as i64);
|
ret.push_int(status as i64);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
Syscall::AssetCancel => {
|
Syscall::AssetCancel => {
|
||||||
let status = hw.assets().cancel(expect_int(args, 0)? as u32);
|
let status = platform.assets().cancel(expect_int(args, 0)? as u32);
|
||||||
ret.push_int(status as i64);
|
ret.push_int(status as i64);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
Syscall::AssetBacklogInfo => {
|
||||||
|
let info = platform.assets().backlog_info();
|
||||||
|
ret.push_int(info.status as i64);
|
||||||
|
ret.push_int(info.pending_count as i64);
|
||||||
|
ret.push_int(info.active_handle as i64);
|
||||||
|
ret.push_int(info.active_asset_id.unwrap_or(0) as i64);
|
||||||
|
ret.push_int(info.active_bank_type.map(|bank| bank as i64).unwrap_or(0));
|
||||||
|
ret.push_int(info.active_slot.map(|slot| slot as i64).unwrap_or(0));
|
||||||
|
ret.push_int(info.active_progress as i64);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Syscall::AssetBacklogPosition => {
|
||||||
|
let position = platform.assets().backlog_position(expect_int(args, 0)? as u32);
|
||||||
|
ret.push_int(position.status as i64);
|
||||||
|
ret.push_int(position.state as i64);
|
||||||
|
ret.push_int(position.position as i64);
|
||||||
|
ret.push_int(position.progress as i64);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Syscall::AssetBacklogMove => {
|
||||||
|
let new_position = expect_non_negative_usize(args, 1, "new_position")?;
|
||||||
|
let status =
|
||||||
|
platform.assets().backlog_move(expect_int(args, 0)? as u32, new_position);
|
||||||
|
ret.push_int(status as i64);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Syscall::AssetBacklogPromote => {
|
||||||
|
let status = platform.assets().backlog_promote(expect_int(args, 0)? as u32);
|
||||||
|
ret.push_int(status as i64);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Syscall::AssetBacklogDemote => {
|
||||||
|
let status = platform.assets().backlog_demote(expect_int(args, 0)? as u32);
|
||||||
|
ret.push_int(status as i64);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Syscall::AssetTargetStatus => {
|
||||||
|
let bank_type = match expect_int(args, 0)? {
|
||||||
|
0 => BankType::GLYPH,
|
||||||
|
1 => BankType::SOUNDS,
|
||||||
|
2 => BankType::SCENE,
|
||||||
|
other => {
|
||||||
|
return Err(VmFault::Trap(
|
||||||
|
TRAP_TYPE,
|
||||||
|
format!("Invalid asset bank type: {}", other),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let slot = expect_non_negative_usize(args, 1, "slot")?;
|
||||||
|
let target = platform.assets().target_status(bank_type, slot);
|
||||||
|
ret.push_int(target.status as i64);
|
||||||
|
ret.push_int(target.asset_id.unwrap_or(0) as i64);
|
||||||
|
ret.push_int(target.handle as i64);
|
||||||
|
ret.push_int(target.state as i64);
|
||||||
|
ret.push_int(target.position as i64);
|
||||||
|
ret.push_int(target.progress as i64);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
Syscall::BankInfo => {
|
Syscall::BankInfo => {
|
||||||
let asset_type = match expect_int(args, 0)? as u32 {
|
let asset_type = match expect_int(args, 0)? as u32 {
|
||||||
0 => BankType::GLYPH,
|
0 => BankType::GLYPH,
|
||||||
1 => BankType::SOUNDS,
|
1 => BankType::SOUNDS,
|
||||||
_ => return Err(VmFault::Trap(TRAP_TYPE, "Invalid asset type".to_string())),
|
_ => return Err(VmFault::Trap(TRAP_TYPE, "Invalid asset type".to_string())),
|
||||||
};
|
};
|
||||||
let telemetry = hw
|
let telemetry = platform
|
||||||
.assets()
|
.assets()
|
||||||
.bank_telemetry()
|
.bank_telemetry()
|
||||||
.into_iter()
|
.into_iter()
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
use prometeu_hal::FrameId;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum FrameAuthorizationError {
|
||||||
|
GameFrameAlreadyActive { active_frame_id: FrameId },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default)]
|
||||||
|
pub struct FrameScheduler {
|
||||||
|
next_game_frame_id: FrameId,
|
||||||
|
active_game_frame_id: Option<FrameId>,
|
||||||
|
completed_game_frames: u64,
|
||||||
|
logical_frame_overruns: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FrameScheduler {
|
||||||
|
pub fn authorize_game_frame(&mut self) -> Result<FrameId, FrameAuthorizationError> {
|
||||||
|
if let Some(active_frame_id) = self.active_game_frame_id {
|
||||||
|
return Err(FrameAuthorizationError::GameFrameAlreadyActive { active_frame_id });
|
||||||
|
}
|
||||||
|
|
||||||
|
let frame_id = self.next_game_frame_id;
|
||||||
|
self.next_game_frame_id = self.next_game_frame_id.next();
|
||||||
|
self.active_game_frame_id = Some(frame_id);
|
||||||
|
Ok(frame_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn complete_game_frame(&mut self) -> Option<FrameId> {
|
||||||
|
let completed = self.active_game_frame_id.take();
|
||||||
|
if completed.is_some() {
|
||||||
|
self.completed_game_frames = self.completed_game_frames.wrapping_add(1);
|
||||||
|
}
|
||||||
|
completed
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn record_logical_frame_overrun(&mut self) {
|
||||||
|
self.logical_frame_overruns = self.logical_frame_overruns.wrapping_add(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn active_game_frame_id(&self) -> Option<FrameId> {
|
||||||
|
self.active_game_frame_id
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn completed_game_frames(&self) -> u64 {
|
||||||
|
self.completed_game_frames
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn logical_frame_overruns(&self) -> u64 {
|
||||||
|
self.logical_frame_overruns
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn authorizes_one_game_frame_until_completion() {
|
||||||
|
let mut scheduler = FrameScheduler::default();
|
||||||
|
|
||||||
|
assert_eq!(scheduler.authorize_game_frame(), Ok(FrameId::ZERO));
|
||||||
|
assert_eq!(
|
||||||
|
scheduler.authorize_game_frame(),
|
||||||
|
Err(FrameAuthorizationError::GameFrameAlreadyActive { active_frame_id: FrameId::ZERO })
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(scheduler.complete_game_frame(), Some(FrameId::ZERO));
|
||||||
|
assert_eq!(scheduler.authorize_game_frame(), Ok(FrameId::new(1)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn completion_is_sequential_without_catch_up_frames() {
|
||||||
|
let mut scheduler = FrameScheduler::default();
|
||||||
|
|
||||||
|
for expected in 0..3 {
|
||||||
|
let frame_id = scheduler.authorize_game_frame().expect("frame authorization");
|
||||||
|
assert_eq!(frame_id, FrameId::new(expected));
|
||||||
|
assert_eq!(scheduler.complete_game_frame(), Some(FrameId::new(expected)));
|
||||||
|
}
|
||||||
|
|
||||||
|
assert_eq!(scheduler.completed_game_frames(), 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn records_logical_frame_overrun_without_advancing_frame_id() {
|
||||||
|
let mut scheduler = FrameScheduler::default();
|
||||||
|
|
||||||
|
assert_eq!(scheduler.authorize_game_frame(), Ok(FrameId::ZERO));
|
||||||
|
scheduler.record_logical_frame_overrun();
|
||||||
|
scheduler.record_logical_frame_overrun();
|
||||||
|
|
||||||
|
assert_eq!(scheduler.logical_frame_overruns(), 2);
|
||||||
|
assert_eq!(scheduler.active_game_frame_id(), Some(FrameId::ZERO));
|
||||||
|
assert_eq!(scheduler.complete_game_frame(), Some(FrameId::ZERO));
|
||||||
|
assert_eq!(scheduler.authorize_game_frame(), Ok(FrameId::new(1)));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,266 @@
|
|||||||
|
use super::*;
|
||||||
|
use crate::CrashReport;
|
||||||
|
use crate::fs::{FsBackend, FsState, VirtualFS};
|
||||||
|
use prometeu_hal::cartridge::Cartridge;
|
||||||
|
use prometeu_hal::log::{LogLevel, LogSource};
|
||||||
|
use prometeu_hal::{FrameId, RenderWorkerBackend, RenderWorkerError, RenderWorkerFrameSink};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
impl VirtualMachineRuntime {
|
||||||
|
pub fn new_with_log_counter(
|
||||||
|
cap_config: Option<CertificationConfig>,
|
||||||
|
logs_count: Arc<AtomicU32>,
|
||||||
|
) -> Self {
|
||||||
|
let boot_time = Instant::now();
|
||||||
|
let atomic_telemetry = Arc::new(AtomicTelemetry::new(logs_count));
|
||||||
|
Self {
|
||||||
|
tick_index: 0,
|
||||||
|
logical_frame_index: 0,
|
||||||
|
logical_frame_active: false,
|
||||||
|
logical_frame_remaining_cycles: 0,
|
||||||
|
last_frame_cpu_time_us: 0,
|
||||||
|
current_app_id: 0,
|
||||||
|
current_cartridge_title: String::new(),
|
||||||
|
current_cartridge_app_version: String::new(),
|
||||||
|
current_cartridge_app_mode: AppMode::Game,
|
||||||
|
frame_scheduler: FrameScheduler::default(),
|
||||||
|
render_capabilities: RenderRuntimeCapabilities::default(),
|
||||||
|
render_manager: RenderManager::new(AppMode::Game),
|
||||||
|
render_worker_handoff: Arc::new(RenderWorkerHandoff::default()),
|
||||||
|
render_worker_ownership: RenderWorkerOwnership::default(),
|
||||||
|
render_worker_controller: None,
|
||||||
|
gfx2d_commands: Vec::new(),
|
||||||
|
gfxui_commands: Vec::new(),
|
||||||
|
logs_written_this_frame: HashMap::new(),
|
||||||
|
game_lifecycle_events_delivered: Vec::new(),
|
||||||
|
atomic_telemetry,
|
||||||
|
last_crash_report: None,
|
||||||
|
certifier: Certifier::new(cap_config.unwrap_or_default()),
|
||||||
|
paused: false,
|
||||||
|
debug_step_request: false,
|
||||||
|
inspection_active: false,
|
||||||
|
frame_start_heap_allocations: 0,
|
||||||
|
frame_start_string_materializations: 0,
|
||||||
|
needs_prepare_entry_call: false,
|
||||||
|
boot_time,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn log(
|
||||||
|
&self,
|
||||||
|
log_service: &mut LogService,
|
||||||
|
level: LogLevel,
|
||||||
|
source: LogSource,
|
||||||
|
tag: u16,
|
||||||
|
msg: String,
|
||||||
|
) {
|
||||||
|
let ts_ms = self.boot_time.elapsed().as_millis() as u64;
|
||||||
|
let frame = self.logical_frame_index;
|
||||||
|
log_service.log(ts_ms, frame, level, source, tag, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mount_fs(
|
||||||
|
&mut self,
|
||||||
|
log_service: &mut LogService,
|
||||||
|
fs: &mut VirtualFS,
|
||||||
|
fs_state: &mut FsState,
|
||||||
|
backend: Box<dyn FsBackend>,
|
||||||
|
) {
|
||||||
|
self.log(
|
||||||
|
log_service,
|
||||||
|
LogLevel::Info,
|
||||||
|
LogSource::Fs,
|
||||||
|
0,
|
||||||
|
"Attempting to mount filesystem".to_string(),
|
||||||
|
);
|
||||||
|
match fs.mount(backend) {
|
||||||
|
Ok(_) => {
|
||||||
|
*fs_state = FsState::Mounted;
|
||||||
|
self.log(
|
||||||
|
log_service,
|
||||||
|
LogLevel::Info,
|
||||||
|
LogSource::Fs,
|
||||||
|
0,
|
||||||
|
"Filesystem mounted successfully".to_string(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
let err_msg = format!("Failed to mount filesystem: {:?}", e);
|
||||||
|
self.log(log_service, LogLevel::Error, LogSource::Fs, 0, err_msg);
|
||||||
|
*fs_state = FsState::Error(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn unmount_fs(&mut self, fs: &mut VirtualFS, fs_state: &mut FsState) {
|
||||||
|
fs.unmount();
|
||||||
|
*fs_state = FsState::Unmounted;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn update_fs(
|
||||||
|
&mut self,
|
||||||
|
log_service: &mut LogService,
|
||||||
|
fs: &mut VirtualFS,
|
||||||
|
fs_state: &mut FsState,
|
||||||
|
) {
|
||||||
|
if *fs_state == FsState::Mounted && !fs.is_healthy() {
|
||||||
|
self.log(
|
||||||
|
log_service,
|
||||||
|
LogLevel::Error,
|
||||||
|
LogSource::Fs,
|
||||||
|
0,
|
||||||
|
"Filesystem became unhealthy, unmounting".to_string(),
|
||||||
|
);
|
||||||
|
self.unmount_fs(fs, fs_state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn clear_cartridge_state(&mut self) {
|
||||||
|
self.logical_frame_index = 0;
|
||||||
|
self.logical_frame_active = false;
|
||||||
|
self.logical_frame_remaining_cycles = 0;
|
||||||
|
self.last_frame_cpu_time_us = 0;
|
||||||
|
self.atomic_telemetry.reset();
|
||||||
|
|
||||||
|
self.current_app_id = 0;
|
||||||
|
self.current_cartridge_title.clear();
|
||||||
|
self.current_cartridge_app_version.clear();
|
||||||
|
self.current_cartridge_app_mode = AppMode::Game;
|
||||||
|
self.frame_scheduler = FrameScheduler::default();
|
||||||
|
self.render_capabilities = RenderRuntimeCapabilities::default();
|
||||||
|
self.render_manager = RenderManager::new(AppMode::Game);
|
||||||
|
let _ = self.stop_render_worker();
|
||||||
|
self.render_worker_handoff = Arc::new(RenderWorkerHandoff::default());
|
||||||
|
self.render_worker_ownership =
|
||||||
|
RenderWorkerOwnership::new(self.render_manager.active_ownership());
|
||||||
|
self.gfx2d_commands.clear();
|
||||||
|
self.gfxui_commands.clear();
|
||||||
|
self.logs_written_this_frame.clear();
|
||||||
|
self.game_lifecycle_events_delivered.clear();
|
||||||
|
|
||||||
|
self.last_crash_report = None;
|
||||||
|
|
||||||
|
self.paused = false;
|
||||||
|
self.debug_step_request = false;
|
||||||
|
self.inspection_active = false;
|
||||||
|
self.frame_start_heap_allocations = 0;
|
||||||
|
self.frame_start_string_materializations = 0;
|
||||||
|
self.needs_prepare_entry_call = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn reset(&mut self, vm: &mut VirtualMachine) {
|
||||||
|
*vm = VirtualMachine::default();
|
||||||
|
self.clear_cartridge_state();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_render_runtime_capabilities(&mut self, capabilities: RenderRuntimeCapabilities) {
|
||||||
|
self.render_capabilities = capabilities;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn start_render_worker<B, S>(&mut self, config: RenderWorkerConfig, backend: B, sink: S)
|
||||||
|
where
|
||||||
|
B: RenderWorkerBackend,
|
||||||
|
S: RenderWorkerFrameSink,
|
||||||
|
{
|
||||||
|
let _ = self.stop_render_worker();
|
||||||
|
self.render_worker_handoff = Arc::new(RenderWorkerHandoff::default());
|
||||||
|
self.render_worker_ownership.set(self.render_manager.active_ownership());
|
||||||
|
self.render_worker_controller = Some(RenderWorkerController::start(
|
||||||
|
config,
|
||||||
|
Arc::clone(&self.render_worker_handoff),
|
||||||
|
self.render_worker_ownership.clone(),
|
||||||
|
backend,
|
||||||
|
sink,
|
||||||
|
));
|
||||||
|
self.render_capabilities.game_render_worker = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn stop_render_worker(&mut self) -> Result<(), RenderWorkerError> {
|
||||||
|
if let Some(mut controller) = self.render_worker_controller.take() {
|
||||||
|
controller.stop()
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn sync_render_worker_ownership(&self) {
|
||||||
|
self.render_worker_ownership.set(self.render_manager.active_ownership());
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn record_repeated_render_worker_frame(&self, frame_id: FrameId) {
|
||||||
|
if let Some(controller) = self.render_worker_controller.as_ref() {
|
||||||
|
controller.record_repeated_frame(frame_id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn deliver_game_lifecycle_events<I>(&mut self, events: I)
|
||||||
|
where
|
||||||
|
I: IntoIterator<Item = GameLifecycleEvent>,
|
||||||
|
{
|
||||||
|
self.game_lifecycle_events_delivered.extend(events);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn delivered_game_lifecycle_events(&self) -> &[GameLifecycleEvent] {
|
||||||
|
&self.game_lifecycle_events_delivered
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn take_delivered_game_lifecycle_events(&mut self) -> Vec<GameLifecycleEvent> {
|
||||||
|
std::mem::take(&mut self.game_lifecycle_events_delivered)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn initialize_vm(
|
||||||
|
&mut self,
|
||||||
|
log_service: &mut LogService,
|
||||||
|
vm: &mut VirtualMachine,
|
||||||
|
cartridge: &Cartridge,
|
||||||
|
) -> Result<(), CrashReport> {
|
||||||
|
self.clear_cartridge_state();
|
||||||
|
vm.set_capabilities(cartridge.capabilities);
|
||||||
|
|
||||||
|
match vm.initialize(cartridge.program.clone()) {
|
||||||
|
Ok(_) => {
|
||||||
|
self.current_app_id = cartridge.app_id;
|
||||||
|
self.current_cartridge_title = cartridge.title.clone();
|
||||||
|
self.current_cartridge_app_version = cartridge.app_version.clone();
|
||||||
|
self.current_cartridge_app_mode = cartridge.app_mode;
|
||||||
|
self.render_manager.transition_render_owner(cartridge.app_mode, cartridge.app_id);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
let report = CrashReport::VmInit { error: e };
|
||||||
|
self.last_crash_report = Some(report.clone());
|
||||||
|
self.log(
|
||||||
|
log_service,
|
||||||
|
LogLevel::Error,
|
||||||
|
LogSource::Vm,
|
||||||
|
report.log_tag(),
|
||||||
|
format!("Failed to initialize VM: {}", report),
|
||||||
|
);
|
||||||
|
Err(report)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::os::{GameLifecycleEvent, GameLifecycleEventKind};
|
||||||
|
use crate::task::TaskId;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn vm_runtime_records_and_drains_delivered_game_lifecycle_events() {
|
||||||
|
let mut runtime = VirtualMachineRuntime::new(None);
|
||||||
|
let pause = GameLifecycleEvent { task_id: TaskId(7), kind: GameLifecycleEventKind::Pause };
|
||||||
|
let resume = GameLifecycleEvent {
|
||||||
|
task_id: TaskId(7),
|
||||||
|
kind: GameLifecycleEventKind::ResumeForeground,
|
||||||
|
};
|
||||||
|
|
||||||
|
runtime.deliver_game_lifecycle_events([pause, resume]);
|
||||||
|
|
||||||
|
assert_eq!(runtime.delivered_game_lifecycle_events(), &[pause, resume]);
|
||||||
|
assert_eq!(runtime.take_delivered_game_lifecycle_events(), vec![pause, resume]);
|
||||||
|
assert!(runtime.delivered_game_lifecycle_events().is_empty());
|
||||||
|
}
|
||||||
|
}
|
||||||
+31
-9
@@ -1,19 +1,34 @@
|
|||||||
|
#[cfg(test)]
|
||||||
|
mod async_render_contract_tests;
|
||||||
mod dispatch;
|
mod dispatch;
|
||||||
|
mod frame_scheduler;
|
||||||
mod lifecycle;
|
mod lifecycle;
|
||||||
|
pub mod render_manager;
|
||||||
|
mod render_worker;
|
||||||
|
pub mod render_worker_handoff;
|
||||||
|
#[cfg(test)]
|
||||||
|
pub(crate) mod render_worker_test_harness;
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests;
|
mod tests;
|
||||||
mod tick;
|
mod tick;
|
||||||
|
|
||||||
use crate::CrashReport;
|
use crate::CrashReport;
|
||||||
use crate::fs::{FsState, VirtualFS};
|
use crate::os::GameLifecycleEvent;
|
||||||
use crate::services::memcard::MemcardService;
|
pub use frame_scheduler::FrameScheduler;
|
||||||
use prometeu_bytecode::string_materialization_count;
|
use prometeu_bytecode::string_materialization_count;
|
||||||
use prometeu_hal::cartridge::AppMode;
|
use prometeu_hal::app_mode::AppMode;
|
||||||
use prometeu_hal::log::LogService;
|
use prometeu_hal::log::LogService;
|
||||||
use prometeu_hal::telemetry::{AtomicTelemetry, CertificationConfig, Certifier};
|
use prometeu_hal::telemetry::{AtomicTelemetry, CertificationConfig, Certifier};
|
||||||
|
use prometeu_hal::{Gfx2dCommand, GfxUiCommand};
|
||||||
use prometeu_vm::VirtualMachine;
|
use prometeu_vm::VirtualMachine;
|
||||||
|
pub use render_manager::{RenderManager, RenderRuntimeCapabilities};
|
||||||
|
pub use render_worker::{
|
||||||
|
LatestRenderFrameStore, RenderWorkerConfig, RenderWorkerController, RenderWorkerOwnership,
|
||||||
|
};
|
||||||
|
pub use render_worker_handoff::{RenderWorkerHandoff, RenderWorkerHandoffWait};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::AtomicU32;
|
||||||
use std::time::Instant;
|
use std::time::Instant;
|
||||||
|
|
||||||
pub struct VirtualMachineRuntime {
|
pub struct VirtualMachineRuntime {
|
||||||
@@ -22,17 +37,20 @@ pub struct VirtualMachineRuntime {
|
|||||||
pub logical_frame_active: bool,
|
pub logical_frame_active: bool,
|
||||||
pub logical_frame_remaining_cycles: u64,
|
pub logical_frame_remaining_cycles: u64,
|
||||||
pub last_frame_cpu_time_us: u64,
|
pub last_frame_cpu_time_us: u64,
|
||||||
pub fs: VirtualFS,
|
|
||||||
pub fs_state: FsState,
|
|
||||||
pub memcard: MemcardService,
|
|
||||||
pub open_files: HashMap<u32, String>,
|
|
||||||
pub next_handle: u32,
|
|
||||||
pub log_service: LogService,
|
|
||||||
pub current_app_id: u32,
|
pub current_app_id: u32,
|
||||||
pub current_cartridge_title: String,
|
pub current_cartridge_title: String,
|
||||||
pub current_cartridge_app_version: String,
|
pub current_cartridge_app_version: String,
|
||||||
pub current_cartridge_app_mode: AppMode,
|
pub current_cartridge_app_mode: AppMode,
|
||||||
|
pub frame_scheduler: FrameScheduler,
|
||||||
|
pub render_capabilities: RenderRuntimeCapabilities,
|
||||||
|
pub render_manager: RenderManager,
|
||||||
|
pub render_worker_handoff: Arc<RenderWorkerHandoff>,
|
||||||
|
pub render_worker_ownership: RenderWorkerOwnership,
|
||||||
|
pub render_worker_controller: Option<RenderWorkerController>,
|
||||||
|
pub gfx2d_commands: Vec<Gfx2dCommand>,
|
||||||
|
pub gfxui_commands: Vec<GfxUiCommand>,
|
||||||
pub logs_written_this_frame: HashMap<u32, u32>,
|
pub logs_written_this_frame: HashMap<u32, u32>,
|
||||||
|
pub game_lifecycle_events_delivered: Vec<GameLifecycleEvent>,
|
||||||
pub atomic_telemetry: Arc<AtomicTelemetry>,
|
pub atomic_telemetry: Arc<AtomicTelemetry>,
|
||||||
pub last_crash_report: Option<CrashReport>,
|
pub last_crash_report: Option<CrashReport>,
|
||||||
pub certifier: Certifier,
|
pub certifier: Certifier,
|
||||||
@@ -50,4 +68,8 @@ impl VirtualMachineRuntime {
|
|||||||
pub const SLICE_PER_TICK: u64 = 1_500_000;
|
pub const SLICE_PER_TICK: u64 = 1_500_000;
|
||||||
pub const MAX_LOG_LEN: usize = 256;
|
pub const MAX_LOG_LEN: usize = 256;
|
||||||
pub const MAX_LOGS_PER_FRAME: u32 = 10;
|
pub const MAX_LOGS_PER_FRAME: u32 = 10;
|
||||||
|
|
||||||
|
pub fn new(cap_config: Option<CertificationConfig>) -> Self {
|
||||||
|
Self::new_with_log_counter(cap_config, Arc::new(AtomicU32::new(0)))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user