dev/ajustments-asset-entry (#12)
Intrepid/Prometeu/Runtime/pipeline/head This commit looks good

Reviewed-on: #12
Co-authored-by: bQUARKz <bquarkz@gmail.com>
Co-committed-by: bQUARKz <bquarkz@gmail.com>
This commit was merged in pull request #12.
This commit is contained in:
2026-04-10 05:31:57 +00:00
committed by bquarkz
parent c4aca95635
commit 035e9d5676
32 changed files with 584 additions and 813 deletions
+132 -141
View File
@@ -1,25 +1,25 @@
#![allow(clippy::collapsible_if)]
use crate::memory_banks::{SoundBankPoolInstaller, TileBankPoolInstaller};
use crate::memory_banks::{GlyphBankPoolInstaller, SoundBankPoolInstaller};
use prometeu_hal::AssetBridge;
use prometeu_hal::asset::{
AssetEntry, AssetId, AssetLoadError, AssetOpStatus, BankStats, BankType, HandleId, LoadStatus,
PreloadEntry, SlotRef, SlotStats,
AssetCodec, AssetEntry, AssetId, AssetLoadError, AssetOpStatus, BankStats, BankType, HandleId,
LoadStatus, PreloadEntry, SlotRef, SlotStats,
};
use prometeu_hal::cartridge::AssetsPayloadSource;
use prometeu_hal::color::Color;
use prometeu_hal::glyph_bank::{GlyphBank, TileSize};
use prometeu_hal::sample::Sample;
use prometeu_hal::sound_bank::SoundBank;
use prometeu_hal::tile_bank::{TileBank, TileSize};
use std::collections::HashMap;
use std::io::Read;
use std::sync::{Arc, Mutex, RwLock};
use std::thread;
use std::time::Instant;
const TILE_BANK_PALETTE_COUNT_V1: usize = 64;
const TILE_BANK_COLORS_PER_PALETTE: usize = 16;
const TILE_BANK_PALETTE_BYTES_V1: usize =
TILE_BANK_PALETTE_COUNT_V1 * TILE_BANK_COLORS_PER_PALETTE * std::mem::size_of::<u16>();
const GLYPH_BANK_PALETTE_COUNT_V1: usize = 64;
const GLYPH_BANK_COLORS_PER_PALETTE: usize = 16;
const GLYPH_BANK_PALETTE_BYTES_V1: usize =
GLYPH_BANK_PALETTE_COUNT_V1 * GLYPH_BANK_COLORS_PER_PALETTE * std::mem::size_of::<u16>();
/// Resident metadata for a decoded/materialized asset inside a BankPolicy.
#[derive(Debug)]
@@ -115,15 +115,15 @@ pub struct AssetManager {
assets_data: Arc<RwLock<AssetsPayloadSource>>,
/// Narrow hardware interfaces
gfx_installer: Arc<dyn TileBankPoolInstaller>,
gfx_installer: Arc<dyn GlyphBankPoolInstaller>,
sound_installer: Arc<dyn SoundBankPoolInstaller>,
/// Track what is installed in each hardware slot (for stats/info).
gfx_slots: Arc<RwLock<[Option<AssetId>; 16]>>,
sound_slots: Arc<RwLock<[Option<AssetId>; 16]>>,
/// Residency policy for GFX tile banks.
gfx_policy: BankPolicy<TileBank>,
/// Residency policy for GFX glyph banks.
gfx_policy: BankPolicy<GlyphBank>,
/// Residency policy for sound banks.
sound_policy: BankPolicy<SoundBank>,
@@ -179,55 +179,44 @@ impl AssetBridge for AssetManager {
}
impl AssetManager {
fn codec_is_none_or_legacy_raw(codec: &str) -> bool {
matches!(codec, "NONE" | "RAW")
}
fn decode_tile_bank_layout(
fn decode_glyph_bank_layout(
entry: &AssetEntry,
) -> Result<(TileSize, usize, usize, usize), String> {
let tile_size_val =
entry.metadata.get("tile_size").and_then(|v| v.as_u64()).ok_or("Missing tile_size")?;
let width =
entry.metadata.get("width").and_then(|v| v.as_u64()).ok_or("Missing width")? as usize;
let height =
entry.metadata.get("height").and_then(|v| v.as_u64()).ok_or("Missing height")? as usize;
let palette_count = entry
.metadata
.get("palette_count")
.and_then(|v| v.as_u64())
.ok_or("Missing palette_count")? as usize;
let meta = entry.metadata_as_glyph_bank()?;
let tile_size = match tile_size_val {
let tile_size = match meta.tile_size {
8 => TileSize::Size8,
16 => TileSize::Size16,
32 => TileSize::Size32,
_ => return Err(format!("Invalid tile_size: {}", tile_size_val)),
_ => return Err(format!("Invalid tile_size: {}", meta.tile_size)),
};
if palette_count != TILE_BANK_PALETTE_COUNT_V1 {
return Err(format!("Invalid palette_count: {}", palette_count));
if meta.palette_count as usize != GLYPH_BANK_PALETTE_COUNT_V1 {
return Err(format!("Invalid palette_count: {}", meta.palette_count));
}
let logical_pixels = width.checked_mul(height).ok_or("TileBank dimensions overflow")?;
let width = meta.width as usize;
let height = meta.height as usize;
let logical_pixels = width.checked_mul(height).ok_or("GlyphBank dimensions overflow")?;
let serialized_pixel_bytes = logical_pixels.div_ceil(2);
let serialized_size = serialized_pixel_bytes
.checked_add(TILE_BANK_PALETTE_BYTES_V1)
.ok_or("TileBank serialized size overflow")?;
.checked_add(GLYPH_BANK_PALETTE_BYTES_V1)
.ok_or("GlyphBank serialized size overflow")?;
let decoded_size = logical_pixels
.checked_add(TILE_BANK_PALETTE_BYTES_V1)
.ok_or("TileBank decoded size overflow")?;
.checked_add(GLYPH_BANK_PALETTE_BYTES_V1)
.ok_or("GlyphBank decoded size overflow")?;
if entry.size != serialized_size as u64 {
return Err(format!(
"Invalid TILEBANK serialized size: expected {}, got {}",
"Invalid GLYPHBANK serialized size: expected {}, got {}",
serialized_size, entry.size
));
}
if entry.decoded_size != decoded_size as u64 {
return Err(format!(
"Invalid TILEBANK decoded_size: expected {}, got {}",
"Invalid GLYPHBANK decoded_size: expected {}, got {}",
decoded_size, entry.decoded_size
));
}
@@ -235,7 +224,7 @@ impl AssetManager {
Ok((tile_size, width, height, serialized_pixel_bytes))
}
fn unpack_tile_bank_pixels(packed_pixels: &[u8], logical_pixels: usize) -> Vec<u8> {
fn unpack_glyph_bank_pixels(packed_pixels: &[u8], logical_pixels: usize) -> Vec<u8> {
let mut pixel_indices = Vec::with_capacity(logical_pixels);
for &packed in packed_pixels {
if pixel_indices.len() < logical_pixels {
@@ -249,21 +238,16 @@ impl AssetManager {
}
fn op_mode_for(entry: &AssetEntry) -> Result<AssetOpMode, String> {
match entry.bank_type {
BankType::TILES if Self::codec_is_none_or_legacy_raw(entry.codec.as_str()) => {
Ok(AssetOpMode::StageInMemory)
}
BankType::SOUNDS if Self::codec_is_none_or_legacy_raw(entry.codec.as_str()) => {
Ok(AssetOpMode::DirectFromSlice)
}
_ => Err(format!("Unsupported codec: {}", entry.codec)),
match (entry.bank_type, entry.codec) {
(BankType::GLYPH, AssetCodec::None) => Ok(AssetOpMode::StageInMemory),
(BankType::SOUNDS, AssetCodec::None) => Ok(AssetOpMode::DirectFromSlice),
}
}
pub fn new(
assets: Vec<AssetEntry>,
assets_data: AssetsPayloadSource,
gfx_installer: Arc<dyn TileBankPoolInstaller>,
gfx_installer: Arc<dyn GlyphBankPoolInstaller>,
sound_installer: Arc<dyn SoundBankPoolInstaller>,
) -> Self {
let mut asset_map = HashMap::new();
@@ -312,9 +296,9 @@ impl AssetManager {
if let Some(entry) = entry_opt {
let slot_index = item.slot;
match entry.bank_type {
BankType::TILES => {
BankType::GLYPH => {
if let Ok(bank) =
Self::perform_load_tile_bank(&entry, self.assets_data.clone())
Self::perform_load_glyph_bank(&entry, self.assets_data.clone())
{
let bank_arc = Arc::new(bank);
self.gfx_policy.put_resident(
@@ -322,7 +306,7 @@ impl AssetManager {
Arc::clone(&bank_arc),
entry.decoded_size as usize,
);
self.gfx_installer.install_tile_bank(slot_index, bank_arc);
self.gfx_installer.install_glyph_bank(slot_index, bank_arc);
let mut slots = self.gfx_slots.write().unwrap();
if slot_index < slots.len() {
slots[slot_index] = Some(entry.asset_id);
@@ -383,7 +367,7 @@ impl AssetManager {
assets.get(&asset_id).ok_or(AssetLoadError::AssetNotFound)?.clone()
};
let slot = match entry.bank_type {
BankType::TILES => SlotRef::gfx(slot_index),
BankType::GLYPH => SlotRef::gfx(slot_index),
BankType::SOUNDS => SlotRef::audio(slot_index),
};
@@ -393,7 +377,7 @@ impl AssetManager {
// Check if already resident (Dedup)
let already_resident = match entry.bank_type {
BankType::TILES => {
BankType::GLYPH => {
if let Some(bank) = self.gfx_policy.get_resident(asset_id) {
self.gfx_policy.stage(handle_id, bank);
true
@@ -451,8 +435,8 @@ impl AssetManager {
}
match entry_clone.bank_type {
BankType::TILES => {
let result = Self::perform_load_tile_bank(&entry_clone, assets_data);
BankType::GLYPH => {
let result = Self::perform_load_glyph_bank(&entry_clone, assets_data);
if let Ok(tilebank) = result {
let bank_arc = Arc::new(tilebank);
let resident_arc = {
@@ -523,10 +507,10 @@ impl AssetManager {
Ok(handle_id)
}
fn perform_load_tile_bank(
fn perform_load_glyph_bank(
entry: &AssetEntry,
assets_data: Arc<RwLock<AssetsPayloadSource>>,
) -> Result<TileBank, String> {
) -> Result<GlyphBank, String> {
let op_mode = Self::op_mode_for(entry)?;
let slice = {
let assets_data = assets_data.read().unwrap();
@@ -539,30 +523,33 @@ impl AssetManager {
AssetOpMode::StageInMemory => {
let buffer =
slice.read_all().map_err(|_| "Asset payload read failed".to_string())?;
Self::decode_tile_bank_from_buffer(entry, &buffer)
Self::decode_glyph_bank_from_buffer(entry, &buffer)
}
AssetOpMode::DirectFromSlice => {
let mut reader =
slice.open_reader().map_err(|_| "Asset payload read failed".to_string())?;
Self::decode_tile_bank_from_reader(entry, &mut reader)
Self::decode_glyph_bank_from_reader(entry, &mut reader)
}
}
}
fn decode_tile_bank_from_buffer(entry: &AssetEntry, buffer: &[u8]) -> Result<TileBank, String> {
let (tile_size, width, height, packed_pixel_bytes) = Self::decode_tile_bank_layout(entry)?;
if buffer.len() < packed_pixel_bytes + TILE_BANK_PALETTE_BYTES_V1 {
return Err("Buffer too small for TILEBANK".to_string());
fn decode_glyph_bank_from_buffer(
entry: &AssetEntry,
buffer: &[u8],
) -> Result<GlyphBank, String> {
let (tile_size, width, height, packed_pixel_bytes) = Self::decode_glyph_bank_layout(entry)?;
if buffer.len() < packed_pixel_bytes + GLYPH_BANK_PALETTE_BYTES_V1 {
return Err("Buffer too small for GLYPHBANK".to_string());
}
let logical_pixels = width * height;
let packed_pixels = &buffer[0..packed_pixel_bytes];
let pixel_indices = Self::unpack_tile_bank_pixels(packed_pixels, logical_pixels);
let pixel_indices = Self::unpack_glyph_bank_pixels(packed_pixels, logical_pixels);
let palette_data =
&buffer[packed_pixel_bytes..packed_pixel_bytes + TILE_BANK_PALETTE_BYTES_V1];
&buffer[packed_pixel_bytes..packed_pixel_bytes + GLYPH_BANK_PALETTE_BYTES_V1];
let mut palettes =
[[Color::BLACK; TILE_BANK_COLORS_PER_PALETTE]; TILE_BANK_PALETTE_COUNT_V1];
[[Color::BLACK; GLYPH_BANK_COLORS_PER_PALETTE]; GLYPH_BANK_PALETTE_COUNT_V1];
for (p, pal) in palettes.iter_mut().enumerate() {
for (c, slot) in pal.iter_mut().enumerate() {
let offset = (p * 16 + c) * 2;
@@ -572,29 +559,29 @@ impl AssetManager {
}
}
Ok(TileBank { tile_size, width, height, pixel_indices, palettes })
Ok(GlyphBank { tile_size, width, height, pixel_indices, palettes })
}
fn decode_tile_bank_from_reader(
fn decode_glyph_bank_from_reader(
entry: &AssetEntry,
reader: &mut impl Read,
) -> Result<TileBank, String> {
let (tile_size, width, height, packed_pixel_bytes) = Self::decode_tile_bank_layout(entry)?;
) -> Result<GlyphBank, String> {
let (tile_size, width, height, packed_pixel_bytes) = Self::decode_glyph_bank_layout(entry)?;
let logical_pixels = width * height;
let mut packed_pixels = vec![0_u8; packed_pixel_bytes];
reader
.read_exact(&mut packed_pixels)
.map_err(|_| "Buffer too small for TILEBANK".to_string())?;
.map_err(|_| "Buffer too small for GLYPHBANK".to_string())?;
let pixel_indices = Self::unpack_tile_bank_pixels(&packed_pixels, logical_pixels);
let pixel_indices = Self::unpack_glyph_bank_pixels(&packed_pixels, logical_pixels);
let mut palette_data = [0_u8; TILE_BANK_PALETTE_BYTES_V1];
let mut palette_data = [0_u8; GLYPH_BANK_PALETTE_BYTES_V1];
reader
.read_exact(&mut palette_data)
.map_err(|_| "Buffer too small for TILEBANK".to_string())?;
.map_err(|_| "Buffer too small for GLYPHBANK".to_string())?;
let mut palettes =
[[Color::BLACK; TILE_BANK_COLORS_PER_PALETTE]; TILE_BANK_PALETTE_COUNT_V1];
[[Color::BLACK; GLYPH_BANK_COLORS_PER_PALETTE]; GLYPH_BANK_PALETTE_COUNT_V1];
for (p, pal) in palettes.iter_mut().enumerate() {
for (c, slot) in pal.iter_mut().enumerate() {
let offset = (p * 16 + c) * 2;
@@ -604,7 +591,7 @@ impl AssetManager {
}
}
Ok(TileBank { tile_size, width, height, pixel_indices, palettes })
Ok(GlyphBank { tile_size, width, height, pixel_indices, palettes })
}
fn perform_load_sound_bank(
@@ -637,8 +624,8 @@ impl AssetManager {
entry: &AssetEntry,
buffer: &[u8],
) -> Result<SoundBank, String> {
let sample_rate =
entry.metadata.get("sample_rate").and_then(|v| v.as_u64()).unwrap_or(44100) as u32;
let meta = entry.metadata_as_sound_bank()?;
let sample_rate = meta.sample_rate;
let mut data = Vec::with_capacity(buffer.len() / 2);
for i in (0..buffer.len()).step_by(2) {
@@ -711,9 +698,9 @@ impl AssetManager {
if let Some(h) = handles.get_mut(&handle_id) {
if h.status == LoadStatus::READY {
match h.slot.asset_type {
BankType::TILES => {
BankType::GLYPH => {
if let Some(bank) = self.gfx_policy.take_staging(handle_id) {
self.gfx_installer.install_tile_bank(h.slot.index, bank);
self.gfx_installer.install_glyph_bank(h.slot.index, bank);
let mut slots = self.gfx_slots.write().unwrap();
if h.slot.index < slots.len() {
slots[h.slot.index] = Some(h._asset_id);
@@ -739,7 +726,7 @@ impl AssetManager {
pub fn bank_info(&self, kind: BankType) -> BankStats {
match kind {
BankType::TILES => {
BankType::GLYPH => {
let mut used_bytes = 0;
{
let resident = self.gfx_policy.resident.read().unwrap();
@@ -830,7 +817,7 @@ impl AssetManager {
pub fn slot_info(&self, slot: SlotRef) -> SlotStats {
match slot.asset_type {
BankType::TILES => {
BankType::GLYPH => {
let slots = self.gfx_slots.read().unwrap();
let asset_id = slots.get(slot.index).and_then(|s| *s);
@@ -888,93 +875,94 @@ impl AssetManager {
#[cfg(test)]
mod tests {
use super::*;
use crate::memory_banks::{MemoryBanks, SoundBankPoolAccess, TileBankPoolAccess};
use crate::memory_banks::{GlyphBankPoolAccess, MemoryBanks, SoundBankPoolAccess};
use prometeu_hal::asset::AssetCodec;
fn expected_tile_payload_size(width: usize, height: usize) -> usize {
(width * height).div_ceil(2) + TILE_BANK_PALETTE_BYTES_V1
fn expected_glyph_payload_size(width: usize, height: usize) -> usize {
(width * height).div_ceil(2) + GLYPH_BANK_PALETTE_BYTES_V1
}
fn expected_tile_decoded_size(width: usize, height: usize) -> usize {
width * height + TILE_BANK_PALETTE_BYTES_V1
fn expected_glyph_decoded_size(width: usize, height: usize) -> usize {
width * height + GLYPH_BANK_PALETTE_BYTES_V1
}
fn test_tile_asset_data() -> Vec<u8> {
fn test_glyph_asset_data() -> Vec<u8> {
let mut data = vec![0x11u8; 128];
data.extend_from_slice(&[0u8; TILE_BANK_PALETTE_BYTES_V1]);
data.extend_from_slice(&[0u8; GLYPH_BANK_PALETTE_BYTES_V1]);
data
}
fn test_tile_asset_entry(asset_name: &str, width: usize, height: usize) -> AssetEntry {
fn test_glyph_asset_entry(asset_name: &str, width: usize, height: usize) -> AssetEntry {
AssetEntry {
asset_id: 0,
asset_name: asset_name.to_string(),
bank_type: BankType::TILES,
bank_type: BankType::GLYPH,
offset: 0,
size: expected_tile_payload_size(width, height) as u64,
decoded_size: expected_tile_decoded_size(width, height) as u64,
codec: "NONE".to_string(),
size: expected_glyph_payload_size(width, height) as u64,
decoded_size: expected_glyph_decoded_size(width, height) as u64,
codec: AssetCodec::None,
metadata: serde_json::json!({
"tile_size": 16,
"width": width,
"height": height,
"palette_count": TILE_BANK_PALETTE_COUNT_V1
"palette_count": GLYPH_BANK_PALETTE_COUNT_V1,
"palette_authored": GLYPH_BANK_PALETTE_COUNT_V1
}),
}
}
#[test]
fn test_decode_tile_bank_unpacks_packed_pixels_and_reads_palette_colors() {
let entry = test_tile_asset_entry("tiles", 2, 2);
fn test_decode_glyph_bank_unpacks_packed_pixels_and_reads_palette_colors() {
let entry = test_glyph_asset_entry("glyphs", 2, 2);
let mut data = vec![0x10, 0x23];
data.extend_from_slice(&[0u8; TILE_BANK_PALETTE_BYTES_V1]);
data.extend_from_slice(&[0u8; GLYPH_BANK_PALETTE_BYTES_V1]);
data[2] = 0x34;
data[3] = 0x12;
let bank = AssetManager::decode_tile_bank_from_buffer(&entry, &data).expect("tile decode");
let bank =
AssetManager::decode_glyph_bank_from_buffer(&entry, &data).expect("glyph decode");
assert_eq!(bank.pixel_indices, vec![1, 0, 2, 3]);
assert_eq!(bank.palettes[0][0], Color(0x1234));
}
#[test]
fn test_decode_tile_bank_rejects_short_packed_buffer() {
let entry = test_tile_asset_entry("tiles", 16, 16);
let data = vec![0u8; expected_tile_payload_size(16, 16) - 1];
fn test_decode_glyph_bank_rejects_short_packed_buffer() {
let entry = test_glyph_asset_entry("glyphs", 16, 16);
let data = vec![0u8; expected_glyph_payload_size(16, 16) - 1];
let err = match AssetManager::decode_tile_bank_from_buffer(&entry, &data) {
Ok(_) => panic!("tile decode should reject short buffer"),
let err = match AssetManager::decode_glyph_bank_from_buffer(&entry, &data) {
Ok(_) => panic!("glyph decode should reject short buffer"),
Err(err) => err,
};
assert_eq!(err, "Buffer too small for TILEBANK");
assert_eq!(err, "Buffer too small for GLYPHBANK");
}
#[test]
fn test_decode_tile_bank_requires_palette_count_64() {
let mut entry = test_tile_asset_entry("tiles", 16, 16);
fn test_decode_glyph_bank_requires_palette_count_64() {
let mut entry = test_glyph_asset_entry("glyphs", 16, 16);
entry.metadata["palette_count"] = serde_json::json!(32);
let err = match AssetManager::decode_tile_bank_from_buffer(&entry, &test_tile_asset_data())
{
Ok(_) => panic!("tile decode should reject invalid palette_count"),
Err(err) => err,
};
let err =
match AssetManager::decode_glyph_bank_from_buffer(&entry, &test_glyph_asset_data()) {
Ok(_) => panic!("glyph decode should reject invalid palette_count"),
Err(err) => err,
};
assert_eq!(err, "Invalid palette_count: 32");
}
#[test]
fn test_op_mode_for_tiles_none_stages_in_memory() {
let entry = test_tile_asset_entry("tiles", 16, 16);
fn test_op_mode_for_glyphs_none_stages_in_memory() {
let entry = test_glyph_asset_entry("glyphs", 16, 16);
assert_eq!(AssetManager::op_mode_for(&entry), Ok(AssetOpMode::StageInMemory));
}
#[test]
fn test_op_mode_for_tiles_raw_is_legacy_alias() {
let mut entry = test_tile_asset_entry("tiles", 16, 16);
entry.codec = "RAW".to_string();
fn test_op_mode_for_glyphs_none_uses_typed_codec() {
let entry = test_glyph_asset_entry("glyphs", 16, 16);
assert_eq!(AssetManager::op_mode_for(&entry), Ok(AssetOpMode::StageInMemory));
}
@@ -987,9 +975,10 @@ mod tests {
offset: 0,
size: 8,
decoded_size: 8,
codec: "NONE".to_string(),
codec: AssetCodec::None,
metadata: serde_json::json!({
"sample_rate": 44100
"sample_rate": 44100,
"channels": 1
}),
};
@@ -999,11 +988,11 @@ mod tests {
#[test]
fn test_asset_loading_flow() {
let banks = Arc::new(MemoryBanks::new());
let gfx_installer = Arc::clone(&banks) as Arc<dyn TileBankPoolInstaller>;
let gfx_installer = Arc::clone(&banks) as Arc<dyn GlyphBankPoolInstaller>;
let sound_installer = Arc::clone(&banks) as Arc<dyn SoundBankPoolInstaller>;
let data = test_tile_asset_data();
let asset_entry = test_tile_asset_entry("test_tiles", 16, 16);
let data = test_glyph_asset_data();
let asset_entry = test_glyph_asset_entry("test_glyphs", 16, 16);
let am = AssetManager::new(
vec![asset_entry],
@@ -1031,17 +1020,17 @@ mod tests {
am.apply_commits();
assert_eq!(am.status(handle), LoadStatus::COMMITTED);
assert!(banks.tile_bank_slot(0).is_some());
assert!(banks.glyph_bank_slot(0).is_some());
}
#[test]
fn test_asset_dedup() {
let banks = Arc::new(MemoryBanks::new());
let gfx_installer = Arc::clone(&banks) as Arc<dyn TileBankPoolInstaller>;
let gfx_installer = Arc::clone(&banks) as Arc<dyn GlyphBankPoolInstaller>;
let sound_installer = Arc::clone(&banks) as Arc<dyn SoundBankPoolInstaller>;
let data = test_tile_asset_data();
let asset_entry = test_tile_asset_entry("test_tiles", 16, 16);
let data = test_glyph_asset_data();
let asset_entry = test_glyph_asset_entry("test_glyphs", 16, 16);
let am = AssetManager::new(
vec![asset_entry],
@@ -1068,7 +1057,7 @@ mod tests {
#[test]
fn test_sound_asset_loading() {
let banks = Arc::new(MemoryBanks::new());
let gfx_installer = Arc::clone(&banks) as Arc<dyn TileBankPoolInstaller>;
let gfx_installer = Arc::clone(&banks) as Arc<dyn GlyphBankPoolInstaller>;
let sound_installer = Arc::clone(&banks) as Arc<dyn SoundBankPoolInstaller>;
// 100 samples of 16-bit PCM (zeros)
@@ -1081,9 +1070,10 @@ mod tests {
offset: 0,
size: data.len() as u64,
decoded_size: data.len() as u64,
codec: "NONE".to_string(),
codec: AssetCodec::None,
metadata: serde_json::json!({
"sample_rate": 44100
"sample_rate": 44100,
"channels": 1
}),
};
@@ -1112,7 +1102,7 @@ mod tests {
#[test]
fn test_preload_on_init() {
let banks = Arc::new(MemoryBanks::new());
let gfx_installer = Arc::clone(&banks) as Arc<dyn TileBankPoolInstaller>;
let gfx_installer = Arc::clone(&banks) as Arc<dyn GlyphBankPoolInstaller>;
let sound_installer = Arc::clone(&banks) as Arc<dyn SoundBankPoolInstaller>;
let data = vec![0u8; 200];
@@ -1124,9 +1114,10 @@ mod tests {
offset: 0,
size: data.len() as u64,
decoded_size: data.len() as u64,
codec: "NONE".to_string(),
codec: AssetCodec::None,
metadata: serde_json::json!({
"sample_rate": 44100
"sample_rate": 44100,
"channels": 1
}),
};
@@ -1152,7 +1143,7 @@ mod tests {
#[test]
fn test_load_returns_asset_not_found() {
let banks = Arc::new(MemoryBanks::new());
let gfx_installer = Arc::clone(&banks) as Arc<dyn TileBankPoolInstaller>;
let gfx_installer = Arc::clone(&banks) as Arc<dyn GlyphBankPoolInstaller>;
let sound_installer = Arc::clone(&banks) as Arc<dyn SoundBankPoolInstaller>;
let am =
AssetManager::new(vec![], AssetsPayloadSource::empty(), gfx_installer, sound_installer);
@@ -1165,11 +1156,11 @@ mod tests {
#[test]
fn test_load_returns_slot_index_invalid() {
let banks = Arc::new(MemoryBanks::new());
let gfx_installer = Arc::clone(&banks) as Arc<dyn TileBankPoolInstaller>;
let gfx_installer = Arc::clone(&banks) as Arc<dyn GlyphBankPoolInstaller>;
let sound_installer = Arc::clone(&banks) as Arc<dyn SoundBankPoolInstaller>;
let data = test_tile_asset_data();
let data = test_glyph_asset_data();
let am = AssetManager::new(
vec![test_tile_asset_entry("test_tiles", 16, 16)],
vec![test_glyph_asset_entry("test_glyphs", 16, 16)],
AssetsPayloadSource::from_bytes(data),
gfx_installer,
sound_installer,
@@ -1183,7 +1174,7 @@ mod tests {
#[test]
fn test_status_returns_unknown_handle() {
let banks = Arc::new(MemoryBanks::new());
let gfx_installer = Arc::clone(&banks) as Arc<dyn TileBankPoolInstaller>;
let gfx_installer = Arc::clone(&banks) as Arc<dyn GlyphBankPoolInstaller>;
let sound_installer = Arc::clone(&banks) as Arc<dyn SoundBankPoolInstaller>;
let am =
AssetManager::new(vec![], AssetsPayloadSource::empty(), gfx_installer, sound_installer);
@@ -1194,11 +1185,11 @@ mod tests {
#[test]
fn test_commit_and_cancel_return_explicit_statuses() {
let banks = Arc::new(MemoryBanks::new());
let gfx_installer = Arc::clone(&banks) as Arc<dyn TileBankPoolInstaller>;
let gfx_installer = Arc::clone(&banks) as Arc<dyn GlyphBankPoolInstaller>;
let sound_installer = Arc::clone(&banks) as Arc<dyn SoundBankPoolInstaller>;
let data = test_tile_asset_data();
let data = test_glyph_asset_data();
let am = AssetManager::new(
vec![test_tile_asset_entry("test_tiles", 16, 16)],
vec![test_glyph_asset_entry("test_glyphs", 16, 16)],
AssetsPayloadSource::from_bytes(data),
gfx_installer,
sound_installer,
+28 -25
View File
@@ -1,9 +1,10 @@
use crate::memory_banks::TileBankPoolAccess;
use crate::memory_banks::GlyphBankPoolAccess;
use prometeu_hal::GfxBridge;
use prometeu_hal::color::Color;
use prometeu_hal::glyph::Glyph;
use prometeu_hal::glyph_bank::{GlyphBank, TileSize};
use prometeu_hal::sprite::Sprite;
use prometeu_hal::tile::Tile;
use prometeu_hal::tile_bank::{TileBank, TileSize};
use prometeu_hal::tile_layer::{HudTileLayer, ScrollableTileLayer, TileMap};
use std::sync::Arc;
@@ -56,12 +57,12 @@ pub struct Gfx {
/// Back buffer: the "Work RAM" where new frames are composed.
back: Vec<u16>,
/// 4 scrollable background layers. Each can have its own scroll (X, Y) and TileBank.
/// 4 scrollable background layers. Each can have its own scroll (X, Y) and GlyphBank.
pub layers: [ScrollableTileLayer; 4],
/// 1 fixed layer for User Interface (HUD). It doesn't scroll.
pub hud: HudTileLayer,
/// Shared access to graphical memory banks (tiles and palettes).
pub tile_banks: Arc<dyn TileBankPoolAccess>,
pub glyph_banks: Arc<dyn GlyphBankPoolAccess>,
/// Hardware sprite list (512 slots). Equivalent to OAM (Object Attribute Memory).
pub sprites: [Sprite; 512],
@@ -273,9 +274,11 @@ impl GfxBridge for Gfx {
impl Gfx {
/// Initializes the graphics system with a specific resolution and shared memory banks.
pub fn new(w: usize, h: usize, tile_banks: Arc<dyn TileBankPoolAccess>) -> Self {
pub fn new(w: usize, h: usize, glyph_banks: Arc<dyn GlyphBankPoolAccess>) -> Self {
const EMPTY_GLYPH: Glyph = Glyph { glyph_id: 0, palette_id: 0 };
const EMPTY_SPRITE: Sprite = Sprite {
tile: Tile { id: 0, flip_x: false, flip_y: false, palette_id: 0 },
glyph: EMPTY_GLYPH,
x: 0,
y: 0,
bank_id: 0,
@@ -300,7 +303,7 @@ impl Gfx {
back: vec![0; len],
layers,
hud: HudTileLayer::new(64, 32),
tile_banks,
glyph_banks,
sprites: [EMPTY_SPRITE; 512],
scene_fade_level: 31,
scene_fade_color: Color::BLACK,
@@ -580,14 +583,14 @@ impl Gfx {
self.h,
&self.priority_buckets[0],
&self.sprites,
&*self.tile_banks,
&*self.glyph_banks,
);
// 2. Main layers and prioritized sprites.
// Order: Layer 0 -> Sprites 1 -> Layer 1 -> Sprites 2 ...
for i in 0..self.layers.len() {
let bank_id = self.layers[i].bank_id as usize;
if let Some(bank) = self.tile_banks.tile_bank_slot(bank_id) {
if let Some(bank) = self.glyph_banks.glyph_bank_slot(bank_id) {
Self::draw_tile_map(
&mut self.back,
self.w,
@@ -606,7 +609,7 @@ impl Gfx {
self.h,
&self.priority_buckets[i + 1],
&self.sprites,
&*self.tile_banks,
&*self.glyph_banks,
);
}
@@ -614,7 +617,7 @@ impl Gfx {
Self::apply_fade_to_buffer(&mut self.back, self.scene_fade_level, self.scene_fade_color);
// 5. HUD: The fixed interface layer, always drawn on top of the world.
Self::render_hud_with_pool(&mut self.back, self.w, self.h, &self.hud, &*self.tile_banks);
Self::render_hud_with_pool(&mut self.back, self.w, self.h, &self.hud, &*self.glyph_banks);
// 6. HUD Fade: Independent fade effect for the UI.
Self::apply_fade_to_buffer(&mut self.back, self.hud_fade_level, self.hud_fade_color);
@@ -630,7 +633,7 @@ impl Gfx {
let scroll_x = self.layers[layer_idx].scroll_x;
let scroll_y = self.layers[layer_idx].scroll_y;
let bank = match self.tile_banks.tile_bank_slot(bank_id) {
let bank = match self.glyph_banks.glyph_bank_slot(bank_id) {
Some(b) => b,
_ => return,
};
@@ -648,7 +651,7 @@ impl Gfx {
/// Renders the HUD (fixed position, no scroll).
pub fn render_hud(&mut self) {
Self::render_hud_with_pool(&mut self.back, self.w, self.h, &self.hud, &*self.tile_banks);
Self::render_hud_with_pool(&mut self.back, self.w, self.h, &self.hud, &*self.glyph_banks);
}
fn render_hud_with_pool(
@@ -656,10 +659,10 @@ impl Gfx {
w: usize,
h: usize,
hud: &HudTileLayer,
tile_banks: &dyn TileBankPoolAccess,
glyph_banks: &dyn GlyphBankPoolAccess,
) {
let bank_id = hud.bank_id as usize;
let bank = match tile_banks.tile_bank_slot(bank_id) {
let bank = match glyph_banks.glyph_bank_slot(bank_id) {
Some(b) => b,
_ => return,
};
@@ -673,7 +676,7 @@ impl Gfx {
screen_w: usize,
screen_h: usize,
map: &TileMap,
bank: &TileBank,
bank: &GlyphBank,
scroll_x: i32,
scroll_y: i32,
) {
@@ -706,7 +709,7 @@ impl Gfx {
let tile = map.tiles[map_y * map.width + map_x];
// Optimized skip for empty (ID 0) tiles.
if tile.id == 0 {
if !tile.active {
continue;
}
@@ -736,7 +739,7 @@ impl Gfx {
x: i32,
y: i32,
tile: Tile,
bank: &TileBank,
bank: &GlyphBank,
) {
let size = bank.tile_size as usize;
@@ -757,7 +760,7 @@ impl Gfx {
let fetch_y = if tile.flip_y { size - 1 - local_y } else { local_y };
// 1. Get the pixel color index (0-15) from the bank.
let px_index = bank.get_pixel_index(tile.id, fetch_x, fetch_y);
let px_index = bank.get_pixel_index(tile.glyph.glyph_id, fetch_x, fetch_y);
// 2. Hardware rule: Color index 0 is always fully transparent.
if px_index == 0 {
@@ -765,7 +768,7 @@ impl Gfx {
}
// 3. Resolve the virtual index to a real RGB565 color using the tile's assigned palette.
let color = bank.resolve_color(tile.palette_id, px_index);
let color = bank.resolve_color(tile.glyph.palette_id, px_index);
back[world_y as usize * screen_w + world_x as usize] = color.raw();
}
@@ -778,12 +781,12 @@ impl Gfx {
screen_h: usize,
bucket: &[usize],
sprites: &[Sprite],
tile_banks: &dyn TileBankPoolAccess,
glyph_banks: &dyn GlyphBankPoolAccess,
) {
for &idx in bucket {
let s = &sprites[idx];
let bank_id = s.bank_id as usize;
if let Some(bank) = tile_banks.tile_bank_slot(bank_id) {
if let Some(bank) = glyph_banks.glyph_bank_slot(bank_id) {
Self::draw_sprite_pixel_by_pixel(back, screen_w, screen_h, s, &bank);
}
}
@@ -794,7 +797,7 @@ impl Gfx {
screen_w: usize,
screen_h: usize,
sprite: &Sprite,
bank: &TileBank,
bank: &GlyphBank,
) {
// ... (same bounds/clipping calculation we already had) ...
let size = bank.tile_size as usize;
@@ -812,7 +815,7 @@ impl Gfx {
let fetch_y = if sprite.flip_y { size - 1 - local_y } else { local_y };
// 1. Get index
let px_index = bank.get_pixel_index(sprite.tile.id, fetch_x, fetch_y);
let px_index = bank.get_pixel_index(sprite.glyph.glyph_id, fetch_x, fetch_y);
// 2. Transparency
if px_index == 0 {
@@ -820,7 +823,7 @@ impl Gfx {
}
// 3. Resolve color via palette (from the tile inside the sprite)
let color = bank.resolve_color(sprite.tile.palette_id, px_index);
let color = bank.resolve_color(sprite.glyph.palette_id, px_index);
back[world_y as usize * screen_w + world_x as usize] = color.raw();
}
@@ -2,8 +2,8 @@ use crate::asset::AssetManager;
use crate::audio::Audio;
use crate::gfx::Gfx;
use crate::memory_banks::{
MemoryBanks, SoundBankPoolAccess, SoundBankPoolInstaller, TileBankPoolAccess,
TileBankPoolInstaller,
GlyphBankPoolAccess, GlyphBankPoolInstaller, MemoryBanks, SoundBankPoolAccess,
SoundBankPoolInstaller,
};
use crate::pad::Pad;
use crate::touch::Touch;
@@ -32,7 +32,7 @@ pub struct Hardware {
pub pad: Pad,
/// The absolute pointer input device (Mouse/Touchscreen).
pub touch: Touch,
/// The Asset Management system (DMA). Handles loading data into VRAM (TileBanks) and ARAM (SoundBanks).
/// The Asset Management system (DMA). Handles loading data into VRAM (GlyphBanks) and ARAM (SoundBanks).
pub assets: AssetManager,
}
@@ -92,7 +92,7 @@ impl Hardware {
gfx: Gfx::new(
Self::W,
Self::H,
Arc::clone(&memory_banks) as Arc<dyn TileBankPoolAccess>,
Arc::clone(&memory_banks) as Arc<dyn GlyphBankPoolAccess>,
),
audio: Audio::new(Arc::clone(&memory_banks) as Arc<dyn SoundBankPoolAccess>),
pad: Pad::default(),
@@ -100,7 +100,7 @@ impl Hardware {
assets: AssetManager::new(
vec![],
AssetsPayloadSource::empty(),
Arc::clone(&memory_banks) as Arc<dyn TileBankPoolInstaller>,
Arc::clone(&memory_banks) as Arc<dyn GlyphBankPoolInstaller>,
Arc::clone(&memory_banks) as Arc<dyn SoundBankPoolInstaller>,
),
}
@@ -1,19 +1,19 @@
use prometeu_hal::glyph_bank::GlyphBank;
use prometeu_hal::sound_bank::SoundBank;
use prometeu_hal::tile_bank::TileBank;
use std::sync::{Arc, RwLock};
/// Non-generic interface for peripherals to access graphical tile banks.
pub trait TileBankPoolAccess: Send + Sync {
/// Returns a reference to the resident TileBank in the specified slot, if any.
fn tile_bank_slot(&self, slot: usize) -> Option<Arc<TileBank>>;
/// Non-generic interface for peripherals to access graphical glyph banks.
pub trait GlyphBankPoolAccess: Send + Sync {
/// Returns a reference to the resident GlyphBank in the specified slot, if any.
fn glyph_bank_slot(&self, slot: usize) -> Option<Arc<GlyphBank>>;
/// Returns the total number of slots available in this bank.
fn tile_bank_slot_count(&self) -> usize;
fn glyph_bank_slot_count(&self) -> usize;
}
/// Non-generic interface for the AssetManager to install graphical tile banks.
pub trait TileBankPoolInstaller: Send + Sync {
/// Atomically swaps the resident TileBank in the specified slot.
fn install_tile_bank(&self, slot: usize, bank: Arc<TileBank>);
/// Non-generic interface for the AssetManager to install graphical glyph banks.
pub trait GlyphBankPoolInstaller: Send + Sync {
/// Atomically swaps the resident GlyphBank in the specified slot.
fn install_glyph_bank(&self, slot: usize, bank: Arc<GlyphBank>);
}
/// Non-generic interface for peripherals to access sound banks.
@@ -36,7 +36,7 @@ pub trait SoundBankPoolInstaller: Send + Sync {
/// Peripherals consume this state via narrow, non-generic traits.
/// AssetManager coordinates residency and installs assets into these slots.
pub struct MemoryBanks {
tile_bank_pool: Arc<RwLock<[Option<Arc<TileBank>>; 16]>>,
glyph_bank_pool: Arc<RwLock<[Option<Arc<GlyphBank>>; 16]>>,
sound_bank_pool: Arc<RwLock<[Option<Arc<SoundBank>>; 16]>>,
}
@@ -50,26 +50,26 @@ impl MemoryBanks {
/// Creates a new set of memory banks with empty slots.
pub fn new() -> Self {
Self {
tile_bank_pool: Arc::new(RwLock::new(std::array::from_fn(|_| None))),
glyph_bank_pool: Arc::new(RwLock::new(std::array::from_fn(|_| None))),
sound_bank_pool: Arc::new(RwLock::new(std::array::from_fn(|_| None))),
}
}
}
impl TileBankPoolAccess for MemoryBanks {
fn tile_bank_slot(&self, slot: usize) -> Option<Arc<TileBank>> {
let pool = self.tile_bank_pool.read().unwrap();
impl GlyphBankPoolAccess for MemoryBanks {
fn glyph_bank_slot(&self, slot: usize) -> Option<Arc<GlyphBank>> {
let pool = self.glyph_bank_pool.read().unwrap();
pool.get(slot).and_then(|s| s.as_ref().map(Arc::clone))
}
fn tile_bank_slot_count(&self) -> usize {
fn glyph_bank_slot_count(&self) -> usize {
16
}
}
impl TileBankPoolInstaller for MemoryBanks {
fn install_tile_bank(&self, slot: usize, bank: Arc<TileBank>) {
let mut pool = self.tile_bank_pool.write().unwrap();
impl GlyphBankPoolInstaller for MemoryBanks {
fn install_glyph_bank(&self, slot: usize, bank: Arc<GlyphBank>) {
let mut pool = self.glyph_bank_pool.write().unwrap();
if slot < 16 {
pool[slot] = Some(bank);
}
+48 -3
View File
@@ -6,12 +6,18 @@ pub type AssetId = i32;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[allow(non_camel_case_types)]
pub enum BankType {
TILES,
GLYPH,
SOUNDS,
// TILEMAPS,
// BLOBS,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub enum AssetCodec {
#[serde(rename = "NONE")]
None,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AssetEntry {
pub asset_id: AssetId,
@@ -20,10 +26,49 @@ pub struct AssetEntry {
pub offset: u64,
pub size: u64,
pub decoded_size: u64,
pub codec: String, // e.g., "NONE" (legacy alias: "RAW")
pub codec: AssetCodec,
pub metadata: serde_json::Value,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct GlyphBankMetadata {
pub tile_size: u32,
pub width: u32,
pub height: u32,
pub palette_count: u32,
pub palette_authored: u32,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct SoundBankMetadata {
pub sample_rate: u32,
pub channels: u32,
}
impl AssetEntry {
pub fn metadata_as_glyph_bank(&self) -> Result<GlyphBankMetadata, String> {
if self.bank_type != BankType::GLYPH {
return Err(format!(
"Asset {} is not a GLYPH bank (type: {:?})",
self.asset_id, self.bank_type
));
}
serde_json::from_value(self.metadata.clone())
.map_err(|e| format!("Invalid GLYPH metadata for asset {}: {}", self.asset_id, e))
}
pub fn metadata_as_sound_bank(&self) -> Result<SoundBankMetadata, String> {
if self.bank_type != BankType::SOUNDS {
return Err(format!(
"Asset {} is not a SOUNDS bank (type: {:?})",
self.asset_id, self.bank_type
));
}
serde_json::from_value(self.metadata.clone())
.map_err(|e| format!("Invalid SOUNDS metadata for asset {}: {}", self.asset_id, e))
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PreloadEntry {
pub asset_id: AssetId,
@@ -85,7 +130,7 @@ pub struct SlotRef {
impl SlotRef {
pub fn gfx(index: usize) -> Self {
Self { asset_type: BankType::TILES, index }
Self { asset_type: BankType::GLYPH, index }
}
pub fn audio(index: usize) -> Self {
@@ -198,9 +198,9 @@ fn validate_preload(
#[cfg(test)]
mod tests {
use super::*;
use crate::asset::{AssetEntry, BankType, PreloadEntry};
use crate::asset::{AssetCodec, AssetEntry, BankType, PreloadEntry};
use crate::cartridge::{ASSETS_PA_MAGIC, ASSETS_PA_SCHEMA_VERSION, AssetsPackPrelude};
use crate::tile_bank::TILE_BANK_PALETTE_COUNT_V1;
use crate::glyph_bank::GLYPH_BANK_PALETTE_COUNT_V1;
use serde_json::json;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
@@ -363,16 +363,17 @@ mod tests {
AssetEntry {
asset_id: 7,
asset_name: "tiles".to_string(),
bank_type: BankType::TILES,
bank_type: BankType::GLYPH,
offset,
size,
decoded_size: 16 * 16 + (TILE_BANK_PALETTE_COUNT_V1 as u64 * 16 * 2),
codec: "NONE".to_string(),
decoded_size: 16 * 16 + (GLYPH_BANK_PALETTE_COUNT_V1 as u64 * 16 * 2),
codec: AssetCodec::None,
metadata: json!({
"tile_size": 16,
"width": 16,
"height": 16,
"palette_count": TILE_BANK_PALETTE_COUNT_V1
"palette_count": GLYPH_BANK_PALETTE_COUNT_V1,
"palette_authored": GLYPH_BANK_PALETTE_COUNT_V1
}),
}
}
@@ -445,16 +446,17 @@ mod tests {
AssetEntry {
asset_id: 8,
asset_name: "other_tiles".to_string(),
bank_type: BankType::TILES,
bank_type: BankType::GLYPH,
offset: 4,
size: 4,
decoded_size: 16 * 16 + (TILE_BANK_PALETTE_COUNT_V1 as u64 * 16 * 2),
codec: "NONE".to_string(),
decoded_size: 16 * 16 + (GLYPH_BANK_PALETTE_COUNT_V1 as u64 * 16 * 2),
codec: AssetCodec::None,
metadata: json!({
"tile_size": 16,
"width": 16,
"height": 16,
"palette_count": TILE_BANK_PALETTE_COUNT_V1
"palette_count": GLYPH_BANK_PALETTE_COUNT_V1,
"palette_authored": GLYPH_BANK_PALETTE_COUNT_V1
}),
},
];
@@ -497,4 +499,88 @@ mod tests {
assert!(matches!(error, CartridgeError::InvalidFormat));
}
#[test]
fn load_rejects_unknown_codec_string_in_assets_pa_header() {
let dir = TestCartridgeDir::new(manifest_with_capabilities(Some(vec!["asset"])));
let header = serde_json::json!({
"asset_table": [{
"asset_id": 7,
"asset_name": "tiles",
"bank_type": "GLYPH",
"offset": 0,
"size": 4,
"decoded_size": 768,
"codec": "LZ4",
"metadata": {
"tile_size": 16,
"width": 16,
"height": 16,
"palette_count": GLYPH_BANK_PALETTE_COUNT_V1,
"palette_authored": GLYPH_BANK_PALETTE_COUNT_V1
}
}],
"preload": []
});
let header_bytes = serde_json::to_vec(&header).expect("header must serialize");
let prelude = AssetsPackPrelude {
magic: ASSETS_PA_MAGIC,
schema_version: ASSETS_PA_SCHEMA_VERSION,
header_len: header_bytes.len() as u32,
payload_offset: (ASSETS_PA_PRELUDE_SIZE + header_bytes.len()) as u64,
flags: 0,
reserved: 0,
header_checksum: 0,
};
let mut bytes = prelude.to_bytes().to_vec();
bytes.extend_from_slice(&header_bytes);
bytes.extend_from_slice(&[1_u8, 2, 3, 4]);
fs::write(dir.path().join("assets.pa"), bytes).expect("must write assets.pa");
let error = DirectoryCartridgeLoader::load(dir.path()).unwrap_err();
assert!(matches!(error, CartridgeError::InvalidFormat));
}
#[test]
fn load_rejects_legacy_raw_codec_string_in_assets_pa_header() {
let dir = TestCartridgeDir::new(manifest_with_capabilities(Some(vec!["asset"])));
let header = serde_json::json!({
"asset_table": [{
"asset_id": 7,
"asset_name": "tiles",
"bank_type": "GLYPH",
"offset": 0,
"size": 4,
"decoded_size": 768,
"codec": "RAW",
"metadata": {
"tile_size": 16,
"width": 16,
"height": 16,
"palette_count": GLYPH_BANK_PALETTE_COUNT_V1,
"palette_authored": GLYPH_BANK_PALETTE_COUNT_V1
}
}],
"preload": []
});
let header_bytes = serde_json::to_vec(&header).expect("header must serialize");
let prelude = AssetsPackPrelude {
magic: ASSETS_PA_MAGIC,
schema_version: ASSETS_PA_SCHEMA_VERSION,
header_len: header_bytes.len() as u32,
payload_offset: (ASSETS_PA_PRELUDE_SIZE + header_bytes.len()) as u64,
flags: 0,
reserved: 0,
header_checksum: 0,
};
let mut bytes = prelude.to_bytes().to_vec();
bytes.extend_from_slice(&header_bytes);
bytes.extend_from_slice(&[1_u8, 2, 3, 4]);
fs::write(dir.path().join("assets.pa"), bytes).expect("must write assets.pa");
let error = DirectoryCartridgeLoader::load(dir.path()).unwrap_err();
assert!(matches!(error, CartridgeError::InvalidFormat));
}
}
+5
View File
@@ -0,0 +1,5 @@
#[derive(Clone, Copy, Debug, Default)]
pub struct Glyph {
pub glyph_id: u16,
pub palette_id: u8,
}
@@ -1,7 +1,7 @@
use crate::color::Color;
pub const TILE_BANK_PALETTE_COUNT_V1: usize = 64;
pub const TILE_BANK_COLORS_PER_PALETTE: usize = 16;
pub const GLYPH_BANK_PALETTE_COUNT_V1: usize = 64;
pub const GLYPH_BANK_COLORS_PER_PALETTE: usize = 16;
/// Standard sizes for square tiles.
#[derive(Clone, Copy, Debug, PartialEq)]
@@ -16,12 +16,12 @@ pub enum TileSize {
/// A container for graphical assets.
///
/// A TileBank stores the decoded runtime representation of a tile-bank asset.
/// A GlyphBank stores the decoded runtime representation of a glyph-bank asset.
///
/// Serialized `assets.pa` payloads keep pixel indices packed as `4bpp` nibbles.
/// After decode, the runtime expands them to one `u8` palette index per pixel
/// while preserving the same `0..15` logical range.
pub struct TileBank {
pub struct GlyphBank {
/// Dimension of each individual tile in the bank.
pub tile_size: TileSize,
/// Width of the full bank sheet in pixels.
@@ -34,18 +34,18 @@ pub struct TileBank {
/// Index 0 is always reserved for transparency.
pub pixel_indices: Vec<u8>,
/// Runtime-facing v1 palette table: 64 palettes of 16 RGB565 colors each.
pub palettes: [[Color; TILE_BANK_COLORS_PER_PALETTE]; TILE_BANK_PALETTE_COUNT_V1],
pub palettes: [[Color; GLYPH_BANK_COLORS_PER_PALETTE]; GLYPH_BANK_PALETTE_COUNT_V1],
}
impl TileBank {
/// Creates an empty tile bank with the specified dimensions.
impl GlyphBank {
/// Creates an empty glyph 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; TILE_BANK_COLORS_PER_PALETTE]; TILE_BANK_PALETTE_COUNT_V1],
palettes: [[Color::BLACK; GLYPH_BANK_COLORS_PER_PALETTE]; GLYPH_BANK_PALETTE_COUNT_V1],
}
}
+2 -1
View File
@@ -7,6 +7,8 @@ pub mod cartridge_loader;
pub mod color;
pub mod debugger_protocol;
pub mod gfx_bridge;
pub mod glyph;
pub mod glyph_bank;
pub mod hardware_bridge;
pub mod host_context;
pub mod host_return;
@@ -21,7 +23,6 @@ pub mod sprite;
pub mod syscalls;
pub mod telemetry;
pub mod tile;
pub mod tile_bank;
pub mod tile_layer;
pub mod touch_bridge;
pub mod vm_fault;
+2 -2
View File
@@ -1,8 +1,8 @@
use crate::tile::Tile;
use crate::glyph::Glyph;
#[derive(Clone, Copy, Debug, Default)]
pub struct Sprite {
pub tile: Tile,
pub glyph: Glyph,
pub x: i32,
pub y: i32,
pub bank_id: u8,
+4 -2
View File
@@ -1,7 +1,9 @@
use crate::glyph::Glyph;
#[derive(Clone, Copy, Debug, Default)]
pub struct Tile {
pub id: u16,
pub glyph: Glyph,
pub active: bool,
pub flip_x: bool,
pub flip_y: bool,
pub palette_id: u8,
}
@@ -1,6 +1,6 @@
use crate::glyph_bank::TileSize;
use crate::glyph_bank::TileSize::Size8;
use crate::tile::Tile;
use crate::tile_bank::TileSize;
use crate::tile_bank::TileSize::Size8;
pub struct TileMap {
pub width: usize,
@@ -4,10 +4,10 @@ use prometeu_bytecode::{TRAP_INVALID_SYSCALL, TRAP_OOB, TRAP_TYPE, Value};
use prometeu_hal::asset::{AssetId, AssetOpStatus, BankType, SlotRef};
use prometeu_hal::cartridge::AppMode;
use prometeu_hal::color::Color;
use prometeu_hal::glyph::Glyph;
use prometeu_hal::log::{LogLevel, LogSource};
use prometeu_hal::sprite::Sprite;
use prometeu_hal::syscalls::Syscall;
use prometeu_hal::tile::Tile;
use prometeu_hal::vm_fault::VmFault;
use prometeu_hal::{
AudioOpStatus, GfxOpStatus, HostContext, HostReturn, NativeInterface, SyscallId, expect_bool,
@@ -139,7 +139,7 @@ impl NativeInterface for VirtualMachineRuntime {
let index = expect_int(args, 1)? as usize;
let x = expect_int(args, 2)? as i32;
let y = expect_int(args, 3)? as i32;
let tile_id = expect_int(args, 4)? as u16;
let glyph_id = expect_int(args, 4)? as u16;
let palette_id = expect_int(args, 5)? as u8;
let active = expect_bool(args, 6)?;
let flip_x = expect_bool(args, 7)?;
@@ -162,7 +162,7 @@ impl NativeInterface for VirtualMachineRuntime {
}
*hw.gfx_mut().sprite_mut(index) = Sprite {
tile: Tile { id: tile_id, flip_x: false, flip_y: false, palette_id },
glyph: Glyph { glyph_id, palette_id },
x,
y,
bank_id,
@@ -481,7 +481,7 @@ impl NativeInterface for VirtualMachineRuntime {
}
Syscall::BankInfo => {
let asset_type = match expect_int(args, 0)? as u32 {
0 => BankType::TILES,
0 => BankType::GLYPH,
1 => BankType::SOUNDS,
_ => return Err(VmFault::Trap(TRAP_TYPE, "Invalid asset type".to_string())),
};
@@ -492,7 +492,7 @@ impl NativeInterface for VirtualMachineRuntime {
}
Syscall::BankSlotInfo => {
let asset_type = match expect_int(args, 0)? as u32 {
0 => BankType::TILES,
0 => BankType::GLYPH,
1 => BankType::SOUNDS,
_ => return Err(VmFault::Trap(TRAP_TYPE, "Invalid asset type".to_string())),
};
@@ -8,10 +8,12 @@ use prometeu_drivers::hardware::Hardware;
use prometeu_hal::AudioOpStatus;
use prometeu_hal::GfxOpStatus;
use prometeu_hal::InputSignals;
use prometeu_hal::asset::{AssetEntry, AssetLoadError, AssetOpStatus, BankType, LoadStatus};
use prometeu_hal::asset::{
AssetCodec, AssetEntry, AssetLoadError, AssetOpStatus, BankType, LoadStatus,
};
use prometeu_hal::cartridge::{AssetsPayloadSource, Cartridge};
use prometeu_hal::glyph_bank::GLYPH_BANK_PALETTE_COUNT_V1;
use prometeu_hal::syscalls::caps;
use prometeu_hal::tile_bank::TILE_BANK_PALETTE_COUNT_V1;
use prometeu_vm::VmInitError;
use std::collections::HashMap;
@@ -92,36 +94,37 @@ fn serialized_single_function_module_with_consts(
.serialize()
}
fn test_tile_payload_size(width: usize, height: usize) -> usize {
(width * height).div_ceil(2) + (TILE_BANK_PALETTE_COUNT_V1 * 16 * std::mem::size_of::<u16>())
fn test_glyph_payload_size(width: usize, height: usize) -> usize {
(width * height).div_ceil(2) + (GLYPH_BANK_PALETTE_COUNT_V1 * 16 * std::mem::size_of::<u16>())
}
fn test_tile_decoded_size(width: usize, height: usize) -> usize {
width * height + (TILE_BANK_PALETTE_COUNT_V1 * 16 * std::mem::size_of::<u16>())
fn test_glyph_decoded_size(width: usize, height: usize) -> usize {
width * height + (GLYPH_BANK_PALETTE_COUNT_V1 * 16 * std::mem::size_of::<u16>())
}
fn test_tile_asset_entry(asset_name: &str, data_len: usize) -> AssetEntry {
fn test_glyph_asset_entry(asset_name: &str, data_len: usize) -> AssetEntry {
AssetEntry {
asset_id: 7,
asset_name: asset_name.to_string(),
bank_type: BankType::TILES,
bank_type: BankType::GLYPH,
offset: 0,
size: data_len as u64,
decoded_size: test_tile_decoded_size(16, 16) as u64,
codec: "NONE".to_string(),
decoded_size: test_glyph_decoded_size(16, 16) as u64,
codec: AssetCodec::None,
metadata: serde_json::json!({
"tile_size": 16,
"width": 16,
"height": 16,
"palette_count": TILE_BANK_PALETTE_COUNT_V1
"palette_count": GLYPH_BANK_PALETTE_COUNT_V1,
"palette_authored": GLYPH_BANK_PALETTE_COUNT_V1
}),
}
}
fn test_tile_asset_data() -> Vec<u8> {
fn test_glyph_asset_data() -> Vec<u8> {
let mut data =
vec![0x11u8; test_tile_payload_size(16, 16) - (TILE_BANK_PALETTE_COUNT_V1 * 16 * 2)];
data.extend_from_slice(&[0u8; TILE_BANK_PALETTE_COUNT_V1 * 16 * 2]);
vec![0x11u8; test_glyph_payload_size(16, 16) - (GLYPH_BANK_PALETTE_COUNT_V1 * 16 * 2)];
data.extend_from_slice(&[0u8; GLYPH_BANK_PALETTE_COUNT_V1 * 16 * 2]);
data
}
@@ -436,10 +439,10 @@ fn tick_gfx_set_sprite_invalid_range_returns_status_not_crash() {
}],
);
let cartridge = cartridge_with_program(program, caps::GFX);
let asset_data = test_tile_asset_data();
let asset_data = test_glyph_asset_data();
hardware.assets.initialize_for_cartridge(
vec![test_tile_asset_entry("tile_asset", asset_data.len())],
vec![test_glyph_asset_entry("tile_asset", asset_data.len())],
vec![prometeu_hal::asset::PreloadEntry { asset_id: 7, slot: 0 }],
AssetsPayloadSource::from_bytes(asset_data),
);
@@ -634,9 +637,9 @@ fn tick_asset_load_invalid_slot_returns_status_and_zero_handle() {
let mut vm = VirtualMachine::default();
let mut hardware = Hardware::new();
let signals = InputSignals::default();
let asset_data = test_tile_asset_data();
let asset_data = test_glyph_asset_data();
hardware.assets.initialize_for_cartridge(
vec![test_tile_asset_entry("tile_asset", asset_data.len())],
vec![test_glyph_asset_entry("tile_asset", asset_data.len())],
vec![],
AssetsPayloadSource::from_bytes(asset_data),
);
@@ -718,9 +721,9 @@ fn tick_asset_commit_invalid_transition_returns_status_not_crash() {
);
let cartridge = cartridge_with_program(program, caps::ASSET);
let asset_data = test_tile_asset_data();
let asset_data = test_glyph_asset_data();
hardware.assets.initialize_for_cartridge(
vec![test_tile_asset_entry("tile_asset", asset_data.len())],
vec![test_glyph_asset_entry("tile_asset", asset_data.len())],
vec![],
AssetsPayloadSource::from_bytes(asset_data),
);
@@ -779,9 +782,9 @@ fn tick_asset_cancel_invalid_transition_returns_status_not_crash() {
);
let cartridge = cartridge_with_program(program, caps::ASSET);
let asset_data = test_tile_asset_data();
let asset_data = test_glyph_asset_data();
hardware.assets.initialize_for_cartridge(
vec![test_tile_asset_entry("tile_asset", asset_data.len())],
vec![test_glyph_asset_entry("tile_asset", asset_data.len())],
vec![],
AssetsPayloadSource::from_bytes(asset_data),
);
@@ -166,7 +166,7 @@ impl VirtualMachineRuntime {
self.last_frame_cpu_time_us = start.elapsed().as_micros() as u64;
let gfx_stats = hw.assets().bank_info(BankType::TILES);
let gfx_stats = hw.assets().bank_info(BankType::GLYPH);
self.telemetry_current.gfx_used_bytes = gfx_stats.used_bytes;
self.telemetry_current.gfx_inflight_bytes = gfx_stats.inflight_bytes;
self.telemetry_current.gfx_slots_occupied = gfx_stats.slots_occupied as u32;
+1 -1
View File
@@ -67,7 +67,7 @@ pub fn generate() -> Result<()> {
const_pool: vec![
ConstantPoolEntry::String("stress".into()),
ConstantPoolEntry::String("frame".into()),
ConstantPoolEntry::String("missing_tile_bank".into()),
ConstantPoolEntry::String("missing_glyph_bank".into()),
],
functions,
code: rom,