clean up, debugger, add comments

This commit is contained in:
2026-03-24 13:40:20 +00:00
parent 28df72417b
commit 31080ea40d
60 changed files with 1033 additions and 557 deletions
+26 -1
View File
@@ -1,5 +1,5 @@
use serde::{Deserialize, Serialize};
use crate::model::AppMode;
use serde::{Deserialize, Serialize};
use crate::virtual_machine::Value;
@@ -80,6 +80,7 @@ pub enum DebugEvent {
vm_steps: u32,
syscalls: u32,
cycles: u64,
cycles_budget: u64,
host_cpu_time_us: u64,
violations: u32,
gfx_used_bytes: usize,
@@ -103,6 +104,30 @@ mod tests {
use super::*;
use crate::virtual_machine::Value;
#[test]
fn test_telemetry_event_serialization() {
let event = DebugEvent::Telemetry {
frame_index: 10,
vm_steps: 100,
syscalls: 5,
cycles: 5000,
cycles_budget: 10000,
host_cpu_time_us: 1200,
violations: 0,
gfx_used_bytes: 1024,
gfx_inflight_bytes: 0,
gfx_slots_occupied: 1,
audio_used_bytes: 2048,
audio_inflight_bytes: 0,
audio_slots_occupied: 2,
};
let json = serde_json::to_string(&event).unwrap();
assert!(json.contains("\"event\":\"telemetry\""));
assert!(json.contains("\"cycles\":5000"));
assert!(json.contains("\"cycles_budget\":10000"));
}
#[test]
fn test_get_state_serialization() {
let resp = DebugResponse::GetState {
+19 -9
View File
@@ -11,21 +11,31 @@ use crate::telemetry::CertificationConfig;
/// PROMETEU Firmware.
///
/// The central orchestrator of the system. It manages the high-level state machine,
/// transitioning between system states like booting, the Hub launcher, and
/// actual application execution.
/// The central orchestrator of the console. The firmware acts as the
/// "Control Unit", managing the high-level state machine of the system.
///
/// It is responsible for transitioning between different modes of operation,
/// such as showing the splash screen, running the Hub (launcher), or
/// executing a game/app.
///
/// ### Execution Loop:
/// The firmware is designed to be ticked once per frame (60Hz). During each
/// tick, it:
/// 1. Updates peripherals with the latest input signals.
/// 2. Delegates the logic update to the current active state.
/// 3. Handles state transitions (e.g., from Loading to Playing).
pub struct Firmware {
/// The Virtual Machine instance.
/// The execution engine (PVM) for user applications.
pub vm: VirtualMachine,
/// The System Operating logic (syscalls, telemetry, logs).
/// The underlying OS services (Syscalls, Filesystem, Telemetry).
pub os: PrometeuOS,
/// The System UI / Launcher environment.
/// The internal state of the system launcher (Hub).
pub hub: PrometeuHub,
/// Current high-level state of the system.
/// The current operational state (e.g., Reset, SplashScreen, GameRunning).
pub state: FirmwareState,
/// Desired execution target resolved at boot.
/// The desired application to run after boot (Hub or specific Cartridge).
pub boot_target: BootTarget,
/// Tracking flag to ensure `on_enter` is called exactly once per state transition.
/// State-machine lifecycle tracker.
state_initialized: bool,
}
@@ -1,10 +1,10 @@
pub use crate::firmware::firmware_step_crash_screen::AppCrashesStep;
pub use crate::firmware::firmware_step_game_running::GameRunningStep;
pub use crate::firmware::firmware_step_hub_home::HubHomeStep;
pub use crate::firmware::firmware_step_launch_hub::LaunchHubStep;
pub use crate::firmware::firmware_step_load_cartridge::LoadCartridgeStep;
pub use crate::firmware::firmware_step_reset::ResetStep;
pub use crate::firmware::firmware_step_splash_screen::SplashScreenStep;
pub use crate::firmware::firmware_step_launch_hub::LaunchHubStep;
pub use crate::firmware::firmware_step_hub_home::HubHomeStep;
pub use crate::firmware::firmware_step_load_cartridge::LoadCartridgeStep;
pub use crate::firmware::firmware_step_game_running::GameRunningStep;
pub use crate::firmware::firmware_step_crash_screen::AppCrashesStep;
#[derive(Debug, Clone)]
pub enum FirmwareState {
@@ -1,7 +1,7 @@
use crate::firmware::firmware_state::{FirmwareState, LaunchHubStep};
use crate::firmware::prometeu_context::PrometeuContext;
use crate::model::Color;
use crate::log::{LogLevel, LogSource};
use crate::model::Color;
#[derive(Debug, Clone)]
pub struct AppCrashesStep {
@@ -1,8 +1,8 @@
use crate::firmware::boot_target::BootTarget;
use crate::firmware::firmware_state::{FirmwareState, HubHomeStep, LoadCartridgeStep};
use crate::firmware::prometeu_context::PrometeuContext;
use crate::model::CartridgeLoader;
use crate::log::{LogLevel, LogSource};
use crate::model::CartridgeLoader;
#[derive(Debug, Clone)]
pub struct LaunchHubStep;
@@ -1,7 +1,7 @@
use crate::firmware::firmware_state::{FirmwareState, GameRunningStep, HubHomeStep};
use crate::firmware::prometeu_context::PrometeuContext;
use crate::model::{AppMode, Cartridge, Color, Rect};
use crate::log::{LogLevel, LogSource};
use crate::model::{AppMode, Cartridge, Color, Rect};
#[derive(Debug, Clone)]
pub struct LoadCartridgeStep {
+1 -1
View File
@@ -11,7 +11,7 @@ pub(crate) mod firmware_step_game_running;
pub(crate) mod firmware_step_crash_screen;
mod prometeu_context;
pub use boot_target::BootTarget;
pub use firmware::Firmware;
pub use firmware_state::FirmwareState;
pub use prometeu_context::PrometeuContext;
pub use boot_target::BootTarget;
+2 -2
View File
@@ -4,8 +4,8 @@ mod fs_entry;
mod fs_backend;
mod virtual_fs;
pub use fs_backend::FsBackend;
pub use fs_entry::FsEntry;
pub use fs_error::FsError;
pub use fs_state::FsState;
pub use fs_entry::FsEntry;
pub use fs_backend::FsBackend;
pub use virtual_fs::VirtualFS;
@@ -1,6 +1,15 @@
use crate::fs::{FsBackend, FsEntry, FsError};
/// Virtual Filesystem (VFS) interface for Prometeu.
///
/// The VFS provides a sandboxed, unified path interface for user applications.
/// Instead of interacting directly with the host's disk, the VM uses
/// normalized paths (e.g., `/user/save.dat`).
///
/// The actual storage is provided by an `FsBackend`, which can be a real
/// directory on disk, an in-memory map, or even a network resource.
pub struct VirtualFS {
/// The active storage implementation.
backend: Option<Box<dyn FsBackend>>,
}
+3 -3
View File
@@ -1,5 +1,5 @@
use crate::hardware::memory_banks::{TileBankPoolInstaller, SoundBankPoolInstaller};
use crate::model::{AssetEntry, BankStats, BankType, Color, HandleId, LoadStatus, SlotRef, SlotStats, TileBank, TileSize, SoundBank, Sample, PreloadEntry};
use crate::hardware::memory_banks::{SoundBankPoolInstaller, TileBankPoolInstaller};
use crate::model::{AssetEntry, BankStats, BankType, Color, HandleId, LoadStatus, PreloadEntry, Sample, SlotRef, SlotStats, SoundBank, TileBank, TileSize};
use std::collections::HashMap;
use std::sync::{Arc, Mutex, RwLock};
use std::thread;
@@ -659,7 +659,7 @@ impl AssetManager {
#[cfg(test)]
mod tests {
use super::*;
use crate::hardware::memory_banks::{TileBankPoolAccess, SoundBankPoolAccess, MemoryBanks};
use crate::hardware::memory_banks::{MemoryBanks, SoundBankPoolAccess, TileBankPoolAccess};
#[test]
fn test_asset_loading_flow() {
+15 -5
View File
@@ -97,15 +97,25 @@ pub enum AudioCommand {
/// PROMETEU Audio Subsystem.
///
/// Models a multi-channel PCM sampler.
/// It works like an "Audio CPU": the Game Core sends high-level commands
/// every frame, and the Host backend implements the low-level mixer.
/// Models a multi-channel PCM sampler (SPU).
/// The audio system in Prometeu is **command-based**. This means the Core
/// doesn't generate raw audio samples; instead, it sends high-level commands
/// (like `Play`, `Stop`, `SetVolume`) to a queue. The physical host backend
/// (e.g., CPAL on desktop) then consumes these commands and performs the
/// actual mixing at the native hardware sample rate.
///
/// ### Key Features:
/// - **16 Simultaneous Voices**: Independent volume, pan, and pitch.
/// - **Sample-based Synthesis**: Plays PCM data stored in SoundBanks.
/// - **Stereo Output**: 48kHz output target.
pub struct Audio {
/// Local state of the 16 hardware voices.
/// Local state of the hardware voices. This state is used for logic
/// (e.g., checking if a sound is still playing) and is synchronized with the Host.
pub voices: [Channel; MAX_CHANNELS],
/// Queue of pending commands to be processed by the Host mixer.
/// This queue is typically flushed and sent to the Host once per frame.
pub commands: Vec<AudioCommand>,
/// Interface to access sound memory banks.
/// Interface to access sound memory banks (ARAM).
pub sound_banks: Arc<dyn SoundBankPoolAccess>,
}
+37 -27
View File
@@ -4,18 +4,24 @@ use std::sync::Arc;
/// Blending modes inspired by classic 16-bit hardware.
/// Defines how source pixels are combined with existing pixels in the framebuffer.
///
/// ### Usage Example:
/// ```rust
/// // Draw a semi-transparent blue rectangle
/// gfx.fill_rect_blend(10, 10, 50, 50, Color::BLUE, BlendMode::Half);
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum BlendMode {
/// No blending: source overwrites destination.
/// No blending: a source overwrites the destination.
#[default]
None,
/// Average: dst = (src + dst) / 2. Creates a semi-transparent effect.
/// Average: `dst = (src + dst) / 2`. Creates a semi-transparent effect.
Half,
/// Additive: dst = dst + (src / 2). Good for glows/light.
/// Additive: `dst = clamp(dst + (src / 2))`. Good for glows/light.
HalfPlus,
/// Subtractive: dst = dst - (src / 2). Good for shadows.
/// Subtractive: `dst = clamp(dst - (src / 2))`. Good for shadows.
HalfMinus,
/// Full Additive: dst = dst + src. Saturated light effect.
/// Full Additive: `dst = clamp(dst + src)`. Saturated light effect.
Full,
}
@@ -24,44 +30,48 @@ pub enum BlendMode {
/// Models a specialized graphics chip with a fixed resolution, double buffering,
/// and a multi-layered tile/sprite architecture.
///
/// Composition Order (back to front):
/// 1. Sprites with priority 0 (optional background objects)
/// 2. Tile Layer 0 + Sprites with priority 1
/// 3. Tile Layer 1 + Sprites with priority 2
/// 4. Tile Layer 2 + Sprites with priority 3
/// 5. Tile Layer 3 + Sprites with priority 4
/// 6. Scene Fade effect
/// 7. HUD Layer (always on top)
/// 8. HUD Fade effect
/// The GFX system works by composing several "layers" into a single 16-bit
/// RGB565 framebuffer. It supports hardware-accelerated primitives (lines, rects)
/// and specialized console features like background scrolling and sprite sorting.
///
/// ### Layer Composition Order (back to front):
/// 1. **Priority 0 Sprites**: Objects behind everything else.
/// 2. **Tile Layer 0 + Priority 1 Sprites**: Background 0.
/// 3. **Tile Layer 1 + Priority 2 Sprites**: Background 1.
/// 4. **Tile Layer 2 + Priority 3 Sprites**: Background 2.
/// 5. **Tile Layer 3 + Priority 4 Sprites**: Foreground.
/// 6. **Scene Fade**: Global brightness/color filter.
/// 7. **HUD Layer**: Fixed UI elements (always on top).
/// 8. **HUD Fade**: Independent fade for the UI.
pub struct Gfx {
/// Width of the internal framebuffer.
/// Width of the internal framebuffer in pixels.
w: usize,
/// Height of the internal framebuffer.
/// Height of the internal framebuffer in pixels.
h: usize,
/// Front buffer: the one currently being displayed by the Host.
/// Front buffer: the "VRAM" currently being displayed by the Host window.
front: Vec<u16>,
/// Back buffer: the one being drawn to during the current frame.
/// Back buffer: the "Work RAM" where new frames are composed.
back: Vec<u16>,
/// 4 scrollable backgrounds.
/// 4 scrollable background layers. Each can have its own scroll (X, Y) and TileBank.
pub layers: [ScrollableTileLayer; 4],
/// 1 fixed layer for User Interface.
/// 1 fixed layer for User Interface (HUD). It doesn't scroll.
pub hud: HudTileLayer,
/// Interface to access graphical memory banks.
/// Shared access to graphical memory banks (tiles and palettes).
pub tile_banks: Arc<dyn TileBankPoolAccess>,
/// Hardware sprites (Object Attribute Memory equivalent).
/// Hardware sprite list (512 slots). Equivalent to OAM (Object Attribute Memory).
pub sprites: [Sprite; 512],
/// Current transparency level for the main scene (0=invisible, 31=fully visible).
/// Scene brightness/fade level (0 = black/invisible, 31 = fully visible).
pub scene_fade_level: u8,
/// Color used for the scene fade effect.
/// Target color for the scene fade effect (usually Black).
pub scene_fade_color: Color,
/// Current transparency level for the HUD (independent of scene).
/// HUD brightness/fade level (independent from the scene).
pub hud_fade_level: u8,
/// Color used for the HUD fade effect.
/// Target color for the HUD fade effect.
pub hud_fade_color: Color,
/// Internal cache used to sort sprites by priority without allocations.
/// Internal cache used to sort sprites into priority groups to optimize rendering.
priority_buckets: [Vec<usize>; 5],
}
+17 -12
View File
@@ -1,23 +1,29 @@
use crate::hardware::{AssetManager, Audio, Gfx, HardwareBridge, Pad, Touch, MemoryBanks};
use crate::hardware::memory_banks::{TileBankPoolAccess, TileBankPoolInstaller, SoundBankPoolAccess, SoundBankPoolInstaller};
use crate::hardware::memory_banks::{SoundBankPoolAccess, SoundBankPoolInstaller, TileBankPoolAccess, TileBankPoolInstaller};
use crate::hardware::{AssetManager, Audio, Gfx, HardwareBridge, MemoryBanks, Pad, Touch};
use std::sync::Arc;
/// Aggregate structure for all virtual hardware peripherals.
///
/// This struct represents the "Mainboard" of the PROMETEU console,
/// containing instances of GFX, Audio, Input (Pad), and Touch.
/// This struct represents the "Mainboard" of the PROMETEU console.
/// It acts as a container for all hardware subsystems. In the Prometeu
/// architecture, hardware is decoupled from the OS and VM, allowing
/// for easier testing and different host implementations (Desktop, Web, etc.).
///
/// ### Console Specifications:
/// - **Resolution**: 320x180 (16:9 Aspect Ratio).
/// - **Color Depth**: RGB565 (16-bit).
/// - **Audio**: Stereo, Command-based mixing.
/// - **Input**: 12-button Digital Gamepad + Absolute Touch/Mouse.
pub struct Hardware {
/// Shared memory banks for hardware assets.
pub memory_banks: Arc<MemoryBanks>,
/// The Graphics Processing Unit.
/// The Graphics Processing Unit (GPU). Handles drawing primitives, sprites, and tilemaps.
pub gfx: Gfx,
/// The Sound Processing Unit.
/// The Sound Processing Unit (SPU). Manages sample playback and volume control.
pub audio: Audio,
/// The standard digital gamepad.
/// The standard digital gamepad. Provides state for D-Pad, face buttons, and triggers.
pub pad: Pad,
/// The absolute pointer input device.
/// The absolute pointer input device (Mouse/Touchscreen).
pub touch: Touch,
/// The Asset Management system.
/// The Asset Management system (DMA). Handles loading data into VRAM (TileBanks) and ARAM (SoundBanks).
pub assets: AssetManager,
}
@@ -48,7 +54,6 @@ impl Hardware {
pub fn new() -> Self {
let memory_banks = Arc::new(MemoryBanks::new());
Self {
memory_banks: Arc::clone(&memory_banks),
gfx: Gfx::new(Self::W, Self::H, Arc::clone(&memory_banks) as Arc<dyn TileBankPoolAccess>),
audio: Audio::new(Arc::clone(&memory_banks) as Arc<dyn SoundBankPoolAccess>),
pad: Pad::default(),
@@ -1,5 +1,5 @@
use crate::model::{SoundBank, TileBank};
use std::sync::{Arc, RwLock};
use crate::model::{TileBank, SoundBank};
/// Non-generic interface for peripherals to access graphical tile banks.
pub trait TileBankPoolAccess: Send + Sync {
+2
View File
@@ -6,6 +6,7 @@ mod input_signal;
mod audio;
mod memory_banks;
pub mod hardware;
pub mod syscalls;
pub use crate::model::HandleId;
pub use asset::AssetManager;
@@ -15,6 +16,7 @@ pub use gfx::Gfx;
pub use input_signal::InputSignals;
pub use memory_banks::MemoryBanks;
pub use pad::Pad;
pub use syscalls::Syscall;
pub use touch::Touch;
pub trait HardwareBridge {
+1 -1
View File
@@ -1,5 +1,5 @@
use crate::model::Button;
use crate::hardware::input_signal::InputSignals;
use crate::model::Button;
#[derive(Default, Clone, Copy, Debug)]
pub struct Pad {
@@ -1,57 +1,106 @@
/// Enumeration of all System Calls (Syscalls) available in the Prometeu environment.
///
/// Syscalls are the primary mechanism for a program running in the Virtual Machine
/// to interact with the outside world (Hardware, OS, Filesystem).
///
/// Each Syscall has a unique 32-bit ID. The IDs are grouped by category:
/// - **0x0xxx**: System & OS Control
/// - **0x1xxx**: Graphics (GFX)
/// - **0x2xxx**: Input (Gamepad & Touch)
/// - **0x3xxx**: Audio (PCM & Mixing)
/// - **0x4xxx**: Filesystem (Sandboxed I/O)
/// - **0x5xxx**: Logging & Debugging
/// - **0x6xxx**: Asset Loading & Memory Banks
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum Syscall {
// System
// --- System ---
/// Checks if a cartridge is currently inserted in the virtual slot.
SystemHasCart = 0x0001,
/// Requests the OS to launch a specific cartridge.
SystemRunCart = 0x0002,
// GFX
// --- GFX (Graphics) ---
/// Fills the entire back buffer with a single color.
GfxClear = 0x1001,
/// Draws a solid rectangle.
GfxFillRect = 0x1002,
/// Draws a 1-pixel wide line.
GfxDrawLine = 0x1003,
/// Draws a circle outline.
GfxDrawCircle = 0x1004,
/// Draws a filled circle (disc).
GfxDrawDisc = 0x1005,
/// Draws a rectangle outline.
GfxDrawSquare = 0x1006,
/// Configures one of the 512 hardware sprites.
GfxSetSprite = 0x1007,
// Input
// --- Input ---
/// Returns the current raw state of the digital gamepad (bitmask).
InputGetPad = 0x2001,
/// Returns buttons that were pressed exactly in this frame.
InputGetPadPressed = 0x2002,
/// Returns buttons that were released exactly in this frame.
InputGetPadReleased = 0x2003,
/// Returns how many frames a button has been held down.
InputGetPadHold = 0x2004,
/// Returns the X coordinate of the touch/mouse pointer.
TouchGetX = 0x2101,
/// Returns the Y coordinate of the touch/mouse pointer.
TouchGetY = 0x2102,
/// Returns true if the pointer is currently touching the screen.
TouchIsDown = 0x2103,
/// Returns true if the touch started in this frame.
TouchIsPressed = 0x2104,
/// Returns true if the touch ended in this frame.
TouchIsReleased = 0x2105,
/// Returns how many frames the pointer has been held down.
TouchGetHold = 0x2106,
// Audio
// --- Audio ---
/// Starts playback of a sound sample by its Bank and ID.
AudioPlaySample = 0x3001,
/// Low-level audio play command.
AudioPlay = 0x3002,
// FS
// --- FS (Filesystem) ---
/// Opens a file for reading or writing. Returns a File Handle (u32).
FsOpen = 0x4001,
/// Reads data from an open file handle into the VM heap.
FsRead = 0x4002,
/// Writes data from the VM heap into an open file handle.
FsWrite = 0x4003,
/// Closes an open file handle.
FsClose = 0x4004,
/// Lists entries in a directory.
FsListDir = 0x4005,
/// Checks if a file or directory exists.
FsExists = 0x4006,
/// Deletes a file or empty directory.
FsDelete = 0x4007,
// Log
// --- Log ---
/// Writes a generic string to the system log.
LogWrite = 0x5001,
/// Writes a string to the system log with a specific numerical tag.
LogWriteTag = 0x5002,
// Asset
// --- Asset (DMA) ---
/// Starts an asynchronous load of a file into a memory bank.
AssetLoad = 0x6001,
/// Returns the status of a pending asset load (0=Loading, 1=Ready, 2=Error).
AssetStatus = 0x6002,
/// Finalizes the asset loading, making it available for GFX/Audio.
AssetCommit = 0x6003,
/// Cancels a pending asset load.
AssetCancel = 0x6004,
// Bank
// --- Bank (Memory) ---
/// Returns information about a specific Memory Bank.
BankInfo = 0x6101,
/// Returns information about a slot within a Memory Bank.
BankSlotInfo = 0x6102,
}
+1 -1
View File
@@ -1,5 +1,5 @@
use crate::model::Button;
use crate::hardware::input_signal::InputSignals;
use crate::model::Button;
#[derive(Default, Clone, Copy, Debug)]
pub struct Touch {
+17
View File
@@ -1,3 +1,20 @@
//! # Prometeu Core
//!
//! This crate contains the engine and hardware definitions for the Prometeu Virtual Console.
//! It serves as the bridge between the physical host (desktop/web) and the virtualized
//! environment where games and apps run.
//!
//! ## Main Components:
//! - [`hardware`]: Virtual peripheral definitions (Graphics, Audio, Input).
//! - [`virtual_machine`]: The stack-based execution engine for Prometeu ByteCode.
//! - [`prometeu_os`]: Resource management, filesystem access, and syscall dispatching.
//! - [`firmware`]: System state machine (Boot, Hub, Game Loading, Crash Handler).
//! - [`model`]: Common data structures (Colors, Sprites, Cartridges).
//! - [`fs`]: Virtualized filesystem abstraction for sandboxed access.
//! - [`log`]: Centralized logging and telemetry service.
//!
//! The "Source of Truth" for the console's behavior lives here.
pub mod hardware;
pub mod log;
pub mod virtual_machine;
+1 -1
View File
@@ -1,5 +1,5 @@
use std::collections::VecDeque;
use crate::log::{LogEvent, LogLevel, LogSource};
use std::collections::VecDeque;
pub struct LogService {
events: VecDeque<LogEvent>,
+2 -2
View File
@@ -3,7 +3,7 @@ mod log_source;
mod log_event;
mod log_service;
pub use log_level::LogLevel;
pub use log_source::LogSource;
pub use log_event::LogEvent;
pub use log_level::LogLevel;
pub use log_service::LogService;
pub use log_source::LogSource;
@@ -1,6 +1,6 @@
use crate::model::cartridge::{Cartridge, CartridgeDTO, CartridgeError, CartridgeManifest};
use std::fs;
use std::path::Path;
use crate::model::cartridge::{Cartridge, CartridgeDTO, CartridgeError, CartridgeManifest};
pub struct CartridgeLoader;
+9 -6
View File
@@ -1,10 +1,13 @@
/// Simple RGB565 color (0bRRRRRGGGGGGBBBBB).
/// - 5 bits Red
/// - 6 bits Green
/// - 5 bits Blue
/// Represents a 16-bit color in the RGB565 format.
///
/// The RGB565 format is a common high-color representation for embedded systems:
/// - **Red**: 5 bits (0..31)
/// - **Green**: 6 bits (0..63)
/// - **Blue**: 5 bits (0..31)
///
/// There is no alpha channel.
/// Transparency is handled via Color Key or Blend Mode.
/// Prometeu does not have a hardware alpha channel. Transparency is achieved
/// by using a specific color key (Magenta / 0xF81F) which the GFX engine
/// skips during rendering.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Color(pub u16);
+1 -1
View File
@@ -11,7 +11,7 @@ mod cartridge;
mod cartridge_loader;
mod window;
pub use asset::{AssetEntry, BankType, BankStats, LoadStatus, SlotRef, SlotStats, HandleId, PreloadEntry};
pub use asset::{AssetEntry, BankStats, BankType, HandleId, LoadStatus, PreloadEntry, SlotRef, SlotStats};
pub use button::{Button, ButtonId};
pub use cartridge::{AppMode, Cartridge, CartridgeDTO, CartridgeError};
pub use cartridge_loader::{CartridgeLoader, DirectoryCartridgeLoader, PackedCartridgeLoader};
+1 -1
View File
@@ -1,5 +1,5 @@
use crate::model::Tile;
use crate::model::tile_bank::TileSize;
use crate::model::Tile;
use crate::model::TileSize::Size8;
pub struct TileMap {
@@ -1,3 +1,4 @@
mod prometeu_hub;
mod window_manager;
pub use prometeu_hub::PrometeuHub;
@@ -1,55 +1,9 @@
use crate::hardware::HardwareBridge;
use crate::log::{LogLevel, LogSource};
use crate::model::{Color, Rect, Window, WindowId};
use crate::model::{Color, Rect};
use crate::prometeu_hub::window_manager::WindowManager;
use crate::prometeu_os::PrometeuOS;
/// PROMETEU Window Manager.
pub struct WindowManager {
pub windows: Vec<Window>,
pub focused: Option<WindowId>,
}
impl WindowManager {
pub fn new() -> Self {
Self {
windows: Vec::new(),
focused: None,
}
}
pub fn add_window(&mut self, title: String, viewport: Rect, color: Color) -> WindowId {
let id = WindowId(self.windows.len() as u32);
let window = Window {
id,
viewport,
has_focus: false,
title,
color,
};
self.windows.push(window);
id
}
pub fn remove_window(&mut self, id: WindowId) {
self.windows.retain(|w| w.id != id);
if self.focused == Some(id) {
self.focused = None;
}
}
pub fn remove_all_windows(&mut self) {
self.windows.clear();
self.focused = None;
}
pub fn set_focus(&mut self, id: WindowId) {
self.focused = Some(id);
for window in &mut self.windows {
window.has_focus = window.id == id;
}
}
}
/// PrometeuHub: Launcher and system UI environment.
pub struct PrometeuHub {
pub window_manager: WindowManager,
@@ -103,42 +57,4 @@ impl PrometeuHub {
);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::Rect;
#[test]
fn test_window_manager_focus() {
let mut wm = WindowManager::new();
let id1 = wm.add_window("Window 1".to_string(), Rect { x: 0, y: 0, w: 10, h: 10 }, Color::WHITE);
let id2 = wm.add_window("Window 2".to_string(), Rect { x: 10, y: 10, w: 10, h: 10 }, Color::WHITE);
assert_eq!(wm.windows.len(), 2);
assert_eq!(wm.focused, None);
wm.set_focus(id1);
assert_eq!(wm.focused, Some(id1));
assert!(wm.windows[0].has_focus);
assert!(!wm.windows[1].has_focus);
wm.set_focus(id2);
assert_eq!(wm.focused, Some(id2));
assert!(!wm.windows[0].has_focus);
assert!(wm.windows[1].has_focus);
}
#[test]
fn test_window_manager_remove_window() {
let mut wm = WindowManager::new();
let id = wm.add_window("Window".to_string(), Rect { x: 0, y: 0, w: 10, h: 10 }, Color::WHITE);
wm.set_focus(id);
assert_eq!(wm.focused, Some(id));
wm.remove_window(id);
assert_eq!(wm.windows.len(), 0);
assert_eq!(wm.focused, None);
}
}
+1 -3
View File
@@ -1,6 +1,4 @@
mod prometeu_os;
pub mod syscalls;
use crate::virtual_machine::NativeInterface;
pub use prometeu_os::PrometeuOS;
pub use syscalls::Syscall;
pub use crate::virtual_machine::native_interface::NativeInterface;
@@ -1,62 +1,72 @@
use crate::fs::{FsBackend, FsState, VirtualFS};
use crate::hardware::syscalls::Syscall;
use crate::hardware::{HardwareBridge, InputSignals};
use crate::log::{LogLevel, LogService, LogSource};
use crate::model::{BankType, Cartridge, Color};
use crate::prometeu_os::{NativeInterface, Syscall};
use crate::prometeu_os::NativeInterface;
use crate::telemetry::{CertificationConfig, Certifier, TelemetryFrame};
use crate::virtual_machine::{Value, VirtualMachine};
use std::collections::HashMap;
use std::time::Instant;
/// PrometeuOS (POS): The system firmware/base.
/// PrometeuOS (POS): The central system firmware and resource manager.
///
/// Maximum authority for boot, peripherals, PVM execution, and fault handling.
/// It acts as the bridge between the high-level PVM applications and the virtual hardware.
/// POS is the "kernel" of the Prometeu console. It manages the lifecycle of
/// applications, handles hardware abstraction through Syscalls, and enforces
/// resource limits (CAP).
///
/// ### Core Responsibilities:
/// - **Syscall Dispatching**: Implements the `NativeInterface` to connect the VM to hardware.
/// - **Resource Management**: Manages file handles, memory bank status, and cycle budgeting.
/// - **Filesystem Sandboxing**: Provides a virtualized filesystem (VFS) to the VM.
/// - **Telemetry & Certification**: Tracks performance and ensures apps stay within their budget.
/// - **Logging**: Provides a centralized log service for system and app events.
pub struct PrometeuOS {
/// Incremented on every host tick (60Hz).
/// Host Tick Index: Incremented on every host hardware update (usually 60Hz).
pub tick_index: u64,
/// Incremented every time a logical game frame is successfully completed.
/// Logical Frame Index: Incremented only when an app successfully completes a full frame via `FRAME_SYNC`.
pub logical_frame_index: u64,
/// Indicates if there is an ongoing logical frame that hasn't reached `FRAME_SYNC` yet.
/// Execution State: True if the VM is currently mid-frame.
pub logical_frame_active: bool,
/// Number of virtual cycles still available for the current logical frame.
/// Cycle Budget: The number of PVM cycles remaining for the current logical frame.
pub logical_frame_remaining_cycles: u64,
/// Real-world CPU time (in microseconds) consumed by the last host tick.
/// Performance Metric: Time spent by the host CPU processing the last tick (in microseconds).
pub last_frame_cpu_time_us: u64,
// Filesystem
/// The virtual filesystem interface.
// --- Filesystem ---
/// The virtual filesystem interface, abstracting the physical storage.
pub fs: VirtualFS,
/// Current state of the FS (Mounted, Error, etc).
/// Current health and connection status of the virtual filesystem.
pub fs_state: FsState,
/// Mapping of numeric handles to file paths for open files.
/// Active file handles mapping IDs to their virtual paths.
pub open_files: HashMap<u32, String>,
/// Sequential handle generator for file operations.
/// Generator for unique, non-zero file handles.
pub next_handle: u32,
// Log Service
// --- Logging & Identity ---
/// The centralized service for recording and retrieving system logs.
pub log_service: LogService,
/// Unique ID of the currently running application.
/// Metadata for the currently running application.
pub current_app_id: u32,
pub current_cartridge_title: String,
pub current_cartridge_app_version: String,
pub current_cartridge_app_mode: crate::model::AppMode,
/// Rate-limiting tracker for application logs to prevent performance degradation.
/// Rate-limiter to prevent apps from flooding the log buffer and killing performance.
pub logs_written_this_frame: HashMap<u32, u32>,
// Telemetry and Certification
/// Accumulator for metrics of the frame currently being executed.
// --- Monitoring & Debugging ---
/// Running counters for the current execution slice.
pub telemetry_current: TelemetryFrame,
/// Snapshot of the metrics from the last completed logical frame.
/// The results of the last successfully completed logical frame.
pub telemetry_last: TelemetryFrame,
/// Logic for evaluating compliance with the active CAP profile.
/// Logic for validating that the app obeys the console's Certification (CAP).
pub certifier: Certifier,
/// Global pause flag (used by debugger or system events).
/// Pause state: When true, `tick()` will not advance the VM.
pub paused: bool,
/// Request from debugger to run exactly one instruction or frame.
/// Debugging flag to execute exactly one instruction or frame regardless of budget.
pub debug_step_request: bool,
/// Instant when the system was initialized.
/// Wall-clock time of system startup.
boot_time: Instant,
}
@@ -197,6 +207,7 @@ impl PrometeuOS {
// Reset telemetry for the new logical frame
self.telemetry_current = TelemetryFrame {
frame_index: self.logical_frame_index,
cycles_budget: self.certifier.config.cycles_budget_per_frame.unwrap_or(Self::CYCLES_PER_LOGICAL_FRAME),
..Default::default()
};
}
@@ -263,7 +274,7 @@ impl PrometeuOS {
self.last_frame_cpu_time_us = start.elapsed().as_micros() as u64;
// Update bank telemetry in current frame (snapshot)
// Update bank telemetry in the current frame (snapshot)
let gfx_stats = hw.assets().bank_info(BankType::TILES);
self.telemetry_current.gfx_used_bytes = gfx_stats.used_bytes;
self.telemetry_current.gfx_inflight_bytes = gfx_stats.inflight_bytes;
@@ -277,6 +288,7 @@ impl PrometeuOS {
// If the frame ended exactly in this tick, we update the final real time in the latch.
if !self.logical_frame_active && self.telemetry_last.frame_index == self.logical_frame_index.wrapping_sub(1) {
self.telemetry_last.host_cpu_time_us = self.last_frame_cpu_time_us;
self.telemetry_last.cycles_budget = self.telemetry_current.cycles_budget;
self.telemetry_last.gfx_used_bytes = self.telemetry_current.gfx_used_bytes;
self.telemetry_last.gfx_inflight_bytes = self.telemetry_current.gfx_inflight_bytes;
self.telemetry_last.gfx_slots_occupied = self.telemetry_current.gfx_slots_occupied;
@@ -460,6 +472,27 @@ mod tests {
assert!(cycles_after_tick_2 > cycles_after_tick_1, "VM should have consumed more cycles because FrameSync reset the budget");
}
#[test]
fn test_telemetry_cycles_budget() {
let mut os = PrometeuOS::new(None);
let mut vm = VirtualMachine::default();
let mut hw = Hardware::new();
let signals = InputSignals::default();
// Standard budget
os.tick(&mut vm, &signals, &mut hw);
assert_eq!(os.telemetry_current.cycles_budget, PrometeuOS::CYCLES_PER_LOGICAL_FRAME);
// Custom budget via CAP
let mut config = CertificationConfig::default();
config.enabled = true;
config.cycles_budget_per_frame = Some(50000);
let mut os_custom = PrometeuOS::new(Some(config));
os_custom.tick(&mut vm, &signals, &mut hw);
assert_eq!(os_custom.telemetry_current.cycles_budget, 50000);
}
#[test]
fn test_get_color_logic() {
let os = PrometeuOS::new(None);
+1
View File
@@ -5,6 +5,7 @@ pub struct TelemetryFrame {
pub frame_index: u64,
pub vm_steps: u32,
pub cycles_used: u64,
pub cycles_budget: u64,
pub syscalls: u32,
pub host_cpu_time_us: u64,
pub violations: u32,
@@ -3,10 +3,20 @@ mod value;
mod call_frame;
mod scope_frame;
mod program;
pub mod native_interface;
pub use prometeu_bytecode::opcode::OpCode;
use crate::hardware::HardwareBridge;
pub use program::Program;
pub use prometeu_bytecode::opcode::OpCode;
pub use value::Value;
pub use virtual_machine::{BudgetReport, LogicalFrameEndingReason, VirtualMachine};
pub trait NativeInterface {
/// Dispatches a syscall from the Virtual Machine to the native implementation.
///
/// ABI Rule: Arguments for the syscall are expected on the `operand_stack` in call order.
/// Since the stack is LIFO, the last argument of the call is the first to be popped.
///
/// The implementation MUST pop all its arguments and SHOULD push a return value if the
/// syscall is defined to return one.
fn syscall(&mut self, id: u32, vm: &mut VirtualMachine, hw: &mut dyn HardwareBridge) -> Result<u64, String>;
}
@@ -1,13 +0,0 @@
use crate::hardware::HardwareBridge;
use crate::virtual_machine::VirtualMachine;
pub trait NativeInterface {
/// Dispatches a syscall from the Virtual Machine to the native implementation.
///
/// ABI Rule: Arguments for the syscall are expected on the `operand_stack` in call order.
/// Since the stack is LIFO, the last argument of the call is the first to be popped.
///
/// The implementation MUST pop all its arguments and SHOULD push a return value if the
/// syscall is defined to return one.
fn syscall(&mut self, id: u32, vm: &mut VirtualMachine, hw: &mut dyn HardwareBridge) -> Result<u64, String>;
}
@@ -1,5 +1,5 @@
use std::sync::Arc;
use crate::virtual_machine::Value;
use std::sync::Arc;
#[derive(Debug, Clone, Default)]
pub struct Program {
@@ -1,15 +1,28 @@
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
/// Represents any piece of data that can be stored on the VM stack or in globals.
///
/// The PVM is "dynamically typed" at the bytecode level, meaning a single
/// `Value` enum can hold different primitive types. The VM performs
/// automatic type promotion (e.g., adding an Int32 to a Float64 results
/// in a Float64) to ensure mathematical correctness.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Value {
/// 32-bit signed integer. Used for most loop counters and indices.
Int32(i32),
/// 64-bit signed integer. Used for large numbers and timestamps.
Int64(i64),
/// 64-bit double precision float. Used for physics and complex math.
Float(f64),
/// Boolean value (true/false).
Boolean(bool),
/// UTF-8 string. Strings are immutable and usually come from the Constant Pool.
String(String),
Ref(usize), // Heap reference
/// A pointer to an object on the heap.
Ref(usize),
/// Represents the absence of a value (equivalent to `null` or `undefined`).
Null,
}
@@ -1,9 +1,8 @@
use crate::hardware::HardwareBridge;
use crate::prometeu_os::NativeInterface;
use crate::virtual_machine::call_frame::CallFrame;
use crate::virtual_machine::scope_frame::ScopeFrame;
use crate::virtual_machine::value::Value;
use crate::virtual_machine::Program;
use crate::virtual_machine::{NativeInterface, Program};
use prometeu_bytecode::opcode::OpCode;
use prometeu_bytecode::pbc::{self, ConstantPoolEntry};
@@ -37,28 +36,41 @@ pub struct BudgetReport {
/// The PVM (PROMETEU Virtual Machine).
///
/// A deterministic, stack-based virtual machine designed for educational purposes.
/// It models execution through fixed-cost cycles and explicit memory management.
/// A deterministic, stack-based virtual machine designed for game logic and
/// educational simulation. The PVM executes bytecode compiled from TypeScript/JS
/// and interacts with virtual hardware through a specialized instruction set.
///
/// ### Architecture Highlights:
/// - **Stack-Based**: Most operations pop values from the stack and push results back.
/// - **Deterministic**: Execution is cycle-aware, allowing for precise performance budgeting.
/// - **Sandboxed**: No direct access to the host system; all I/O goes through Syscalls.
/// - **Type-Aware**: Supports integers, floats, booleans, and strings with automatic promotion.
///
/// ### Memory Regions:
/// - **ROM**: Immutable instruction storage.
/// - **Operand Stack**: Fast-access temporary storage for calculations.
/// - **Global Pool**: Persistent storage for cross-frame variables.
/// - **Heap**: Dynamic memory for complex data (simplified version).
pub struct VirtualMachine {
/// Program Counter: points to the next byte in the ROM to be executed.
/// Program Counter (PC): The absolute byte offset in ROM for the next instruction.
pub pc: usize,
/// Operand Stack: used for intermediate calculations and passing arguments to opcodes.
/// Operand Stack: The primary workspace for all mathematical and logical operations.
pub operand_stack: Vec<Value>,
/// Call Stack: stores execution frames for function calls.
/// Call Stack: Manages function call context (return addresses, frame limits).
pub call_stack: Vec<CallFrame>,
/// Scope Stack: stores frames for blocks within a function.
/// Scope Stack: Handles block-level local variable visibility (scopes).
pub scope_stack: Vec<ScopeFrame>,
/// Globals: storage for persistent variables that survive between frames.
/// Global Variable Store: Variables that persist for the lifetime of the program.
pub globals: Vec<Value>,
/// The currently loaded program (Bytecode + Constant Pool).
/// The loaded executable (Bytecode + Constant Pool), that is the ROM translated.
pub program: Program,
/// Dynamic memory region for complex structures (Simplified in current version).
/// Heap Memory: Dynamic allocation pool.
pub heap: Vec<Value>,
/// Total accumulated execution cycles since the last reset.
/// Total virtual cycles consumed since the VM started.
pub cycles: u64,
/// Flag indicating if the VM has been stopped by a `HALT` instruction.
/// Stop flag: true if a `HALT` opcode was encountered.
pub halted: bool,
/// A set of PC addresses where execution should pause.
/// Set of ROM addresses used for software breakpoints in the debugger.
pub breakpoints: std::collections::HashSet<usize>,
}
@@ -692,7 +704,6 @@ impl VirtualMachine {
mod tests {
use super::*;
use crate::hardware::HardwareBridge;
use crate::prometeu_os::NativeInterface;
use crate::virtual_machine::Value;
struct MockNative;
@@ -997,7 +1008,7 @@ mod tests {
// Check if scope_stack was leaked (it currently would be if we don't clear it on RET)
// The PR doesn't explicitly say RET should clear scope_stack, but it's good practice.
// "Não mexe em scopes intermediários (eles devem já ter sido fechados)"
// "Don't touch intermediate scopes (they should have already been closed)"
// If they were closed, scope_stack would be empty for this frame.
}