Compare commits
60
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
|
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"
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ members = [
|
|||||||
"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",
|
||||||
|
|||||||
@@ -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));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -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
|
||||||
|
|||||||
@@ -191,10 +191,10 @@ impl GlyphAssetSlotIndex {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const GLYPH_BANK_PALETTE_COUNT_V1: usize = 64;
|
const GLYPH_BANK_MAX_PALETTE_COUNT_V1: usize = 64;
|
||||||
const GLYPH_BANK_COLORS_PER_PALETTE: usize = 16;
|
const GLYPH_BANK_COLORS_PER_PALETTE: usize = 16;
|
||||||
const GLYPH_BANK_PALETTE_BYTES_V1: usize =
|
const GLYPH_BANK_PALETTE_BYTES_PER_PALETTE: usize =
|
||||||
GLYPH_BANK_PALETTE_COUNT_V1 * GLYPH_BANK_COLORS_PER_PALETTE * size_of::<u32>();
|
GLYPH_BANK_COLORS_PER_PALETTE * size_of::<u32>();
|
||||||
|
|
||||||
/// Resident metadata for a decoded/materialized asset inside a BankPolicy.
|
/// Resident metadata for a decoded/materialized asset inside a BankPolicy.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@@ -599,7 +599,7 @@ impl AssetBridge for AssetManager {
|
|||||||
impl AssetManager {
|
impl AssetManager {
|
||||||
fn decode_glyph_bank_layout(
|
fn decode_glyph_bank_layout(
|
||||||
entry: &AssetEntry,
|
entry: &AssetEntry,
|
||||||
) -> Result<(TileSize, usize, usize, usize), String> {
|
) -> Result<(TileSize, usize, usize, usize, usize, usize), String> {
|
||||||
let meta = entry.metadata_as_glyph_bank()?;
|
let meta = entry.metadata_as_glyph_bank()?;
|
||||||
|
|
||||||
let tile_size = match meta.tile_size {
|
let tile_size = match meta.tile_size {
|
||||||
@@ -609,7 +609,8 @@ impl AssetManager {
|
|||||||
_ => return Err(format!("Invalid tile_size: {}", meta.tile_size)),
|
_ => return Err(format!("Invalid tile_size: {}", meta.tile_size)),
|
||||||
};
|
};
|
||||||
|
|
||||||
if meta.palette_count as usize != GLYPH_BANK_PALETTE_COUNT_V1 {
|
let palette_count = meta.palette_count as usize;
|
||||||
|
if !(1..=GLYPH_BANK_MAX_PALETTE_COUNT_V1).contains(&palette_count) {
|
||||||
return Err(format!("Invalid palette_count: {}", meta.palette_count));
|
return Err(format!("Invalid palette_count: {}", meta.palette_count));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -618,12 +619,14 @@ impl AssetManager {
|
|||||||
|
|
||||||
let logical_pixels = width.checked_mul(height).ok_or("GlyphBank dimensions overflow")?;
|
let logical_pixels = width.checked_mul(height).ok_or("GlyphBank dimensions overflow")?;
|
||||||
let serialized_pixel_bytes = logical_pixels.div_ceil(2);
|
let serialized_pixel_bytes = logical_pixels.div_ceil(2);
|
||||||
|
let palette_bytes = palette_count
|
||||||
|
.checked_mul(GLYPH_BANK_PALETTE_BYTES_PER_PALETTE)
|
||||||
|
.ok_or("GlyphBank palette size overflow")?;
|
||||||
let serialized_size = serialized_pixel_bytes
|
let serialized_size = serialized_pixel_bytes
|
||||||
.checked_add(GLYPH_BANK_PALETTE_BYTES_V1)
|
.checked_add(palette_bytes)
|
||||||
.ok_or("GlyphBank serialized size overflow")?;
|
.ok_or("GlyphBank serialized size overflow")?;
|
||||||
let decoded_size = logical_pixels
|
let decoded_size =
|
||||||
.checked_add(GLYPH_BANK_PALETTE_BYTES_V1)
|
logical_pixels.checked_add(palette_bytes).ok_or("GlyphBank decoded size overflow")?;
|
||||||
.ok_or("GlyphBank decoded size overflow")?;
|
|
||||||
|
|
||||||
if entry.size != serialized_size as u64 {
|
if entry.size != serialized_size as u64 {
|
||||||
return Err(format!(
|
return Err(format!(
|
||||||
@@ -639,7 +642,7 @@ impl AssetManager {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok((tile_size, width, height, serialized_pixel_bytes))
|
Ok((tile_size, width, height, serialized_pixel_bytes, palette_count, palette_bytes))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn unpack_glyph_bank_pixels(packed_pixels: &[u8], logical_pixels: usize) -> Vec<u8> {
|
fn unpack_glyph_bank_pixels(packed_pixels: &[u8], logical_pixels: usize) -> Vec<u8> {
|
||||||
@@ -1200,19 +1203,18 @@ impl AssetManager {
|
|||||||
entry: &AssetEntry,
|
entry: &AssetEntry,
|
||||||
buffer: &[u8],
|
buffer: &[u8],
|
||||||
) -> Result<GlyphBank, String> {
|
) -> Result<GlyphBank, String> {
|
||||||
let (tile_size, width, height, packed_pixel_bytes) = Self::decode_glyph_bank_layout(entry)?;
|
let (tile_size, width, height, packed_pixel_bytes, palette_count, palette_bytes) =
|
||||||
if buffer.len() < packed_pixel_bytes + GLYPH_BANK_PALETTE_BYTES_V1 {
|
Self::decode_glyph_bank_layout(entry)?;
|
||||||
|
if buffer.len() < packed_pixel_bytes + palette_bytes {
|
||||||
return Err("Buffer too small for GLYPHBANK".to_string());
|
return Err("Buffer too small for GLYPHBANK".to_string());
|
||||||
}
|
}
|
||||||
|
|
||||||
let logical_pixels = width * height;
|
let logical_pixels = width * height;
|
||||||
let packed_pixels = &buffer[0..packed_pixel_bytes];
|
let packed_pixels = &buffer[0..packed_pixel_bytes];
|
||||||
let pixel_indices = Self::unpack_glyph_bank_pixels(packed_pixels, logical_pixels);
|
let pixel_indices = Self::unpack_glyph_bank_pixels(packed_pixels, logical_pixels);
|
||||||
let palette_data =
|
let palette_data = &buffer[packed_pixel_bytes..packed_pixel_bytes + palette_bytes];
|
||||||
&buffer[packed_pixel_bytes..packed_pixel_bytes + GLYPH_BANK_PALETTE_BYTES_V1];
|
|
||||||
|
|
||||||
let mut palettes =
|
let mut palettes = vec![[Color::BLACK; GLYPH_BANK_COLORS_PER_PALETTE]; palette_count];
|
||||||
[[Color::BLACK; GLYPH_BANK_COLORS_PER_PALETTE]; GLYPH_BANK_PALETTE_COUNT_V1];
|
|
||||||
for (p, pal) in palettes.iter_mut().enumerate() {
|
for (p, pal) in palettes.iter_mut().enumerate() {
|
||||||
for (c, slot) in pal.iter_mut().enumerate() {
|
for (c, slot) in pal.iter_mut().enumerate() {
|
||||||
let offset = (p * 16 + c) * 4;
|
let offset = (p * 16 + c) * 4;
|
||||||
@@ -1232,7 +1234,8 @@ impl AssetManager {
|
|||||||
entry: &AssetEntry,
|
entry: &AssetEntry,
|
||||||
reader: &mut impl Read,
|
reader: &mut impl Read,
|
||||||
) -> Result<GlyphBank, String> {
|
) -> Result<GlyphBank, String> {
|
||||||
let (tile_size, width, height, packed_pixel_bytes) = Self::decode_glyph_bank_layout(entry)?;
|
let (tile_size, width, height, packed_pixel_bytes, palette_count, palette_bytes) =
|
||||||
|
Self::decode_glyph_bank_layout(entry)?;
|
||||||
let logical_pixels = width * height;
|
let logical_pixels = width * height;
|
||||||
let mut packed_pixels = vec![0_u8; packed_pixel_bytes];
|
let mut packed_pixels = vec![0_u8; packed_pixel_bytes];
|
||||||
reader
|
reader
|
||||||
@@ -1241,13 +1244,12 @@ impl AssetManager {
|
|||||||
|
|
||||||
let pixel_indices = Self::unpack_glyph_bank_pixels(&packed_pixels, logical_pixels);
|
let pixel_indices = Self::unpack_glyph_bank_pixels(&packed_pixels, logical_pixels);
|
||||||
|
|
||||||
let mut palette_data = [0_u8; GLYPH_BANK_PALETTE_BYTES_V1];
|
let mut palette_data = vec![0_u8; palette_bytes];
|
||||||
reader
|
reader
|
||||||
.read_exact(&mut palette_data)
|
.read_exact(&mut palette_data)
|
||||||
.map_err(|_| "Buffer too small for GLYPHBANK".to_string())?;
|
.map_err(|_| "Buffer too small for GLYPHBANK".to_string())?;
|
||||||
|
|
||||||
let mut palettes =
|
let mut palettes = vec![[Color::BLACK; GLYPH_BANK_COLORS_PER_PALETTE]; palette_count];
|
||||||
[[Color::BLACK; GLYPH_BANK_COLORS_PER_PALETTE]; GLYPH_BANK_PALETTE_COUNT_V1];
|
|
||||||
for (p, pal) in palettes.iter_mut().enumerate() {
|
for (p, pal) in palettes.iter_mut().enumerate() {
|
||||||
for (c, slot) in pal.iter_mut().enumerate() {
|
for (c, slot) in pal.iter_mut().enumerate() {
|
||||||
let offset = (p * 16 + c) * 4;
|
let offset = (p * 16 + c) * 4;
|
||||||
@@ -1858,6 +1860,9 @@ impl AssetManager {
|
|||||||
self.glyph_slot_index.clear();
|
self.glyph_slot_index.clear();
|
||||||
self.sound_slots.write().unwrap().fill(None);
|
self.sound_slots.write().unwrap().fill(None);
|
||||||
self.scene_slots.write().unwrap().fill(None);
|
self.scene_slots.write().unwrap().fill(None);
|
||||||
|
self.gfx_installer.clear_glyph_banks();
|
||||||
|
self.sound_installer.clear_sound_banks();
|
||||||
|
self.scene_installer.clear_scene_banks();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn glyph_asset_slot_index(&self) -> GlyphAssetSlotIndex {
|
pub fn glyph_asset_slot_index(&self) -> GlyphAssetSlotIndex {
|
||||||
@@ -1880,35 +1885,53 @@ mod tests {
|
|||||||
use prometeu_hal::tile::Tile;
|
use prometeu_hal::tile::Tile;
|
||||||
use prometeu_hal::tilemap::TileMap;
|
use prometeu_hal::tilemap::TileMap;
|
||||||
|
|
||||||
fn expected_glyph_payload_size(width: usize, height: usize) -> usize {
|
fn expected_glyph_payload_size(width: usize, height: usize, palette_count: usize) -> usize {
|
||||||
(width * height).div_ceil(2) + GLYPH_BANK_PALETTE_BYTES_V1
|
(width * height).div_ceil(2) + (palette_count * GLYPH_BANK_PALETTE_BYTES_PER_PALETTE)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn expected_glyph_decoded_size(width: usize, height: usize) -> usize {
|
fn expected_glyph_decoded_size(width: usize, height: usize, palette_count: usize) -> usize {
|
||||||
width * height + GLYPH_BANK_PALETTE_BYTES_V1
|
width * height + (palette_count * GLYPH_BANK_PALETTE_BYTES_PER_PALETTE)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn test_glyph_asset_data() -> Vec<u8> {
|
fn test_glyph_asset_data() -> Vec<u8> {
|
||||||
|
test_glyph_asset_data_with_palette_count(GLYPH_BANK_MAX_PALETTE_COUNT_V1)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn test_glyph_asset_data_with_palette_count(palette_count: usize) -> Vec<u8> {
|
||||||
let mut data = vec![0x11u8; 128];
|
let mut data = vec![0x11u8; 128];
|
||||||
data.extend_from_slice(&[0u8; GLYPH_BANK_PALETTE_BYTES_V1]);
|
data.extend_from_slice(&vec![0u8; palette_count * GLYPH_BANK_PALETTE_BYTES_PER_PALETTE]);
|
||||||
data
|
data
|
||||||
}
|
}
|
||||||
|
|
||||||
fn test_glyph_asset_entry(asset_name: &str, width: usize, height: usize) -> AssetEntry {
|
fn test_glyph_asset_entry(asset_name: &str, width: usize, height: usize) -> AssetEntry {
|
||||||
|
test_glyph_asset_entry_with_palette_count(
|
||||||
|
asset_name,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
GLYPH_BANK_MAX_PALETTE_COUNT_V1,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn test_glyph_asset_entry_with_palette_count(
|
||||||
|
asset_name: &str,
|
||||||
|
width: usize,
|
||||||
|
height: usize,
|
||||||
|
palette_count: usize,
|
||||||
|
) -> AssetEntry {
|
||||||
AssetEntry {
|
AssetEntry {
|
||||||
asset_id: 0,
|
asset_id: 0,
|
||||||
asset_name: asset_name.to_string(),
|
asset_name: asset_name.to_string(),
|
||||||
bank_type: BankType::GLYPH,
|
bank_type: BankType::GLYPH,
|
||||||
offset: 0,
|
offset: 0,
|
||||||
size: expected_glyph_payload_size(width, height) as u64,
|
size: expected_glyph_payload_size(width, height, palette_count) as u64,
|
||||||
decoded_size: expected_glyph_decoded_size(width, height) as u64,
|
decoded_size: expected_glyph_decoded_size(width, height, palette_count) as u64,
|
||||||
codec: AssetCodec::None,
|
codec: AssetCodec::None,
|
||||||
metadata: serde_json::json!({
|
metadata: serde_json::json!({
|
||||||
"tile_size": 16,
|
"tile_size": 16,
|
||||||
"width": width,
|
"width": width,
|
||||||
"height": height,
|
"height": height,
|
||||||
"palette_count": GLYPH_BANK_PALETTE_COUNT_V1,
|
"palette_count": palette_count,
|
||||||
"palette_authored": GLYPH_BANK_PALETTE_COUNT_V1
|
"palette_authored": palette_count
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2031,22 +2054,67 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_decode_glyph_bank_unpacks_packed_pixels_and_reads_palette_colors() {
|
fn test_decode_glyph_bank_unpacks_packed_pixels_and_reads_palette_colors() {
|
||||||
let entry = test_glyph_asset_entry("glyphs", 2, 2);
|
let entry = test_glyph_asset_entry_with_palette_count("glyphs", 2, 2, 1);
|
||||||
let mut data = vec![0x10, 0x23];
|
let mut data = vec![0x10, 0x23];
|
||||||
data.extend_from_slice(&[0u8; GLYPH_BANK_PALETTE_BYTES_V1]);
|
data.extend_from_slice(&[0u8; GLYPH_BANK_PALETTE_BYTES_PER_PALETTE]);
|
||||||
data[2..6].copy_from_slice(&[0x12, 0x34, 0x56, 0x78]);
|
data[2..6].copy_from_slice(&[0x12, 0x34, 0x56, 0x78]);
|
||||||
|
|
||||||
let bank =
|
let bank =
|
||||||
AssetManager::decode_glyph_bank_from_buffer(&entry, &data).expect("glyph decode");
|
AssetManager::decode_glyph_bank_from_buffer(&entry, &data).expect("glyph decode");
|
||||||
|
|
||||||
assert_eq!(bank.pixel_indices, vec![1, 0, 2, 3]);
|
assert_eq!(bank.pixel_indices, vec![1, 0, 2, 3]);
|
||||||
|
assert_eq!(bank.palette_count(), 1);
|
||||||
assert_eq!(bank.palettes[0][0], Color::from_raw(0x12345678));
|
assert_eq!(bank.palettes[0][0], Color::from_raw(0x12345678));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_decode_glyph_bank_accepts_intermediate_palette_count() {
|
||||||
|
let entry = test_glyph_asset_entry_with_palette_count("glyphs", 16, 16, 7);
|
||||||
|
let data = test_glyph_asset_data_with_palette_count(7);
|
||||||
|
|
||||||
|
let bank =
|
||||||
|
AssetManager::decode_glyph_bank_from_buffer(&entry, &data).expect("glyph decode");
|
||||||
|
|
||||||
|
assert_eq!(bank.palette_count(), 7);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_decode_glyph_bank_accepts_max_palette_count() {
|
||||||
|
let entry = test_glyph_asset_entry_with_palette_count(
|
||||||
|
"glyphs",
|
||||||
|
16,
|
||||||
|
16,
|
||||||
|
GLYPH_BANK_MAX_PALETTE_COUNT_V1,
|
||||||
|
);
|
||||||
|
let data = test_glyph_asset_data_with_palette_count(GLYPH_BANK_MAX_PALETTE_COUNT_V1);
|
||||||
|
|
||||||
|
let bank =
|
||||||
|
AssetManager::decode_glyph_bank_from_buffer(&entry, &data).expect("glyph decode");
|
||||||
|
|
||||||
|
assert_eq!(bank.palette_count(), GLYPH_BANK_MAX_PALETTE_COUNT_V1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_decode_glyph_bank_reader_matches_buffer_for_variable_palette_count() {
|
||||||
|
let entry = test_glyph_asset_entry_with_palette_count("glyphs", 16, 16, 3);
|
||||||
|
let data = test_glyph_asset_data_with_palette_count(3);
|
||||||
|
|
||||||
|
let from_buffer =
|
||||||
|
AssetManager::decode_glyph_bank_from_buffer(&entry, &data).expect("buffer decode");
|
||||||
|
let mut reader = std::io::Cursor::new(data);
|
||||||
|
let from_reader = AssetManager::decode_glyph_bank_from_reader(&entry, &mut reader)
|
||||||
|
.expect("reader decode");
|
||||||
|
|
||||||
|
assert_eq!(from_buffer.palette_count(), from_reader.palette_count());
|
||||||
|
assert_eq!(from_buffer.pixel_indices, from_reader.pixel_indices);
|
||||||
|
assert_eq!(from_buffer.palettes, from_reader.palettes);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_decode_glyph_bank_rejects_short_packed_buffer() {
|
fn test_decode_glyph_bank_rejects_short_packed_buffer() {
|
||||||
let entry = test_glyph_asset_entry("glyphs", 16, 16);
|
let entry = test_glyph_asset_entry("glyphs", 16, 16);
|
||||||
let data = vec![0u8; expected_glyph_payload_size(16, 16) - 1];
|
let data =
|
||||||
|
vec![0u8; expected_glyph_payload_size(16, 16, GLYPH_BANK_MAX_PALETTE_COUNT_V1) - 1];
|
||||||
|
|
||||||
let err = match AssetManager::decode_glyph_bank_from_buffer(&entry, &data) {
|
let err = match AssetManager::decode_glyph_bank_from_buffer(&entry, &data) {
|
||||||
Ok(_) => panic!("glyph decode should reject short buffer"),
|
Ok(_) => panic!("glyph decode should reject short buffer"),
|
||||||
@@ -2057,9 +2125,9 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_decode_glyph_bank_requires_palette_count_64() {
|
fn test_decode_glyph_bank_rejects_palette_count_zero() {
|
||||||
let mut entry = test_glyph_asset_entry("glyphs", 16, 16);
|
let mut entry = test_glyph_asset_entry("glyphs", 16, 16);
|
||||||
entry.metadata["palette_count"] = serde_json::json!(32);
|
entry.metadata["palette_count"] = serde_json::json!(0);
|
||||||
|
|
||||||
let err =
|
let err =
|
||||||
match AssetManager::decode_glyph_bank_from_buffer(&entry, &test_glyph_asset_data()) {
|
match AssetManager::decode_glyph_bank_from_buffer(&entry, &test_glyph_asset_data()) {
|
||||||
@@ -2067,7 +2135,67 @@ mod tests {
|
|||||||
Err(err) => err,
|
Err(err) => err,
|
||||||
};
|
};
|
||||||
|
|
||||||
assert_eq!(err, "Invalid palette_count: 32");
|
assert_eq!(err, "Invalid palette_count: 0");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_decode_glyph_bank_rejects_palette_count_above_v1_max() {
|
||||||
|
let mut entry = test_glyph_asset_entry("glyphs", 16, 16);
|
||||||
|
entry.metadata["palette_count"] = serde_json::json!(65);
|
||||||
|
|
||||||
|
let err =
|
||||||
|
match AssetManager::decode_glyph_bank_from_buffer(&entry, &test_glyph_asset_data()) {
|
||||||
|
Ok(_) => panic!("glyph decode should reject invalid palette_count"),
|
||||||
|
Err(err) => err,
|
||||||
|
};
|
||||||
|
|
||||||
|
assert_eq!(err, "Invalid palette_count: 65");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_decode_glyph_bank_rejects_mismatched_variable_decoded_size() {
|
||||||
|
let mut entry = test_glyph_asset_entry_with_palette_count("glyphs", 16, 16, 3);
|
||||||
|
entry.decoded_size += 1;
|
||||||
|
|
||||||
|
let err = match AssetManager::decode_glyph_bank_from_buffer(
|
||||||
|
&entry,
|
||||||
|
&test_glyph_asset_data_with_palette_count(3),
|
||||||
|
) {
|
||||||
|
Ok(_) => panic!("glyph decode should reject invalid decoded_size"),
|
||||||
|
Err(err) => err,
|
||||||
|
};
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
err,
|
||||||
|
format!(
|
||||||
|
"Invalid GLYPHBANK decoded_size: expected {}, got {}",
|
||||||
|
expected_glyph_decoded_size(16, 16, 3),
|
||||||
|
expected_glyph_decoded_size(16, 16, 3) + 1
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_decode_glyph_bank_rejects_mismatched_variable_serialized_size() {
|
||||||
|
let mut entry = test_glyph_asset_entry_with_palette_count("glyphs", 16, 16, 3);
|
||||||
|
entry.size += 1;
|
||||||
|
|
||||||
|
let err = match AssetManager::decode_glyph_bank_from_buffer(
|
||||||
|
&entry,
|
||||||
|
&test_glyph_asset_data_with_palette_count(3),
|
||||||
|
) {
|
||||||
|
Ok(_) => panic!("glyph decode should reject invalid serialized size"),
|
||||||
|
Err(err) => err,
|
||||||
|
};
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
err,
|
||||||
|
format!(
|
||||||
|
"Invalid GLYPHBANK serialized size: expected {}, got {}",
|
||||||
|
expected_glyph_payload_size(16, 16, 3),
|
||||||
|
expected_glyph_payload_size(16, 16, 3) + 1
|
||||||
|
)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -2668,6 +2796,51 @@ mod tests {
|
|||||||
assert_eq!(am.slot_info(SlotRef::scene(4)).asset_id, Some(2));
|
assert_eq!(am.slot_info(SlotRef::scene(4)).asset_id, Some(2));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn shutdown_clears_physical_memory_bank_slots() {
|
||||||
|
let banks = Arc::new(MemoryBanks::new());
|
||||||
|
let gfx_installer = Arc::clone(&banks) as Arc<dyn GlyphBankPoolInstaller>;
|
||||||
|
let sound_installer = Arc::clone(&banks) as Arc<dyn SoundBankPoolInstaller>;
|
||||||
|
let scene_installer = Arc::clone(&banks) as Arc<dyn SceneBankPoolInstaller>;
|
||||||
|
|
||||||
|
let glyph_data = test_glyph_asset_data();
|
||||||
|
let scene = test_scene();
|
||||||
|
let scene_data = encode_scene_payload(&scene);
|
||||||
|
let glyph_entry = test_glyph_asset_entry("preload_glyphs", 16, 16);
|
||||||
|
let scene_entry = test_scene_asset_entry("preload_scene", &scene_data, &scene);
|
||||||
|
|
||||||
|
let mut payload = Vec::new();
|
||||||
|
payload.extend_from_slice(&glyph_data);
|
||||||
|
payload.extend_from_slice(&scene_data);
|
||||||
|
let mut shifted_scene_entry = scene_entry;
|
||||||
|
shifted_scene_entry.offset = glyph_data.len() as u64;
|
||||||
|
|
||||||
|
let am = AssetManager::new(
|
||||||
|
vec![],
|
||||||
|
AssetsPayloadSource::empty(),
|
||||||
|
gfx_installer,
|
||||||
|
sound_installer,
|
||||||
|
scene_installer,
|
||||||
|
);
|
||||||
|
am.initialize_for_cartridge(
|
||||||
|
vec![glyph_entry, shifted_scene_entry],
|
||||||
|
vec![PreloadEntry { asset_id: 0, slot: 0 }, PreloadEntry { asset_id: 2, slot: 0 }],
|
||||||
|
AssetsPayloadSource::from_bytes(payload),
|
||||||
|
);
|
||||||
|
|
||||||
|
assert!(banks.glyph_bank_slot(0).is_some());
|
||||||
|
assert!(banks.scene_bank_slot(0).is_some());
|
||||||
|
assert_eq!(am.slot_info(SlotRef::gfx(0)).asset_id, Some(0));
|
||||||
|
assert_eq!(am.slot_info(SlotRef::scene(0)).asset_id, Some(2));
|
||||||
|
|
||||||
|
am.shutdown();
|
||||||
|
|
||||||
|
assert!(banks.glyph_bank_slot(0).is_none());
|
||||||
|
assert!(banks.scene_bank_slot(0).is_none());
|
||||||
|
assert_eq!(am.slot_info(SlotRef::gfx(0)).asset_id, None);
|
||||||
|
assert_eq!(am.slot_info(SlotRef::scene(0)).asset_id, None);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_load_returns_asset_not_found() {
|
fn test_load_returns_asset_not_found() {
|
||||||
let banks = Arc::new(MemoryBanks::new());
|
let banks = Arc::new(MemoryBanks::new());
|
||||||
|
|||||||
@@ -557,8 +557,9 @@ mod tests {
|
|||||||
|
|
||||||
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;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -812,7 +812,14 @@ impl Gfx {
|
|||||||
let fetch_x = if tile.entry.flip_x() { size - 1 - local_x } else { local_x };
|
let fetch_x = if tile.entry.flip_x() { size - 1 - local_x } else { local_x };
|
||||||
let fetch_y = if tile.entry.flip_y() { size - 1 - local_y } else { local_y };
|
let fetch_y = if tile.entry.flip_y() { size - 1 - local_y } else { local_y };
|
||||||
let px_index = tile.bank.get_pixel_index(tile.entry.glyph_id, fetch_x, fetch_y);
|
let px_index = tile.bank.get_pixel_index(tile.entry.glyph_id, fetch_x, fetch_y);
|
||||||
let color = tile.bank.resolve_color(tile.entry.palette_id, px_index);
|
let color = tile.bank.resolve_color(tile.entry.palette_id, px_index).unwrap_or_else(
|
||||||
|
|| {
|
||||||
|
panic!(
|
||||||
|
"SCENE composition fatal: palette_id {} is not resident for glyph asset {}",
|
||||||
|
tile.entry.palette_id, tile.entry.glyph_asset_id
|
||||||
|
)
|
||||||
|
},
|
||||||
|
);
|
||||||
if color.alpha() == 0 {
|
if color.alpha() == 0 {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -862,7 +869,14 @@ impl Gfx {
|
|||||||
let fetch_y = if sprite.flip_y { size - 1 - local_y } else { local_y };
|
let fetch_y = if sprite.flip_y { size - 1 - local_y } else { local_y };
|
||||||
|
|
||||||
let px_index = bank.get_pixel_index(sprite.glyph.glyph_id, fetch_x, fetch_y);
|
let px_index = bank.get_pixel_index(sprite.glyph.glyph_id, fetch_x, fetch_y);
|
||||||
let color = bank.resolve_color(sprite.glyph.palette_id, px_index);
|
let color = bank.resolve_color(sprite.glyph.palette_id, px_index).unwrap_or_else(
|
||||||
|
|| {
|
||||||
|
panic!(
|
||||||
|
"SPRITE composition fatal: palette_id {} is not resident for glyph bank {}",
|
||||||
|
sprite.glyph.palette_id, sprite.bank_id
|
||||||
|
)
|
||||||
|
},
|
||||||
|
);
|
||||||
if color.alpha() == 0 {
|
if color.alpha() == 0 {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -1010,9 +1024,14 @@ mod tests {
|
|||||||
|
|
||||||
fn make_glyph_bank(tile_size: TileSize, palette_colors: &[(u8, u8, Color)]) -> GlyphBank {
|
fn make_glyph_bank(tile_size: TileSize, palette_colors: &[(u8, u8, Color)]) -> GlyphBank {
|
||||||
let size = tile_size as usize;
|
let size = tile_size as usize;
|
||||||
let mut bank = GlyphBank::new(tile_size, size, size);
|
let palette_count = palette_colors
|
||||||
|
.iter()
|
||||||
|
.map(|(palette_id, _, _)| *palette_id as usize + 1)
|
||||||
|
.max()
|
||||||
|
.unwrap_or(1);
|
||||||
|
let mut bank = GlyphBank::with_palette_count(tile_size, size, size, palette_count);
|
||||||
for (palette_id, color_index, color) in palette_colors {
|
for (palette_id, color_index, color) in palette_colors {
|
||||||
bank.palettes[*palette_id as usize][*color_index as usize] = *color;
|
bank.palette_mut(*palette_id).unwrap()[*color_index as usize] = *color;
|
||||||
}
|
}
|
||||||
bank
|
bank
|
||||||
}
|
}
|
||||||
@@ -1152,6 +1171,26 @@ mod tests {
|
|||||||
assert_eq!(back[0], Color::RED.raw());
|
assert_eq!(back[0], Color::RED.raw());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[should_panic(expected = "SPRITE composition fatal: palette_id 1 is not resident")]
|
||||||
|
fn sprite_draw_panics_for_invalid_palette_reference() {
|
||||||
|
let bank = make_filled_glyph_bank(TileSize::Size8, 0, &[(0, 0, Color::GREEN)]);
|
||||||
|
let mut back = vec![Color::BLACK.raw(); 8 * 8];
|
||||||
|
let sprite = Sprite {
|
||||||
|
glyph: Glyph { glyph_id: 0, palette_id: 1 },
|
||||||
|
x: 0,
|
||||||
|
y: 0,
|
||||||
|
layer: 0,
|
||||||
|
flip_x: false,
|
||||||
|
flip_y: false,
|
||||||
|
bank_id: 0,
|
||||||
|
active: true,
|
||||||
|
priority: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
Gfx::draw_sprite_pixel_by_pixel(&mut back, 8, 8, &sprite, &bank);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_cached_tile_draws_opaque_color_index_zero() {
|
fn test_cached_tile_draws_opaque_color_index_zero() {
|
||||||
let bank = make_filled_glyph_bank(TileSize::Size8, 0, &[(0, 0, Color::GREEN)]);
|
let bank = make_filled_glyph_bank(TileSize::Size8, 0, &[(0, 0, Color::GREEN)]);
|
||||||
@@ -1194,6 +1233,26 @@ mod tests {
|
|||||||
assert_eq!(target.back[0], Color::RED.raw());
|
assert_eq!(target.back[0], Color::RED.raw());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[should_panic(expected = "SCENE composition fatal: palette_id 1 is not resident")]
|
||||||
|
fn cached_tile_draw_panics_for_invalid_palette_reference() {
|
||||||
|
let bank = make_filled_glyph_bank(TileSize::Size8, 0, &[(0, 0, Color::GREEN)]);
|
||||||
|
let mut back = vec![Color::BLACK.raw(); 8 * 8];
|
||||||
|
let mut target = RenderTarget { back: &mut back, screen_w: 8, screen_h: 8 };
|
||||||
|
let entry = CachedTileEntry {
|
||||||
|
active: true,
|
||||||
|
glyph_id: 0,
|
||||||
|
palette_id: 1,
|
||||||
|
flags: 0,
|
||||||
|
glyph_asset_id: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
Gfx::draw_cached_tile_pixels(
|
||||||
|
&mut target,
|
||||||
|
CachedTileDraw { x: 0, y: 0, entry, bank: &bank, tile_size: TileSize::Size8 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_draw_rect() {
|
fn test_draw_rect() {
|
||||||
let banks = Arc::new(MemoryBanks::new());
|
let banks = Arc::new(MemoryBanks::new());
|
||||||
|
|||||||
@@ -118,7 +118,11 @@ impl Game2DFrameComposer for Hardware {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn emit_sprite(&mut self, sprite: Sprite) -> prometeu_hal::ComposerOpStatus {
|
fn emit_sprite(&mut self, sprite: Sprite) -> prometeu_hal::ComposerOpStatus {
|
||||||
if self.gfx.glyph_banks.glyph_bank_slot(sprite.bank_id as usize).is_none() {
|
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;
|
return prometeu_hal::ComposerOpStatus::BankInvalid;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -261,7 +265,7 @@ mod tests {
|
|||||||
|
|
||||||
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;
|
||||||
}
|
}
|
||||||
@@ -433,4 +437,28 @@ mod tests {
|
|||||||
|
|
||||||
assert_eq!(hardware.gfx.front_buffer()[0], Color::RED.raw());
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,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.
|
||||||
@@ -38,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.
|
||||||
@@ -52,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.
|
||||||
@@ -100,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 {
|
||||||
@@ -120,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 {
|
||||||
@@ -140,6 +154,10 @@ 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 {
|
impl HalRenderResourceAccess for MemoryBanks {
|
||||||
@@ -178,7 +196,7 @@ mod tests {
|
|||||||
|
|
||||||
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::WHITE;
|
bank.palette_mut(0).unwrap()[1] = Color::WHITE;
|
||||||
bank
|
bank
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -14,6 +14,7 @@ pub enum FirmwareState {
|
|||||||
LaunchHub(LaunchHubStep),
|
LaunchHub(LaunchHubStep),
|
||||||
HubHome(HubHomeStep),
|
HubHome(HubHomeStep),
|
||||||
LoadCartridge(LoadCartridgeStep),
|
LoadCartridge(LoadCartridgeStep),
|
||||||
|
ResumeResidentGame,
|
||||||
GameRunning(GameRunningStep),
|
GameRunning(GameRunningStep),
|
||||||
ShellRunning(ShellRunningStep),
|
ShellRunning(ShellRunningStep),
|
||||||
AppCrashes(AppCrashesStep),
|
AppCrashes(AppCrashesStep),
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
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::CrashReport;
|
|
||||||
use prometeu_system::task::{TaskId, TaskState};
|
use prometeu_system::task::{TaskId, TaskState};
|
||||||
|
use prometeu_system::{CrashReport, ResidentGameState};
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct GameRunningStep {
|
pub struct GameRunningStep {
|
||||||
@@ -36,13 +37,35 @@ impl GameRunningStep {
|
|||||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||||
}
|
}
|
||||||
|
|
||||||
let result = ctx.os.vm().tick(ctx.vm, ctx.signals, ctx.platform);
|
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 {
|
if let Some(report) = result {
|
||||||
let _ = ctx.os.lifecycle().crash_task(self.task_id, Some(&report));
|
let _ = ctx.os.lifecycle().crash_task(self.task_id, Some(&report));
|
||||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { 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
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ use crate::firmware::firmware_state::{
|
|||||||
AppCrashesStep, FirmwareState, LoadCartridgeStep, ShellRunningStep,
|
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::cartridge_loader::CartridgeLoader;
|
||||||
use prometeu_hal::log::{LogLevel, LogSource};
|
use prometeu_hal::log::{LogLevel, LogSource};
|
||||||
use prometeu_hal::primitives::Rect;
|
use prometeu_hal::primitives::Rect;
|
||||||
@@ -19,14 +21,29 @@ impl HubHomeStep {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
pub fn on_update(&mut self, ctx: &mut PrometeuContext) -> Option<FirmwareState> {
|
||||||
let outcome = ctx.hub.update_shell_profile(ctx.os, ctx.vm, ctx.signals, ctx.platform);
|
let outcome = ctx.hub.update_shell_profile(ctx.os, ctx.platform);
|
||||||
if let Some(report) = outcome.crash {
|
if let Some(report) = outcome.crash {
|
||||||
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
return Some(FirmwareState::AppCrashes(AppCrashesStep { report }));
|
||||||
}
|
}
|
||||||
|
|
||||||
match outcome.action {
|
match outcome.action {
|
||||||
Some(SystemProfileAction::LaunchNativeShell(app)) => {
|
Some(SystemProfileAction::LaunchNativeShell(app)) => {
|
||||||
let task_id = ctx.os.sessions().create_native_shell_task(app.app_id(), app.title());
|
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(
|
let id = ctx.os.windows().add_window(
|
||||||
app.title().to_string(),
|
app.title().to_string(),
|
||||||
WindowOwner::Task(task_id),
|
WindowOwner::Task(task_id),
|
||||||
@@ -36,19 +53,71 @@ impl HubHomeStep {
|
|||||||
ctx.os.windows().set_focus(id);
|
ctx.os.windows().set_focus(id);
|
||||||
return Some(FirmwareState::ShellRunning(ShellRunningStep::new(task_id)));
|
return Some(FirmwareState::ShellRunning(ShellRunningStep::new(task_id)));
|
||||||
}
|
}
|
||||||
Some(SystemProfileAction::LaunchGame { path }) => match CartridgeLoader::load(&path) {
|
Some(SystemProfileAction::LaunchGame { target }) => {
|
||||||
Ok(cartridge) => {
|
match CartridgeLoader::load(&target.path) {
|
||||||
return Some(FirmwareState::LoadCartridge(LoadCartridgeStep::new(cartridge)));
|
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);
|
||||||
|
|
||||||
|
if resident_app_id == cartridge.app_id {
|
||||||
|
return Some(FirmwareState::ResumeResidentGame);
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Err(error) = resident_game_termination::terminate_resident_game(
|
||||||
|
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
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Err(error) => {
|
}
|
||||||
|
Some(SystemProfileAction::KillResidentGame) => {
|
||||||
|
if let Err(error) =
|
||||||
|
resident_game_termination::terminate_resident_game(ctx.os, ctx.platform, true)
|
||||||
|
{
|
||||||
ctx.os.log(
|
ctx.os.log(
|
||||||
LogLevel::Error,
|
LogLevel::Error,
|
||||||
LogSource::Hub,
|
LogSource::Hub,
|
||||||
0,
|
0,
|
||||||
format!("Failed to launch Home game {}: {:?}", path.display(), error),
|
format!("Failed to kill resident game from Hub: {error:?}"),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
Some(SystemProfileAction::CloseShell) | None => {}
|
Some(SystemProfileAction::CloseShell) | None => {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
use crate::firmware::firmware_state::{
|
use crate::firmware::firmware_state::{
|
||||||
AppCrashesStep, FirmwareState, GameRunningStep, ShellRunningStep,
|
AppCrashesStep, FirmwareState, GameRunningStep, HubHomeStep, 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::app_mode::AppMode;
|
||||||
use prometeu_hal::cartridge::Cartridge;
|
use prometeu_hal::cartridge::Cartridge;
|
||||||
use prometeu_hal::color::Color;
|
use prometeu_hal::color::Color;
|
||||||
@@ -14,11 +15,30 @@ use prometeu_system::windows::WindowOwner;
|
|||||||
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) {
|
||||||
@@ -29,6 +49,8 @@ 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.platform.assets_mut().initialize_for_cartridge(
|
ctx.platform.assets_mut().initialize_for_cartridge(
|
||||||
self.cartridge.asset_table.clone(),
|
self.cartridge.asset_table.clone(),
|
||||||
@@ -36,19 +58,66 @@ impl LoadCartridgeStep {
|
|||||||
self.cartridge.assets.clone(),
|
self.cartridge.assets.clone(),
|
||||||
);
|
);
|
||||||
|
|
||||||
self.init_error = ctx.os.vm().initialize(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::Shell {
|
let Some(task_id) = self.loaded_task_id.take() else {
|
||||||
let task_id = ctx
|
let report = CrashReport::VmPanic {
|
||||||
.os
|
message: format!(
|
||||||
.sessions()
|
"cartridge {} was not loaded into a VM session",
|
||||||
.create_vm_shell_task(self.cartridge.app_id, self.cartridge.title.clone());
|
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(
|
let id = ctx.os.windows().add_window(
|
||||||
self.cartridge.title.clone(),
|
self.cartridge.title.clone(),
|
||||||
WindowOwner::Task(task_id),
|
WindowOwner::Task(task_id),
|
||||||
@@ -59,10 +128,6 @@ impl LoadCartridgeStep {
|
|||||||
return Some(FirmwareState::ShellRunning(ShellRunningStep::new(task_id)));
|
return Some(FirmwareState::ShellRunning(ShellRunningStep::new(task_id)));
|
||||||
}
|
}
|
||||||
|
|
||||||
let task_id = ctx
|
|
||||||
.os
|
|
||||||
.sessions()
|
|
||||||
.create_vm_game_task(self.cartridge.app_id, self.cartridge.title.clone());
|
|
||||||
Some(FirmwareState::GameRunning(GameRunningStep::new(task_id)))
|
Some(FirmwareState::GameRunning(GameRunningStep::new(task_id)))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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.vm().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> {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
use crate::firmware::firmware_state::{AppCrashesStep, FirmwareState, HubHomeStep};
|
use crate::firmware::firmware_state::{AppCrashesStep, FirmwareState, HubHomeStep};
|
||||||
use crate::firmware::prometeu_context::PrometeuContext;
|
use crate::firmware::prometeu_context::PrometeuContext;
|
||||||
use prometeu_hal::log::LogSource;
|
use prometeu_hal::log::LogSource;
|
||||||
|
use prometeu_system::process::ProcessKind;
|
||||||
use prometeu_system::task::{TaskId, TaskState};
|
use prometeu_system::task::{TaskId, TaskState};
|
||||||
use prometeu_system::{CrashReport, SystemProfileAction};
|
use prometeu_system::{CrashReport, SystemProfileAction};
|
||||||
|
|
||||||
@@ -59,7 +60,36 @@ impl ShellRunningStep {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let outcome = ctx.hub.update_shell_profile(ctx.os, ctx.vm, ctx.signals, ctx.platform);
|
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 {
|
if let Some(report) = outcome.crash {
|
||||||
let _ = ctx.os.lifecycle().crash_task(self.task_id, Some(&report));
|
let _ = ctx.os.lifecycle().crash_task(self.task_id, Some(&report));
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ pub(crate) mod firmware_step_reset;
|
|||||||
pub(crate) mod firmware_step_shell_running;
|
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,10 +1,8 @@
|
|||||||
use crate::firmware::boot_target::BootTarget;
|
use crate::firmware::boot_target::BootTarget;
|
||||||
use prometeu_hal::{InputSignals, RuntimePlatform};
|
use prometeu_hal::{InputSignals, RuntimePlatform};
|
||||||
use prometeu_system::{PrometeuHub, SystemOS};
|
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 SystemOS,
|
||||||
pub hub: &'a mut PrometeuHub,
|
pub hub: &'a mut PrometeuHub,
|
||||||
pub boot_target: &'a BootTarget,
|
pub boot_target: &'a BootTarget,
|
||||||
|
|||||||
@@ -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 })
|
||||||
|
}
|
||||||
@@ -203,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};
|
||||||
@@ -369,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 * 4),
|
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
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -452,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 * 4),
|
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
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
@@ -519,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": []
|
||||||
@@ -561,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": []
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -35,22 +35,59 @@ pub struct GlyphBank {
|
|||||||
/// Palette indices are ordinary indices; transparency is resolved through
|
/// Palette indices are ordinary indices; transparency is resolved through
|
||||||
/// the RGBA alpha channel of the palette entry.
|
/// 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 RGBA8888 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],
|
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)
|
||||||
@@ -71,11 +108,48 @@ impl GlyphBank {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Maps a 4-bit index to a real RGBA8888 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> {
|
||||||
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::TRANSPARENT)
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,17 +4,26 @@ mod programs;
|
|||||||
mod services;
|
mod services;
|
||||||
|
|
||||||
pub use crash_report::CrashReport;
|
pub use crash_report::CrashReport;
|
||||||
pub use os::{LifecycleError, LifecycleOperation, SystemOS};
|
pub use os::{
|
||||||
pub use programs::{NativeShellApp, PrometeuHub, SystemProfileAction, SystemProfileUpdate};
|
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 prometeu_hal::{RenderWorkerBackend, RenderWorkerFrameSink};
|
||||||
pub use services::async_work::{
|
pub use services::async_work::{
|
||||||
AsyncWorkActiveJob, AsyncWorkCancelToken, AsyncWorkJobContext, AsyncWorkJobId,
|
AsyncWorkActiveJob, AsyncWorkCancelToken, AsyncWorkJobContext, AsyncWorkJobId,
|
||||||
AsyncWorkJobKind, AsyncWorkJobOutcome, AsyncWorkLane, AsyncWorkLaneConfig,
|
AsyncWorkJobKind, AsyncWorkJobOutcome, AsyncWorkLane, AsyncWorkLaneConfig,
|
||||||
AsyncWorkLaneController, AsyncWorkLaneError, AsyncWorkLaneTelemetry, AsyncWorkPriority,
|
AsyncWorkLaneController, AsyncWorkLaneError, AsyncWorkLaneTelemetry, AsyncWorkPriority,
|
||||||
};
|
};
|
||||||
|
pub use services::foreground::{
|
||||||
|
ForegroundOwner, ForegroundStack, ForegroundStackError, ResidentGame, ResidentGameState,
|
||||||
|
};
|
||||||
pub use services::fs;
|
pub use services::fs;
|
||||||
pub use services::game_library::{
|
pub use services::game_library::{
|
||||||
GameLibrary, GameLibraryDiagnostic, GameLibraryEntry, discover_games_root,
|
GameLibrary, GameLibraryDiagnostic, GameLibraryEntry, GameSwitchTarget, discover_games_root,
|
||||||
};
|
};
|
||||||
pub use services::memcard::MemcardAsyncLaneOperation;
|
pub use services::memcard::MemcardAsyncLaneOperation;
|
||||||
pub use services::process;
|
pub use services::process;
|
||||||
@@ -23,4 +32,5 @@ pub use services::vm_runtime::{
|
|||||||
LatestRenderFrameStore, RenderWorkerConfig, RenderWorkerController, RenderWorkerHandoff,
|
LatestRenderFrameStore, RenderWorkerConfig, RenderWorkerController, RenderWorkerHandoff,
|
||||||
RenderWorkerHandoffWait, RenderWorkerOwnership, VirtualMachineRuntime,
|
RenderWorkerHandoffWait, RenderWorkerOwnership, VirtualMachineRuntime,
|
||||||
};
|
};
|
||||||
|
pub use services::vm_session;
|
||||||
pub use services::windows;
|
pub use services::windows;
|
||||||
|
|||||||
@@ -1,8 +1,14 @@
|
|||||||
use crate::CrashReport;
|
use crate::CrashReport;
|
||||||
use crate::os::SystemOS;
|
use crate::os::SystemOS;
|
||||||
use crate::os::{LifecycleError, LifecycleOperation};
|
use crate::os::{
|
||||||
use crate::process::{ProcessId, ProcessState};
|
DEFAULT_GAME_PAUSE_BUDGET_TICKS, GameLifecycleEvent, GameLifecycleEventKind, LifecycleError,
|
||||||
use crate::task::{TaskId, TaskState};
|
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 struct LifecycleFacade<'a> {
|
||||||
pub(in crate::os) os: &'a mut SystemOS,
|
pub(in crate::os) os: &'a mut SystemOS,
|
||||||
@@ -14,28 +20,145 @@ impl<'a> LifecycleFacade<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn process_state_for_task(&self, task_id: TaskId) -> Result<ProcessState, LifecycleError> {
|
pub fn process_state_for_task(&self, task_id: TaskId) -> Result<ProcessState, LifecycleError> {
|
||||||
let process_id = process_id_for_task(self.os, task_id)?;
|
process_for_task(self.os, task_id).map(|process| process.state)
|
||||||
self.os
|
}
|
||||||
.process_manager
|
|
||||||
.get(process_id)
|
pub fn process_kind_for_task(&self, task_id: TaskId) -> Result<ProcessKind, LifecycleError> {
|
||||||
.map(|process| process.state)
|
process_for_task(self.os, task_id).map(|process| process.kind)
|
||||||
.ok_or(LifecycleError::ProcessNotFound(process_id))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_foreground_task(&mut self, task_id: TaskId) -> Result<(), LifecycleError> {
|
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)?;
|
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.task_manager.set_foreground(task_id);
|
||||||
self.os.process_manager.mark_running(process_id);
|
self.os.process_manager.mark_running(process_id);
|
||||||
|
|
||||||
Ok(())
|
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> {
|
pub fn suspend_task(&mut self, task_id: TaskId) -> Result<(), LifecycleError> {
|
||||||
let process_id = process_id_for_task(self.os, task_id)?;
|
let process_id = process_id_for_task(self.os, task_id)?;
|
||||||
|
|
||||||
self.os.task_manager.mark_suspended(task_id);
|
self.os.task_manager.mark_suspended(task_id);
|
||||||
self.os.process_manager.mark_suspended(process_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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -54,8 +177,32 @@ impl<'a> LifecycleFacade<'a> {
|
|||||||
|
|
||||||
let process_id = process_id_for_task(self.os, task_id)?;
|
let process_id = process_id_for_task(self.os, task_id)?;
|
||||||
|
|
||||||
self.os.task_manager.set_foreground(task_id);
|
match task_kind_for_task(self.os, task_id)? {
|
||||||
self.os.process_manager.mark_running(process_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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -65,10 +212,38 @@ impl<'a> LifecycleFacade<'a> {
|
|||||||
|
|
||||||
self.os.task_manager.close_task(task_id);
|
self.os.task_manager.close_task(task_id);
|
||||||
self.os.process_manager.mark_stopped(process_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(())
|
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(
|
pub fn crash_task(
|
||||||
&mut self,
|
&mut self,
|
||||||
task_id: TaskId,
|
task_id: TaskId,
|
||||||
@@ -78,11 +253,22 @@ impl<'a> LifecycleFacade<'a> {
|
|||||||
|
|
||||||
self.os.task_manager.mark_crashed(task_id);
|
self.os.task_manager.mark_crashed(task_id);
|
||||||
self.os.process_manager.mark_crashed(process_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(())
|
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> {
|
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))?;
|
let task = os.task_manager.get(task_id).ok_or(LifecycleError::TaskNotFound(task_id))?;
|
||||||
|
|
||||||
@@ -92,3 +278,22 @@ fn process_id_for_task(os: &SystemOS, task_id: TaskId) -> Result<ProcessId, Life
|
|||||||
|
|
||||||
Ok(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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -6,6 +6,6 @@ mod window;
|
|||||||
|
|
||||||
pub use fs::FsFacade;
|
pub use fs::FsFacade;
|
||||||
pub use lifecycle::LifecycleFacade;
|
pub use lifecycle::LifecycleFacade;
|
||||||
pub use sessions::SessionsFacade;
|
pub use sessions::{SessionError, SessionsFacade};
|
||||||
pub use vm::VmFacade;
|
pub use vm::VmFacade;
|
||||||
pub use window::WindowFacade;
|
pub use window::WindowFacade;
|
||||||
|
|||||||
@@ -1,44 +1,209 @@
|
|||||||
|
use crate::CrashReport;
|
||||||
|
use crate::os::LifecycleError;
|
||||||
use crate::os::SystemOS;
|
use crate::os::SystemOS;
|
||||||
|
use crate::process::ProcessId;
|
||||||
use crate::task::TaskId;
|
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 struct SessionsFacade<'a> {
|
||||||
pub(in crate::os) os: &'a mut SystemOS,
|
pub(in crate::os) os: &'a mut SystemOS,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> SessionsFacade<'a> {
|
impl<'a> SessionsFacade<'a> {
|
||||||
|
#[cfg(test)]
|
||||||
pub fn create_vm_game_task(&mut self, app_id: u32, title: impl Into<String>) -> TaskId {
|
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 title = title.into();
|
||||||
let process_id = self.os.process_manager.spawn_vm_game(app_id, title.clone());
|
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);
|
let task_id = self.os.task_manager.create_game_task(process_id, app_id, title);
|
||||||
self.os
|
self.os.lifecycle().set_game_foreground_task(task_id)?;
|
||||||
.lifecycle()
|
self.try_create_vm_session_for_task(task_id)?;
|
||||||
.set_foreground_task(task_id)
|
|
||||||
.expect("newly created game task should have an associated process");
|
|
||||||
|
|
||||||
task_id
|
Ok(task_id)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
pub fn create_vm_shell_task(&mut self, app_id: u32, title: impl Into<String>) -> TaskId {
|
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 title = title.into();
|
||||||
let process_id = self.os.process_manager.spawn_vm_shell(app_id, title.clone());
|
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);
|
let task_id = self.os.task_manager.create_shell_task(process_id, app_id, title);
|
||||||
self.os
|
self.os.lifecycle().set_shell_foreground_task(task_id)?;
|
||||||
.lifecycle()
|
self.try_create_vm_session_for_task(task_id)?;
|
||||||
.set_foreground_task(task_id)
|
|
||||||
.expect("newly created shell task should have an associated process");
|
|
||||||
|
|
||||||
task_id
|
Ok(task_id)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
pub fn create_native_shell_task(&mut self, app_id: u32, title: impl Into<String>) -> TaskId {
|
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 title = title.into();
|
||||||
let process_id = self.os.process_manager.spawn_native_shell(app_id, title.clone());
|
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);
|
let task_id = self.os.task_manager.create_shell_task(process_id, app_id, title);
|
||||||
self.os
|
self.os.lifecycle().set_shell_foreground_task(task_id)?;
|
||||||
.lifecycle()
|
|
||||||
.set_foreground_task(task_id)
|
|
||||||
.expect("newly created native shell task should have an associated process");
|
|
||||||
|
|
||||||
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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,15 @@
|
|||||||
use crate::CrashReport;
|
use crate::CrashReport;
|
||||||
use crate::os::SystemOS;
|
use crate::os::{GameLifecycleEvent, SystemOS};
|
||||||
|
use crate::task::TaskId;
|
||||||
|
use crate::vm_session::VmSession;
|
||||||
use crate::{RenderWorkerConfig, RenderWorkerController};
|
use crate::{RenderWorkerConfig, RenderWorkerController};
|
||||||
|
use prometeu_bytecode::Value;
|
||||||
use prometeu_hal::app_mode::AppMode;
|
use prometeu_hal::app_mode::AppMode;
|
||||||
use prometeu_hal::cartridge::Cartridge;
|
|
||||||
use prometeu_hal::telemetry::{CertificationConfig, TelemetryFrame};
|
use prometeu_hal::telemetry::{CertificationConfig, TelemetryFrame};
|
||||||
use prometeu_hal::{
|
use prometeu_hal::{
|
||||||
FrameId, InputSignals, RenderWorkerBackend, RenderWorkerError, RenderWorkerFrameSink,
|
FrameId, InputSignals, RenderOwnership, RenderWorkerBackend, RenderWorkerError,
|
||||||
RuntimePlatform,
|
RenderWorkerFrameSink, RuntimePlatform,
|
||||||
};
|
};
|
||||||
use prometeu_vm::VirtualMachine;
|
|
||||||
use std::sync::atomic::Ordering;
|
use std::sync::atomic::Ordering;
|
||||||
|
|
||||||
pub struct VmFacade<'a> {
|
pub struct VmFacade<'a> {
|
||||||
@@ -16,88 +17,216 @@ pub struct VmFacade<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> VmFacade<'a> {
|
impl<'a> VmFacade<'a> {
|
||||||
pub fn initialize(
|
pub fn tick_session(
|
||||||
&mut self,
|
&mut self,
|
||||||
vm: &mut VirtualMachine,
|
task_id: TaskId,
|
||||||
cartridge: &Cartridge,
|
|
||||||
) -> Result<(), CrashReport> {
|
|
||||||
self.os.clear_cartridge_service_state();
|
|
||||||
self.os.vm_runtime.initialize_vm(&mut self.os.log_service, vm, cartridge)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn tick(
|
|
||||||
&mut self,
|
|
||||||
vm: &mut VirtualMachine,
|
|
||||||
signals: &InputSignals,
|
signals: &InputSignals,
|
||||||
platform: &mut dyn RuntimePlatform,
|
platform: &mut dyn RuntimePlatform,
|
||||||
) -> Option<CrashReport> {
|
) -> Option<CrashReport> {
|
||||||
self.os.vm_runtime.tick(
|
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.log_service,
|
||||||
&mut self.os.fs,
|
&mut self.os.fs,
|
||||||
&mut self.os.fs_state,
|
&mut session.fs_state,
|
||||||
&mut self.os.memcard,
|
&mut self.os.memcard,
|
||||||
&mut self.os.open_files,
|
&mut session.open_files,
|
||||||
&mut self.os.next_handle,
|
&mut session.next_handle,
|
||||||
vm,
|
&mut session.vm,
|
||||||
signals,
|
signals,
|
||||||
platform,
|
platform,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn reset(&mut self, vm: &mut VirtualMachine) {
|
fn deliver_pending_game_lifecycle_events_to_session(&mut self, task_id: TaskId) {
|
||||||
self.os.vm_runtime.reset(vm);
|
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 debug_step_instruction(
|
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,
|
&mut self,
|
||||||
vm: &mut VirtualMachine,
|
|
||||||
platform: &mut dyn RuntimePlatform,
|
platform: &mut dyn RuntimePlatform,
|
||||||
) -> Option<CrashReport> {
|
) -> Option<CrashReport> {
|
||||||
self.os.vm_runtime.debug_step_instruction(&mut self.os.log_service, vm, platform)
|
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 {
|
pub fn paused(&self) -> bool {
|
||||||
self.os.vm_runtime.paused
|
self.active_session()
|
||||||
|
.map(|session| session.runtime.paused)
|
||||||
|
.unwrap_or(self.os.vm_runtime.paused)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_paused(&mut self, paused: bool) {
|
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;
|
self.os.vm_runtime.paused = paused;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_inspection_active(&mut self, active: bool) {
|
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;
|
self.os.vm_runtime.inspection_active = active;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn request_debug_step(&mut self) {
|
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;
|
self.os.vm_runtime.debug_step_request = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn debug_step_requested(&self) -> bool {
|
pub fn debug_step_requested(&self) -> bool {
|
||||||
self.os.vm_runtime.debug_step_request
|
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 {
|
pub fn logical_frame_active(&self) -> bool {
|
||||||
self.os.vm_runtime.logical_frame_active
|
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 {
|
pub fn tick_index(&self) -> u64 {
|
||||||
self.os.vm_runtime.tick_index
|
self.active_session()
|
||||||
|
.map(|session| session.runtime.tick_index)
|
||||||
|
.unwrap_or(self.os.vm_runtime.tick_index)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn logical_frame_index(&self) -> u64 {
|
pub fn logical_frame_index(&self) -> u64 {
|
||||||
self.os.vm_runtime.logical_frame_index
|
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 {
|
pub fn last_frame_cpu_time_us(&self) -> u64 {
|
||||||
self.os.vm_runtime.last_frame_cpu_time_us
|
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 {
|
pub fn completed_logical_frames(&self) -> u64 {
|
||||||
self.os.vm_runtime.atomic_telemetry.completed_logical_frames.load(Ordering::Relaxed).into()
|
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 {
|
pub fn telemetry_snapshot(&self) -> TelemetryFrame {
|
||||||
self.os.vm_runtime.atomic_telemetry.snapshot()
|
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)
|
pub fn start_render_worker<B, S>(&mut self, config: RenderWorkerConfig, backend: B, sink: S)
|
||||||
@@ -120,27 +249,82 @@ impl<'a> VmFacade<'a> {
|
|||||||
self.os.vm_runtime.record_repeated_render_worker_frame(frame_id);
|
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 {
|
pub fn cert_config(&self) -> &CertificationConfig {
|
||||||
&self.os.vm_runtime.certifier.config
|
&self.os.vm_runtime.certifier.config
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn last_crash_report(&self) -> Option<&CrashReport> {
|
pub fn last_crash_report(&self) -> Option<&CrashReport> {
|
||||||
self.os.vm_runtime.last_crash_report.as_ref()
|
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 {
|
pub fn current_app_id(&self) -> u32 {
|
||||||
self.os.vm_runtime.current_app_id
|
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 {
|
pub fn current_cartridge_title(&self) -> String {
|
||||||
self.os.vm_runtime.current_cartridge_title.clone()
|
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 {
|
pub fn current_cartridge_app_version(&self) -> String {
|
||||||
self.os.vm_runtime.current_cartridge_app_version.clone()
|
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 {
|
pub fn current_cartridge_app_mode(&self) -> AppMode {
|
||||||
self.os.vm_runtime.current_cartridge_app_mode
|
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()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,20 @@
|
|||||||
use crate::process::ProcessId;
|
use crate::process::ProcessId;
|
||||||
use crate::task::{TaskId, TaskState};
|
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)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum LifecycleOperation {
|
pub enum LifecycleOperation {
|
||||||
SetForeground,
|
SetForeground,
|
||||||
@@ -15,4 +29,7 @@ pub enum LifecycleError {
|
|||||||
TaskNotFound(TaskId),
|
TaskNotFound(TaskId),
|
||||||
ProcessNotFound(ProcessId),
|
ProcessNotFound(ProcessId),
|
||||||
InvalidTransition { task_id: TaskId, from: TaskState, operation: LifecycleOperation },
|
InvalidTransition { task_id: TaskId, from: TaskState, operation: LifecycleOperation },
|
||||||
|
ResidentGameAlreadyExists { existing: TaskId, requested: TaskId },
|
||||||
|
ForegroundShellAlreadyExists { existing: TaskId, requested: TaskId },
|
||||||
|
TaskIsNotResidentGame(TaskId),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,11 @@ mod facades;
|
|||||||
mod lifecycle;
|
mod lifecycle;
|
||||||
mod system_os;
|
mod system_os;
|
||||||
|
|
||||||
pub use facades::{FsFacade, LifecycleFacade, SessionsFacade, VmFacade, WindowFacade};
|
pub use facades::{
|
||||||
pub use lifecycle::{LifecycleError, LifecycleOperation};
|
FsFacade, LifecycleFacade, SessionError, SessionsFacade, VmFacade, WindowFacade,
|
||||||
|
};
|
||||||
|
pub use lifecycle::{
|
||||||
|
DEFAULT_GAME_PAUSE_BUDGET_TICKS, GameLifecycleEvent, GameLifecycleEventKind, LifecycleError,
|
||||||
|
LifecycleOperation,
|
||||||
|
};
|
||||||
pub use system_os::SystemOS;
|
pub use system_os::SystemOS;
|
||||||
|
|||||||
@@ -1,8 +1,12 @@
|
|||||||
use crate::VirtualMachineRuntime;
|
use crate::VirtualMachineRuntime;
|
||||||
use crate::fs::{FsState, VirtualFS};
|
use crate::fs::{FsState, VirtualFS};
|
||||||
use crate::os::{FsFacade, LifecycleFacade, SessionsFacade, VmFacade, WindowFacade};
|
use crate::os::{
|
||||||
|
FsFacade, GameLifecycleEvent, LifecycleFacade, SessionsFacade, VmFacade, WindowFacade,
|
||||||
|
};
|
||||||
use crate::process::ProcessManager;
|
use crate::process::ProcessManager;
|
||||||
|
use crate::services::foreground::ForegroundStack;
|
||||||
use crate::services::memcard::MemcardService;
|
use crate::services::memcard::MemcardService;
|
||||||
|
use crate::services::vm_session::VmSessionRegistry;
|
||||||
use crate::services::windows::WindowManager;
|
use crate::services::windows::WindowManager;
|
||||||
use crate::task::TaskManager;
|
use crate::task::TaskManager;
|
||||||
use prometeu_hal::log::{LogEvent, LogLevel, LogService, LogSource};
|
use prometeu_hal::log::{LogEvent, LogLevel, LogService, LogSource};
|
||||||
@@ -14,6 +18,9 @@ pub struct SystemOS {
|
|||||||
pub(super) vm_runtime: VirtualMachineRuntime,
|
pub(super) vm_runtime: VirtualMachineRuntime,
|
||||||
pub(super) process_manager: ProcessManager,
|
pub(super) process_manager: ProcessManager,
|
||||||
pub(super) task_manager: TaskManager,
|
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) window_manager: WindowManager,
|
||||||
pub(super) log_service: LogService,
|
pub(super) log_service: LogService,
|
||||||
pub(super) fs: VirtualFS,
|
pub(super) fs: VirtualFS,
|
||||||
@@ -33,6 +40,9 @@ impl SystemOS {
|
|||||||
),
|
),
|
||||||
process_manager: ProcessManager::new(),
|
process_manager: ProcessManager::new(),
|
||||||
task_manager: TaskManager::new(),
|
task_manager: TaskManager::new(),
|
||||||
|
foreground_stack: ForegroundStack::new(),
|
||||||
|
vm_sessions: VmSessionRegistry::new(),
|
||||||
|
game_lifecycle_events: Vec::new(),
|
||||||
window_manager: WindowManager::new(),
|
window_manager: WindowManager::new(),
|
||||||
log_service,
|
log_service,
|
||||||
fs: VirtualFS::new(),
|
fs: VirtualFS::new(),
|
||||||
@@ -133,15 +143,33 @@ impl SystemOS {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::os::{LifecycleError, LifecycleOperation};
|
use crate::os::{GameLifecycleEventKind, LifecycleError, LifecycleOperation, SessionError};
|
||||||
use crate::process::ProcessState;
|
use crate::process::{ProcessId, ProcessKind, ProcessState};
|
||||||
|
use crate::services::foreground::{ForegroundOwner, ResidentGame, ResidentGameState};
|
||||||
use crate::task::{TaskId, TaskState};
|
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 {
|
fn process_state_for_task(os: &SystemOS, task_id: TaskId) -> ProcessState {
|
||||||
let task = os.task_manager.get(task_id).expect("task should exist");
|
let task = os.task_manager.get(task_id).expect("task should exist");
|
||||||
os.process_manager.get(task.process_id).expect("process should exist").state
|
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]
|
#[test]
|
||||||
fn set_foreground_task_marks_task_and_process_running() {
|
fn set_foreground_task_marks_task_and_process_running() {
|
||||||
let mut os = SystemOS::new(None);
|
let mut os = SystemOS::new(None);
|
||||||
@@ -157,6 +185,394 @@ mod tests {
|
|||||||
assert_eq!(process_state_for_task(&os, task_id), ProcessState::Running);
|
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]
|
#[test]
|
||||||
fn suspend_task_marks_task_and_process_suspended() {
|
fn suspend_task_marks_task_and_process_suspended() {
|
||||||
let mut os = SystemOS::new(None);
|
let mut os = SystemOS::new(None);
|
||||||
@@ -184,6 +600,10 @@ mod tests {
|
|||||||
TaskState::Foreground
|
TaskState::Foreground
|
||||||
);
|
);
|
||||||
assert_eq!(process_state_for_task(&os, task_id), ProcessState::Running);
|
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]
|
#[test]
|
||||||
|
|||||||
@@ -1,3 +1,6 @@
|
|||||||
mod prometeu_hub;
|
mod prometeu_hub;
|
||||||
|
|
||||||
pub use prometeu_hub::{NativeShellApp, PrometeuHub, SystemProfileAction, SystemProfileUpdate};
|
pub use prometeu_hub::{
|
||||||
|
HUB_SUSPENDED_GAME_KILL_CONTROL, NativeShellApp, PrometeuHub, SystemProfileAction,
|
||||||
|
SystemProfileUpdate,
|
||||||
|
};
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
#[allow(clippy::module_inception)]
|
#[allow(clippy::module_inception)]
|
||||||
mod prometeu_hub;
|
mod prometeu_hub;
|
||||||
|
|
||||||
pub use prometeu_hub::{NativeShellApp, PrometeuHub, SystemProfileAction, SystemProfileUpdate};
|
pub use prometeu_hub::{
|
||||||
|
HUB_SUSPENDED_GAME_KILL_CONTROL, NativeShellApp, PrometeuHub, SystemProfileAction,
|
||||||
|
SystemProfileUpdate,
|
||||||
|
};
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
use crate::{CrashReport, GameLibrary, SystemOS};
|
use crate::task::TaskId;
|
||||||
|
use crate::{CrashReport, GameLibrary, GameSwitchTarget, SystemOS};
|
||||||
|
use prometeu_hal::app_mode::AppMode;
|
||||||
use prometeu_hal::color::Color;
|
use prometeu_hal::color::Color;
|
||||||
use prometeu_hal::primitives::Rect;
|
use prometeu_hal::primitives::Rect;
|
||||||
use prometeu_hal::{
|
use prometeu_hal::{
|
||||||
FrameId, GfxUiCommand, InputPlatform, InputSignals, RenderSubmission, RuntimePlatform,
|
FrameId, GfxUiCommand, InputPlatform, InputSignals, RenderSubmission, RuntimePlatform,
|
||||||
ShellUiFramePacket,
|
ShellUiFramePacket,
|
||||||
};
|
};
|
||||||
use prometeu_vm::VirtualMachine;
|
|
||||||
use std::path::PathBuf;
|
|
||||||
|
|
||||||
const SHELL_A_BUTTON: Rect = Rect { x: 112, y: 172, w: 112, h: 32 };
|
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 SHELL_B_BUTTON: Rect = Rect { x: 256, y: 172, w: 112, h: 32 };
|
||||||
@@ -20,6 +20,7 @@ const GAME_ROW_W: i32 = 336;
|
|||||||
const GAME_ROW_H: i32 = 22;
|
const GAME_ROW_H: i32 = 22;
|
||||||
const GAME_ROW_GAP: i32 = 6;
|
const GAME_ROW_GAP: i32 = 6;
|
||||||
const MAX_HOME_GAME_ROWS: usize = 3;
|
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)]
|
#[cfg(test)]
|
||||||
const SHELL_FRAME: Rect = Rect { x: 40, y: 20, w: 400, h: 220 };
|
const SHELL_FRAME: Rect = Rect { x: 40, y: 20, w: 400, h: 220 };
|
||||||
|
|
||||||
@@ -32,6 +33,8 @@ const COLOR_TEXT: Color = Color::rgb(230, 236, 224);
|
|||||||
const COLOR_MUTED: Color = Color::rgb(91, 112, 128);
|
const COLOR_MUTED: Color = Color::rgb(91, 112, 128);
|
||||||
const COLOR_BUTTON: Color = Color::rgb(45, 59, 82);
|
const COLOR_BUTTON: Color = Color::rgb(45, 59, 82);
|
||||||
const COLOR_BUTTON_ACTIVE: Color = Color::rgb(72, 91, 122);
|
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 {
|
||||||
@@ -83,7 +86,8 @@ impl NativeShellApp {
|
|||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub enum SystemProfileAction {
|
pub enum SystemProfileAction {
|
||||||
LaunchNativeShell(NativeShellApp),
|
LaunchNativeShell(NativeShellApp),
|
||||||
LaunchGame { path: PathBuf },
|
LaunchGame { target: GameSwitchTarget },
|
||||||
|
KillResidentGame,
|
||||||
CloseShell,
|
CloseShell,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -132,12 +136,14 @@ impl PrometeuHub {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let input = platform.input();
|
let input = platform.input();
|
||||||
|
let suspended_game = if in_shell { None } else { resident_game_indicator(os) };
|
||||||
if let Some(action) = action_for_click(
|
if let Some(action) = action_for_click(
|
||||||
in_shell,
|
in_shell,
|
||||||
input.touch().x(),
|
input.touch().x(),
|
||||||
input.touch().y(),
|
input.touch().y(),
|
||||||
input.touch().f().pressed,
|
input.touch().f().pressed,
|
||||||
self.game_library.entries(),
|
self.game_library.entries(),
|
||||||
|
suspended_game.as_ref(),
|
||||||
) {
|
) {
|
||||||
return Some(action);
|
return Some(action);
|
||||||
}
|
}
|
||||||
@@ -150,7 +156,13 @@ impl PrometeuHub {
|
|||||||
let pointer_y = platform.input().touch().y();
|
let pointer_y = platform.input().touch().y();
|
||||||
|
|
||||||
let packet = if os.windows().window_count() == 0 {
|
let packet = if os.windows().window_count() == 0 {
|
||||||
render_home_packet(pointer_x, pointer_y, self.game_library.entries())
|
let suspended_game = resident_game_indicator(os);
|
||||||
|
render_home_packet(
|
||||||
|
pointer_x,
|
||||||
|
pointer_y,
|
||||||
|
self.game_library.entries(),
|
||||||
|
suspended_game.as_ref(),
|
||||||
|
)
|
||||||
} else {
|
} else {
|
||||||
let mut commands = Vec::new();
|
let mut commands = Vec::new();
|
||||||
for window in os.windows().windows() {
|
for window in os.windows().windows() {
|
||||||
@@ -174,7 +186,23 @@ impl PrometeuHub {
|
|||||||
pub fn update_shell_profile(
|
pub fn update_shell_profile(
|
||||||
&mut self,
|
&mut self,
|
||||||
os: &mut SystemOS,
|
os: &mut SystemOS,
|
||||||
vm: &mut VirtualMachine,
|
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,
|
signals: &InputSignals,
|
||||||
platform: &mut dyn RuntimePlatform,
|
platform: &mut dyn RuntimePlatform,
|
||||||
) -> SystemProfileUpdate {
|
) -> SystemProfileUpdate {
|
||||||
@@ -185,7 +213,7 @@ impl PrometeuHub {
|
|||||||
if platform.input().pad().start().down {
|
if platform.input().pad().start().down {
|
||||||
action = Some(SystemProfileAction::CloseShell);
|
action = Some(SystemProfileAction::CloseShell);
|
||||||
} else if action != Some(SystemProfileAction::CloseShell) {
|
} else if action != Some(SystemProfileAction::CloseShell) {
|
||||||
crash = os.vm().tick(vm, signals, platform);
|
crash = os.vm().tick_session(task_id, signals, platform);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -193,6 +221,22 @@ impl PrometeuHub {
|
|||||||
|
|
||||||
SystemProfileUpdate { crash, action }
|
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(
|
fn action_for_click(
|
||||||
@@ -201,6 +245,7 @@ fn action_for_click(
|
|||||||
y: i32,
|
y: i32,
|
||||||
pressed: bool,
|
pressed: bool,
|
||||||
game_entries: &[crate::GameLibraryEntry],
|
game_entries: &[crate::GameLibraryEntry],
|
||||||
|
suspended_game: Option<&SuspendedGameIndicator>,
|
||||||
) -> Option<SystemProfileAction> {
|
) -> Option<SystemProfileAction> {
|
||||||
if !pressed {
|
if !pressed {
|
||||||
return None;
|
return None;
|
||||||
@@ -210,6 +255,10 @@ fn action_for_click(
|
|||||||
return rect_contains(CLOSE_BUTTON, x, y).then_some(SystemProfileAction::CloseShell);
|
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
|
if let Some(entry) = game_entries
|
||||||
.iter()
|
.iter()
|
||||||
.take(MAX_HOME_GAME_ROWS)
|
.take(MAX_HOME_GAME_ROWS)
|
||||||
@@ -217,7 +266,7 @@ fn action_for_click(
|
|||||||
.find(|(index, _entry)| rect_contains(game_row_rect(*index), x, y))
|
.find(|(index, _entry)| rect_contains(game_row_rect(*index), x, y))
|
||||||
.map(|(_index, entry)| entry)
|
.map(|(_index, entry)| entry)
|
||||||
{
|
{
|
||||||
return Some(SystemProfileAction::LaunchGame { path: entry.path.clone() });
|
return Some(SystemProfileAction::LaunchGame { target: entry.switch_target() });
|
||||||
}
|
}
|
||||||
|
|
||||||
HOME_BUTTONS
|
HOME_BUTTONS
|
||||||
@@ -226,6 +275,23 @@ fn action_for_click(
|
|||||||
.map(|button| SystemProfileAction::LaunchNativeShell(button.app))
|
.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 {
|
fn game_row_rect(index: usize) -> Rect {
|
||||||
Rect {
|
Rect {
|
||||||
x: GAME_ROW_X,
|
x: GAME_ROW_X,
|
||||||
@@ -250,6 +316,7 @@ fn render_home_packet(
|
|||||||
pointer_x: i32,
|
pointer_x: i32,
|
||||||
pointer_y: i32,
|
pointer_y: i32,
|
||||||
game_entries: &[crate::GameLibraryEntry],
|
game_entries: &[crate::GameLibraryEntry],
|
||||||
|
suspended_game: Option<&SuspendedGameIndicator>,
|
||||||
) -> ShellUiFramePacket {
|
) -> ShellUiFramePacket {
|
||||||
let mut commands = Vec::new();
|
let mut commands = Vec::new();
|
||||||
commands.push(GfxUiCommand::Clear { color: COLOR_BG });
|
commands.push(GfxUiCommand::Clear { color: COLOR_BG });
|
||||||
@@ -289,6 +356,11 @@ fn render_home_packet(
|
|||||||
draw_button(&mut commands, button.rect, button.label, hovered);
|
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)
|
ShellUiFramePacket::new(commands)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -391,6 +463,39 @@ fn draw_game_row(commands: &mut Vec<GfxUiCommand>, rect: Rect, label: &str, hove
|
|||||||
draw_buffer_text(commands, rect.x + 8, rect.y + 7, label, COLOR_TEXT);
|
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) {
|
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 });
|
commands.push(GfxUiCommand::DrawText { x, y, text: text.to_string(), color });
|
||||||
}
|
}
|
||||||
@@ -398,11 +503,47 @@ fn draw_buffer_text(commands: &mut Vec<GfxUiCommand>, x: i32, y: i32, text: &str
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
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]
|
#[test]
|
||||||
fn shell_a_button_click_emits_launch_action() {
|
fn shell_a_button_click_emits_launch_action() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
action_for_click(false, HOME_BUTTONS[0].rect.x, HOME_BUTTONS[0].rect.y, true, &[]),
|
action_for_click(
|
||||||
|
false,
|
||||||
|
HOME_BUTTONS[0].rect.x,
|
||||||
|
HOME_BUTTONS[0].rect.y,
|
||||||
|
true,
|
||||||
|
&[],
|
||||||
|
None
|
||||||
|
),
|
||||||
Some(SystemProfileAction::LaunchNativeShell(NativeShellApp::ShellA))
|
Some(SystemProfileAction::LaunchNativeShell(NativeShellApp::ShellA))
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -415,7 +556,8 @@ mod tests {
|
|||||||
SHELL_B_BUTTON.x + SHELL_B_BUTTON.w - 1,
|
SHELL_B_BUTTON.x + SHELL_B_BUTTON.w - 1,
|
||||||
SHELL_B_BUTTON.y,
|
SHELL_B_BUTTON.y,
|
||||||
true,
|
true,
|
||||||
&[]
|
&[],
|
||||||
|
None
|
||||||
),
|
),
|
||||||
Some(SystemProfileAction::LaunchNativeShell(NativeShellApp::ShellB))
|
Some(SystemProfileAction::LaunchNativeShell(NativeShellApp::ShellB))
|
||||||
);
|
);
|
||||||
@@ -429,7 +571,8 @@ mod tests {
|
|||||||
SHELL_A_BUTTON.x + SHELL_A_BUTTON.w,
|
SHELL_A_BUTTON.x + SHELL_A_BUTTON.w,
|
||||||
SHELL_A_BUTTON.y,
|
SHELL_A_BUTTON.y,
|
||||||
true,
|
true,
|
||||||
&[]
|
&[],
|
||||||
|
None
|
||||||
),
|
),
|
||||||
None
|
None
|
||||||
);
|
);
|
||||||
@@ -439,7 +582,8 @@ mod tests {
|
|||||||
SHELL_A_BUTTON.x,
|
SHELL_A_BUTTON.x,
|
||||||
SHELL_A_BUTTON.y + SHELL_A_BUTTON.h,
|
SHELL_A_BUTTON.y + SHELL_A_BUTTON.h,
|
||||||
true,
|
true,
|
||||||
&[]
|
&[],
|
||||||
|
None
|
||||||
),
|
),
|
||||||
None
|
None
|
||||||
);
|
);
|
||||||
@@ -447,7 +591,10 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn held_pointer_does_not_emit_click_action() {
|
fn held_pointer_does_not_emit_click_action() {
|
||||||
assert_eq!(action_for_click(false, SHELL_A_BUTTON.x, SHELL_A_BUTTON.y, false, &[]), None);
|
assert_eq!(
|
||||||
|
action_for_click(false, SHELL_A_BUTTON.x, SHELL_A_BUTTON.y, false, &[], None),
|
||||||
|
None
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -475,19 +622,35 @@ mod tests {
|
|||||||
discovered_at: std::time::SystemTime::UNIX_EPOCH,
|
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!(
|
assert_eq!(
|
||||||
action_for_click(false, GAME_ROW_X, GAME_ROW_Y, true, std::slice::from_ref(&entry)),
|
action,
|
||||||
Some(SystemProfileAction::LaunchGame { path: entry.path.clone() })
|
Some(SystemProfileAction::LaunchGame {
|
||||||
|
target: GameSwitchTarget {
|
||||||
|
path: entry.path.clone(),
|
||||||
|
app_id: 42,
|
||||||
|
title: "Stress".to_string(),
|
||||||
|
app_version: "1.0.0".to_string(),
|
||||||
|
}
|
||||||
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn close_button_click_emits_close_only_in_shell() {
|
fn close_button_click_emits_close_only_in_shell() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
action_for_click(true, CLOSE_BUTTON.x, CLOSE_BUTTON.y, true, &[]),
|
action_for_click(true, CLOSE_BUTTON.x, CLOSE_BUTTON.y, true, &[], None),
|
||||||
Some(SystemProfileAction::CloseShell)
|
Some(SystemProfileAction::CloseShell)
|
||||||
);
|
);
|
||||||
assert_eq!(action_for_click(false, CLOSE_BUTTON.x, CLOSE_BUTTON.y, true, &[]), None);
|
assert_eq!(action_for_click(false, CLOSE_BUTTON.x, CLOSE_BUTTON.y, true, &[], None), None);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -501,7 +664,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn home_render_produces_shell_ui_packet_commands() {
|
fn home_render_produces_shell_ui_packet_commands() {
|
||||||
let packet = render_home_packet(SHELL_A_BUTTON.x, SHELL_A_BUTTON.y, &[]);
|
let packet = render_home_packet(SHELL_A_BUTTON.x, SHELL_A_BUTTON.y, &[], None);
|
||||||
|
|
||||||
assert!(matches!(packet.commands.first(), Some(GfxUiCommand::Clear { .. })));
|
assert!(matches!(packet.commands.first(), Some(GfxUiCommand::Clear { .. })));
|
||||||
assert!(packet.commands.iter().any(|command| {
|
assert!(packet.commands.iter().any(|command| {
|
||||||
@@ -509,6 +672,123 @@ mod tests {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[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]
|
#[test]
|
||||||
fn shell_close_button_sits_inside_shell_frame() {
|
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.y));
|
||||||
@@ -518,4 +798,35 @@ mod tests {
|
|||||||
CLOSE_BUTTON.y + CLOSE_BUTTON.h - 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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -25,6 +25,29 @@ impl GameLibraryEntry {
|
|||||||
discovered_at,
|
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)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
@@ -256,6 +279,31 @@ mod tests {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[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]
|
#[test]
|
||||||
fn missing_root_returns_diagnostic_and_no_entries() {
|
fn missing_root_returns_diagnostic_and_no_entries() {
|
||||||
let root = TestRoot::new();
|
let root = TestRoot::new();
|
||||||
@@ -267,4 +315,22 @@ mod tests {
|
|||||||
assert_eq!(library.diagnostics().len(), 1);
|
assert_eq!(library.diagnostics().len(), 1);
|
||||||
assert_eq!(library.diagnostics()[0].reason, GameLibraryDiagnosticReason::RootNotDirectory);
|
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,8 +1,10 @@
|
|||||||
pub mod async_work;
|
pub mod async_work;
|
||||||
|
pub mod foreground;
|
||||||
pub mod fs;
|
pub mod fs;
|
||||||
pub mod game_library;
|
pub mod game_library;
|
||||||
pub mod memcard;
|
pub mod memcard;
|
||||||
pub mod process;
|
pub mod process;
|
||||||
pub mod task;
|
pub mod task;
|
||||||
pub mod vm_runtime;
|
pub mod vm_runtime;
|
||||||
|
pub mod vm_session;
|
||||||
pub mod windows;
|
pub mod windows;
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ impl VirtualMachineRuntime {
|
|||||||
gfx2d_commands: Vec::new(),
|
gfx2d_commands: Vec::new(),
|
||||||
gfxui_commands: Vec::new(),
|
gfxui_commands: Vec::new(),
|
||||||
logs_written_this_frame: HashMap::new(),
|
logs_written_this_frame: HashMap::new(),
|
||||||
|
game_lifecycle_events_delivered: Vec::new(),
|
||||||
atomic_telemetry,
|
atomic_telemetry,
|
||||||
last_crash_report: None,
|
last_crash_report: None,
|
||||||
certifier: Certifier::new(cap_config.unwrap_or_default()),
|
certifier: Certifier::new(cap_config.unwrap_or_default()),
|
||||||
@@ -135,6 +136,7 @@ impl VirtualMachineRuntime {
|
|||||||
self.gfx2d_commands.clear();
|
self.gfx2d_commands.clear();
|
||||||
self.gfxui_commands.clear();
|
self.gfxui_commands.clear();
|
||||||
self.logs_written_this_frame.clear();
|
self.logs_written_this_frame.clear();
|
||||||
|
self.game_lifecycle_events_delivered.clear();
|
||||||
|
|
||||||
self.last_crash_report = None;
|
self.last_crash_report = None;
|
||||||
|
|
||||||
@@ -191,6 +193,21 @@ impl VirtualMachineRuntime {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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(
|
pub fn initialize_vm(
|
||||||
&mut self,
|
&mut self,
|
||||||
log_service: &mut LogService,
|
log_service: &mut LogService,
|
||||||
@@ -224,3 +241,26 @@ impl VirtualMachineRuntime {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ mod tests;
|
|||||||
mod tick;
|
mod tick;
|
||||||
|
|
||||||
use crate::CrashReport;
|
use crate::CrashReport;
|
||||||
|
use crate::os::GameLifecycleEvent;
|
||||||
pub use frame_scheduler::FrameScheduler;
|
pub use frame_scheduler::FrameScheduler;
|
||||||
use prometeu_bytecode::string_materialization_count;
|
use prometeu_bytecode::string_materialization_count;
|
||||||
use prometeu_hal::app_mode::AppMode;
|
use prometeu_hal::app_mode::AppMode;
|
||||||
@@ -49,6 +50,7 @@ pub struct VirtualMachineRuntime {
|
|||||||
pub gfx2d_commands: Vec<Gfx2dCommand>,
|
pub gfx2d_commands: Vec<Gfx2dCommand>,
|
||||||
pub gfxui_commands: Vec<GfxUiCommand>,
|
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,
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ use prometeu_hal::asset::{
|
|||||||
use prometeu_hal::cartridge::{AssetsPayloadSource, Cartridge};
|
use prometeu_hal::cartridge::{AssetsPayloadSource, Cartridge};
|
||||||
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::{GLYPH_BANK_PALETTE_COUNT_V1, GlyphBank, TileSize};
|
use prometeu_hal::glyph_bank::{GLYPH_BANK_MAX_PALETTE_COUNT_V1, GlyphBank, TileSize};
|
||||||
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::syscalls::caps;
|
use prometeu_hal::syscalls::caps;
|
||||||
@@ -113,11 +113,12 @@ fn serialized_single_function_module_with_consts(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn test_glyph_payload_size(width: usize, height: usize) -> usize {
|
fn test_glyph_payload_size(width: usize, height: usize) -> usize {
|
||||||
(width * height).div_ceil(2) + (GLYPH_BANK_PALETTE_COUNT_V1 * 16 * std::mem::size_of::<u32>())
|
(width * height).div_ceil(2)
|
||||||
|
+ (GLYPH_BANK_MAX_PALETTE_COUNT_V1 * 16 * std::mem::size_of::<u32>())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn test_glyph_decoded_size(width: usize, height: usize) -> usize {
|
fn test_glyph_decoded_size(width: usize, height: usize) -> usize {
|
||||||
width * height + (GLYPH_BANK_PALETTE_COUNT_V1 * 16 * std::mem::size_of::<u32>())
|
width * height + (GLYPH_BANK_MAX_PALETTE_COUNT_V1 * 16 * std::mem::size_of::<u32>())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn test_glyph_asset_entry(asset_name: &str, data_len: usize) -> AssetEntry {
|
fn test_glyph_asset_entry(asset_name: &str, data_len: usize) -> AssetEntry {
|
||||||
@@ -133,23 +134,23 @@ fn test_glyph_asset_entry(asset_name: &str, data_len: usize) -> AssetEntry {
|
|||||||
"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
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn test_glyph_asset_data() -> Vec<u8> {
|
fn test_glyph_asset_data() -> Vec<u8> {
|
||||||
let mut data =
|
let mut data =
|
||||||
vec![0x11u8; test_glyph_payload_size(16, 16) - (GLYPH_BANK_PALETTE_COUNT_V1 * 16 * 4)];
|
vec![0x11u8; test_glyph_payload_size(16, 16) - (GLYPH_BANK_MAX_PALETTE_COUNT_V1 * 16 * 4)];
|
||||||
data.extend_from_slice(&[0u8; GLYPH_BANK_PALETTE_COUNT_V1 * 16 * 4]);
|
data.extend_from_slice(&[0u8; GLYPH_BANK_MAX_PALETTE_COUNT_V1 * 16 * 4]);
|
||||||
data
|
data
|
||||||
}
|
}
|
||||||
|
|
||||||
fn runtime_test_glyph_bank(tile_size: TileSize, palette_id: u8, color: Color) -> GlyphBank {
|
fn runtime_test_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 = GlyphBank::with_palette_count(tile_size, size, size, palette_id as usize + 1);
|
||||||
bank.palettes[palette_id as usize][1] = color;
|
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;
|
||||||
}
|
}
|
||||||
@@ -1275,6 +1276,53 @@ fn tick_composer_emit_sprite_operational_error_returns_status_not_crash() {
|
|||||||
assert_eq!(vm.operand_stack_top(1), vec![Value::Int64(ComposerOpStatus::BankInvalid as i64)]);
|
assert_eq!(vm.operand_stack_top(1), vec![Value::Int64(ComposerOpStatus::BankInvalid as i64)]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tick_composer_emit_sprite_invalid_palette_returns_bank_invalid() {
|
||||||
|
let mut runtime = VirtualMachineRuntime::new(None);
|
||||||
|
let mut log_service = LogService::new(4096);
|
||||||
|
let mut fs = VirtualFS::new();
|
||||||
|
let mut fs_state = FsState::Unmounted;
|
||||||
|
let mut memcard = MemcardService::new();
|
||||||
|
let mut open_files: HashMap<u32, String> = HashMap::new();
|
||||||
|
let mut next_handle = 1;
|
||||||
|
let mut vm = VirtualMachine::default();
|
||||||
|
let banks = Arc::new(MemoryBanks::new());
|
||||||
|
banks.install_glyph_bank(0, Arc::new(runtime_test_glyph_bank(TileSize::Size8, 0, Color::BLUE)));
|
||||||
|
let mut platform = TestPlatform::new_with_memory_banks(banks);
|
||||||
|
let signals = InputSignals::default();
|
||||||
|
let code = assemble(
|
||||||
|
"PUSH_I32 0\nPUSH_I32 1\nPUSH_I32 0\nPUSH_I32 0\nPUSH_I32 0\nPUSH_I32 0\nPUSH_BOOL 0\nPUSH_BOOL 0\nPUSH_I32 0\nHOSTCALL 0\nHALT",
|
||||||
|
)
|
||||||
|
.expect("assemble");
|
||||||
|
let program = serialized_single_function_module(
|
||||||
|
code,
|
||||||
|
vec![SyscallDecl {
|
||||||
|
module: "composer".into(),
|
||||||
|
name: "emit_sprite".into(),
|
||||||
|
version: 1,
|
||||||
|
arg_slots: 9,
|
||||||
|
ret_slots: 1,
|
||||||
|
}],
|
||||||
|
);
|
||||||
|
let cartridge = cartridge_with_program(program, caps::GFX);
|
||||||
|
|
||||||
|
runtime.initialize_vm(&mut log_service, &mut vm, &cartridge).expect("runtime must initialize");
|
||||||
|
let report = runtime.tick(
|
||||||
|
&mut log_service,
|
||||||
|
&mut fs,
|
||||||
|
&mut fs_state,
|
||||||
|
&mut memcard,
|
||||||
|
&mut open_files,
|
||||||
|
&mut next_handle,
|
||||||
|
&mut vm,
|
||||||
|
&signals,
|
||||||
|
&mut platform,
|
||||||
|
);
|
||||||
|
assert!(report.is_none(), "invalid palette must not crash VM execution");
|
||||||
|
assert!(vm.is_halted());
|
||||||
|
assert_eq!(vm.operand_stack_top(1), vec![Value::Int64(ComposerOpStatus::BankInvalid as i64)]);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn tick_composer_emit_sprite_invalid_layer_returns_status_not_crash() {
|
fn tick_composer_emit_sprite_invalid_layer_returns_status_not_crash() {
|
||||||
let mut runtime = VirtualMachineRuntime::new(None);
|
let mut runtime = VirtualMachineRuntime::new(None);
|
||||||
|
|||||||
@@ -0,0 +1,310 @@
|
|||||||
|
use crate::VirtualMachineRuntime;
|
||||||
|
use crate::fs::FsState;
|
||||||
|
use crate::process::{Process, ProcessId, ProcessKind};
|
||||||
|
use crate::task::{Task, TaskId, TaskKind};
|
||||||
|
use prometeu_hal::app_mode::AppMode;
|
||||||
|
use prometeu_hal::telemetry::CertificationConfig;
|
||||||
|
use prometeu_vm::VirtualMachine;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::AtomicU32;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
pub struct VmSessionId(pub TaskId);
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum VmSessionError {
|
||||||
|
SessionAlreadyExists(TaskId),
|
||||||
|
TaskProcessMismatch { task_id: TaskId, task_process: ProcessId, process_id: ProcessId },
|
||||||
|
TaskKindMismatch { task_id: TaskId, task_kind: TaskKind, process_kind: ProcessKind },
|
||||||
|
ProcessIsNotVmBacked(ProcessId),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct VmSession {
|
||||||
|
pub id: VmSessionId,
|
||||||
|
pub task_id: TaskId,
|
||||||
|
pub process_id: ProcessId,
|
||||||
|
pub app_id: u32,
|
||||||
|
pub title: String,
|
||||||
|
pub app_version: String,
|
||||||
|
pub app_mode: AppMode,
|
||||||
|
pub vm: VirtualMachine,
|
||||||
|
pub runtime: VirtualMachineRuntime,
|
||||||
|
pub fs_state: FsState,
|
||||||
|
pub open_files: HashMap<u32, String>,
|
||||||
|
pub next_handle: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VmSession {
|
||||||
|
fn new(
|
||||||
|
task: &Task,
|
||||||
|
process: &Process,
|
||||||
|
app_mode: AppMode,
|
||||||
|
app_version: impl Into<String>,
|
||||||
|
cap_config: Option<CertificationConfig>,
|
||||||
|
logs_count: Arc<AtomicU32>,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
id: VmSessionId(task.id),
|
||||||
|
task_id: task.id,
|
||||||
|
process_id: process.id,
|
||||||
|
app_id: task.app_id,
|
||||||
|
title: task.title.clone(),
|
||||||
|
app_version: app_version.into(),
|
||||||
|
app_mode,
|
||||||
|
vm: VirtualMachine::default(),
|
||||||
|
runtime: VirtualMachineRuntime::new_with_log_counter(cap_config, logs_count),
|
||||||
|
fs_state: FsState::Unmounted,
|
||||||
|
open_files: HashMap::new(),
|
||||||
|
next_handle: 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clear_cartridge_service_state(&mut self) {
|
||||||
|
self.open_files.clear();
|
||||||
|
self.next_handle = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct VmSessionRegistry {
|
||||||
|
sessions: HashMap<VmSessionId, VmSession>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VmSessionRegistry {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self { sessions: HashMap::new() }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn create_for_task(
|
||||||
|
&mut self,
|
||||||
|
task: &Task,
|
||||||
|
process: &Process,
|
||||||
|
app_version: impl Into<String>,
|
||||||
|
cap_config: Option<CertificationConfig>,
|
||||||
|
logs_count: Arc<AtomicU32>,
|
||||||
|
) -> Result<VmSessionId, VmSessionError> {
|
||||||
|
if task.process_id != process.id {
|
||||||
|
return Err(VmSessionError::TaskProcessMismatch {
|
||||||
|
task_id: task.id,
|
||||||
|
task_process: task.process_id,
|
||||||
|
process_id: process.id,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let app_mode = app_mode_for_task_and_process(task, process)?;
|
||||||
|
let id = VmSessionId(task.id);
|
||||||
|
if self.sessions.contains_key(&id) {
|
||||||
|
return Err(VmSessionError::SessionAlreadyExists(task.id));
|
||||||
|
}
|
||||||
|
|
||||||
|
self.sessions.insert(
|
||||||
|
id,
|
||||||
|
VmSession::new(task, process, app_mode, app_version, cap_config, logs_count),
|
||||||
|
);
|
||||||
|
Ok(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get(&self, id: VmSessionId) -> Option<&VmSession> {
|
||||||
|
self.sessions.get(&id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_mut(&mut self, id: VmSessionId) -> Option<&mut VmSession> {
|
||||||
|
self.sessions.get_mut(&id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn for_task(&self, task_id: TaskId) -> Option<&VmSession> {
|
||||||
|
self.get(VmSessionId(task_id))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn for_task_mut(&mut self, task_id: TaskId) -> Option<&mut VmSession> {
|
||||||
|
self.get_mut(VmSessionId(task_id))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove_for_task(&mut self, task_id: TaskId) -> Option<VmSession> {
|
||||||
|
self.sessions.remove(&VmSessionId(task_id))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn resident_game(&self) -> Option<&VmSession> {
|
||||||
|
self.sessions.values().find(|session| session.app_mode == AppMode::Game)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn resident_game_for_app(&self, app_id: u32) -> Option<&VmSession> {
|
||||||
|
self.sessions
|
||||||
|
.values()
|
||||||
|
.find(|session| session.app_mode == AppMode::Game && session.app_id == app_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn len(&self) -> usize {
|
||||||
|
self.sessions.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.sessions.is_empty()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clear(&mut self) {
|
||||||
|
self.sessions.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn app_mode_for_task_and_process(
|
||||||
|
task: &Task,
|
||||||
|
process: &Process,
|
||||||
|
) -> Result<AppMode, VmSessionError> {
|
||||||
|
match (task.kind, process.kind) {
|
||||||
|
(TaskKind::Game, ProcessKind::VmGame) => Ok(AppMode::Game),
|
||||||
|
(TaskKind::Shell, ProcessKind::VmShell) => Ok(AppMode::Shell),
|
||||||
|
(_, ProcessKind::NativeShell) => Err(VmSessionError::ProcessIsNotVmBacked(process.id)),
|
||||||
|
_ => Err(VmSessionError::TaskKindMismatch {
|
||||||
|
task_id: task.id,
|
||||||
|
task_kind: task.kind,
|
||||||
|
process_kind: process.kind,
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::process::Process;
|
||||||
|
use crate::task::Task;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn creates_vm_game_session_for_vm_game_task() {
|
||||||
|
let process = Process::new(ProcessId(1), 42, "Stress", ProcessKind::VmGame);
|
||||||
|
let task = Task::new(TaskId(7), process.id, 42, "Stress", TaskKind::Game);
|
||||||
|
let mut registry = VmSessionRegistry::new();
|
||||||
|
|
||||||
|
let id = registry
|
||||||
|
.create_for_task(&task, &process, "", None, Arc::new(AtomicU32::new(0)))
|
||||||
|
.expect("session should create");
|
||||||
|
let session = registry.get(id).expect("session should exist");
|
||||||
|
|
||||||
|
assert_eq!(session.id, VmSessionId(task.id));
|
||||||
|
assert_eq!(session.task_id, task.id);
|
||||||
|
assert_eq!(session.process_id, process.id);
|
||||||
|
assert_eq!(session.app_id, 42);
|
||||||
|
assert_eq!(session.title, "Stress");
|
||||||
|
assert_eq!(session.app_mode, AppMode::Game);
|
||||||
|
assert_eq!(session.runtime.current_app_id, 0);
|
||||||
|
assert_eq!(session.fs_state, FsState::Unmounted);
|
||||||
|
assert_eq!(session.next_handle, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn creates_vm_shell_session_for_vm_shell_task() {
|
||||||
|
let process = Process::new(ProcessId(1), 7, "Shell", ProcessKind::VmShell);
|
||||||
|
let task = Task::new(TaskId(3), process.id, 7, "Shell", TaskKind::Shell);
|
||||||
|
let mut registry = VmSessionRegistry::new();
|
||||||
|
|
||||||
|
let id = registry
|
||||||
|
.create_for_task(&task, &process, "1.0", None, Arc::new(AtomicU32::new(0)))
|
||||||
|
.expect("session should create");
|
||||||
|
let session = registry.get(id).expect("session should exist");
|
||||||
|
|
||||||
|
assert_eq!(session.app_mode, AppMode::Shell);
|
||||||
|
assert_eq!(session.app_version, "1.0");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_native_shell_process() {
|
||||||
|
let process = Process::new(ProcessId(1), 7, "Shell", ProcessKind::NativeShell);
|
||||||
|
let task = Task::new(TaskId(3), process.id, 7, "Shell", TaskKind::Shell);
|
||||||
|
let mut registry = VmSessionRegistry::new();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
registry.create_for_task(&task, &process, "", None, Arc::new(AtomicU32::new(0))),
|
||||||
|
Err(VmSessionError::ProcessIsNotVmBacked(process.id))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn finds_resident_game_by_app_id() {
|
||||||
|
let process = Process::new(ProcessId(1), 42, "Stress", ProcessKind::VmGame);
|
||||||
|
let task = Task::new(TaskId(7), process.id, 42, "Stress", TaskKind::Game);
|
||||||
|
let mut registry = VmSessionRegistry::new();
|
||||||
|
registry
|
||||||
|
.create_for_task(&task, &process, "", None, Arc::new(AtomicU32::new(0)))
|
||||||
|
.expect("session should create");
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
registry.resident_game_for_app(42).map(|session| session.task_id),
|
||||||
|
Some(task.id)
|
||||||
|
);
|
||||||
|
assert_eq!(registry.resident_game_for_app(43).map(|session| session.task_id), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn remove_for_task_removes_only_matching_session() {
|
||||||
|
let game_process = Process::new(ProcessId(1), 42, "Stress", ProcessKind::VmGame);
|
||||||
|
let game_task = Task::new(TaskId(7), game_process.id, 42, "Stress", TaskKind::Game);
|
||||||
|
let shell_process = Process::new(ProcessId(2), 9, "Shell", ProcessKind::VmShell);
|
||||||
|
let shell_task = Task::new(TaskId(8), shell_process.id, 9, "Shell", TaskKind::Shell);
|
||||||
|
let mut registry = VmSessionRegistry::new();
|
||||||
|
|
||||||
|
registry
|
||||||
|
.create_for_task(&game_task, &game_process, "", None, Arc::new(AtomicU32::new(0)))
|
||||||
|
.expect("game session should create");
|
||||||
|
registry
|
||||||
|
.create_for_task(&shell_task, &shell_process, "", None, Arc::new(AtomicU32::new(0)))
|
||||||
|
.expect("shell session should create");
|
||||||
|
|
||||||
|
let removed = registry.remove_for_task(game_task.id).expect("game session should remove");
|
||||||
|
|
||||||
|
assert_eq!(removed.task_id, game_task.id);
|
||||||
|
assert_eq!(registry.for_task(game_task.id).map(|session| session.task_id), None);
|
||||||
|
assert_eq!(
|
||||||
|
registry.for_task(shell_task.id).map(|session| session.task_id),
|
||||||
|
Some(shell_task.id)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn session_runtime_state_is_independent_per_session() {
|
||||||
|
let game_process = Process::new(ProcessId(1), 42, "Stress", ProcessKind::VmGame);
|
||||||
|
let game_task = Task::new(TaskId(7), game_process.id, 42, "Stress", TaskKind::Game);
|
||||||
|
let shell_process = Process::new(ProcessId(2), 9, "Shell", ProcessKind::VmShell);
|
||||||
|
let shell_task = Task::new(TaskId(8), shell_process.id, 9, "Shell", TaskKind::Shell);
|
||||||
|
let mut registry = VmSessionRegistry::new();
|
||||||
|
|
||||||
|
registry
|
||||||
|
.create_for_task(&game_task, &game_process, "", None, Arc::new(AtomicU32::new(0)))
|
||||||
|
.expect("game session should create");
|
||||||
|
registry
|
||||||
|
.create_for_task(&shell_task, &shell_process, "", None, Arc::new(AtomicU32::new(0)))
|
||||||
|
.expect("shell session should create");
|
||||||
|
|
||||||
|
registry
|
||||||
|
.for_task_mut(game_task.id)
|
||||||
|
.expect("game session should exist")
|
||||||
|
.runtime
|
||||||
|
.tick_index = 11;
|
||||||
|
registry
|
||||||
|
.for_task_mut(shell_task.id)
|
||||||
|
.expect("shell session should exist")
|
||||||
|
.runtime
|
||||||
|
.tick_index = 3;
|
||||||
|
registry
|
||||||
|
.for_task_mut(game_task.id)
|
||||||
|
.expect("game session should exist")
|
||||||
|
.open_files
|
||||||
|
.insert(1, "/game.save".to_string());
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
registry.for_task(game_task.id).map(|session| session.runtime.tick_index),
|
||||||
|
Some(11)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
registry.for_task(shell_task.id).map(|session| session.runtime.tick_index),
|
||||||
|
Some(3)
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
registry
|
||||||
|
.for_task(shell_task.id)
|
||||||
|
.expect("shell session should exist")
|
||||||
|
.open_files
|
||||||
|
.is_empty()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2627,7 +2627,7 @@ mod tests {
|
|||||||
fn test_loader_hardening_unsupported_version() {
|
fn test_loader_hardening_unsupported_version() {
|
||||||
let mut vm = VirtualMachine::default();
|
let mut vm = VirtualMachine::default();
|
||||||
let mut header = vec![0u8; 32];
|
let mut header = vec![0u8; 32];
|
||||||
header[0..4].copy_from_slice(b"PBS\0");
|
header[0..4].copy_from_slice(&prometeu_bytecode::PBX_MAGIC);
|
||||||
header[4..6].copy_from_slice(&1u16.to_le_bytes()); // version 1 (unsupported)
|
header[4..6].copy_from_slice(&1u16.to_le_bytes()); // version 1 (unsupported)
|
||||||
|
|
||||||
let res = vm.initialize(header);
|
let res = vm.initialize(header);
|
||||||
@@ -2635,16 +2635,16 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_loader_hardening_malformed_pbs_v0() {
|
fn test_loader_hardening_malformed_pbx_v0() {
|
||||||
let mut vm = VirtualMachine::default();
|
let mut vm = VirtualMachine::default();
|
||||||
let mut header = vec![0u8; 32];
|
let mut header = vec![0u8; 32];
|
||||||
header[0..4].copy_from_slice(b"PBS\0");
|
header[0..4].copy_from_slice(&prometeu_bytecode::PBX_MAGIC);
|
||||||
header[8..12].copy_from_slice(&1u32.to_le_bytes()); // 1 section claimed but none provided
|
header[8..12].copy_from_slice(&1u32.to_le_bytes()); // 1 section claimed but none provided
|
||||||
|
|
||||||
let res = vm.initialize(header);
|
let res = vm.initialize(header);
|
||||||
match res {
|
match res {
|
||||||
Err(VmInitError::ImageLoadFailed(prometeu_bytecode::LoadError::UnexpectedEof)) => {}
|
Err(VmInitError::ImageLoadFailed(prometeu_bytecode::LoadError::UnexpectedEof)) => {}
|
||||||
_ => panic!("Expected PbsV0LoadFailed(UnexpectedEof), got {:?}", res),
|
_ => panic!("Expected PBX v0 load failure UnexpectedEof, got {:?}", res),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2695,6 +2695,13 @@ mod tests {
|
|||||||
assert_eq!(vm.pc, 0);
|
assert_eq!(vm.pc, 0);
|
||||||
assert_eq!(vm.program.rom.len(), 2);
|
assert_eq!(vm.program.rom.len(), 2);
|
||||||
assert_eq!(vm.cycles, 0);
|
assert_eq!(vm.cycles, 0);
|
||||||
|
|
||||||
|
vm.prepare_boot_call();
|
||||||
|
let mut native = MockNative;
|
||||||
|
let mut ctx = HostContext::new(None);
|
||||||
|
let report = vm.run_budget(100, &mut native, &mut ctx).expect("run loaded PBX");
|
||||||
|
assert_eq!(report.reason, LogicalFrameEndingReason::Halted);
|
||||||
|
assert!(vm.is_halted());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -3084,7 +3091,7 @@ mod tests {
|
|||||||
fn test_loader_hardening_missing_sysc_section() {
|
fn test_loader_hardening_missing_sysc_section() {
|
||||||
let mut vm = VirtualMachine::default();
|
let mut vm = VirtualMachine::default();
|
||||||
let mut header = vec![0u8; 32];
|
let mut header = vec![0u8; 32];
|
||||||
header[0..4].copy_from_slice(b"PBS\0");
|
header[0..4].copy_from_slice(&prometeu_bytecode::PBX_MAGIC);
|
||||||
|
|
||||||
let res = vm.initialize(header);
|
let res = vm.initialize(header);
|
||||||
|
|
||||||
|
|||||||
@@ -83,30 +83,32 @@ impl VirtualMachine {
|
|||||||
self.scheduler = Scheduler::new();
|
self.scheduler = Scheduler::new();
|
||||||
self.current_coro = None;
|
self.current_coro = None;
|
||||||
|
|
||||||
let program = if program_bytes.starts_with(b"PBS\0") {
|
let program = match prometeu_bytecode::BytecodeLoader::load(&program_bytes) {
|
||||||
match prometeu_bytecode::BytecodeLoader::load(&program_bytes) {
|
Ok(mut module) => {
|
||||||
Ok(mut module) => {
|
patch_module_hostcalls(&mut module, self.capabilities)
|
||||||
patch_module_hostcalls(&mut module, self.capabilities)
|
.map_err(VmInitError::LoaderPatchFailed)?;
|
||||||
.map_err(VmInitError::LoaderPatchFailed)?;
|
|
||||||
|
|
||||||
let max_stacks = Verifier::verify(&module.code, &module.functions)
|
let max_stacks = Verifier::verify(&module.code, &module.functions)
|
||||||
.map_err(|e| VmInitError::VerificationFailed(format!("{:?}", e)))?;
|
.map_err(|e| VmInitError::VerificationFailed(format!("{:?}", e)))?;
|
||||||
|
|
||||||
let mut program = ProgramImage::from(module);
|
let mut program = ProgramImage::from(module);
|
||||||
let mut functions = program.functions.as_ref().to_vec();
|
let mut functions = program.functions.as_ref().to_vec();
|
||||||
for (func, max_stack) in functions.iter_mut().zip(max_stacks) {
|
for (func, max_stack) in functions.iter_mut().zip(max_stacks) {
|
||||||
func.max_stack_slots = max_stack;
|
func.max_stack_slots = max_stack;
|
||||||
}
|
|
||||||
program.functions = std::sync::Arc::from(functions);
|
|
||||||
program
|
|
||||||
}
|
}
|
||||||
Err(prometeu_bytecode::LoadError::InvalidVersion) => {
|
program.functions = std::sync::Arc::from(functions);
|
||||||
return Err(VmInitError::UnsupportedFormat);
|
program
|
||||||
}
|
|
||||||
Err(e) => return Err(VmInitError::ImageLoadFailed(e)),
|
|
||||||
}
|
}
|
||||||
} else {
|
Err(prometeu_bytecode::LoadError::InvalidVersion) => {
|
||||||
return Err(VmInitError::InvalidFormat);
|
return Err(VmInitError::UnsupportedFormat);
|
||||||
|
}
|
||||||
|
Err(prometeu_bytecode::LoadError::InvalidMagic) => {
|
||||||
|
return Err(VmInitError::InvalidFormat);
|
||||||
|
}
|
||||||
|
Err(prometeu_bytecode::LoadError::UnexpectedEof) if program_bytes.len() < 32 => {
|
||||||
|
return Err(VmInitError::InvalidFormat);
|
||||||
|
}
|
||||||
|
Err(e) => return Err(VmInitError::ImageLoadFailed(e)),
|
||||||
};
|
};
|
||||||
|
|
||||||
let pc = program
|
let pc = program
|
||||||
|
|||||||
@@ -2,8 +2,8 @@ use prometeu_vm::{VirtualMachine, VmInitError};
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn invalid_image_format_is_rejected_before_execution() {
|
fn invalid_image_format_is_rejected_before_execution() {
|
||||||
// Provide bytes that are not a valid PBS image. The VM must reject it with InvalidFormat.
|
// Provide bytes that are not a valid PBX image. The VM must reject it with InvalidFormat.
|
||||||
let program_bytes = b"NOT_PBS_IMAGE".to_vec();
|
let program_bytes = b"NOT_PBX_IMAGE".to_vec();
|
||||||
let mut vm = VirtualMachine::default();
|
let mut vm = VirtualMachine::default();
|
||||||
let result = vm.initialize(program_bytes);
|
let result = vm.initialize(program_bytes);
|
||||||
assert!(matches!(result, Err(VmInitError::InvalidFormat)));
|
assert!(matches!(result, Err(VmInitError::InvalidFormat)));
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
use std::fs;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
const TARGET_MANIFESTS: &[&str] =
|
||||||
|
&["crates/console/prometeu-bytecode/Cargo.toml", "crates/console/prometeu-vm/Cargo.toml"];
|
||||||
|
|
||||||
|
const FORBIDDEN_DEPENDENCY_FRAGMENTS: &[&str] = &["compiler", "frontend"];
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pbx_and_pvm_crates_must_not_depend_on_compiler_or_frontend_crates() {
|
||||||
|
let workspace_root = find_workspace_root().expect("runtime workspace root");
|
||||||
|
let mut violations = Vec::new();
|
||||||
|
|
||||||
|
for relative_path in TARGET_MANIFESTS {
|
||||||
|
let manifest_path = workspace_root.join(relative_path);
|
||||||
|
let manifest = fs::read_to_string(&manifest_path)
|
||||||
|
.unwrap_or_else(|error| panic!("failed to read {}: {error}", manifest_path.display()));
|
||||||
|
|
||||||
|
for dependency in dependency_names(&manifest) {
|
||||||
|
let normalized = dependency.to_ascii_lowercase();
|
||||||
|
if FORBIDDEN_DEPENDENCY_FRAGMENTS.iter().any(|fragment| normalized.contains(fragment)) {
|
||||||
|
violations.push(format!("{relative_path}: forbidden dependency `{dependency}`"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
violations.is_empty(),
|
||||||
|
"PBX/PVM crates must remain independent of compiler and frontend crates:\n{}",
|
||||||
|
violations.join("\n")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dependency_names(manifest: &str) -> Vec<&str> {
|
||||||
|
let mut names = Vec::new();
|
||||||
|
let mut in_dependency_section = false;
|
||||||
|
|
||||||
|
for raw_line in manifest.lines() {
|
||||||
|
let line = raw_line.trim();
|
||||||
|
if line.starts_with('[') && line.ends_with(']') {
|
||||||
|
let section = &line[1..line.len() - 1];
|
||||||
|
in_dependency_section = section == "dependencies"
|
||||||
|
|| section == "dev-dependencies"
|
||||||
|
|| section == "build-dependencies"
|
||||||
|
|| section.ends_with(".dependencies")
|
||||||
|
|| section.ends_with(".dev-dependencies")
|
||||||
|
|| section.ends_with(".build-dependencies");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if !in_dependency_section || line.is_empty() || line.starts_with('#') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some((name, _)) = line.split_once('=') {
|
||||||
|
names.push(name.trim().trim_matches('"'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
names
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_workspace_root() -> Option<PathBuf> {
|
||||||
|
let mut cursor = Path::new(env!("CARGO_MANIFEST_DIR")).to_path_buf();
|
||||||
|
loop {
|
||||||
|
let manifest = cursor.join("Cargo.toml");
|
||||||
|
if fs::read_to_string(&manifest).is_ok_and(|contents| contents.contains("[workspace]")) {
|
||||||
|
return Some(cursor);
|
||||||
|
}
|
||||||
|
if !cursor.pop() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -28,6 +28,8 @@ pub struct HostDebugger {
|
|||||||
last_telemetry_frame: u64,
|
last_telemetry_frame: u64,
|
||||||
/// Last fault summary sent to the debugger client.
|
/// Last fault summary sent to the debugger client.
|
||||||
last_fault_summary: Option<String>,
|
last_fault_summary: Option<String>,
|
||||||
|
/// Debug cartridge metadata captured before the VM session exists.
|
||||||
|
debug_cartridge: Option<HandshakeCartridge>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for HostDebugger {
|
impl Default for HostDebugger {
|
||||||
@@ -46,19 +48,25 @@ impl HostDebugger {
|
|||||||
last_log_seq: 0,
|
last_log_seq: 0,
|
||||||
last_telemetry_frame: 0,
|
last_telemetry_frame: 0,
|
||||||
last_fault_summary: None,
|
last_fault_summary: None,
|
||||||
|
debug_cartridge: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Configures the debugger based on the boot target.
|
/// Configures the debugger based on the boot target.
|
||||||
/// If debug mode is enabled, it binds to the specified TCP port.
|
/// If debug mode is enabled, it binds to the specified TCP port.
|
||||||
pub fn setup_boot_target(&mut self, boot_target: &BootTarget, firmware: &mut Firmware) {
|
pub fn setup_boot_target(&mut self, boot_target: &BootTarget, _firmware: &mut Firmware) {
|
||||||
if let BootTarget::Cartridge { path, debug: true, debug_port } = boot_target {
|
if let BootTarget::Cartridge { path, debug: true, debug_port } = boot_target {
|
||||||
self.waiting_for_start = true;
|
self.waiting_for_start = true;
|
||||||
|
|
||||||
// Pre-load cartridge metadata so the Handshake message can contain
|
// Pre-load cartridge metadata so the Handshake message can contain
|
||||||
// valid information about the App being debugged.
|
// valid information before the VM session is created.
|
||||||
if let Ok(cartridge) = CartridgeLoader::load(path) {
|
if let Ok(cartridge) = CartridgeLoader::load(path) {
|
||||||
let _ = firmware.os.vm().initialize(&mut firmware.vm, &cartridge);
|
self.debug_cartridge = Some(HandshakeCartridge {
|
||||||
|
app_id: cartridge.app_id,
|
||||||
|
title: cartridge.title,
|
||||||
|
app_version: cartridge.app_version,
|
||||||
|
app_mode: cartridge.app_mode,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
match TcpListener::bind(format!("127.0.0.1:{}", debug_port)) {
|
match TcpListener::bind(format!("127.0.0.1:{}", debug_port)) {
|
||||||
@@ -116,12 +124,7 @@ impl HostDebugger {
|
|||||||
let handshake = DebugResponse::Handshake {
|
let handshake = DebugResponse::Handshake {
|
||||||
protocol_version: DEVTOOLS_PROTOCOL_VERSION,
|
protocol_version: DEVTOOLS_PROTOCOL_VERSION,
|
||||||
runtime_version: "0.1".to_string(),
|
runtime_version: "0.1".to_string(),
|
||||||
cartridge: HandshakeCartridge {
|
cartridge: self.handshake_cartridge(firmware),
|
||||||
app_id: firmware.os.vm().current_app_id(),
|
|
||||||
title: firmware.os.vm().current_cartridge_title(),
|
|
||||||
app_version: firmware.os.vm().current_cartridge_app_version(),
|
|
||||||
app_mode: firmware.os.vm().current_cartridge_app_mode(),
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
self.send_response(handshake);
|
self.send_response(handshake);
|
||||||
} else {
|
} else {
|
||||||
@@ -201,7 +204,7 @@ impl HostDebugger {
|
|||||||
DebugCommand::Step => {
|
DebugCommand::Step => {
|
||||||
// Execute exactly one instruction and keep paused.
|
// Execute exactly one instruction and keep paused.
|
||||||
firmware.os.vm().set_paused(true);
|
firmware.os.vm().set_paused(true);
|
||||||
let _ = firmware.os.vm().debug_step_instruction(&mut firmware.vm, platform);
|
let _ = firmware.os.vm().debug_step_active_session(platform);
|
||||||
}
|
}
|
||||||
DebugCommand::StepFrame => {
|
DebugCommand::StepFrame => {
|
||||||
// Execute until the end of the current logical frame.
|
// Execute until the end of the current logical frame.
|
||||||
@@ -210,10 +213,10 @@ impl HostDebugger {
|
|||||||
}
|
}
|
||||||
DebugCommand::GetState => {
|
DebugCommand::GetState => {
|
||||||
// Return detailed VM register and stack state.
|
// Return detailed VM register and stack state.
|
||||||
let stack_top = firmware.vm.operand_stack_top(10);
|
let stack_top = firmware.os.vm().active_operand_stack_top(10);
|
||||||
|
|
||||||
let resp = DebugResponse::GetState {
|
let resp = DebugResponse::GetState {
|
||||||
pc: firmware.vm.pc(),
|
pc: firmware.os.vm().active_pc().unwrap_or(0),
|
||||||
stack_top,
|
stack_top,
|
||||||
frame_index: firmware.os.vm().logical_frame_index(),
|
frame_index: firmware.os.vm().logical_frame_index(),
|
||||||
app_id: firmware.os.vm().current_app_id(),
|
app_id: firmware.os.vm().current_app_id(),
|
||||||
@@ -221,18 +224,37 @@ impl HostDebugger {
|
|||||||
self.send_response(resp);
|
self.send_response(resp);
|
||||||
}
|
}
|
||||||
DebugCommand::SetBreakpoint { pc } => {
|
DebugCommand::SetBreakpoint { pc } => {
|
||||||
firmware.vm.insert_breakpoint(pc);
|
let _ = firmware.os.vm().insert_active_breakpoint(pc);
|
||||||
}
|
}
|
||||||
DebugCommand::ListBreakpoints => {
|
DebugCommand::ListBreakpoints => {
|
||||||
let pcs = firmware.vm.breakpoints_list();
|
let pcs = firmware.os.vm().active_breakpoints_list();
|
||||||
self.send_response(DebugResponse::Breakpoints { pcs });
|
self.send_response(DebugResponse::Breakpoints { pcs });
|
||||||
}
|
}
|
||||||
DebugCommand::ClearBreakpoint { pc } => {
|
DebugCommand::ClearBreakpoint { pc } => {
|
||||||
firmware.vm.remove_breakpoint(pc);
|
let _ = firmware.os.vm().remove_active_breakpoint(pc);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn handshake_cartridge(&self, firmware: &mut Firmware) -> HandshakeCartridge {
|
||||||
|
let app_id = firmware.os.vm().current_app_id();
|
||||||
|
if app_id != 0 {
|
||||||
|
return HandshakeCartridge {
|
||||||
|
app_id,
|
||||||
|
title: firmware.os.vm().current_cartridge_title(),
|
||||||
|
app_version: firmware.os.vm().current_cartridge_app_version(),
|
||||||
|
app_mode: firmware.os.vm().current_cartridge_app_mode(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
self.debug_cartridge.clone().unwrap_or_else(|| HandshakeCartridge {
|
||||||
|
app_id,
|
||||||
|
title: firmware.os.vm().current_cartridge_title(),
|
||||||
|
app_version: firmware.os.vm().current_cartridge_app_version(),
|
||||||
|
app_mode: firmware.os.vm().current_cartridge_app_mode(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) fn cert_event_from_snapshot(
|
pub(crate) fn cert_event_from_snapshot(
|
||||||
tag: u16,
|
tag: u16,
|
||||||
telemetry: TelemetryFrame,
|
telemetry: TelemetryFrame,
|
||||||
@@ -315,7 +337,7 @@ impl HostDebugger {
|
|||||||
// Map specific internal log tags to protocol events.
|
// Map specific internal log tags to protocol events.
|
||||||
if event.tag == 0xDEB1 {
|
if event.tag == 0xDEB1 {
|
||||||
self.send_event(DebugEvent::BreakpointHit {
|
self.send_event(DebugEvent::BreakpointHit {
|
||||||
pc: firmware.vm.pc(),
|
pc: firmware.os.vm().active_pc().unwrap_or(0),
|
||||||
frame_index: firmware.os.vm().logical_frame_index(),
|
frame_index: firmware.os.vm().logical_frame_index(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -409,6 +431,52 @@ mod tests {
|
|||||||
assert!(firmware.os.vm().debug_step_requested());
|
assert!(firmware.os.vm().debug_step_requested());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn breakpoint_commands_mutate_active_vm_session() {
|
||||||
|
let mut debugger = HostDebugger::new();
|
||||||
|
let mut firmware = Firmware::new(None);
|
||||||
|
let mut platform = TestPlatform::new();
|
||||||
|
let task_id = firmware
|
||||||
|
.os
|
||||||
|
.sessions()
|
||||||
|
.try_create_vm_game_task(42, "Sector Crawl")
|
||||||
|
.expect("debugger test should create a game session");
|
||||||
|
|
||||||
|
debugger.handle_command(
|
||||||
|
DebugCommand::SetBreakpoint { pc: 123 },
|
||||||
|
&mut firmware,
|
||||||
|
&mut platform,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
firmware
|
||||||
|
.os
|
||||||
|
.sessions()
|
||||||
|
.vm_session_for_task(task_id)
|
||||||
|
.expect("game VM session should exist")
|
||||||
|
.vm
|
||||||
|
.breakpoints_list(),
|
||||||
|
vec![123]
|
||||||
|
);
|
||||||
|
|
||||||
|
debugger.handle_command(
|
||||||
|
DebugCommand::ClearBreakpoint { pc: 123 },
|
||||||
|
&mut firmware,
|
||||||
|
&mut platform,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
firmware
|
||||||
|
.os
|
||||||
|
.sessions()
|
||||||
|
.vm_session_for_task(task_id)
|
||||||
|
.expect("game VM session should exist")
|
||||||
|
.vm
|
||||||
|
.breakpoints_list()
|
||||||
|
.is_empty()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn handle_command_start_leaves_waiting_for_start_mode() {
|
fn handle_command_start_leaves_waiting_for_start_mode() {
|
||||||
let mut debugger = HostDebugger::new();
|
let mut debugger = HostDebugger::new();
|
||||||
|
|||||||
@@ -43,9 +43,27 @@ impl FbViewport {
|
|||||||
|
|
||||||
pub struct HostInputHandler {
|
pub struct HostInputHandler {
|
||||||
pub signals: InputSignals,
|
pub signals: InputSignals,
|
||||||
|
system_controls: HostSystemControls,
|
||||||
display_size: (usize, usize),
|
display_size: (usize, usize),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct HostSystemControls {
|
||||||
|
home_requested: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HostSystemControls {
|
||||||
|
pub fn request_home(&mut self) {
|
||||||
|
self.home_requested = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn take_home_requested(&mut self) -> bool {
|
||||||
|
let requested = self.home_requested;
|
||||||
|
self.home_requested = false;
|
||||||
|
requested
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl Default for HostInputHandler {
|
impl Default for HostInputHandler {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self::new((480, 270))
|
Self::new((480, 270))
|
||||||
@@ -54,35 +72,51 @@ impl Default for HostInputHandler {
|
|||||||
|
|
||||||
impl HostInputHandler {
|
impl HostInputHandler {
|
||||||
pub fn new(display_size: (usize, usize)) -> Self {
|
pub fn new(display_size: (usize, usize)) -> Self {
|
||||||
Self { signals: InputSignals::default(), display_size }
|
Self {
|
||||||
|
signals: InputSignals::default(),
|
||||||
|
system_controls: HostSystemControls::default(),
|
||||||
|
display_size,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn take_home_requested(&mut self) -> bool {
|
||||||
|
self.system_controls.take_home_requested()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clear_guest_signals(&mut self) {
|
||||||
|
self.signals = InputSignals::default();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn handle_key_code(&mut self, code: KeyCode, state: ElementState) {
|
||||||
|
let is_down = state == ElementState::Pressed;
|
||||||
|
|
||||||
|
match code {
|
||||||
|
KeyCode::Escape | KeyCode::Home if is_down => self.system_controls.request_home(),
|
||||||
|
|
||||||
|
KeyCode::ArrowUp => self.signals.up_signal = is_down,
|
||||||
|
KeyCode::ArrowDown => self.signals.down_signal = is_down,
|
||||||
|
KeyCode::ArrowLeft => self.signals.left_signal = is_down,
|
||||||
|
KeyCode::ArrowRight => self.signals.right_signal = is_down,
|
||||||
|
|
||||||
|
KeyCode::KeyA => self.signals.a_signal = is_down,
|
||||||
|
KeyCode::KeyD => self.signals.b_signal = is_down,
|
||||||
|
KeyCode::KeyW => self.signals.x_signal = is_down,
|
||||||
|
KeyCode::KeyS => self.signals.y_signal = is_down,
|
||||||
|
KeyCode::KeyQ => self.signals.l_signal = is_down,
|
||||||
|
KeyCode::KeyE => self.signals.r_signal = is_down,
|
||||||
|
|
||||||
|
KeyCode::KeyZ => self.signals.start_signal = is_down,
|
||||||
|
KeyCode::ShiftLeft | KeyCode::ShiftRight => self.signals.select_signal = is_down,
|
||||||
|
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn handle_event(&mut self, event: &WindowEvent, window: &Window) {
|
pub fn handle_event(&mut self, event: &WindowEvent, window: &Window) {
|
||||||
match event {
|
match event {
|
||||||
WindowEvent::KeyboardInput { event, .. } => {
|
WindowEvent::KeyboardInput { event, .. } => {
|
||||||
if let PhysicalKey::Code(code) = event.physical_key {
|
if let PhysicalKey::Code(code) = event.physical_key {
|
||||||
let is_down = event.state == ElementState::Pressed;
|
self.handle_key_code(code, event.state);
|
||||||
|
|
||||||
match code {
|
|
||||||
KeyCode::ArrowUp => self.signals.up_signal = is_down,
|
|
||||||
KeyCode::ArrowDown => self.signals.down_signal = is_down,
|
|
||||||
KeyCode::ArrowLeft => self.signals.left_signal = is_down,
|
|
||||||
KeyCode::ArrowRight => self.signals.right_signal = is_down,
|
|
||||||
|
|
||||||
KeyCode::KeyA => self.signals.a_signal = is_down,
|
|
||||||
KeyCode::KeyD => self.signals.b_signal = is_down,
|
|
||||||
KeyCode::KeyW => self.signals.x_signal = is_down,
|
|
||||||
KeyCode::KeyS => self.signals.y_signal = is_down,
|
|
||||||
KeyCode::KeyQ => self.signals.l_signal = is_down,
|
|
||||||
KeyCode::KeyE => self.signals.r_signal = is_down,
|
|
||||||
|
|
||||||
KeyCode::KeyZ => self.signals.start_signal = is_down,
|
|
||||||
KeyCode::ShiftLeft | KeyCode::ShiftRight => {
|
|
||||||
self.signals.select_signal = is_down
|
|
||||||
}
|
|
||||||
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,3 +168,81 @@ impl HostInputHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn assert_no_pad_signal(signals: InputSignals) {
|
||||||
|
assert!(!signals.up_signal);
|
||||||
|
assert!(!signals.down_signal);
|
||||||
|
assert!(!signals.left_signal);
|
||||||
|
assert!(!signals.right_signal);
|
||||||
|
assert!(!signals.a_signal);
|
||||||
|
assert!(!signals.b_signal);
|
||||||
|
assert!(!signals.x_signal);
|
||||||
|
assert!(!signals.y_signal);
|
||||||
|
assert!(!signals.l_signal);
|
||||||
|
assert!(!signals.r_signal);
|
||||||
|
assert!(!signals.start_signal);
|
||||||
|
assert!(!signals.select_signal);
|
||||||
|
assert!(!signals.f_signal);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn escape_requests_home_without_mutating_guest_pad() {
|
||||||
|
let mut input = HostInputHandler::default();
|
||||||
|
|
||||||
|
input.handle_key_code(KeyCode::Escape, ElementState::Pressed);
|
||||||
|
|
||||||
|
assert!(input.take_home_requested());
|
||||||
|
assert!(!input.take_home_requested());
|
||||||
|
assert_no_pad_signal(input.signals);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn physical_home_requests_home_without_mutating_guest_pad() {
|
||||||
|
let mut input = HostInputHandler::default();
|
||||||
|
|
||||||
|
input.handle_key_code(KeyCode::Home, ElementState::Pressed);
|
||||||
|
|
||||||
|
assert!(input.take_home_requested());
|
||||||
|
assert_no_pad_signal(input.signals);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn home_release_does_not_emit_a_new_home_request() {
|
||||||
|
let mut input = HostInputHandler::default();
|
||||||
|
|
||||||
|
input.handle_key_code(KeyCode::Home, ElementState::Released);
|
||||||
|
|
||||||
|
assert!(!input.take_home_requested());
|
||||||
|
assert_no_pad_signal(input.signals);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn existing_keyboard_pad_mapping_is_preserved() {
|
||||||
|
let mut input = HostInputHandler::default();
|
||||||
|
|
||||||
|
input.handle_key_code(KeyCode::KeyZ, ElementState::Pressed);
|
||||||
|
input.handle_key_code(KeyCode::ShiftLeft, ElementState::Pressed);
|
||||||
|
input.handle_key_code(KeyCode::ArrowUp, ElementState::Pressed);
|
||||||
|
|
||||||
|
assert!(input.signals.start_signal);
|
||||||
|
assert!(input.signals.select_signal);
|
||||||
|
assert!(input.signals.up_signal);
|
||||||
|
assert!(!input.take_home_requested());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn clearing_guest_signals_preserves_system_home_control() {
|
||||||
|
let mut input = HostInputHandler::default();
|
||||||
|
|
||||||
|
input.handle_key_code(KeyCode::ArrowUp, ElementState::Pressed);
|
||||||
|
input.handle_key_code(KeyCode::Escape, ElementState::Pressed);
|
||||||
|
input.clear_guest_signals();
|
||||||
|
|
||||||
|
assert_no_pad_signal(input.signals);
|
||||||
|
assert!(input.take_home_requested());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -10,8 +10,8 @@ use pixels::{Pixels, PixelsBuilder, SurfaceTexture};
|
|||||||
use prometeu_drivers::hardware::Hardware;
|
use prometeu_drivers::hardware::Hardware;
|
||||||
use prometeu_drivers::{AudioCommand, LocalFramebufferRenderBackend, MemoryBanks};
|
use prometeu_drivers::{AudioCommand, LocalFramebufferRenderBackend, MemoryBanks};
|
||||||
use prometeu_firmware::{BootTarget, Firmware, FirmwareState};
|
use prometeu_firmware::{BootTarget, Firmware, FirmwareState};
|
||||||
use prometeu_hal::RuntimePlatform;
|
|
||||||
use prometeu_hal::telemetry::CertificationConfig;
|
use prometeu_hal::telemetry::CertificationConfig;
|
||||||
|
use prometeu_hal::{OwnedRgba8888Frame, RenderOwnership, RuntimePlatform};
|
||||||
use prometeu_system::{LatestRenderFrameStore, RenderWorkerConfig, discover_games_root};
|
use prometeu_system::{LatestRenderFrameStore, RenderWorkerConfig, discover_games_root};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
@@ -26,16 +26,22 @@ const IDLE_HOST_POLL_DT: Duration = Duration::from_millis(100);
|
|||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
struct PresentationState {
|
struct PresentationState {
|
||||||
latest_published_frame: u64,
|
latest_published_frame: Option<PresentationFrameMarker>,
|
||||||
last_presented_frame: Option<u64>,
|
last_presented_frame: Option<PresentationFrameMarker>,
|
||||||
host_invalidated: bool,
|
host_invalidated: bool,
|
||||||
redraw_requested: bool,
|
redraw_requested: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
struct PresentationFrameMarker {
|
||||||
|
ownership: RenderOwnership,
|
||||||
|
frame_id: u64,
|
||||||
|
}
|
||||||
|
|
||||||
impl Default for PresentationState {
|
impl Default for PresentationState {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
latest_published_frame: 0,
|
latest_published_frame: None,
|
||||||
last_presented_frame: None,
|
last_presented_frame: None,
|
||||||
host_invalidated: true,
|
host_invalidated: true,
|
||||||
redraw_requested: false,
|
redraw_requested: false,
|
||||||
@@ -44,9 +50,10 @@ impl Default for PresentationState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl PresentationState {
|
impl PresentationState {
|
||||||
fn note_published_frame(&mut self, frame_index: u64) {
|
fn note_published_frame(&mut self, ownership: RenderOwnership, frame_id: u64) {
|
||||||
if frame_index > self.latest_published_frame {
|
let marker = PresentationFrameMarker { ownership, frame_id };
|
||||||
self.latest_published_frame = frame_index;
|
if self.latest_published_frame != Some(marker) {
|
||||||
|
self.latest_published_frame = Some(marker);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,7 +62,7 @@ impl PresentationState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn needs_redraw(&self) -> bool {
|
fn needs_redraw(&self) -> bool {
|
||||||
self.host_invalidated || self.last_presented_frame != Some(self.latest_published_frame)
|
self.host_invalidated || self.last_presented_frame != self.latest_published_frame
|
||||||
}
|
}
|
||||||
|
|
||||||
fn should_request_redraw(&mut self) -> bool {
|
fn should_request_redraw(&mut self) -> bool {
|
||||||
@@ -70,7 +77,7 @@ impl PresentationState {
|
|||||||
fn mark_presented(&mut self) {
|
fn mark_presented(&mut self) {
|
||||||
self.redraw_requested = false;
|
self.redraw_requested = false;
|
||||||
self.host_invalidated = false;
|
self.host_invalidated = false;
|
||||||
self.last_presented_frame = Some(self.latest_published_frame);
|
self.last_presented_frame = self.latest_published_frame;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -88,8 +95,12 @@ fn desired_control_flow(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn should_present_worker_frame(state: &FirmwareState) -> bool {
|
fn should_present_worker_frame(
|
||||||
matches!(state, FirmwareState::GameRunning(_))
|
state: &FirmwareState,
|
||||||
|
frame: &OwnedRgba8888Frame,
|
||||||
|
active_ownership: RenderOwnership,
|
||||||
|
) -> bool {
|
||||||
|
matches!(state, FirmwareState::GameRunning(_)) && frame.ownership == active_ownership
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The Desktop implementation of the PROMETEU Runtime.
|
/// The Desktop implementation of the PROMETEU Runtime.
|
||||||
@@ -312,8 +323,13 @@ impl ApplicationHandler for HostRunner {
|
|||||||
{
|
{
|
||||||
let frame = pixels.frame_mut();
|
let frame = pixels.frame_mut();
|
||||||
|
|
||||||
if should_present_worker_frame(&self.firmware.state)
|
let active_ownership = self.firmware.os.vm().active_render_ownership();
|
||||||
&& let Some(worker_frame) = self.render_frame_store.latest_frame()
|
if let Some(worker_frame) = self.render_frame_store.latest_frame()
|
||||||
|
&& should_present_worker_frame(
|
||||||
|
&self.firmware.state,
|
||||||
|
&worker_frame,
|
||||||
|
active_ownership,
|
||||||
|
)
|
||||||
{
|
{
|
||||||
self.firmware
|
self.firmware
|
||||||
.os
|
.os
|
||||||
@@ -372,6 +388,13 @@ impl ApplicationHandler for HostRunner {
|
|||||||
self.firmware.os.fs().mount(Box::new(backend));
|
self.firmware.os.fs().mount(Box::new(backend));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if self.input.take_home_requested() {
|
||||||
|
self.input.clear_guest_signals();
|
||||||
|
self.firmware.request_home_from_host();
|
||||||
|
self.invalidate_host_surface();
|
||||||
|
self.request_redraw_if_needed();
|
||||||
|
}
|
||||||
|
|
||||||
// 3. Timing Management (The heart of determinism).
|
// 3. Timing Management (The heart of determinism).
|
||||||
// We measure the elapsed time since the last iteration and add it to an
|
// We measure the elapsed time since the last iteration and add it to an
|
||||||
// accumulator. We then execute exactly as many 60Hz slices as the
|
// accumulator. We then execute exactly as many 60Hz slices as the
|
||||||
@@ -399,7 +422,10 @@ impl ApplicationHandler for HostRunner {
|
|||||||
// Sync pause state with audio.
|
// Sync pause state with audio.
|
||||||
// We do this AFTER firmware.tick to avoid MasterPause/Resume commands
|
// We do this AFTER firmware.tick to avoid MasterPause/Resume commands
|
||||||
// being cleared by the OS if a new logical frame starts in this tick.
|
// being cleared by the OS if a new logical frame starts in this tick.
|
||||||
let is_paused = self.firmware.os.vm().paused() || self.debugger.waiting_for_start;
|
let lifecycle_audio_paused = self.firmware.game_lifecycle_audio_paused();
|
||||||
|
let is_paused = lifecycle_audio_paused
|
||||||
|
|| self.firmware.os.vm().paused()
|
||||||
|
|| self.debugger.waiting_for_start;
|
||||||
if is_paused != self.last_paused_state {
|
if is_paused != self.last_paused_state {
|
||||||
self.last_paused_state = is_paused;
|
self.last_paused_state = is_paused;
|
||||||
let cmd =
|
let cmd =
|
||||||
@@ -414,12 +440,15 @@ impl ApplicationHandler for HostRunner {
|
|||||||
self.stats.record_frame();
|
self.stats.record_frame();
|
||||||
}
|
}
|
||||||
|
|
||||||
if should_present_worker_frame(&self.firmware.state)
|
let active_ownership = self.firmware.os.vm().active_render_ownership();
|
||||||
&& let Some(worker_frame) = self.render_frame_store.latest_frame()
|
if let Some(worker_frame) = self.render_frame_store.latest_frame()
|
||||||
|
&& should_present_worker_frame(&self.firmware.state, &worker_frame, active_ownership)
|
||||||
{
|
{
|
||||||
self.presentation.note_published_frame(worker_frame.frame_id.get());
|
self.presentation
|
||||||
|
.note_published_frame(worker_frame.ownership, worker_frame.frame_id.get());
|
||||||
} else {
|
} else {
|
||||||
self.presentation.note_published_frame(self.firmware.os.frame_index());
|
self.presentation
|
||||||
|
.note_published_frame(active_ownership, self.firmware.os.frame_index());
|
||||||
}
|
}
|
||||||
|
|
||||||
if was_debugger_connected != self.debugger.stream.is_some()
|
if was_debugger_connected != self.debugger.stream.is_some()
|
||||||
@@ -485,14 +514,37 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn presentation_state_requests_redraw_for_new_frame_publication() {
|
fn presentation_state_requests_redraw_for_new_frame_publication() {
|
||||||
|
let ownership = RenderOwnership::new(1, AppMode::Game, 1);
|
||||||
let mut state = PresentationState::default();
|
let mut state = PresentationState::default();
|
||||||
state.mark_presented();
|
state.mark_presented();
|
||||||
|
|
||||||
state.note_published_frame(1);
|
state.note_published_frame(ownership, 1);
|
||||||
|
|
||||||
assert!(state.should_request_redraw());
|
assert!(state.should_request_redraw());
|
||||||
state.mark_presented();
|
state.mark_presented();
|
||||||
assert_eq!(state.last_presented_frame, Some(1));
|
assert_eq!(
|
||||||
|
state.last_presented_frame,
|
||||||
|
Some(PresentationFrameMarker { ownership, frame_id: 1 })
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn presentation_state_requests_redraw_when_ownership_changes_with_lower_frame_id() {
|
||||||
|
let first = RenderOwnership::new(3, AppMode::Game, 1);
|
||||||
|
let next = RenderOwnership::new(4, AppMode::Game, 2);
|
||||||
|
let mut state = PresentationState::default();
|
||||||
|
|
||||||
|
state.note_published_frame(first, 120);
|
||||||
|
state.mark_presented();
|
||||||
|
|
||||||
|
state.note_published_frame(next, 0);
|
||||||
|
|
||||||
|
assert!(state.should_request_redraw());
|
||||||
|
state.mark_presented();
|
||||||
|
assert_eq!(
|
||||||
|
state.last_presented_frame,
|
||||||
|
Some(PresentationFrameMarker { ownership: next, frame_id: 0 })
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -536,14 +588,39 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn worker_frame_presentation_is_game_only() {
|
fn worker_frame_presentation_requires_game_state_and_current_ownership() {
|
||||||
assert!(should_present_worker_frame(&FirmwareState::GameRunning(GameRunningStep::new(
|
let active = RenderOwnership::new(3, AppMode::Game, 1);
|
||||||
TaskId(1),
|
let current = OwnedRgba8888Frame::packed(FrameId::new(9), active, 1, 1, vec![0xFF00FFFF])
|
||||||
))));
|
.expect("test frame");
|
||||||
assert!(!should_present_worker_frame(&FirmwareState::ShellRunning(ShellRunningStep::new(
|
let stale = OwnedRgba8888Frame::packed(
|
||||||
TaskId(2)
|
FrameId::new(8),
|
||||||
),)));
|
RenderOwnership::new(2, AppMode::Game, 1),
|
||||||
assert!(!should_present_worker_frame(&FirmwareState::HubHome(HubHomeStep)));
|
1,
|
||||||
|
1,
|
||||||
|
vec![0xFF00FFFF],
|
||||||
|
)
|
||||||
|
.expect("test frame");
|
||||||
|
|
||||||
|
assert!(should_present_worker_frame(
|
||||||
|
&FirmwareState::GameRunning(GameRunningStep::new(TaskId(1))),
|
||||||
|
¤t,
|
||||||
|
active,
|
||||||
|
));
|
||||||
|
assert!(!should_present_worker_frame(
|
||||||
|
&FirmwareState::GameRunning(GameRunningStep::new(TaskId(1),)),
|
||||||
|
&stale,
|
||||||
|
active,
|
||||||
|
));
|
||||||
|
assert!(!should_present_worker_frame(
|
||||||
|
&FirmwareState::ShellRunning(ShellRunningStep::new(TaskId(2))),
|
||||||
|
¤t,
|
||||||
|
active,
|
||||||
|
));
|
||||||
|
assert!(!should_present_worker_frame(
|
||||||
|
&FirmwareState::HubHome(HubHomeStep),
|
||||||
|
¤t,
|
||||||
|
active,
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -563,11 +640,14 @@ mod tests {
|
|||||||
let mut presentation = PresentationState::default();
|
let mut presentation = PresentationState::default();
|
||||||
presentation.mark_presented();
|
presentation.mark_presented();
|
||||||
let published = store.latest_frame().expect("published frame");
|
let published = store.latest_frame().expect("published frame");
|
||||||
presentation.note_published_frame(published.frame_id.get());
|
presentation.note_published_frame(published.ownership, published.frame_id.get());
|
||||||
|
|
||||||
assert!(presentation.should_request_redraw());
|
assert!(presentation.should_request_redraw());
|
||||||
presentation.mark_presented();
|
presentation.mark_presented();
|
||||||
assert_eq!(presentation.last_presented_frame, Some(9));
|
assert_eq!(
|
||||||
|
presentation.last_presented_frame,
|
||||||
|
Some(PresentationFrameMarker { ownership: published.ownership, frame_id: 9 })
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
[package]
|
||||||
|
name = "pbxgen-dummy-boy"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
anyhow = "1"
|
||||||
|
prometeu-bytecode = { path = "../../console/prometeu-bytecode" }
|
||||||
|
prometeu-hal = { path = "../../console/prometeu-hal" }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
serde_json = "1"
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
use anyhow::Result;
|
||||||
|
use prometeu_bytecode::assembler::assemble;
|
||||||
|
use prometeu_bytecode::model::{BytecodeModule, DebugInfo, Export, FunctionMeta, SyscallDecl};
|
||||||
|
use prometeu_hal::color::Color;
|
||||||
|
use std::fs;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
const APP_ID: u32 = 2;
|
||||||
|
const TITLE: &str = "Dummy Boy";
|
||||||
|
const APP_VERSION: &str = "0.1.0";
|
||||||
|
|
||||||
|
fn asm(s: &str) -> Vec<u8> {
|
||||||
|
assemble(s).expect("assemble")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn generate() -> Result<()> {
|
||||||
|
let out_dir = cartridge_dir();
|
||||||
|
fs::create_dir_all(&out_dir)?;
|
||||||
|
fs::write(out_dir.join("program.pbx"), build_program())?;
|
||||||
|
fs::write(out_dir.join("manifest.json"), manifest_json())?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn build_program() -> Vec<u8> {
|
||||||
|
let mut rom = Vec::new();
|
||||||
|
|
||||||
|
rom.extend(asm("GET_GLOBAL 0\nPUSH_I32 1\nADD\nSET_GLOBAL 0"));
|
||||||
|
rom.extend(asm(&format!("PUSH_I64 {}\nHOSTCALL 0", Color::BLACK.raw())));
|
||||||
|
|
||||||
|
rom.extend(asm("GET_GLOBAL 0\nPUSH_I32 3\nMOD\nPUSH_I32 0\nEQ"));
|
||||||
|
let jump_to_green_case_offset = rom.len() + 2;
|
||||||
|
rom.extend(asm("JMP_IF_FALSE 0"));
|
||||||
|
rom.extend(asm(&format!("PUSH_I64 {}\nSET_LOCAL 0", Color::RED.raw())));
|
||||||
|
let jump_to_draw_after_red_offset = rom.len() + 2;
|
||||||
|
rom.extend(asm("JMP 0"));
|
||||||
|
|
||||||
|
let green_case = rom.len() as u32;
|
||||||
|
rom.extend(asm("GET_GLOBAL 0\nPUSH_I32 3\nMOD\nPUSH_I32 1\nEQ"));
|
||||||
|
let jump_to_blue_case_offset = rom.len() + 2;
|
||||||
|
rom.extend(asm("JMP_IF_FALSE 0"));
|
||||||
|
rom.extend(asm(&format!("PUSH_I64 {}\nSET_LOCAL 0", Color::GREEN.raw())));
|
||||||
|
let jump_to_draw_after_green_offset = rom.len() + 2;
|
||||||
|
rom.extend(asm("JMP 0"));
|
||||||
|
|
||||||
|
let blue_case = rom.len() as u32;
|
||||||
|
rom.extend(asm(&format!("PUSH_I64 {}\nSET_LOCAL 0", Color::BLUE.raw())));
|
||||||
|
|
||||||
|
let draw = rom.len() as u32;
|
||||||
|
rom.extend(asm(&format!(
|
||||||
|
"PUSH_I32 180\n\
|
||||||
|
PUSH_I32 75\n\
|
||||||
|
PUSH_I32 120\n\
|
||||||
|
PUSH_I32 120\n\
|
||||||
|
PUSH_I64 {}\n\
|
||||||
|
GET_LOCAL 0\n\
|
||||||
|
HOSTCALL 1\n\
|
||||||
|
FRAME_SYNC\n\
|
||||||
|
RET",
|
||||||
|
Color::WHITE.raw()
|
||||||
|
)));
|
||||||
|
|
||||||
|
patch_jump(&mut rom, jump_to_green_case_offset, green_case);
|
||||||
|
patch_jump(&mut rom, jump_to_draw_after_red_offset, draw);
|
||||||
|
patch_jump(&mut rom, jump_to_blue_case_offset, blue_case);
|
||||||
|
patch_jump(&mut rom, jump_to_draw_after_green_offset, draw);
|
||||||
|
|
||||||
|
BytecodeModule {
|
||||||
|
version: 0,
|
||||||
|
const_pool: vec![],
|
||||||
|
functions: vec![FunctionMeta {
|
||||||
|
code_offset: 0,
|
||||||
|
code_len: rom.len() as u32,
|
||||||
|
param_slots: 0,
|
||||||
|
local_slots: 1,
|
||||||
|
return_slots: 0,
|
||||||
|
max_stack_slots: 8,
|
||||||
|
}],
|
||||||
|
code: rom,
|
||||||
|
debug_info: Some(DebugInfo {
|
||||||
|
pc_to_span: vec![],
|
||||||
|
function_names: vec![(0, "main".into())],
|
||||||
|
}),
|
||||||
|
exports: vec![Export { symbol: "main".into(), func_idx: 0 }],
|
||||||
|
syscalls: vec![
|
||||||
|
SyscallDecl {
|
||||||
|
module: "gfx2d".into(),
|
||||||
|
name: "clear".into(),
|
||||||
|
version: 1,
|
||||||
|
arg_slots: 1,
|
||||||
|
ret_slots: 0,
|
||||||
|
},
|
||||||
|
SyscallDecl {
|
||||||
|
module: "gfx2d".into(),
|
||||||
|
name: "draw_square".into(),
|
||||||
|
version: 1,
|
||||||
|
arg_slots: 6,
|
||||||
|
ret_slots: 0,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
.serialize()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn manifest_json() -> Vec<u8> {
|
||||||
|
format!(
|
||||||
|
"{{\n \"magic\": \"PMTU\",\n \"cartridge_version\": 1,\n \"app_id\": {APP_ID},\n \"title\": \"{TITLE}\",\n \"app_version\": \"{APP_VERSION}\",\n \"app_mode\": \"Game\",\n \"capabilities\": [\"gfx2d\"]\n}}\n"
|
||||||
|
)
|
||||||
|
.into_bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cartridge_dir() -> PathBuf {
|
||||||
|
let mut out_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||||
|
out_dir.pop();
|
||||||
|
out_dir.pop();
|
||||||
|
out_dir.pop();
|
||||||
|
out_dir.push("test-cartridges");
|
||||||
|
out_dir.push("dummy-boy");
|
||||||
|
out_dir
|
||||||
|
}
|
||||||
|
|
||||||
|
fn patch_jump(buf: &mut [u8], imm_offset: usize, target: u32) {
|
||||||
|
buf[imm_offset..imm_offset + 4].copy_from_slice(&target.to_le_bytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn generated_program_is_pbx_module_with_expected_syscalls() {
|
||||||
|
let bytes = build_program();
|
||||||
|
|
||||||
|
assert!(bytes.starts_with(&prometeu_bytecode::PBX_MAGIC));
|
||||||
|
assert!(bytes.len() > 64);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn manifest_declares_distinct_game_identity() {
|
||||||
|
let manifest: serde_json::Value =
|
||||||
|
serde_json::from_slice(&manifest_json()).expect("manifest should parse");
|
||||||
|
|
||||||
|
assert_eq!(manifest["app_id"], APP_ID);
|
||||||
|
assert_eq!(manifest["title"], TITLE);
|
||||||
|
assert_eq!(manifest["app_mode"], "Game");
|
||||||
|
assert_eq!(manifest["capabilities"], serde_json::json!(["gfx2d"]));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
use anyhow::Result;
|
||||||
|
|
||||||
|
fn main() -> Result<()> {
|
||||||
|
pbxgen_dummy_boy::generate()
|
||||||
|
}
|
||||||
@@ -14,7 +14,7 @@ use prometeu_hal::cartridge::{
|
|||||||
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::{
|
use prometeu_hal::glyph_bank::{
|
||||||
TileSize, GLYPH_BANK_COLORS_PER_PALETTE, GLYPH_BANK_PALETTE_COUNT_V1,
|
TileSize, GLYPH_BANK_COLORS_PER_PALETTE, GLYPH_BANK_MAX_PALETTE_COUNT_V1,
|
||||||
};
|
};
|
||||||
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};
|
||||||
@@ -275,15 +275,15 @@ fn build_glyph_asset() -> (AssetEntry, Vec<u8>) {
|
|||||||
bank_type: BankType::GLYPH,
|
bank_type: BankType::GLYPH,
|
||||||
offset: 0,
|
offset: 0,
|
||||||
size: payload.len() as u64,
|
size: payload.len() as u64,
|
||||||
decoded_size: (8 * 8 + GLYPH_BANK_PALETTE_COUNT_V1 * GLYPH_BANK_COLORS_PER_PALETTE * 4)
|
decoded_size: (8 * 8 + GLYPH_BANK_MAX_PALETTE_COUNT_V1 * GLYPH_BANK_COLORS_PER_PALETTE * 4)
|
||||||
as u64,
|
as u64,
|
||||||
codec: AssetCodec::None,
|
codec: AssetCodec::None,
|
||||||
metadata: serde_json::json!({
|
metadata: serde_json::json!({
|
||||||
"tile_size": 8,
|
"tile_size": 8,
|
||||||
"width": 8,
|
"width": 8,
|
||||||
"height": 8,
|
"height": 8,
|
||||||
"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
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -292,8 +292,8 @@ fn build_glyph_asset() -> (AssetEntry, Vec<u8>) {
|
|||||||
|
|
||||||
fn build_palette_bytes() -> Vec<u8> {
|
fn build_palette_bytes() -> Vec<u8> {
|
||||||
let mut bytes =
|
let mut bytes =
|
||||||
Vec::with_capacity(GLYPH_BANK_PALETTE_COUNT_V1 * GLYPH_BANK_COLORS_PER_PALETTE * 4);
|
Vec::with_capacity(GLYPH_BANK_MAX_PALETTE_COUNT_V1 * GLYPH_BANK_COLORS_PER_PALETTE * 4);
|
||||||
for palette_id in 0..GLYPH_BANK_PALETTE_COUNT_V1 {
|
for palette_id in 0..GLYPH_BANK_MAX_PALETTE_COUNT_V1 {
|
||||||
for color_index in 0..GLYPH_BANK_COLORS_PER_PALETTE {
|
for color_index in 0..GLYPH_BANK_COLORS_PER_PALETTE {
|
||||||
let color = if color_index == 1 { stress_color(palette_id) } else { Color::BLACK };
|
let color = if color_index == 1 { stress_color(palette_id) } else { Color::BLACK };
|
||||||
bytes.extend_from_slice(&color.raw().to_be_bytes());
|
bytes.extend_from_slice(&color.raw().to_be_bytes());
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
{"type":"meta","next_id":{"DSC":44,"AGD":46,"DEC":37,"PLN":136,"LSN":51,"CLSN":1}}
|
{"type":"meta","next_id":{"DSC":49,"AGD":52,"DEC":43,"PLN":174,"LSN":57,"CLSN":1}}
|
||||||
{"type":"discussion","id":"DSC-0043","status":"open","ticket":"system-os-cartridge-switch-orchestrator","title":"SystemOS Cartridge Switch Orchestrator","created_at":"2026-07-03","updated_at":"2026-07-03","tags":["runtime","os","lifecycle","game","cartridge","architecture"],"agendas":[{"id":"AGD-0044","file":"AGD-0044-systemos-cartridge-switch-orchestrator.md","status":"open","created_at":"2026-07-03","updated_at":"2026-07-03"}],"decisions":[],"plans":[],"lessons":[]}
|
{"type":"discussion","id":"DSC-0044","status":"done","ticket":"hub-suspended-game-kill-affordance","title":"Hub Suspended Game Kill Affordance","created_at":"2026-07-05","updated_at":"2026-07-05","tags":["hub","lifecycle","game","ui"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0054","file":"discussion/lessons/DSC-0044-hub-suspended-game-kill-affordance/LSN-0054-manual-hub-kill-must-share-game-termination-cleanup.md","status":"done","created_at":"2026-07-05","updated_at":"2026-07-05"}]}
|
||||||
|
{"type":"discussion","id":"DSC-0043","status":"done","ticket":"system-os-cartridge-switch-orchestrator","title":"SystemOS Cartridge Switch Orchestrator","created_at":"2026-07-03","updated_at":"2026-07-05","tags":["runtime","os","lifecycle","game","cartridge","architecture"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0053","file":"discussion/lessons/DSC-0043-system-os-cartridge-switch-orchestrator/LSN-0053-game-switching-is-lifecycle-replacement-not-loader-work.md","status":"done","created_at":"2026-07-05","updated_at":"2026-07-05"}]}
|
||||||
{"type":"discussion","id":"DSC-0039","status":"abandoned","ticket":"render-pipeline-family-and-future-3d","title":"Render Pipeline Family and Future 3D","created_at":"2026-06-04","updated_at":"2026-06-04","tags":["gfx","renderer","runtime","architecture","pipeline"],"agendas":[{"id":"AGD-0039","file":"AGD-0039-render-pipeline-family-and-future-3d.md","status":"abandoned","created_at":"2026-06-04","updated_at":"2026-06-04","_override_reason":"User explicitly chose to close this agenda without a new decision because DSC-0038 already established enough architecture for future extension, and 3D is intentionally deferred."}],"decisions":[],"plans":[],"lessons":[],"_override_reason":"User explicitly chose to close this agenda without a new decision because DSC-0038 already established enough architecture for future extension, and 3D is intentionally deferred."}
|
{"type":"discussion","id":"DSC-0039","status":"abandoned","ticket":"render-pipeline-family-and-future-3d","title":"Render Pipeline Family and Future 3D","created_at":"2026-06-04","updated_at":"2026-06-04","tags":["gfx","renderer","runtime","architecture","pipeline"],"agendas":[{"id":"AGD-0039","file":"AGD-0039-render-pipeline-family-and-future-3d.md","status":"abandoned","created_at":"2026-06-04","updated_at":"2026-06-04","_override_reason":"User explicitly chose to close this agenda without a new decision because DSC-0038 already established enough architecture for future extension, and 3D is intentionally deferred."}],"decisions":[],"plans":[],"lessons":[],"_override_reason":"User explicitly chose to close this agenda without a new decision because DSC-0038 already established enough architecture for future extension, and 3D is intentionally deferred."}
|
||||||
{"type":"discussion","id":"DSC-0040","status":"done","ticket":"vm-render-parallel-execution-boundary","title":"VM and Render Parallel Execution Boundary","created_at":"2026-06-04","updated_at":"2026-06-06","tags":["runtime","renderer","vm","concurrency","architecture","perf"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0048","file":"discussion/lessons/DSC-0040-vm-render-parallel-execution-boundary/LSN-0048-render-workers-need-a-closed-packet-contract.md","status":"done","created_at":"2026-06-06","updated_at":"2026-06-06"}]}
|
{"type":"discussion","id":"DSC-0040","status":"done","ticket":"vm-render-parallel-execution-boundary","title":"VM and Render Parallel Execution Boundary","created_at":"2026-06-04","updated_at":"2026-06-06","tags":["runtime","renderer","vm","concurrency","architecture","perf"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0048","file":"discussion/lessons/DSC-0040-vm-render-parallel-execution-boundary/LSN-0048-render-workers-need-a-closed-packet-contract.md","status":"done","created_at":"2026-06-06","updated_at":"2026-06-06"}]}
|
||||||
{"type":"discussion","id":"DSC-0041","status":"open","ticket":"foreground-stack-game-pause-shell-vm-backed","title":"Foreground Stack, Game Pause, and VM-Backed Shell Coexistence","created_at":"2026-06-05","updated_at":"2026-06-05","tags":["runtime","os","lifecycle","shell","game","vm","foreground","architecture"],"agendas":[{"id":"AGD-0041","file":"AGD-0041-foreground-stack-game-pause-shell-vm-backed.md","status":"open","created_at":"2026-06-05","updated_at":"2026-06-05"}],"decisions":[],"plans":[],"lessons":[]}
|
{"type":"discussion","id":"DSC-0041","status":"done","ticket":"foreground-stack-game-pause-shell-vm-backed","title":"Foreground Stack, Game Pause, and VM-Backed Shell Coexistence","created_at":"2026-06-05","updated_at":"2026-07-05","tags":["runtime","os","lifecycle","shell","game","vm","foreground","architecture"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0052","file":"discussion/lessons/DSC-0041-foreground-stack-game-pause-shell-vm-backed/LSN-0052-foreground-ownership-and-vm-session-ownership-are-separate.md","status":"done","created_at":"2026-07-05","updated_at":"2026-07-05"}]}
|
||||||
{"type":"discussion","id":"DSC-0042","status":"done","ticket":"real-render-worker-establishment","title":"Real Render Worker Establishment","created_at":"2026-06-06","updated_at":"2026-06-20","tags":["runtime","renderer","worker","concurrency","host","hal","architecture"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0049","file":"discussion/lessons/DSC-0042-real-render-worker-establishment/LSN-0049-render-worker-publication-boundary.md","status":"done","created_at":"2026-06-20","updated_at":"2026-06-20"}]}
|
{"type":"discussion","id":"DSC-0042","status":"done","ticket":"real-render-worker-establishment","title":"Real Render Worker Establishment","created_at":"2026-06-06","updated_at":"2026-06-20","tags":["runtime","renderer","worker","concurrency","host","hal","architecture"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0049","file":"discussion/lessons/DSC-0042-real-render-worker-establishment/LSN-0049-render-worker-publication-boundary.md","status":"done","created_at":"2026-06-20","updated_at":"2026-06-20"}]}
|
||||||
{"type":"discussion","id":"DSC-0038","status":"done","ticket":"render-frame-packet-boundary","title":"Logical Render Pipelines and Command Packets","created_at":"2026-05-25","updated_at":"2026-06-04","tags":["gfx","renderer","runtime","frame-composer","architecture","ui","pipeline"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0047","file":"discussion/lessons/DSC-0038-render-frame-packet-boundary/LSN-0047-typed-render-submissions-preserve-domain-boundaries.md","status":"done","created_at":"2026-06-04","updated_at":"2026-06-04"}]}
|
{"type":"discussion","id":"DSC-0038","status":"done","ticket":"render-frame-packet-boundary","title":"Logical Render Pipelines and Command Packets","created_at":"2026-05-25","updated_at":"2026-06-04","tags":["gfx","renderer","runtime","frame-composer","architecture","ui","pipeline"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0047","file":"discussion/lessons/DSC-0038-render-frame-packet-boundary/LSN-0047-typed-render-submissions-preserve-domain-boundaries.md","status":"done","created_at":"2026-06-04","updated_at":"2026-06-04"}]}
|
||||||
{"type":"discussion","id":"DSC-0035","status":"done","ticket":"task-owned-shell-windows","title":"Agenda - Task-Owned Shell Windows","created_at":"2026-05-15","updated_at":"2026-05-15","tags":["runtime","os","task","window-manager","shell","lifecycle"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0044","file":"discussion/lessons/DSC-0035-task-owned-shell-windows/LSN-0044-task-window-liveness-belongs-to-the-task.md","status":"done","created_at":"2026-05-15","updated_at":"2026-05-15"}]}
|
{"type":"discussion","id":"DSC-0035","status":"done","ticket":"task-owned-shell-windows","title":"Agenda - Task-Owned Shell Windows","created_at":"2026-05-15","updated_at":"2026-05-15","tags":["runtime","os","task","window-manager","shell","lifecycle"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0044","file":"discussion/lessons/DSC-0035-task-owned-shell-windows/LSN-0044-task-window-liveness-belongs-to-the-task.md","status":"done","created_at":"2026-05-15","updated_at":"2026-05-15"}]}
|
||||||
@@ -14,10 +15,11 @@
|
|||||||
{"type":"discussion","id":"DSC-0001","status":"done","ticket":"legacy-runtime-learn-import","title":"Import legacy runtime learn into discussion lessons","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["migration","tech-debt"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0001","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0001-prometeu-learn-index.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0002","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0002-historical-asset-status-first-fault-and-return-contract.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0003","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0003-historical-audio-status-first-fault-and-return-contract.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0004","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0004-historical-cartridge-boot-protocol-and-manifest-authority.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0005","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0005-historical-game-memcard-slots-surface-and-semantics.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0006","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0006-historical-gfx-status-first-fault-and-return-contract.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0007","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0007-historical-retired-fault-and-input-decisions.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0008","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0008-historical-vm-core-and-assets.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0009","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0009-mental-model-asset-management.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0010","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0010-mental-model-audio.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0011","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0011-mental-model-gfx.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0012","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0012-mental-model-input.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0013","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0013-mental-model-observability-and-debugging.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0014","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0014-mental-model-portability-and-cross-platform.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0015","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0015-mental-model-save-memory-and-memcard.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0016","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0016-mental-model-status-first-and-fault-thinking.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0017","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0017-mental-model-time-and-cycles.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0018","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0018-mental-model-touch.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
|
{"type":"discussion","id":"DSC-0001","status":"done","ticket":"legacy-runtime-learn-import","title":"Import legacy runtime learn into discussion lessons","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["migration","tech-debt"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0001","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0001-prometeu-learn-index.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0002","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0002-historical-asset-status-first-fault-and-return-contract.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0003","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0003-historical-audio-status-first-fault-and-return-contract.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0004","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0004-historical-cartridge-boot-protocol-and-manifest-authority.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0005","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0005-historical-game-memcard-slots-surface-and-semantics.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0006","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0006-historical-gfx-status-first-fault-and-return-contract.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0007","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0007-historical-retired-fault-and-input-decisions.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0008","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0008-historical-vm-core-and-assets.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0009","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0009-mental-model-asset-management.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0010","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0010-mental-model-audio.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0011","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0011-mental-model-gfx.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0012","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0012-mental-model-input.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0013","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0013-mental-model-observability-and-debugging.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0014","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0014-mental-model-portability-and-cross-platform.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0015","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0015-mental-model-save-memory-and-memcard.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0016","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0016-mental-model-status-first-and-fault-thinking.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0017","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0017-mental-model-time-and-cycles.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0018","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0018-mental-model-touch.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
|
||||||
{"type":"discussion","id":"DSC-0002","status":"done","ticket":"runtime-edge-test-plan","title":"Agenda - Runtime Edge Test Plan","created_at":"2026-03-27","updated_at":"2026-04-21","tags":[],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0037","file":"discussion/lessons/DSC-0002-runtime-edge-test-plan/LSN-0037-domain-gates-must-be-owned-by-the-repository.md","status":"done","created_at":"2026-04-21","updated_at":"2026-04-21"}]}
|
{"type":"discussion","id":"DSC-0002","status":"done","ticket":"runtime-edge-test-plan","title":"Agenda - Runtime Edge Test Plan","created_at":"2026-03-27","updated_at":"2026-04-21","tags":[],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0037","file":"discussion/lessons/DSC-0002-runtime-edge-test-plan/LSN-0037-domain-gates-must-be-owned-by-the-repository.md","status":"done","created_at":"2026-04-21","updated_at":"2026-04-21"}]}
|
||||||
{"type":"discussion","id":"DSC-0003","status":"open","ticket":"packed-cartridge-loader-pmc","title":"Agenda - Packed Cartridge Loader PMC","created_at":"2026-03-27","updated_at":"2026-03-27","tags":[],"agendas":[{"id":"AGD-0002","file":"AGD-0002-packed-cartridge-loader-pmc.md","status":"open","created_at":"2026-03-27","updated_at":"2026-03-27"}],"decisions":[],"plans":[],"lessons":[]}
|
{"type":"discussion","id":"DSC-0003","status":"open","ticket":"packed-cartridge-loader-pmc","title":"Agenda - Packed Cartridge Loader PMC","created_at":"2026-03-27","updated_at":"2026-03-27","tags":[],"agendas":[{"id":"AGD-0002","file":"AGD-0002-packed-cartridge-loader-pmc.md","status":"open","created_at":"2026-03-27","updated_at":"2026-03-27"}],"decisions":[],"plans":[],"lessons":[]}
|
||||||
{"type":"discussion","id":"DSC-0004","status":"in_progress","ticket":"system-run-cart","title":"Agenda - System Run Cart","created_at":"2026-03-27","updated_at":"2026-07-03","tags":[],"agendas":[{"id":"AGD-0003","file":"AGD-0003-system-run-cart.md","status":"accepted","created_at":"2026-03-27","updated_at":"2026-07-03"},{"id":"AGD-0045","file":"AGD-0045-systemos-library-root-home-game-launch.md","status":"accepted","created_at":"2026-07-03","updated_at":"2026-07-03"}],"decisions":[{"id":"DEC-0035","file":"DEC-0035-remove-userland-system-run-cart-and-preserve-direct-boot.md","status":"accepted","created_at":"2026-07-03","updated_at":"2026-07-03","ref_agenda":"AGD-0003"},{"id":"DEC-0036","file":"DEC-0036-systemos-games-root-and-home-game-launch.md","status":"accepted","created_at":"2026-07-03","updated_at":"2026-07-03","ref_agenda":"AGD-0045"}],"plans":[{"id":"PLN-0129","file":"PLN-0129-remove-userland-run-cart-abi-surface.md","status":"done","created_at":"2026-07-03","updated_at":"2026-07-03","ref_decisions":["DEC-0035"]},{"id":"PLN-0130","file":"PLN-0130-remove-runtime-run-cart-stub-dispatch.md","status":"done","created_at":"2026-07-03","updated_at":"2026-07-03","ref_decisions":["DEC-0035"]},{"id":"PLN-0131","file":"PLN-0131-preserve-direct-cartridge-boot-coverage.md","status":"done","created_at":"2026-07-03","updated_at":"2026-07-03","ref_decisions":["DEC-0035"]},{"id":"PLN-0132","file":"PLN-0132-specify-games-root-home-launch-contract.md","status":"done","created_at":"2026-07-03","updated_at":"2026-07-03","ref_decisions":["DEC-0036"]},{"id":"PLN-0133","file":"PLN-0133-implement-games-root-library-discovery.md","status":"done","created_at":"2026-07-03","updated_at":"2026-07-03","ref_decisions":["DEC-0036"]},{"id":"PLN-0134","file":"PLN-0134-wire-home-game-list-launch-flow.md","status":"done","created_at":"2026-07-03","updated_at":"2026-07-03","ref_decisions":["DEC-0036"]},{"id":"PLN-0135","file":"PLN-0135-validate-games-root-launch-end-to-end.md","status":"done","created_at":"2026-07-03","updated_at":"2026-07-03","ref_decisions":["DEC-0036"]}],"lessons":[]}
|
{"type":"discussion","id":"DSC-0004","status":"done","ticket":"system-run-cart","title":"Agenda - System Run Cart","created_at":"2026-03-27","updated_at":"2026-07-03","tags":[],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0051","file":"discussion/lessons/DSC-0004-system-run-cart/LSN-0051-launch-authority-belongs-to-systemos.md","status":"done","created_at":"2026-07-03","updated_at":"2026-07-03"}]}
|
||||||
{"type":"discussion","id":"DSC-0005","status":"open","ticket":"system-fault-semantics-and-control-surface","title":"Agenda - System Fault Semantics and Control Surface","created_at":"2026-03-27","updated_at":"2026-03-27","tags":[],"agendas":[{"id":"AGD-0004","file":"AGD-0004-system-fault-semantics-and-control-surface.md","status":"open","created_at":"2026-03-27","updated_at":"2026-03-27"}],"decisions":[],"plans":[],"lessons":[]}
|
{"type":"discussion","id":"DSC-0005","status":"open","ticket":"system-fault-semantics-and-control-surface","title":"Agenda - System Fault Semantics and Control Surface","created_at":"2026-03-27","updated_at":"2026-03-27","tags":[],"agendas":[{"id":"AGD-0004","file":"AGD-0004-system-fault-semantics-and-control-surface.md","status":"open","created_at":"2026-03-27","updated_at":"2026-03-27"}],"decisions":[],"plans":[],"lessons":[]}
|
||||||
{"type":"discussion","id":"DSC-0006","status":"open","ticket":"vm-owned-random-service","title":"Agenda - VM-Owned Random Service","created_at":"2026-03-27","updated_at":"2026-03-27","tags":[],"agendas":[{"id":"AGD-0005","file":"AGD-0005-vm-owned-random-service.md","status":"open","created_at":"2026-03-27","updated_at":"2026-03-27"}],"decisions":[],"plans":[],"lessons":[]}
|
{"type":"discussion","id":"DSC-0006","status":"open","ticket":"vm-owned-random-service","title":"Agenda - VM-Owned Random Service","created_at":"2026-03-27","updated_at":"2026-03-27","tags":[],"agendas":[{"id":"AGD-0005","file":"AGD-0005-vm-owned-random-service.md","status":"open","created_at":"2026-03-27","updated_at":"2026-03-27"}],"decisions":[],"plans":[],"lessons":[]}
|
||||||
{"type":"discussion","id":"DSC-0007","status":"open","ticket":"app-home-filesystem-surface-and-semantics","title":"Agenda - App Home Filesystem Surface and Semantics","created_at":"2026-03-27","updated_at":"2026-03-27","tags":[],"agendas":[{"id":"AGD-0006","file":"AGD-0006-app-home-filesystem-surface-and-semantics.md","status":"open","created_at":"2026-03-27","updated_at":"2026-03-27"}],"decisions":[],"plans":[],"lessons":[]}
|
{"type":"discussion","id":"DSC-0007","status":"open","ticket":"app-home-filesystem-surface-and-semantics","title":"Agenda - App Home Filesystem Surface and Semantics","created_at":"2026-03-27","updated_at":"2026-03-27","tags":[],"agendas":[{"id":"AGD-0006","file":"AGD-0006-app-home-filesystem-surface-and-semantics.md","status":"open","created_at":"2026-03-27","updated_at":"2026-03-27"}],"decisions":[],"plans":[],"lessons":[]}
|
||||||
|
{"type":"discussion","id":"DSC-0045","status":"open","ticket":"background-service-audio-execution","title":"Background Service and Audio Execution","created_at":"2026-07-05","updated_at":"2026-07-05","tags":["runtime","os","lifecycle","service","audio","background","architecture"],"agendas":[{"id":"AGD-0048","file":"AGD-0048-background-service-audio-execution.md","status":"open","created_at":"2026-07-05","updated_at":"2026-07-05"}],"decisions":[],"plans":[],"lessons":[]}
|
||||||
{"type":"discussion","id":"DSC-0008","status":"done","ticket":"perf-runtime-telemetry-hot-path","title":"Agenda - [PERF] Runtime Telemetry Hot Path","created_at":"2026-03-27","updated_at":"2026-06-04","tags":[],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0026","file":"discussion/lessons/DSC-0008-perf-runtime-telemetry-hot-path/LSN-0026-push-based-telemetry-model.md","status":"done","created_at":"2026-04-10","updated_at":"2026-04-10"}]}
|
{"type":"discussion","id":"DSC-0008","status":"done","ticket":"perf-runtime-telemetry-hot-path","title":"Agenda - [PERF] Runtime Telemetry Hot Path","created_at":"2026-03-27","updated_at":"2026-06-04","tags":[],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0026","file":"discussion/lessons/DSC-0008-perf-runtime-telemetry-hot-path/LSN-0026-push-based-telemetry-model.md","status":"done","created_at":"2026-04-10","updated_at":"2026-04-10"}]}
|
||||||
{"type":"discussion","id":"DSC-0009","status":"done","ticket":"perf-async-background-work-lanes-for-assets-and-fs","title":"Agenda - [PERF] Async Background Work Lanes for Assets and FS","created_at":"2026-03-27","updated_at":"2026-07-01","tags":["perf","asset","fs","async","scheduler","runtime"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0050","file":"discussion/lessons/DSC-0009-perf-async-background-work-lanes-for-assets-and-fs/LSN-0050-serial-async-lanes-bound-backlog-complexity.md","status":"done","created_at":"2026-07-01","updated_at":"2026-07-01"}]}
|
{"type":"discussion","id":"DSC-0009","status":"done","ticket":"perf-async-background-work-lanes-for-assets-and-fs","title":"Agenda - [PERF] Async Background Work Lanes for Assets and FS","created_at":"2026-03-27","updated_at":"2026-07-01","tags":["perf","asset","fs","async","scheduler","runtime"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0050","file":"discussion/lessons/DSC-0009-perf-async-background-work-lanes-for-assets-and-fs/LSN-0050-serial-async-lanes-bound-backlog-complexity.md","status":"done","created_at":"2026-07-01","updated_at":"2026-07-01"}]}
|
||||||
{"type":"discussion","id":"DSC-0010","status":"done","ticket":"perf-host-desktop-frame-pacing-and-presentation","title":"Agenda - [PERF] Host Desktop Frame Pacing and Presentation","created_at":"2026-03-27","updated_at":"2026-04-20","tags":[],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0036","file":"discussion/lessons/DSC-0010-perf-host-desktop-frame-pacing-and-presentation/LSN-0036-frame-publication-and-host-invalidation-must-be-separate.md","status":"done","created_at":"2026-04-20","updated_at":"2026-04-20"}]}
|
{"type":"discussion","id":"DSC-0010","status":"done","ticket":"perf-host-desktop-frame-pacing-and-presentation","title":"Agenda - [PERF] Host Desktop Frame Pacing and Presentation","created_at":"2026-03-27","updated_at":"2026-04-20","tags":[],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0036","file":"discussion/lessons/DSC-0010-perf-host-desktop-frame-pacing-and-presentation/LSN-0036-frame-publication-and-host-invalidation-must-be-separate.md","status":"done","created_at":"2026-04-20","updated_at":"2026-04-20"}]}
|
||||||
@@ -42,3 +44,6 @@
|
|||||||
{"type":"discussion","id":"DSC-0033","status":"done","ticket":"system-os-service-ownership-and-module-layout","title":"Agenda - SystemOS Service Ownership and Module Layout","created_at":"2026-05-14","updated_at":"2026-05-15","tags":["runtime","os","services","module-layout","vm","window-manager","logging"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0042","file":"discussion/lessons/DSC-0033-system-os-service-ownership-and-module-layout/LSN-0042-systemos-service-ownership-boundary.md","status":"done","created_at":"2026-05-15","updated_at":"2026-05-15"}]}
|
{"type":"discussion","id":"DSC-0033","status":"done","ticket":"system-os-service-ownership-and-module-layout","title":"Agenda - SystemOS Service Ownership and Module Layout","created_at":"2026-05-14","updated_at":"2026-05-15","tags":["runtime","os","services","module-layout","vm","window-manager","logging"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0042","file":"discussion/lessons/DSC-0033-system-os-service-ownership-and-module-layout/LSN-0042-systemos-service-ownership-boundary.md","status":"done","created_at":"2026-05-15","updated_at":"2026-05-15"}]}
|
||||||
{"type":"discussion","id":"DSC-0036","status":"done","ticket":"prometeu-hub-ui-direction","title":"Agenda - Prometeu Hub UI Direction","created_at":"2026-05-15","updated_at":"2026-05-22","tags":["hub","ui","shell","system-apps","lifecycle","design-system"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0045","file":"discussion/lessons/DSC-0036-prometeu-hub-ui-direction/LSN-0045-hub-ui-slices-should-prove-os-boundaries.md","status":"done","created_at":"2026-05-22","updated_at":"2026-05-22"}]}
|
{"type":"discussion","id":"DSC-0036","status":"done","ticket":"prometeu-hub-ui-direction","title":"Agenda - Prometeu Hub UI Direction","created_at":"2026-05-15","updated_at":"2026-05-22","tags":["hub","ui","shell","system-apps","lifecycle","design-system"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0045","file":"discussion/lessons/DSC-0036-prometeu-hub-ui-direction/LSN-0045-hub-ui-slices-should-prove-os-boundaries.md","status":"done","created_at":"2026-05-22","updated_at":"2026-05-22"}]}
|
||||||
{"type":"discussion","id":"DSC-0037","status":"done","ticket":"rgba8888-framebuffer-and-pixel-format-direction","title":"Agenda - RGBA8888 Framebuffer and Pixel Format Direction","created_at":"2026-05-22","updated_at":"2026-05-23","tags":["gfx","framebuffer","rgb565","rgba8888","renderer","assets","host","backend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0046","file":"discussion/lessons/DSC-0037-rgba8888-framebuffer-and-pixel-format-direction/LSN-0046-pixel-format-contracts-must-move-as-one-surface.md","status":"done","created_at":"2026-05-23","updated_at":"2026-05-23"}]}
|
{"type":"discussion","id":"DSC-0037","status":"done","ticket":"rgba8888-framebuffer-and-pixel-format-direction","title":"Agenda - RGBA8888 Framebuffer and Pixel Format Direction","created_at":"2026-05-22","updated_at":"2026-05-23","tags":["gfx","framebuffer","rgb565","rgba8888","renderer","assets","host","backend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0046","file":"discussion/lessons/DSC-0037-rgba8888-framebuffer-and-pixel-format-direction/LSN-0046-pixel-format-contracts-must-move-as-one-surface.md","status":"done","created_at":"2026-05-23","updated_at":"2026-05-23"}]}
|
||||||
|
{"type":"discussion","id":"DSC-0046","status":"done","ticket":"runtime-owned-variable-glyph-bank-palette-protocol","title":"Runtime-Owned Variable Glyph Bank Palette Protocol","created_at":"2026-07-14","updated_at":"2026-07-14","tags":["runtime","gfx","assets","glyph-bank","palette-serialization","protocol"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0055","file":"discussion/lessons/DSC-0046-runtime-owned-variable-glyph-bank-palette-protocol/LSN-0055-runtime-owned-asset-protocols-must-align-payload-residency-and-lookup.md","status":"done","created_at":"2026-07-14","updated_at":"2026-07-14"}]}
|
||||||
|
{"type":"discussion","id":"DSC-0047","status":"open","ticket":"portable-host-backend-strategy","title":"Portable Host Backend Strategy","created_at":"2026-07-14","updated_at":"2026-07-14","tags":["host","desktop","portable","sdl","backend","rendering","input","audio","linux","android","handheld"],"agendas":[{"id":"AGD-0050","file":"AGD-0050-portable-host-backend-strategy.md","status":"open","created_at":"2026-07-14","updated_at":"2026-07-14"}],"decisions":[],"plans":[],"lessons":[]}
|
||||||
|
{"type":"discussion","id":"DSC-0048","status":"done","ticket":"corrigir-identificacao-formato-pbx","title":"Corrigir Identificacao do Formato PBX","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["runtime","bytecode","pbx","loader","format","architecture"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0056","file":"discussion/lessons/DSC-0048-corrigir-identificacao-formato-pbx/LSN-0056-runtime-artifact-identity-must-not-borrow-frontend-names.md","status":"done","created_at":"2026-07-15","updated_at":"2026-07-15"}]}
|
||||||
|
|||||||
+118
@@ -0,0 +1,118 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0051
|
||||||
|
ticket: system-run-cart
|
||||||
|
title: Launch Authority Belongs to SystemOS
|
||||||
|
created: 2026-07-03
|
||||||
|
tags: [runtime, systemos, cartridge, launch, abi, home]
|
||||||
|
---
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
The `system.run_cart` workflow resolved two related questions: whether a guest
|
||||||
|
should have an app-callable cartridge launch syscall, and how Home should start
|
||||||
|
games from a local library.
|
||||||
|
|
||||||
|
The final model removes `system.run_cart` from the userland ABI while preserving
|
||||||
|
direct host-controlled cartridge boot. Home launch is restored as a
|
||||||
|
system-owned path: the host may provide `--games-root <dir>`, SystemOS/Home
|
||||||
|
discovers valid Game directory cartridges, and selecting an entry routes through
|
||||||
|
firmware into `LoadCartridge`.
|
||||||
|
|
||||||
|
The important distinction is authority. A launch can be a valid product action
|
||||||
|
without being a guest capability.
|
||||||
|
|
||||||
|
## Key Decisions
|
||||||
|
|
||||||
|
### Remove Guest Cartridge Launch
|
||||||
|
|
||||||
|
**What:** Prometeu removed `system.run_cart` from the public userland syscall
|
||||||
|
surface, generated guest metadata, and runtime dispatch.
|
||||||
|
|
||||||
|
**Why:** A guest syscall made cartridge launch look like app-owned navigation.
|
||||||
|
That gave userland implied authority over target resolution, lifecycle cleanup,
|
||||||
|
failure policy, and system navigation.
|
||||||
|
|
||||||
|
**Trade-offs:** Obsolete guest code cannot keep a compatibility stub. The
|
||||||
|
runtime instead keeps direct boot as a host/system entrypoint and lets stale
|
||||||
|
guest attempts fail through the invalid syscall path.
|
||||||
|
|
||||||
|
### Preserve Direct Boot Outside The Guest ABI
|
||||||
|
|
||||||
|
**What:** Host, CLI, debugger, tests, and single-game flows continue to boot a
|
||||||
|
selected cartridge directly.
|
||||||
|
|
||||||
|
**Why:** Direct boot is still essential for development, automation, and future
|
||||||
|
single-game distribution. Those flows start with a host-selected target before
|
||||||
|
VM execution, so they do not need a guest syscall.
|
||||||
|
|
||||||
|
**Trade-offs:** The loader remains reusable, but it is not lifecycle
|
||||||
|
orchestration authority. Higher-level transitions must be owned by firmware or
|
||||||
|
SystemOS.
|
||||||
|
|
||||||
|
### Model Home Launch As A System Action
|
||||||
|
|
||||||
|
**What:** `--games-root <dir>` configures a local games library for Home. V1
|
||||||
|
discovery scans immediate child directories, keeps only valid Game cartridges,
|
||||||
|
and exposes enough internal metadata to launch a selected entry.
|
||||||
|
|
||||||
|
**Why:** Home needs a product path for "choose a game and start it", but that
|
||||||
|
action belongs to the system profile. SystemOS can present the library and ask
|
||||||
|
firmware to enter `LoadCartridge` without reintroducing guest-controlled launch.
|
||||||
|
|
||||||
|
**Trade-offs:** V1 intentionally excludes recursive discovery, `.pmc`, non-game
|
||||||
|
apps, rich catalog metadata, return-to-Home, and game-to-game switching. Those
|
||||||
|
need separate lifecycle and orchestration decisions.
|
||||||
|
|
||||||
|
## Patterns and Algorithms
|
||||||
|
|
||||||
|
### Authority-Based API Classification
|
||||||
|
|
||||||
|
Before exposing an operation to guest/userland code, classify what authority it
|
||||||
|
implies. If the operation selects another executable target, changes process
|
||||||
|
lifecycle, or controls navigation between system-owned modes, it is probably a
|
||||||
|
SystemOS or firmware action rather than an app syscall.
|
||||||
|
|
||||||
|
### Separate Selection From Loading
|
||||||
|
|
||||||
|
Home owns user selection and presentation. SystemOS owns the launch request.
|
||||||
|
Firmware owns the transition into `LoadCartridge`. The cartridge loader remains
|
||||||
|
the mechanism that validates and materializes a cartridge, not the authority
|
||||||
|
that decides when navigation is allowed.
|
||||||
|
|
||||||
|
### Expandable Internal Catalog Records
|
||||||
|
|
||||||
|
Home can render a small v1 list while the internal entry retains manifest data,
|
||||||
|
title, app id, app version, cartridge path, and discovery metadata. This keeps
|
||||||
|
the UI simple without reducing the model to a display-only DTO.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
### Compatibility Stubs Preserve False Contracts
|
||||||
|
|
||||||
|
A syscall that returns success without doing real lifecycle work is worse than
|
||||||
|
an absent syscall. It teaches callers that the platform supports app-driven
|
||||||
|
launch while hiding that no complete transition happened.
|
||||||
|
|
||||||
|
### A Product Flow Is Not Automatically A Guest API
|
||||||
|
|
||||||
|
"Home can launch a game" and "a guest can launch a cartridge" are different
|
||||||
|
claims. Product behavior should be mapped to the component with the correct
|
||||||
|
authority instead of mirrored into the nearest callable ABI.
|
||||||
|
|
||||||
|
### Generic Library Roots Prematurely Expand Scope
|
||||||
|
|
||||||
|
The first launcher path is a games library, not a marketplace or full app
|
||||||
|
catalog. Shell apps, System apps, packages, icons, search, and recursive layouts
|
||||||
|
carry separate contracts and should not be smuggled into the v1 games-root path.
|
||||||
|
|
||||||
|
## Takeaways
|
||||||
|
|
||||||
|
- Cartridge launch is system navigation, not a userland syscall.
|
||||||
|
- Direct boot can remain host-controlled without appearing in guest metadata.
|
||||||
|
- Home launch should emit a system action and let firmware enter
|
||||||
|
`LoadCartridge`.
|
||||||
|
- Loader reuse does not imply loader ownership of lifecycle policy.
|
||||||
|
- Keep v1 discovery narrow: immediate child directory cartridges with
|
||||||
|
`app_mode: Game`.
|
||||||
|
- Preserve internal catalog metadata even when the Home UI renders only a small
|
||||||
|
subset.
|
||||||
+145
@@ -0,0 +1,145 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0052
|
||||||
|
ticket: foreground-stack-game-pause-shell-vm-backed
|
||||||
|
title: Foreground Ownership and VM Session Ownership Are Separate
|
||||||
|
created: 2026-07-05
|
||||||
|
tags: [runtime, os, lifecycle, shell, game, vm, foreground, architecture]
|
||||||
|
---
|
||||||
|
|
||||||
|
# LSN-0052: Foreground Ownership and VM Session Ownership Are Separate
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
DSC-0041 closed the `Game -> Home/Shell -> same Game` lifecycle for the first
|
||||||
|
runtime implementation that supports both native Shell apps and VM-backed Shell
|
||||||
|
apps. The important architectural shift was not only pausing the Game. The
|
||||||
|
runtime also had to stop treating one firmware-owned VM as the place where all
|
||||||
|
guest execution state lives.
|
||||||
|
|
||||||
|
The final model separates two questions:
|
||||||
|
|
||||||
|
- Who owns the foreground visual/input authority right now?
|
||||||
|
- Which VM-backed process owns a mutable VM execution context?
|
||||||
|
|
||||||
|
Foreground ownership is global SystemOS policy. VM execution state belongs to a
|
||||||
|
session associated with a task/process. A suspended resident Game is not a saved
|
||||||
|
snapshot and not a special global VM. It is a live VM session that is temporarily
|
||||||
|
ineligible for normal foreground ticks, input, frame pacing, and render
|
||||||
|
publication.
|
||||||
|
|
||||||
|
## Key Decisions
|
||||||
|
|
||||||
|
### Foreground Stack and Game Pause Contract
|
||||||
|
|
||||||
|
**What:** PROMETEU uses a single foreground owner in v1. Hub/Home is the root
|
||||||
|
Shell owner, a Game may remain resident, and one foreground Shell app may run in
|
||||||
|
front of the resident Game. Pressing desktop `Esc` is a host/SystemOS Home
|
||||||
|
request, not guest input.
|
||||||
|
|
||||||
|
**Why:** This preserves console-like navigation without turning the runtime into
|
||||||
|
a general multitasking scheduler. It lets the system pause and suspend a Game,
|
||||||
|
run Hub or Shell, then resume the same Game deterministically.
|
||||||
|
|
||||||
|
**Trade-offs:** The model intentionally rejects multiple resident Games, direct
|
||||||
|
Shell-to-Game return, background execution, and Game-to-Game switching in v1.
|
||||||
|
Those features remain future work, but the lifecycle structure now has a place
|
||||||
|
to add them.
|
||||||
|
|
||||||
|
### VM Session Ownership for VM-Backed Processes
|
||||||
|
|
||||||
|
**What:** VM-backed mutable execution state is owned by VM sessions. A
|
||||||
|
VM-backed Game and a VM-backed Shell never share the same VM, stack, heap, PC,
|
||||||
|
open handles, cartridge identity, or VM-scoped runtime state.
|
||||||
|
|
||||||
|
**Why:** A single firmware-owned VM cannot represent a suspended resident Game
|
||||||
|
and a foreground VM Shell at the same time. Loading the Shell into that global
|
||||||
|
VM would overwrite the Game context that the lifecycle model says is resident.
|
||||||
|
|
||||||
|
**Trade-offs:** Session ownership is more explicit than one global VM, but it
|
||||||
|
keeps the model simpler than snapshot/restore. It also prepares the runtime for
|
||||||
|
future background-capable sessions without committing to background scheduling
|
||||||
|
yet.
|
||||||
|
|
||||||
|
## Patterns and Algorithms
|
||||||
|
|
||||||
|
### Pause Is Cooperative, Suspension Is OS Authority
|
||||||
|
|
||||||
|
The Game receives lifecycle events such as pause and resume, but the OS owns the
|
||||||
|
actual scheduling state. If the Game does not cooperate within the bounded pause
|
||||||
|
budget, SystemOS can suspend it anyway. On resume, the Game receives a foreground
|
||||||
|
restore event and may still keep its internal pause screen while it
|
||||||
|
synchronizes.
|
||||||
|
|
||||||
|
This distinction prevents userland from owning system navigation. The Game may
|
||||||
|
observe and react. It cannot veto Home.
|
||||||
|
|
||||||
|
### Foreground Owner Is Not the Same as Tick Eligibility
|
||||||
|
|
||||||
|
Foreground ownership controls input, visual authority, render ownership, and
|
||||||
|
normal frame pacing. Tick eligibility controls whether a VM session may execute.
|
||||||
|
In v1, only the foreground VM session receives normal ticks, and the resident
|
||||||
|
Game does not tick while Shell or Hub is foreground.
|
||||||
|
|
||||||
|
The important design detail is that the data model does not assume this must be
|
||||||
|
true forever. Sessions can later become background-eligible without changing who
|
||||||
|
owns render/input foreground.
|
||||||
|
|
||||||
|
### VM Sessions Are the Unit of Mutable Guest State
|
||||||
|
|
||||||
|
Each VM-backed task/process maps to a `VmSession`. The session owns the VM,
|
||||||
|
runtime state, session-scoped filesystem state, open file handles, next handle
|
||||||
|
allocation, cartridge identity, lifecycle delivery state, and debug state.
|
||||||
|
|
||||||
|
Cartridge loading creates or reuses a VM session through SystemOS session
|
||||||
|
services. Firmware orchestrates macro states such as `LoadCartridge`,
|
||||||
|
`GameRunning`, `HubHome`, and `ShellRunning`, but it no longer owns a canonical
|
||||||
|
guest VM.
|
||||||
|
|
||||||
|
### Debugger and Host Inspection Must Follow the Active Session
|
||||||
|
|
||||||
|
Host debugging must inspect and mutate the active session VM, not a transitional
|
||||||
|
global VM. PC, operand stack, breakpoints, debug-step execution, cartridge
|
||||||
|
identity, and breakpoint-hit events all need to resolve through active session
|
||||||
|
state.
|
||||||
|
|
||||||
|
This keeps debugger behavior aligned with actual execution. A debugger that
|
||||||
|
observes a different VM than the scheduler ticks is worse than no debugger: it
|
||||||
|
creates false confidence and hides lifecycle bugs.
|
||||||
|
|
||||||
|
### Operational Failures Should Cross Facades as Typed Errors
|
||||||
|
|
||||||
|
Session creation and loading are operational boundaries. Missing task, missing
|
||||||
|
process, duplicate VM session, missing VM session during initialization, and
|
||||||
|
foreground Shell rejection should be typed errors. Firmware can then choose a
|
||||||
|
controlled crash report, a launch rejection, or a logged no-transition outcome.
|
||||||
|
|
||||||
|
Panics are reserved for test/setup wrappers or impossible internal invariants
|
||||||
|
that have already been proven by prior checks.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
- Do not use a global VM as a compatibility bridge after session ownership is
|
||||||
|
introduced. It will eventually become stale or contradictory.
|
||||||
|
- Do not let Home/SystemOS be guest input. It changes OS authority, so it must
|
||||||
|
bypass guest pad state.
|
||||||
|
- Do not present old frames after foreground ownership changes. Render ownership
|
||||||
|
and epoch validation are part of lifecycle correctness, not renderer polish.
|
||||||
|
- Do not model pause and suspension as the same state. Pause is visible to the
|
||||||
|
Game; suspension is the scheduler mechanism.
|
||||||
|
- Do not encode v1 limits such as one resident Game or one foreground Shell by
|
||||||
|
collapsing storage into one VM. Express those limits as lifecycle/session
|
||||||
|
policy.
|
||||||
|
- Do not let debugger state drift from scheduler state. The debugger must use
|
||||||
|
the same active session as normal execution.
|
||||||
|
|
||||||
|
## Takeaways
|
||||||
|
|
||||||
|
- Foreground ownership is global policy; VM execution state is session-owned.
|
||||||
|
- A suspended Game is a preserved session, not a serialized VM and not a global
|
||||||
|
VM waiting to be reused.
|
||||||
|
- Shell apps can be native or VM-backed, but only VM-backed processes need VM
|
||||||
|
sessions.
|
||||||
|
- Session ownership is the foundation for future background-capable processes,
|
||||||
|
even before background execution exists.
|
||||||
|
- Typed session/lifecycle errors make launch and recovery behavior explicit at
|
||||||
|
firmware boundaries.
|
||||||
+67
@@ -0,0 +1,67 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0053
|
||||||
|
ticket: system-os-cartridge-switch-orchestrator
|
||||||
|
title: Game Switching Is Lifecycle Replacement, Not Loader Work
|
||||||
|
created: 2026-07-05
|
||||||
|
tags: [runtime, os, lifecycle, game, cartridge]
|
||||||
|
---
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
PROMETEU supports two superficially similar flows:
|
||||||
|
|
||||||
|
- `Game -> Home -> same Game`, which is pause/suspend/resume.
|
||||||
|
- `Game A -> Home -> Game B`, which is destructive replacement.
|
||||||
|
|
||||||
|
The second flow is not a loader feature. It is a SystemOS lifecycle operation
|
||||||
|
that happens to use the cartridge loader after the old resident Game has been
|
||||||
|
removed from resumable state.
|
||||||
|
|
||||||
|
## Key Decisions
|
||||||
|
|
||||||
|
### SystemOS Game Cartridge Switch Orchestrator
|
||||||
|
|
||||||
|
**What:** A different-Game launch from Home terminates the previous resident
|
||||||
|
Game before loading the new cartridge. The new Game receives a fresh VM session.
|
||||||
|
|
||||||
|
**Why:** Reusing or preserving the old Game while the new Game loads creates a
|
||||||
|
rollback problem across VM state, handles, assets, input, audio, render
|
||||||
|
ownership, debug state, and lifecycle delivery. V1 does not need that
|
||||||
|
transactional model.
|
||||||
|
|
||||||
|
**Trade-offs:** Failed replacement returns to Home and does not restore the old
|
||||||
|
Game. This is intentionally simpler than snapshot/rollback and makes state
|
||||||
|
ownership visible in tests.
|
||||||
|
|
||||||
|
## Patterns and Algorithms
|
||||||
|
|
||||||
|
Use a resolved SystemOS switch target, not a guest syscall, for Home launches.
|
||||||
|
The target carries cartridge path and identity, while SystemOS owns the policy:
|
||||||
|
|
||||||
|
1. detect whether the selected Game matches the resident `app_id`;
|
||||||
|
2. resume if it is the same Game;
|
||||||
|
3. terminate the old resident Game if it is different;
|
||||||
|
4. load the new cartridge through the normal loader;
|
||||||
|
5. create and initialize a fresh VM session;
|
||||||
|
6. return to Home on replacement failure without restoring the previous Game.
|
||||||
|
|
||||||
|
The loader stays a materializer. It does not close tasks, remove sessions,
|
||||||
|
repair foreground state, or own failure recovery.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
- Treating a different Game as a resume path leaks VM execution state.
|
||||||
|
- Letting the loader own lifecycle cleanup hides policy in the wrong layer.
|
||||||
|
- Keeping the old Game as rollback state requires correctness across assets,
|
||||||
|
render ownership, input barriers, audio, open handles, and debugger state.
|
||||||
|
- A switch test with only one cartridge cannot prove identity replacement.
|
||||||
|
|
||||||
|
## Takeaways
|
||||||
|
|
||||||
|
- Same-Game Home selection is resume; different-Game Home selection is
|
||||||
|
destructive replacement.
|
||||||
|
- SystemOS owns cartridge switching policy; the cartridge loader only loads.
|
||||||
|
- Replacement failure should be a clean Home state, not a rollback to the old
|
||||||
|
Game.
|
||||||
|
- End-to-end switch tests need visually distinct cartridges to catch stale
|
||||||
|
session or stale frame reuse.
|
||||||
+72
@@ -0,0 +1,72 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0054
|
||||||
|
ticket: hub-suspended-game-kill-affordance
|
||||||
|
title: Manual Hub Kill Must Share Game Termination Cleanup
|
||||||
|
created: 2026-07-05
|
||||||
|
tags: [hub, lifecycle, game, ui, assets]
|
||||||
|
---
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
After a Game returns to Home, the Game can remain resident and suspended so it
|
||||||
|
can be resumed later. That state needs a visible, direct way to terminate the
|
||||||
|
resident Game without launching another cartridge just to force replacement.
|
||||||
|
|
||||||
|
The Hub kill affordance solved the UX gap, but the durable engineering lesson is
|
||||||
|
the cleanup boundary: manual kill must not become a second, partial termination
|
||||||
|
path.
|
||||||
|
|
||||||
|
## Key Decisions
|
||||||
|
|
||||||
|
### Hub Suspended Game Kill Affordance
|
||||||
|
|
||||||
|
**What:** Hub renders a red bottom-right control when a Game is resident and
|
||||||
|
suspended. The control shows only the Game title. Clicking it immediately
|
||||||
|
terminates the resident Game and keeps the user in Hub.
|
||||||
|
|
||||||
|
**Why:** The user can distinguish "resume this Game" from "discard this resident
|
||||||
|
Game" without starting a different cartridge. Reusing the canonical termination
|
||||||
|
path prevents a repeat of stale scene/glyph/asset state bugs.
|
||||||
|
|
||||||
|
**Trade-offs:** V1 has no confirmation step. The destructive nature is carried
|
||||||
|
by placement, color, and the fact that the target Game is already out of
|
||||||
|
foreground.
|
||||||
|
|
||||||
|
## Patterns and Algorithms
|
||||||
|
|
||||||
|
Manual Hub kill and destructive Game replacement should call the same resident
|
||||||
|
Game termination helper. That helper is responsible for the whole runtime
|
||||||
|
surface:
|
||||||
|
|
||||||
|
- close the Game task;
|
||||||
|
- stop the process;
|
||||||
|
- remove the VM session;
|
||||||
|
- clear resident Game state and task-scoped lifecycle delivery;
|
||||||
|
- restore Shell/Hub render ownership;
|
||||||
|
- clear lifecycle audio pause state;
|
||||||
|
- unbind the Game2D composer scene;
|
||||||
|
- shut down cartridge-scoped asset manager state and physical banks;
|
||||||
|
- emit explicit Hub/POS observability for manual kill.
|
||||||
|
|
||||||
|
The Hub itself should emit a high-level action such as `KillResidentGame`; it
|
||||||
|
should not know how to clean runtime subsystems.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
- A UI-only kill that removes a task but leaves assets or composer binding alive
|
||||||
|
can still fail later when another Game renders.
|
||||||
|
- A cleanup-only helper without an end-to-end Hub click test can miss the
|
||||||
|
interaction between hitbox, foreground ownership, render owner, and no-resume.
|
||||||
|
- Hard-coded click coordinates in tests make the UI contract harder to maintain;
|
||||||
|
expose the layout hitbox when tests need to exercise it.
|
||||||
|
|
||||||
|
## Takeaways
|
||||||
|
|
||||||
|
- Visible system controls should produce system actions, not direct subsystem
|
||||||
|
mutation from UI code.
|
||||||
|
- Manual kill and Game replacement are variants of the same resident Game
|
||||||
|
termination contract.
|
||||||
|
- Cleanup tests should prove both logical state removal and visible-frame
|
||||||
|
behavior: the control appears before kill and disappears after kill.
|
||||||
|
- "No resume after kill" is as important as "task closed" because resumability
|
||||||
|
is the user-facing state.
|
||||||
+97
@@ -0,0 +1,97 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0055
|
||||||
|
ticket: runtime-owned-variable-glyph-bank-palette-protocol
|
||||||
|
title: Runtime-Owned Asset Protocols Must Align Payload, Residency, and Lookup
|
||||||
|
created: 2026-07-14
|
||||||
|
tags: [runtime, assets, glyph-bank, palette-serialization, protocol]
|
||||||
|
decision: DEC-0041
|
||||||
|
---
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
The runtime changed the `GLYPH/indexed_v1` glyph-bank palette contract from a
|
||||||
|
fixed 64-palette payload and resident table to variable palette serialization
|
||||||
|
and variable resident palette storage.
|
||||||
|
|
||||||
|
The initiating pressure came from packer/studio: fixed RGBA8888 palette padding
|
||||||
|
made small glyph banks pay for `64 * 16 * 4` palette bytes even when they used
|
||||||
|
far fewer palettes. The important architectural point was that the runtime, not
|
||||||
|
the packer, had to decide the protocol. The packer can only emit payloads that
|
||||||
|
conform to the runtime contract once the runtime spec is published.
|
||||||
|
|
||||||
|
## Key Decisions
|
||||||
|
|
||||||
|
### Variable Glyph Bank Palette Protocol
|
||||||
|
|
||||||
|
**What:**
|
||||||
|
`palette_count` became the number of serialized palettes and the number of
|
||||||
|
resident palettes in the loaded `GlyphBank`. The valid range is `1..=64`.
|
||||||
|
`palette_id` remains a direct palette identity and is valid only when
|
||||||
|
`palette_id < palette_count` for the referenced resident bank.
|
||||||
|
|
||||||
|
**Why:**
|
||||||
|
Keeping serialized count variable while retaining a fixed 64-slot resident
|
||||||
|
table would preserve two meanings for palette capacity. The runtime would save
|
||||||
|
payload bytes but still carry a split contract between payload shape, resident
|
||||||
|
shape, and lookup validity. Making all three agree gives the runtime one
|
||||||
|
source of truth.
|
||||||
|
|
||||||
|
**Trade-offs:**
|
||||||
|
Palette validity is now bank-dependent. Scene and sprite composition must check
|
||||||
|
the referenced loaded bank instead of relying on a global `0..63` rule. This
|
||||||
|
adds validation work, but it prevents invalid references from silently becoming
|
||||||
|
transparent or default colors.
|
||||||
|
|
||||||
|
## Patterns and Algorithms
|
||||||
|
|
||||||
|
Let the runtime own runtime-facing asset protocols. Tooling can discover pain,
|
||||||
|
but the runtime spec must define effective metadata, payload shape, resident
|
||||||
|
shape, and failure semantics.
|
||||||
|
|
||||||
|
Make count fields material. A count such as `palette_count` should not describe
|
||||||
|
only what the producer authored or only what the payload happens to include. If
|
||||||
|
runtime lookup depends on it, the count must also define resident state and
|
||||||
|
validation boundaries.
|
||||||
|
|
||||||
|
Keep identity direct unless a real remapping problem exists. Sparse-to-dense
|
||||||
|
palette remapping was rejected because it would add a second identity layer
|
||||||
|
across scenes, sprites, packer output, and runtime lookup. V1 keeps palette id
|
||||||
|
`N` as palette slot `N` in the resident bank.
|
||||||
|
|
||||||
|
Separate transparent color from invalid lookup. RGBA alpha is valid color data.
|
||||||
|
An invalid palette reference must be observable as invalid; it must not be
|
||||||
|
collapsed into `Color::TRANSPARENT`.
|
||||||
|
|
||||||
|
Use residue scans after protocol migrations. Search for fixed byte formulas,
|
||||||
|
old constants, fixture helpers, and spec phrases. Legitimate hits should be
|
||||||
|
renamed as maximum-bound concepts, not left as accidental active contracts.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
Partially variable specs are worse than fixed specs. The asset spec already had
|
||||||
|
variable size formulas in some places but still required `palette_count = 64`
|
||||||
|
elsewhere. That contradiction made it unclear which rule was canonical.
|
||||||
|
|
||||||
|
Resident data structures can preserve obsolete protocol assumptions after the
|
||||||
|
payload changes. A fixed array in `GlyphBank` would have kept the old model
|
||||||
|
alive even if decode accepted variable payloads.
|
||||||
|
|
||||||
|
Fallback rendering hides contract errors. Returning transparent for an invalid
|
||||||
|
palette id makes bad assets and bad scene references look like intentional
|
||||||
|
alpha, which is exactly the wrong failure mode for a runtime protocol.
|
||||||
|
|
||||||
|
Fixture generators are part of the contract surface. Stress cartridges and
|
||||||
|
test payload builders must express whether they are using a variable count or
|
||||||
|
the v1 maximum; otherwise they reintroduce fixed-padding assumptions.
|
||||||
|
|
||||||
|
## Takeaways
|
||||||
|
|
||||||
|
- Runtime-facing asset protocols should align payload size, resident memory,
|
||||||
|
and lookup validity.
|
||||||
|
- `palette_count` is effective runtime metadata, not producer commentary.
|
||||||
|
- Direct identity is simpler than remapping until a concrete remapping need
|
||||||
|
exists.
|
||||||
|
- Invalid palette references should fail explicitly; transparent remains a
|
||||||
|
valid RGBA color, not an error substitute.
|
||||||
|
- Protocol migrations need spec edits, code changes, fixture updates, and
|
||||||
|
residue scans in the same workflow.
|
||||||
+61
@@ -0,0 +1,61 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0056
|
||||||
|
ticket: corrigir-identificacao-formato-pbx
|
||||||
|
title: Runtime Artifact Identity Must Not Borrow Frontend Names
|
||||||
|
created: 2026-07-15
|
||||||
|
tags: [runtime, bytecode, pbx, frontend, format-boundary]
|
||||||
|
---
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
Prometeu accepts bytecode produced by multiple frontends. PBS is the base
|
||||||
|
frontend language, while PBX is the executable bytecode artifact consumed by the
|
||||||
|
runtime.
|
||||||
|
|
||||||
|
The runtime had inherited PBS terminology in the executable bytecode path,
|
||||||
|
including the serialized magic number, comments, tests, and VM loader checks.
|
||||||
|
That made one frontend appear to own the runtime executable format.
|
||||||
|
|
||||||
|
## Key Decisions
|
||||||
|
|
||||||
|
### PBX Executable Format Identity
|
||||||
|
|
||||||
|
**What:** PBX is the runtime executable bytecode format, and `PBX\0` is its only
|
||||||
|
valid magic number.
|
||||||
|
|
||||||
|
**Why:** Runtime artifact identity must be independent from any frontend that can
|
||||||
|
produce the artifact. Naming the executable format after PBS would make the
|
||||||
|
runtime boundary look language-specific.
|
||||||
|
|
||||||
|
**Trade-offs:** The correction intentionally rejects old PBS-prefixed executable
|
||||||
|
artifacts instead of carrying a compatibility alias. This keeps the format
|
||||||
|
contract singular, but requires stale generated fixtures to be regenerated or
|
||||||
|
updated.
|
||||||
|
|
||||||
|
## Patterns and Algorithms
|
||||||
|
|
||||||
|
Put file-format identity in the module that serializes and deserializes the
|
||||||
|
format. Loaders and higher-level runtime code should call that boundary instead
|
||||||
|
of duplicating magic-number checks.
|
||||||
|
|
||||||
|
When renaming an artifact identity, update all fixture construction and generator
|
||||||
|
assertions in the same pass as production serialization. Mixed fixture identity
|
||||||
|
usually means tests are asserting historical spelling rather than current
|
||||||
|
contract.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
Do not globally erase frontend names. PBS remains correct when the subject is
|
||||||
|
the PBS language, stdlib, or frontend-facing API. It is wrong only when it names
|
||||||
|
the executable bytecode artifact.
|
||||||
|
|
||||||
|
Do not preserve old magic values just to make a rename feel less disruptive. If
|
||||||
|
there is no compatibility requirement for old artifacts, aliases keep the
|
||||||
|
incorrect model alive.
|
||||||
|
|
||||||
|
## Takeaways
|
||||||
|
|
||||||
|
- Runtime artifact names should describe the runtime contract, not the compiler
|
||||||
|
or frontend that produced the artifact.
|
||||||
|
- Magic numbers are normative format identity, not cosmetic labels.
|
||||||
|
- Loader code should delegate file-format validation to the format owner.
|
||||||
@@ -1,202 +0,0 @@
|
|||||||
---
|
|
||||||
id: AGD-0003
|
|
||||||
ticket: system-run-cart
|
|
||||||
title: Agenda - System Run Cart
|
|
||||||
status: accepted
|
|
||||||
created: 2026-03-27
|
|
||||||
resolved:
|
|
||||||
decision:
|
|
||||||
tags: []
|
|
||||||
---
|
|
||||||
|
|
||||||
# Agenda - System Run Cart
|
|
||||||
|
|
||||||
## Problema
|
|
||||||
|
|
||||||
`system.run_cart` existe na ABI pública, mas hoje não produz efeito real no runtime.
|
|
||||||
Isso expõe duas questões: a superfície atual é um placebo e, mesmo quando houver
|
|
||||||
fluxo real, rodar cartuchos não deve ser uma operação userland. A autoridade
|
|
||||||
para iniciar cartuchos deve pertencer ao sistema/firmware.
|
|
||||||
|
|
||||||
Isso cria uma falsa promessa de plataforma:
|
|
||||||
|
|
||||||
- o programa consegue declarar e chamar uma operação que aparenta iniciar cartuchos;
|
|
||||||
- o loader aceita sua existência;
|
|
||||||
- o runtime retorna sucesso vazio;
|
|
||||||
- nenhuma troca de cartucho, transição de firmware, validação de alvo ou política de segurança ocorre.
|
|
||||||
|
|
||||||
## Dor
|
|
||||||
|
|
||||||
- A ABI expõe uma capability de sistema que, na prática, nao existe.
|
|
||||||
- Mesmo se implementada, a operação não deve ser uma syscall userland comum:
|
|
||||||
apps não devem iniciar cartuchos diretamente.
|
|
||||||
- O guest pode acreditar que solicitou uma troca de app quando nada aconteceu.
|
|
||||||
- Isso corrói a confiabilidade da plataforma: a interface pública deixa de ser contrato e vira placebo.
|
|
||||||
- Qualquer ferramenta, SDK ou documentação construída sobre essa syscall passa a modelar um comportamento inexistente.
|
|
||||||
|
|
||||||
## Alvo da Discussao
|
|
||||||
|
|
||||||
Definir o contrato real da troca de cartucho iniciada pelo sistema do ponto de vista:
|
|
||||||
|
|
||||||
- do guest;
|
|
||||||
- do runtime;
|
|
||||||
- do firmware;
|
|
||||||
- do host/cartridge loader.
|
|
||||||
|
|
||||||
Ao final da discussão, deve ficar claro se a superfície atual:
|
|
||||||
|
|
||||||
- permanece apenas como mecanismo interno do sistema e sai da ABI userland; ou
|
|
||||||
- permanece na ABI somente como superfície privilegiada impossível de chamar por apps comuns; ou
|
|
||||||
- sai temporariamente da ABI até existir fluxo fechado.
|
|
||||||
|
|
||||||
Esta discussao nao deve depender do fechamento previo do formato `.pmc`.
|
|
||||||
Para o primeiro fluxo fechado, `system.run_cart` pode resolver um alvo por
|
|
||||||
um loader ja disponivel, incluindo cartucho em diretorio ou fixture de teste.
|
|
||||||
O suporte ao artefato empacotado `.pmc` permanece responsabilidade da
|
|
||||||
`DSC-0003 / packed-cartridge-loader-pmc` e nao deve bloquear a prova inicial
|
|
||||||
de troca `Shell/Hub -> Game`.
|
|
||||||
|
|
||||||
Tambem precisa ficar claro que `run_cart`, se existir, nao e o orquestrador da
|
|
||||||
troca. No boot direto por linha de comando, carregar um cartucho e simples
|
|
||||||
porque o runtime nasce ja apontado para aquele jogo. Com o SO em execucao, o
|
|
||||||
caso real e diferente: pode haver um Game residente/rodando, o usuario volta
|
|
||||||
para Home, e o sistema decide iniciar outro Game. Nesse caso o SO precisa
|
|
||||||
orquestrar fechamento/suspensao descartada do app atual, limpeza de estado,
|
|
||||||
resolucao do novo alvo, carregamento e transicao para o proximo estado de
|
|
||||||
firmware. O carregador de cartucho e apenas uma etapa desse fluxo.
|
|
||||||
|
|
||||||
A direcao preferida e que a orquestracao de troca de cartucho viva no
|
|
||||||
SystemOS. Porem, essa agenda nao deve capturar o caso `Game -> Home -> mesmo
|
|
||||||
Game`: esse e o escopo da `AGD-0041`, que precisa fechar foreground,
|
|
||||||
pausa/suspensao e retorno ao mesmo Game. A troca `Home -> outro Game`, com
|
|
||||||
fechamento do jogo atual e carregamento de outro cartucho, pode merecer uma
|
|
||||||
agenda propria depois da `AGD-0041`, derivada do contrato de foreground que ela
|
|
||||||
fechar.
|
|
||||||
|
|
||||||
## O Que Precisa Ser Definido
|
|
||||||
|
|
||||||
1. Semântica da operação.
|
|
||||||
O que significa "run cart" quando existe SO: trocar imediatamente,
|
|
||||||
agendar para o próximo frame, iniciar uma transicao orquestrada pelo
|
|
||||||
sistema, ou apenas carregar bytes de cartucho como etapa interna?
|
|
||||||
|
|
||||||
2. Origem do alvo.
|
|
||||||
Como o guest identifica o cartucho alvo: id numérico, nome canônico, path virtual, handle, manifesto, ou nenhum argumento nesta primeira versão?
|
|
||||||
Para v1, uma opcao aceitavel e limitar a resolucao a alvos conhecidos pelo host/test harness e carregaveis pelo loader de diretorio, deixando `.pmc` fora do caminho critico.
|
|
||||||
|
|
||||||
3. Modelo de segurança.
|
|
||||||
Nenhum app/userland deve chamar `run_cart`. O sistema/firmware e o caminho
|
|
||||||
host/CLI/debug devem ser as unicas autoridades para iniciar cartuchos.
|
|
||||||
Se apps precisarem solicitar navegacao no futuro, isso deve ser uma
|
|
||||||
superficie nova e mediada pelo sistema.
|
|
||||||
|
|
||||||
4. Ponto de integração.
|
|
||||||
Onde a transição vive: `VirtualMachineRuntime`, firmware, host, SystemOS,
|
|
||||||
ou combinação dos três? Para esta agenda, a decisao minima e separar o boot
|
|
||||||
direto host/CLI/debug da ABI guest. A orquestracao `Home -> outro Game`
|
|
||||||
pertence a `DSC-0043 / AGD-0044`.
|
|
||||||
|
|
||||||
5. Efeitos observáveis.
|
|
||||||
O que acontece quando um guest tenta chamar a superficie removida, e como
|
|
||||||
ferramentas/boot direto continuam carregando cartuchos sem depender de uma
|
|
||||||
syscall userland?
|
|
||||||
|
|
||||||
6. Contrato de erro.
|
|
||||||
Remocao da ABI significa erro de build/declaracao, syscall desconhecida,
|
|
||||||
ou bloqueio em registro/capability ate a limpeza completa das declaracoes?
|
|
||||||
|
|
||||||
## O Que Necessita Para Resolver
|
|
||||||
|
|
||||||
- remocao de `system.run_cart` da ABI userland;
|
|
||||||
- definicao de que boot direto continua por caminho host/CLI/debug, nao por
|
|
||||||
syscall guest;
|
|
||||||
- separacao explicita entre boot direto, loader interno e orquestracao
|
|
||||||
`Home -> outro Game` da `DSC-0043 / AGD-0044`;
|
|
||||||
- testes garantindo que guest/userland nao pode declarar/chamar `run_cart`;
|
|
||||||
- testes garantindo que boot direto de cartucho continua funcional.
|
|
||||||
|
|
||||||
## Fora de Escopo
|
|
||||||
|
|
||||||
- catálogo completo de apps instalados;
|
|
||||||
- UX final do launcher/hub;
|
|
||||||
- resolução remota ou download de cartuchos;
|
|
||||||
- política de marketplace/distribuição.
|
|
||||||
- obrigatoriedade de boot a partir de `.pmc` no primeiro fluxo funcional.
|
|
||||||
|
|
||||||
## Sugestao / Recomendacao
|
|
||||||
|
|
||||||
Recomendo remover `system.run_cart` da ABI userland para v1. Nao ha necessidade
|
|
||||||
de compatibilidade com a superficie atual: ela nao deve permanecer como stub,
|
|
||||||
syscall reservada chamavel por guest, nem sucesso vazio.
|
|
||||||
|
|
||||||
Rodar cartuchos deve ser uma operacao interna do SystemOS/firmware ou do
|
|
||||||
caminho host/CLI/debug, nunca uma syscall de app. O boot direto deve continuar
|
|
||||||
existindo porque e o fluxo essencial para testar cartuchos em desenvolvimento e
|
|
||||||
tambem representa o modo futuro de executar um jogo unico, como em uma
|
|
||||||
integracao tipo Steam.
|
|
||||||
|
|
||||||
Recomendo tambem separar dois conceitos:
|
|
||||||
|
|
||||||
- **boot direto:** usado por linha de comando/debug, inicia o runtime ja com um
|
|
||||||
cartucho alvo e pode continuar simples;
|
|
||||||
- **troca via SO:** fluxo orquestrado pelo SystemOS, que fecha o app
|
|
||||||
atual quando necessario, limpa estado cartridge-scoped, resolve o proximo
|
|
||||||
alvo e so entao chama o carregador.
|
|
||||||
|
|
||||||
Essa agenda nao deve implementar o fluxo `Game -> Home -> mesmo Game`; esse
|
|
||||||
trabalho pertence a `AGD-0041`. Depois dela, a troca `Home -> outro Game` deve
|
|
||||||
ser aberta ou refinada como discussao propria, porque adiciona fechamento do
|
|
||||||
jogo atual, limpeza cartridge-scoped, resolucao de novo alvo e falhas de load.
|
|
||||||
|
|
||||||
Se a plataforma precisar de uma ação solicitável por apps no futuro, ela deve
|
|
||||||
ser modelada separadamente como pedido de navegação mediado pelo sistema, com
|
|
||||||
nome e erros que não prometam boot direto.
|
|
||||||
|
|
||||||
## Respostas Atuais
|
|
||||||
|
|
||||||
- `system.run_cart` deve ser removido da ABI userland.
|
|
||||||
- Nao precisamos manter compatibilidade com a superficie atual.
|
|
||||||
- Nao deve existir syscall publica para app iniciar cartucho.
|
|
||||||
- Boot direto por linha de comando, host, debug ou fluxo equivalente de jogo
|
|
||||||
unico deve permanecer.
|
|
||||||
- O carregamento interno pode continuar usando loader ja disponivel, incluindo
|
|
||||||
cartucho em diretorio/fixture.
|
|
||||||
- `.pmc`, catalogo, UX final de launcher e troca `Game A -> Home -> Game B`
|
|
||||||
ficam fora desta agenda.
|
|
||||||
- Se no futuro apps precisarem pedir navegacao, isso deve ser uma nova
|
|
||||||
superficie mediada pelo sistema, nao a volta de `run_cart` userland.
|
|
||||||
|
|
||||||
## Critério de Saida Desta Agenda
|
|
||||||
|
|
||||||
Esta agenda só pode virar PR de implementação quando existir decisão escrita para:
|
|
||||||
|
|
||||||
- retirada da superfície userland atual;
|
|
||||||
- preservacao explicita do boot direto host/CLI/debug;
|
|
||||||
- comportamento esperado para declaracao/chamada guest obsoleta;
|
|
||||||
- fronteira com `AGD-0041` e `AGD-0044`;
|
|
||||||
- cobertura minima de testes para remocao userland e boot direto.
|
|
||||||
|
|
||||||
## Discussao
|
|
||||||
|
|
||||||
- 2026-07-03: A agenda deve ser aberta antes da `AGD-0041` como habilitadora
|
|
||||||
de validacao do ciclo `Shell/Hub -> Game`. Ficou definido como premissa de
|
|
||||||
agenda que o primeiro `system.run_cart` testavel nao depende de `.pmc`; ele
|
|
||||||
pode usar cartucho em diretorio ou fixture resolvida pelo host/test harness.
|
|
||||||
- 2026-07-03: Direcao ajustada: `run_cart` nao deve ser uma operacao userland.
|
|
||||||
A autoridade de iniciar cartuchos deve pertencer ao sistema/firmware; apps
|
|
||||||
podem, no maximo, solicitar navegacao por uma superficie separada e mediada.
|
|
||||||
- 2026-07-03: Direcao refinada: `run_cart` simples nao resolve o caso com SO.
|
|
||||||
Boot direto por linha de comando continua sendo um caminho simples, mas
|
|
||||||
iniciar outro jogo a partir do Home exige um orquestrador do SO/firmware que
|
|
||||||
fecha o app atual, limpa estado e so entao carrega o novo cartucho.
|
|
||||||
- 2026-07-03: Escopo refinado: `Game -> Home -> mesmo Game` pertence a
|
|
||||||
`AGD-0041`. A agenda atual nao deve absorver esse trabalho. Depois da
|
|
||||||
`AGD-0041`, a troca `Home -> outro Game` pode ser aberta ou refinada como
|
|
||||||
agenda propria para o orquestrador de troca de cartucho no SystemOS.
|
|
||||||
- 2026-07-03: A troca `Game A -> Home -> Game B` foi separada para
|
|
||||||
`DSC-0043 / AGD-0044`, mantendo esta agenda focada na superficie
|
|
||||||
`run_cart`/loader e sua remocao ou restricao como operacao userland.
|
|
||||||
- 2026-07-03: Direcao aceita para esta agenda: remover `system.run_cart` da ABI
|
|
||||||
userland sem necessidade de compatibilidade, manter boot direto para
|
|
||||||
CLI/debug/teste de cartuchos e futuro modo de jogo unico, e deixar navegacao
|
|
||||||
mediada por apps para uma superficie futura separada se ela vier a existir.
|
|
||||||
@@ -1,126 +0,0 @@
|
|||||||
---
|
|
||||||
id: AGD-0041
|
|
||||||
ticket: foreground-stack-game-pause-shell-vm-backed
|
|
||||||
title: Foreground Stack, Game Pause, and VM-Backed Shell Coexistence
|
|
||||||
status: open
|
|
||||||
created: 2026-06-05
|
|
||||||
resolved:
|
|
||||||
decision:
|
|
||||||
tags: [runtime, os, lifecycle, shell, game, vm, foreground, architecture]
|
|
||||||
---
|
|
||||||
|
|
||||||
## Contexto
|
|
||||||
|
|
||||||
Durante a discussao da `DSC-0040` sobre separar VM e render worker, surgiu um caso que nao pertence somente ao render: `Game -> Shell -> Game`.
|
|
||||||
|
|
||||||
O caso minimo e:
|
|
||||||
|
|
||||||
- um Game esta rodando;
|
|
||||||
- o usuario aperta Home;
|
|
||||||
- o Game deve sair do foreground sem ser encerrado;
|
|
||||||
- o Hub/Shell assume a tela;
|
|
||||||
- o usuario pode abrir um app Shell, inclusive VM-backed;
|
|
||||||
- depois o usuario retorna ao mesmo Game.
|
|
||||||
|
|
||||||
O render worker precisa saber qual visual owner pode apresentar frames, mas a decisao principal e de lifecycle: quais VMs existem, quais podem executar, o que significa pausar um Game, e como Shell apps coexistem com um Game pausado.
|
|
||||||
|
|
||||||
Material relacionado:
|
|
||||||
|
|
||||||
- `DSC-0031`: separacao entre perfis Game e System/Shell.
|
|
||||||
- `DSC-0032`: SystemOS como autoridade de lifecycle/process/task.
|
|
||||||
- `DSC-0035`: janelas Shell pertencem a tasks e definem liveness do app.
|
|
||||||
- `DSC-0036`: Hub/Shell prova fatias de lifecycle.
|
|
||||||
- `DSC-0040`: render ownership/epoch durante transicoes e paralelismo VM/render.
|
|
||||||
|
|
||||||
## Problema
|
|
||||||
|
|
||||||
Precisamos definir o contrato de foreground para impedir ambiguidades como:
|
|
||||||
|
|
||||||
- Game pausado continuando a executar frames logicos enquanto Shell esta no foreground;
|
|
||||||
- Shell VM-backed competindo com Game por pacing, input, superficie ou render ownership;
|
|
||||||
- multiplos Shells foreground ou multiplos Games ativos sem uma politica explicita;
|
|
||||||
- retorno ao Game sem clareza sobre estado pausado, input, render invalidation e retomada da VM.
|
|
||||||
|
|
||||||
Sem esse contrato, a separacao VM/render da `DSC-0040` pode ficar tecnicamente correta, mas o SystemOS ainda pode permitir estados incoerentes.
|
|
||||||
|
|
||||||
## Pontos Criticos
|
|
||||||
|
|
||||||
- Existe apenas um foreground visual owner por vez.
|
|
||||||
- Background execution e outro assunto e deve ficar fora da primeira decisao, salvo se for necessario definir uma proibicao explicita.
|
|
||||||
- Shell VM-backed nao deve herdar politica de game loop so por usar VM.
|
|
||||||
- Game pausado provavelmente deve reter estado, mas nao deve consumir frames logicos.
|
|
||||||
- O Hub/Shell precisa ser capaz de rodar enquanto o Game esta suspenso.
|
|
||||||
- A transicao deve invalidar render submissions antigas para impedir present de frames obsoletos.
|
|
||||||
- O modelo precisa caber no SystemOS/lifecycle existente, nao diretamente no render worker.
|
|
||||||
|
|
||||||
## Opcoes
|
|
||||||
|
|
||||||
### Opcao A - Foreground unico, Game suspenso, Shell unico
|
|
||||||
|
|
||||||
- **Abordagem:** permitir no maximo um Game carregado e no maximo um Shell foreground; ao apertar Home, o Game entra em estado pausado/suspenso e Shell/Hub assume o foreground. Shell VM-backed pode executar apenas enquanto for o foreground Shell.
|
|
||||||
- **Pro:** modelo simples, previsivel e alinhado com console; reduz concorrencia real entre VMs; combina com a regra de render ownership unico.
|
|
||||||
- **Contra:** nao cobre multitarefa/background; futuras features de overlay ou apps persistentes precisarao expandir o contrato.
|
|
||||||
- **Manutenibilidade:** alta; SystemOS pode modelar uma pilha pequena de foreground/suspended sem virar scheduler generico.
|
|
||||||
|
|
||||||
### Opcao B - Multiplas VMs residentes, somente foreground executa
|
|
||||||
|
|
||||||
- **Abordagem:** permitir que Game e Shell VM-backed coexistam como VMs residentes, mas somente a entidade foreground executa. O Game pausado fica residente, sem tick; Shell VM-backed roda sob lifecycle Shell.
|
|
||||||
- **Pro:** preserva estado e permite retorno rapido; nao exige background execution.
|
|
||||||
- **Contra:** precisa contrato claro de memoria, ownership de input, foco, cancelamento e fechamento.
|
|
||||||
- **Manutenibilidade:** boa se os estados forem explicitos; ruim se a residencia for confundida com execucao em background.
|
|
||||||
|
|
||||||
### Opcao C - Encerrar Game ao entrar no Shell VM-backed
|
|
||||||
|
|
||||||
- **Abordagem:** Home fecha/salva o Game antes de abrir Shell VM-backed, evitando coexistencia.
|
|
||||||
- **Pro:** simplifica o runtime.
|
|
||||||
- **Contra:** quebra a expectativa de console moderno; torna `Game -> Shell -> Game` um reload, nao uma pausa.
|
|
||||||
- **Manutenibilidade:** simples no curto prazo, mas provavelmente gera mais excecoes e UX ruim depois.
|
|
||||||
|
|
||||||
### Opcao D - Background real desde ja
|
|
||||||
|
|
||||||
- **Abordagem:** permitir Game pausado ou Shell apps rodando em background com politicas de prioridade.
|
|
||||||
- **Pro:** cobre casos futuros ricos.
|
|
||||||
- **Contra:** amplia demais escopo: scheduler, budget, energia, audio, input, IO e memoria.
|
|
||||||
- **Manutenibilidade:** baixa para v1; mistura a decisao de foreground com multitarefa real.
|
|
||||||
|
|
||||||
## Sugestao / Recomendacao
|
|
||||||
|
|
||||||
Recomendo seguir com a combinacao das opcoes A e B:
|
|
||||||
|
|
||||||
- somente um Game residente por vez;
|
|
||||||
- somente um Shell foreground por vez;
|
|
||||||
- Game pode ficar pausado/suspenso enquanto Shell esta foreground;
|
|
||||||
- Shell VM-backed pode existir junto com Game pausado, mas segue lifecycle Shell;
|
|
||||||
- somente o owner foreground executa VM/tick/event loop conforme sua politica;
|
|
||||||
- background execution fica explicitamente fora de escopo;
|
|
||||||
- render ownership muda junto com foreground owner e deve invalidar submissions antigas via epoch/generation, conforme `DSC-0040`.
|
|
||||||
|
|
||||||
Isso preserva o ciclo `Game -> Home/Shell -> Game` sem transformar o runtime em multitarefa geral agora.
|
|
||||||
|
|
||||||
## Perguntas em Aberto
|
|
||||||
|
|
||||||
- [ ] Qual e o nome canonico dos estados de Game fora do foreground: `Paused`, `Suspended`, ambos, ou outro?
|
|
||||||
- [ ] Ao apertar Home, o Game deve receber um evento/interrupt/trap de pausa antes de parar de executar?
|
|
||||||
- [ ] O Hub e um Shell especial sempre presente ou uma task Shell comum?
|
|
||||||
- [ ] Um app Shell VM-backed pode substituir o Hub no foreground ou o Hub permanece como owner raiz?
|
|
||||||
- [ ] Quando o Shell VM-backed fecha, o retorno vai sempre para Hub ou pode voltar diretamente ao Game?
|
|
||||||
- [ ] O input do Game e drenado/limpo ao pausar e ao retomar?
|
|
||||||
- [ ] Audio do Game pausa junto com a VM ou tem politica propria?
|
|
||||||
- [ ] Existe limite de memoria/residencia para manter Game pausado enquanto Shell app roda?
|
|
||||||
- [ ] O retorno ao Game exige novo frame antes de trocar a superficie, ou a tela pode manter Hub/Shell ate a primeira submission valida?
|
|
||||||
- [ ] Quais eventos de lifecycle precisam ser visiveis para firmware, OS, VM e host?
|
|
||||||
|
|
||||||
## Criterio para Encerrar
|
|
||||||
|
|
||||||
A agenda pode ser encerrada quando tivermos uma decisao clara sobre:
|
|
||||||
|
|
||||||
- cardinalidade de Games e Shells residentes/foreground;
|
|
||||||
- semantica de Game pausado/suspenso;
|
|
||||||
- politica de execucao para Shell VM-backed durante Game pausado;
|
|
||||||
- regra de foreground visual owner e render invalidation;
|
|
||||||
- comportamento minimo do ciclo `Game -> Shell -> Game`;
|
|
||||||
- itens explicitamente fora de escopo, especialmente background execution real.
|
|
||||||
|
|
||||||
## Discussao
|
|
||||||
|
|
||||||
- 2026-06-05: Agenda criada a partir da `DSC-0040`, quando o caso de Shell VM-backed aberto sobre um Game pausado mostrou que a discussao pertence ao lifecycle/SystemOS, nao apenas ao render worker.
|
|
||||||
@@ -1,145 +0,0 @@
|
|||||||
---
|
|
||||||
id: AGD-0044
|
|
||||||
ticket: system-os-cartridge-switch-orchestrator
|
|
||||||
title: SystemOS Cartridge Switch Orchestrator
|
|
||||||
status: open
|
|
||||||
created: 2026-07-03
|
|
||||||
resolved:
|
|
||||||
decision:
|
|
||||||
tags: [runtime, os, lifecycle, game, cartridge, architecture]
|
|
||||||
---
|
|
||||||
|
|
||||||
## Contexto
|
|
||||||
|
|
||||||
A `AGD-0041` cobre o caso `Game -> Home/Shell -> mesmo Game`: o usuario sai do
|
|
||||||
foreground do jogo, o SO assume a tela, Shell/Hub pode rodar, e depois o mesmo
|
|
||||||
Game e retomado.
|
|
||||||
|
|
||||||
Existe um segundo caso, diferente, que nao deve ser escondido dentro da
|
|
||||||
`AGD-0041`: `Game A -> Home -> Game B`.
|
|
||||||
|
|
||||||
Nesse fluxo, o usuario esta com um Game rodando, aperta Home, volta para o SO e
|
|
||||||
pede para iniciar outro jogo. O SystemOS nao deve simplesmente chamar um loader
|
|
||||||
por cima do estado atual. Ele precisa orquestrar a substituicao do app corrente:
|
|
||||||
fechar ou descartar o Game residente, limpar estado cartridge-scoped, resolver o
|
|
||||||
novo alvo, carregar o proximo cartucho e entrar no novo estado de firmware.
|
|
||||||
|
|
||||||
Essa agenda tambem se relaciona com a `AGD-0003 / system-run-cart`: `run_cart`,
|
|
||||||
se existir, nao e userland e nao e o orquestrador. O carregador de cartucho e
|
|
||||||
apenas uma etapa dentro de uma transicao comandada pelo SystemOS.
|
|
||||||
|
|
||||||
## Problema
|
|
||||||
|
|
||||||
Sem um orquestrador explicito de troca de cartucho no SystemOS, a plataforma
|
|
||||||
pode cair em estados incoerentes:
|
|
||||||
|
|
||||||
- carregar um novo Game sem fechar corretamente o Game anterior;
|
|
||||||
- reaproveitar estado VM, assets, input, audio, render ou telemetria do cartucho
|
|
||||||
anterior;
|
|
||||||
- misturar boot direto por linha de comando com troca de app sob o SO;
|
|
||||||
- deixar o loader decidir lifecycle, quando ele deveria apenas materializar o
|
|
||||||
cartucho alvo;
|
|
||||||
- tentar implementar `Home -> outro Game` antes de existir o contrato de
|
|
||||||
foreground/pausa definido pela `AGD-0041`.
|
|
||||||
|
|
||||||
## Pontos Criticos
|
|
||||||
|
|
||||||
- Esta agenda deve ser executada depois da `AGD-0041`.
|
|
||||||
- `Game -> Home -> mesmo Game` fica fora desta agenda.
|
|
||||||
- O SystemOS deve ser a autoridade da troca entre cartuchos sob o SO.
|
|
||||||
- O loader nao deve possuir politica de fechamento, pausa, foreground ou
|
|
||||||
cleanup.
|
|
||||||
- Boot direto por CLI/debug continua sendo caminho separado e mais simples.
|
|
||||||
- A troca para outro Game deve tratar falha de load sem deixar o sistema em
|
|
||||||
estado parcialmente substituido.
|
|
||||||
- `.pmc`, catalogo completo e UX final de launcher continuam fora de escopo,
|
|
||||||
salvo se forem necessarios para definir o contrato minimo.
|
|
||||||
|
|
||||||
## Opcoes
|
|
||||||
|
|
||||||
### Opcao A - Adiar tudo para depois da AGD-0041
|
|
||||||
|
|
||||||
- **Abordagem:** manter esta agenda como registro de escopo futuro; primeiro
|
|
||||||
fechar e implementar o contrato `Game -> Home -> mesmo Game`.
|
|
||||||
- **Pro:** evita misturar pausa/resume com substituicao de cartucho; reduz risco
|
|
||||||
de reabrir arquitetura durante a `AGD-0041`.
|
|
||||||
- **Contra:** a plataforma continua sem troca `Home -> outro Game` ate uma etapa
|
|
||||||
posterior.
|
|
||||||
- **Manutenibilidade:** alta, porque cada agenda fecha um eixo de lifecycle.
|
|
||||||
|
|
||||||
### Opcao B - Definir agora o contrato conceitual, implementar depois
|
|
||||||
|
|
||||||
- **Abordagem:** fechar uma decisao curta ja dizendo que o orquestrador pertence
|
|
||||||
ao SystemOS, que `run_cart` nao e userland, e que a execucao depende da
|
|
||||||
`AGD-0041`; o plano de codigo fica para depois.
|
|
||||||
- **Pro:** reduz ambiguidade enquanto trabalhamos na `AGD-0041`.
|
|
||||||
- **Contra:** pode produzir uma decisao com pouca evidencia operacional antes
|
|
||||||
do contrato de foreground estar fechado.
|
|
||||||
- **Manutenibilidade:** boa se a decisao for claramente marcada como dependente
|
|
||||||
da `AGD-0041`.
|
|
||||||
|
|
||||||
### Opcao C - Implementar o orquestrador completo agora
|
|
||||||
|
|
||||||
- **Abordagem:** tentar resolver `Game A -> Home -> Game B` antes ou junto da
|
|
||||||
`AGD-0041`.
|
|
||||||
- **Pro:** ataca o fluxo final diretamente.
|
|
||||||
- **Contra:** mistura pausa/resume, fechamento, cleanup, resolucao de alvo e
|
|
||||||
falha de load em uma unica frente; alto risco de contrato instavel.
|
|
||||||
- **Manutenibilidade:** baixa para v1, porque a troca completa depende do
|
|
||||||
contrato de foreground ainda aberto.
|
|
||||||
|
|
||||||
## Sugestao / Recomendacao
|
|
||||||
|
|
||||||
Recomendo a Opcao A agora, com esta agenda aberta como marcador explicito de
|
|
||||||
escopo futuro.
|
|
||||||
|
|
||||||
A ordem preferida passa a ser:
|
|
||||||
|
|
||||||
1. fechar a `AGD-0041` para definir foreground, pausa/suspensao, Shell no
|
|
||||||
foreground e retorno ao mesmo Game;
|
|
||||||
2. voltar para esta agenda e decidir o contrato do orquestrador de troca de
|
|
||||||
cartucho no SystemOS;
|
|
||||||
3. so entao planejar a execucao de `Game A -> Home -> Game B`.
|
|
||||||
|
|
||||||
Se durante a `AGD-0041` aparecer uma decisao que exige antecipar parte do
|
|
||||||
orquestrador, esta agenda deve ser reaberta/atualizada com a dependencia
|
|
||||||
concreta em vez de esconder a troca de cartucho dentro da agenda de foreground.
|
|
||||||
|
|
||||||
## Perguntas em Aberto
|
|
||||||
|
|
||||||
- [ ] Depois da `AGD-0041`, qual estado representa um Game que sera descartado
|
|
||||||
em vez de retomado?
|
|
||||||
- [ ] O fechamento do Game atual e observavel para o firmware/game, ou e uma
|
|
||||||
destruicao interna do SystemOS?
|
|
||||||
- [ ] Quais estados cartridge-scoped devem ser limpos antes do novo load: VM,
|
|
||||||
assets, FS handles, input, audio, render ownership, telemetry, logs?
|
|
||||||
- [ ] Se o novo cartucho falha ao carregar, o sistema volta ao Home, mostra uma
|
|
||||||
tela de erro, ou tenta preservar o Game anterior?
|
|
||||||
- [ ] Como a resolucao do novo alvo e representada sem depender de catalogo
|
|
||||||
completo ou `.pmc`?
|
|
||||||
- [ ] Qual evidencia minima prova `Game A -> Home -> Game B` sem depender de UX
|
|
||||||
final de launcher?
|
|
||||||
|
|
||||||
## Criterio para Encerrar
|
|
||||||
|
|
||||||
A agenda pode virar decisao quando:
|
|
||||||
|
|
||||||
- a `AGD-0041` tiver fechado o contrato de foreground/pausa/resume;
|
|
||||||
- estiver claro que o orquestrador pertence ao SystemOS;
|
|
||||||
- `run_cart`/loader estiver limitado a etapa interna, nao userland;
|
|
||||||
- existir regra para fechar/descartar o Game atual;
|
|
||||||
- existir contrato de limpeza de estado cartridge-scoped;
|
|
||||||
- existir politica para falha de carregamento do novo Game;
|
|
||||||
- houver criterio de teste minimo para `Game A -> Home -> Game B`.
|
|
||||||
|
|
||||||
## Discussao
|
|
||||||
|
|
||||||
- 2026-07-03: Agenda criada a partir da separacao entre `AGD-0041`
|
|
||||||
(`Game -> Home -> mesmo Game`) e `AGD-0003` (`run_cart`/loader nao userland).
|
|
||||||
O novo escopo cobre a troca posterior `Game A -> Home -> Game B`, com
|
|
||||||
orquestracao pelo SystemOS depois que o contrato de foreground estiver
|
|
||||||
fechado.
|
|
||||||
|
|
||||||
## Resolution
|
|
||||||
|
|
||||||
Ainda em aberto.
|
|
||||||
@@ -1,161 +0,0 @@
|
|||||||
---
|
|
||||||
id: AGD-0045
|
|
||||||
ticket: system-run-cart
|
|
||||||
title: SystemOS Library Root and Home Game Launch
|
|
||||||
status: accepted
|
|
||||||
created: 2026-07-03
|
|
||||||
resolved:
|
|
||||||
decision:
|
|
||||||
tags: [runtime, os, hub, cartridge, launcher, library, game, architecture]
|
|
||||||
---
|
|
||||||
|
|
||||||
## Contexto
|
|
||||||
|
|
||||||
A `DEC-0035` fechou que `system.run_cart` nao deve existir como syscall
|
|
||||||
userland e que boot direto por host/CLI/debug deve permanecer.
|
|
||||||
|
|
||||||
Isso resolveu a autoridade negativa, mas ainda nao resolveu a experiencia
|
|
||||||
desejada para o SO: apontar o runtime para um diretorio raiz de biblioteca,
|
|
||||||
fazer a Home listar os cartuchos encontrados ali e permitir que o usuario clique
|
|
||||||
em um jogo para carrega-lo.
|
|
||||||
|
|
||||||
O objetivo pratico e um "Switch feio": uma lista simples na Home, sem UX final,
|
|
||||||
sem marketplace e sem catalogo rico, mas capaz de provar que o SO, e nao o
|
|
||||||
guest, escolhe e carrega um cartucho a partir de uma biblioteca local.
|
|
||||||
|
|
||||||
## Problema
|
|
||||||
|
|
||||||
Hoje temos dois caminhos separados:
|
|
||||||
|
|
||||||
- boot direto por `--run <cart>` funciona e carrega um cartucho unico;
|
|
||||||
- Hub/Home existe, mas mostra acoes fixas de Shell nativo e nao lista jogos de
|
|
||||||
uma biblioteca real.
|
|
||||||
|
|
||||||
Sem uma biblioteca de cartuchos visivel para o SO, o usuario nao consegue
|
|
||||||
iniciar jogos a partir da Home. Isso deixa a agenda `system-run-cart` incompleta
|
|
||||||
do ponto de vista de produto: removemos o `run_cart` userland, mas ainda falta a
|
|
||||||
alternativa correta, que e o SO iniciar cartuchos por acao de usuario.
|
|
||||||
|
|
||||||
## Pontos Criticos
|
|
||||||
|
|
||||||
- O root da biblioteca deve ser fornecido pelo host como `--games-root <dir>`.
|
|
||||||
- O scan inicial deve cobrir subdiretorios imediatos com `manifest.json`.
|
|
||||||
- O loader de diretorio existente deve continuar sendo a autoridade para validar
|
|
||||||
cartucho completo; a biblioteca pode ler metadados minimos para listagem.
|
|
||||||
- A Home pode mostrar uma lista feia/clicavel; polimento visual fica fora.
|
|
||||||
- O clique em um Game deve iniciar `LoadCartridge` pelo firmware/SystemOS, nao
|
|
||||||
por syscall guest.
|
|
||||||
- V1 nao precisa tratar retorno de um Game para Home, porque isso pertence a
|
|
||||||
`AGD-0041`.
|
|
||||||
- `.pmc`, outros tipos de app, catalogo remoto, marketplace, icones, busca e
|
|
||||||
metadados ricos ficam fora.
|
|
||||||
|
|
||||||
## Opcoes
|
|
||||||
|
|
||||||
### Opcao A - Biblioteca apenas para listagem
|
|
||||||
|
|
||||||
- **Abordagem:** adicionar `--games-root`, escanear manifestos e mostrar jogos
|
|
||||||
na Home, mas sem permitir launch ainda.
|
|
||||||
- **Pro:** baixa complexidade; prova descoberta/catalogo local.
|
|
||||||
- **Contra:** nao entrega o objetivo principal de carregar jogo pela Home.
|
|
||||||
- **Manutenibilidade:** boa, mas valor funcional limitado.
|
|
||||||
|
|
||||||
### Opcao B - Home lista biblioteca e carrega Game quando nao ha Game ativo
|
|
||||||
|
|
||||||
- **Abordagem:** adicionar `--games-root`, escanear cartuchos locais, renderizar
|
|
||||||
lista simples na Home e permitir clique para carregar um Game via
|
|
||||||
`LoadCartridge`. A primeira versao cobre Home inicial/sem Game residente.
|
|
||||||
- **Pro:** entrega o fluxo desejado sem abrir troca completa entre jogos.
|
|
||||||
- **Contra:** exige passar biblioteca/acao selecionada entre host, Hub,
|
|
||||||
firmware e loader.
|
|
||||||
- **Manutenibilidade:** boa se a fronteira ficar clara: biblioteca descobre,
|
|
||||||
Hub escolhe, firmware carrega.
|
|
||||||
|
|
||||||
### Opcao C - Biblioteca mais troca completa entre jogos
|
|
||||||
|
|
||||||
- **Abordagem:** Home lista biblioteca e tambem permite `Game A -> Home ->
|
|
||||||
Game B` ja no primeiro passo.
|
|
||||||
- **Pro:** cobre a experiencia final.
|
|
||||||
- **Contra:** mistura biblioteca com pausa, fechamento, cleanup e falha de load;
|
|
||||||
depende de `AGD-0041` e `AGD-0044`.
|
|
||||||
- **Manutenibilidade:** baixa para v1.
|
|
||||||
|
|
||||||
## Sugestao / Recomendacao
|
|
||||||
|
|
||||||
Recomendo a Opcao B.
|
|
||||||
|
|
||||||
O v1 deve permitir:
|
|
||||||
|
|
||||||
- host recebe `--games-root <dir>`;
|
|
||||||
- o SO/Hub recebe uma lista de cartuchos descobertos;
|
|
||||||
- a Home mostra uma lista simples/clicavel de jogos;
|
|
||||||
- clicar em um Game carrega o cartucho via firmware `LoadCartridge`;
|
|
||||||
- boot direto por `--run <cart>` continua separado e intacto;
|
|
||||||
- nenhum guest/app chama `run_cart`;
|
|
||||||
- o escopo v1 acontece na Home inicial; retorno de Game para Home fica para
|
|
||||||
`AGD-0041`, e troca `Game A -> Home -> Game B` fica para `AGD-0044`.
|
|
||||||
|
|
||||||
Detalhes aceitos para v1:
|
|
||||||
|
|
||||||
- scan apenas de subdiretorios imediatos;
|
|
||||||
- somente cartuchos `app_mode: Game`;
|
|
||||||
- `.pmc` fica para futuro;
|
|
||||||
- cartuchos invalidos sao logados e omitidos da lista;
|
|
||||||
- o modelo interno deve ser uma entry de biblioteca expansivel, nao apenas um
|
|
||||||
summary de UI. A entry pode manter o manifest carregado em memoria, path
|
|
||||||
interno necessario para launch e metadados operacionais como instante de
|
|
||||||
descoberta/instalacao. A UI v1 mostra apenas `title`, `app_id` e
|
|
||||||
`app_version`, mas futuros metadados ingeridos pela biblioteca poderao ser
|
|
||||||
usados pelo catalogo e pela propria UI;
|
|
||||||
- clique carrega imediatamente, sem confirmacao;
|
|
||||||
- falha de load volta para Home e registra log/erro.
|
|
||||||
|
|
||||||
Essa agenda deve produzir a alternativa correta ao `run_cart` userland: uma
|
|
||||||
acao de sistema, iniciada pela Home, que carrega cartucho escolhido pelo usuario
|
|
||||||
a partir de uma biblioteca local.
|
|
||||||
|
|
||||||
## Perguntas em Aberto
|
|
||||||
|
|
||||||
- [x] O argumento deve se chamar `--games-root`.
|
|
||||||
- [x] A biblioteca deve escanear apenas subdiretorios imediatos.
|
|
||||||
- [x] A listagem v1 deve incluir apenas `app_mode: Game`.
|
|
||||||
- [x] O scan deve logar cartuchos invalidos e omiti-los da lista.
|
|
||||||
- [x] O Hub/SystemOS deve receber uma entry de biblioteca expansivel, capaz de
|
|
||||||
manter o manifest carregado, path interno para launch e metadados
|
|
||||||
operacionais como timestamp de descoberta/instalacao. A UI v1 so precisa
|
|
||||||
mostrar `title`, `app_id` e `app_version`.
|
|
||||||
- [x] O clique deve carregar imediatamente, sem confirmacao.
|
|
||||||
- [x] Se um cartucho falha ao carregar, o sistema volta para Home e registra
|
|
||||||
erro/log.
|
|
||||||
- [x] Retorno de Game para Home nao pertence a esta agenda; fica para
|
|
||||||
`AGD-0041`.
|
|
||||||
- [x] O teste minimo deve provar o fluxo `games-root -> Home list -> click ->
|
|
||||||
LoadCartridge -> GameRunning`?
|
|
||||||
|
|
||||||
## Criterio para Encerrar
|
|
||||||
|
|
||||||
A agenda pode virar decisao quando estiver claro:
|
|
||||||
|
|
||||||
- nome e semantica do argumento de host para root da biblioteca;
|
|
||||||
- escopo do scan e metadados minimos;
|
|
||||||
- fronteira entre biblioteca, Hub, firmware e loader;
|
|
||||||
- politica v1 para cartuchos invalidos;
|
|
||||||
- regra v1 para launch quando nao ha Game ativo;
|
|
||||||
- fronteira explicita com `AGD-0041` e `AGD-0044`;
|
|
||||||
- testes minimos para discovery e launch pela Home.
|
|
||||||
|
|
||||||
## Discussao
|
|
||||||
|
|
||||||
- 2026-07-03: Agenda criada como continuacao da `DSC-0004` apos a `DEC-0035`.
|
|
||||||
A decisao anterior removeu `run_cart` userland; esta agenda define o caminho
|
|
||||||
correto para o SO/Home carregar jogos a partir de uma biblioteca local.
|
|
||||||
- 2026-07-03: Respostas aceitas: usar `--games-root`, escanear apenas
|
|
||||||
subdiretorios imediatos, listar somente Games, deixar `.pmc` e outros apps
|
|
||||||
para depois, logar/omitir invalidos, usar summary com `title`, `app_id` e
|
|
||||||
`app_version`, carregar imediatamente no clique, e deixar retorno para Home
|
|
||||||
sob responsabilidade da `AGD-0041`.
|
|
||||||
- 2026-07-03: Modelo de dados refinado: a biblioteca deve produzir entries
|
|
||||||
expansíveis, nao somente summaries de UI. Cada entry pode manter manifest em
|
|
||||||
memoria, path interno de launch e metadados operacionais como timestamp de
|
|
||||||
descoberta/instalacao; a UI v1 escolhe quais campos mostrar, mas o modelo
|
|
||||||
deve permitir que metadados futuros sejam ingeridos e usados pelo catalogo/UI.
|
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
---
|
||||||
|
id: AGD-0048
|
||||||
|
ticket: background-service-audio-execution
|
||||||
|
title: Agenda - Background Service and Audio Execution
|
||||||
|
status: open
|
||||||
|
created: 2026-07-05
|
||||||
|
resolved:
|
||||||
|
decision:
|
||||||
|
tags: [runtime, os, lifecycle, service, audio, background, architecture]
|
||||||
|
---
|
||||||
|
|
||||||
|
# Agenda - Background Service and Audio Execution
|
||||||
|
|
||||||
|
## Contexto
|
||||||
|
|
||||||
|
O runtime ja tem sinais claros de preparacao para multitarefa controlada:
|
||||||
|
|
||||||
|
- `TaskState::Background` existe como estado de tarefa;
|
||||||
|
- `VmSession` separa estado mutavel de VM por tarefa/processo;
|
||||||
|
- `SystemOS` e dono de lifecycle, task/process, VM sessions, filesystem,
|
||||||
|
memcard, windows e logging;
|
||||||
|
- a spec de eventos separa foreground ownership de execution eligibility;
|
||||||
|
- o contrato atual declara que execucao real em background fica fora do v1, mas
|
||||||
|
o modelo foi desenhado para permitir servicos ou processos de midia no futuro.
|
||||||
|
|
||||||
|
O caso motivador e:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Game foreground -> Home -> music player -> escolher musica -> voltar ao Game
|
||||||
|
```
|
||||||
|
|
||||||
|
Depois disso, o Game deve voltar ao foreground enquanto o player continua
|
||||||
|
executando e produzindo audio junto com audio do Game.
|
||||||
|
|
||||||
|
## Problema
|
||||||
|
|
||||||
|
Hoje o runtime preserva sessoes, mas nao tem contrato para uma sessao continuar
|
||||||
|
executando quando nao e foreground.
|
||||||
|
|
||||||
|
Os pontos atuais que bloqueiam o caso:
|
||||||
|
|
||||||
|
- `TaskKind` so distingue `Game` e `Shell`;
|
||||||
|
- `ProcessKind` so distingue `VmGame`, `VmShell` e `NativeShell`;
|
||||||
|
- `ProcessState` nao possui estado normativo de background-running;
|
||||||
|
- `GameRunningStep` ticka apenas o Game foreground;
|
||||||
|
- `ShellRunningStep` ticka apenas o Shell foreground;
|
||||||
|
- `HubHomeStep` nao ticka sessoes VM em background;
|
||||||
|
- `Audio` e `AudioMixer` usam vozes globais sem namespace por tarefa/sessao;
|
||||||
|
- cada logical frame chama `platform.audio_mut().clear_commands()`, o que torna
|
||||||
|
perigoso tickar dois produtores de audio no mesmo frame;
|
||||||
|
- pausa de lifecycle hoje emite `MasterPause`, afetando o mixer inteiro.
|
||||||
|
|
||||||
|
Sem uma decisao, background service pode virar apenas "tickar mais uma VM", mas
|
||||||
|
isso quebraria isolamento, audio, debugger, lifecycle e previsibilidade.
|
||||||
|
|
||||||
|
## Pontos Criticos
|
||||||
|
|
||||||
|
1. **Execution eligibility nao e foreground.**
|
||||||
|
O contrato atual ja separa os conceitos, mas a implementacao ainda so ticka o
|
||||||
|
owner foreground. Precisamos introduzir uma politica explicita de quem pode
|
||||||
|
executar em background.
|
||||||
|
|
||||||
|
2. **Servico nao e Shell escondido.**
|
||||||
|
Um music player pode ter UI de Shell para escolher musica, mas a reproducao
|
||||||
|
continua como servico quando a UI deixa o foreground. Fechar isso como
|
||||||
|
`Shell` em background confundiria janela, tarefa, sessao e servico.
|
||||||
|
|
||||||
|
3. **Audio precisa de origem.**
|
||||||
|
Hoje `voice_id` e global no mixer. Se Game e player usam `voice_id = 0`, um
|
||||||
|
sobrescreve o outro. Precisamos decidir se o mixer tera namespaces por
|
||||||
|
`AudioOwner`, se servicos terao pool dedicado, ou se o player nao usara a
|
||||||
|
mesma superficie `audio.*`.
|
||||||
|
|
||||||
|
4. **Pausa de Game nao pode pausar servico de midia.**
|
||||||
|
`MasterPause` global serve para o contrato atual de pausa/debug, mas nao
|
||||||
|
expressa "pausar Game audio e manter music player". Pausa precisa virar
|
||||||
|
escopo por origem ou politica de mixer.
|
||||||
|
|
||||||
|
5. **Servico precisa de lifecycle proprio.**
|
||||||
|
Deve existir contrato para start, foreground UI, background-running, stop,
|
||||||
|
crash, terminate, recurso negado, e talvez wake/resume de UI.
|
||||||
|
|
||||||
|
6. **Budget e determinismo precisam ser fechados.**
|
||||||
|
Se servicos rodam junto com Game, precisamos decidir cota por frame, ordem de
|
||||||
|
ticks, starvation, crash isolation, e se background service participa do
|
||||||
|
mesmo tempo deterministico da maquina.
|
||||||
|
|
||||||
|
7. **Sistema de apps precisa descobrir e lancar o player.**
|
||||||
|
Hoje Home lista Game cartridges e tem Shells nativos fixos. O caso de music
|
||||||
|
player exige decidir se ele e cartridge `System`, app instalado, Shell nativo,
|
||||||
|
ou novo perfil `Service`.
|
||||||
|
|
||||||
|
## Opcoes
|
||||||
|
|
||||||
|
### Opcao A - Background Service como novo tipo de processo/sessao
|
||||||
|
|
||||||
|
Criar contrato explicito para `Service`:
|
||||||
|
|
||||||
|
- `TaskKind::Service` ou entidade equivalente;
|
||||||
|
- `ProcessKind::VmService` / `NativeService`;
|
||||||
|
- execution eligibility independente de foreground;
|
||||||
|
- UI de controle opcional via Shell task associada ao servico;
|
||||||
|
- audio com origem por service/session;
|
||||||
|
- lifecycle proprio: start, background, foreground-control, stop, crash.
|
||||||
|
|
||||||
|
**Pros:**
|
||||||
|
- modela diretamente music player e futuros servicos;
|
||||||
|
- preserva a separacao entre UI foreground e execucao;
|
||||||
|
- evita transformar Shell em "processo que tambem e daemon";
|
||||||
|
- facilita quotas, permissao e observabilidade.
|
||||||
|
|
||||||
|
**Contras:**
|
||||||
|
- maior mudanca arquitetural;
|
||||||
|
- exige novo contrato em specs, SystemOS, firmware, audio e testes;
|
||||||
|
- precisa fechar politica de recursos antes de implementar.
|
||||||
|
|
||||||
|
**Manutencao:**
|
||||||
|
- melhor base para crescer com qualidade, desde que o MVP seja pequeno.
|
||||||
|
|
||||||
|
### Opcao B - Shell em background com audio permitido
|
||||||
|
|
||||||
|
Permitir que uma VM Shell continue tickando quando sai do foreground e use audio
|
||||||
|
normalmente.
|
||||||
|
|
||||||
|
**Pros:**
|
||||||
|
- reaproveita Shell, WindowManager e VM session existentes;
|
||||||
|
- menor numero de novos tipos no curto prazo.
|
||||||
|
|
||||||
|
**Contras:**
|
||||||
|
- mistura UI e servico;
|
||||||
|
- torna `TaskState::Background` semantico antes de definir `ProcessState`;
|
||||||
|
- abre precedente para qualquer Shell continuar executando;
|
||||||
|
- nao resolve sozinho namespace de audio, pause por origem, quotas e debugging.
|
||||||
|
|
||||||
|
**Manutencao:**
|
||||||
|
- atraente como atalho, mas tende a espalhar excecoes pela firmware state
|
||||||
|
machine.
|
||||||
|
|
||||||
|
### Opcao C - Audio player como servico nativo OS-owned, sem VM background
|
||||||
|
|
||||||
|
Implementar music player como servico nativo de SystemOS, controlado por uma
|
||||||
|
Shell UI. A reproducao continua no host/OS sem tickar VM em background.
|
||||||
|
|
||||||
|
**Pros:**
|
||||||
|
- entrega o caso de musica com menor risco para scheduler VM;
|
||||||
|
- evita abrir execucao arbitraria de background agora;
|
||||||
|
- audio service pode ser projetado como recurso OS-owned e depois exposto.
|
||||||
|
|
||||||
|
**Contras:**
|
||||||
|
- nao resolve background VM services em geral;
|
||||||
|
- player deixa de ser app userland completo no primeiro ciclo;
|
||||||
|
- precisa ainda fechar origem/mixagem de audio e relacao com UI.
|
||||||
|
|
||||||
|
**Manutencao:**
|
||||||
|
- bom MVP se o objetivo imediato for media playback, mas deve ser declarado como
|
||||||
|
`media service` nativo, nao como contrato geral de background VM.
|
||||||
|
|
||||||
|
## Sugestao / Recomendacao
|
||||||
|
|
||||||
|
Recomendo fechar em duas camadas:
|
||||||
|
|
||||||
|
1. **Decisao de arquitetura:** introduzir o conceito de service/background
|
||||||
|
execution como contrato de SystemOS, separado de foreground Shell e Game.
|
||||||
|
Essa decisao deve definir execution eligibility, lifecycle, quotas, crash
|
||||||
|
policy, controle de UI e relacao com VM sessions.
|
||||||
|
|
||||||
|
2. **MVP de media:** implementar primeiro um `media/audio service` com escopo
|
||||||
|
reduzido, preferencialmente OS-owned ou `Service` bem delimitado, antes de
|
||||||
|
permitir background VM arbitrario.
|
||||||
|
|
||||||
|
Para excelente qualidade, o primeiro plano nao deve tentar "qualquer app em
|
||||||
|
background". O alvo deve ser: um unico servico de audio/midia, com origem de
|
||||||
|
audio propria, controle por Hub/Shell, execucao enquanto Game esta foreground,
|
||||||
|
e testes end-to-end de mistura e lifecycle.
|
||||||
|
|
||||||
|
## Perguntas em Aberto
|
||||||
|
|
||||||
|
- O music player deve ser um cartridge `System`, um novo `Service`, ou um
|
||||||
|
servico nativo do OS controlado por Shell?
|
||||||
|
- A UI do player e a reproducao pertencem a mesma tarefa ou a tarefas
|
||||||
|
separadas?
|
||||||
|
- Um servico pode ter janela foreground temporaria e continuar sem janela?
|
||||||
|
- Quantos servicos background podem existir no MVP: um media service ou N
|
||||||
|
servicos?
|
||||||
|
- O background service recebe ticks todo frame, tick rate reduzido, ou apenas
|
||||||
|
eventos?
|
||||||
|
- O audio mixer deve isolar vozes por `TaskId`, `ProcessId`, `VmSessionId`,
|
||||||
|
`AppId`, ou novo `AudioOwner`?
|
||||||
|
- Como pausar apenas o audio do Game durante Home/debug sem pausar musica?
|
||||||
|
- O debugger inspeciona foreground session apenas ou tambem sessoes background?
|
||||||
|
- Como crash de servico e exibido: toast/log, janela de crash, ou parada
|
||||||
|
silenciosa com diagnostico?
|
||||||
|
- Que capacidades sao necessarias para media service: `audio`, `fs`, `asset`,
|
||||||
|
talvez `background_audio`?
|
||||||
|
|
||||||
|
## Criterio para Encerrar
|
||||||
|
|
||||||
|
Esta agenda pode virar decisao quando houver resposta escrita para:
|
||||||
|
|
||||||
|
- modelo de entidade (`Service` novo vs Shell background vs native OS service);
|
||||||
|
- execution eligibility e ordem de ticks;
|
||||||
|
- lifecycle e estados de task/process;
|
||||||
|
- ownership/namespace de audio e politica de pausa por origem;
|
||||||
|
- relacao entre UI foreground do player e reproducao background;
|
||||||
|
- escopo do MVP e explicitamente o que fica fora;
|
||||||
|
- testes obrigatorios de lifecycle, audio mixing, crash isolation e regressao do
|
||||||
|
contrato Game/Home/Shell existente.
|
||||||
|
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
---
|
||||||
|
id: AGD-0050
|
||||||
|
ticket: portable-host-backend-strategy
|
||||||
|
title: Portable Host Backend Strategy
|
||||||
|
status: open
|
||||||
|
created: 2026-07-14
|
||||||
|
resolved:
|
||||||
|
decision:
|
||||||
|
tags: [host, desktop, portable, sdl, backend, rendering, input, audio, linux, android, handheld]
|
||||||
|
---
|
||||||
|
|
||||||
|
## Contexto
|
||||||
|
|
||||||
|
O runtime ja tem uma fronteira de host relativamente clara: o host desktop atual vive em `crates/host/prometeu-host-desktop-winit`, usando `winit`, `pixels` e `cpal` para janela, apresentacao de framebuffer, input e audio.
|
||||||
|
|
||||||
|
A direcao desejada nao e substituir esse host de forma disruptiva no primeiro corte. A proposta e estudar e construir um segundo host portatil para servir como runtime host em handhelds e consoles portateis, especialmente hardwares chineses que rodam Linux internamente e, em alguns casos, Android customizado. O mesmo host tambem deve servir como base para uma futura versao DIY do hardware, desde que ela rode sobre um Linux base compatível. SDL e a hipotese principal, mas a agenda tambem deve avaliar outras familias de host/backend antes de virar decisao normativa.
|
||||||
|
|
||||||
|
Esse novo host deve conviver com o host atual durante estabilizacao, mas nao e descartavel: ele e candidato a se tornar o host principal quando provar paridade e estabilidade.
|
||||||
|
|
||||||
|
A troca deve ficar isolada no dominio de host: contratos de runtime, firmware, frame, input semantico e audio semantico nao devem mudar por causa da escolha de backend. Essa separacao e justamente o objetivo arquitetural que permite que um host portatil evolua para principal sem arrastar o runtime.
|
||||||
|
|
||||||
|
## Problema
|
||||||
|
|
||||||
|
Hoje a existencia de um unico host desktop torna dificil separar problemas do runtime de problemas do adaptador de plataforma. Um novo host portatil pode ajudar em testes, portabilidade, comparacao operacional e reducao de dependencia de uma pilha unica de janela/render/audio. O alvo "mobile" desta agenda nao significa telefone/tablet como produto primario; significa hardware portatil dedicado, geralmente com controles fisicos, framebuffer/display integrado, Linux customizado e distribuicao fora do modelo desktop tradicional. O alvo tambem inclui um possivel handheld DIY futuro, em que o valor esperado e ja existir um host pronto se o dispositivo expuser um Linux base suficiente.
|
||||||
|
|
||||||
|
O risco e tratar uma tecnologia especifica como resposta antes de comparar os requisitos reais de Linux handheld e Android. A agenda precisa cravar o modelo de host paralelo em estabilizacao, com destino de host principal, e entao escolher a familia de backend que melhor atende esse objetivo.
|
||||||
|
|
||||||
|
## Pontos Criticos
|
||||||
|
|
||||||
|
- A troca de host deve ser simples e local ao host, sem exigir mudancas em runtime, firmware, asset protocol, render packet, VM ou syscalls.
|
||||||
|
- O novo host precisa consumir as mesmas saidas canonicas do runtime: frames RGBA8888, comandos semanticos de audio e eventos de input normalizados.
|
||||||
|
- A estrategia deve preservar o host `winit` enquanto o novo host ainda nao provar equivalencia operacional, mas o novo host e candidato a virar o host principal depois dessa prova.
|
||||||
|
- O alvo primario e portabilidade operacional para handhelds Linux e consoles portateis com controles fisicos; Android customizado e um alvo possivel que deve influenciar a escolha de API, packaging e input/audio.
|
||||||
|
- O host portatil deve ser viavel em um futuro hardware DIY rodando Linux base, sem exigir um runtime especial ou fork de contratos.
|
||||||
|
- Testes devem distinguir contrato comum de host de detalhes especificos de backend.
|
||||||
|
- SDL2 pode ter ecossistema Rust mais estabelecido; SDL3 pode estar mais alinhado com a direcao upstream. A escolha da versao e uma pergunta separada da decisao de criar um segundo host.
|
||||||
|
- A arquitetura deve evitar duplicar logica de runtime loop, pacing, debugger, stats e presentation policy quando essa logica for comum a qualquer host.
|
||||||
|
- Outras familias de host tambem devem ser avaliadas: evoluir `winit`, SDL2/SDL3, backend Android nativo, ou uma camada multiplataforma alternativa.
|
||||||
|
|
||||||
|
## Opcoes
|
||||||
|
|
||||||
|
### Opcao A - Manter apenas o host winit atual
|
||||||
|
|
||||||
|
- **Abordagem:** continuar evoluindo `prometeu-host-desktop-winit` como unico host desktop.
|
||||||
|
- **Pro:** menor custo imediato; evita nova dependencia nativa.
|
||||||
|
- **Con:** mantem a pilha de plataforma unica como ponto de acoplamento pratico.
|
||||||
|
- **Tradeoff:** bom para estabilidade curta, fraco para provar independencia real do host.
|
||||||
|
|
||||||
|
### Opcao B - Migrar diretamente do host winit para outro backend
|
||||||
|
|
||||||
|
- **Abordagem:** substituir o host desktop atual por um novo backend portatil assim que a escolha tecnologica for feita.
|
||||||
|
- **Pro:** reduz a manutencao para um unico host depois da migracao.
|
||||||
|
- **Con:** aumenta risco de regressao e mistura decisao de backend com mudanca operacional.
|
||||||
|
- **Tradeoff:** so faz sentido depois de prova local de superioridade e paridade, o que ainda nao existe.
|
||||||
|
|
||||||
|
### Opcao C - Criar um host SDL paralelo com destino de principal
|
||||||
|
|
||||||
|
- **Abordagem:** adicionar um novo crate/binario de host SDL que implemente os mesmos contratos externos do host atual, mantendo `winit` como referencia e rollback ate haver evidencia de equivalencia.
|
||||||
|
- **Pro:** permite teste A/B, reduz risco, valida se a fronteira de host esta realmente limpa, atende a meta de handheld Linux/Android customizado/DIY e preserva caminho para tornar SDL o host principal.
|
||||||
|
- **Con:** aumenta temporariamente manutencao e exige fatorar partes comuns se houver duplicacao.
|
||||||
|
- **Tradeoff:** melhor caminho para chegar a um host principal portatil sem reabrir runtime.
|
||||||
|
|
||||||
|
### Opcao D - Evoluir winit/pixels/cpal como host portatil
|
||||||
|
|
||||||
|
- **Abordagem:** manter a familia atual e investir em configuracao, input, fullscreen, packaging e compatibilidade de Linux handheld/Android/DIY dentro dela.
|
||||||
|
- **Pro:** reaproveita o host existente e reduz dependencias nativas novas.
|
||||||
|
- **Con:** pode nao resolver os problemas praticos de distribuicao, gamepad/device handling, fullscreen/scaling, Android customizado e ambientes handheld.
|
||||||
|
- **Tradeoff:** forte se a pilha atual suportar bem os alvos; fraco se o problema real for portabilidade operacional.
|
||||||
|
|
||||||
|
### Opcao E - Host Android nativo separado
|
||||||
|
|
||||||
|
- **Abordagem:** tratar Linux handheld e Android como hosts diferentes: SDL ou winit para Linux; Android com camada nativa/propria quando o alvo amadurecer.
|
||||||
|
- **Pro:** permite respeitar o ciclo de vida, packaging, input e audio do Android sem contaminar o host Linux.
|
||||||
|
- **Con:** duplica mais superficie e adia a promessa de um host portatil unico.
|
||||||
|
- **Tradeoff:** bom se Android tiver requisitos proprios demais; ruim se SDL conseguir cobrir Android bem o bastante.
|
||||||
|
|
||||||
|
### Opcao F - Camada multiplataforma alternativa
|
||||||
|
|
||||||
|
- **Abordagem:** avaliar alternativas como uma camada Rust-first ou game-framework-level para janela, input, audio e render.
|
||||||
|
- **Pro:** pode reduzir FFI nativa e integrar melhor com Cargo.
|
||||||
|
- **Con:** pode ser menos madura para Linux handheld/Android real, packaging e controles.
|
||||||
|
- **Tradeoff:** deve ser considerada, mas precisa provar vantagem concreta sobre SDL para justificar risco.
|
||||||
|
|
||||||
|
## Sugestao / Recomendacao
|
||||||
|
|
||||||
|
Recomendacao inicial: manter a **Opcao C** como favorita, mas ampliar a fase de agenda para comparar SDL com as demais familias de host antes da decisao. O resultado desejado continua sendo um segundo host portatil, inicialmente paralelo, com destino explicito de se tornar o host principal quando atingir paridade e estabilidade.
|
||||||
|
|
||||||
|
O caminho recomendado e:
|
||||||
|
|
||||||
|
1. Definir o contrato minimo de equivalencia entre hosts: janela, framebuffer RGBA8888, input, audio, pacing, debugger/logs e encerramento.
|
||||||
|
2. Identificar o que e comum ao host e o que e backend especifico.
|
||||||
|
3. Comparar as familias candidatas contra esse contrato: SDL2, SDL3, winit atual evoluido, Android nativo separado e alternativas Rust-first.
|
||||||
|
4. Implementar o candidato escolhido como novo crate/binario sem remover `prometeu-host-desktop-winit`.
|
||||||
|
5. Permitir troca simples por binario/comando/feature, mantendo o runtime cego para a escolha.
|
||||||
|
6. Tratar handheld Linux como alvo primario de produto para esse host; tratar Android customizado e DIY Linux como restricoes de desenho quando afetarem backend, packaging, input, audio ou boot/runtime integration.
|
||||||
|
7. Promover o novo host a principal apenas depois de evidencia de estabilidade e paridade.
|
||||||
|
|
||||||
|
## Perguntas em Aberto
|
||||||
|
|
||||||
|
- [ ] A primeira implementacao SDL deve usar SDL2 ou SDL3?
|
||||||
|
- [ ] SDL deve ser a familia escolhida, ou winit evoluido, Android nativo separado ou outra camada oferece melhor caminho?
|
||||||
|
- [ ] A selecao do host deve ser por binario separado, feature Cargo, parametro CLI, ou combinacao desses mecanismos?
|
||||||
|
- [ ] Qual e o menor conjunto de comportamento que define paridade aceitavel com o host winit?
|
||||||
|
- [ ] Quais partes do host atual devem virar modulo comum antes do SDL, e quais devem ser duplicadas primeiro para evitar abstracao prematura?
|
||||||
|
- [ ] O host SDL deve reutilizar `cpal` para audio inicialmente ou usar audio SDL desde o primeiro corte?
|
||||||
|
- [ ] Quais familias de hardware handheld Linux devem ser usadas como referencia inicial?
|
||||||
|
- [ ] Handheld Linux exige controles/gamepad, fullscreen, scaling, latency, sleep/resume, framebuffer/display mode ou packaging especificos desde o primeiro corte?
|
||||||
|
- [ ] Qual e o "Linux base" minimo que um futuro hardware DIY precisaria expor para rodar o host portatil sem fork?
|
||||||
|
- [ ] Android customizado deve ser criterio de escolha entre SDL2 e SDL3 agora, ou deve ficar como compatibilidade futura?
|
||||||
|
- [ ] Como validar input e pacing de forma automatizada sem depender de janela real em CI?
|
||||||
|
- [ ] O nome do crate deve ser `prometeu-host-desktop-sdl`, `prometeu-host-desktop-sdl2`, ou algo neutro a versao?
|
||||||
|
|
||||||
|
## Criterio para Encerrar
|
||||||
|
|
||||||
|
A agenda pode virar decision quando estiver claro:
|
||||||
|
|
||||||
|
- se o novo host sera paralelo em estabilizacao, com destino de host principal;
|
||||||
|
- qual familia de backend sera alvo inicial;
|
||||||
|
- se SDL for escolhido, qual versao SDL sera alvo inicial;
|
||||||
|
- como a selecao/troca de host deve funcionar;
|
||||||
|
- quais contratos sao comuns e proibidos de mudar;
|
||||||
|
- quais requisitos minimos de handheld Linux e possivel Android customizado entram no primeiro plano;
|
||||||
|
- qual contrato minimo de Linux base mantem aberta a opcao de hardware DIY;
|
||||||
|
- qual evidencia minima prova paridade suficiente para iniciar planos de implementacao.
|
||||||
|
|
||||||
|
## Discussion
|
||||||
|
|
||||||
|
Ponto inicial aceito pelo usuario: a intencao e ter um segundo host para testes, com troca simples e facil, aproveitando o trabalho ja feito para isolar essa troca no host sem envolver runtime ou outros dominios.
|
||||||
|
|
||||||
|
Atualizacao de escopo: o novo host nao e descartavel. O objetivo e servir como runtime host para sistemas Linux rodando em consoles portateis e hardwares handheld chineses, e possivelmente Android customizado. Assim que estiver estavel, ele deve poder virar o host principal.
|
||||||
|
|
||||||
|
Atualizacao de escopo: outras familias de host/backend tambem devem viver nesta agenda. SDL segue como hipotese forte, mas a decisao deve comparar opcoes antes de cravar a tecnologia.
|
||||||
|
|
||||||
|
Clarificacao: "mobile" nesta agenda nao se refere primariamente a telefone/tablet. O foco sao dispositivos portateis dedicados com Linux interno ou Android customizado, geralmente com controles fisicos e ambiente de distribuicao proprio.
|
||||||
|
|
||||||
|
Clarificacao: a agenda tambem deve preservar a opcao de um futuro hardware DIY. A premissa desejada e que, se esse hardware expuser um Linux base suficiente, o runtime ja tenha um host portatil pronto para rodar nele.
|
||||||
|
|
||||||
|
## Resolution
|
||||||
-136
@@ -1,136 +0,0 @@
|
|||||||
---
|
|
||||||
id: DEC-0035
|
|
||||||
ticket: system-run-cart
|
|
||||||
title: Remove Userland system.run_cart and Preserve Direct Boot
|
|
||||||
status: accepted
|
|
||||||
created: 2026-07-03
|
|
||||||
ref_agenda: AGD-0003
|
|
||||||
tags: []
|
|
||||||
---
|
|
||||||
|
|
||||||
## Status
|
|
||||||
|
|
||||||
Accepted.
|
|
||||||
|
|
||||||
## Contexto
|
|
||||||
|
|
||||||
`system.run_cart` existe na ABI publica, mas nao possui comportamento real de
|
|
||||||
troca de cartucho. Isso cria uma falsa promessa: um guest pode declarar/chamar
|
|
||||||
uma operacao que aparenta iniciar outro cartucho, enquanto o runtime retorna
|
|
||||||
sucesso vazio ou nao executa uma transicao completa.
|
|
||||||
|
|
||||||
A discussao fechou tres separacoes:
|
|
||||||
|
|
||||||
- boot direto por host/CLI/debug e necessario e deve permanecer;
|
|
||||||
- apps/userland nao devem iniciar cartuchos diretamente;
|
|
||||||
- troca `Game A -> Home -> Game B` exige um orquestrador de SystemOS proprio,
|
|
||||||
separado em `DSC-0043 / AGD-0044`.
|
|
||||||
|
|
||||||
`AGD-0041` permanece responsavel por `Game -> Home -> mesmo Game`, foreground,
|
|
||||||
pausa/suspensao e retorno ao mesmo Game.
|
|
||||||
|
|
||||||
## Decisao
|
|
||||||
|
|
||||||
`system.run_cart` MUST be removed from the userland guest ABI.
|
|
||||||
|
|
||||||
No app, cartridge, Shell app, or other userland guest code MAY directly request
|
|
||||||
cartridge boot through `system.run_cart`.
|
|
||||||
|
|
||||||
The platform MUST NOT preserve compatibility for the current userland
|
|
||||||
`system.run_cart` surface. It MUST NOT remain as a callable stub, reserved
|
|
||||||
guest syscall that returns success, or capability-gated userland escape hatch.
|
|
||||||
|
|
||||||
Direct boot MUST remain supported through host/CLI/debug or equivalent
|
|
||||||
single-game launch paths. This direct boot path is a host/system entrypoint,
|
|
||||||
not a guest syscall.
|
|
||||||
|
|
||||||
Internal cartridge loading MAY continue to use the existing loader path,
|
|
||||||
including directory cartridges and test fixtures. `.pmc` support is not required
|
|
||||||
by this decision.
|
|
||||||
|
|
||||||
If apps ever need to request navigation in the future, that MUST be designed as
|
|
||||||
a separate SystemOS-mediated surface with different naming and semantics. It
|
|
||||||
MUST NOT reintroduce userland `run_cart` as direct cartridge boot.
|
|
||||||
|
|
||||||
## Rationale
|
|
||||||
|
|
||||||
Direct cartridge boot is essential for development, debugging, automated tests,
|
|
||||||
and future distribution modes where the runtime launches as a single game. That
|
|
||||||
use case does not require a guest-visible syscall.
|
|
||||||
|
|
||||||
Userland cartridge boot would give app code authority over system navigation,
|
|
||||||
lifecycle, cleanup, target resolution, and failure policy. Those concerns belong
|
|
||||||
to SystemOS/firmware and later to the cartridge switch orchestrator, not to a VM
|
|
||||||
guest syscall.
|
|
||||||
|
|
||||||
Keeping a stub or compatibility surface would preserve the current ambiguity.
|
|
||||||
The public ABI should not advertise an operation that either does nothing or
|
|
||||||
looks like direct app-controlled navigation.
|
|
||||||
|
|
||||||
## Invariantes / Contrato
|
|
||||||
|
|
||||||
- Guest/userland MUST NOT expose or call `system.run_cart`.
|
|
||||||
- The public syscall registry, declarations, generated bindings, and docs MUST
|
|
||||||
stop presenting `system.run_cart` as an app-callable operation.
|
|
||||||
- Booting a cartridge directly MUST remain available from host/CLI/debug flows.
|
|
||||||
- Direct boot MUST enter the runtime with a selected cartridge target; it MUST
|
|
||||||
NOT depend on a guest syscall issued after VM startup.
|
|
||||||
- Loader code MAY remain reusable by host/firmware/SystemOS internals.
|
|
||||||
- Loader code MUST NOT become lifecycle orchestration authority.
|
|
||||||
- `Game -> Home -> same Game` remains owned by `AGD-0041`.
|
|
||||||
- `Game A -> Home -> Game B` remains owned by `DSC-0043 / AGD-0044`.
|
|
||||||
- `.pmc`, app catalog, launcher UX, marketplace/distribution, and full cartridge
|
|
||||||
replacement under Home are outside this decision.
|
|
||||||
|
|
||||||
## Impactos
|
|
||||||
|
|
||||||
- **Spec / ABI:** remove or retire `system.run_cart` from the userland syscall
|
|
||||||
surface. Any syscall table, PBS declarations, generated metadata, or docs
|
|
||||||
must stop advertising it to apps.
|
|
||||||
- **Runtime / VM:** guest dispatch must no longer treat `system.run_cart` as a
|
|
||||||
valid userland operation. If obsolete bytecode or declarations still reach the
|
|
||||||
runtime during migration, they must fail explicitly rather than report success.
|
|
||||||
- **Firmware / Host:** direct boot remains supported for command-line,
|
|
||||||
debugger, test harness, and future single-game launch flows.
|
|
||||||
- **SystemOS:** no new cart-switch orchestrator is required by this decision.
|
|
||||||
That work is deferred to `DSC-0043 / AGD-0044`.
|
|
||||||
- **Tooling:** tools must continue to support direct cartridge launch for
|
|
||||||
development and test workflows, without relying on a guest syscall.
|
|
||||||
- **Tests:** coverage must prove both sides: userland cannot declare/call
|
|
||||||
`system.run_cart`, and direct boot of a cartridge still works.
|
|
||||||
|
|
||||||
## Alternativas Descartadas
|
|
||||||
|
|
||||||
- **Implement `system.run_cart` as a normal syscall:** rejected because it gives
|
|
||||||
userland direct navigation authority and mixes guest execution with system
|
|
||||||
lifecycle.
|
|
||||||
- **Keep a compatibility stub:** rejected because no compatibility is required
|
|
||||||
and a stub preserves the false contract.
|
|
||||||
- **Make `system.run_cart` privileged but still guest-visible:** rejected for v1
|
|
||||||
because it keeps the ambiguous idea that some guest profile may directly boot
|
|
||||||
cartuchos.
|
|
||||||
- **Implement full `Home -> another Game` now:** rejected for this decision; it
|
|
||||||
requires SystemOS orchestration after the `AGD-0041` foreground contract.
|
|
||||||
|
|
||||||
## Referencias
|
|
||||||
|
|
||||||
- Agenda: `AGD-0003`
|
|
||||||
- Foreground/pause scope: `AGD-0041`
|
|
||||||
- Future cartridge switch orchestrator: `DSC-0043 / AGD-0044`
|
|
||||||
- Related lessons: `LSN-0041` SystemOS lifecycle authority, `LSN-0042`
|
|
||||||
SystemOS service ownership boundary, `LSN-0043` SystemOS domain facades.
|
|
||||||
|
|
||||||
## Propagacao Necessaria
|
|
||||||
|
|
||||||
- Remove `SystemRunCart` from userland ABI declarations and generated syscall
|
|
||||||
metadata.
|
|
||||||
- Remove or rewrite runtime dispatch paths that return success for
|
|
||||||
`system.run_cart`.
|
|
||||||
- Preserve host/CLI/debug direct boot paths and add regression tests for them.
|
|
||||||
- Add negative tests for guest/userland declaration or call attempts.
|
|
||||||
- Update any documentation/spec text that describes `system.run_cart` as
|
|
||||||
app-callable.
|
|
||||||
|
|
||||||
## Revision Log
|
|
||||||
|
|
||||||
- 2026-07-03: Initial draft from `AGD-0003`.
|
|
||||||
@@ -1,156 +0,0 @@
|
|||||||
---
|
|
||||||
id: DEC-0036
|
|
||||||
ticket: system-run-cart
|
|
||||||
title: SystemOS Games Root and Home Game Launch
|
|
||||||
status: accepted
|
|
||||||
created: 2026-07-03
|
|
||||||
ref_agenda: AGD-0045
|
|
||||||
tags: []
|
|
||||||
---
|
|
||||||
|
|
||||||
## Status
|
|
||||||
|
|
||||||
Accepted.
|
|
||||||
|
|
||||||
## Contexto
|
|
||||||
|
|
||||||
`DEC-0035` removed `system.run_cart` from the userland guest ABI and preserved
|
|
||||||
direct host/CLI/debug cartridge boot. That decision intentionally did not
|
|
||||||
deliver the Home/SO product flow: pointing PROMETEU at a local games directory,
|
|
||||||
listing available games in Home, and launching a selected game by user action.
|
|
||||||
|
|
||||||
This decision defines the first system-owned replacement for userland
|
|
||||||
`run_cart`: a local games-root library discovered by the host/SystemOS and
|
|
||||||
exposed through a simple Home UI.
|
|
||||||
|
|
||||||
## Decisao
|
|
||||||
|
|
||||||
PROMETEU MUST support a host-provided games library root through
|
|
||||||
`--games-root <dir>`.
|
|
||||||
|
|
||||||
The games root is a directory containing game cartridge directories as immediate
|
|
||||||
children. V1 MUST scan only immediate child directories. Recursive discovery is
|
|
||||||
out of scope.
|
|
||||||
|
|
||||||
The v1 games library MUST include only cartridges whose manifest declares
|
|
||||||
`app_mode: Game`. Shell/System apps, `.pmc` packages, remote catalogs,
|
|
||||||
marketplace/distribution metadata, rich icons, search, and non-game apps are out
|
|
||||||
of scope.
|
|
||||||
|
|
||||||
The library MUST produce expandable internal entries, not UI-only summaries.
|
|
||||||
Each entry MUST retain enough internal data to launch the cartridge and to grow
|
|
||||||
as a catalog model. At minimum, each entry MUST include:
|
|
||||||
|
|
||||||
- loaded manifest data;
|
|
||||||
- `title`;
|
|
||||||
- `app_id`;
|
|
||||||
- `app_version`;
|
|
||||||
- internal cartridge path;
|
|
||||||
- operational discovery metadata, including a timestamp or equivalent discovery
|
|
||||||
marker.
|
|
||||||
|
|
||||||
The Home UI v1 SHOULD display only `title`, `app_id`, and `app_version`. It MAY
|
|
||||||
hide path and operational metadata.
|
|
||||||
|
|
||||||
Invalid cartridge candidates MUST be logged and omitted from the Home game list.
|
|
||||||
|
|
||||||
Selecting a listed Game in Home MUST immediately request a system-owned launch
|
|
||||||
through firmware/SystemOS, resulting in `LoadCartridge` for that cartridge. This
|
|
||||||
MUST NOT use a guest syscall and MUST NOT reintroduce userland `run_cart`.
|
|
||||||
|
|
||||||
If launch fails, the machine MUST return to or remain in Home and record an
|
|
||||||
error/log. A polished error UI is out of scope.
|
|
||||||
|
|
||||||
Booting directly with `--run <cart>` MUST remain separate and unchanged.
|
|
||||||
|
|
||||||
Returning from a running Game to Home is outside this decision and belongs to
|
|
||||||
`AGD-0041`. Switching from `Game A -> Home -> Game B` after a game is already
|
|
||||||
active belongs to `DSC-0043 / AGD-0044`.
|
|
||||||
|
|
||||||
## Rationale
|
|
||||||
|
|
||||||
The previous `run_cart` surface was wrong because it made cartridge launch look
|
|
||||||
like an app/userland capability. The desired behavior is still valid, but the
|
|
||||||
authority must live in the system: Home presents available games and the
|
|
||||||
firmware/SystemOS loads the selected cartridge.
|
|
||||||
|
|
||||||
Using `--games-root` keeps the v1 product model honest: this is a local game
|
|
||||||
library, not a general app root. Other app types can be introduced later without
|
|
||||||
forcing the first launcher model to pretend it is a full marketplace.
|
|
||||||
|
|
||||||
Immediate child scanning keeps discovery deterministic and testable. `.pmc` and
|
|
||||||
recursive layouts can be added after the directory-cartridge path is proven.
|
|
||||||
|
|
||||||
An expandable entry model avoids prematurely freezing the UI shape as the data
|
|
||||||
model. The UI is intentionally simple, but the catalog model needs room for
|
|
||||||
future metadata such as package origin, installation/discovery timestamps, rich
|
|
||||||
presentation fields, and packaged cartridge details.
|
|
||||||
|
|
||||||
## Invariantes / Contrato
|
|
||||||
|
|
||||||
- `--games-root <dir>` is the v1 host argument for a local games library.
|
|
||||||
- The games root is Game-only in v1.
|
|
||||||
- Discovery scans immediate child directories only.
|
|
||||||
- Directory candidates without valid Game cartridge metadata are logged and
|
|
||||||
omitted.
|
|
||||||
- Library entries are internal catalog records, not direct UI DTOs.
|
|
||||||
- The UI v1 displays a simple clickable list and may show only `title`,
|
|
||||||
`app_id`, and `app_version`.
|
|
||||||
- The internal entry retains cartridge path and loaded manifest data for launch.
|
|
||||||
- Home selection is a system action that enters firmware/SystemOS loading. It is
|
|
||||||
not a guest syscall.
|
|
||||||
- `--run <cart>` direct boot remains independent from `--games-root`.
|
|
||||||
- Return-to-Home and game-to-game switching are not implemented by this
|
|
||||||
decision.
|
|
||||||
|
|
||||||
## Impactos
|
|
||||||
|
|
||||||
- **Host:** add a `--games-root <dir>` argument and pass the resolved root into
|
|
||||||
runtime/firmware/SystemOS initialization.
|
|
||||||
- **SystemOS / Hub:** add a local game library model and expose entries to Home.
|
|
||||||
Home must render a minimal clickable list and emit a system-owned launch
|
|
||||||
action for a selected entry.
|
|
||||||
- **Firmware:** consume the Home launch action and transition to
|
|
||||||
`LoadCartridge` with the selected cartridge path.
|
|
||||||
- **Loader:** continue to validate complete directory cartridges. Discovery may
|
|
||||||
read manifest metadata, but full launch still uses the existing loader.
|
|
||||||
- **Runtime / VM:** no userland ABI is added. No guest syscall participates in
|
|
||||||
launch.
|
|
||||||
- **Specs / Docs:** document `--games-root`, Game-only v1 discovery, and the
|
|
||||||
distinction between direct boot, games library launch, and future game
|
|
||||||
switching.
|
|
||||||
- **Tests:** cover discovery, invalid omission/logging, Home action emission,
|
|
||||||
and the end-to-end path from games root selection to `GameRunning`.
|
|
||||||
|
|
||||||
## Alternativas Descartadas
|
|
||||||
|
|
||||||
- **List only, no launch:** rejected because it does not satisfy the product
|
|
||||||
goal of starting games from Home.
|
|
||||||
- **General app root:** rejected for v1 because Shell/System apps need separate
|
|
||||||
lifecycle and UI contracts.
|
|
||||||
- **Recursive discovery:** rejected for v1 to keep semantics deterministic.
|
|
||||||
- **`.pmc` discovery:** rejected for v1 because packed cartridge loading is a
|
|
||||||
separate open agenda.
|
|
||||||
- **Game-to-game switch now:** rejected because it depends on foreground and
|
|
||||||
cartridge-switch orchestration work in `AGD-0041` and `AGD-0044`.
|
|
||||||
|
|
||||||
## Referencias
|
|
||||||
|
|
||||||
- Source agenda: `AGD-0045`
|
|
||||||
- Userland run-cart removal: `DEC-0035`
|
|
||||||
- Foreground/Home return scope: `AGD-0041`
|
|
||||||
- Future cartridge switch orchestration: `DSC-0043 / AGD-0044`
|
|
||||||
|
|
||||||
## Propagacao Necessaria
|
|
||||||
|
|
||||||
- Add or update runtime specs for games-root discovery and Home launch.
|
|
||||||
- Add host CLI argument plumbing for `--games-root`.
|
|
||||||
- Add a catalog/library entry model.
|
|
||||||
- Add Hub/Home list rendering and click handling.
|
|
||||||
- Add firmware/SystemOS action routing to `LoadCartridge`.
|
|
||||||
- Add tests for discovery, invalid candidates, action emission, and
|
|
||||||
`games-root -> Home click -> GameRunning`.
|
|
||||||
|
|
||||||
## Revision Log
|
|
||||||
|
|
||||||
- 2026-07-03: Initial draft from `AGD-0045`.
|
|
||||||
@@ -1,90 +0,0 @@
|
|||||||
---
|
|
||||||
id: PLN-0129
|
|
||||||
ticket: system-run-cart
|
|
||||||
title: Remove Userland Run Cart ABI Surface
|
|
||||||
status: done
|
|
||||||
created: 2026-07-03
|
|
||||||
ref_decisions: [DEC-0035]
|
|
||||||
tags: []
|
|
||||||
---
|
|
||||||
|
|
||||||
## Briefing
|
|
||||||
|
|
||||||
`DEC-0035` removes `system.run_cart` from the userland guest ABI. This plan
|
|
||||||
covers the public ABI, syscall registry/declaration surface, generated metadata,
|
|
||||||
and documentation/spec propagation. It does not change runtime dispatch behavior
|
|
||||||
or direct boot tests; those are covered by `PLN-0130` and `PLN-0131`.
|
|
||||||
|
|
||||||
## Objective
|
|
||||||
|
|
||||||
Remove `system.run_cart` from every app-callable/userland ABI surface while
|
|
||||||
preserving non-guest direct boot entrypoints.
|
|
||||||
|
|
||||||
## Dependencies
|
|
||||||
|
|
||||||
- Source decision: `DEC-0035`.
|
|
||||||
- Must stay scoped away from `AGD-0041` and `AGD-0044`.
|
|
||||||
- Coordinate with `PLN-0130` so runtime dispatch does not retain a callable
|
|
||||||
success path after the declaration is removed.
|
|
||||||
|
|
||||||
## Scope
|
|
||||||
|
|
||||||
- Remove or retire `Syscall::SystemRunCart` from userland-visible syscall
|
|
||||||
declarations in `crates/console/prometeu-hal/src/syscalls.rs`.
|
|
||||||
- Remove the `system.run_cart` registry entry from
|
|
||||||
`crates/console/prometeu-hal/src/syscalls/domains/system.rs` and
|
|
||||||
`crates/console/prometeu-hal/src/syscalls/registry.rs`, unless implementation
|
|
||||||
discovers an internal-only registry distinct from guest ABI.
|
|
||||||
- Remove generated/static bytecode or VM-facing declarations that expose
|
|
||||||
`system.run_cart`, including known references in
|
|
||||||
`crates/console/prometeu-bytecode/src/model.rs` and
|
|
||||||
`crates/console/prometeu-vm/src/virtual_machine.rs` if they include it.
|
|
||||||
- Update docs/specs that mention `system.run_cart` as app-callable.
|
|
||||||
- Update `AGD-0004` references only if they become factually misleading after
|
|
||||||
removal; do not close or reinterpret that agenda.
|
|
||||||
|
|
||||||
## Non-Goals
|
|
||||||
|
|
||||||
- Do not implement `Home -> another Game`.
|
|
||||||
- Do not add a replacement app navigation syscall.
|
|
||||||
- Do not implement `.pmc`.
|
|
||||||
- Do not change direct host/CLI/debug boot behavior.
|
|
||||||
- Do not add compatibility stubs for obsolete guest code.
|
|
||||||
|
|
||||||
## Execution Method
|
|
||||||
|
|
||||||
1. Search for `SystemRunCart`, `run_cart`, and `"system", "run_cart"` across
|
|
||||||
`crates/`, `docs/`, and `discussion/`.
|
|
||||||
2. Remove `system.run_cart` from userland syscall domain declarations and
|
|
||||||
lookup/name registries.
|
|
||||||
3. Remove generated/static guest-facing metadata entries that advertise
|
|
||||||
`system.run_cart`.
|
|
||||||
4. Update docs/specs to state that cartridges are booted by host/system paths,
|
|
||||||
not by guest syscall.
|
|
||||||
5. Compile the workspace or targeted crates to find stale references.
|
|
||||||
|
|
||||||
## Acceptance Criteria
|
|
||||||
|
|
||||||
- No userland ABI declaration advertises `system.run_cart`.
|
|
||||||
- No generated guest metadata exposes `run_cart` as callable.
|
|
||||||
- Documentation/spec text no longer describes app-callable cartridge boot.
|
|
||||||
- Any retained code path is clearly internal-only and is not reachable through
|
|
||||||
guest syscall lookup.
|
|
||||||
|
|
||||||
## Tests
|
|
||||||
|
|
||||||
- Add or update syscall registry tests to assert `system.run_cart` is absent
|
|
||||||
from the public/userland registry.
|
|
||||||
- Run targeted tests for `prometeu-hal`, `prometeu-bytecode`, and
|
|
||||||
`prometeu-vm` if available.
|
|
||||||
- Run repository validation commands used for syscall declaration consistency.
|
|
||||||
|
|
||||||
## Affected Artifacts
|
|
||||||
|
|
||||||
- `crates/console/prometeu-hal/src/syscalls.rs`
|
|
||||||
- `crates/console/prometeu-hal/src/syscalls/domains/system.rs`
|
|
||||||
- `crates/console/prometeu-hal/src/syscalls/registry.rs`
|
|
||||||
- `crates/console/prometeu-bytecode/src/model.rs`
|
|
||||||
- `crates/console/prometeu-vm/src/virtual_machine.rs`
|
|
||||||
- `docs/specs/runtime/`
|
|
||||||
- `discussion/workflow/agendas/AGD-0004-system-fault-semantics-and-control-surface.md`
|
|
||||||
@@ -1,79 +0,0 @@
|
|||||||
---
|
|
||||||
id: PLN-0130
|
|
||||||
ticket: system-run-cart
|
|
||||||
title: Remove Runtime Run Cart Stub Dispatch
|
|
||||||
status: done
|
|
||||||
created: 2026-07-03
|
|
||||||
ref_decisions: [DEC-0035]
|
|
||||||
tags: []
|
|
||||||
---
|
|
||||||
|
|
||||||
## Briefing
|
|
||||||
|
|
||||||
`DEC-0035` forbids a callable userland `system.run_cart` stub. This plan covers
|
|
||||||
runtime and VM dispatch cleanup so obsolete calls cannot silently succeed.
|
|
||||||
Public ABI removal is handled by `PLN-0129`; direct boot preservation is handled
|
|
||||||
by `PLN-0131`.
|
|
||||||
|
|
||||||
## Objective
|
|
||||||
|
|
||||||
Remove the runtime no-op dispatch path for `SystemRunCart` and ensure stale or
|
|
||||||
obsolete userland attempts fail explicitly rather than returning success.
|
|
||||||
|
|
||||||
## Dependencies
|
|
||||||
|
|
||||||
- Source decision: `DEC-0035`.
|
|
||||||
- Depends on the ABI direction in `PLN-0129`, but can be implemented in the same
|
|
||||||
PR if the public enum/registry removal and dispatch cleanup move together.
|
|
||||||
|
|
||||||
## Scope
|
|
||||||
|
|
||||||
- Remove the `Syscall::SystemRunCart => return Ok(())` path from
|
|
||||||
`crates/console/prometeu-system/src/services/vm_runtime/dispatch.rs`.
|
|
||||||
- Update any match arms made unreachable or obsolete by removing
|
|
||||||
`SystemRunCart`.
|
|
||||||
- Ensure stale numeric syscall ids or stale bytecode declarations fail with the
|
|
||||||
repository's existing unknown/invalid syscall behavior.
|
|
||||||
- Add negative coverage for userland attempts to invoke the removed operation,
|
|
||||||
using the closest existing VM runtime syscall tests.
|
|
||||||
|
|
||||||
## Non-Goals
|
|
||||||
|
|
||||||
- Do not implement a replacement navigation operation.
|
|
||||||
- Do not implement the `Home -> another Game` orchestrator.
|
|
||||||
- Do not alter direct host/CLI/debug cartridge boot paths.
|
|
||||||
- Do not change `system.has_cart` behavior unless required by compile fallout.
|
|
||||||
|
|
||||||
## Execution Method
|
|
||||||
|
|
||||||
1. Inspect `dispatch.rs` for all `SystemRunCart` match arms.
|
|
||||||
2. Remove the no-op success path and any unreachable arms tied only to
|
|
||||||
`SystemRunCart`.
|
|
||||||
3. If the public enum variant is removed by `PLN-0129`, update exhaustiveness
|
|
||||||
and registry mapping accordingly.
|
|
||||||
4. Add or update VM runtime tests that demonstrate `system.run_cart` is not
|
|
||||||
callable from guest/userland.
|
|
||||||
5. Run targeted runtime tests and compile checks.
|
|
||||||
|
|
||||||
## Acceptance Criteria
|
|
||||||
|
|
||||||
- There is no runtime path where a guest `system.run_cart` call returns `Ok(())`.
|
|
||||||
- Stale/obsolete attempts fail explicitly through existing invalid syscall or
|
|
||||||
declaration validation behavior.
|
|
||||||
- `system.has_cart` and unrelated system syscalls keep their current behavior.
|
|
||||||
- Runtime dispatch remains exhaustive and clear after removing `SystemRunCart`.
|
|
||||||
|
|
||||||
## Tests
|
|
||||||
|
|
||||||
- Add a negative test in `crates/console/prometeu-system/src/services/vm_runtime`
|
|
||||||
for stale userland `run_cart` attempts, if the test harness can express it.
|
|
||||||
- Run `cargo test` for `prometeu-system` and any impacted syscall crates.
|
|
||||||
- Run a workspace compile/test command if targeted tests reveal cross-crate enum
|
|
||||||
fallout.
|
|
||||||
|
|
||||||
## Affected Artifacts
|
|
||||||
|
|
||||||
- `crates/console/prometeu-system/src/services/vm_runtime/dispatch.rs`
|
|
||||||
- `crates/console/prometeu-system/src/services/vm_runtime/tests.rs`
|
|
||||||
- `crates/console/prometeu-hal/src/syscalls.rs`
|
|
||||||
- `crates/console/prometeu-hal/src/syscalls/registry.rs`
|
|
||||||
@@ -1,83 +0,0 @@
|
|||||||
---
|
|
||||||
id: PLN-0131
|
|
||||||
ticket: system-run-cart
|
|
||||||
title: Preserve Direct Cartridge Boot Coverage
|
|
||||||
status: done
|
|
||||||
created: 2026-07-03
|
|
||||||
ref_decisions: [DEC-0035]
|
|
||||||
tags: []
|
|
||||||
---
|
|
||||||
|
|
||||||
## Briefing
|
|
||||||
|
|
||||||
`DEC-0035` removes userland `system.run_cart`, but direct cartridge boot remains
|
|
||||||
mandatory for development, debugging, automated tests, and future single-game
|
|
||||||
launch scenarios. This plan protects that path while the guest syscall is
|
|
||||||
removed.
|
|
||||||
|
|
||||||
## Objective
|
|
||||||
|
|
||||||
Preserve and test host/CLI/debug direct cartridge boot without relying on a
|
|
||||||
guest syscall.
|
|
||||||
|
|
||||||
## Dependencies
|
|
||||||
|
|
||||||
- Source decision: `DEC-0035`.
|
|
||||||
- Can be implemented after or alongside `PLN-0129` and `PLN-0130`.
|
|
||||||
- Must not depend on `.pmc`, app catalog, launcher UX, `AGD-0041`, or
|
|
||||||
`AGD-0044`.
|
|
||||||
|
|
||||||
## Scope
|
|
||||||
|
|
||||||
- Identify direct boot entrypoints in `crates/tools/prometeu-cli/src/main.rs`,
|
|
||||||
`crates/host/prometeu-host-desktop-winit/src/lib.rs`,
|
|
||||||
`crates/host/prometeu-host-desktop-winit/src/debugger.rs`, and firmware
|
|
||||||
cartridge loading code.
|
|
||||||
- Add or preserve tests showing a cartridge can be loaded directly into
|
|
||||||
firmware/runtime from host or CLI paths.
|
|
||||||
- Ensure these paths do not call or require `system.run_cart`.
|
|
||||||
- Document the distinction between direct boot and guest navigation where
|
|
||||||
runtime specs describe boot behavior.
|
|
||||||
|
|
||||||
## Non-Goals
|
|
||||||
|
|
||||||
- Do not implement `Home -> another Game`.
|
|
||||||
- Do not add app-callable navigation.
|
|
||||||
- Do not require `.pmc`.
|
|
||||||
- Do not redesign cartridge loader internals beyond what is required to keep
|
|
||||||
direct boot working.
|
|
||||||
|
|
||||||
## Execution Method
|
|
||||||
|
|
||||||
1. Trace the CLI/debug direct boot path from cartridge path argument through
|
|
||||||
loader, firmware `load_cartridge`, and runtime initialization.
|
|
||||||
2. Add regression tests at the lowest practical layer proving direct boot still
|
|
||||||
reaches `GameRunning` for a valid game cartridge.
|
|
||||||
3. Add a guard or assertion that direct boot does not depend on `system.run_cart`
|
|
||||||
metadata.
|
|
||||||
4. Update docs/specs to describe direct boot as host/system-controlled.
|
|
||||||
5. Run targeted CLI/firmware/host tests.
|
|
||||||
|
|
||||||
## Acceptance Criteria
|
|
||||||
|
|
||||||
- A valid game cartridge can still boot directly from host/CLI/debug paths.
|
|
||||||
- Direct boot does not depend on `system.run_cart` being in the guest syscall
|
|
||||||
registry.
|
|
||||||
- Existing debugger/handshake metadata that reports cartridge info still works.
|
|
||||||
- The direct boot behavior is documented as host/system entry, not guest ABI.
|
|
||||||
|
|
||||||
## Tests
|
|
||||||
|
|
||||||
- Add or preserve firmware tests around `load_cartridge` and `GameRunning`.
|
|
||||||
- Add or preserve host/CLI tests for cartridge path boot when practical.
|
|
||||||
- Run `cargo test` for `prometeu-firmware`, `prometeu-host-desktop-winit`, and
|
|
||||||
`prometeu-cli` where available.
|
|
||||||
|
|
||||||
## Affected Artifacts
|
|
||||||
|
|
||||||
- `crates/tools/prometeu-cli/src/main.rs`
|
|
||||||
- `crates/host/prometeu-host-desktop-winit/src/lib.rs`
|
|
||||||
- `crates/host/prometeu-host-desktop-winit/src/debugger.rs`
|
|
||||||
- `crates/console/prometeu-firmware/src/firmware/firmware.rs`
|
|
||||||
- `crates/console/prometeu-firmware/src/firmware/firmware_step_load_cartridge.rs`
|
|
||||||
- `docs/specs/runtime/`
|
|
||||||
@@ -1,103 +0,0 @@
|
|||||||
---
|
|
||||||
id: PLN-0132
|
|
||||||
ticket: system-run-cart
|
|
||||||
title: Specify Games Root Home Launch Contract
|
|
||||||
status: done
|
|
||||||
created: 2026-07-03
|
|
||||||
ref_decisions: [DEC-0036]
|
|
||||||
tags: []
|
|
||||||
---
|
|
||||||
|
|
||||||
## Briefing
|
|
||||||
|
|
||||||
`DEC-0036` establishes a new system-owned game library launch path:
|
|
||||||
the host receives `--games-root <dir>`, SystemOS/Home lists valid Game
|
|
||||||
directory cartridges from that root, and selecting one starts the cartridge
|
|
||||||
through firmware loading rather than a guest syscall.
|
|
||||||
|
|
||||||
This plan updates the normative specs before code is changed.
|
|
||||||
|
|
||||||
## Objective
|
|
||||||
|
|
||||||
Document the v1 games-root and Home launch contract in the canonical runtime
|
|
||||||
specs so implementation plans cannot drift back into userland `run_cart` or
|
|
||||||
general app-library semantics.
|
|
||||||
|
|
||||||
## Dependencies
|
|
||||||
|
|
||||||
- Source decision: `DEC-0036`.
|
|
||||||
- Prior decision: `DEC-0035`, which removed userland `system.run_cart` and
|
|
||||||
preserved direct `--run` boot.
|
|
||||||
- This plan must be completed before `PLN-0133`, `PLN-0134`, and `PLN-0135`.
|
|
||||||
|
|
||||||
## Scope
|
|
||||||
|
|
||||||
- Update the runtime specs to define `--games-root <dir>` as the v1 local games
|
|
||||||
library root.
|
|
||||||
- Specify that discovery scans only immediate child directories.
|
|
||||||
- Specify that v1 library discovery includes only valid directory cartridges
|
|
||||||
with `app_mode: Game`.
|
|
||||||
- Specify that `.pmc`, recursive discovery, Shell/System apps, marketplace
|
|
||||||
metadata, rich presentation, search, and non-game apps are out of scope.
|
|
||||||
- Specify the internal library entry contract: loaded manifest data, `title`,
|
|
||||||
`app_id`, `app_version`, internal cartridge path, and discovery metadata.
|
|
||||||
- Specify that Home v1 may display only `title`, `app_id`, and `app_version`.
|
|
||||||
- Specify that selecting a Home game emits a system-owned launch request that
|
|
||||||
transitions through firmware/SystemOS into `LoadCartridge`.
|
|
||||||
- Specify that invalid candidates are logged and omitted.
|
|
||||||
- Specify that launch failure remains or returns to Home and logs the failure.
|
|
||||||
- Reaffirm that direct `--run <cart>` boot remains independent and unchanged.
|
|
||||||
|
|
||||||
## Non-Goals
|
|
||||||
|
|
||||||
- No Rust implementation.
|
|
||||||
- No Home UI changes.
|
|
||||||
- No `.pmc` discovery or packaged-cartridge spec changes.
|
|
||||||
- No recursive library layout.
|
|
||||||
- No return-to-Home behavior for a running Game.
|
|
||||||
- No Game A -> Home -> Game B orchestration.
|
|
||||||
- No guest syscall or userland ABI addition.
|
|
||||||
|
|
||||||
## Execution Method
|
|
||||||
|
|
||||||
1. Update [docs/specs/runtime/14-boot-profiles.md](/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/docs/specs/runtime/14-boot-profiles.md) with:
|
|
||||||
- direct `--run` boot remaining a single-cartridge boot profile;
|
|
||||||
- `--games-root <dir>` as a SystemOS/Home library profile;
|
|
||||||
- the distinction between direct boot, Home launch, and future game-switch
|
|
||||||
orchestration.
|
|
||||||
2. Update [docs/specs/runtime/12-firmware-pos-and-prometeuhub.md](/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/docs/specs/runtime/12-firmware-pos-and-prometeuhub.md) with:
|
|
||||||
- Home's responsibility to display the local games library;
|
|
||||||
- the system-owned launch action boundary;
|
|
||||||
- failure handling that leaves the machine in Home and records an error.
|
|
||||||
3. Update [docs/specs/runtime/13-cartridge.md](/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/docs/specs/runtime/13-cartridge.md) with:
|
|
||||||
- directory-cartridge discovery requirements for library candidates;
|
|
||||||
- Game-only filtering by manifest `app_mode`;
|
|
||||||
- invalid candidate omission and diagnostics.
|
|
||||||
4. Update [docs/specs/runtime/16-host-abi-and-syscalls.md](/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/docs/specs/runtime/16-host-abi-and-syscalls.md) only if needed to reinforce that no guest syscall owns cartridge launch.
|
|
||||||
5. Keep all spec text in English.
|
|
||||||
|
|
||||||
## Acceptance Criteria
|
|
||||||
|
|
||||||
- The specs define `--games-root <dir>` and do not describe it as a generic app
|
|
||||||
root.
|
|
||||||
- The specs state that v1 scans immediate child directories only.
|
|
||||||
- The specs state that only valid Game directory cartridges enter the Home list.
|
|
||||||
- The specs state that Home launch is system-owned and enters `LoadCartridge`.
|
|
||||||
- The specs preserve `--run <cart>` as a separate direct boot path.
|
|
||||||
- The specs explicitly exclude `.pmc`, recursive discovery, return-to-Home, and
|
|
||||||
game-switch orchestration from this implementation slice.
|
|
||||||
- No spec reintroduces userland `run_cart`.
|
|
||||||
|
|
||||||
## Tests
|
|
||||||
|
|
||||||
- Run `discussion validate`.
|
|
||||||
- Run targeted text checks for `--games-root`, `LoadCartridge`, and absence of
|
|
||||||
`system.run_cart` as an active public launch mechanism in edited specs.
|
|
||||||
|
|
||||||
## Affected Artifacts
|
|
||||||
|
|
||||||
- `docs/specs/runtime/12-firmware-pos-and-prometeuhub.md`
|
|
||||||
- `docs/specs/runtime/13-cartridge.md`
|
|
||||||
- `docs/specs/runtime/14-boot-profiles.md`
|
|
||||||
- `docs/specs/runtime/16-host-abi-and-syscalls.md`
|
|
||||||
- `discussion/workflow/plans/PLN-0132-specify-games-root-home-launch-contract.md`
|
|
||||||
@@ -1,118 +0,0 @@
|
|||||||
---
|
|
||||||
id: PLN-0133
|
|
||||||
ticket: system-run-cart
|
|
||||||
title: Implement Games Root Library Discovery
|
|
||||||
status: done
|
|
||||||
created: 2026-07-03
|
|
||||||
ref_decisions: [DEC-0036]
|
|
||||||
tags: []
|
|
||||||
---
|
|
||||||
|
|
||||||
## Briefing
|
|
||||||
|
|
||||||
`DEC-0036` requires a host-provided games root and an expandable internal
|
|
||||||
library model before Home can render or launch games. This plan implements the
|
|
||||||
library discovery and host plumbing only; UI launch wiring is handled by
|
|
||||||
`PLN-0134`.
|
|
||||||
|
|
||||||
## Objective
|
|
||||||
|
|
||||||
Add a tested games-root discovery model that scans immediate child directory
|
|
||||||
cartridges, filters to valid Game manifests, records diagnostics for invalid
|
|
||||||
candidates, and carries enough metadata for Home rendering and later launch.
|
|
||||||
|
|
||||||
## Dependencies
|
|
||||||
|
|
||||||
- Source decision: `DEC-0036`.
|
|
||||||
- `PLN-0132` should be completed first so code follows the documented contract.
|
|
||||||
- Existing cartridge manifest and directory loader behavior in the console
|
|
||||||
crates.
|
|
||||||
- Existing host CLI and `HostRunner` boot setup.
|
|
||||||
|
|
||||||
## Scope
|
|
||||||
|
|
||||||
- Add `--games-root <PATH>` to the desktop host CLI.
|
|
||||||
- Pass the optional games root into the host runner / firmware initialization
|
|
||||||
path without changing direct `--run` or `--debug` boot behavior.
|
|
||||||
- Add a SystemOS-owned games library model for directory cartridge discovery.
|
|
||||||
- Scan only immediate child directories of the root.
|
|
||||||
- Read and retain manifest data for each valid candidate.
|
|
||||||
- Include only candidates whose manifest declares `app_mode: Game`.
|
|
||||||
- Retain internal cartridge path and operational discovery metadata on each
|
|
||||||
entry.
|
|
||||||
- Emit diagnostics for invalid, unreadable, or non-Game candidates and omit
|
|
||||||
them from the returned entries.
|
|
||||||
- Keep discovery independent from full cartridge launch: discovery reads
|
|
||||||
metadata; launch still uses the existing loader in `PLN-0134`.
|
|
||||||
|
|
||||||
## Non-Goals
|
|
||||||
|
|
||||||
- No Home list rendering.
|
|
||||||
- No click handling or `LoadCartridge` transition.
|
|
||||||
- No `.pmc` discovery.
|
|
||||||
- No recursive scan.
|
|
||||||
- No Shell/System app catalog.
|
|
||||||
- No marketplace metadata, icons, search, sorting UI, or polished errors.
|
|
||||||
- No new guest syscall.
|
|
||||||
|
|
||||||
## Execution Method
|
|
||||||
|
|
||||||
1. Introduce a library/discovery module in the SystemOS side, preferably under
|
|
||||||
`crates/console/prometeu-system/src/services/` unless the existing module
|
|
||||||
layout has a more local owner.
|
|
||||||
2. Define an internal entry type with at least:
|
|
||||||
- loaded cartridge manifest data;
|
|
||||||
- `title`;
|
|
||||||
- `app_id`;
|
|
||||||
- `app_version`;
|
|
||||||
- internal cartridge path;
|
|
||||||
- discovery metadata, using `SystemTime` or another explicit discovery
|
|
||||||
marker.
|
|
||||||
3. Define discovery diagnostics that can be logged by the caller and asserted in
|
|
||||||
tests.
|
|
||||||
4. Implement a scanner that:
|
|
||||||
- accepts an optional root path;
|
|
||||||
- returns an empty library when no root is configured;
|
|
||||||
- iterates only immediate child directories;
|
|
||||||
- parses `manifest.json` using structured manifest types, not ad hoc string
|
|
||||||
matching;
|
|
||||||
- filters to `app_mode: Game`;
|
|
||||||
- sorts entries deterministically for stable Home presentation and tests.
|
|
||||||
5. Add `--games-root <PATH>` to
|
|
||||||
[crates/host/prometeu-host-desktop-winit/src/lib.rs](/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/host/prometeu-host-desktop-winit/src/lib.rs)
|
|
||||||
and pass the path into
|
|
||||||
[crates/host/prometeu-host-desktop-winit/src/runner.rs](/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/host/prometeu-host-desktop-winit/src/runner.rs).
|
|
||||||
6. Store or expose the discovered library to firmware/SystemOS in a way that
|
|
||||||
`PLN-0134` can consume without re-scanning inside the Home click path.
|
|
||||||
7. Add focused unit tests using temporary cartridge roots with:
|
|
||||||
- one valid Game directory cartridge;
|
|
||||||
- one valid non-Game cartridge;
|
|
||||||
- one invalid directory;
|
|
||||||
- one nested directory that must not be discovered.
|
|
||||||
|
|
||||||
## Acceptance Criteria
|
|
||||||
|
|
||||||
- `--games-root <PATH>` is accepted by the desktop host CLI.
|
|
||||||
- Absence of `--games-root` leaves existing Hub boot behavior unchanged.
|
|
||||||
- Direct `--run <cart>` and `--debug <cart>` behavior remains unchanged.
|
|
||||||
- Discovery returns only immediate valid Game directory cartridges.
|
|
||||||
- Each library entry retains manifest data, path, title, app id, app version,
|
|
||||||
and discovery metadata.
|
|
||||||
- Invalid candidates are represented in diagnostics and excluded from entries.
|
|
||||||
- Discovery does not fully load or boot cartridge programs.
|
|
||||||
|
|
||||||
## Tests
|
|
||||||
|
|
||||||
- Add and run focused games-library discovery tests in the owning console crate.
|
|
||||||
- Run `cargo test -p prometeu-system` if the library lives in
|
|
||||||
`prometeu-system`.
|
|
||||||
- Run `cargo test -p prometeu-host-desktop-winit` for CLI/runner plumbing.
|
|
||||||
- Run `discussion validate`.
|
|
||||||
|
|
||||||
## Affected Artifacts
|
|
||||||
|
|
||||||
- `crates/console/prometeu-system/src/services/`
|
|
||||||
- `crates/console/prometeu-system/src/lib.rs` or module exports as needed
|
|
||||||
- `crates/host/prometeu-host-desktop-winit/src/lib.rs`
|
|
||||||
- `crates/host/prometeu-host-desktop-winit/src/runner.rs`
|
|
||||||
- `discussion/workflow/plans/PLN-0133-implement-games-root-library-discovery.md`
|
|
||||||
@@ -1,104 +0,0 @@
|
|||||||
---
|
|
||||||
id: PLN-0134
|
|
||||||
ticket: system-run-cart
|
|
||||||
title: Wire Home Game List Launch Flow
|
|
||||||
status: done
|
|
||||||
created: 2026-07-03
|
|
||||||
ref_decisions: [DEC-0036]
|
|
||||||
tags: []
|
|
||||||
---
|
|
||||||
|
|
||||||
## Briefing
|
|
||||||
|
|
||||||
After `PLN-0133`, SystemOS can discover a local Game library but Home still
|
|
||||||
does not present or launch those entries. This plan wires the discovered
|
|
||||||
library into Prometeu Hub/Home and routes a selected game to firmware
|
|
||||||
`LoadCartridge`.
|
|
||||||
|
|
||||||
## Objective
|
|
||||||
|
|
||||||
Make Home display a minimal clickable games list and launch the selected Game
|
|
||||||
through a system-owned firmware/SystemOS path, without reintroducing userland
|
|
||||||
`run_cart`.
|
|
||||||
|
|
||||||
## Dependencies
|
|
||||||
|
|
||||||
- Source decision: `DEC-0036`.
|
|
||||||
- `PLN-0132` for documented contract.
|
|
||||||
- `PLN-0133` for `--games-root` plumbing and the internal library entry model.
|
|
||||||
- Existing Prometeu Hub Home profile and firmware state transitions.
|
|
||||||
|
|
||||||
## Scope
|
|
||||||
|
|
||||||
- Provide the discovered games library to Prometeu Hub/Home.
|
|
||||||
- Render a minimal Home list showing `title`, `app_id`, and `app_version`.
|
|
||||||
- Add Home hit-testing/click handling for game entries.
|
|
||||||
- Extend the system profile action model with a system-owned game launch action.
|
|
||||||
- Handle that action in firmware/SystemOS by loading the selected cartridge via
|
|
||||||
the existing cartridge loader and entering `LoadCartridge`.
|
|
||||||
- On load failure, log/record the error and keep or return the machine to Home.
|
|
||||||
- Preserve existing native shell launch behavior.
|
|
||||||
|
|
||||||
## Non-Goals
|
|
||||||
|
|
||||||
- No polished launcher UI.
|
|
||||||
- No icons, screenshots, search, filtering, or marketplace metadata.
|
|
||||||
- No return-to-Home while a Game is running.
|
|
||||||
- No Game A -> Home -> Game B foreground orchestration.
|
|
||||||
- No `.pmc` launch support.
|
|
||||||
- No guest syscall.
|
|
||||||
- No direct-boot behavior changes.
|
|
||||||
|
|
||||||
## Execution Method
|
|
||||||
|
|
||||||
1. Extend the SystemOS/Hub action type currently represented by
|
|
||||||
`SystemProfileAction::LaunchNativeShell` with a game-launch action that
|
|
||||||
carries a stable reference to the selected library entry or cartridge path.
|
|
||||||
2. Update the Prometeu Hub state in
|
|
||||||
[crates/console/prometeu-system/src/programs/prometeu_hub.rs](/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/console/prometeu-system/src/programs/prometeu_hub.rs)
|
|
||||||
or its local modules to accept the discovered game entries.
|
|
||||||
3. Render the Home games list with stable dimensions and simple clickable rows.
|
|
||||||
Rows must display only `title`, `app_id`, and `app_version` for v1.
|
|
||||||
4. Add hit-testing so selecting a row emits the game-launch action immediately.
|
|
||||||
5. Update
|
|
||||||
[crates/console/prometeu-firmware/src/firmware/steps/firmware_step_hub_home.rs](/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/console/prometeu-firmware/src/firmware/steps/firmware_step_hub_home.rs)
|
|
||||||
to consume the new action.
|
|
||||||
6. In the firmware action handler:
|
|
||||||
- call the existing cartridge loader for the selected path;
|
|
||||||
- on success, return `FirmwareState::LoadCartridge(...)`;
|
|
||||||
- on failure, log/record the error and remain in the Home path.
|
|
||||||
7. Ensure shell launch still works exactly as before.
|
|
||||||
8. Add unit or integration tests for:
|
|
||||||
- Home list presentation data;
|
|
||||||
- click-to-action emission;
|
|
||||||
- firmware action handling success;
|
|
||||||
- firmware action handling failure.
|
|
||||||
|
|
||||||
## Acceptance Criteria
|
|
||||||
|
|
||||||
- Starting the host with `--games-root <dir>` exposes valid Game entries in
|
|
||||||
Home.
|
|
||||||
- The Home list displays `title`, `app_id`, and `app_version`.
|
|
||||||
- Clicking a listed Game routes through a system action and enters
|
|
||||||
`LoadCartridge`.
|
|
||||||
- The launch path does not use a guest syscall and does not mention
|
|
||||||
`system.run_cart`.
|
|
||||||
- Invalid or failing launch paths remain in Home and record an error.
|
|
||||||
- Existing native shell Home actions continue to work.
|
|
||||||
- Direct `--run` remains separate and unchanged.
|
|
||||||
|
|
||||||
## Tests
|
|
||||||
|
|
||||||
- Run `cargo test -p prometeu-system` for Hub action and presentation behavior.
|
|
||||||
- Run `cargo test -p prometeu-firmware` for firmware transition behavior.
|
|
||||||
- Run `cargo test -p prometeu-host-desktop-winit` if runner integration changes.
|
|
||||||
- Run `discussion validate`.
|
|
||||||
|
|
||||||
## Affected Artifacts
|
|
||||||
|
|
||||||
- `crates/console/prometeu-system/src/programs/prometeu_hub.rs`
|
|
||||||
- `crates/console/prometeu-system/src/services/`
|
|
||||||
- `crates/console/prometeu-firmware/src/firmware/steps/firmware_step_hub_home.rs`
|
|
||||||
- `crates/console/prometeu-firmware/src/firmware/firmware.rs`
|
|
||||||
- `crates/host/prometeu-host-desktop-winit/src/runner.rs`
|
|
||||||
- `discussion/workflow/plans/PLN-0134-wire-home-game-list-launch-flow.md`
|
|
||||||
@@ -1,99 +0,0 @@
|
|||||||
---
|
|
||||||
id: PLN-0135
|
|
||||||
ticket: system-run-cart
|
|
||||||
title: Validate Games Root Launch End To End
|
|
||||||
status: done
|
|
||||||
created: 2026-07-03
|
|
||||||
ref_decisions: [DEC-0036]
|
|
||||||
tags: []
|
|
||||||
---
|
|
||||||
|
|
||||||
## Briefing
|
|
||||||
|
|
||||||
`PLN-0132` through `PLN-0134` specify, discover, display, and launch games
|
|
||||||
from a local games root. This plan closes the slice by adding end-to-end
|
|
||||||
validation evidence and manual smoke instructions for the product behavior the
|
|
||||||
user wants: point the SO at a directory, click a listed game, and boot it.
|
|
||||||
|
|
||||||
## Objective
|
|
||||||
|
|
||||||
Prove the complete `--games-root -> Home list -> click -> LoadCartridge ->
|
|
||||||
GameRunning` path while preserving direct `--run` boot and the absence of
|
|
||||||
userland `run_cart`.
|
|
||||||
|
|
||||||
## Dependencies
|
|
||||||
|
|
||||||
- Source decision: `DEC-0036`.
|
|
||||||
- `PLN-0132`, `PLN-0133`, and `PLN-0134` must be complete.
|
|
||||||
- Existing test cartridge fixtures, especially `test-cartridges/stress-console`.
|
|
||||||
|
|
||||||
## Scope
|
|
||||||
|
|
||||||
- Add automated integration coverage for the full games-root Home launch path
|
|
||||||
where the existing host/firmware test seams allow it.
|
|
||||||
- Add or document a minimal local games-root fixture using existing directory
|
|
||||||
cartridges.
|
|
||||||
- Validate invalid-candidate omission at the end-to-end boundary.
|
|
||||||
- Validate direct `--run` still works after games-root wiring.
|
|
||||||
- Capture manual smoke-test commands for release-mode functional verification.
|
|
||||||
|
|
||||||
## Non-Goals
|
|
||||||
|
|
||||||
- No new product UI polish.
|
|
||||||
- No screenshot automation unless the existing test harness already supports it
|
|
||||||
cleanly.
|
|
||||||
- No return-to-Home after a running Game.
|
|
||||||
- No Game A -> Home -> Game B orchestration.
|
|
||||||
- No `.pmc` validation.
|
|
||||||
- No broad performance tuning beyond confirming release-mode smoke behavior.
|
|
||||||
|
|
||||||
## Execution Method
|
|
||||||
|
|
||||||
1. Add an integration-style firmware or host test that constructs a games root
|
|
||||||
with a valid Game directory cartridge and boots to Hub/Home with that root.
|
|
||||||
2. Drive the Home selection path through the same action path used by user
|
|
||||||
input, not by calling the cartridge loader directly.
|
|
||||||
3. Assert that the machine reaches `LoadCartridge` or `GameRunning`, depending
|
|
||||||
on the most stable observable state available in the test harness.
|
|
||||||
4. Add a negative case with an invalid candidate and assert it is omitted or
|
|
||||||
reported as a diagnostic without appearing in Home.
|
|
||||||
5. Add a regression assertion that no public guest syscall named
|
|
||||||
`system.run_cart` is required by this path.
|
|
||||||
6. Re-run direct boot tests or add a small regression test proving
|
|
||||||
`--run test-cartridges/stress-console` remains independent from
|
|
||||||
`--games-root`.
|
|
||||||
7. Record manual smoke commands in the relevant spec or developer-facing doc:
|
|
||||||
- `cargo run --release -p prometeu-host-desktop-winit -- --games-root test-cartridges`
|
|
||||||
- `cargo run --release -p prometeu-host-desktop-winit -- --run test-cartridges/stress-console`
|
|
||||||
|
|
||||||
## Acceptance Criteria
|
|
||||||
|
|
||||||
- Automated tests cover a valid games-root Home launch path.
|
|
||||||
- Automated tests cover invalid candidate omission or diagnostics at the
|
|
||||||
end-to-end boundary.
|
|
||||||
- Automated or documented validation proves direct `--run` still works.
|
|
||||||
- Manual smoke instructions use release mode for realistic interactive speed.
|
|
||||||
- Validation evidence shows no guest syscall participates in launch.
|
|
||||||
- `discussion validate` passes.
|
|
||||||
|
|
||||||
## Tests
|
|
||||||
|
|
||||||
- Run `cargo test -p prometeu-system`.
|
|
||||||
- Run `cargo test -p prometeu-firmware`.
|
|
||||||
- Run `cargo test -p prometeu-host-desktop-winit`.
|
|
||||||
- Run `cargo test -p prometeu-hal syscalls` to keep the removed syscall surface
|
|
||||||
guarded.
|
|
||||||
- Manually smoke test:
|
|
||||||
`cargo run --release -p prometeu-host-desktop-winit -- --games-root test-cartridges`.
|
|
||||||
- Manually smoke test:
|
|
||||||
`cargo run --release -p prometeu-host-desktop-winit -- --run test-cartridges/stress-console`.
|
|
||||||
- Run `discussion validate`.
|
|
||||||
|
|
||||||
## Affected Artifacts
|
|
||||||
|
|
||||||
- `crates/console/prometeu-system/`
|
|
||||||
- `crates/console/prometeu-firmware/`
|
|
||||||
- `crates/host/prometeu-host-desktop-winit/`
|
|
||||||
- `crates/console/prometeu-hal/src/syscalls/tests.rs`
|
|
||||||
- Runtime specs or developer docs containing smoke commands
|
|
||||||
- `discussion/workflow/plans/PLN-0135-validate-games-root-launch-end-to-end.md`
|
|
||||||
@@ -239,8 +239,10 @@ The same physical surface may be reused by multiple visual owners, but logical
|
|||||||
ownership MUST remain explicit.
|
ownership MUST remain explicit.
|
||||||
|
|
||||||
Game pause/resume, foreground stack behavior, and coexistence of a paused Game
|
Game pause/resume, foreground stack behavior, and coexistence of a paused Game
|
||||||
with VM-backed Shell apps are outside this contract and are tracked by the
|
with VM-backed Shell apps are defined by the foreground/lifecycle contract. The
|
||||||
foreground/lifecycle discussion.
|
render boundary's responsibility is narrower: foreground owner changes MUST
|
||||||
|
advance ownership, stale submissions MUST be discarded, and visual return to a
|
||||||
|
resumed Game MUST wait for a valid submission from the current ownership epoch.
|
||||||
|
|
||||||
### 4.7 Render telemetry
|
### 4.7 Render telemetry
|
||||||
|
|
||||||
@@ -623,7 +625,8 @@ Each tilemap cell contains:
|
|||||||
|
|
||||||
Runtime-facing validity rule for v1:
|
Runtime-facing validity rule for v1:
|
||||||
|
|
||||||
- `palette_id` values are valid only in the range `0..63`
|
- `palette_id` values are valid only when `palette_id < palette_count` for the
|
||||||
|
resolved resident glyph bank
|
||||||
|
|
||||||
#### Sprite
|
#### Sprite
|
||||||
|
|
||||||
@@ -638,7 +641,8 @@ Each sprite draw contains:
|
|||||||
|
|
||||||
Runtime-facing validity rule for v1:
|
Runtime-facing validity rule for v1:
|
||||||
|
|
||||||
- `palette_id` values are valid only in the range `0..63`
|
- `palette_id` values are valid only when `palette_id < palette_count` for the
|
||||||
|
referenced resident glyph bank
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -647,7 +651,7 @@ Runtime-facing validity rule for v1:
|
|||||||
The pipeline works like this:
|
The pipeline works like this:
|
||||||
|
|
||||||
1. Read indexed pixel from tile (value 0..15)
|
1. Read indexed pixel from tile (value 0..15)
|
||||||
2. Resolve:
|
2. Validate and resolve:
|
||||||
- real_color = palette[palette_id][index]
|
- real_color = palette[palette_id][index]
|
||||||
3. Apply:
|
3. Apply:
|
||||||
- flip
|
- flip
|
||||||
@@ -665,6 +669,9 @@ else:
|
|||||||
draw_or_blend(color)
|
draw_or_blend(color)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The `palette_id` lookup above is valid only after the runtime has established
|
||||||
|
that the referenced resident glyph bank contains that palette.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 19.7. Organization of Tile Banks
|
### 19.7. Organization of Tile Banks
|
||||||
@@ -764,6 +771,8 @@ Rules:
|
|||||||
- missing glyph dependencies referenced by a resident scene are not a passive `status:int` case;
|
- missing glyph dependencies referenced by a resident scene are not a passive `status:int` case;
|
||||||
- if scene activation discovers that a layer dependency cannot be resolved to a committed glyph asset, the machine MUST fail fatally and emit a clear log;
|
- if scene activation discovers that a layer dependency cannot be resolved to a committed glyph asset, the machine MUST fail fatally and emit a clear log;
|
||||||
- if scene composition later discovers that a layer dependency can no longer be resolved, the machine MUST fail fatally and emit a clear log;
|
- if scene composition later discovers that a layer dependency can no longer be resolved, the machine MUST fail fatally and emit a clear log;
|
||||||
|
- if scene activation or composition discovers that a tile references `palette_id >= palette_count` for its resolved glyph bank, the machine MUST fail fatally and emit a clear log;
|
||||||
|
- invalid scene palette references are scene dependency failures and MUST NOT be rendered through transparent, black, or default color substitution;
|
||||||
- runtime MUST NOT continue canonical scene composition after such a dependency failure.
|
- runtime MUST NOT continue canonical scene composition after such a dependency failure.
|
||||||
|
|
||||||
### 20.2 `composer.emit_sprite`
|
### 20.2 `composer.emit_sprite`
|
||||||
@@ -772,7 +781,7 @@ Rules:
|
|||||||
|
|
||||||
ABI:
|
ABI:
|
||||||
1. `glyph_id: int` — glyph index within the bank
|
1. `glyph_id: int` — glyph index within the bank
|
||||||
2. `palette_id: int` — palette index
|
2. `palette_id: int` — palette index within the referenced bank; valid only when `palette_id < palette_count` for that resident glyph bank
|
||||||
3. `x: int` — x coordinate
|
3. `x: int` — x coordinate
|
||||||
4. `y: int` — y coordinate
|
4. `y: int` — y coordinate
|
||||||
5. `layer: int` — composition layer reference
|
5. `layer: int` — composition layer reference
|
||||||
@@ -795,4 +804,6 @@ Operational notes:
|
|||||||
- the canonical public sprite contract is frame-emission based;
|
- the canonical public sprite contract is frame-emission based;
|
||||||
- no caller-provided sprite index exists in the v1 canonical ABI;
|
- no caller-provided sprite index exists in the v1 canonical ABI;
|
||||||
- no `active` flag exists in the v1 canonical ABI;
|
- no `active` flag exists in the v1 canonical ABI;
|
||||||
|
- `palette_id >= palette_count` for the referenced glyph bank MUST return `BANK_INVALID`;
|
||||||
|
- invalid sprite palette references MUST NOT be rendered through transparent, black, or default color substitution;
|
||||||
- overflow remains non-fatal and must not escalate to trap in v1.
|
- overflow remains non-fatal and must not escalate to trap in v1.
|
||||||
|
|||||||
@@ -107,3 +107,21 @@ Input access is VM-owned and should not be reported as host syscall consumption.
|
|||||||
All platforms must provide the mandatory input elements (`pad`, `touch`, `button`) to the runtime.
|
All platforms must provide the mandatory input elements (`pad`, `touch`, `button`) to the runtime.
|
||||||
|
|
||||||
Platform differences in physical device mapping are resolved outside VM semantics.
|
Platform differences in physical device mapping are resolved outside VM semantics.
|
||||||
|
|
||||||
|
## 9 Host/System Controls
|
||||||
|
|
||||||
|
Host/System controls are not part of the guest-visible input surface.
|
||||||
|
|
||||||
|
The Home/SystemOS request changes machine foreground authority. It must be
|
||||||
|
handled by the host, firmware, or SystemOS before input is exposed to the Game.
|
||||||
|
It must not be represented as `pad.start`, `pad.select`, a new pad field, a VM
|
||||||
|
intrinsic, or a userland syscall.
|
||||||
|
|
||||||
|
For the desktop host, `Esc` is the primary keyboard mapping for the
|
||||||
|
Home/SystemOS request. The physical `Home` key may be supported as an alias.
|
||||||
|
Both mappings are host controls and must not mutate `InputSignals`.
|
||||||
|
|
||||||
|
When a Game leaves or re-enters foreground, pending Game input must be cleared
|
||||||
|
or barriered so held or pressed input cannot leak across pause/resume
|
||||||
|
boundaries. This barrier applies to the Game-facing snapshot; it does not
|
||||||
|
change the meaning of host/system Home controls.
|
||||||
|
|||||||
@@ -100,7 +100,89 @@ Important properties:
|
|||||||
- no execution occurs outside the frame loop;
|
- no execution occurs outside the frame loop;
|
||||||
- frame structure remains observable for host tooling and host-owned certification.
|
- frame structure remains observable for host tooling and host-owned certification.
|
||||||
|
|
||||||
## 7 Render Worker Concurrency
|
## 7 Foreground Lifecycle Events
|
||||||
|
|
||||||
|
Foreground lifecycle events are system events with bounded delivery points.
|
||||||
|
They do not execute arbitrary guest callbacks at arrival time.
|
||||||
|
|
||||||
|
The Game pause path is:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Home/SystemOS request
|
||||||
|
-> pause event becomes visible to the Game
|
||||||
|
-> bounded pause reaction budget
|
||||||
|
-> SystemOS suspension, even if the Game did not cooperate
|
||||||
|
```
|
||||||
|
|
||||||
|
The Game resume path is:
|
||||||
|
|
||||||
|
```text
|
||||||
|
SystemOS resume request
|
||||||
|
-> VM reactivation
|
||||||
|
-> resume or foreground-restore event becomes visible to the Game
|
||||||
|
-> Game may synchronize while still internally paused
|
||||||
|
-> visual foreground returns after a valid current-epoch render submission
|
||||||
|
```
|
||||||
|
|
||||||
|
`Paused` is the Game-visible event/state. `Suspended` is the OS-owned
|
||||||
|
scheduler/runtime state. A Game may observe pause/resume, but it must not
|
||||||
|
control whether SystemOS suspends or resumes the VM.
|
||||||
|
|
||||||
|
When SystemOS replaces one Game with another from Home, the old Game MAY receive
|
||||||
|
a cooperative terminate/save lifecycle event if the runtime supports such an
|
||||||
|
event. That event is non-blocking in v1. SystemOS remains authoritative and may
|
||||||
|
close the old Game task/session without guest acknowledgement.
|
||||||
|
|
||||||
|
Pause budgets are measured in deterministic machine units, not host wall-clock
|
||||||
|
time. A suspended Game receives no normal gameplay ticks, no normal Game input,
|
||||||
|
and no frame pacing. Real background execution is outside the v1 foreground
|
||||||
|
contract.
|
||||||
|
|
||||||
|
## 8 VM Sessions and Execution Eligibility
|
||||||
|
|
||||||
|
Every VM-backed process MUST own a distinct VM session. A VM session owns the
|
||||||
|
mutable execution context for that process, including the VM instance,
|
||||||
|
per-session runtime counters, lifecycle delivery bookkeeping, debug/pause state,
|
||||||
|
and transient handles opened through VM-facing services.
|
||||||
|
|
||||||
|
Foreground ownership and execution eligibility are related but separate
|
||||||
|
concepts:
|
||||||
|
|
||||||
|
- foreground ownership selects the visual/navigation owner;
|
||||||
|
- execution eligibility selects which sessions may receive VM ticks;
|
||||||
|
- v1 grants normal VM execution only to the foreground VM-backed task, plus the
|
||||||
|
bounded Game pause handoff tick defined above;
|
||||||
|
- a suspended resident Game preserves its VM session but MUST NOT receive
|
||||||
|
normal gameplay ticks, normal Game input, or frame pacing;
|
||||||
|
- a VM-backed Shell owns its own VM session and MUST NOT overwrite or advance
|
||||||
|
the resident Game session while the Shell is foreground;
|
||||||
|
- a native Shell does not own a VM session.
|
||||||
|
|
||||||
|
The model is intentionally compatible with future background execution. Future
|
||||||
|
service or media processes may become execution-eligible without changing the
|
||||||
|
rule that mutable VM context belongs to the owning session. This chapter does
|
||||||
|
not grant any v1 background progress guarantee.
|
||||||
|
|
||||||
|
Durable app data remains keyed by `app_id` where the relevant storage contract
|
||||||
|
requires it. Transient VM handles, open files, lifecycle delivery queues, and
|
||||||
|
staging state are session-scoped unless another spec explicitly makes them
|
||||||
|
durable app data.
|
||||||
|
|
||||||
|
During destructive Game replacement, the old Game VM session MUST be removed
|
||||||
|
from execution eligibility and resumable state before the new Game becomes the
|
||||||
|
foreground Game. The new Game MUST receive a fresh VM session. Failure while
|
||||||
|
loading or initializing the replacement Game MUST return the machine to
|
||||||
|
Hub/Home and MUST NOT restore the previous Game in v1.
|
||||||
|
|
||||||
|
Manual Hub termination of a suspended resident Game has the same session
|
||||||
|
removal authority as destructive Game replacement, except that no replacement
|
||||||
|
Game is started. SystemOS MUST remove the Game from execution eligibility and
|
||||||
|
resumable state, close its task, stop its process, remove its VM session, clear
|
||||||
|
task-scoped pending lifecycle delivery, and keep Hub/Home as the foreground
|
||||||
|
owner. After manual Hub termination, resume queries MUST report no resident
|
||||||
|
Game. A later launch of the same cartridge is a fresh Game session.
|
||||||
|
|
||||||
|
## 9 Render Worker Concurrency
|
||||||
|
|
||||||
The render worker is not a machine-visible event source and does not introduce
|
The render worker is not a machine-visible event source and does not introduce
|
||||||
guest callbacks. It is an implementation-side consumer of closed render
|
guest callbacks. It is an implementation-side consumer of closed render
|
||||||
@@ -127,7 +209,7 @@ Shutdown is explicit and bounded. A shutdown request wakes a waiting worker,
|
|||||||
causes pending work that will not be consumed to be discarded, and reports a
|
causes pending work that will not be consumed to be discarded, and reports a
|
||||||
typed failure if the worker cannot join within the configured timeout.
|
typed failure if the worker cannot join within the configured timeout.
|
||||||
|
|
||||||
## 8 Async Asset and IO Work Lane
|
## 10 Async Asset and IO Work Lane
|
||||||
|
|
||||||
The asset/IO async work lane is not a machine-visible event source and does not
|
The asset/IO async work lane is not a machine-visible event source and does not
|
||||||
introduce guest callbacks. It is an implementation-side lane for asset
|
introduce guest callbacks. It is an implementation-side lane for asset
|
||||||
@@ -151,7 +233,7 @@ does not publish resident graphics/audio/scene state directly.
|
|||||||
FS and game persistence services may consume this lane for IO-style work, but
|
FS and game persistence services may consume this lane for IO-style work, but
|
||||||
public FS API shape is defined by the FS/app-home contract, not by this chapter.
|
public FS API shape is defined by the FS/app-home contract, not by this chapter.
|
||||||
|
|
||||||
## 9 Determinism and Best Practices
|
## 11 Determinism and Best Practices
|
||||||
|
|
||||||
PROMETEU encourages:
|
PROMETEU encourages:
|
||||||
|
|
||||||
@@ -166,7 +248,7 @@ PROMETEU discourages:
|
|||||||
- hidden timing channels;
|
- hidden timing channels;
|
||||||
- ambiguous out-of-band execution.
|
- ambiguous out-of-band execution.
|
||||||
|
|
||||||
## 10 Relationship to Other Specs
|
## 12 Relationship to Other Specs
|
||||||
|
|
||||||
- [`09a-coroutines-and-cooperative-scheduling.md`](09a-coroutines-and-cooperative-scheduling.md) defines coroutine lifecycle and scheduling behavior.
|
- [`09a-coroutines-and-cooperative-scheduling.md`](09a-coroutines-and-cooperative-scheduling.md) defines coroutine lifecycle and scheduling behavior.
|
||||||
- [`10-debug-inspection-and-profiling.md`](10-debug-inspection-and-profiling.md) defines observability and diagnostics surfaces.
|
- [`10-debug-inspection-and-profiling.md`](10-debug-inspection-and-profiling.md) defines observability and diagnostics surfaces.
|
||||||
|
|||||||
@@ -44,6 +44,11 @@ PROMETEU operates in three main modes:
|
|||||||
|
|
||||||
No mode alters the logical result of the program.
|
No mode alters the logical result of the program.
|
||||||
|
|
||||||
|
Debug boot is a host-selected direct cartridge boot profile. It follows the same
|
||||||
|
cartridge/app-mode resolution path as direct boot and is separate from
|
||||||
|
Home-driven Game switching. Debug boot MUST NOT be modeled as a guest-visible
|
||||||
|
Game switch request and MUST NOT reuse a Home switch failure-recovery contract.
|
||||||
|
|
||||||
## 3 Execution Control
|
## 3 Execution Control
|
||||||
|
|
||||||
### 3.1 Pause and Resume
|
### 3.1 Pause and Resume
|
||||||
|
|||||||
@@ -43,13 +43,28 @@ The VM does not own the machine lifecycle. Firmware does.
|
|||||||
Game directory cartridges.
|
Game directory cartridges.
|
||||||
- **Library entry**: an internal catalog record retained by Hub/SystemOS for a
|
- **Library entry**: an internal catalog record retained by Hub/SystemOS for a
|
||||||
discovered cartridge.
|
discovered cartridge.
|
||||||
|
- **Game switch target**: a SystemOS-owned launch target derived from a library
|
||||||
|
entry. It carries the cartridge path plus resolved identity such as `app_id`,
|
||||||
|
`title`, and `app_version`.
|
||||||
|
- **Foreground visual owner**: the single machine owner whose visual output may
|
||||||
|
be presented at a given time.
|
||||||
|
- **Paused**: a Game-visible lifecycle event/state. The Game may observe it and
|
||||||
|
prepare for foreground loss.
|
||||||
|
- **Suspended**: an OS-owned scheduler/runtime state. A suspended Game remains
|
||||||
|
resident but does not receive normal gameplay ticks, normal Game input, or
|
||||||
|
frame pacing.
|
||||||
|
- **VM session**: the POS-owned mutable execution context for one VM-backed
|
||||||
|
process. It contains the VM instance and per-session runtime state.
|
||||||
|
- **Hub resident Game kill control**: a Hub/Home affordance that terminates the
|
||||||
|
current resident Game instead of resuming it.
|
||||||
|
|
||||||
## 3 POS Responsibilities
|
## 3 POS Responsibilities
|
||||||
|
|
||||||
POS is responsible for:
|
POS is responsible for:
|
||||||
|
|
||||||
- deterministic reset into known machine state;
|
- deterministic reset into known machine state;
|
||||||
- VM initialization and teardown for cartridge execution;
|
- VM session creation, initialization, activation, and teardown for cartridge
|
||||||
|
execution;
|
||||||
- input latching and logical-frame budgeting;
|
- input latching and logical-frame budgeting;
|
||||||
- peripheral reset/orchestration;
|
- peripheral reset/orchestration;
|
||||||
- fault capture and crash-flow transition;
|
- fault capture and crash-flow transition;
|
||||||
@@ -61,6 +76,10 @@ At the VM boundary, POS must preserve:
|
|||||||
- `FRAME_SYNC` as the canonical frame boundary;
|
- `FRAME_SYNC` as the canonical frame boundary;
|
||||||
- deterministic transition from host tick to VM slice execution.
|
- deterministic transition from host tick to VM slice execution.
|
||||||
|
|
||||||
|
Firmware must not treat a single global VM object as the canonical execution
|
||||||
|
owner for all cartridges. The firmware state machine orchestrates macro-state;
|
||||||
|
POS/session services own VM-backed process context.
|
||||||
|
|
||||||
## 4 PrometeuHub Responsibilities
|
## 4 PrometeuHub Responsibilities
|
||||||
|
|
||||||
PrometeuHub is responsible for:
|
PrometeuHub is responsible for:
|
||||||
@@ -72,6 +91,8 @@ PrometeuHub is responsible for:
|
|||||||
- presenting the host-provided local games library when `--games-root <dir>` is
|
- presenting the host-provided local games library when `--games-root <dir>` is
|
||||||
configured;
|
configured;
|
||||||
- emitting system-owned launch actions for selected Home entries.
|
- emitting system-owned launch actions for selected Home entries.
|
||||||
|
- presenting a resident Game kill control while Hub/Home owns foreground and a
|
||||||
|
Game is resident/suspended.
|
||||||
|
|
||||||
The Hub does not execute bytecode directly. It always delegates execution setup to POS.
|
The Hub does not execute bytecode directly. It always delegates execution setup to POS.
|
||||||
|
|
||||||
@@ -154,19 +175,125 @@ Shell task loses its eligible focused window
|
|||||||
-> FirmwareState::HubHome
|
-> FirmwareState::HubHome
|
||||||
```
|
```
|
||||||
|
|
||||||
## 7 Cartridge Load Flow
|
## 7 Foreground Stack and Game Pause
|
||||||
|
|
||||||
|
The v1 foreground contract is single-owner:
|
||||||
|
|
||||||
|
- exactly one foreground visual owner exists at a time;
|
||||||
|
- at most one Game may be resident;
|
||||||
|
- at most one Shell app may be foreground;
|
||||||
|
- Hub/Home is the root Shell owner and back-stack controller.
|
||||||
|
|
||||||
|
The minimal supported navigation cycle is:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Game foreground
|
||||||
|
-> Home request
|
||||||
|
-> Game pause notification
|
||||||
|
-> Game suspended by SystemOS after a bounded budget
|
||||||
|
-> Hub/Home foreground
|
||||||
|
-> optional Shell foreground
|
||||||
|
-> Shell close returns to Hub/Home
|
||||||
|
-> same Game resume/foreground-restore notification
|
||||||
|
-> Game foreground after a valid current-epoch render submission
|
||||||
|
```
|
||||||
|
|
||||||
|
`Paused` is cooperative and visible to the Game. `Suspended` is imposed by
|
||||||
|
SystemOS. The Game may react to pause/resume, but it must not control whether
|
||||||
|
the OS suspends or resumes its VM.
|
||||||
|
|
||||||
|
When Home is requested during Game execution, SystemOS must notify the Game and
|
||||||
|
grant a short bounded pause budget. After the budget, SystemOS may suspend the
|
||||||
|
VM even if the Game did not cooperate. While suspended, the Game must not
|
||||||
|
receive normal gameplay ticks, normal Game input, or frame pacing.
|
||||||
|
|
||||||
|
When returning to the same Game, SystemOS must reactivate the VM and send a
|
||||||
|
resume or foreground-restore notification before visual foreground is restored.
|
||||||
|
The Game may remain internally paused while it synchronizes. Hub/Shell remains
|
||||||
|
visible until the resumed Game publishes a valid render submission for the
|
||||||
|
current ownership epoch.
|
||||||
|
|
||||||
|
Input pending for the Game must be cleared or barriered across pause/resume
|
||||||
|
boundaries. Game audio pauses with the Game VM in v1. Independent background
|
||||||
|
audio, real background execution, multiple resident Games, multiple foreground
|
||||||
|
Shells, and direct Game-to-Game switching are outside this contract.
|
||||||
|
|
||||||
|
The resident Game VM session remains allocated while Hub or Shell is foreground.
|
||||||
|
It preserves Game VM state but is not execution-eligible except for the bounded
|
||||||
|
pause handoff and later foreground resume. A VM-backed Shell has a separate VM
|
||||||
|
session. A native Shell has no VM session.
|
||||||
|
|
||||||
|
When Hub/Home is foreground and a Game cartridge remains resident/suspended,
|
||||||
|
PrometeuHub MUST render a red control in the bottom-right of the Hub viewport.
|
||||||
|
The control MUST display only the resident Game title. It MUST NOT be rendered
|
||||||
|
for no resident Game, Shell tasks, System tasks, or native Shell tasks.
|
||||||
|
|
||||||
|
Clicking the Hub resident Game kill control is a system-owned immediate
|
||||||
|
termination request. Firmware MUST keep the user in Hub/Home, MUST NOT ask for
|
||||||
|
confirmation in v1, and MUST NOT resume the killed Game on subsequent Home
|
||||||
|
actions. The control MUST disappear on the next Hub frame after the resident
|
||||||
|
Game is no longer present.
|
||||||
|
|
||||||
|
## 8 Cartridge Load Flow
|
||||||
|
|
||||||
Current high-level flow:
|
Current high-level flow:
|
||||||
|
|
||||||
1. POS receives a cartridge to load;
|
1. POS receives a cartridge to load;
|
||||||
2. asset manager is initialized from the cartridge asset table, preload list, and packed asset bytes;
|
2. asset manager is initialized from the cartridge asset table, preload list, and packed asset bytes;
|
||||||
3. POS initializes the VM/runtime for the cartridge;
|
3. POS creates or selects the VM session for the cartridge;
|
||||||
4. launch behavior branches by `AppMode`:
|
4. POS initializes the session-owned VM/runtime for the cartridge;
|
||||||
|
5. launch behavior branches by `AppMode`:
|
||||||
- `Game` -> transition to the game-running firmware state;
|
- `Game` -> transition to the game-running firmware state;
|
||||||
- `System` -> create/focus a Hub window and return to the Hub state.
|
- `System` -> create/focus a Hub window and return to the Hub state.
|
||||||
|
|
||||||
If VM initialization fails, firmware transitions to the crash path.
|
If VM initialization fails, firmware transitions to the crash path.
|
||||||
|
|
||||||
|
For v1, POS must enforce at most one resident Game session. Selecting the same
|
||||||
|
resident Game from Home resumes that session. Selecting a different Game from
|
||||||
|
Home is a SystemOS-owned Game switch and MUST be destructive replacement:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Game A resident
|
||||||
|
-> Hub/Home selected Game B with different app_id
|
||||||
|
-> SystemOS terminates Game A resident task/session
|
||||||
|
-> SystemOS removes Game A from resumable state
|
||||||
|
-> firmware loads Game B through LoadCartridge
|
||||||
|
-> Game B receives a fresh VM session
|
||||||
|
```
|
||||||
|
|
||||||
|
SystemOS MUST NOT create a second resident Game session. SystemOS MUST NOT
|
||||||
|
reuse the old Game VM session, transient VM handles, pending lifecycle delivery
|
||||||
|
state, render ownership, debug pause state, or crash/debug runtime state for the
|
||||||
|
new Game. Durable app data remains governed by the relevant storage specs and
|
||||||
|
may still be keyed by `app_id`.
|
||||||
|
|
||||||
|
SystemOS MAY emit a cooperative non-blocking terminate/save lifecycle event
|
||||||
|
before closing the old Game when such an event exists. Replacement MUST NOT
|
||||||
|
block on that event in v1. VM-backed Shell loading creates a distinct Shell
|
||||||
|
session and must not overwrite resident Game VM state.
|
||||||
|
|
||||||
|
Manual Hub resident Game kill and destructive different-Game replacement MUST
|
||||||
|
share the canonical resident-Game termination path. That path MUST:
|
||||||
|
|
||||||
|
- close the resident Game task;
|
||||||
|
- mark its process stopped;
|
||||||
|
- remove its VM session;
|
||||||
|
- clear resident Game state and pending Game lifecycle delivery for that task;
|
||||||
|
- keep or return foreground ownership to Hub/Home;
|
||||||
|
- transition render ownership to Shell/Hub (`AppMode::Shell`, `app_id = 0`);
|
||||||
|
- clear the Game lifecycle audio pause state;
|
||||||
|
- unbind the Game2D frame composer scene;
|
||||||
|
- shut down cartridge-scoped asset manager state, including slot identity and
|
||||||
|
physical glyph/scene/sound banks.
|
||||||
|
|
||||||
|
After this operation, the killed Game MUST NOT be resumable. Launching that
|
||||||
|
same Game again from Home is a fresh cartridge load and a fresh VM session.
|
||||||
|
Manual Hub kill MUST emit an INFO Hub log with the message shape:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Resident game killed from Hub: <title>
|
||||||
|
```
|
||||||
|
|
||||||
POS selects the cartridge and its execution context, but the cartridge's initial callable is not chosen by firmware metadata. Execution starts from the cartridge boot protocol defined in [`13-cartridge.md`](13-cartridge.md), currently `func_id = 0`.
|
POS selects the cartridge and its execution context, but the cartridge's initial callable is not chosen by firmware metadata. Execution starts from the cartridge boot protocol defined in [`13-cartridge.md`](13-cartridge.md), currently `func_id = 0`.
|
||||||
|
|
||||||
When Home launches a discovered Game entry, the request is a system-owned action
|
When Home launches a discovered Game entry, the request is a system-owned action
|
||||||
@@ -179,7 +306,17 @@ If the selected cartridge cannot be loaded, firmware must leave or return the
|
|||||||
machine in the Hub/Home flow and record the failure through diagnostics or
|
machine in the Hub/Home flow and record the failure through diagnostics or
|
||||||
logging. A polished Home error surface is not required by v1.
|
logging. A polished Home error surface is not required by v1.
|
||||||
|
|
||||||
## 8 Firmware States
|
If a destructive Game switch has already begun and the new Game fails to load or
|
||||||
|
initialize, firmware MUST return to Hub/Home, MUST discard any partial new Game
|
||||||
|
task/session/window/render/input/audio state, and MUST NOT restore the previous
|
||||||
|
Game. Direct boot and debug boot failures remain governed by the boot profile
|
||||||
|
that requested them and may still transition to the crash path.
|
||||||
|
|
||||||
|
Switch validation MUST include two distinct Game cartridges. The current
|
||||||
|
repository evidence uses `Stress Console` and `Dummy Boy`; those cartridges are
|
||||||
|
test evidence, not required runtime features.
|
||||||
|
|
||||||
|
## 9 Firmware States
|
||||||
|
|
||||||
The current firmware state model includes:
|
The current firmware state model includes:
|
||||||
|
|
||||||
@@ -189,11 +326,12 @@ The current firmware state model includes:
|
|||||||
- `HubHome`
|
- `HubHome`
|
||||||
- `LoadCartridge`
|
- `LoadCartridge`
|
||||||
- `GameRunning`
|
- `GameRunning`
|
||||||
|
- `ShellRunning`
|
||||||
- `AppCrashes`
|
- `AppCrashes`
|
||||||
|
|
||||||
These states express machine orchestration above the VM. They are not guest-visible bytecode states.
|
These states express machine orchestration above the VM. They are not guest-visible bytecode states.
|
||||||
|
|
||||||
## 9 Execution Contract
|
## 10 Execution Contract
|
||||||
|
|
||||||
For game-mode execution, firmware/runtime coordination preserves:
|
For game-mode execution, firmware/runtime coordination preserves:
|
||||||
|
|
||||||
@@ -204,7 +342,7 @@ For game-mode execution, firmware/runtime coordination preserves:
|
|||||||
|
|
||||||
This keeps the machine model deterministic and observable.
|
This keeps the machine model deterministic and observable.
|
||||||
|
|
||||||
## 10 Crash Handling
|
## 11 Crash Handling
|
||||||
|
|
||||||
Firmware owns terminal fault presentation.
|
Firmware owns terminal fault presentation.
|
||||||
|
|
||||||
@@ -216,7 +354,35 @@ When a terminal app fault occurs:
|
|||||||
|
|
||||||
Crash handling is outside the guest VM execution model.
|
Crash handling is outside the guest VM execution model.
|
||||||
|
|
||||||
## 11 Relationship to Other Specs
|
## 12 Desktop Smoke Validation
|
||||||
|
|
||||||
|
The foreground contract can be smoke-tested on the desktop host with:
|
||||||
|
|
||||||
|
```text
|
||||||
|
cargo run --release -p prometeu-host-desktop-winit -- --run test-cartridges/stress-console
|
||||||
|
cargo run --release -p prometeu-host-desktop-winit -- --games-root test-cartridges
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected behavior:
|
||||||
|
|
||||||
|
- direct `--run` still boots the selected Game without using a guest cartridge
|
||||||
|
switching API;
|
||||||
|
- `--games-root` starts in Home and launches Games through the Home library;
|
||||||
|
- while a Game is running, `Esc` opens Home/SystemOS without entering the guest
|
||||||
|
pad input surface;
|
||||||
|
- the Game is paused, then suspended after the bounded SystemOS budget;
|
||||||
|
- Home remains foreground while the Game is resident;
|
||||||
|
- launching and closing a Shell app returns to Home without losing the resident
|
||||||
|
Game;
|
||||||
|
- a VM-backed Shell advances its own VM session and does not tick the suspended
|
||||||
|
resident Game session;
|
||||||
|
- returning to the same Game resumes it through the foreground lifecycle and
|
||||||
|
waits for current-epoch Game rendering before visual Game presentation.
|
||||||
|
- clicking the red bottom-right resident Game kill control terminates the
|
||||||
|
resident Game, keeps Home foreground, clears runtime/cartridge residue, and
|
||||||
|
removes the resume path.
|
||||||
|
|
||||||
|
## 13 Relationship to Other Specs
|
||||||
|
|
||||||
- [`02-vm-instruction-set.md`](02-vm-instruction-set.md) defines the VM subsystem run by firmware.
|
- [`02-vm-instruction-set.md`](02-vm-instruction-set.md) defines the VM subsystem run by firmware.
|
||||||
- [`09-events-and-concurrency.md`](09-events-and-concurrency.md) defines the frame-boundary model used by firmware.
|
- [`09-events-and-concurrency.md`](09-events-and-concurrency.md) defines the frame-boundary model used by firmware.
|
||||||
|
|||||||
@@ -186,6 +186,9 @@ For the v1 Home games library:
|
|||||||
- the manifest must declare `app_mode: "Game"`;
|
- the manifest must declare `app_mode: "Game"`;
|
||||||
- the library retains the loaded manifest data, `title`, `app_id`,
|
- the library retains the loaded manifest data, `title`, `app_id`,
|
||||||
`app_version`, the internal cartridge path, and discovery metadata;
|
`app_version`, the internal cartridge path, and discovery metadata;
|
||||||
|
- the library entry identity is the input to the SystemOS Game switch target;
|
||||||
|
- `app_id` is the v1 identity used to distinguish same-Game resume from
|
||||||
|
different-Game destructive replacement;
|
||||||
- invalid candidates are logged or reported as diagnostics and omitted from the
|
- invalid candidates are logged or reported as diagnostics and omitted from the
|
||||||
Home list;
|
Home list;
|
||||||
- valid non-Game cartridges are omitted from the Game library.
|
- valid non-Game cartridges are omitted from the Game library.
|
||||||
@@ -193,6 +196,11 @@ For the v1 Home games library:
|
|||||||
Discovery reads metadata for cataloging. It does not replace the normal
|
Discovery reads metadata for cataloging. It does not replace the normal
|
||||||
cartridge loader used when firmware starts the selected cartridge.
|
cartridge loader used when firmware starts the selected cartridge.
|
||||||
|
|
||||||
|
Selecting a discovered Game from Home is not cartridge self-execution and is not
|
||||||
|
guest-controlled. The cartridge path is consumed by firmware/SystemOS, which
|
||||||
|
owns same-Game resume, different-Game replacement, failure recovery, and VM
|
||||||
|
session creation policy.
|
||||||
|
|
||||||
### Packaged `.pmc` form
|
### Packaged `.pmc` form
|
||||||
|
|
||||||
This form is recognized conceptually by the loader boundary, but its actual load path is not implemented yet.
|
This form is recognized conceptually by the loader boundary, but its actual load path is not implemented yet.
|
||||||
|
|||||||
@@ -50,6 +50,8 @@ For a cartridge boot target:
|
|||||||
- `Game` cartridges transition into the game-running pipeline;
|
- `Game` cartridges transition into the game-running pipeline;
|
||||||
- `System` cartridges transition into a Runtime/Hub pipeline dedicated to
|
- `System` cartridges transition into a Runtime/Hub pipeline dedicated to
|
||||||
system UI and app hosting.
|
system UI and app hosting.
|
||||||
|
- VM-backed cartridges are initialized in a POS-owned VM session associated with
|
||||||
|
the created task/process.
|
||||||
|
|
||||||
This preserves the distinction between machine firmware state and app execution mode.
|
This preserves the distinction between machine firmware state and app execution mode.
|
||||||
|
|
||||||
@@ -95,9 +97,23 @@ The v1 games root contract is:
|
|||||||
and transitions through `LoadCartridge`;
|
and transitions through `LoadCartridge`;
|
||||||
- launch failure leaves or returns the machine to Home and records an error.
|
- launch failure leaves or returns the machine to Home and records an error.
|
||||||
|
|
||||||
Game-to-game switching after a game is already active is not part of this boot
|
Game-to-game switching after a game is already active is not a boot profile.
|
||||||
profile. That orchestration belongs to the foreground/home and cartridge switch
|
That orchestration belongs to the foreground/home and cartridge switch
|
||||||
contracts.
|
contracts. In that path, SystemOS owns the switch policy: selecting the same
|
||||||
|
resident Game resumes it, while selecting a different Game performs destructive
|
||||||
|
replacement and creates a fresh VM session for the new Game.
|
||||||
|
|
||||||
|
The foreground/home contract defines `Game -> Home/Shell -> same Game` after a
|
||||||
|
Game is already running. It does not change direct `--run`, debugger direct
|
||||||
|
boot, or `--games-root` Home library startup semantics. Home/SystemOS requests
|
||||||
|
are host/system controls, not guest cartridge boot APIs.
|
||||||
|
|
||||||
|
Direct boot creates the initial VM session for the selected cartridge. It does
|
||||||
|
not create a reusable global VM shared by later Game or Shell cartridges.
|
||||||
|
Direct boot and debug boot MUST NOT be treated as failed-switch recovery paths:
|
||||||
|
load or initialization failures for direct boot may transition to the crash
|
||||||
|
flow, while Home-driven switch failures return to Home and do not restore the
|
||||||
|
previous Game.
|
||||||
|
|
||||||
## 5 Firmware State Relationship
|
## 5 Firmware State Relationship
|
||||||
|
|
||||||
@@ -142,6 +158,10 @@ Direct single-cartridge boot remains a separate validation path:
|
|||||||
cargo run --release -p prometeu-host-desktop-winit -- --run test-cartridges/stress-console
|
cargo run --release -p prometeu-host-desktop-winit -- --run test-cartridges/stress-console
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Game switch validation should cover the Home-driven two-cartridge path, for
|
||||||
|
example `Stress Console -> Home -> Dummy Boy`, and assert that the first Game is
|
||||||
|
not resumable after replacement.
|
||||||
|
|
||||||
## 8 Relationship to Other Specs
|
## 8 Relationship to Other Specs
|
||||||
|
|
||||||
- [`12-firmware-pos-and-prometeuhub.md`](12-firmware-pos-and-prometeuhub.md) defines the firmware state machine that consumes boot targets.
|
- [`12-firmware-pos-and-prometeuhub.md`](12-firmware-pos-and-prometeuhub.md) defines the firmware state machine that consumes boot targets.
|
||||||
|
|||||||
@@ -115,7 +115,7 @@ For `BankType::GLYPH`, the v1 runtime-facing contract is:
|
|||||||
- `codec = NONE`
|
- `codec = NONE`
|
||||||
- serialized pixels use packed `u4` palette indices
|
- serialized pixels use packed `u4` palette indices
|
||||||
- serialized palettes use `RGBA8888` with canonical RGBA channel order
|
- serialized palettes use `RGBA8888` with canonical RGBA channel order
|
||||||
- `palette_count = 64`
|
- `palette_count` is the number of serialized and resident palettes and must be in `1..=64`
|
||||||
- runtime materialization may expand pixel indices to one `u8` per pixel
|
- runtime materialization may expand pixel indices to one `u8` per pixel
|
||||||
|
|
||||||
For `GLYPH`, `NONE` means there is no additional generic codec layer beyond the bank contract itself.
|
For `GLYPH`, `NONE` means there is no additional generic codec layer beyond the bank contract itself.
|
||||||
@@ -136,7 +136,7 @@ Required effective metadata fields for `GLYPH` at the root level:
|
|||||||
- `tile_size`: tile edge in pixels; valid values are `8`, `16`, or `32`
|
- `tile_size`: tile edge in pixels; valid values are `8`, `16`, or `32`
|
||||||
- `width`: total sheet width in pixels
|
- `width`: total sheet width in pixels
|
||||||
- `height`: total sheet height in pixels
|
- `height`: total sheet height in pixels
|
||||||
- `palette_count`: number of serialized palettes for the bank
|
- `palette_count`: number of serialized palettes and resident runtime palettes for the bank
|
||||||
|
|
||||||
Optional informative subtrees:
|
Optional informative subtrees:
|
||||||
|
|
||||||
@@ -145,7 +145,7 @@ Optional informative subtrees:
|
|||||||
|
|
||||||
Validation rules for `GLYPH` v1:
|
Validation rules for `GLYPH` v1:
|
||||||
|
|
||||||
- `palette_count` must be `64`
|
- `palette_count` must be in the inclusive range `1..=64`
|
||||||
- `width * height` defines the number of logical indexed pixels in the decoded sheet
|
- `width * height` defines the number of logical indexed pixels in the decoded sheet
|
||||||
- extra metadata may exist, but the runtime contract must not depend on it to reconstruct the in-memory bank unless that data is defined at the root as an effective field.
|
- extra metadata may exist, but the runtime contract must not depend on it to reconstruct the in-memory bank unless that data is defined at the root as an effective field.
|
||||||
|
|
||||||
@@ -158,7 +158,16 @@ The tile-bank payload therefore separates serialized storage form from runtime m
|
|||||||
|
|
||||||
- serialized pixel plane: packed `4bpp`
|
- serialized pixel plane: packed `4bpp`
|
||||||
- decoded pixel plane: expanded `u8` indices, one entry per pixel
|
- decoded pixel plane: expanded `u8` indices, one entry per pixel
|
||||||
- palette table: `64 * 16` colors in RGBA8888 channel order
|
- palette table: `palette_count * 16` colors in RGBA8888 channel order
|
||||||
|
|
||||||
|
For `GLYPH` v1:
|
||||||
|
|
||||||
|
```text
|
||||||
|
serialized_pixel_bytes = ceil(width * height / 2)
|
||||||
|
palette_bytes = palette_count * 16 * 4
|
||||||
|
size = serialized_pixel_bytes + palette_bytes
|
||||||
|
decoded_size = (width * height) + palette_bytes
|
||||||
|
```
|
||||||
|
|
||||||
For `GLYPH` v1:
|
For `GLYPH` v1:
|
||||||
|
|
||||||
@@ -172,6 +181,11 @@ before they are loaded by the runtime.
|
|||||||
Palette indices are ordinary indices. Transparency is represented by the alpha
|
Palette indices are ordinary indices. Transparency is represented by the alpha
|
||||||
channel of the resolved RGBA8888 palette entry, not by reserving index `0`.
|
channel of the resolved RGBA8888 palette entry, not by reserving index `0`.
|
||||||
|
|
||||||
|
`palette_id` is valid only when it is lower than the referenced resident glyph
|
||||||
|
bank's `palette_count`. Canonical runtime composition MUST NOT substitute
|
||||||
|
transparent, black, or any other default color for `palette_id >=
|
||||||
|
palette_count`.
|
||||||
|
|
||||||
### 4.2 `SCENE` asset contract in v1
|
### 4.2 `SCENE` asset contract in v1
|
||||||
|
|
||||||
For `BankType::SCENE`, the v1 runtime-facing contract is:
|
For `BankType::SCENE`, the v1 runtime-facing contract is:
|
||||||
|
|||||||
@@ -65,6 +65,12 @@ dedicated `System` profile ABI and stdlib/framework.
|
|||||||
|
|
||||||
## 3 Syscall Resolution
|
## 3 Syscall Resolution
|
||||||
|
|
||||||
|
PBX, Prometeu Bytecode Executable, is the runtime executable bytecode format.
|
||||||
|
Its canonical file magic is `PBX\0`. The former PBS-prefixed magic is not valid
|
||||||
|
for PBX artifacts: PBS names a frontend language, while PBX names the executable
|
||||||
|
artifact accepted by the runtime. This distinction is required because Prometeu
|
||||||
|
bytecode can be produced by multiple frontends.
|
||||||
|
|
||||||
The host maintains a registry:
|
The host maintains a registry:
|
||||||
|
|
||||||
```
|
```
|
||||||
@@ -187,6 +193,11 @@ The game memcard profile uses module `mem` with status-first return shapes.
|
|||||||
The `mem` module is a game profile surface. It is not the public storage model
|
The `mem` module is a game profile surface. It is not the public storage model
|
||||||
for `System` profile apps.
|
for `System` profile apps.
|
||||||
|
|
||||||
|
Durable memcard data is keyed by `app_id` according to the save-memory
|
||||||
|
contract. Runtime handles, open file tables, pending lifecycle delivery, and
|
||||||
|
other mutable VM-facing syscall context are scoped to the owning VM session and
|
||||||
|
MUST NOT be used as durable app identity.
|
||||||
|
|
||||||
Canonical operations in v1 are:
|
Canonical operations in v1 are:
|
||||||
|
|
||||||
- `mem.slot_count() -> (status, count)`
|
- `mem.slot_count() -> (status, count)`
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Dummy Boy
|
||||||
|
|
||||||
|
Regenerate this cartridge with:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo run -p pbxgen-dummy-boy
|
||||||
|
```
|
||||||
|
|
||||||
|
Dummy Boy is a minimal visual Game cartridge used by runtime switch tests. It
|
||||||
|
clears the frame and draws a centered square whose fill color cycles
|
||||||
|
deterministically across frames.
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"magic": "PMTU",
|
||||||
|
"cartridge_version": 1,
|
||||||
|
"app_id": 2,
|
||||||
|
"title": "Dummy Boy",
|
||||||
|
"app_version": "0.1.0",
|
||||||
|
"app_mode": "Game",
|
||||||
|
"capabilities": ["gfx2d"]
|
||||||
|
}
|
||||||
Binary file not shown.
Binary file not shown.
Reference in New Issue
Block a user