feat(stress): add a deterministic particle demo with sequenced music

Move Storm Eagle playback and source assets to Stress Console and keep Dummy Boy silent. Exercise VM math, seeded Random and persistent typed particles with a projected tunnel, bounded 512-sprite heavy workload, reproducible replays and measured costs.
This commit is contained in:
2026-11-20 22:15:47 +00:00
parent 8510c5b00d
commit c2bf8d055c
42 changed files with 20688 additions and 232 deletions
Generated
+4
View File
@@ -1883,6 +1883,7 @@ dependencies = [
"anyhow",
"prometeu-bytecode",
"prometeu-hal",
"prometeu-host-headless",
"serde_json",
]
@@ -1892,7 +1893,10 @@ version = "0.1.0"
dependencies = [
"anyhow",
"prometeu-bytecode",
"prometeu-drivers",
"prometeu-hal",
"prometeu-host-headless",
"prometeu-vm",
"serde_json",
]
@@ -1024,6 +1024,10 @@ mod tests {
platform.assets().slot_info(SlotRef { asset_type: BankType::SCENE, index: 0 }).asset_id,
Some(1)
);
assert_eq!(
platform.assets().slot_info(SlotRef { asset_type: BankType::MUSIC, index: 0 }).asset_id,
Some(201)
);
firmware.request_home_from_host();
firmware.tick(&InputSignals::default(), &mut platform);
@@ -1038,6 +1042,10 @@ mod tests {
platform.assets().slot_info(SlotRef { asset_type: BankType::SCENE, index: 0 }).asset_id,
Some(1)
);
assert_eq!(
platform.assets().slot_info(SlotRef { asset_type: BankType::MUSIC, index: 0 }).asset_id,
Some(201)
);
firmware.tick(&InputSignals::default(), &mut platform);
let dummy_click =
@@ -1051,6 +1059,10 @@ mod tests {
platform.assets().slot_info(SlotRef { asset_type: BankType::SCENE, index: 0 }).asset_id,
None
);
assert_eq!(
platform.assets().slot_info(SlotRef { asset_type: BankType::MUSIC, index: 0 }).asset_id,
None
);
assert!(platform.local_hardware().memory_banks.glyph_bank_slot(0).is_none());
assert!(platform.local_hardware().memory_banks.scene_bank_slot(0).is_none());
@@ -1078,6 +1090,7 @@ mod tests {
);
firmware.tick(&InputSignals::default(), &mut platform);
wait_for_cartridge_preload(&mut firmware, &mut platform);
match &firmware.state {
FirmwareState::GameRunning(step) => assert_eq!(step.task_id, dummy_task),
@@ -1128,6 +1141,10 @@ mod tests {
platform.assets().slot_info(SlotRef { asset_type: BankType::SCENE, index: 0 }).asset_id,
Some(1)
);
assert_eq!(
platform.assets().slot_info(SlotRef { asset_type: BankType::MUSIC, index: 0 }).asset_id,
Some(201)
);
assert!(platform.local_hardware().memory_banks.glyph_bank_slot(0).is_some());
assert!(platform.local_hardware().memory_banks.scene_bank_slot(0).is_some());
@@ -687,6 +687,50 @@ impl ApplicationHandler for HostRunner {
mod tests {
use super::*;
#[test]
fn studio_stress_demoscene_publishes_graphics_and_native_music() {
let cart = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../../test-cartridges/stress-console");
let mut host = HostRunner::new(None, None);
host.set_boot_target(BootTarget::Cartridge {
path: cart.to_string_lossy().into_owned(),
debug: false,
debug_port: 0,
});
let deadline = Instant::now() + Duration::from_secs(5);
while !host.studio_boot_step(true).unwrap() {
assert!(Instant::now() < deadline);
std::thread::sleep(Duration::from_millis(1));
}
let (mut callback, mut reclaimer) = crate::audio::AudioCallback::new();
let transport = host.hardware.audio.transport();
let mut pcm = [0.0; 1600];
let mut audible = false;
while host.studio_frame(None).is_none() || !audible {
assert!(Instant::now() < deadline, "demo did not publish graphics/music");
host.studio_step(Default::default()).unwrap();
callback.render(&transport, &mut pcm);
audible |= pcm.iter().any(|x| x.abs() > 0.001);
reclaimer.service(&transport);
std::thread::sleep(Duration::from_millis(2));
}
assert!(callback.diagnostics().maximum_voices > 0);
assert_eq!(host.studio_frame(None).unwrap().ownership.app_id, 1);
let before_pause = callback.diagnostics().frames;
host.studio_pause(true);
callback.render(&transport, &mut pcm);
assert!(pcm.iter().all(|x| *x == 0.0));
assert_eq!(callback.diagnostics().frames, before_pause);
reclaimer.service(&transport);
host.studio_pause(false);
callback.render(&transport, &mut pcm);
assert!(callback.diagnostics().frames > before_pause);
reclaimer.service(&transport);
host.studio_stop(true).unwrap();
callback.render(&transport, &mut pcm);
assert!(pcm.iter().all(|x| *x == 0.0));
}
#[test]
fn studio_can_boot_and_publish_without_a_window() {
let cart = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
@@ -68,6 +68,7 @@ fn regenerated_cartridges_run_six_complete_frames_on_production_host() {
struct Effects {
scene_binds: usize,
frame_commands: usize,
music_plays: usize,
}
impl NativeInterface for Effects {
fn syscall(
@@ -81,6 +82,9 @@ fn regenerated_cartridges_run_six_complete_frames_on_production_host() {
if syscall == Syscall::ComposerBindScene {
self.scene_binds += 1;
}
if syscall == Syscall::MusicPlay {
self.music_plays += 1;
}
if matches!(syscall, Syscall::GfxClear | Syscall::ComposerSetCamera) {
self.frame_commands += 1;
}
@@ -125,7 +129,7 @@ fn regenerated_cartridges_run_six_complete_frames_on_production_host() {
)
.unwrap();
let mut vm = prometeu_vm::VirtualMachine::from_image(image, Default::default());
let mut effects = Effects { scene_binds: 0, frame_commands: 0 };
let mut effects = Effects { scene_binds: 0, frame_commands: 0, music_plays: 0 };
for _ in 0..6 {
vm.prepare_boot_call().unwrap();
assert_eq!(
@@ -135,6 +139,7 @@ fn regenerated_cartridges_run_six_complete_frames_on_production_host() {
}
assert_eq!(effects.frame_commands, 6);
assert_eq!(effects.scene_binds, usize::from(name == "stress-console"));
assert_eq!(effects.music_plays, usize::from(name == "stress-console"));
}
}
+1
View File
@@ -10,3 +10,4 @@ prometeu-hal = { path = "../../console/prometeu-hal" }
[dev-dependencies]
serde_json = "1"
prometeu-host-headless = { path = "../../host/prometeu-host-headless" }
+5
View File
@@ -21,6 +21,11 @@ pub fn generate() -> Result<()> {
fs::create_dir_all(&out_dir)?;
fs::write(out_dir.join("program.pbx"), build_program())?;
fs::write(out_dir.join("manifest.json"), manifest_json())?;
match fs::remove_file(out_dir.join("assets.pa")) {
Ok(()) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(error.into()),
}
Ok(())
}
@@ -0,0 +1,35 @@
use prometeu_host_headless::{AdvanceFrameOutcome, HeadlessHost};
use std::path::PathBuf;
#[test]
fn dummy_boy_is_visual_only_and_silent() {
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../test-cartridges/dummy-boy");
assert!(!root.join("assets.pa").exists());
assert_eq!(std::fs::read(root.join("program.pbx")).unwrap(), pbxgen_dummy_boy::build_program());
assert_eq!(
std::fs::read(root.join("manifest.json")).unwrap(),
pbxgen_dummy_boy::manifest_json()
);
let manifest: serde_json::Value =
serde_json::from_slice(&pbxgen_dummy_boy::manifest_json()).unwrap();
assert_eq!(manifest["capabilities"], serde_json::json!(["gfx2d"]));
let mut host = HeadlessHost::new();
host.boot(root.to_string_lossy()).unwrap();
let expected = [10098790910174709541_u64, 9216878996269485861, 8328467396362782501];
for index in 0..6 {
assert!(matches!(
host.advance_frame().unwrap(),
AdvanceFrameOutcome::FrameCompleted { .. }
));
let frame = host.capture_frame().unwrap();
let hash = frame.frame.pixels.iter().fold(0xcbf29ce484222325_u64, |hash, byte| {
(hash ^ u64::from(*byte)).wrapping_mul(0x100000001b3)
});
assert_eq!(hash, expected[index % 3]);
host.resume().unwrap();
let mut pcm = [1.0; 1600];
host.render_audio(&mut pcm);
assert_eq!(pcm, [0.0; 1600]);
}
assert_eq!(host.audio_diagnostics().maximum_voices, 0);
}
+6
View File
@@ -6,5 +6,11 @@ edition = "2021"
[dependencies]
prometeu-bytecode = { path = "../../console/prometeu-bytecode" }
prometeu-hal = { path = "../../console/prometeu-hal" }
prometeu-vm = { path = "../../console/prometeu-vm" }
anyhow = "1"
serde_json = "1"
[dev-dependencies]
prometeu-drivers = { path = "../../console/prometeu-drivers" }
prometeu-host-headless = { path = "../../host/prometeu-host-headless" }
prometeu-vm = { path = "../../console/prometeu-vm", features = ["resource-diagnostics"] }
@@ -0,0 +1,81 @@
# Stress Console local measurement
Executed on 2026-11-20: Apple M2 Pro, macOS/Darwin 27.2.0, aarch64,
`rustc 1.98.1 (48a229cea 2026-09-01)`, Cargo release profile, VM
`resource-diagnostics` enabled. The host was not isolated and its power/thermal
state was not controlled. These are elapsed-time observations from one run.
Reproduce from the runtime root:
```sh
cargo run -p pbxgen-stress --release --example demo_measure -- 120 /tmp/stress-measure
```
Seed: `1347571533`. Particle position-travel multiplier: `1.5`. Each preset loads
independently, executes its first frame,
then measures 120 steady logical frames. All measured frames compose the native
640x360 image and process 800 stereo audio frames (48 kHz). Initialization is
excluded from steady distributions. Percentiles are nearest-rank over the 120
samples; they do not estimate a guaranteed upper bound.
| Preset | VM only mean ms | Headless mean ms | p95 ms | Max ms | Mean virtual cycles | Host ticks/logical frame |
| --- | ---: | ---: | ---: | ---: | ---: | ---: |
| light | 1.982 | 2.683 | 2.853 | 2.996 | 84701.2 | 1 |
| normal | 4.154 | 4.907 | 5.056 | 5.184 | 178972.8 | 1 |
| heavy | 19.183 | 19.685 | 20.553 | 21.700 | 774621.4 | 4 |
VM-only uses the same PBX on the real VM and SpriteController; other native
calls are counted. Headless uses actual firmware, assets, composition and audio.
Virtual cycles are machine accounting, not CPU cycles or milliseconds. The
heavy preset spans four 250,000-cycle host slices per logical frame; light and
normal use one. `advance_frame` completes all required slices, so these timings
are not physical presentation cadence or a promise of 60 FPS in another host.
| Preset | Host boot ms | First frame ms | GuestBytes used | Live handles/objects | AuxiliaryBytes used | TemporaryBytes peak | Sprites accepted |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| light | 1.730 | 3.037 | 22640 | 66 | 8680 | 3840 | 192 |
| normal | 3.421 | 5.213 | 44656 | 130 | 16360 | 7680 | 256 |
| heavy | 3.278 | 20.683 | 132720 | 386 | 31720 | 15360 | 512 |
Each preset recorded zero sprite overflows and zero guest composer errors.
Music play was submitted once. The two-second observation reached eight active
voices; the separate 52.4-second audio regression reached ten, with no clipped
samples. Processing 800 audio frames averaged 0.123–0.128 ms in this run.
The guest retains exactly N Particle structs plus one array and one RNG object.
Rebirth reuses those objects. Quota accounting excludes process RSS, framebuffers,
resident banks, renderer caches and allocator overhead. The musical bank has
60,358 PCM bytes and canonical decoded size 112,224 bytes; those are independent
of the workload preset. Boot/first-frame times include their respective host
work and are not isolated codec-decoding measurements.
The current default is heavy: 384 particles, four real simulation passes and
128 tunnel markers. It deliberately selects the largest existing numerical
workload. Normal (128 particles/two passes) and light remain explicit options
for comparison. The current run includes the 1.5 position-travel multiplier and
the larger heavy population. Relative to the previous 256-particle heavy workload, sprite
admission rises from 384 to 512, mean virtual cycles from about 531,444 to
774,621 and host slices from three to four. Its observed mean headless cost
increased from 13.649 to 19.685 ms. These observations do not provide a handheld
frame-rate guarantee.
The example saves report.json, generated cartridges and PPM captures. Diagnostic
state hashes after the initial frame plus 120 measured frames were:
| Preset | Particle-state hash | Native frame hash |
| --- | --- | --- |
| light | `b53cd663d1741a24` | `87f646410e9c3ade` |
| normal | `16b062d046d8efc9` | `c33ceb1e514ff1a8` |
| heavy | `f934f3e61ae1be77` | `6c3302f4a16903bc` |
The tests additionally pin six-frame numeric and visual baselines and execute
them in debug and release. A separate probe checks actual guest displacement
against the updated velocity, establishing the 1.5 multiplier independently of
the replay hashes. The native desktop integration test exercises actual
cartridge music through AudioCallback without a physical output device.
No physical callback deadlines, underruns, GPU presentation, VSync, battery
consumption, thermal throttling or affordable handheld hardware were measured.
The headless harness drives audio explicitly; it cannot observe a device underrun.
Use dedicated subsystem tests for numeric edge cases, GC churn, storage/input,
crossfade, SFX and full 32-voice load.
@@ -0,0 +1,101 @@
//! Reproducible fixture measurement; times include diagnostics and do not qualify a handheld.
#[path = "../tests/support/mod.rs"]
mod support;
use pbxgen_stress::{Preset, DEFAULT_SEED};
use prometeu_host_headless::{AdvanceFrameOutcome, HeadlessHost};
use std::{
io::Write,
path::{Path, PathBuf},
time::Instant,
};
fn distribution(mut ms: Vec<f64>) -> serde_json::Value {
ms.sort_by(f64::total_cmp);
let n = ms.len();
serde_json::json!({"count":n,"mean_ms":ms.iter().sum::<f64>()/n as f64,"p50_ms":ms[(n*50).div_ceil(100)-1],"p95_ms":ms[(n*95).div_ceil(100)-1],"max_ms":ms[n-1]})
}
fn ppm(path: &Path, pixels: &[u32]) {
let mut f = std::io::BufWriter::new(std::fs::File::create(path).unwrap());
write!(f, "P6\n640 360\n255\n").unwrap();
for &p in pixels {
let (r, g, b, _) = prometeu_hal::color::Color::unpack_to_native(p);
f.write_all(&[r, g, b]).unwrap();
}
}
fn main() {
let frames: usize = std::env::args().nth(1).unwrap_or("120".into()).parse().expect("frames");
assert!((1..=10000).contains(&frames));
let output =
PathBuf::from(std::env::args().nth(2).unwrap_or("/tmp/prometeu-demo-measure".into()));
std::fs::create_dir_all(&output).unwrap();
let mut reports = vec![];
for preset in [Preset::Light, Preset::Normal, Preset::Heavy] {
let started = Instant::now();
let mut vm = support::vm(preset, DEFAULT_SEED);
let vm_load_ms = started.elapsed().as_secs_f64() * 1000.0;
let mut native = support::Workload::default();
let started = Instant::now();
let init_cycles = support::frame(&mut vm, &mut native);
let init_vm_ms = started.elapsed().as_secs_f64() * 1000.0;
let mut vm_times = Vec::new();
let mut cycles = 0;
for _ in 0..frames {
let started = Instant::now();
cycles += support::frame(&mut vm, &mut native);
vm_times.push(started.elapsed().as_secs_f64() * 1000.0);
}
let resources = vm.resource_snapshot();
let state_hash = support::hash(&support::particle_bits(&vm));
let cart = output.join(format!("{}-cartridge", preset.name()));
pbxgen_stress::generate_with(preset, DEFAULT_SEED, Some(cart.clone())).unwrap();
let mut host = HeadlessHost::new();
let started = Instant::now();
host.boot(cart.to_string_lossy()).unwrap();
let boot_ms = started.elapsed().as_secs_f64() * 1000.0;
let started = Instant::now();
assert!(matches!(
host.advance_frame().unwrap(),
AdvanceFrameOutcome::FrameCompleted { .. }
));
let host_first_frame_ms = started.elapsed().as_secs_f64() * 1000.0;
host.resume().unwrap();
let mut pcm = [0.0; 1600];
host.render_audio(&mut pcm);
let mut host_times = vec![];
let mut audio_times = vec![];
let mut previous_tick = host.get_state().tick_index;
let mut slices = vec![];
for _ in 0..frames {
let started = Instant::now();
assert!(matches!(
host.advance_frame().unwrap(),
AdvanceFrameOutcome::FrameCompleted { .. }
));
host.resume().unwrap();
let audio_started = Instant::now();
host.render_audio(&mut pcm);
audio_times.push(audio_started.elapsed().as_secs_f64() * 1000.0);
host_times.push(started.elapsed().as_secs_f64() * 1000.0);
let tick = host.get_state().tick_index;
slices.push(tick - previous_tick);
previous_tick = tick;
}
let capture = host.capture_frame().unwrap();
let file = output.join(format!("{}.ppm", preset.name()));
ppm(&file, &capture.frame.pixels);
let audio = host.audio_diagnostics();
reports.push(serde_json::json!({"preset":preset.name(),"particles":preset.particles(),"substeps":preset.substeps(),"steady_frames":frames,"seed":DEFAULT_SEED,
"vm_load_ms":vm_load_ms,"vm_first_frame_ms":init_vm_ms,"host_boot_ms":boot_ms,"host_first_frame_ms":host_first_frame_ms,
"vm_only_with_bounded_native":distribution(vm_times),"headless_graphics_and_800_audio_frames":distribution(host_times),"audio_800_frames_only":distribution(audio_times),
"mean_host_ticks_per_logical_frame":slices.iter().sum::<u64>() as f64 / frames as f64,"max_host_ticks_per_logical_frame":slices.iter().max(),
"first_virtual_cycles":init_cycles,"mean_steady_virtual_cycles":cycles as f64/frames as f64,
"sprites_submitted_per_frame":preset.particles()+128,"sprites_accepted_last_frame":native.sprites.sprite_count(),"sprite_overflow":native.sprites.dropped_sprites(),"guest_composer_errors":native.errors,
"live_guest_objects":resources.live_objects,"vm_budget_used":resources.budget.used,"vm_budget_peaks":resources.budget.peaks,"vm_budget_limits":resources.budget.limits,
"state_hash":format!("{state_hash:016x}"),"music_play_commands":native.plays,"observed_maximum_voices":audio.maximum_voices,"audio_frames":audio.frames,
"capture":file,"frame_hash":format!("{:016x}",support::hash(&capture.frame.pixels.iter().map(|&p|u64::from(p)).collect::<Vec<_>>()))}));
}
let report = serde_json::json!({"profile":if cfg!(debug_assertions){"debug"}else{"release"},"arch":std::env::consts::ARCH,"os":std::env::consts::OS,"resource_diagnostics":true,"particle_travel_scale":pbxgen_stress::PARTICLE_TRAVEL_SCALE,
"notes":["Native-only timing uses real VM and SpriteController, with other host calls counted.","Headless timing includes real software composition and 800 stereo audio frames per logical frame.","No physical callback, VSync, GPU presentation, power or handheld measurement.","VM quota arrays are ordered by RuntimeResource; they are not process RSS."],"presets":reports});
std::fs::write(output.join("report.json"), serde_json::to_vec_pretty(&report).unwrap())
.unwrap();
println!("{}", serde_json::to_string_pretty(&report).unwrap());
}
@@ -0,0 +1,56 @@
# Stress Console music fixture
This fixture uses the Storm Eagle transcription supplied by the owner, sourced
from [Hooktheory](https://www.hooktheory.com/theorytab/view/setsuo-yamamoto/mega-man-x---storm-eagle).
`transcription.json` retains the musical fields: 90 melody notes, 20 chords,
relative degrees/accidentals, inversions and exact 480-PPQ source ticks. The
arranger multiplies ticks by two for native PPQ960, preserving the triplets and
the 72-beat loop. The nearest integer tempo to 168 BPM is 357143 us/quarter.
The eight source WAVs are an unchanged PCM subset extracted from the supplied
`MegaManX-SF-3.0.sf2`, whose INFO author is CliffyJiffy. Original bank fingerprint,
root keys, rates, pitch corrections and raw instrument generators are retained
in `soundfont-source.json`. The complete extracted banks remain at the sibling
port's `games/ports/snes/megaman-x/audio/`; playback and regeneration of this
selected fixture do not depend on that directory.
`tools/arrange_music.py` creates the offline authoring manifest `song.json` and
`instrument-mapping.json`. The latter records source-to-target pitch, loop,
gain, ADSR, pan and modulation decisions, including omitted SF2 hold/modulation
envelopes. Melodic negative SF2 sustain attenuation is clamped conceptually to
full sustain; target gain/articulation are explicit musical mix choices.
Drum Kit root overrides are applied. Source sample rates are preserved; root
and pitch correction are applied by native instruments. No full SF2 conversion,
chorus or SNES DSP emulation is claimed.
To rebuild the MusicBank from the existing WAVs/JSON, from the runtime root:
```sh
python3 crates/tools/pbxgen-stress/tools/regenerate_music.py
cargo run -p pbxgen-stress
```
This requires Python 3, Java 21+ and the sibling Studio checkout. A temporary
Gradle init task resolves the existing packer's runtime classpath. `PackMusic.java`
calls `AudioBankPacker.pack` twice, checks identical output, and writes the bank
and its size metrics. It contains no codec or MusicBank serializer. Studio source
and build scripts are not changed. Use `--studio PATH` for another checkout.
`storm-eagle.mbnk` and the usual `assets.pa` envelope are generated assets.
`bank-metrics.json` distinguishes cartridge payload, PCM bytes and canonical
decoded size; those values do not include all allocator/host overhead.
Run conformance and the optional WAV export with:
```sh
cargo test -p pbxgen-stress
PROMETEU_STRESS_WAV=/tmp/stress-console-storm-eagle.wav \
cargo test -p pbxgen-stress --release --test music_cartridge \
full_sequence_loops_and_frame_controls_preserve_audio -- --nocapture
```
The WAV is rendered by the real cartridge/headless/native mixer path at stereo
48 kHz and contains more than two loops. The test also compares playback with
and without bounded, representative graphics frames across both loops, checks
pause/resume and reports signal metrics and observed voices. It does not measure
sustained frame rate. Listening is still required to judge the mix.
@@ -0,0 +1,6 @@
{
"version" : 1,
"decoded_size" : 112224,
"pcm_bytes" : 60358,
"cartridge_bytes" : 90810
}
File diff suppressed because it is too large Load Diff
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
Binary file not shown.
@@ -0,0 +1,716 @@
{
"source_fingerprints": [
"d8c7849d857ba7c8b80361ca4a4f0a60c5156790",
"941f8ddea835dfe5edd68ad1498c39bf592b4a58"
],
"source_ppq_inferred_from_paired_beat_tick_fields": 480,
"tonic": "B",
"scale": "minor",
"notes": [
{
"startTick": 0,
"durationTicks": 1200,
"sd": "1",
"octave": 0
},
{
"startTick": 1200,
"durationTicks": 240,
"sd": "#7",
"octave": -1
},
{
"startTick": 1440,
"durationTicks": 240,
"sd": "1",
"octave": 0
},
{
"startTick": 1680,
"durationTicks": 240,
"sd": "2",
"octave": 0
},
{
"startTick": 1920,
"durationTicks": 160,
"sd": "3",
"octave": 0
},
{
"startTick": 2080,
"durationTicks": 160,
"sd": "2",
"octave": 0
},
{
"startTick": 2240,
"durationTicks": 160,
"sd": "1",
"octave": 0
},
{
"startTick": 2400,
"durationTicks": 1440,
"sd": "5",
"octave": 0
},
{
"startTick": 3840,
"durationTicks": 720,
"sd": "6",
"octave": 0
},
{
"startTick": 4560,
"durationTicks": 120,
"sd": "5",
"octave": 0
},
{
"startTick": 4680,
"durationTicks": 120,
"sd": "4",
"octave": 0
},
{
"startTick": 4800,
"durationTicks": 720,
"sd": "5",
"octave": 0
},
{
"startTick": 5520,
"durationTicks": 120,
"sd": "4",
"octave": 0
},
{
"startTick": 5640,
"durationTicks": 120,
"sd": "3",
"octave": 0
},
{
"startTick": 5760,
"durationTicks": 960,
"sd": "2",
"octave": 0
},
{
"startTick": 6720,
"durationTicks": 960,
"sd": "5",
"octave": -1
},
{
"startTick": 7680,
"durationTicks": 1200,
"sd": "1",
"octave": 0
},
{
"startTick": 8880,
"durationTicks": 240,
"sd": "#7",
"octave": -1
},
{
"startTick": 9120,
"durationTicks": 240,
"sd": "1",
"octave": 0
},
{
"startTick": 9360,
"durationTicks": 240,
"sd": "2",
"octave": 0
},
{
"startTick": 9600,
"durationTicks": 160,
"sd": "3",
"octave": 0
},
{
"startTick": 9760,
"durationTicks": 160,
"sd": "2",
"octave": 0
},
{
"startTick": 9920,
"durationTicks": 160,
"sd": "1",
"octave": 0
},
{
"startTick": 10080,
"durationTicks": 1440,
"sd": "5",
"octave": 0
},
{
"startTick": 11520,
"durationTicks": 720,
"sd": "6",
"octave": 0
},
{
"startTick": 12240,
"durationTicks": 120,
"sd": "5",
"octave": 0
},
{
"startTick": 12360,
"durationTicks": 120,
"sd": "4",
"octave": 0
},
{
"startTick": 12480,
"durationTicks": 720,
"sd": "5",
"octave": 0
},
{
"startTick": 13200,
"durationTicks": 120,
"sd": "4",
"octave": 0
},
{
"startTick": 13320,
"durationTicks": 120,
"sd": "3",
"octave": 0
},
{
"startTick": 13440,
"durationTicks": 960,
"sd": "2",
"octave": 0
},
{
"startTick": 14400,
"durationTicks": 960,
"sd": "5",
"octave": 0
},
{
"startTick": 15360,
"durationTicks": 240,
"sd": "6",
"octave": 0
},
{
"startTick": 15600,
"durationTicks": 240,
"sd": "3",
"octave": 0
},
{
"startTick": 15840,
"durationTicks": 240,
"sd": "6",
"octave": 0
},
{
"startTick": 16080,
"durationTicks": 240,
"sd": "1",
"octave": 1
},
{
"startTick": 16320,
"durationTicks": 240,
"sd": "6",
"octave": 0
},
{
"startTick": 16560,
"durationTicks": 240,
"sd": "3",
"octave": 0
},
{
"startTick": 16800,
"durationTicks": 240,
"sd": "6",
"octave": 0
},
{
"startTick": 17040,
"durationTicks": 240,
"sd": "1",
"octave": 1
},
{
"startTick": 17280,
"durationTicks": 240,
"sd": "2",
"octave": 1
},
{
"startTick": 17520,
"durationTicks": 240,
"sd": "1",
"octave": 1
},
{
"startTick": 17760,
"durationTicks": 240,
"sd": "#7",
"octave": 0
},
{
"startTick": 18000,
"durationTicks": 240,
"sd": "2",
"octave": 1
},
{
"startTick": 18240,
"durationTicks": 240,
"sd": "1",
"octave": 1
},
{
"startTick": 18480,
"durationTicks": 240,
"sd": "#7",
"octave": 0
},
{
"startTick": 18720,
"durationTicks": 240,
"sd": "2",
"octave": 1
},
{
"startTick": 18960,
"durationTicks": 120,
"sd": "1",
"octave": 1
},
{
"startTick": 19200,
"durationTicks": 960,
"sd": "3",
"octave": 1
},
{
"startTick": 20160,
"durationTicks": 960,
"sd": "4",
"octave": 1
},
{
"startTick": 21120,
"durationTicks": 480,
"sd": "5",
"octave": 1
},
{
"startTick": 21600,
"durationTicks": 240,
"sd": "4",
"octave": 1
},
{
"startTick": 21840,
"durationTicks": 1200,
"sd": "3",
"octave": 1
},
{
"startTick": 23040,
"durationTicks": 240,
"sd": "6",
"octave": 0
},
{
"startTick": 23280,
"durationTicks": 240,
"sd": "3",
"octave": 0
},
{
"startTick": 23520,
"durationTicks": 240,
"sd": "6",
"octave": 0
},
{
"startTick": 23760,
"durationTicks": 240,
"sd": "1",
"octave": 1
},
{
"startTick": 24000,
"durationTicks": 240,
"sd": "6",
"octave": 0
},
{
"startTick": 24240,
"durationTicks": 240,
"sd": "3",
"octave": 0
},
{
"startTick": 24480,
"durationTicks": 240,
"sd": "6",
"octave": 0
},
{
"startTick": 24720,
"durationTicks": 240,
"sd": "1",
"octave": 1
},
{
"startTick": 24960,
"durationTicks": 240,
"sd": "2",
"octave": 1
},
{
"startTick": 25200,
"durationTicks": 240,
"sd": "1",
"octave": 1
},
{
"startTick": 25440,
"durationTicks": 240,
"sd": "#7",
"octave": 0
},
{
"startTick": 25680,
"durationTicks": 240,
"sd": "2",
"octave": 1
},
{
"startTick": 25920,
"durationTicks": 240,
"sd": "1",
"octave": 1
},
{
"startTick": 26160,
"durationTicks": 240,
"sd": "#7",
"octave": 0
},
{
"startTick": 26400,
"durationTicks": 240,
"sd": "2",
"octave": 1
},
{
"startTick": 26640,
"durationTicks": 240,
"sd": "1",
"octave": 1
},
{
"startTick": 26880,
"durationTicks": 120,
"sd": "1",
"octave": 1
},
{
"startTick": 27000,
"durationTicks": 120,
"sd": "#7",
"octave": 0
},
{
"startTick": 27120,
"durationTicks": 720,
"sd": "1",
"octave": 1
},
{
"startTick": 27840,
"durationTicks": 120,
"sd": "5",
"octave": 0
},
{
"startTick": 27960,
"durationTicks": 120,
"sd": "4",
"octave": 0
},
{
"startTick": 28080,
"durationTicks": 720,
"sd": "5",
"octave": 0
},
{
"startTick": 28800,
"durationTicks": 120,
"sd": "3",
"octave": 0
},
{
"startTick": 28920,
"durationTicks": 120,
"sd": "2",
"octave": 0
},
{
"startTick": 29040,
"durationTicks": 720,
"sd": "3",
"octave": 0
},
{
"startTick": 29760,
"durationTicks": 120,
"sd": "1",
"octave": 0
},
{
"startTick": 29880,
"durationTicks": 120,
"sd": "7",
"octave": -1
},
{
"startTick": 30000,
"durationTicks": 720,
"sd": "1",
"octave": 0
},
{
"startTick": 30720,
"durationTicks": 120,
"sd": "5",
"octave": -1
},
{
"startTick": 30840,
"durationTicks": 120,
"sd": "4",
"octave": -1
},
{
"startTick": 30960,
"durationTicks": 720,
"sd": "5",
"octave": -1
},
{
"startTick": 31680,
"durationTicks": 120,
"sd": "3",
"octave": -1
},
{
"startTick": 31800,
"durationTicks": 120,
"sd": "2",
"octave": -1
},
{
"startTick": 31920,
"durationTicks": 720,
"sd": "3",
"octave": -1
},
{
"startTick": 32640,
"durationTicks": 120,
"sd": "1",
"octave": -1
},
{
"startTick": 32760,
"durationTicks": 120,
"sd": "7",
"octave": -2
},
{
"startTick": 32880,
"durationTicks": 720,
"sd": "1",
"octave": -1
}
],
"chords": [
{
"startTick": 0,
"durationTicks": 1920,
"root": 1,
"type": 5,
"inversion": 0,
"borrowed": ""
},
{
"startTick": 1920,
"durationTicks": 1920,
"root": 5,
"type": 5,
"inversion": 0,
"borrowed": ""
},
{
"startTick": 3840,
"durationTicks": 1920,
"root": 6,
"type": 5,
"inversion": 0,
"borrowed": ""
},
{
"startTick": 5760,
"durationTicks": 960,
"root": 7,
"type": 5,
"inversion": 0,
"borrowed": ""
},
{
"startTick": 6720,
"durationTicks": 960,
"root": 5,
"type": 5,
"inversion": 1,
"borrowed": "major"
},
{
"startTick": 7680,
"durationTicks": 1920,
"root": 1,
"type": 5,
"inversion": 0,
"borrowed": ""
},
{
"startTick": 9600,
"durationTicks": 1920,
"root": 5,
"type": 5,
"inversion": 0,
"borrowed": ""
},
{
"startTick": 11520,
"durationTicks": 1920,
"root": 6,
"type": 5,
"inversion": 0,
"borrowed": ""
},
{
"startTick": 13440,
"durationTicks": 960,
"root": 7,
"type": 7,
"inversion": 0,
"borrowed": ""
},
{
"startTick": 14400,
"durationTicks": 960,
"root": 5,
"type": 7,
"inversion": 1,
"borrowed": "major"
},
{
"startTick": 15360,
"durationTicks": 1920,
"root": 6,
"type": 5,
"inversion": 0,
"borrowed": ""
},
{
"startTick": 17280,
"durationTicks": 1920,
"root": 5,
"type": 5,
"inversion": 0,
"borrowed": "major"
},
{
"startTick": 19200,
"durationTicks": 960,
"root": 1,
"type": 5,
"inversion": 0,
"borrowed": ""
},
{
"startTick": 20160,
"durationTicks": 960,
"root": 7,
"type": 5,
"inversion": 1,
"borrowed": ""
},
{
"startTick": 21120,
"durationTicks": 960,
"root": 3,
"type": 5,
"inversion": 0,
"borrowed": ""
},
{
"startTick": 22080,
"durationTicks": 960,
"root": 1,
"type": 5,
"inversion": 2,
"borrowed": ""
},
{
"startTick": 23040,
"durationTicks": 1920,
"root": 6,
"type": 5,
"inversion": 0,
"borrowed": ""
},
{
"startTick": 24960,
"durationTicks": 1920,
"root": 5,
"type": 5,
"inversion": 0,
"borrowed": "major"
},
{
"startTick": 26880,
"durationTicks": 3840,
"root": 1,
"type": 5,
"inversion": 0,
"borrowed": ""
},
{
"startTick": 30720,
"durationTicks": 3840,
"root": 1,
"type": 5,
"inversion": 0,
"borrowed": ""
}
],
"source_duration_ticks": 34560,
"proposed_root_midi": 71,
"bpm": 168
}
+375
View File
@@ -0,0 +1,375 @@
//! This module emits guest code. It never simulates particles or precomputes motion.
use prometeu_bytecode::{
assemble,
load_limits::LoadBudget,
model::{ConstantPoolEntry, DebugInfo, Export, SyscallDecl},
registry::{
BuiltinId, FunctionDecl, NamedType, Registry, RegistryDeclarations, TypeDecl, TypeId,
TypeKind,
},
registry_codec::PbxModule,
};
pub const PARTICLE_TRAVEL_SCALE: f64 = 1.5;
pub const DEFAULT_SEED: i64 = 0x5052_4f4d;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Preset {
Light,
Normal,
Heavy,
}
impl Preset {
pub fn name(self) -> &'static str {
match self {
Self::Light => "light",
Self::Normal => "normal",
Self::Heavy => "heavy",
}
}
pub fn particles(self) -> i32 {
match self {
Self::Light => 64,
Self::Normal => 128,
Self::Heavy => 384,
}
}
pub fn substeps(self) -> i32 {
match self {
Self::Light => 1,
Self::Normal => 2,
Self::Heavy => 4,
}
}
pub fn parse(s: &str) -> Option<Self> {
match s {
"light" => Some(Self::Light),
"normal" => Some(Self::Normal),
"heavy" => Some(Self::Heavy),
_ => None,
}
}
}
// Registry: 0:Int32, 1:Int64, 2:Float, 3:Random, 4:Particle, 5:Array<Particle>.
// Particle: x,y,vx,vy:Float; life,palette:Int32. Global 2 roots RNG, 3 roots array.
// Main locals: i,particle,time,pass,x,y,vx,vy,radius,angle,phase,speed,px,py,ring,segment.
struct Code(Vec<u8>);
impl Code {
fn emit(&mut self, s: &str) {
self.0.extend(assemble(s).expect("guest assembly"));
}
fn float(&mut self, x: f64) {
self.emit(&format!("PUSH_F64 f64:0x{:016x}", x.to_bits()));
}
fn intrinsic(&mut self, owner: &str, name: &str) {
let meta =
prometeu_vm::lookup_intrinsic(owner, name, 1).expect("runtime intrinsic catalog");
self.emit(&format!("INTRINSIC {}", meta.id));
}
fn branch(&mut self, opcode: &str) -> usize {
let at = self.0.len() + 2;
self.emit(&format!("{opcode} 0"));
at
}
fn patch(&mut self, at: usize, target: usize) {
self.0[at..at + 4].copy_from_slice(&(target as u32).to_le_bytes());
}
fn here(&self) -> usize {
self.0.len()
}
fn jump(&mut self, to: usize) {
self.emit(&format!("JMP {to}"));
}
fn field(&mut self, n: u32) {
self.emit(&format!("GET_LOCAL 1\nSTRUCT_GET type=4,field={n}"));
}
fn set_field_local(&mut self, n: u32, local: u32) {
self.emit(&format!("GET_LOCAL 1\nGET_LOCAL {local}\nSTRUCT_SET type=4,field={n}"));
}
fn respawn(&mut self) {
for (field, extent) in [(0, 270.0), (1, 130.0), (2, 0.8), (3, 0.8)] {
self.emit("GET_LOCAL 1\nGET_GLOBAL 2");
self.intrinsic("random", "nextf");
self.float(2.0);
self.emit("MUL");
self.float(1.0);
self.emit("SUB");
self.float(extent);
self.emit(&format!("MUL\nSTRUCT_SET type=4,field={field}"));
}
self.emit("GET_LOCAL 1\nGET_GLOBAL 2\nPUSH_I64 45\nPUSH_I64 225");
self.intrinsic("random", "range");
self.intrinsic("math.i64", "to_i32");
self.emit("STRUCT_SET type=4,field=4\nGET_LOCAL 1\nGET_GLOBAL 2");
self.intrinsic("random", "next");
self.emit("PUSH_I64 7\nBIT_AND");
self.intrinsic("math.i64", "to_i32");
self.emit("PUSH_I32 8\nADD\nSTRUCT_SET type=4,field=5\nGET_GLOBAL 6\nPUSH_I32 1\nADD\nSET_GLOBAL 6");
}
fn submit(&mut self) {
// The machine returns status; retain it and report failures instead of silently dropping.
self.emit("HOSTCALL 4\nGET_GLOBAL 5\nADD\nSET_GLOBAL 5");
}
}
pub fn program(preset: Preset, seed: i64) -> Vec<u8> {
let mut c = Code(Vec::new());
c.emit("GET_GLOBAL 1\nPUSH_I32 0\nEQ");
let initialized = c.branch("JMP_IF_FALSE");
c.emit(&format!("PUSH_I64 {seed}"));
c.intrinsic("random", "new");
c.emit(&format!(
"SET_GLOBAL 2\nPUSH_I64 {}\nARRAY_NEW 5\nSET_GLOBAL 3\nPUSH_I32 0\nSET_LOCAL 0",
preset.particles()
));
let init = c.here();
c.emit("STRUCT_NEW 4\nSET_LOCAL 1");
c.respawn();
c.emit("GET_GLOBAL 3\nGET_LOCAL 0");
c.intrinsic("math.i32", "to_i64");
c.emit(&format!("GET_LOCAL 1\nARRAY_SET 5\nGET_LOCAL 0\nPUSH_I32 1\nADD\nSET_LOCAL 0\nGET_LOCAL 0\nPUSH_I32 {}\nLT",preset.particles()));
let done = c.branch("JMP_IF_FALSE");
c.jump(init);
c.patch(done, c.here());
c.emit("PUSH_I32 0\nHOSTCALL 2\nPOP_N 1\nPUSH_I32 0\nPUSH_I32 180\nHOSTCALL 6\nPOP_N 1\nPUSH_I32 0\nPUSH_I32 0\nPUSH_I32 1\nHOSTCALL 5\nPOP_N 1");
c.emit("PUSH_I32 0\nPUSH_I32 0\nPUSH_I32 167");
c.float(0.22);
c.float(0.18);
c.float(1.0);
c.emit("HOSTCALL 7\nPOP_N 1\nPUSH_I32 1\nSET_GLOBAL 1");
c.patch(initialized, c.here());
c.emit("GET_GLOBAL 0\nPUSH_I32 1\nADD\nSET_GLOBAL 0\nPUSH_I32 0\nSET_GLOBAL 5\nGET_GLOBAL 0");
c.intrinsic("math.i32", "to_float");
c.float(0.016666666666666666);
c.emit("MUL\nSET_LOCAL 2");
c.emit("GET_GLOBAL 0\nPUSH_I32 128\nMOD\nGET_GLOBAL 0\nPUSH_I32 2\nDIV\nPUSH_I32 152\nMOD\nHOSTCALL 3");
c.emit("PUSH_I32 0\nSET_LOCAL 0");
let particle = c.here();
c.emit("GET_GLOBAL 3\nGET_LOCAL 0");
c.intrinsic("math.i32", "to_i64");
c.emit("ARRAY_GET 5\nSET_LOCAL 1");
c.field(4);
c.emit("PUSH_I32 1\nSUB\nSET_LOCAL 14");
c.set_field_local(4, 14);
c.emit("GET_LOCAL 14\nPUSH_I32 0\nGT");
let alive = c.branch("JMP_IF_TRUE");
c.respawn();
c.patch(alive, c.here());
for (field, local) in [(0, 4), (1, 5), (2, 6), (3, 7)] {
c.field(field);
c.emit(&format!("SET_LOCAL {local}"));
}
c.emit("PUSH_I32 0\nSET_LOCAL 3");
let pass = c.here();
c.emit("GET_LOCAL 4\nGET_LOCAL 5");
c.intrinsic("vec2", "length");
c.float(40.0);
c.emit("ADD\nSET_LOCAL 8");
c.emit("GET_LOCAL 5\nGET_LOCAL 4");
c.float(0.00001);
c.emit("ADD");
c.intrinsic("mathf", "atan2");
c.emit("SET_LOCAL 9");
c.emit("GET_LOCAL 8");
c.float(0.018);
c.emit("MUL\nGET_LOCAL 2\nADD\nSET_LOCAL 10");
// A softened tangential force, centre attraction and time-varying wave perturbation.
for (v, radial, tangent, trig, sign) in [(6, 4, 5, "sin", -1.0), (7, 5, 4, "cos", 1.0)] {
c.emit(&format!("GET_LOCAL {v}\nGET_LOCAL {radial}"));
c.float(-0.002);
c.emit("MUL");
c.emit(&format!("GET_LOCAL {tangent}\nGET_LOCAL 8\nDIV"));
c.float(sign * 0.45);
c.emit("MUL\nADD\nGET_LOCAL 10\nGET_LOCAL 9\nADD");
c.intrinsic("mathf", trig);
c.float(0.1);
c.emit("MUL\nADD");
c.float(1.0 / f64::from(preset.substeps()));
c.emit("MUL\nADD");
c.float(0.995);
c.emit("MUL");
c.float(-3.5);
c.float(3.5);
c.intrinsic("mathf", "clamp");
c.emit(&format!("SET_LOCAL {v}"));
}
c.emit("GET_LOCAL 6\nGET_LOCAL 7\nGET_LOCAL 6\nGET_LOCAL 7");
c.intrinsic("vec2", "dot");
c.intrinsic("mathf", "sqrt");
c.emit("SET_LOCAL 11");
for (position, velocity, extent) in [(4, 6, 300.0), (5, 7, 142.0)] {
c.emit(&format!("GET_LOCAL {position}\nGET_LOCAL {velocity}"));
c.float(PARTICLE_TRAVEL_SCALE / f64::from(preset.substeps()));
c.emit("MUL\nADD");
c.float(-extent);
c.float(extent);
c.intrinsic("mathf", "clamp");
c.emit(&format!("SET_LOCAL {position}"));
}
c.emit(&format!("GET_GLOBAL 7\nPUSH_I32 1\nADD\nSET_GLOBAL 7\nGET_LOCAL 3\nPUSH_I32 1\nADD\nSET_LOCAL 3\nGET_LOCAL 3\nPUSH_I32 {}\nLT",preset.substeps()));
let passes_done = c.branch("JMP_IF_FALSE");
c.jump(pass);
c.patch(passes_done, c.here());
for (field, local) in [(0, 4), (1, 5), (2, 6), (3, 7)] {
c.set_field_local(field, local);
}
c.emit("GET_LOCAL 11");
c.float(0.35);
c.emit("MUL");
c.intrinsic("mathf", "to_i32");
c.emit("PUSH_I32 0\nPUSH_I32 1");
c.intrinsic("math.i32", "clamp");
c.field(5);
c.emit("GET_LOCAL 4");
c.float(316.0);
c.emit("ADD");
c.intrinsic("mathf", "to_i32");
c.emit("GET_LOCAL 5");
c.float(176.0);
c.emit("ADD");
c.intrinsic("mathf", "to_i32");
c.emit("PUSH_I32 3\nPUSH_I32 0\nPUSH_BOOL 0\nPUSH_BOOL 0\nPUSH_I32 3");
c.submit();
c.emit(&format!(
"GET_LOCAL 0\nPUSH_I32 1\nADD\nSET_LOCAL 0\nGET_LOCAL 0\nPUSH_I32 {}\nLT",
preset.particles()
));
let particles_done = c.branch("JMP_IF_FALSE");
c.jump(particle);
c.patch(particles_done, c.here());
// Eight rings, sixteen markers each, projected onto the native 2D compositor.
c.emit("PUSH_I32 0\nSET_LOCAL 0");
let tunnel = c.here();
c.emit("GET_LOCAL 0\nPUSH_I32 16\nDIV\nSET_LOCAL 14\nGET_LOCAL 0\nPUSH_I32 16\nMOD");
c.intrinsic("math.i32", "to_float");
c.float(std::f64::consts::TAU / 16.0);
c.emit("MUL\nGET_LOCAL 2");
c.float(0.18);
c.emit("MUL\nADD\nGET_LOCAL 14");
c.intrinsic("math.i32", "to_float");
c.float(0.10);
c.emit("MUL\nADD\nSET_LOCAL 9");
c.float(9000.0);
c.emit("GET_LOCAL 14\nPUSH_I32 40\nMUL\nGET_GLOBAL 0\nPUSH_I32 2\nMUL\nADD\nPUSH_I32 320\nMOD\nPUSH_I32 32\nADD");
c.intrinsic("math.i32", "to_float");
c.emit("DIV\nSET_LOCAL 8");
for (local, trig, scale, center) in [(12, "cos", 1.0, 316.0), (13, "sin", 0.58, 176.0)] {
c.emit("GET_LOCAL 9");
c.intrinsic("mathf", trig);
c.emit("GET_LOCAL 8\nMUL");
c.float(scale);
c.emit("MUL");
c.float(center);
c.emit("ADD\nGET_LOCAL 2");
c.float(0.6);
c.emit("MUL");
c.intrinsic("mathf", if local == 12 { "sin" } else { "cos" });
c.float(if local == 12 { 30.0 } else { 18.0 });
c.emit(&format!("MUL\nADD\nSET_LOCAL {local}"));
}
c.emit("PUSH_I32 2\nGET_LOCAL 14\nPUSH_I32 16\nADD\nGET_LOCAL 12");
c.intrinsic("mathf", "to_i32");
c.emit("GET_LOCAL 13");
c.intrinsic("mathf", "to_i32");
c.emit("PUSH_I32 2\nPUSH_I32 0\nPUSH_BOOL 0\nPUSH_BOOL 0\nPUSH_I32 1");
c.submit();
c.emit("GET_LOCAL 0\nPUSH_I32 1\nADD\nSET_LOCAL 0\nGET_LOCAL 0\nPUSH_I32 128\nLT");
let tunnel_done = c.branch("JMP_IF_FALSE");
c.jump(tunnel);
c.patch(tunnel_done, c.here());
// Opaque title/footer bands keep stars and particles from obscuring the text.
c.emit("PUSH_I32 0\nPUSH_I32 0\nPUSH_I32 640\nPUSH_I32 40\nPUSH_I64 50795263\nHOSTCALL 8");
c.emit("PUSH_I32 0\nPUSH_I32 312\nPUSH_I32 640\nPUSH_I32 48\nPUSH_I64 50795263\nHOSTCALL 8");
for (i, y, color) in
[(0, 14, 0xd4f4ffffu32), (1, 30, 0x729dbbff), (2, 320, 0x9de9d7ff), (3, 336, 0x729dbbff)]
{
c.emit(&format!("PUSH_I32 16\nPUSH_I32 {y}\nPUSH_CONST {i}\nPUSH_I64 {color}\nHOSTCALL 0"));
}
c.emit("GET_GLOBAL 5\nPUSH_I32 0\nNEQ");
let no_errors = c.branch("JMP_IF_FALSE");
c.emit("PUSH_I32 3\nPUSH_CONST 4\nHOSTCALL 1");
c.patch(no_errors, c.here());
c.emit("GET_GLOBAL 0\nPUSH_I32 60\nMOD\nPUSH_I32 0\nEQ");
let no_log = c.branch("JMP_IF_FALSE");
c.emit("PUSH_I32 2\nPUSH_CONST 2\nHOSTCALL 1");
c.patch(no_log, c.here());
c.emit("RET");
let types = [BuiltinId::INT32, BuiltinId::INT64, BuiltinId::FLOAT, BuiltinId::RANDOM]
.into_iter()
.map(|b| TypeDecl { name: None, kind: TypeKind::Builtin(b) })
.chain([
TypeDecl {
name: Some("Particle".into()),
kind: TypeKind::Struct(
[2, 2, 2, 2, 0, 0]
.into_iter()
.map(|t| NamedType { type_id: TypeId(t), name: None })
.collect(),
),
},
TypeDecl { name: None, kind: TypeKind::Array(TypeId(4)) },
])
.collect();
let mut budget = LoadBudget::new(Default::default());
let registry = Registry::resolve(
RegistryDeclarations {
types,
functions: vec![FunctionDecl {
code_len: c.0.len() as u32,
local_slots: 16,
max_stack_slots: 32,
..Default::default()
}],
implementations: vec![],
},
c.0.len(),
&mut budget,
)
.expect("demo registry");
let constants = vec![
"PROMETEU // VORTEX FIELD".into(),
"MATH + RANDOM + GUEST STATE + COMPOSER".into(),
format!(
"{} // {} PARTICLES x {} PASSES",
preset.name().to_uppercase(),
preset.particles(),
preset.substeps()
),
format!("STORM EAGLE // MUSIC A // SEED {seed}"),
"DEMO: COMPOSER SUBMISSION FAILED".into(),
]
.into_iter()
.map(ConstantPoolEntry::String)
.collect::<Vec<_>>();
let syscalls = [
("gfx2d", "draw_text", 4, 0),
("log", "write", 2, 0),
("composer", "bind_scene", 1, 1),
("composer", "set_camera", 2, 0),
("composer", "emit_sprite", 9, 1),
("music", "play", 3, 1),
("music", "set_volume", 2, 1),
("audio", "set_effect", 6, 1),
("gfx2d", "fill_rect", 5, 0),
]
.into_iter()
.map(|(module, name, arg_slots, ret_slots)| SyscallDecl {
module: module.into(),
name: name.into(),
version: 1,
arg_slots,
ret_slots,
})
.collect::<Vec<_>>();
let debug = DebugInfo { pc_to_span: vec![], function_names: vec![(0, "main".into())] };
PbxModule {
registry: &registry,
constants: &constants,
code: &c.0,
debug: Some(&debug),
exports: &[Export { symbol: "main".into(), func_idx: 0 }],
syscalls: &syscalls,
}
.serialize(&mut budget)
.expect("demo PBX")
}
+117 -224
View File
@@ -1,9 +1,4 @@
use anyhow::Result;
use prometeu_bytecode::assembler::assemble;
use prometeu_bytecode::load_limits::LoadBudget;
use prometeu_bytecode::model::{ConstantPoolEntry, DebugInfo, Export, SyscallDecl};
use prometeu_bytecode::registry::{FunctionDecl, Registry, RegistryDeclarations};
use prometeu_bytecode::registry_codec::PbxModule;
use prometeu_hal::asset::{
AssetCodec, AssetEntry, AssetId, BankType, PreloadEntry, SCENE_DECODED_LAYER_OVERHEAD_BYTES_V1,
SCENE_LAYER_COUNT_V1, SCENE_PAYLOAD_MAGIC_V1, SCENE_PAYLOAD_VERSION_V1,
@@ -25,211 +20,50 @@ use std::fs;
use std::mem::size_of;
use std::path::PathBuf;
mod music;
const STRESS_GLYPH_ASSET_ID: AssetId = 100;
const STRESS_SCENE_ASSET_ID: AssetId = 1;
const STRESS_VIEWPORT_W: i32 = prometeu_hal::graphics_contract::WIDTH as i32;
const STRESS_VIEWPORT_H: i32 = prometeu_hal::graphics_contract::HEIGHT as i32;
const STRESS_SPRITE_COLS: i32 = 48;
const STRESS_SPRITE_ROWS: i32 = 24;
const STRESS_SPRITE_SPACING_PX: i32 = 10;
const STRESS_SCENE_TILE_W: usize = 96;
const STRESS_SCENE_TILE_H: usize = 64;
fn asm(s: &str) -> Vec<u8> {
assemble(s).expect("assemble")
mod demo;
pub use demo::{Preset, DEFAULT_SEED, PARTICLE_TRAVEL_SCALE};
pub const DEFAULT_PRESET: Preset = Preset::Heavy;
pub fn build_program() -> Vec<u8> {
build_program_with(DEFAULT_PRESET, DEFAULT_SEED)
}
pub fn build_program_with(preset: Preset, seed: i64) -> Vec<u8> {
demo::program(preset, seed)
}
pub fn manifest_json() -> Vec<u8> {
b"{\n \"magic\": \"PMTU\",\n \"cartridge_version\": 1,\n \"app_id\": 1,\n \"title\": \"Stress Console\",\n \"app_version\": \"0.1.0\",\n \"app_mode\": \"Game\",\n \"capabilities\": [\"composer\", \"gfx2d\", \"log\", \"asset\", \"audio\"]\n}\n".to_vec()
}
pub fn generate() -> Result<()> {
let mut rom: Vec<u8> = Vec::new();
let syscalls = vec![
SyscallDecl {
module: "gfx2d".into(),
name: "draw_text".into(),
version: 1,
arg_slots: 4,
ret_slots: 0,
},
SyscallDecl {
module: "log".into(),
name: "write".into(),
version: 1,
arg_slots: 2,
ret_slots: 0,
},
SyscallDecl {
module: "composer".into(),
name: "bind_scene".into(),
version: 1,
arg_slots: 1,
ret_slots: 1,
},
SyscallDecl {
module: "composer".into(),
name: "set_camera".into(),
version: 1,
arg_slots: 2,
ret_slots: 0,
},
SyscallDecl {
module: "composer".into(),
name: "emit_sprite".into(),
version: 1,
arg_slots: 9,
ret_slots: 1,
},
];
heavy_load(&mut rom);
// light_load(&mut rom);
let registry = Registry::resolve(
RegistryDeclarations {
functions: vec![FunctionDecl {
lifecycle_role: Default::default(),
code_len: rom.len() as u32,
local_slots: 2,
max_stack_slots: 32,
..Default::default()
}],
..Default::default()
},
rom.len(),
&mut LoadBudget::new(Default::default()),
)
.expect("resolved program declarations");
let constants = vec![
ConstantPoolEntry::String("stress".into()),
ConstantPoolEntry::String("frame".into()),
ConstantPoolEntry::String("overlay".into()),
ConstantPoolEntry::String("composer".into()),
];
let debug = DebugInfo { pc_to_span: vec![], function_names: vec![(0, "main".into())] };
let exports = [Export { symbol: "main".into(), func_idx: 0 }];
let bytes = PbxModule {
registry: &registry,
constants: &constants,
code: &rom,
debug: Some(&debug),
exports: &exports,
syscalls: &syscalls,
}
.serialize(&mut LoadBudget::new(Default::default()))
.expect("bounded v0 program");
generate_with(DEFAULT_PRESET, DEFAULT_SEED, None)
}
pub fn generate_with(preset: Preset, seed: i64, output: Option<PathBuf>) -> Result<()> {
let mut out_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
out_dir.pop(); // pbxgen-stress
out_dir.pop(); // tools
out_dir.pop(); // crates
out_dir.push("test-cartridges");
out_dir.push("stress-console");
let out_dir = output.unwrap_or(out_dir);
fs::create_dir_all(&out_dir)?;
fs::write(out_dir.join("program.pbx"), bytes)?;
fs::write(out_dir.join("program.pbx"), build_program_with(preset, seed))?;
fs::write(out_dir.join("assets.pa"), build_assets_pack()?)?;
fs::write(out_dir.join("manifest.json"), b"{\n \"magic\": \"PMTU\",\n \"cartridge_version\": 1,\n \"app_id\": 1,\n \"title\": \"Stress Console\",\n \"app_version\": \"0.1.0\",\n \"app_mode\": \"Game\",\n \"capabilities\": [\"composer\", \"gfx2d\", \"log\", \"asset\"]\n}\n")?;
fs::write(out_dir.join("manifest.json"), manifest_json())?;
Ok(())
}
fn heavy_load(rom: &mut Vec<u8>) {
// Single function 0: main
// Global 0 = frame counter
// Global 1 = scene bound flag
// Local 0 = sprite row
// Local 1 = sprite col
rom.extend(asm("GET_GLOBAL 0\nPUSH_I32 1\nADD\nSET_GLOBAL 0"));
rom.extend(asm("GET_GLOBAL 1\nPUSH_I32 0\nEQ"));
let jif_bind_done_offset = rom.len() + 2;
rom.extend(asm("JMP_IF_FALSE 0"));
rom.extend(asm("PUSH_I32 0\nHOSTCALL 2\nPOP_N 1\nPUSH_I32 1\nSET_GLOBAL 1"));
let bind_done_target = rom.len() as u32;
let scene_width_px = (STRESS_SCENE_TILE_W * 8) as i32;
let scene_height_px = (STRESS_SCENE_TILE_H * 8) as i32;
let camera_x_span = scene_width_px - STRESS_VIEWPORT_W;
let camera_y_span = scene_height_px - STRESS_VIEWPORT_H;
rom.extend(asm(&format!(
"GET_GLOBAL 0\nPUSH_I32 2\nMUL\nPUSH_I32 {camera_x_span}\nMOD\nGET_GLOBAL 0\nPUSH_I32 {camera_y_span}\nMOD\nHOSTCALL 3"
)));
rom.extend(asm("PUSH_I32 0\nSET_LOCAL 0"));
let row_loop_start = rom.len() as u32;
rom.extend(asm(&format!("GET_LOCAL 0\nPUSH_I32 {STRESS_SPRITE_ROWS}\nLT")));
let jif_row_end_offset = rom.len() + 2;
rom.extend(asm("JMP_IF_FALSE 0"));
rom.extend(asm("PUSH_I32 0\nSET_LOCAL 1"));
let col_loop_start = rom.len() as u32;
rom.extend(asm(&format!("GET_LOCAL 1\nPUSH_I32 {STRESS_SPRITE_COLS}\nLT")));
let jif_col_end_offset = rom.len() + 2;
rom.extend(asm("JMP_IF_FALSE 0"));
rom.extend(asm(&format!(
"PUSH_I32 0\n\
GET_LOCAL 0\nPUSH_I32 {STRESS_SPRITE_COLS}\nMUL\nGET_LOCAL 1\nADD\nGET_GLOBAL 0\nADD\nPUSH_I32 15\nMOD\nPUSH_I32 1\nADD\n\
GET_LOCAL 1\nPUSH_I32 {STRESS_SPRITE_SPACING_PX}\nMUL\nGET_GLOBAL 0\nPUSH_I32 10\nMOD\nADD\nPUSH_I32 {STRESS_VIEWPORT_W}\nMOD\n\
GET_LOCAL 0\nPUSH_I32 {STRESS_SPRITE_SPACING_PX}\nMUL\nGET_GLOBAL 0\nPUSH_I32 2\nMUL\nPUSH_I32 10\nMOD\nADD\nPUSH_I32 {STRESS_VIEWPORT_H}\nMOD\n\
GET_LOCAL 0\nGET_LOCAL 1\nADD\nGET_GLOBAL 0\nADD\nPUSH_I32 4\nMOD\n\
PUSH_I32 0\n\
GET_LOCAL 1\nGET_GLOBAL 0\nADD\nPUSH_I32 1\nBIT_AND\nPUSH_I32 0\nNEQ\n\
GET_LOCAL 0\nGET_GLOBAL 0\nADD\nPUSH_I32 1\nBIT_AND\nPUSH_I32 0\nNEQ\n\
GET_LOCAL 0\nGET_LOCAL 1\nADD\nPUSH_I32 4\nMOD\n\
HOSTCALL 4\nPOP_N 1"
)));
rom.extend(asm("GET_LOCAL 1\nPUSH_I32 1\nADD\nSET_LOCAL 1"));
let jmp_col_loop_offset = rom.len() + 2;
rom.extend(asm("JMP 0"));
let col_loop_end = rom.len() as u32;
rom.extend(asm("GET_LOCAL 0\nPUSH_I32 1\nADD\nSET_LOCAL 0"));
let jmp_row_loop_offset = rom.len() + 2;
rom.extend(asm("JMP 0"));
let row_loop_end = rom.len() as u32;
rom.extend(asm("GET_GLOBAL 0\nPUSH_I32 3\nMUL\nPUSH_I32 380\nMOD\n\
PUSH_I32 8\n\
PUSH_CONST 0\n\
GET_GLOBAL 0\nPUSH_I32 2047\nMUL\nPUSH_I32 65535\nBIT_AND\n\
HOSTCALL 0"));
rom.extend(asm("PUSH_I32 16\n\
GET_GLOBAL 0\nPUSH_I32 2\nMUL\nPUSH_I32 186\nMOD\nPUSH_I32 32\nADD\n\
PUSH_CONST 1\n\
GET_GLOBAL 0\nPUSH_I32 4093\nMUL\nPUSH_I32 65535\nBIT_AND\n\
HOSTCALL 0"));
rom.extend(asm("PUSH_I32 336\n\
GET_GLOBAL 0\nPUSH_I32 5\nMUL\nPUSH_I32 194\nMOD\n\
PUSH_CONST 2\n\
GET_GLOBAL 0\nPUSH_I32 1237\nMUL\nPUSH_I32 65535\nBIT_AND\n\
HOSTCALL 0"));
rom.extend(asm("GET_GLOBAL 0\nPUSH_I32 4\nMUL\nPUSH_I32 240\nMOD\nPUSH_I32 112\nADD\n\
GET_GLOBAL 0\nPUSH_I32 3\nMUL\nPUSH_I32 120\nMOD\nPUSH_I32 88\nADD\n\
PUSH_CONST 3\n\
GET_GLOBAL 0\nPUSH_I32 3001\nMUL\nPUSH_I32 65535\nBIT_AND\n\
HOSTCALL 0"));
rom.extend(asm("GET_GLOBAL 0\nPUSH_I32 60\nMOD\nPUSH_I32 0\nEQ"));
let jif_log_offset = rom.len() + 2;
rom.extend(asm("JMP_IF_FALSE 0"));
rom.extend(asm("PUSH_I32 2\nPUSH_CONST 0\nHOSTCALL 1"));
let after_log = rom.len() as u32;
rom.extend(asm("RET"));
let patch = |buf: &mut Vec<u8>, imm_offset: usize, target: u32| {
buf[imm_offset..imm_offset + 4].copy_from_slice(&target.to_le_bytes());
};
patch(rom, jif_bind_done_offset, bind_done_target);
patch(rom, jif_row_end_offset, row_loop_end);
patch(rom, jif_col_end_offset, col_loop_end);
patch(rom, jmp_col_loop_offset, col_loop_start);
patch(rom, jmp_row_loop_offset, row_loop_start);
patch(rom, jif_log_offset, after_log);
}
fn build_assets_pack() -> Result<Vec<u8>> {
pub fn build_assets_pack() -> Result<Vec<u8>> {
let (glyph_entry, glyph_payload) = build_glyph_asset();
let scene = build_scene_bank();
let scene_payload = encode_scene_payload(&scene);
@@ -244,12 +78,15 @@ fn build_assets_pack() -> Result<Vec<u8>> {
metadata: serde_json::json!({}),
};
let asset_table = vec![glyph_entry, scene_entry];
let (music_entry, music_payload) =
music::asset((glyph_payload.len() + scene_payload.len()) as u64)?;
let asset_table = vec![glyph_entry, scene_entry, music_entry];
let preload = vec![
PreloadEntry { asset_id: STRESS_GLYPH_ASSET_ID, slot: 0 },
PreloadEntry { asset_id: STRESS_SCENE_ASSET_ID, slot: 0 },
PreloadEntry { asset_id: music::ASSET_ID, slot: 0 },
];
let payload_len = glyph_payload.len() + scene_payload.len();
let payload_len = glyph_payload.len() + scene_payload.len() + music_payload.len();
let header = serde_json::to_vec(&AssetsPackHeader { asset_table, preload })?;
let payload_offset = (ASSETS_PA_PRELUDE_SIZE + header.len()) as u64;
let prelude = AssetsPackPrelude {
@@ -266,27 +103,60 @@ fn build_assets_pack() -> Result<Vec<u8>> {
bytes.extend_from_slice(&header);
bytes.extend_from_slice(&glyph_payload);
bytes.extend_from_slice(&scene_payload);
bytes.extend_from_slice(music_payload);
debug_assert_eq!(bytes.len(), payload_offset as usize + payload_len);
Ok(bytes)
}
fn build_glyph_asset() -> (AssetEntry, Vec<u8>) {
let pixel_indices = vec![1_u8; 8 * 8];
// Four 8x8 tiles in a row: soft particle, star, tunnel marker, opaque backdrop.
let mut pixel_indices = vec![0_u8; 32 * 8];
for y in 0..8_i32 {
for x in 0..8_i32 {
let dx = (x * 2 - 7).abs();
let dy = (y * 2 - 7).abs();
let radius = dx * dx + dy * dy;
pixel_indices[y as usize * 32 + x as usize] = if radius <= 4 {
3
} else if radius <= 20 {
2
} else if radius <= 42 {
1
} else {
0
};
pixel_indices[y as usize * 32 + 8 + x as usize] = if dx <= 1 && dy <= 1 {
3
} else if (dx <= 1 && dy <= 5) || (dy <= 1 && dx <= 5) {
2
} else {
0
};
pixel_indices[y as usize * 32 + 16 + x as usize] = if dx + dy <= 4 {
3
} else if dx + dy <= 6 {
2
} else {
0
};
pixel_indices[y as usize * 32 + 24 + x as usize] = 4;
}
}
let mut payload = pack_4bpp(&pixel_indices);
payload.extend_from_slice(&build_palette_bytes());
let entry = AssetEntry {
asset_id: STRESS_GLYPH_ASSET_ID,
asset_name: "stress_square".into(),
asset_name: "vortex_tiles".into(),
bank_type: BankType::GLYPH,
offset: 0,
size: payload.len() as u64,
decoded_size: (8 * 8 + GLYPH_BANK_MAX_PALETTE_COUNT_V1 * GLYPH_BANK_COLORS_PER_PALETTE * 4)
decoded_size: (32 * 8 + GLYPH_BANK_MAX_PALETTE_COUNT_V1 * GLYPH_BANK_COLORS_PER_PALETTE * 4)
as u64,
codec: AssetCodec::None,
metadata: serde_json::json!({
"tile_size": 8,
"width": 8,
"width": 32,
"height": 8,
"palette_count": GLYPH_BANK_MAX_PALETTE_COUNT_V1,
"palette_authored": GLYPH_BANK_MAX_PALETTE_COUNT_V1
@@ -301,20 +171,40 @@ fn build_palette_bytes() -> Vec<u8> {
Vec::with_capacity(GLYPH_BANK_MAX_PALETTE_COUNT_V1 * GLYPH_BANK_COLORS_PER_PALETTE * 4);
for palette_id in 0..GLYPH_BANK_MAX_PALETTE_COUNT_V1 {
for color_index in 0..GLYPH_BANK_COLORS_PER_PALETTE {
let color = if color_index == 1 { stress_color(palette_id) } else { Color::BLACK };
let (r, g, b) = match palette_id {
0..=7 => (
40 + palette_id as u8 * 8,
64 + palette_id as u8 * 10,
100 + palette_id as u8 * 12,
),
8..=15 => {
let n = palette_id as u8 - 8;
(60 + n * 25, 230 - n * 18, 255 - n * 8)
}
_ => {
let n = (palette_id % 8) as u8;
(90 + n * 20, 100 + n * 8, 240 - n * 9)
}
};
let color = match color_index {
0 => Color::TRANSPARENT,
1 => Color::rgba(r / 2, g / 2, b / 2, 48),
2 => Color::rgba(r, g, b, 150),
3 => Color::rgba(
r.saturating_add(60),
g.saturating_add(60),
b.saturating_add(60),
255,
),
4 => Color::rgb(3, 7, 18),
_ => Color::TRANSPARENT,
};
bytes.extend_from_slice(&color.raw().to_be_bytes());
}
}
bytes
}
fn stress_color(palette_id: usize) -> Color {
let r = ((palette_id * 53) % 256) as u8;
let g = ((palette_id * 97 + 64) % 256) as u8;
let b = ((palette_id * 29 + 128) % 256) as u8;
Color::rgb(r, g, b)
}
fn pack_4bpp(indices: &[u8]) -> Vec<u8> {
let mut packed = Vec::with_capacity(indices.len().div_ceil(2));
for chunk in indices.chunks(2) {
@@ -326,7 +216,7 @@ fn pack_4bpp(indices: &[u8]) -> Vec<u8> {
}
fn build_scene_bank() -> SceneBank {
let mut layers = std::array::from_fn(|layer_index| {
let layers = std::array::from_fn(|layer_index| {
let mut tiles = vec![
Tile {
active: false,
@@ -339,15 +229,17 @@ fn build_scene_bank() -> SceneBank {
for y in 0..STRESS_SCENE_TILE_H {
for x in 0..STRESS_SCENE_TILE_W {
let diagonal = (x + layer_index * 2) % 11 == (y * 2) % 11;
let stripe = (x / 6 + y / 5 + layer_index) % 5 == 0;
if diagonal || stripe {
let index = y * STRESS_SCENE_TILE_W + x;
tiles[index] = Tile {
// Static authored star field; particle randomness belongs to the guest RNG.
let star = (x * 73 + y * 151 + x * y * 13 + layer_index * 31) % 173 == 0;
if layer_index == 0 || star {
tiles[y * STRESS_SCENE_TILE_W + x] = Tile {
active: true,
glyph: Glyph { glyph_id: 0, palette_id: layer_index as u8 + 1 },
flip_x: false,
flip_y: false,
glyph: Glyph {
glyph_id: if layer_index == 0 { 3 } else { 1 },
palette_id: layer_index as u8,
},
flip_x: (x + y) % 2 == 0,
flip_y: (x + y) % 3 == 0,
};
}
}
@@ -367,14 +259,6 @@ fn build_scene_bank() -> SceneBank {
}
});
// Keep the farthest layer a bit sparser so the diagonal remains visually readable.
for step in 0..12 {
let x = 10 + step * 7;
let y = 4 + step * 3;
let index = y * STRESS_SCENE_TILE_W + x;
layers[3].tilemap.tiles[index].active = false;
}
SceneBank { layers }
}
@@ -433,7 +317,7 @@ mod tests {
use super::*;
#[test]
fn assets_pack_contains_preloaded_glyph_and_scene_assets() {
fn assets_pack_contains_preloaded_glyph_scene_and_music_assets() {
let bytes = build_assets_pack().expect("assets pack");
let prelude =
AssetsPackPrelude::from_bytes(&bytes[..ASSETS_PA_PRELUDE_SIZE]).expect("prelude");
@@ -445,23 +329,32 @@ mod tests {
let header: AssetsPackHeader =
serde_json::from_slice(&bytes[header_start..header_end]).expect("header");
assert_eq!(header.asset_table.len(), 2);
assert_eq!(header.preload.len(), 2);
assert_eq!(header.asset_table.len(), 3);
assert_eq!(header.preload.len(), 3);
assert_eq!(header.asset_table[0].asset_id, STRESS_GLYPH_ASSET_ID);
assert_eq!(header.asset_table[1].asset_id, STRESS_SCENE_ASSET_ID);
assert_eq!(header.asset_table[2].asset_id, music::ASSET_ID);
assert_eq!(header.asset_table[0].bank_type, BankType::GLYPH);
assert_eq!(header.asset_table[1].bank_type, BankType::SCENE);
assert_eq!(header.asset_table[2].bank_type, BankType::MUSIC);
assert_eq!(header.preload[0].asset_id, STRESS_GLYPH_ASSET_ID);
assert_eq!(header.preload[1].asset_id, STRESS_SCENE_ASSET_ID);
assert_eq!(header.preload[2].asset_id, music::ASSET_ID);
assert_eq!(header.preload[0].slot, 0);
assert_eq!(header.preload[1].slot, 0);
assert_eq!(header.preload[2].slot, 0);
assert_eq!(header.asset_table[0].offset, 0);
assert_eq!(header.asset_table[1].offset, header.asset_table[0].size);
assert_eq!(
header.asset_table[2].offset,
header.asset_table[0].size + header.asset_table[1].size
);
assert_eq!(
bytes.len(),
prelude.payload_offset as usize
+ header.asset_table[0].size as usize
+ header.asset_table[1].size as usize
+ header.asset_table[2].size as usize
);
}
}
+21 -2
View File
@@ -1,5 +1,24 @@
use anyhow::Result;
use anyhow::{bail, Context, Result};
use pbxgen_stress::{Preset, DEFAULT_PRESET, DEFAULT_SEED};
use std::path::PathBuf;
fn main() -> Result<()> {
pbxgen_stress::generate()
let mut preset = DEFAULT_PRESET;
let mut seed = DEFAULT_SEED;
let mut output = None;
let mut args = std::env::args().skip(1);
while let Some(arg) = args.next() {
if arg == "--help" {
println!("pbxgen-stress [--preset light|normal|heavy] [--seed INT64] [--output DIR] (default: {})", DEFAULT_PRESET.name());
return Ok(());
}
let value = args.next().context("option requires a value")?;
match arg.as_str() {
"--preset" => preset = Preset::parse(&value).context("unknown preset")?,
"--seed" => seed = value.parse().context("seed must be Int64")?,
"--output" => output = Some(PathBuf::from(value)),
_ => bail!("unknown option {arg}"),
}
}
pbxgen_stress::generate_with(preset, seed, output)
}
+22
View File
@@ -0,0 +1,22 @@
use anyhow::Result;
use prometeu_hal::asset::{AssetCodec, AssetEntry, AssetId, BankType};
pub const ASSET_ID: AssetId = 201;
const MUSIC: &[u8] = include_bytes!("../music/storm-eagle.mbnk");
const METRICS: &str = include_str!("../music/bank-metrics.json");
/// Only the asset entry; AudioBankPacker owns MusicBank serialization and codecs.
pub fn asset(offset: u64) -> Result<(AssetEntry, &'static [u8])> {
let metrics: serde_json::Value = serde_json::from_str(METRICS)?;
let entry = AssetEntry {
asset_id: ASSET_ID,
asset_name: "storm_eagle".into(),
bank_type: BankType::MUSIC,
offset,
size: MUSIC.len() as u64,
decoded_size: metrics["decoded_size"].as_u64().expect("packer decoded_size"),
codec: AssetCodec::None,
metadata: serde_json::json!({"version": 1}),
};
Ok((entry, MUSIC))
}
@@ -0,0 +1,82 @@
use pbxgen_stress::{Preset, DEFAULT_SEED};
use prometeu_host_headless::{AdvanceFrameOutcome, HeadlessHost};
use std::path::PathBuf;
struct Cart(PathBuf);
impl Cart {
fn new(seed: i64) -> Self {
let unique =
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let path =
std::env::temp_dir().join(format!("prometeu-demo-{}-{unique}", std::process::id()));
pbxgen_stress::generate_with(Preset::Normal, seed, Some(path.clone())).unwrap();
Self(path)
}
fn boot(&self) -> HeadlessHost {
let mut h = HeadlessHost::new();
h.boot(self.0.to_string_lossy()).unwrap();
h
}
}
impl Drop for Cart {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn advance(h: &mut HeadlessHost) -> Vec<u32> {
assert!(matches!(h.advance_frame().unwrap(), AdvanceFrameOutcome::FrameCompleted { .. }));
assert!(h.get_fault().is_none());
h.capture_frame().unwrap().frame.pixels
}
fn hash(v: &[u32]) -> u64 {
v.iter().fold(14695981039346656037, |h, &p| (h ^ u64::from(p)).wrapping_mul(1099511628211))
}
#[test]
fn native_visual_replay_seed_and_pause_resume() {
let cart = Cart::new(DEFAULT_SEED);
let other = Cart::new(DEFAULT_SEED + 1);
let mut a = cart.boot();
let mut b = cart.boot();
let mut changed = other.boot();
let mut last = vec![];
let mut hashes = vec![];
for frame in 0..6 {
let actual = advance(&mut a);
let expected = advance(&mut b);
assert_eq!(actual, expected);
assert_ne!(actual, last);
hashes.push(hash(&actual));
if frame == 0 {
assert_ne!(actual, advance(&mut changed));
}
// Explicit pause freezes audio and does not alter the displayed guest state.
a.resume().unwrap();
a.pause().unwrap();
let before = a.audio_diagnostics().frames;
let mut silence = [1.0; 1600];
a.render_audio(&mut silence);
assert_eq!(silence, [0.0; 1600]);
assert_eq!(a.audio_diagnostics().frames, before);
assert_eq!(a.capture_frame().unwrap().frame.pixels, actual);
a.resume().unwrap();
b.resume().unwrap();
let mut left = [0.0; 1600];
let mut right = [0.0; 1600];
a.render_audio(&mut left);
b.render_audio(&mut right);
assert_eq!(left, right);
last = actual;
}
assert!(a.audio_diagnostics().maximum_voices > 0);
println!("visual_hashes={hashes:?}");
assert_eq!(
hashes,
[
509059057377717011,
11639740206223880472,
10144685766373560685,
12298401095609708800,
8400916329250932746,
12687665705214954737
]
);
}
@@ -0,0 +1,200 @@
use prometeu_drivers::bank_format::{decode_audio_bank, DecodedAudioBank};
use prometeu_host_headless::{AdvanceFrameOutcome, HeadlessHost};
use std::path::PathBuf;
struct Cartridge(PathBuf);
impl Cartridge {
fn new() -> Self {
let unique =
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let path = std::env::temp_dir()
.join(format!("stress-console-music-{}-{unique}", std::process::id()));
std::fs::create_dir_all(&path).unwrap();
std::fs::write(path.join("program.pbx"), pbxgen_stress::build_program()).unwrap();
std::fs::write(path.join("manifest.json"), pbxgen_stress::manifest_json()).unwrap();
std::fs::write(path.join("assets.pa"), pbxgen_stress::build_assets_pack().unwrap())
.unwrap();
Self(path)
}
fn boot(&self) -> HeadlessHost {
let mut host = HeadlessHost::new();
host.boot(self.0.to_string_lossy()).unwrap();
assert!(matches!(
host.advance_frame().unwrap(),
AdvanceFrameOutcome::FrameCompleted { .. }
));
host.resume().unwrap();
host
}
}
impl Drop for Cartridge {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
fn bank_preserves_transcription_and_mixed_samples() {
let bytes = include_bytes!("../music/storm-eagle.mbnk");
let decoded =
decode_audio_bank(bytes, true).expect("packer bank must load in the real decoder");
let metrics: serde_json::Value =
serde_json::from_str(include_str!("../music/bank-metrics.json")).unwrap();
assert_eq!(decoded.decoded_size() as u64, metrics["decoded_size"].as_u64().unwrap());
let DecodedAudioBank::Music(bank) = decoded else { panic!("expected music") };
assert_eq!(bank.samples.len(), 8);
assert_eq!(bank.instruments.len(), 8);
let manifest: serde_json::Value =
serde_json::from_str(include_str!("../music/song.json")).unwrap();
let lead: Vec<_> = manifest["events"]
.as_array()
.unwrap()
.iter()
.filter(|e| e["kind"] == 1 && e["track"] == 0)
.collect();
assert_eq!(lead.len(), 90);
let first_pitches: Vec<_> = lead.iter().take(8).map(|e| e["c"].as_u64().unwrap()).collect();
assert_eq!(first_pitches, [71, 70, 71, 73, 74, 73, 71, 78]);
assert_eq!(lead[4]["tick"], 3840);
assert_eq!(lead[5]["tick"], 4160);
assert_eq!(lead[6]["tick"], 4480);
assert_eq!(manifest["duration_ticks"], 69120);
let mapping: serde_json::Value =
serde_json::from_str(include_str!("../music/instrument-mapping.json")).unwrap();
assert_eq!(mapping["voicings"].as_array().unwrap().len(), 20);
assert_eq!(mapping["voicings"][4]["target_tones"], serde_json::json!([58, 61, 66]));
let samples_at = 48 + u32::from_le_bytes(bytes[40..44].try_into().unwrap()) as usize;
let codecs: Vec<_> = (0..8).map(|i| bytes[samples_at + i * 40]).collect();
assert!(codecs.contains(&0) && codecs.contains(&1));
}
#[test]
fn tracked_cartridge_is_the_exact_generator_output() {
let root =
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../test-cartridges/stress-console");
assert_eq!(std::fs::read(root.join("program.pbx")).unwrap(), pbxgen_stress::build_program());
assert_eq!(std::fs::read(root.join("manifest.json")).unwrap(), pbxgen_stress::manifest_json());
assert_eq!(
std::fs::read(root.join("assets.pa")).unwrap(),
pbxgen_stress::build_assets_pack().unwrap()
);
}
#[test]
fn guest_preloads_music_and_renders_audio() {
let cartridge = Cartridge::new();
let mut host = cartridge.boot();
let mut output = [0.0; 9600];
host.render_audio(&mut output);
assert!(output.iter().any(|x| x.abs() > 0.001));
assert!(host.audio_diagnostics().maximum_voices > 0);
assert_eq!(host.audio_diagnostics().frames, 4800);
}
fn render_sequence(
mut host: HeadlessHost,
frames: usize,
graphics_and_pause: bool,
) -> (Vec<f32>, prometeu_drivers::engine::AudioDiagnostics, usize) {
let mut output = vec![0.0; frames * 2];
let mut graphics_frames = 0;
for (index, buffer) in output.chunks_mut(1600).enumerate() {
if graphics_and_pause {
// Exercise the heavy workload at bounded checkpoints across both loops.
// This is a sequencing regression test, not a 60 FPS performance run.
if index < 6 || index % 120 == 0 || [60, 1543, 3086].contains(&index) {
assert!(matches!(
host.advance_frame().unwrap(),
AdvanceFrameOutcome::FrameCompleted { .. }
));
graphics_frames += 1;
host.resume().unwrap();
}
if index == 60 {
let before = host.audio_diagnostics().frames;
host.pause().unwrap();
let mut silence = [1.0; 2048];
host.render_audio(&mut silence);
assert_eq!(silence, [0.0; 2048]);
assert_eq!(host.audio_diagnostics().frames, before);
host.resume().unwrap();
}
}
host.render_audio(buffer);
}
let diagnostics = host.audio_diagnostics();
assert_eq!(diagnostics.frames, frames as u64);
(output, diagnostics, graphics_frames)
}
fn write_wav(path: &std::path::Path, pcm: &[f32]) {
use std::io::Write;
let mut file = std::fs::File::create(path).unwrap();
let byte_count = u32::try_from(pcm.len() * 2).unwrap();
file.write_all(b"RIFF").unwrap();
file.write_all(&(36 + byte_count).to_le_bytes()).unwrap();
file.write_all(b"WAVEfmt \x10\0\0\0\x01\0\x02\0").unwrap();
file.write_all(&48_000_u32.to_le_bytes()).unwrap();
file.write_all(&192_000_u32.to_le_bytes()).unwrap();
file.write_all(&4_u16.to_le_bytes()).unwrap();
file.write_all(&16_u16.to_le_bytes()).unwrap();
file.write_all(b"data").unwrap();
file.write_all(&byte_count.to_le_bytes()).unwrap();
let mut bytes = Vec::with_capacity(pcm.len() * 2);
for value in pcm {
bytes.extend_from_slice(&((value.clamp(-1.0, 1.0) * 32767.0).round() as i16).to_le_bytes());
}
file.write_all(&bytes).unwrap();
}
#[test]
fn full_sequence_loops_and_frame_controls_preserve_audio() {
let cartridge = Cartridge::new();
let one_loop_numerator = 48_000_u64 * 72 * 357_143;
let first_loop = one_loop_numerator.div_ceil(1_000_000) as usize;
let frames = (one_loop_numerator * 2).div_ceil(1_000_000) as usize + 48_000;
let (reference, diagnostics, _) = render_sequence(cartridge.boot(), frames, false);
let (with_frames, _, graphics_frames) = render_sequence(cartridge.boot(), frames, true);
assert!(graphics_frames >= 30);
assert_eq!(
reference, with_frames,
"graphics and explicit pause/resume must not change a single PCM sample"
);
assert!((6..=12).contains(&diagnostics.maximum_voices));
let peak = reference.iter().map(|x| x.abs()).fold(0.0_f32, f32::max);
let energy: f64 = reference.iter().map(|x| f64::from(*x).powi(2)).sum();
let rms = (energy / reference.len() as f64).sqrt();
let clipped = reference.iter().filter(|x| x.abs() >= 1.0).count();
let stereo_difference: f64 =
reference.as_chunks::<2>().0.iter().map(|lr| f64::from(lr[0] - lr[1]).powi(2)).sum();
// Loop onset should reproduce the opening. A subframe remainder and the shared
// echo tail may differ, so compare relative signal energy rather than bit identity.
let mut loop_error = 0.0;
let mut opening_energy = 0.0;
for i in 400..4000 {
loop_error += f64::from(reference[i] - reference[first_loop * 2 + i]).powi(2);
opening_energy += f64::from(reference[i]).powi(2);
}
let loop_error_ratio = loop_error / opening_energy;
let report = serde_json::json!({
"sample_rate": 48000, "channels": 2, "audio_frames": frames,
"seconds": frames as f64 / 48000.0, "first_loop_frame": first_loop,
"maximum_voices": diagnostics.maximum_voices, "peak": peak,
"rms": rms, "clipped_samples": clipped,
"loop_onset_relative_error": loop_error_ratio,
"graphics_pause_pcm_identical": true,
"interleaved_graphics_frames": graphics_frames,
});
println!("stress_music={report}");
if let Some(path) = std::env::var_os("PROMETEU_STRESS_WAV") {
write_wav(std::path::Path::new(&path), &reference);
}
assert!(reference.iter().all(|x| x.is_finite()));
assert!(rms > 0.005 && stereo_difference > 0.01);
assert_eq!(clipped, 0, "adjust arrangement gain rather than delivering clipped audio");
assert!(
loop_error_ratio < 0.04,
"loop did not reproduce the musical opening: {loop_error_ratio}"
);
}
@@ -0,0 +1,127 @@
#![allow(dead_code)]
use prometeu_bytecode::{load_limits::LoadBudget, Value};
use prometeu_drivers::SpriteController;
use prometeu_hal::{
glyph::Glyph,
sprite::Sprite,
syscalls::{caps, Syscall},
ComposerOpStatus, HostContext, HostReturn, NativeInterface,
};
use prometeu_vm::{LogicalFrameEndingReason as End, ValidatedProgramImage, VirtualMachine};
#[derive(Default)]
pub struct Workload {
pub sprites: SpriteController,
pub submitted: usize,
pub binds: usize,
pub camera: usize,
pub text: usize,
pub logs: usize,
pub plays: usize,
pub errors: usize,
pub reject_first_sprite: bool,
pub sprite_hash: u64,
}
impl NativeInterface for Workload {
fn syscall(
&mut self,
id: u32,
args: &[Value],
out: &mut HostReturn,
_: &mut HostContext,
) -> Result<(), prometeu_hal::vm_fault::VmFault> {
let op = Syscall::from_u32(id).unwrap();
let int = |i: usize| match args[i] {
Value::Int32(x) => i64::from(x),
Value::Int64(x) => x,
_ => panic!("integer argument {i}"),
};
let boolean = |i: usize| match args[i] {
Value::Boolean(b) => b,
_ => panic!("bool argument {i}"),
};
let mut status = ComposerOpStatus::Ok as i64;
match op {
Syscall::ComposerBindScene => self.binds += 1,
Syscall::ComposerSetCamera => self.camera += 1,
Syscall::GfxDrawText => self.text += 1,
Syscall::GfxFillRect => {}
Syscall::LogWrite => {
self.logs += 1;
if int(0) == 3 {
self.errors += 1;
}
}
Syscall::MusicPlay => self.plays += 1,
Syscall::MusicSetVolume | Syscall::AudioSetEffect => {}
Syscall::ComposerEmitSprite => {
self.submitted += 1;
for i in 0..6 {
self.sprite_hash =
(self.sprite_hash ^ int(i) as u64).wrapping_mul(1099511628211);
}
let sprite = Sprite {
glyph: Glyph { glyph_id: int(0) as u16, palette_id: int(1) as u8 },
x: int(2) as i32,
y: int(3) as i32,
layer: int(4) as u8,
bank_id: int(5) as u8,
active: false,
flip_x: boolean(6),
flip_y: boolean(7),
priority: int(8) as u8,
};
if !self.sprites.emit_sprite(sprite)
|| (self.reject_first_sprite && self.submitted == 1)
{
status = ComposerOpStatus::SpriteOverflow as i64;
}
}
_ => panic!("unexpected {op:?}"),
}
for _ in 0..op.results_count() {
out.push_int(status);
}
Ok(())
}
}
pub fn vm(preset: pbxgen_stress::Preset, seed: i64) -> VirtualMachine {
let bytes = pbxgen_stress::build_program_with(preset, seed);
let image =
ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(Default::default()), caps::ALL)
.unwrap();
VirtualMachine::from_image(image, Default::default())
}
pub fn frame(vm: &mut VirtualMachine, native: &mut Workload) -> u64 {
native.sprites.begin_frame();
vm.prepare_boot_call().unwrap();
let mut cycles = 0;
for _ in 0..100 {
let r = vm.run_budget(250_000, native, &mut HostContext::new(None)).unwrap();
cycles += r.cycles_used;
match r.reason {
End::EndOfRom => return cycles,
End::BudgetExhausted => {}
reason => panic!("{reason:?}"),
}
}
panic!("unbounded frame")
}
pub fn particle_bits(vm: &VirtualMachine) -> Vec<u64> {
use prometeu_vm::resource_diagnostics::StorageValue;
vm.heap()
.diagnostic_typed_storage()
.iter()
.filter(|o| o.type_id.0 == 4)
.flat_map(|o| o.groups.iter())
.flat_map(|g| g.iter())
.map(|v| match v {
StorageValue::FloatBits(x) => *x,
StorageValue::Int32(x) => *x as u64,
_ => panic!("particle type"),
})
.collect()
}
pub fn hash(values: &[u64]) -> u64 {
values.iter().fold(14695981039346656037, |h, x| (h ^ x).wrapping_mul(1099511628211))
}
@@ -0,0 +1,198 @@
mod support;
use pbxgen_stress::{Preset, DEFAULT_SEED};
use support::*;
#[test]
fn presets_replay_native_state_without_churn_or_sprite_overflow() {
for preset in [Preset::Light, Preset::Normal, Preset::Heavy] {
let mut a = vm(preset, DEFAULT_SEED);
let mut b = vm(preset, DEFAULT_SEED);
let mut other = vm(preset, DEFAULT_SEED + 1);
let mut na = Workload::default();
let mut nb = Workload::default();
let mut no = Workload::default();
let mut previous = vec![];
for f in 1..=6 {
let cycles = frame(&mut a, &mut na);
assert_eq!(cycles, frame(&mut b, &mut nb));
frame(&mut other, &mut no);
let state = particle_bits(&a);
assert_eq!(state, particle_bits(&b));
assert_ne!(state, particle_bits(&other));
assert_ne!(state, previous);
previous = state;
assert_eq!(previous.len(), preset.particles() as usize * 6);
assert_eq!(a.heap().len(), preset.particles() as usize + 2);
assert_eq!(na.submitted, f * (preset.particles() as usize + 128));
assert_eq!(na.sprites.sprite_count(), preset.particles() as usize + 128);
assert_eq!(na.sprites.dropped_sprites(), 0);
assert_eq!(na.errors, 0);
}
assert_eq!(na.binds, 1);
assert_eq!(na.plays, 1);
assert_eq!(na.camera, 6);
assert_eq!(na.text, 24);
let expected = match preset {
Preset::Light => 0xa0277985ff4cefcd,
Preset::Normal => 0x3a9cf871667c92ee,
Preset::Heavy => 0x57257956419e88d2,
};
assert_eq!(hash(&previous), expected, "guest numeric replay changed");
println!("replay={} hash={:016x}", preset.name(), hash(&previous));
}
}
#[test]
fn actual_intrinsic_execution_and_particle_rebirth() {
use prometeu_bytecode::{
decode_next, isa::core::CoreOpCode, load_limits::LoadBudget, registry_codec::PbxEnvelope,
};
use prometeu_hal::HostContext;
use prometeu_vm::LogicalFrameEndingReason as End;
use std::collections::BTreeMap;
let bytes = pbxgen_stress::build_program_with(Preset::Light, 42);
let mut budget = LoadBudget::new(Default::default());
let envelope = PbxEnvelope::parse(&bytes, &mut budget).unwrap();
let section = envelope.section(2).unwrap();
let code = section.bytes;
let mut sites = BTreeMap::new();
let mut pc = 0;
while pc < code.len() {
let i = decode_next(pc, code).unwrap();
if i.opcode == CoreOpCode::Intrinsic {
sites.insert(pc, i.imm_u32().unwrap());
}
pc = i.next_pc;
}
let mut v = vm(Preset::Light, 42);
for &pc in sites.keys() {
v.insert_breakpoint(pc);
}
let mut n = Workload::default();
v.prepare_boot_call().unwrap();
let mut calls = BTreeMap::<u32, usize>::new();
loop {
if let Some(&id) = sites.get(&v.pc()) {
*calls.entry(id).or_default() += 1;
v.step(&mut n, &mut HostContext::new(None)).unwrap();
continue;
}
let r = v.run_budget(250_000, &mut n, &mut HostContext::new(None)).unwrap();
match r.reason {
End::Breakpoint | End::BudgetExhausted => {}
End::EndOfRom => break,
x => panic!("{x:?}"),
}
}
println!("executed_intrinsic_calls={calls:?}");
for (owner, name, min) in [
("random", "new", 1),
("random", "nextf", 256),
("random", "range", 64),
("random", "next", 64),
("mathf", "sin", 192),
("mathf", "cos", 192),
("mathf", "atan2", 64),
("mathf", "sqrt", 64),
("mathf", "clamp", 256),
("vec2", "dot", 64),
("vec2", "length", 64),
] {
let id = prometeu_vm::lookup_intrinsic(owner, name, 1).unwrap().id;
assert!(calls.get(&id).copied().unwrap_or(0) >= min, "{owner}.{name}: {calls:?}");
}
for pc in sites.keys() {
v.remove_breakpoint(*pc);
}
// Every initial lifetime is <225 frames: all particles must eventually be reborn.
for _ in 1..230 {
frame(&mut v, &mut n);
}
let lifetimes: Vec<_> = particle_bits(&v).as_chunks::<6>().0.iter().map(|s| s[4]).collect();
assert!(lifetimes.iter().all(|&life| (1..225).contains(&life)));
assert_eq!(v.heap().len(), 66);
assert_eq!(n.plays, 1);
assert_eq!(n.errors, 0);
}
#[test]
fn sprite_overflow_is_a_separate_bounded_controller_case() {
let mut n = Workload::default();
let mut v = vm(Preset::Heavy, 42);
frame(&mut v, &mut n);
let sprite = prometeu_hal::sprite::Sprite {
glyph: prometeu_hal::glyph::Glyph { glyph_id: 0, palette_id: 8 },
x: 0,
y: 0,
layer: 3,
bank_id: 0,
active: false,
flip_x: false,
flip_y: false,
priority: 3,
};
for _ in n.sprites.sprite_count()..512 {
assert!(n.sprites.emit_sprite(sprite));
}
assert!(!n.sprites.emit_sprite(sprite));
assert_eq!(n.sprites.sprite_count(), 512);
assert_eq!(n.sprites.dropped_sprites(), 1);
}
#[test]
fn guest_reports_a_failed_submission_instead_of_discarding_status() {
let mut v = vm(Preset::Light, 42);
let mut n = Workload { reject_first_sprite: true, ..Default::default() };
frame(&mut v, &mut n);
assert_eq!(n.errors, 1);
frame(&mut v, &mut n);
assert_eq!(n.errors, 1, "frame status must reset after the failed frame");
}
#[test]
fn faster_travel_changes_actual_guest_positions() {
use prometeu_bytecode::{
decode_next, isa::core::CoreOpCode, load_limits::LoadBudget, registry_codec::PbxEnvelope,
};
use prometeu_hal::HostContext;
use prometeu_vm::LogicalFrameEndingReason as End;
let bytes = pbxgen_stress::build_program_with(Preset::Light, DEFAULT_SEED);
let mut budget = LoadBudget::new(Default::default());
let envelope = PbxEnvelope::parse(&bytes, &mut budget).unwrap();
let code = envelope.section(2).unwrap().bytes;
let mut pc = 0;
let before_update = loop {
let op = decode_next(pc, code).unwrap();
if op.opcode == CoreOpCode::Hostcall && op.imm_u32().unwrap() == 2 {
break pc;
}
pc = op.next_pc;
};
let mut v = vm(Preset::Light, DEFAULT_SEED);
let mut n = Workload::default();
v.insert_breakpoint(before_update);
v.prepare_boot_call().unwrap();
assert_eq!(
v.run_budget(1_000_000, &mut n, &mut HostContext::new(None)).unwrap().reason,
End::Breakpoint
);
let initial = particle_bits(&v);
v.remove_breakpoint(before_update);
assert_eq!(
v.run_budget(1_000_000, &mut n, &mut HostContext::new(None)).unwrap().reason,
End::EndOfRom
);
let updated = particle_bits(&v);
assert_eq!(initial.len(), updated.len());
for (before, after) in initial.as_chunks::<6>().0.iter().zip(updated.as_chunks::<6>().0) {
for (position, velocity) in [(0, 2), (1, 3)] {
let old = f64::from_bits(before[position]);
let speed = f64::from_bits(after[velocity]);
let actual = f64::from_bits(after[position]);
assert!(
(actual - (old + 1.5 * speed)).abs() < 1e-10,
"light preset has one pass: position must advance by 1.5 times velocity"
);
}
}
}
@@ -0,0 +1,27 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Map;
import p.packer.services.AudioBankPacker;
/** Fixture adapter only: the existing packer owns validation, codecs and serialization. */
class PackMusic {
public static void main(String[] args) throws Exception {
Path root = Path.of(args[0]).toAbsolutePath();
ObjectMapper mapper = new ObjectMapper();
var packed = AudioBankPacker.pack(root, root.resolve("song.json"), true, mapper);
var repeated = AudioBankPacker.pack(root, root.resolve("song.json"), true, mapper);
if (!Arrays.equals(packed.payload(), repeated.payload()) || packed.decodedSize() != repeated.decodedSize()) {
throw new IllegalStateException("Audio packer output changed for identical input");
}
Files.write(root.resolve("storm-eagle.mbnk"), packed.payload());
Files.write(root.resolve("bank-metrics.json"), mapper.writerWithDefaultPrettyPrinter()
.writeValueAsBytes(Map.of("cartridge_bytes", packed.payload().length,
"decoded_size", packed.decodedSize(),
"pcm_bytes", packed.pcmBytes(),
"version", 1)));
System.out.println("MusicBank: " + packed.payload().length + " cartridge bytes, "
+ packed.pcmBytes() + " PCM bytes, " + packed.decodedSize() + " decoded bytes");
}
}
@@ -0,0 +1,170 @@
#!/usr/bin/env python3
"""Build this fixture's authoring manifest. AudioBankPacker serializes the bank."""
import hashlib
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1] / 'music'
PPQ = 960
TEMPO = 357143 # nearest integer microseconds/quarter to 168 BPM
MINOR = [0, 2, 3, 5, 7, 8, 10]
MAJOR = [0, 2, 4, 5, 7, 9, 11]
def write_json(name, value):
(ROOT / name).write_text(json.dumps(value, indent=2) + '\n')
def degree(sd, octave):
accidental = sd.count('#') - sd.count('b')
return 71 + MINOR[int(sd[-1]) - 1] + accidental + octave * 12
def chord_notes(chord):
scale = MAJOR if chord['borrowed'] == 'major' else MINOR
first = chord['root'] - 1
notes = [47 + scale[(first + step) % 7] + 12 * ((first + step) // 7)
for step in range(0, 6 if chord['type'] == 5 else 8, 2)]
for _ in range(chord['inversion']):
notes.append(notes.pop(0) + 12)
return notes
def main():
source = json.loads((ROOT / 'transcription.json').read_text())
sf = json.loads((ROOT / 'soundfont-source.json').read_text())
assert len(source['notes']) == 90 and len(source['chords']) == 20
assert source['source_ppq_inferred_from_paired_beat_tick_fields'] == 480
duration = source['source_duration_ticks'] * 2
assert duration == 72 * PPQ
samples = []
for sample in sf['samples']:
samples.append({'file': sample['file'], 'codec': 'PCM16_LE'})
# Samples retain their original rate and PCM. Only cartridge encoding changes.
for i in [3, 4, 5, 7]:
samples[i]['codec'] = 'IMA_ADPCM_WAV4'
for i in [0, 1, 2, 6]:
start, end = sf['samples'][i]['validated_loop_frames']
samples[i].update(loop_start=start, loop_end=end)
instruments = []
mapping = []
def instrument(identifier, sample_index, *, root=None, gain=128, pan=128,
attack=2, decay=0, sustain=65535, release=12, looping=False,
vibrato=0, send=0, preset=None, articulation=''):
sample = sf['samples'][sample_index]
raw = sf['instruments'][preset] if preset is not None else None
inst = dict(id=identifier, sample=sample_index, low=0, high=127,
root=sample['root_note_midi'] if root is None else root,
tuning_cents=sample['pitch_correction_cents'], gain=gain, pan=pan,
attack_ms=attack, decay_ms=decay, sustain=sustain,
release_ms=release, looping=looping, curve=1,
vibrato_millihz=5000 if vibrato else 0,
vibrato_cents=vibrato, send=send)
instruments.append(inst)
mapping.append({'instrument_id': identifier, 'sample_name': sample['name'],
'source_sample_id': sample['sample_id'],
'source_file_pcm_sha256': sample['pcm_sha256'],
'source_instrument': raw, 'target': inst,
'arrangement_articulation': articulation})
instrument(0, 0, gain=180, release=9, looping=True, vibrato=15, send=6500, preset=0,
articulation='Lead: source root/rate/correction and 5 Hz/15-cent LFO; clamp invalid negative SF2 sustain attenuation to zero; 2 ms attack/9 ms release prevent clicks. Mod-envelope/delay stages are not emulated.')
instrument(1, 2, gain=95, release=8, looping=True, preset=2,
articulation='Bass: source root/rate and loop; replace source hold/modulation envelope with short articulated eighth notes and 2 ms attack/8 ms release.')
instrument(2, 1, gain=52, release=8, looping=True, preset=1,
articulation='Rhythm: source root/rate/loop/correction. Gain is a musical mix trim; no SF2 mod-envelope/delayed LFO. Three/four chord tones retain harmony and inversion.')
instrument(3, 3, root=36, gain=165, attack=0, release=4, preset=3,
articulation='Kick: Drum Kit root override 36; one-shot PCM envelope, no loop.')
instrument(4, 4, root=38, gain=115, attack=0, release=6, preset=3,
articulation='Heavy snare: Drum Kit root override 38; one-shot, no loop.')
instrument(5, 5, root=42, gain=52, pan=178, attack=0, release=4, preset=3,
articulation='Closed hi-hat: Drum Kit root override 42; one-shot, explicit short note-off; no source hold stage.')
instrument(6, 6, root=49, gain=65, pan=70, attack=0, decay=900,
sustain=0, release=90, looping=True, preset=3,
articulation='Crash: Drum Kit root override 49 and source loop; 900 ms exponential decay replaces SF2 hold/decay for this arrangement.')
instrument(7, 7, root=41, gain=105, pan=90, attack=0, release=6, preset=3,
articulation='Tom: Drum Kit root override 41; one-shot, fill notes select pitch.')
events = []
note_id = 0
def note(tick, length, track, inst, pitch, velocity):
nonlocal note_id
note_id += 1
end = min(duration - 1, tick + length)
assert 0 <= tick < end < duration
events.append(dict(tick=tick, kind=1, track=track, a=note_id, b=inst, c=pitch, d=velocity))
events.append(dict(tick=end, kind=2, track=track, a=note_id))
for n in source['notes']:
note(n['startTick'] * 2, n['durationTicks'] * 2, 0, 0,
degree(n['sd'], n['octave']), 235)
voicings = []
for chord in source['chords']:
start, length = chord['startTick'] * 2, chord['durationTicks'] * 2
tones = chord_notes(chord)
bass = tones[0]
while bass >= 47:
bass -= 12
while min(tones) < 54:
tones = [n + 12 for n in tones]
voicings.append(dict(source=chord, target_tones=tones, bass=bass))
# Each chord keeps its authored harmony; repeated stabs add rock articulation.
for beat in range(0, length, PPQ * 4):
for offset in [0, PPQ, PPQ * 3 // 2, PPQ * 5 // 2, PPQ * 3]:
tick = start + beat + offset
if tick >= start + length:
continue
for voice, pitch in enumerate(tones):
note(tick, min(PPQ * 2 // 5, start + length - tick),
2 + voice, 2, pitch, 180 if offset == 0 else 145)
for offset in range(0, length, PPQ // 2):
pitch = bass + (12 if offset % (PPQ * 4) == PPQ * 5 // 2 else 0)
note(start + offset, PPQ * 2 // 5, 1, 1, pitch, 215 if offset % PPQ == 0 else 190)
for bar in range(18):
at = bar * PPQ * 4
for eighth in range(8):
note(at + eighth * PPQ // 2, PPQ // 5, 8, 5, 42,
190 if eighth % 2 == 0 else 135)
for offset in [0, PPQ * 3 // 2, PPQ * 2, PPQ * 7 // 2]:
note(at + offset, PPQ // 2, 6, 3, 36, 235)
for offset in [PPQ, PPQ * 3]:
note(at + offset, PPQ * 3 // 4, 7, 4, 38, 235)
if bar in [0, 4, 8, 12, 16]:
note(at, PPQ * 2, 9, 6, 49, 200)
if bar in [3, 7, 11, 15, 17]:
for i in range(3):
note(at + PPQ * 3 + i * PPQ // 3, PPQ // 3, 10, 7, 45 - i * 2, 180 + 15 * i)
# Stereo placement is shared by each logical track, including four-tone sevenths.
for track, pan in [(2, 52), (3, 100), (4, 192), (5, 214)]:
events.append(dict(tick=0, kind=5, track=track, c=pan))
# Stable ties: note-off precedes note-on at the same tick, so repeated notes release correctly.
events.sort(key=lambda e: (e['tick'], 0 if e['kind'] == 2 else 1))
manifest = dict(name='Storm Eagle — Stress Console arrangement', ppq=PPQ,
tempo_us_per_quarter=TEMPO, duration_ticks=duration,
loop_start_tick=0, track_count=11, samples=samples,
instruments=instruments, events=events)
write_json('song.json', manifest)
write_json('instrument-mapping.json', {
'source': 'User-supplied MegaManX-SF-3.0.sf2 by CliffyJiffy (SF2 INFO)',
'source_sha256': sf['source_sf2_sha256'], 'instruments': mapping,
'conversion': 'Source root, sample rate, pitch correction, selected Drum Kit overrides and loop bounds retained. The sign of pitch correction adds to playback cents. Gains, ADSR and articulation are explicit arrangement choices. This is not a complete SF2 conversion.',
'pitch_reference': 'https://github.com/FluidSynth/fluidsynth/blob/master/src/synth/fluid_voice.c (root key minus sample pitch correction)',
'gain_and_envelope': 'SF2 has modulation/hold stages unavailable in this machine and negative sustain attenuation on melodic patches. Retain raw generators in soundfont-source.json; use declared target ADSR/mix trims rather than emulating unsupported stages.',
'voicings': voicings, 'tempo_bpm_requested': source['bpm'],
'tempo_microseconds_per_quarter': TEMPO,
'actual_bpm': 60_000_000 / TEMPO,
'loop_seconds': duration * TEMPO / (PPQ * 1_000_000),
'source_melody_notes': len(source['notes']), 'source_chords': len(source['chords']),
'total_note_ons': note_id,
'authoring_sha256': hashlib.sha256((ROOT / 'song.json').read_bytes()).hexdigest(),
})
print(f'Prepared {note_id} notes, {len(events)} events, {len(samples)} samples; {duration} ticks')
if __name__ == '__main__':
main()
@@ -0,0 +1,11 @@
// A fixture task injected through -I; no Studio build/source changes.
gradle.projectsEvaluated {
def packer = gradle.rootProject.findProject(':prometeu-packer:prometeu-packer-v1')
if (packer == null) return // The init script also observes buildSrc.
packer.tasks.register('stressAudioClasspath') {
dependsOn packer.tasks.named('classes')
doLast {
println 'STRESS_CLASSPATH=' + packer.sourceSets.main.runtimeClasspath.asPath
}
}
}
@@ -0,0 +1,32 @@
#!/usr/bin/env python3
"""Regenerate the fixture through the repository's existing Java audio packer."""
import argparse
import subprocess
import sys
from pathlib import Path
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--studio', type=Path, help='Studio checkout (defaults to sibling checkout)')
args = parser.parse_args()
tool = Path(__file__).resolve().parent
runtime = tool.parents[3]
studio = (args.studio or runtime.parent / 'studio').resolve()
subprocess.run([sys.executable, str(tool / 'arrange_music.py')], check=True)
result = subprocess.run([
str(studio / 'gradlew'), '-I', str(tool / 'packer-classpath.gradle'),
':prometeu-packer:prometeu-packer-v1:stressAudioClasspath',
'--quiet', '--console=plain', '--no-daemon'],
cwd=studio, capture_output=True, text=True)
if result.returncode:
sys.stderr.write(result.stdout + result.stderr)
result.check_returncode()
classpath = next(line.split('=', 1)[1] for line in result.stdout.splitlines()
if line.startswith('STRESS_CLASSPATH='))
subprocess.run(['java', '--class-path', classpath, str(tool / 'PackMusic.java'),
str(tool.parent / 'music')], check=True)
if __name__ == '__main__':
main()
+11 -4
View File
@@ -1,11 +1,18 @@
# Dummy Boy
Regenerate this cartridge with:
Dummy Boy is a silent visual fixture. It clears the frame and draws a centered
square whose fill color cycles deterministically across frames. It requires only
the `gfx2d` capability and has no asset pack or audio commands.
From the runtime root:
```sh
cargo run -p pbxgen-dummy-boy
cargo run -p prometeu-host-desktop-winit -- test-cartridges/dummy-boy
cargo test -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.
Regeneration removes this fixture's obsolete `assets.pa` if present. The tests
check generator output, six visual frames and silent headless audio.
The musical workload lives in [Stress Console](../stress-console/README.md).
+140
View File
@@ -0,0 +1,140 @@
# Stress Console
Stress Console runs a procedural particle vortex and projected tunnel in guest
bytecode while a Storm Eagle arrangement plays on the independent audio clock.
It is an integration workload for the VM, numeric intrinsics, deterministic RNG,
typed state, compositor and sample-based sequencer.
From the runtime root:
```sh
cargo run -p pbxgen-stress
cargo run --release -p prometeu-host-desktop-winit -- test-cartridges/stress-console
cargo test -p pbxgen-stress -p pbxgen-dummy-boy
```
The tracked cartridge and generator default to the heavy preset and seed
`1347571533`. To generate another reproducible load without replacing it:
```sh
cargo run -p pbxgen-stress -- --preset normal --seed 42 --output /tmp/stress-normal
cargo run --release -p prometeu-host-desktop-winit -- /tmp/stress-normal
```
| Preset | Particles | Substeps per particle/frame | Accepted sprite submissions/frame |
| --- | ---: | ---: | ---: |
| light | 64 | 1 | 192 |
| normal | 128 | 2 | 256 |
| heavy (default) | 384 | 4 | 512 |
Preset selection happens when generating the cartridge; there is no switch during
playback.
These are workload settings, not new hardware limits. Every substep executes;
light/normal leave room within the existing 512 sprite slots; heavy fills all
512 slots. Positions outside the viewport are clipped normally, so accepted
submissions are not a count of visible objects. A separate test exercises overflow; the presentation checks
submission status and logs failures instead of deliberately overflowing.
## Guest algorithm and coverage
An array roots reusable Particle structs with x/y position, x/y velocity,
lifetime and palette. A separate rooted Random object supplies initial state
and particle rebirth. The live object count is particles + 2 and remains stable
while particles are reused. The RNG seed is explicit; there is no host entropy.
The softened vortex uses centre attraction, tangential acceleration, sine/cosine
perturbation and damping. Each substep calculates distance and angle, updates
clamped velocity, computes speed and advances clamped positions. Position travel
uses a 1.5 multiplier per simulation pass, so particles move faster while the
force clock, tunnel and music keep their own timing. Speed changes
the sprite shape. Lifetimes expire after 45..224 logical frames; rebirth uses
new random values in the existing struct. Increasing substeps increases real
numerical work, with a smaller integration step. Presets need not produce the
same trajectory as one another.
Eight rings of sixteen markers form a rotating, twisted tunnel. The guest
projects ring depth and angle onto the existing 2D compositor; there is no new
3D renderer. Four scene layers provide a dark backdrop and sparse star fields,
with parallax 1, 0.75, 0.5 and 0.25. Camera motion, transparent glow/star glyphs,
palettes, sprite priorities and four readable text overlays run together. Particles
and tunnel markers use sprites; stars/backdrop use scene tiles. Two `fill_rect`
commands and four `draw_text` calls draw the overlay with graphics primitives
and do not consume sprite slots.
| Surface | Executed workload / validation |
| --- | --- |
| Math | Float arithmetic; `mathf.sin/cos/atan2/sqrt/clamp/to_i32`, `vec2.dot/length`, integer clamp and explicit numeric conversions |
| Random | Native `random.new/next/nextf/range`; initialization and rebirth; same-seed replay and changed-seed divergence |
| Typed state | Guest array and struct references, typed field reads/writes, persistent roots, bounded reusable objects |
| VM | Nested loops, branches, globals/locals, virtual budget slices and native calls |
| Graphics | GlyphBank 100 and SceneBank 1 in slot 0 of each type; four layers, camera, palettes/alpha, tunnel and particle sprites, overlay |
| Logging | One level-2 message per 60 logical frames; level-3 report for failed composer submissions |
| Audio | MusicBank 201 in Music slot 0; Music A, eight instruments, envelopes/modulation, stereo pan and shared echo |
| Lifecycle | Initial setup and music play once per session; pause/resume and Stress/Home/Dummy/Home/Stress consumers |
The simulation uses a fixed logical-frame step of 1/60. It does not read wall
clock time. Music timing comes from audio processing, so slow graphics never
change sequence tempo. Exact beat synchronization of the visual is not claimed.
The generator emits PBX and static artwork; all particle simulation, RNG draws
and animated projection run inside the VM, including headless execution.
## Music and assets
The self-contained MusicBank holds a 72-beat B-minor arrangement, approximately
168 BPM (357143 integer microseconds per quarter), about 25.7 seconds per loop.
It uses the owner-supplied transcription and a subset of MegaManX-SF-3.0 samples
by CliffyJiffy. Bass, drums and articulation are arranged for the fixture; this
is not an exact reproduction of the original recording. Volume is 180; shared
echo uses 167 ms, feedback 0.22, wet 0.18 and dry 1.0.
PCM16 and IMA ADPCM samples share the bank on cartridge; loading materializes
resident PCM16. The bank occupies 90,810 cartridge bytes and materializes 60,358 PCM sample
bytes. Its canonical decoded size is 112,224 bytes, excluding host allocator
and ownership overhead. The complete tracked cartridge runs without Studio,
SoundFont software or downloaded source banks.
See the [audio sources and regeneration contract](../../crates/tools/pbxgen-stress/music/README.md)
for WAVs, authoring JSON, packer integration and optional rendered WAV export.
[Dummy Boy](../dummy-boy/README.md) remains a small silent visual fixture.
## Reproducible verification and measurements
```sh
cargo test -p pbxgen-stress --release -- --nocapture
cargo run -p pbxgen-stress --release --example demo_measure -- 120 /tmp/stress-measure
```
The measurement example writes `report.json`, three generated cartridges and a
native RGB PPM capture per preset. It reports initialization separately from
steady frames; mean, p50, p95 and maximum real times; virtual cycles separately;
sprite admission and host slices; state/frame hashes; VM quota usage/peaks; and audio voices.
Each steady headless frame also processes 800 stereo audio frames. The separate
native-only measurement uses the real VM and SpriteController while counting
other host calls. VM quota arrays follow RuntimeResource order: GuestBytes,
HandleSlots, AuxiliaryBytes, TemporaryBytes, StringBytes, StringAllocations,
IndividualStringBytes, CallDepth. They are not process RSS or total console RAM.
Tests inspect actual guest storage and observe executed intrinsic calls using
debugger breakpoints. Numeric replay hashes for all presets and six native visual frames of the
normal preset are pinned; debug/release runs compare the same baselines. A 230-frame run exercises
rebirth without growing the heap. Other tests compare more than two musical
loops sample-for-sample with and without representative graphics checkpoints,
including explicit pause/resume. Those checkpoints are not a sustained 60 FPS
benchmark.
The companion [measurement record](../../crates/tools/pbxgen-stress/examples/MEASUREMENTS.md)
reports one executed host configuration and its limitations.
## Limits
This demo does not qualify every intrinsic edge case, Random statistics, GC
under allocation churn, quota failures, input, save/memcard, dynamic bank
replacement, SFX, Music B, crossfade or all 32 audio voices. Those remain separate
subsystem tests/benchmarks. Storm Eagle peaks at approximately ten voices.
Headless timings include software composition and diagnostics. They do not
measure physical callback deadlines, GPU presentation, VSync, power or handheld
performance. No ARM handheld guarantee follows from a desktop run. The earlier
1152-request/512-admission grid has been replaced; it is no longer this cartridge's
normal workload.
Binary file not shown.
+1 -1
View File
@@ -5,5 +5,5 @@
"title": "Stress Console",
"app_version": "0.1.0",
"app_mode": "Game",
"capabilities": ["composer", "gfx2d", "log", "asset"]
"capabilities": ["composer", "gfx2d", "log", "asset", "audio"]
}
Binary file not shown.