added domains into crates

This commit is contained in:
2026-03-24 13:40:34 +00:00
parent 1135514508
commit bddd588464
222 changed files with 751 additions and 790 deletions
+80
View File
@@ -0,0 +1,80 @@
use serde::{Deserialize, Serialize};
pub type HandleId = u32;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[allow(non_camel_case_types)]
pub enum BankType {
TILES,
SOUNDS,
// TILEMAPS,
// BLOBS,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AssetEntry {
pub asset_id: u32,
pub asset_name: String,
pub bank_type: BankType,
pub offset: u64,
pub size: u64,
pub decoded_size: u64,
pub codec: String, // e.g., "RAW"
pub metadata: serde_json::Value,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PreloadEntry {
pub asset_name: String,
pub slot: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum LoadStatus {
PENDING,
LOADING,
READY,
COMMITTED,
CANCELED,
ERROR,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BankStats {
pub total_bytes: usize,
pub used_bytes: usize,
pub free_bytes: usize,
pub inflight_bytes: usize,
pub slot_count: usize,
pub slots_occupied: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SlotStats {
pub asset_id: Option<u32>,
pub asset_name: Option<String>,
pub generation: u32,
pub resident_bytes: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SlotRef {
pub asset_type: BankType,
pub index: usize,
}
impl SlotRef {
pub fn gfx(index: usize) -> Self {
Self {
asset_type: BankType::TILES,
index,
}
}
pub fn audio(index: usize) -> Self {
Self {
asset_type: BankType::SOUNDS,
index,
}
}
}
@@ -0,0 +1,19 @@
use crate::asset::{AssetEntry, BankStats, BankType, HandleId, LoadStatus, PreloadEntry, SlotRef, SlotStats};
pub trait AssetBridge {
fn initialize_for_cartridge(
&self,
assets: Vec<AssetEntry>,
preload: Vec<PreloadEntry>,
assets_data: Vec<u8>,
);
fn load(&self, asset_name: &str, slot: SlotRef) -> Result<HandleId, String>;
fn status(&self, handle: HandleId) -> LoadStatus;
fn commit(&self, handle: HandleId);
fn cancel(&self, handle: HandleId);
fn apply_commits(&self);
fn bank_info(&self, kind: BankType) -> BankStats;
fn slot_info(&self, slot: SlotRef) -> SlotStats;
fn find_slot_by_name(&self, asset_name: &str, kind: BankType) -> Option<u8>;
fn shutdown(&self);
}
@@ -0,0 +1,38 @@
use std::sync::Arc;
use crate::sample::Sample;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LoopMode {
Off,
On,
}
pub trait AudioBridge {
fn play(
&mut self,
bank_id: u8,
sample_id: u16,
voice_id: usize,
volume: u8,
pan: u8,
pitch: f64,
priority: u8,
loop_mode: LoopMode,
);
fn play_sample(
&mut self,
sample: Arc<Sample>,
voice_id: usize,
volume: u8,
pan: u8,
pitch: f64,
priority: u8,
loop_mode: LoopMode,
);
fn stop(&mut self, voice_id: usize);
fn set_volume(&mut self, voice_id: usize, volume: u8);
fn set_pan(&mut self, voice_id: usize, pan: u8);
fn set_pitch(&mut self, voice_id: usize, pitch: f64);
fn is_playing(&self, voice_id: usize) -> bool;
fn clear_commands(&mut self);
}
+41
View File
@@ -0,0 +1,41 @@
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum ButtonId {
Up = 0,
Down = 1,
Left = 2,
Right = 3,
A = 4,
B = 5,
X = 6,
Y = 7,
L = 8,
R = 9,
Start = 10,
Select = 11,
}
#[repr(C)]
#[derive(Default, Clone, Copy, Debug)]
pub struct Button {
pub pressed: bool,
pub released: bool,
pub down: bool,
pub hold_frames: u16,
}
impl Button {
pub fn begin_frame(&mut self, is_down_now: bool) {
let was_down = self.down;
self.down = is_down_now.clone();
self.pressed = !was_down && self.down;
self.released = was_down && !self.down;
if self.down {
self.hold_frames = self.hold_frames.saturating_add(1);
} else {
self.hold_frames = 0;
}
}
}
@@ -0,0 +1,77 @@
use crate::asset::{AssetEntry, PreloadEntry};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
pub enum AppMode {
Game,
System,
}
#[derive(Debug, Clone)]
pub struct Cartridge {
pub app_id: u32,
pub title: String,
pub app_version: String,
pub app_mode: AppMode,
pub entrypoint: String,
pub program: Vec<u8>,
pub assets: Vec<u8>,
pub asset_table: Vec<AssetEntry>,
pub preload: Vec<PreloadEntry>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CartridgeDTO {
pub app_id: u32,
pub title: String,
pub app_version: String,
pub app_mode: AppMode,
pub entrypoint: String,
pub program: Vec<u8>,
pub assets: Vec<u8>,
#[serde(default)]
pub asset_table: Vec<AssetEntry>,
#[serde(default)]
pub preload: Vec<PreloadEntry>,
}
impl From<CartridgeDTO> for Cartridge {
fn from(dto: CartridgeDTO) -> Self {
Self {
app_id: dto.app_id,
title: dto.title,
app_version: dto.app_version,
app_mode: dto.app_mode,
entrypoint: dto.entrypoint,
program: dto.program,
assets: dto.assets,
asset_table: dto.asset_table,
preload: dto.preload,
}
}
}
#[derive(Debug)]
pub enum CartridgeError {
NotFound,
InvalidFormat,
InvalidManifest,
UnsupportedVersion,
MissingProgram,
IoError,
}
#[derive(Deserialize)]
pub struct CartridgeManifest {
pub magic: String,
pub cartridge_version: u32,
pub app_id: u32,
pub title: String,
pub app_version: String,
pub app_mode: AppMode,
pub entrypoint: String,
#[serde(default)]
pub asset_table: Vec<AssetEntry>,
#[serde(default)]
pub preload: Vec<PreloadEntry>,
}
@@ -0,0 +1,80 @@
use std::fs;
use std::path::Path;
use crate::cartridge::{Cartridge, CartridgeDTO, CartridgeError, CartridgeManifest};
pub struct CartridgeLoader;
impl CartridgeLoader {
pub fn load(path: impl AsRef<Path>) -> Result<Cartridge, CartridgeError> {
let path = path.as_ref();
if !path.exists() {
return Err(CartridgeError::NotFound);
}
if path.is_dir() {
DirectoryCartridgeLoader::load(path)
} else if path.extension().is_some_and(|ext| ext == "pmc") {
PackedCartridgeLoader::load(path)
} else {
Err(CartridgeError::InvalidFormat)
}
}
}
pub struct DirectoryCartridgeLoader;
impl DirectoryCartridgeLoader {
pub fn load(path: &Path) -> Result<Cartridge, CartridgeError> {
let manifest_path = path.join("manifest.json");
if !manifest_path.exists() {
return Err(CartridgeError::InvalidManifest);
}
let manifest_content = fs::read_to_string(manifest_path).map_err(|_| CartridgeError::IoError)?;
let manifest: CartridgeManifest = serde_json::from_str(&manifest_content).map_err(|_| CartridgeError::InvalidManifest)?;
// Additional validation as per requirements
if manifest.magic != "PMTU" {
return Err(CartridgeError::InvalidManifest);
}
if manifest.cartridge_version != 1 {
return Err(CartridgeError::UnsupportedVersion);
}
let program_path = path.join("program.pbc");
if !program_path.exists() {
return Err(CartridgeError::MissingProgram);
}
let program = fs::read(program_path).map_err(|_| CartridgeError::IoError)?;
let assets_pa_path = path.join("assets.pa");
let assets = if assets_pa_path.exists() {
fs::read(assets_pa_path).map_err(|_| CartridgeError::IoError)?
} else {
Vec::new()
};
let dto = CartridgeDTO {
app_id: manifest.app_id,
title: manifest.title,
app_version: manifest.app_version,
app_mode: manifest.app_mode,
entrypoint: manifest.entrypoint,
program,
assets,
asset_table: manifest.asset_table,
preload: manifest.preload,
};
Ok(Cartridge::from(dto))
}
}
pub struct PackedCartridgeLoader;
impl PackedCartridgeLoader {
pub fn load(_path: &Path) -> Result<Cartridge, CartridgeError> {
Err(CartridgeError::InvalidFormat)
}
}
+76
View File
@@ -0,0 +1,76 @@
/// 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)
///
/// 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);
impl Color {
pub const BLACK: Self = Self::rgb(0, 0, 0); // 0x0000
pub const WHITE: Self = Self::rgb(255, 255, 255); // 0xFFFF
pub const RED: Self = Self::rgb(255, 0, 0); // 0xF800
pub const GREEN: Self = Self::rgb(0, 255, 0); // 0x07E0
pub const BLUE: Self = Self::rgb(0, 0, 255); // 0x001F
pub const YELLOW: Self = Self::rgb(255, 255, 0); // 0xFFE0
pub const ORANGE: Self = Self::rgb(255, 128, 0);
pub const INDIGO: Self = Self::rgb(75, 0, 130);
pub const GRAY: Self = Self::rgb(128, 128, 128);
pub const CYAN: Self = Self::rgb(0, 255, 255); // 0x07FF
pub const MAGENTA: Self = Self::rgb(255, 0, 255); // 0xF81F
pub const COLOR_KEY: Self = Self::MAGENTA;
pub const TRANSPARENT: Self = Self::MAGENTA;
/// Extracts channels in the native RGB565 range:
/// R: 0..31, G: 0..63, B: 0..31
#[inline(always)]
pub const fn unpack_to_native(px: u16) -> (u8, u8, u8) {
let r = ((px >> 11) & 0x1F) as u8;
let g = ((px >> 5) & 0x3F) as u8;
let b = (px & 0x1F) as u8;
(r, g, b)
}
/// Packs channels from the native RGB565 range into a pixel:
/// R: 0..31, G: 0..63, B: 0..31
#[inline(always)]
pub const fn pack_from_native(r: u8, g: u8, b: u8) -> u16 {
((r as u16 & 0x1F) << 11) | ((g as u16 & 0x3F) << 5) | (b as u16 & 0x1F)
}
/// Creates an RGB565 color from 8-bit components (0..255).
pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
let r5 = (r as u16 >> 3) & 0x1F;
let g6 = (g as u16 >> 2) & 0x3F;
let b5 = (b as u16 >> 3) & 0x1F;
Self((r5 << 11) | (g6 << 5) | b5)
}
pub const fn gray_scale(c: u8) -> Self {
Self::rgb(c, c, c)
}
pub const fn from_raw(raw: u16) -> Self {
Self(raw)
}
pub const fn raw(self) -> u16 {
self.0
}
pub const fn hex(self) -> i32 {
let (r5, g6, b5) = Self::unpack_to_native(self.0);
let r8 = ((r5 as u32) << 3) | ((r5 as u32) >> 2);
let g8 = ((g6 as u32) << 2) | ((g6 as u32) >> 4);
let b8 = ((b5 as u32) << 3) | ((b5 as u32) >> 2);
let hex = r8 << 16 | g8 << 8 | b8;
hex as i32
}
}
@@ -0,0 +1,145 @@
use serde::{Deserialize, Serialize};
use prometeu_abi::Value;
use crate::cartridge::AppMode;
pub const DEVTOOLS_PROTOCOL_VERSION: u32 = 1;
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum DebugCommand {
#[serde(rename = "ok")]
Ok,
#[serde(rename = "start")]
Start,
#[serde(rename = "pause")]
Pause,
#[serde(rename = "resume")]
Resume,
#[serde(rename = "step")]
Step,
#[serde(rename = "stepFrame")]
StepFrame,
#[serde(rename = "getState")]
GetState,
#[serde(rename = "setBreakpoint")]
SetBreakpoint { pc: usize },
#[serde(rename = "listBreakpoints")]
ListBreakpoints,
#[serde(rename = "clearBreakpoint")]
ClearBreakpoint { pc: usize },
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum DebugResponse {
#[serde(rename = "handshake")]
Handshake {
protocol_version: u32,
runtime_version: String,
cartridge: HandshakeCartridge,
},
#[serde(rename = "getState")]
GetState {
pc: usize,
stack_top: Vec<Value>,
frame_index: u64,
app_id: u32,
},
#[serde(rename = "breakpoints")]
Breakpoints {
pcs: Vec<usize>,
},
}
#[derive(Debug, Serialize, Deserialize)]
pub struct HandshakeCartridge {
pub app_id: u32,
pub title: String,
pub app_version: String,
pub app_mode: AppMode,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "event")]
pub enum DebugEvent {
#[serde(rename = "breakpointHit")]
BreakpointHit {
pc: usize,
frame_index: u64,
},
#[serde(rename = "log")]
Log {
level: String,
source: String,
msg: String,
},
#[serde(rename = "telemetry")]
Telemetry {
frame_index: u64,
vm_steps: u32,
syscalls: u32,
cycles: u64,
cycles_budget: u64,
host_cpu_time_us: u64,
violations: u32,
gfx_used_bytes: usize,
gfx_inflight_bytes: usize,
gfx_slots_occupied: u32,
audio_used_bytes: usize,
audio_inflight_bytes: usize,
audio_slots_occupied: u32,
},
#[serde(rename = "cert")]
Cert {
rule: String,
used: u64,
limit: u64,
frame_index: u64,
},
}
#[cfg(test)]
mod tests {
use super::*;
#[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 {
pc: 42,
stack_top: vec![Value::Int64(10), Value::String("test".into()), Value::Boolean(true)],
frame_index: 5,
app_id: 1,
};
let json = serde_json::to_string(&resp).unwrap();
assert!(json.contains("\"type\":\"getState\""));
assert!(json.contains("\"pc\":42"));
assert!(json.contains("\"stack_top\":[10,\"test\",true]"));
assert!(json.contains("\"frame_index\":5"));
assert!(json.contains("\"app_id\":1"));
}
}
@@ -0,0 +1,53 @@
use crate::color::Color;
use crate::sprite::Sprite;
use crate::tile_layer::{HudTileLayer, ScrollableTileLayer};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BlendMode {
None,
Half,
HalfPlus,
HalfMinus,
Full,
}
pub trait GfxBridge {
fn size(&self) -> (usize, usize);
fn front_buffer(&self) -> &[u16];
fn clear(&mut self, color: Color);
fn fill_rect_blend(&mut self, x: i32, y: i32, w: i32, h: i32, color: Color, mode: BlendMode);
fn fill_rect(&mut self, x: i32, y: i32, w: i32, h: i32, color: Color);
fn draw_pixel(&mut self, x: i32, y: i32, color: Color);
fn draw_line(&mut self, x0: i32, y0: i32, x1: i32, y1: i32, color: Color);
fn draw_circle(&mut self, xc: i32, yc: i32, r: i32, color: Color);
fn draw_circle_points(&mut self, xc: i32, yc: i32, x: i32, y: i32, color: Color);
fn fill_circle(&mut self, xc: i32, yc: i32, r: i32, color: Color);
fn draw_circle_lines(&mut self, xc: i32, yc: i32, x: i32, y: i32, color: Color);
fn draw_disc(&mut self, x: i32, y: i32, r: i32, border_color: Color, fill_color: Color);
fn draw_rect(&mut self, x: i32, y: i32, w: i32, h: i32, color: Color);
fn draw_square(&mut self, x: i32, y: i32, w: i32, h: i32, border_color: Color, fill_color: Color);
fn draw_horizontal_line(&mut self, x0: i32, x1: i32, y: i32, color: Color);
fn draw_vertical_line(&mut self, x: i32, y0: i32, y1: i32, color: Color);
fn present(&mut self);
fn render_all(&mut self);
fn render_layer(&mut self, layer_idx: usize);
fn render_hud(&mut self);
fn draw_text(&mut self, x: i32, y: i32, text: &str, color: Color);
fn draw_char(&mut self, x: i32, y: i32, c: char, color: Color);
fn layer(&self, index: usize) -> &ScrollableTileLayer;
fn layer_mut(&mut self, index: usize) -> &mut ScrollableTileLayer;
fn hud(&self) -> &HudTileLayer;
fn hud_mut(&mut self) -> &mut HudTileLayer;
fn sprite(&self, index: usize) -> &Sprite;
fn sprite_mut(&mut self, index: usize) -> &mut Sprite;
fn scene_fade_level(&self) -> u8;
fn set_scene_fade_level(&mut self, level: u8);
fn scene_fade_color(&self) -> Color;
fn set_scene_fade_color(&mut self, color: Color);
fn hud_fade_level(&self) -> u8;
fn set_hud_fade_level(&mut self, level: u8);
fn hud_fade_color(&self) -> Color;
fn set_hud_fade_color(&mut self, color: Color);
}
@@ -0,0 +1,22 @@
use crate::asset_bridge::AssetBridge;
use crate::audio_bridge::AudioBridge;
use crate::gfx_bridge::GfxBridge;
use crate::pad_bridge::PadBridge;
use crate::touch_bridge::TouchBridge;
pub trait HardwareBridge {
fn gfx(&self) -> &dyn GfxBridge;
fn gfx_mut(&mut self) -> &mut dyn GfxBridge;
fn audio(&self) -> &dyn AudioBridge;
fn audio_mut(&mut self) -> &mut dyn AudioBridge;
fn pad(&self) -> &dyn PadBridge;
fn pad_mut(&mut self) -> &mut dyn PadBridge;
fn touch(&self) -> &dyn TouchBridge;
fn touch_mut(&mut self) -> &mut dyn TouchBridge;
fn assets(&self) -> &dyn AssetBridge;
fn assets_mut(&mut self) -> &mut dyn AssetBridge;
}
@@ -0,0 +1,24 @@
use prometeu_abi::VmFault;
use crate::hardware_bridge::HardwareBridge;
pub struct HostContext<'a> {
pub hw: Option<&'a mut dyn HardwareBridge>,
}
impl<'a> HostContext<'a> {
pub fn new(hw: Option<&'a mut dyn HardwareBridge>) -> Self {
Self { hw }
}
#[inline]
pub fn require_hw(&mut self) -> Result<&mut dyn HardwareBridge, VmFault> {
match &mut self.hw {
Some(hw) => Ok(*hw),
None => Err(VmFault::Unavailable),
}
}
}
pub trait HostContextProvider {
fn make_ctx(&'_ mut self) -> HostContext<'_>;
}
@@ -0,0 +1,34 @@
use prometeu_abi::Value;
use prometeu_abi::VmFault;
pub struct HostReturn<'a> {
stack: &'a mut Vec<Value>
}
impl<'a> HostReturn<'a> {
pub fn new(stack: &'a mut Vec<Value>) -> Self {
Self { stack }
}
pub fn push_bool(&mut self, v: bool) {
self.stack.push(Value::Boolean(v));
}
pub fn push_int(&mut self, v: i64) {
self.stack.push(Value::Int64(v));
}
pub fn push_bounded(&mut self, v: u32) -> Result<(), VmFault> {
if v > 0xFFFF {
return Err(VmFault::Trap(prometeu_bytecode::abi::TRAP_OOB, "Bounded value overflow".into()));
}
self.stack.push(Value::Bounded(v));
Ok(())
}
pub fn push_null(&mut self) {
self.stack.push(Value::Null);
}
pub fn push_gate(&mut self, g: usize) {
self.stack.push(Value::Gate(g));
}
pub fn push_string(&mut self, s: String) {
self.stack.push(Value::String(s));
}
}
@@ -0,0 +1,23 @@
#[derive(Default, Clone, Copy, Debug)]
pub struct InputSignals {
// PAD
pub up_signal: bool,
pub down_signal: bool,
pub left_signal: bool,
pub right_signal: bool,
pub a_signal: bool,
pub b_signal: bool,
pub x_signal: bool,
pub y_signal: bool,
pub l_signal: bool,
pub r_signal: bool,
pub start_signal: bool,
pub select_signal: bool,
// TOUCH
pub f_signal: bool,
pub x_pos: i32,
pub y_pos: i32,
}
+39
View File
@@ -0,0 +1,39 @@
pub mod asset_bridge;
pub mod audio_bridge;
pub mod gfx_bridge;
pub mod hardware_bridge;
pub mod host_context;
pub mod host_return;
pub mod native_interface;
pub mod pad_bridge;
pub mod touch_bridge;
pub mod native_helpers;
pub mod input_signals;
pub mod cartridge;
pub mod cartridge_loader;
pub mod debugger_protocol;
pub mod asset;
pub mod color;
pub mod button;
pub mod tile;
pub mod tile_layer;
pub mod tile_bank;
pub mod sound_bank;
pub mod sprite;
pub mod sample;
pub mod window;
pub mod syscalls;
pub mod telemetry;
pub mod log;
pub use asset_bridge::AssetBridge;
pub use audio_bridge::{AudioBridge, LoopMode};
pub use gfx_bridge::{BlendMode, GfxBridge};
pub use hardware_bridge::HardwareBridge;
pub use host_context::{HostContext, HostContextProvider};
pub use host_return::HostReturn;
pub use input_signals::InputSignals;
pub use native_interface::{NativeInterface, SyscallId};
pub use pad_bridge::PadBridge;
pub use touch_bridge::TouchBridge;
pub use native_helpers::{expect_bool, expect_bounded, expect_int};
@@ -0,0 +1,12 @@
use crate::log::{LogLevel, LogSource};
#[derive(Debug, Clone)]
pub struct LogEvent {
pub seq: u64,
pub ts_ms: u64,
pub frame: u64,
pub level: LogLevel,
pub source: LogSource,
pub tag: u16,
pub msg: String,
}
@@ -0,0 +1,8 @@
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogLevel {
Trace,
Debug,
Info,
Warn,
Error,
}
@@ -0,0 +1,93 @@
use std::collections::VecDeque;
use crate::log::{LogEvent, LogLevel, LogSource};
pub struct LogService {
events: VecDeque<LogEvent>,
capacity: usize,
next_seq: u64,
}
impl LogService {
pub fn new(capacity: usize) -> Self {
Self {
events: VecDeque::with_capacity(capacity),
capacity,
next_seq: 0,
}
}
pub fn log(&mut self, ts_ms: u64, frame: u64, level: LogLevel, source: LogSource, tag: u16, msg: String) {
if self.events.len() >= self.capacity {
self.events.pop_front();
}
self.events.push_back(LogEvent {
seq: self.next_seq,
ts_ms,
frame,
level,
source,
tag,
msg,
});
self.next_seq += 1;
}
pub fn get_recent(&self, n: usize) -> Vec<LogEvent> {
self.events.iter().rev().take(n).cloned().collect::<Vec<_>>().into_iter().rev().collect()
}
pub fn get_after(&self, seq: u64) -> Vec<LogEvent> {
self.events.iter().filter(|e| e.seq > seq).cloned().collect()
}
pub fn last_seq(&self) -> Option<u64> {
self.events.back().map(|e| e.seq)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_ring_buffer_capacity() {
let mut service = LogService::new(3);
service.log(100, 1, LogLevel::Info, LogSource::Pos, 0, "Log 1".to_string());
service.log(110, 1, LogLevel::Info, LogSource::Pos, 0, "Log 2".to_string());
service.log(120, 1, LogLevel::Info, LogSource::Pos, 0, "Log 3".to_string());
assert_eq!(service.events.len(), 3);
assert_eq!(service.events[0].msg, "Log 1");
service.log(130, 1, LogLevel::Info, LogSource::Pos, 0, "Log 4".to_string());
assert_eq!(service.events.len(), 3);
assert_eq!(service.events[0].msg, "Log 2");
assert_eq!(service.events[2].msg, "Log 4");
}
#[test]
fn test_get_recent() {
let mut service = LogService::new(10);
for i in 0..5 {
service.log(i as u64, 1, LogLevel::Info, LogSource::Pos, 0, format!("Log {}", i));
}
let recent = service.get_recent(2);
assert_eq!(recent.len(), 2);
assert_eq!(recent[0].msg, "Log 3");
assert_eq!(recent[1].msg, "Log 4");
}
#[test]
fn test_get_after() {
let mut service = LogService::new(10);
for i in 0..5 {
service.log(i as u64, 1, LogLevel::Info, LogSource::Pos, 0, format!("Log {}", i));
}
let after = service.get_after(2); // seqs are 0, 1, 2, 3, 4. Should return 3 and 4.
assert_eq!(after.len(), 2);
assert_eq!(after[0].msg, "Log 3");
assert_eq!(after[1].msg, "Log 4");
}
}
@@ -0,0 +1,8 @@
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogSource {
Pos,
Hub,
Vm,
Fs,
App { app_id: u32 },
}
@@ -0,0 +1,9 @@
mod log_level;
mod log_source;
mod log_event;
mod log_service;
pub use log_event::LogEvent;
pub use log_level::LogLevel;
pub use log_service::LogService;
pub use log_source::LogSource;
@@ -0,0 +1,26 @@
use prometeu_abi::Value;
use prometeu_abi::VmFault;
pub fn expect_bounded(args: &[Value], idx: usize) -> Result<u32, VmFault> {
args.get(idx)
.and_then(|v| match v {
Value::Bounded(b) => Some(*b),
_ => None,
})
.ok_or_else(|| VmFault::Trap(prometeu_bytecode::abi::TRAP_TYPE, format!("Expected bounded at index {}", idx)))
}
pub fn expect_int(args: &[Value], idx: usize) -> Result<i64, VmFault> {
args.get(idx)
.and_then(|v| v.as_integer())
.ok_or_else(|| VmFault::Trap(prometeu_bytecode::abi::TRAP_TYPE, format!("Expected integer at index {}", idx)))
}
pub fn expect_bool(args: &[Value], idx: usize) -> Result<bool, VmFault> {
args.get(idx)
.and_then(|v| match v {
Value::Boolean(b) => Some(*b),
_ => None,
})
.ok_or_else(|| VmFault::Trap(prometeu_bytecode::abi::TRAP_TYPE, format!("Expected boolean at index {}", idx)))
}
@@ -0,0 +1,14 @@
use prometeu_abi::{Value, VmFault};
use crate::host_context::HostContext;
use crate::host_return::HostReturn;
pub type SyscallId = u32;
pub trait NativeInterface {
/// Dispatches a syscall from the Virtual Machine to the native implementation.
///
/// ABI Rule: Arguments for the syscall are passed in `args`.
///
/// Returns are written via `ret`.
fn syscall(&mut self, id: SyscallId, args: &[Value], ret: &mut HostReturn, ctx: &mut HostContext) -> Result<(), VmFault>;
}
@@ -0,0 +1,20 @@
use crate::button::Button;
use crate::input_signals::InputSignals;
pub trait PadBridge {
fn begin_frame(&mut self, signals: &InputSignals);
fn any(&self) -> bool;
fn up(&self) -> &Button;
fn down(&self) -> &Button;
fn left(&self) -> &Button;
fn right(&self) -> &Button;
fn a(&self) -> &Button;
fn b(&self) -> &Button;
fn x(&self) -> &Button;
fn y(&self) -> &Button;
fn l(&self) -> &Button;
fn r(&self) -> &Button;
fn start(&self) -> &Button;
fn select(&self) -> &Button;
}
+27
View File
@@ -0,0 +1,27 @@
pub struct Sample {
pub sample_rate: u32,
pub data: Vec<i16>,
pub loop_start: Option<u32>,
pub loop_end: Option<u32>,
}
impl Sample {
pub fn new(sample_rate: u32, data: Vec<i16>) -> Self {
Self {
sample_rate,
data,
loop_start: None,
loop_end: None,
}
}
pub fn with_loop(mut self, start: u32, end: u32) -> Self {
self.loop_start = Some(start);
self.loop_end = Some(end);
self
}
pub fn frames_len(&self) -> usize {
self.data.len()
}
}
@@ -0,0 +1,16 @@
use std::sync::Arc;
use crate::sample::Sample;
/// A container for audio assets.
///
/// A SoundBank stores multiple audio samples that can be played by the
/// audio subsystem.
pub struct SoundBank {
pub samples: Vec<Arc<Sample>>,
}
impl SoundBank {
pub fn new(samples: Vec<Arc<Sample>>) -> Self {
Self { samples }
}
}
+13
View File
@@ -0,0 +1,13 @@
use crate::tile::Tile;
#[derive(Clone, Copy, Debug, Default)]
pub struct Sprite {
pub tile: Tile,
pub x: i32,
pub y: i32,
pub bank_id: u8,
pub active: bool,
pub flip_x: bool,
pub flip_y: bool,
pub priority: u8,
}
+381
View File
@@ -0,0 +1,381 @@
/// 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 ---
/// Checks if a cartridge is currently inserted in the virtual slot.
SystemHasCart = 0x0001,
/// Requests the OS to launch a specific cartridge.
SystemRunCart = 0x0002,
// --- 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,
/// Draws a text string at the specified coordinates.
GfxDrawText = 0x1008,
/// Fills the entire back buffer with a single RGB565 color (flattened).
GfxClear565 = 0x1010,
// --- 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 full snapshot of the gamepad state (48 slots).
InputPadSnapshot = 0x2010,
/// Returns the full snapshot of the touch state (6 slots).
InputTouchSnapshot = 0x2011,
/// 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,
/// Returns the full Button struct (6 bytes) for the touch finger state.
TouchGetFinger = 0x2107,
// --- Input (Pad service-based) ---
/// Returns the full Button struct (6 bytes) for each gamepad button
PadGetUp = 0x2200,
PadGetDown = 0x2201,
PadGetLeft = 0x2202,
PadGetRight = 0x2203,
PadGetA = 0x2204,
PadGetB = 0x2205,
PadGetX = 0x2206,
PadGetY = 0x2207,
PadGetL = 0x2208,
PadGetR = 0x2209,
PadGetStart = 0x220A,
PadGetSelect = 0x220B,
// --- Audio ---
/// Starts playback of a sound sample by its Bank and ID.
AudioPlaySample = 0x3001,
/// Low-level audio play command.
AudioPlay = 0x3002,
// --- 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 ---
/// 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 (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 (Memory) ---
/// Returns information about a specific Memory Bank.
BankInfo = 0x6101,
/// Returns information about a slot within a Memory Bank.
BankSlotInfo = 0x6102,
}
impl Syscall {
pub fn from_u32(id: u32) -> Option<Self> {
match id {
0x0001 => Some(Self::SystemHasCart),
0x0002 => Some(Self::SystemRunCart),
0x1001 => Some(Self::GfxClear),
0x1002 => Some(Self::GfxFillRect),
0x1003 => Some(Self::GfxDrawLine),
0x1004 => Some(Self::GfxDrawCircle),
0x1005 => Some(Self::GfxDrawDisc),
0x1006 => Some(Self::GfxDrawSquare),
0x1007 => Some(Self::GfxSetSprite),
0x1008 => Some(Self::GfxDrawText),
0x1010 => Some(Self::GfxClear565),
0x2001 => Some(Self::InputGetPad),
0x2002 => Some(Self::InputGetPadPressed),
0x2003 => Some(Self::InputGetPadReleased),
0x2004 => Some(Self::InputGetPadHold),
0x2010 => Some(Self::InputPadSnapshot),
0x2011 => Some(Self::InputTouchSnapshot),
0x2101 => Some(Self::TouchGetX),
0x2102 => Some(Self::TouchGetY),
0x2103 => Some(Self::TouchIsDown),
0x2104 => Some(Self::TouchIsPressed),
0x2105 => Some(Self::TouchIsReleased),
0x2106 => Some(Self::TouchGetHold),
0x2107 => Some(Self::TouchGetFinger),
0x2200 => Some(Self::PadGetUp),
0x2201 => Some(Self::PadGetDown),
0x2202 => Some(Self::PadGetLeft),
0x2203 => Some(Self::PadGetRight),
0x2204 => Some(Self::PadGetA),
0x2205 => Some(Self::PadGetB),
0x2206 => Some(Self::PadGetX),
0x2207 => Some(Self::PadGetY),
0x2208 => Some(Self::PadGetL),
0x2209 => Some(Self::PadGetR),
0x220A => Some(Self::PadGetStart),
0x220B => Some(Self::PadGetSelect),
0x3001 => Some(Self::AudioPlaySample),
0x3002 => Some(Self::AudioPlay),
0x4001 => Some(Self::FsOpen),
0x4002 => Some(Self::FsRead),
0x4003 => Some(Self::FsWrite),
0x4004 => Some(Self::FsClose),
0x4005 => Some(Self::FsListDir),
0x4006 => Some(Self::FsExists),
0x4007 => Some(Self::FsDelete),
0x5001 => Some(Self::LogWrite),
0x5002 => Some(Self::LogWriteTag),
0x6001 => Some(Self::AssetLoad),
0x6002 => Some(Self::AssetStatus),
0x6003 => Some(Self::AssetCommit),
0x6004 => Some(Self::AssetCancel),
0x6101 => Some(Self::BankInfo),
0x6102 => Some(Self::BankSlotInfo),
_ => None,
}
}
pub fn args_count(&self) -> usize {
match self {
Self::SystemHasCart => 0,
Self::SystemRunCart => 0,
Self::GfxClear => 1,
Self::GfxFillRect => 5,
Self::GfxDrawLine => 5,
Self::GfxDrawCircle => 4,
Self::GfxDrawDisc => 5,
Self::GfxDrawSquare => 6,
Self::GfxSetSprite => 10,
Self::GfxDrawText => 4,
Self::GfxClear565 => 1,
Self::InputGetPad => 1,
Self::InputGetPadPressed => 1,
Self::InputGetPadReleased => 1,
Self::InputGetPadHold => 1,
Self::InputPadSnapshot => 0,
Self::InputTouchSnapshot => 0,
Self::TouchGetX => 0,
Self::TouchGetY => 0,
Self::TouchIsDown => 0,
Self::TouchIsPressed => 0,
Self::TouchIsReleased => 0,
Self::TouchGetHold => 0,
Self::TouchGetFinger => 0,
Self::PadGetUp => 0,
Self::PadGetDown => 0,
Self::PadGetLeft => 0,
Self::PadGetRight => 0,
Self::PadGetA => 0,
Self::PadGetB => 0,
Self::PadGetX => 0,
Self::PadGetY => 0,
Self::PadGetL => 0,
Self::PadGetR => 0,
Self::PadGetStart => 0,
Self::PadGetSelect => 0,
Self::AudioPlaySample => 5,
Self::AudioPlay => 7,
Self::FsOpen => 1,
Self::FsRead => 1,
Self::FsWrite => 2,
Self::FsClose => 1,
Self::FsListDir => 1,
Self::FsExists => 1,
Self::FsDelete => 1,
Self::LogWrite => 2,
Self::LogWriteTag => 3,
Self::AssetLoad => 3,
Self::AssetStatus => 1,
Self::AssetCommit => 1,
Self::AssetCancel => 1,
Self::BankInfo => 1,
Self::BankSlotInfo => 2,
}
}
pub fn results_count(&self) -> usize {
match self {
// --- System ---
Self::SystemHasCart => 1,
Self::SystemRunCart => 0,
// --- GFX (void) ---
Self::GfxClear => 0,
Self::GfxFillRect => 0,
Self::GfxDrawLine => 0,
Self::GfxDrawCircle => 0,
Self::GfxDrawDisc => 0,
Self::GfxDrawSquare => 0,
Self::GfxSetSprite => 0,
Self::GfxDrawText => 0,
Self::GfxClear565 => 0,
// --- Input (scalar/snapshots) ---
Self::InputGetPad => 1,
Self::InputGetPadPressed => 1,
Self::InputGetPadReleased => 1,
Self::InputGetPadHold => 1,
Self::InputPadSnapshot => 48,
Self::InputTouchSnapshot => 6,
// --- Touch (scalars/struct) ---
Self::TouchGetX => 1,
Self::TouchGetY => 1,
Self::TouchIsDown => 1,
Self::TouchIsPressed => 1,
Self::TouchIsReleased => 1,
Self::TouchGetHold => 1,
Self::TouchGetFinger => 4, // Button struct (4 slots)
// --- Pad (per-button struct: 4 slots) ---
Self::PadGetUp
| Self::PadGetDown
| Self::PadGetLeft
| Self::PadGetRight
| Self::PadGetA
| Self::PadGetB
| Self::PadGetX
| Self::PadGetY
| Self::PadGetL
| Self::PadGetR
| Self::PadGetStart
| Self::PadGetSelect => 4,
// --- Audio (void) ---
Self::AudioPlaySample => 0,
Self::AudioPlay => 0,
// --- FS ---
Self::FsOpen => 1,
Self::FsRead => 1, // bytes read
Self::FsWrite => 1, // bytes written
Self::FsClose => 0,
Self::FsListDir => 1, // entries count/handle (TBD)
Self::FsExists => 1,
Self::FsDelete => 0,
// --- Log (void) ---
Self::LogWrite | Self::LogWriteTag => 0,
// --- Asset/Bank (conservador) ---
Self::AssetLoad => 1,
Self::AssetStatus => 1,
Self::AssetCommit => 0,
Self::AssetCancel => 0,
Self::BankInfo => 1,
Self::BankSlotInfo => 1,
}
}
pub fn name(&self) -> &'static str {
match self {
Self::SystemHasCart => "SystemHasCart",
Self::SystemRunCart => "SystemRunCart",
Self::GfxClear => "GfxClear",
Self::GfxFillRect => "GfxFillRect",
Self::GfxDrawLine => "GfxDrawLine",
Self::GfxDrawCircle => "GfxDrawCircle",
Self::GfxDrawDisc => "GfxDrawDisc",
Self::GfxDrawSquare => "GfxDrawSquare",
Self::GfxSetSprite => "GfxSetSprite",
Self::GfxDrawText => "GfxDrawText",
Self::GfxClear565 => "GfxClear565",
Self::InputGetPad => "InputGetPad",
Self::InputGetPadPressed => "InputGetPadPressed",
Self::InputGetPadReleased => "InputGetPadReleased",
Self::InputGetPadHold => "InputGetPadHold",
Self::InputPadSnapshot => "InputPadSnapshot",
Self::InputTouchSnapshot => "InputTouchSnapshot",
Self::TouchGetX => "TouchGetX",
Self::TouchGetY => "TouchGetY",
Self::TouchIsDown => "TouchIsDown",
Self::TouchIsPressed => "TouchIsPressed",
Self::TouchIsReleased => "TouchIsReleased",
Self::TouchGetHold => "TouchGetHold",
Self::TouchGetFinger => "TouchGetFinger",
Self::PadGetUp => "PadGetUp",
Self::PadGetDown => "PadGetDown",
Self::PadGetLeft => "PadGetLeft",
Self::PadGetRight => "PadGetRight",
Self::PadGetA => "PadGetA",
Self::PadGetB => "PadGetB",
Self::PadGetX => "PadGetX",
Self::PadGetY => "PadGetY",
Self::PadGetL => "PadGetL",
Self::PadGetR => "PadGetR",
Self::PadGetStart => "PadGetStart",
Self::PadGetSelect => "PadGetSelect",
Self::AudioPlaySample => "AudioPlaySample",
Self::AudioPlay => "AudioPlay",
Self::FsOpen => "FsOpen",
Self::FsRead => "FsRead",
Self::FsWrite => "FsWrite",
Self::FsClose => "FsClose",
Self::FsListDir => "FsListDir",
Self::FsExists => "FsExists",
Self::FsDelete => "FsDelete",
Self::LogWrite => "LogWrite",
Self::LogWriteTag => "LogWriteTag",
Self::AssetLoad => "AssetLoad",
Self::AssetStatus => "AssetStatus",
Self::AssetCommit => "AssetCommit",
Self::AssetCancel => "AssetCancel",
Self::BankInfo => "BankInfo",
Self::BankSlotInfo => "BankSlotInfo",
}
}
}
@@ -0,0 +1,123 @@
use crate::log::{LogLevel, LogService, LogSource};
#[derive(Debug, Clone, Copy, Default)]
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,
// GFX Banks
pub gfx_used_bytes: usize,
pub gfx_inflight_bytes: usize,
pub gfx_slots_occupied: u32,
// Audio Banks
pub audio_used_bytes: usize,
pub audio_inflight_bytes: usize,
pub audio_slots_occupied: u32,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct CertificationConfig {
pub enabled: bool,
pub cycles_budget_per_frame: Option<u64>,
pub max_syscalls_per_frame: Option<u32>,
pub max_host_cpu_us_per_frame: Option<u64>,
}
pub struct Certifier {
pub config: CertificationConfig,
}
impl Certifier {
pub fn new(config: CertificationConfig) -> Self {
Self { config }
}
pub fn evaluate(&self, telemetry: &TelemetryFrame, log_service: &mut LogService, ts_ms: u64) -> usize {
if !self.config.enabled {
return 0;
}
let mut violations = 0;
if let Some(budget) = self.config.cycles_budget_per_frame {
if telemetry.cycles_used > budget {
log_service.log(
ts_ms,
telemetry.frame_index,
LogLevel::Warn,
LogSource::Pos,
0xCA01,
format!("Cert: cycles_used exceeded budget ({} > {})", telemetry.cycles_used, budget),
);
violations += 1;
}
}
if let Some(limit) = self.config.max_syscalls_per_frame {
if telemetry.syscalls > limit {
log_service.log(
ts_ms,
telemetry.frame_index,
LogLevel::Warn,
LogSource::Pos,
0xCA02,
format!("Cert: syscalls per frame exceeded limit ({} > {})", telemetry.syscalls, limit),
);
violations += 1;
}
}
if let Some(limit) = self.config.max_host_cpu_us_per_frame {
if telemetry.host_cpu_time_us > limit {
log_service.log(
ts_ms,
telemetry.frame_index,
LogLevel::Warn,
LogSource::Pos,
0xCA03,
format!("Cert: host_cpu_time_us exceeded limit ({} > {})", telemetry.host_cpu_time_us, limit),
);
violations += 1;
}
}
violations
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::log::LogService;
#[test]
fn test_certifier_violations() {
let config = CertificationConfig {
enabled: true,
cycles_budget_per_frame: Some(100),
max_syscalls_per_frame: Some(5),
max_host_cpu_us_per_frame: Some(1000),
};
let cert = Certifier::new(config);
let mut ls = LogService::new(10);
let mut tel = TelemetryFrame::default();
tel.cycles_used = 150;
tel.syscalls = 10;
tel.host_cpu_time_us = 500;
let violations = cert.evaluate(&tel, &mut ls, 1000);
assert_eq!(violations, 2);
let logs = ls.get_recent(10);
assert_eq!(logs.len(), 2);
assert!(logs[0].msg.contains("cycles_used"));
assert!(logs[1].msg.contains("syscalls"));
}
}
+7
View File
@@ -0,0 +1,7 @@
#[derive(Clone, Copy, Debug, Default)]
pub struct Tile {
pub id: u16,
pub flip_x: bool,
pub flip_y: bool,
pub palette_id: u8,
}
@@ -0,0 +1,75 @@
use crate::color::Color;
/// Standard sizes for square tiles.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TileSize {
/// 8x8 pixels.
Size8 = 8,
/// 16x16 pixels.
Size16 = 16,
/// 32x32 pixels.
Size32 = 32,
}
/// A container for graphical assets.
///
/// A TileBank stores both the raw pixel data (as palette indices) and the
/// color palettes themselves. This encapsulates all the information needed
/// to render a set of tiles.
pub struct TileBank {
/// Dimension of each individual tile in the bank.
pub tile_size: TileSize,
/// Width of the full bank sheet in pixels.
pub width: usize,
/// Height of the full bank sheet in pixels.
pub height: usize,
/// Pixel data stored as 4-bit indices (packed into 8-bit values).
/// Index 0 is always reserved for transparency.
pub pixel_indices: Vec<u8>,
/// Table of 64 palettes, each containing 16 RGB565 colors, total of 1024 colors for a bank.
pub palettes: [[Color; 16]; 64],
}
impl TileBank {
/// Creates an empty tile bank with the specified dimensions.
pub fn new(tile_size: TileSize, width: usize, height: usize) -> Self {
Self {
tile_size,
width,
height,
pixel_indices: vec![0; width * height], // Index 0 = Transparent
palettes: [[Color::BLACK; 16]; 64],
}
}
/// Resolves a global tile ID and local pixel coordinates to a palette index.
/// tile_id: the tile index in the bank
/// local_x, local_y: the pixel position inside the tile (0 to tile_size-1)
pub fn get_pixel_index(&self, tile_id: u16, local_x: usize, local_y: usize) -> u8 {
let size = self.tile_size as usize;
let tiles_per_row = self.width / size;
let tile_x = (tile_id as usize % tiles_per_row) * size;
let tile_y = (tile_id as usize / tiles_per_row) * size;
let pixel_x = tile_x + local_x;
let pixel_y = tile_y + local_y;
if pixel_x < self.width && pixel_y < self.height {
self.pixel_indices[pixel_y * self.width + pixel_x]
} else {
0 // Default to transparent if out of bounds
}
}
/// Maps a 4-bit index to a real RGB565 Color using the specified palette.
pub fn resolve_color(&self, palette_id: u8, pixel_index: u8) -> Color {
// Hardware Rule: Index 0 is always transparent.
// We use Magenta as the 'transparent' signal color during composition.
if pixel_index == 0 {
return Color::COLOR_KEY;
}
self.palettes[palette_id as usize][pixel_index as usize]
}
}
@@ -0,0 +1,109 @@
use crate::tile::Tile;
use crate::tile_bank::TileSize;
use crate::tile_bank::TileSize::Size8;
pub struct TileMap {
pub width: usize,
pub height: usize,
pub tiles: Vec<Tile>,
}
impl TileMap {
fn create(width: usize, height: usize) -> Self {
Self {
width,
height,
tiles: vec![Tile::default(); width * height],
}
}
pub fn set_tile(&mut self, x: usize, y: usize, tile: Tile) {
if x < self.width && y < self.height {
self.tiles[y * self.width + x] = tile;
}
}
}
pub struct TileLayer {
pub bank_id: u8,
pub tile_size: TileSize,
pub map: TileMap,
}
impl TileLayer {
fn create(width: usize, height: usize, tile_size: TileSize) -> Self {
Self {
bank_id: 0,
tile_size,
map: TileMap::create(width, height),
}
}
}
impl std::ops::Deref for TileLayer {
type Target = TileMap;
fn deref(&self) -> &Self::Target {
&self.map
}
}
impl std::ops::DerefMut for TileLayer {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.map
}
}
pub struct ScrollableTileLayer {
pub layer: TileLayer,
pub scroll_x: i32,
pub scroll_y: i32,
}
impl ScrollableTileLayer {
pub fn new(width: usize, height: usize, tile_size: TileSize) -> Self {
Self {
layer: TileLayer::create(width, height, tile_size),
scroll_x: 0,
scroll_y: 0,
}
}
}
impl std::ops::Deref for ScrollableTileLayer {
type Target = TileLayer;
fn deref(&self) -> &Self::Target {
&self.layer
}
}
impl std::ops::DerefMut for ScrollableTileLayer {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.layer
}
}
pub struct HudTileLayer {
pub layer: TileLayer,
}
impl HudTileLayer {
pub fn new(width: usize, height: usize) -> Self {
Self {
layer: TileLayer::create(width, height, Size8),
}
}
}
impl std::ops::Deref for HudTileLayer {
type Target = TileLayer;
fn deref(&self) -> &Self::Target {
&self.layer
}
}
impl std::ops::DerefMut for HudTileLayer {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.layer
}
}
@@ -0,0 +1,9 @@
use crate::input_signals::InputSignals;
use crate::button::Button;
pub trait TouchBridge {
fn begin_frame(&mut self, signals: &InputSignals);
fn f(&self) -> &Button;
fn x(&self) -> i32;
fn y(&self) -> i32;
}
+21
View File
@@ -0,0 +1,21 @@
use crate::color::Color;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Rect {
pub x: i32,
pub y: i32,
pub w: i32,
pub h: i32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct WindowId(pub u32);
#[derive(Debug, Clone)]
pub struct Window {
pub id: WindowId,
pub viewport: Rect,
pub has_focus: bool,
pub title: String,
pub color: Color,
}