fix(runtime): bound camera resolver work and handle extreme coordinates
Intrepid/Prometeu/Runtime/pipeline/head This commit looks good
Intrepid/Prometeu/Runtime/pipeline/head This commit looks good
Preserve camera hysteresis with constant-time wide arithmetic, refresh nonoverlapping cache jumps, and clip wide offsets before drawing. Add guest pixel-oracle and resource/snapshot regressions and document the contract. Validated by the complete tooling verify run 20261126T113331Z-1d071c1d (all 11 stages passed), plus focused debug/release tests. Work: WRK-0020.
This commit is contained in:
@@ -770,16 +770,16 @@ impl Gfx {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
let tile_size_px = request.tile_size as i32;
|
let tile_size_px = request.tile_size as i64;
|
||||||
for cache_y in 0..layer_cache.height() {
|
for cache_y in 0..layer_cache.height() {
|
||||||
let screen_tile_y = cache_y as i32 * tile_size_px - request.source_offset_y_px;
|
let screen_tile_y = cache_y as i64 * tile_size_px - request.source_offset_y_px;
|
||||||
if screen_tile_y >= screen_h as i32 || screen_tile_y + tile_size_px <= 0 {
|
if screen_tile_y >= screen_h as i64 || screen_tile_y + tile_size_px <= 0 {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
for cache_x in 0..layer_cache.width() {
|
for cache_x in 0..layer_cache.width() {
|
||||||
let screen_tile_x = cache_x as i32 * tile_size_px - request.source_offset_x_px;
|
let screen_tile_x = cache_x as i64 * tile_size_px - request.source_offset_x_px;
|
||||||
if screen_tile_x >= screen_w as i32 || screen_tile_x + tile_size_px <= 0 {
|
if screen_tile_x >= screen_w as i64 || screen_tile_x + tile_size_px <= 0 {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -791,8 +791,10 @@ impl Gfx {
|
|||||||
Self::draw_cached_tile_pixels(
|
Self::draw_cached_tile_pixels(
|
||||||
&mut target,
|
&mut target,
|
||||||
CachedTileDraw {
|
CachedTileDraw {
|
||||||
x: screen_tile_x,
|
// Culling leaves -tile_size < local < screen extent;
|
||||||
y: screen_tile_y,
|
// only these small local coordinates enter the pixel loop.
|
||||||
|
x: i32::try_from(screen_tile_x).expect("visible tile x must fit Int32"),
|
||||||
|
y: i32::try_from(screen_tile_y).expect("visible tile y must fit Int32"),
|
||||||
entry,
|
entry,
|
||||||
bank: &bank,
|
bank: &bank,
|
||||||
tile_size: request.tile_size,
|
tile_size: request.tile_size,
|
||||||
|
|||||||
@@ -107,3 +107,55 @@ fn native_tile_edges_and_mixed_camera_layers_cover_every_corner() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cache_tiles_are_clipped_in_wide_coordinates_before_local_pixel_drawing() {
|
||||||
|
let banks = Arc::new(MemoryBanks::new());
|
||||||
|
let mut bank = GlyphBank::new(TileSize::Size8, 8, 8);
|
||||||
|
bank.pixel_indices.fill(1);
|
||||||
|
bank.palettes[0][1] = Color::WHITE;
|
||||||
|
banks.install_glyph_bank(0, Arc::new(bank));
|
||||||
|
let scene = SceneBank {
|
||||||
|
layers: std::array::from_fn(|_| SceneLayer {
|
||||||
|
active: true,
|
||||||
|
glyph_asset_id: 0,
|
||||||
|
tile_size: TileSize::Size8,
|
||||||
|
parallax_factor: ParallaxFactor { x: 1.0, y: 1.0 },
|
||||||
|
tilemap: TileMap {
|
||||||
|
width: 128,
|
||||||
|
height: 128,
|
||||||
|
tiles: vec![
|
||||||
|
Tile {
|
||||||
|
active: true,
|
||||||
|
glyph: Glyph { glyph_id: 0, palette_id: 0 },
|
||||||
|
flip_x: false,
|
||||||
|
flip_y: false,
|
||||||
|
};
|
||||||
|
128 * 128
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
let mut resolver = SceneViewportResolver::new(640, 360, 85, 49, 4, 12);
|
||||||
|
let mut cache = SceneViewportCache::new(&scene, 85, 49);
|
||||||
|
cache.materialize_all_layers(&scene);
|
||||||
|
let mut gfx = Gfx::new(WIDTH, HEIGHT, banks);
|
||||||
|
let mut update = resolver.update(&scene, 0, 0);
|
||||||
|
gfx.render_scene_from_cache(&cache, &update, &[0; 4]);
|
||||||
|
gfx.present();
|
||||||
|
assert!(gfx.front_buffer().iter().all(|&p| p == Color::WHITE.raw()));
|
||||||
|
for offset in [i64::from(i32::MIN), i64::from(i32::MAX), -(1_i64 << 37), 1_i64 << 37] {
|
||||||
|
for vertical in [false, true] {
|
||||||
|
for copy in &mut update.copy_requests {
|
||||||
|
copy.source_offset_x_px = if vertical { 0 } else { offset };
|
||||||
|
copy.source_offset_y_px = if vertical { offset } else { 0 };
|
||||||
|
}
|
||||||
|
gfx.render_scene_from_cache(&cache, &update, &[0; 4]);
|
||||||
|
gfx.present();
|
||||||
|
assert!(
|
||||||
|
gfx.front_buffer().iter().all(|&p| p == Color::BLACK.raw()),
|
||||||
|
"off-scene offset={offset}, vertical={vertical}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -22,8 +22,8 @@ pub struct LayerCopyRequest {
|
|||||||
pub tile_size: TileSize,
|
pub tile_size: TileSize,
|
||||||
pub viewport_width_px: i32,
|
pub viewport_width_px: i32,
|
||||||
pub viewport_height_px: i32,
|
pub viewport_height_px: i32,
|
||||||
pub source_offset_x_px: i32,
|
pub source_offset_x_px: i64,
|
||||||
pub source_offset_y_px: i32,
|
pub source_offset_y_px: i64,
|
||||||
pub cache_origin_tile_x: i32,
|
pub cache_origin_tile_x: i32,
|
||||||
pub cache_origin_tile_y: i32,
|
pub cache_origin_tile_y: i32,
|
||||||
pub camera_x_px: i32,
|
pub camera_x_px: i32,
|
||||||
@@ -49,6 +49,8 @@ pub struct SceneViewportResolver {
|
|||||||
initialized: bool,
|
initialized: bool,
|
||||||
master_anchor: TileAnchor,
|
master_anchor: TileAnchor,
|
||||||
layer_anchors: [TileAnchor; 4],
|
layer_anchors: [TileAnchor; 4],
|
||||||
|
#[cfg(test)]
|
||||||
|
axis_evaluations: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SceneViewportResolver {
|
impl SceneViewportResolver {
|
||||||
@@ -70,6 +72,8 @@ impl SceneViewportResolver {
|
|||||||
initialized: false,
|
initialized: false,
|
||||||
master_anchor: TileAnchor::default(),
|
master_anchor: TileAnchor::default(),
|
||||||
layer_anchors: [TileAnchor::default(); 4],
|
layer_anchors: [TileAnchor::default(); 4],
|
||||||
|
#[cfg(test)]
|
||||||
|
axis_evaluations: 0,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -90,16 +94,22 @@ impl SceneViewportResolver {
|
|||||||
camera_y_px: i32,
|
camera_y_px: i32,
|
||||||
) -> ResolverUpdate {
|
) -> ResolverUpdate {
|
||||||
let mut refresh_requests = Vec::new();
|
let mut refresh_requests = Vec::new();
|
||||||
let camera_center_x = camera_x_px + self.viewport_width_px / 2;
|
#[cfg(test)]
|
||||||
let camera_center_y = camera_y_px + self.viewport_height_px / 2;
|
{
|
||||||
|
self.axis_evaluations = 0;
|
||||||
|
}
|
||||||
|
let camera_center_x = i64::from(camera_x_px) + i64::from(self.viewport_width_px / 2);
|
||||||
|
let camera_center_y = i64::from(camera_y_px) + i64::from(self.viewport_height_px / 2);
|
||||||
|
|
||||||
let layer_inputs: [(i32, i32, i32, i32, i32); 4] = std::array::from_fn(|i| {
|
let layer_inputs: [(i64, i32, i32, i64, i64); 4] = std::array::from_fn(|i| {
|
||||||
let layer = &scene.layers[i];
|
let layer = &scene.layers[i];
|
||||||
let tile_size_px = layer.tile_size as i32;
|
let tile_size_px = layer.tile_size as i64;
|
||||||
let layer_camera_x_px = ((camera_x_px as f32) * layer.parallax_factor.x).floor() as i32;
|
let layer_camera_x_px = ((camera_x_px as f32) * layer.parallax_factor.x).floor() as i32;
|
||||||
let layer_camera_y_px = ((camera_y_px as f32) * layer.parallax_factor.y).floor() as i32;
|
let layer_camera_y_px = ((camera_y_px as f32) * layer.parallax_factor.y).floor() as i32;
|
||||||
let layer_center_x_px = layer_camera_x_px + self.viewport_width_px / 2;
|
let layer_center_x_px =
|
||||||
let layer_center_y_px = layer_camera_y_px + self.viewport_height_px / 2;
|
i64::from(layer_camera_x_px) + i64::from(self.viewport_width_px / 2);
|
||||||
|
let layer_center_y_px =
|
||||||
|
i64::from(layer_camera_y_px) + i64::from(self.viewport_height_px / 2);
|
||||||
(
|
(
|
||||||
tile_size_px,
|
tile_size_px,
|
||||||
layer_camera_x_px,
|
layer_camera_x_px,
|
||||||
@@ -113,7 +123,7 @@ impl SceneViewportResolver {
|
|||||||
self.master_anchor = self.initial_anchor(
|
self.master_anchor = self.initial_anchor(
|
||||||
scene.layers[0].tilemap.width,
|
scene.layers[0].tilemap.width,
|
||||||
scene.layers[0].tilemap.height,
|
scene.layers[0].tilemap.height,
|
||||||
scene.layers[0].tile_size as i32,
|
scene.layers[0].tile_size as i64,
|
||||||
camera_center_x,
|
camera_center_x,
|
||||||
camera_center_y,
|
camera_center_y,
|
||||||
);
|
);
|
||||||
@@ -123,7 +133,7 @@ impl SceneViewportResolver {
|
|||||||
self.layer_anchors[layer_index] = self.initial_anchor(
|
self.layer_anchors[layer_index] = self.initial_anchor(
|
||||||
layer.tilemap.width,
|
layer.tilemap.width,
|
||||||
layer.tilemap.height,
|
layer.tilemap.height,
|
||||||
layer.tile_size as i32,
|
layer.tile_size as i64,
|
||||||
layer_center_x_px,
|
layer_center_x_px,
|
||||||
layer_center_y_px,
|
layer_center_y_px,
|
||||||
);
|
);
|
||||||
@@ -145,7 +155,7 @@ impl SceneViewportResolver {
|
|||||||
self.master_anchor,
|
self.master_anchor,
|
||||||
camera_center_x,
|
camera_center_x,
|
||||||
camera_center_y,
|
camera_center_y,
|
||||||
layer0.tile_size as i32,
|
layer0.tile_size as i64,
|
||||||
layer0.tilemap.width,
|
layer0.tilemap.width,
|
||||||
layer0.tilemap.height,
|
layer0.tilemap.height,
|
||||||
);
|
);
|
||||||
@@ -174,16 +184,16 @@ impl SceneViewportResolver {
|
|||||||
let anchor = self.layer_anchors[layer_index];
|
let anchor = self.layer_anchors[layer_index];
|
||||||
let cache_origin_tile_x = anchor.x - (self.cache_width_tiles as i32 / 2);
|
let cache_origin_tile_x = anchor.x - (self.cache_width_tiles as i32 / 2);
|
||||||
let cache_origin_tile_y = anchor.y - (self.cache_height_tiles as i32 / 2);
|
let cache_origin_tile_y = anchor.y - (self.cache_height_tiles as i32 / 2);
|
||||||
let cache_origin_x_px = cache_origin_tile_x * tile_size_px;
|
let cache_origin_x_px = i64::from(cache_origin_tile_x) * tile_size_px;
|
||||||
let cache_origin_y_px = cache_origin_tile_y * tile_size_px;
|
let cache_origin_y_px = i64::from(cache_origin_tile_y) * tile_size_px;
|
||||||
|
|
||||||
LayerCopyRequest {
|
LayerCopyRequest {
|
||||||
layer_index,
|
layer_index,
|
||||||
tile_size: layer.tile_size,
|
tile_size: layer.tile_size,
|
||||||
viewport_width_px: self.viewport_width_px,
|
viewport_width_px: self.viewport_width_px,
|
||||||
viewport_height_px: self.viewport_height_px,
|
viewport_height_px: self.viewport_height_px,
|
||||||
source_offset_x_px: layer_camera_x_px - cache_origin_x_px,
|
source_offset_x_px: i64::from(layer_camera_x_px) - cache_origin_x_px,
|
||||||
source_offset_y_px: layer_camera_y_px - cache_origin_y_px,
|
source_offset_y_px: i64::from(layer_camera_y_px) - cache_origin_y_px,
|
||||||
cache_origin_tile_x,
|
cache_origin_tile_x,
|
||||||
cache_origin_tile_y,
|
cache_origin_tile_y,
|
||||||
camera_x_px: layer_camera_x_px,
|
camera_x_px: layer_camera_x_px,
|
||||||
@@ -200,91 +210,74 @@ impl SceneViewportResolver {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn initial_anchor(
|
fn initial_anchor(
|
||||||
&self,
|
&mut self,
|
||||||
scene_width_tiles: usize,
|
scene_width_tiles: usize,
|
||||||
scene_height_tiles: usize,
|
scene_height_tiles: usize,
|
||||||
tile_size_px: i32,
|
tile_size_px: i64,
|
||||||
camera_center_x_px: i32,
|
camera_center_x_px: i64,
|
||||||
camera_center_y_px: i32,
|
camera_center_y_px: i64,
|
||||||
) -> TileAnchor {
|
) -> TileAnchor {
|
||||||
let proposed = TileAnchor {
|
#[cfg(test)]
|
||||||
x: camera_center_x_px.div_euclid(tile_size_px),
|
{
|
||||||
y: camera_center_y_px.div_euclid(tile_size_px),
|
self.axis_evaluations += 2;
|
||||||
};
|
}
|
||||||
self.clamp_anchor(proposed, scene_width_tiles, scene_height_tiles)
|
TileAnchor {
|
||||||
|
x: Self::clamp_axis(
|
||||||
|
camera_center_x_px.div_euclid(tile_size_px),
|
||||||
|
scene_width_tiles,
|
||||||
|
self.cache_width_tiles,
|
||||||
|
),
|
||||||
|
y: Self::clamp_axis(
|
||||||
|
camera_center_y_px.div_euclid(tile_size_px),
|
||||||
|
scene_height_tiles,
|
||||||
|
self.cache_height_tiles,
|
||||||
|
),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn advance_anchor(
|
fn advance_anchor(
|
||||||
&self,
|
&mut self,
|
||||||
current: TileAnchor,
|
current: TileAnchor,
|
||||||
camera_center_x_px: i32,
|
camera_center_x_px: i64,
|
||||||
camera_center_y_px: i32,
|
camera_center_y_px: i64,
|
||||||
tile_size_px: i32,
|
tile_size_px: i64,
|
||||||
scene_width_tiles: usize,
|
scene_width_tiles: usize,
|
||||||
scene_height_tiles: usize,
|
scene_height_tiles: usize,
|
||||||
) -> TileAnchor {
|
) -> TileAnchor {
|
||||||
let mut next = current;
|
#[cfg(test)]
|
||||||
// Mixed layers must not step past the center and immediately step back.
|
{
|
||||||
let trigger = self.hysteresis_trigger_px.max(tile_size_px / 2);
|
self.axis_evaluations += 2;
|
||||||
|
|
||||||
loop {
|
|
||||||
let center_x_px = next.x * tile_size_px + tile_size_px / 2;
|
|
||||||
let drift_x = camera_center_x_px - center_x_px;
|
|
||||||
if drift_x.abs() <= self.hysteresis_safe_px {
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
if drift_x > trigger {
|
let next_x = self.advance_axis(current.x, camera_center_x_px, tile_size_px);
|
||||||
next.x += 1;
|
let next_y = self.advance_axis(current.y, camera_center_y_px, tile_size_px);
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if drift_x < -trigger {
|
|
||||||
next.x -= 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
loop {
|
|
||||||
let center_y_px = next.y * tile_size_px + tile_size_px / 2;
|
|
||||||
let drift_y = camera_center_y_px - center_y_px;
|
|
||||||
if drift_y.abs() <= self.hysteresis_safe_px {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
if drift_y > trigger {
|
|
||||||
next.y += 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if drift_y < -trigger {
|
|
||||||
next.y -= 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
self.clamp_anchor(next, scene_width_tiles, scene_height_tiles)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn clamp_anchor(
|
|
||||||
&self,
|
|
||||||
proposed: TileAnchor,
|
|
||||||
scene_width_tiles: usize,
|
|
||||||
scene_height_tiles: usize,
|
|
||||||
) -> TileAnchor {
|
|
||||||
TileAnchor {
|
TileAnchor {
|
||||||
x: self.clamp_axis(proposed.x, scene_width_tiles, self.cache_width_tiles),
|
x: Self::clamp_axis(next_x, scene_width_tiles, self.cache_width_tiles),
|
||||||
y: self.clamp_axis(proposed.y, scene_height_tiles, self.cache_height_tiles),
|
y: Self::clamp_axis(next_y, scene_height_tiles, self.cache_height_tiles),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn clamp_axis(&self, proposed: i32, scene_tiles: usize, cache_tiles: usize) -> i32 {
|
fn advance_axis(&self, current: i32, camera_center_px: i64, tile_size_px: i64) -> i64 {
|
||||||
let half = (cache_tiles / 2) as i32;
|
// This is the first tile step whose drift is inside either stopping band.
|
||||||
if scene_tiles <= cache_tiles {
|
// The half-tile floor prevents a mixed-size layer from stepping back again.
|
||||||
return half;
|
let bound = i64::from(self.hysteresis_safe_px.max(self.hysteresis_trigger_px))
|
||||||
|
.max(tile_size_px / 2);
|
||||||
|
let current = i64::from(current);
|
||||||
|
let drift = camera_center_px - (current * tile_size_px + tile_size_px / 2);
|
||||||
|
if drift > bound {
|
||||||
|
current + (drift - bound + tile_size_px - 1) / tile_size_px
|
||||||
|
} else if drift < -bound {
|
||||||
|
current - (-drift - bound + tile_size_px - 1) / tile_size_px
|
||||||
|
} else {
|
||||||
|
current
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let min = half;
|
fn clamp_axis(proposed: i64, scene_tiles: usize, cache_tiles: usize) -> i32 {
|
||||||
let max = (scene_tiles - cache_tiles) as i32 + half;
|
let min = (cache_tiles / 2) as i64;
|
||||||
proposed.clamp(min, max)
|
let max = scene_tiles.saturating_sub(cache_tiles) as i64 + min;
|
||||||
|
// Int32 camera centers divided by tiles >= 8 and runtime-sized caches
|
||||||
|
// yield Int32 anchors, even when a serialized scene dimension is u32::MAX.
|
||||||
|
i32::try_from(proposed.clamp(min, max)).expect("viewport anchor must fit Int32")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn emit_refresh_requests(
|
fn emit_refresh_requests(
|
||||||
@@ -297,6 +290,16 @@ impl SceneViewportResolver {
|
|||||||
let delta_x = next.x - previous.x;
|
let delta_x = next.x - previous.x;
|
||||||
let delta_y = next.y - previous.y;
|
let delta_y = next.y - previous.y;
|
||||||
|
|
||||||
|
if delta_x.unsigned_abs() as usize >= self.cache_width_tiles
|
||||||
|
|| delta_y.unsigned_abs() as usize >= self.cache_height_tiles
|
||||||
|
{
|
||||||
|
requests.push(CacheRefreshRequest::RefreshRegion {
|
||||||
|
layer_index,
|
||||||
|
region: ViewportRegion::new(0, 0, self.cache_width_tiles, self.cache_height_tiles),
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if delta_x == 0 && delta_y == 0 {
|
if delta_x == 0 && delta_y == 0 {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -585,4 +588,190 @@ mod tests {
|
|||||||
.all(|request| matches!(request, CacheRefreshRequest::InvalidateLayer { .. }))
|
.all(|request| matches!(request, CacheRefreshRequest::InvalidateLayer { .. }))
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn uniform_scene(width: usize, height: usize) -> SceneBank {
|
||||||
|
SceneBank {
|
||||||
|
layers: std::array::from_fn(|_| make_layer(TileSize::Size8, 1.0, 1.0, width, height)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn native_resolver() -> SceneViewportResolver {
|
||||||
|
SceneViewportResolver::new(640, 360, 85, 49, 4, 12)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn refresh_area(update: &ResolverUpdate, width: usize, height: usize) -> usize {
|
||||||
|
update
|
||||||
|
.refresh_requests
|
||||||
|
.iter()
|
||||||
|
.map(|request| match request {
|
||||||
|
CacheRefreshRequest::RefreshLine { cache_y, .. } => {
|
||||||
|
assert!(*cache_y < height);
|
||||||
|
width
|
||||||
|
}
|
||||||
|
CacheRefreshRequest::RefreshColumn { cache_x, .. } => {
|
||||||
|
assert!(*cache_x < width);
|
||||||
|
height
|
||||||
|
}
|
||||||
|
CacheRefreshRequest::RefreshRegion { region, .. } => {
|
||||||
|
assert!(region.x + region.width <= width);
|
||||||
|
assert!(region.y + region.height <= height);
|
||||||
|
region.width * region.height
|
||||||
|
}
|
||||||
|
CacheRefreshRequest::InvalidateLayer { .. } => 0,
|
||||||
|
})
|
||||||
|
.sum()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn arithmetic_advancement_matches_iterative_stopping_bands() {
|
||||||
|
// Independent reference retains the old step-by-step stopping rules,
|
||||||
|
// using small inputs where the original arithmetic is defined.
|
||||||
|
for tile in [8_i64, 16, 32] {
|
||||||
|
for (safe, trigger) in [(4, 12), (12, 20), (28, 36), (40, 4)] {
|
||||||
|
let resolver = SceneViewportResolver::new(640, 360, 85, 49, safe, trigger);
|
||||||
|
for previous in -5..=5 {
|
||||||
|
for center in -128..=128 {
|
||||||
|
let mut expected = i64::from(previous);
|
||||||
|
loop {
|
||||||
|
let drift = center - (expected * tile + tile / 2);
|
||||||
|
if drift.abs() <= i64::from(safe) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let threshold = i64::from(trigger).max(tile / 2);
|
||||||
|
if drift > threshold {
|
||||||
|
expected += 1;
|
||||||
|
} else if drift < -threshold {
|
||||||
|
expected -= 1;
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_eq!(resolver.advance_axis(previous, center, tile), expected);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hysteresis_retains_history_and_partial_columns_at_the_trigger() {
|
||||||
|
let scene = uniform_scene(512, 256);
|
||||||
|
let mut cold = native_resolver();
|
||||||
|
assert_eq!(cold.update(&scene, 24, 0).master_anchor.x, 43);
|
||||||
|
let mut warm = native_resolver();
|
||||||
|
warm.update(&scene, 0, 0);
|
||||||
|
let held = warm.update(&scene, 24, 0);
|
||||||
|
assert_eq!(held.master_anchor.x, 42);
|
||||||
|
assert!(held.refresh_requests.is_empty());
|
||||||
|
assert!(warm.update(&scene, 32, 0).refresh_requests.is_empty());
|
||||||
|
let right = warm.update(&scene, 33, 0);
|
||||||
|
assert_eq!(
|
||||||
|
right.refresh_requests,
|
||||||
|
(0..4)
|
||||||
|
.map(|layer_index| {
|
||||||
|
CacheRefreshRequest::RefreshColumn { layer_index, cache_x: 84 }
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
);
|
||||||
|
assert!(warm.update(&scene, 16, 0).refresh_requests.is_empty());
|
||||||
|
let left = warm.update(&scene, 15, 0);
|
||||||
|
assert_eq!(
|
||||||
|
left.refresh_requests,
|
||||||
|
(0..4)
|
||||||
|
.map(|layer_index| {
|
||||||
|
CacheRefreshRequest::RefreshColumn { layer_index, cache_x: 0 }
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn non_overlapping_jumps_materialize_one_cache_per_layer() {
|
||||||
|
let scene = uniform_scene(512, 256);
|
||||||
|
for target in [(1600, 0), (0, 1200), (1600, 1200)] {
|
||||||
|
let mut resolver = native_resolver();
|
||||||
|
resolver.update(&scene, 0, 0);
|
||||||
|
for (x, y) in [target, (0, 0)] {
|
||||||
|
let update = resolver.update(&scene, x, y);
|
||||||
|
assert_eq!(
|
||||||
|
update.refresh_requests,
|
||||||
|
(0..4)
|
||||||
|
.map(|layer_index| {
|
||||||
|
CacheRefreshRequest::RefreshRegion {
|
||||||
|
layer_index,
|
||||||
|
region: ViewportRegion::new(0, 0, 85, 49),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
);
|
||||||
|
assert_eq!(refresh_area(&update, 85, 49), 4 * 85 * 49);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn axis_work_and_materialization_are_bounded_at_int32_extremes() {
|
||||||
|
let mut scene = uniform_scene(512, 256);
|
||||||
|
scene.layers[1].tile_size = TileSize::Size16;
|
||||||
|
scene.layers[1].parallax_factor = ParallaxFactor { x: 0.5, y: 0.75 };
|
||||||
|
scene.layers[2].tile_size = TileSize::Size32;
|
||||||
|
scene.layers[2].parallax_factor = ParallaxFactor { x: -0.5, y: 2.0 };
|
||||||
|
scene.layers[3].parallax_factor = ParallaxFactor { x: f32::MAX, y: -f32::MAX };
|
||||||
|
let positions = [
|
||||||
|
(0, 0),
|
||||||
|
(1000, 0),
|
||||||
|
(1_000_000, 0),
|
||||||
|
(100_000_000, 0),
|
||||||
|
(i32::MAX, i32::MIN),
|
||||||
|
(i32::MIN, i32::MAX),
|
||||||
|
(0, 0),
|
||||||
|
];
|
||||||
|
for first in [(i32::MAX, i32::MIN), (i32::MIN, i32::MAX), (0, 0)] {
|
||||||
|
let mut resolver = native_resolver();
|
||||||
|
for (x, y) in std::iter::once(first).chain(positions) {
|
||||||
|
let update = resolver.update(&scene, x, y);
|
||||||
|
assert_eq!(resolver.axis_evaluations, 10);
|
||||||
|
assert!(refresh_area(&update, 85, 49) <= 4 * 85 * 49);
|
||||||
|
assert!(update.refresh_requests.len() <= 4 * 84);
|
||||||
|
for copy in update.copy_requests {
|
||||||
|
assert!(copy.cache_origin_tile_x >= 0 && copy.cache_origin_tile_y >= 0);
|
||||||
|
assert_eq!(
|
||||||
|
copy.source_offset_x_px,
|
||||||
|
i64::from(copy.camera_x_px)
|
||||||
|
- i64::from(copy.cache_origin_tile_x) * copy.tile_size as i64
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn empty_scene_dimensions_keep_wide_clamp_bounds() {
|
||||||
|
for (width, height) in [(u32::MAX as usize, 0), (0, u32::MAX as usize), (0, 0)] {
|
||||||
|
let scene = uniform_scene(width, height);
|
||||||
|
let mut resolver = native_resolver();
|
||||||
|
for (x, y) in [(0, 0), (i32::MAX, i32::MIN), (i32::MIN, i32::MAX), (0, 0)] {
|
||||||
|
let update = resolver.update(&scene, x, y);
|
||||||
|
assert!(refresh_area(&update, 85, 49) <= 4 * 85 * 49);
|
||||||
|
if width == 0 {
|
||||||
|
assert_eq!(update.master_anchor.x, 42);
|
||||||
|
}
|
||||||
|
if height == 0 {
|
||||||
|
assert_eq!(update.master_anchor.y, 24);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parallax_keeps_existing_float_quantization_and_negative_floor() {
|
||||||
|
let mut scene = uniform_scene(128, 128);
|
||||||
|
scene.layers[1].parallax_factor = ParallaxFactor { x: 0.5, y: -0.5 };
|
||||||
|
let mut resolver = native_resolver();
|
||||||
|
let large = resolver.update(&scene, 16_777_217, 0);
|
||||||
|
assert_eq!(large.copy_requests[0].camera_x_px, 16_777_216);
|
||||||
|
let negative = resolver.update(&scene, -3, 3);
|
||||||
|
assert_eq!(negative.copy_requests[1].camera_x_px, -2);
|
||||||
|
assert_eq!(negative.copy_requests[1].camera_y_px, -2);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,155 @@
|
|||||||
|
#[path = "support/camera.rs"]
|
||||||
|
mod camera;
|
||||||
|
use camera::*;
|
||||||
|
use prometeu_drivers::{GlyphBankPoolAccess, SceneBankPoolAccess};
|
||||||
|
use prometeu_hal::{Gfx2dCommand, color::Color, primitives::Rect};
|
||||||
|
use prometeu_host_headless::{AdvanceFrameOutcome, HeadlessHost};
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
fn assert_guest_frames(fixture: &CameraFixture, positions: &[(i32, i32)]) {
|
||||||
|
let cartridge = fixture.cartridge(positions);
|
||||||
|
let mut host = HeadlessHost::new();
|
||||||
|
host.boot(cartridge.0.to_string_lossy()).unwrap();
|
||||||
|
for (index, &(x, y)) in positions.iter().enumerate() {
|
||||||
|
let result = host.advance_frame().unwrap();
|
||||||
|
assert!(
|
||||||
|
matches!(result, AdvanceFrameOutcome::FrameCompleted { logical_frame_index, .. }
|
||||||
|
if logical_frame_index == index as u64 + 1),
|
||||||
|
"{result:?}, fault={:?}",
|
||||||
|
host.get_fault()
|
||||||
|
);
|
||||||
|
let frame = host.capture_frame().unwrap();
|
||||||
|
assert_pixels(&frame.frame.pixels, &fixture.expected(Some(&fixture.scene), x, y, true));
|
||||||
|
}
|
||||||
|
assert!(host.get_fault().is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn guest_camera_follow_teleport_parallax_and_return_match_canonical_pixels() {
|
||||||
|
for profile in ["size8", "size16", "size32", "mixed", "finite-extreme"] {
|
||||||
|
let fixture = CameraFixture::new(profile, 512, 256);
|
||||||
|
let positions: Vec<_> = (0..24)
|
||||||
|
.map(|n| (n * 4 - 16, 40 + n % 4))
|
||||||
|
.chain((0..12).rev().map(|n| (n * 8, 42)))
|
||||||
|
.chain([
|
||||||
|
(1600, 1200),
|
||||||
|
(0, 0),
|
||||||
|
(-100, -70),
|
||||||
|
(150, 80),
|
||||||
|
(i32::MAX, i32::MIN),
|
||||||
|
(i32::MIN, i32::MAX),
|
||||||
|
(0, 0),
|
||||||
|
])
|
||||||
|
.collect();
|
||||||
|
assert_guest_frames(&fixture, &positions);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn guest_first_frame_handles_extreme_cameras_and_admitted_empty_scenes() {
|
||||||
|
for profile in ["size8", "mixed"] {
|
||||||
|
for first in [(i32::MIN, 0), (0, i32::MIN), (i32::MAX, i32::MAX)] {
|
||||||
|
assert_guest_frames(&CameraFixture::new(profile, 128, 128), &[first, (0, 0)]);
|
||||||
|
}
|
||||||
|
for (width, height) in [(u32::MAX as usize, 0), (0, u32::MAX as usize), (0, 0)] {
|
||||||
|
let fixture = CameraFixture::new(profile, width, height);
|
||||||
|
assert_guest_frames(&fixture, &[(0, 0), (i32::MAX, i32::MIN), (0, 0)]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn closed_camera_packet_ignores_live_changes_and_preserves_resident_resources() {
|
||||||
|
for profile in ["size8", "mixed"] {
|
||||||
|
let fixture = CameraFixture::new(profile, 512, 256);
|
||||||
|
let mut hw = fixture.hardware(false);
|
||||||
|
let scene = hw.memory_banks.scene_bank_slot(0).unwrap();
|
||||||
|
let scene_bytes = scene_payload(&scene);
|
||||||
|
let glyphs: Vec<_> = (0..4).map(|i| hw.memory_banks.glyph_bank_slot(i).unwrap()).collect();
|
||||||
|
hw.frame_composer.bind_scene(0);
|
||||||
|
hw.frame_composer.set_camera(40, 20);
|
||||||
|
for sprite in sprites() {
|
||||||
|
assert!(hw.frame_composer.emit_sprite(sprite));
|
||||||
|
}
|
||||||
|
let packet = hw.frame_composer.close_game2d_packet();
|
||||||
|
let saved = packet.clone();
|
||||||
|
hw.frame_composer.set_camera(i32::MAX, i32::MIN);
|
||||||
|
hw.frame_composer.begin_frame();
|
||||||
|
hw.frame_composer.unbind_scene();
|
||||||
|
hw.frame_composer.render_game2d_frame_packet(&packet, &mut hw.gfx);
|
||||||
|
hw.gfx.present();
|
||||||
|
assert_eq!(packet, saved);
|
||||||
|
assert_eq!(hw.frame_composer.camera(), (40, 20));
|
||||||
|
assert_pixels(
|
||||||
|
hw.gfx.front_buffer(),
|
||||||
|
&fixture.expected(Some(&fixture.scene), 40, 20, false),
|
||||||
|
);
|
||||||
|
assert_cache(hw.frame_composer.cache().unwrap(), &fixture.scene);
|
||||||
|
assert!(Arc::ptr_eq(&scene, hw.frame_composer.active_scene().unwrap()));
|
||||||
|
assert_resident_identity(&hw, &[scene], &glyphs);
|
||||||
|
assert_eq!(scene_bytes, scene_payload(&hw.memory_banks.scene_bank_slot(0).unwrap()));
|
||||||
|
for (i, actual) in glyphs.iter().enumerate() {
|
||||||
|
let expected = fixture.glyph_bank(i);
|
||||||
|
assert_eq!(actual.pixel_indices, expected.pixel_indices);
|
||||||
|
assert_eq!(actual.palettes, expected.palettes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn camera_scene_transitions_preserve_ring_contents_resources_and_no_scene_buffers() {
|
||||||
|
for profile in ["size8", "mixed"] {
|
||||||
|
let fixture = CameraFixture::new(profile, 512, 256);
|
||||||
|
let mut hw = fixture.hardware(true);
|
||||||
|
let scenes: Vec<_> = (0..2).map(|i| hw.memory_banks.scene_bank_slot(i).unwrap()).collect();
|
||||||
|
let glyphs: Vec<_> = (0..4).map(|i| hw.memory_banks.glyph_bank_slot(i).unwrap()).collect();
|
||||||
|
let mut reference_front = vec![Color::BLACK.raw(); WIDTH * HEIGHT];
|
||||||
|
let mut reference_back = reference_front.clone();
|
||||||
|
for (slot, x, y) in [
|
||||||
|
(Some(0), 0, 0),
|
||||||
|
(Some(0), 1600, 1200),
|
||||||
|
(None, 0, 0),
|
||||||
|
(Some(1), 100, 40),
|
||||||
|
(Some(0), 20, 10),
|
||||||
|
] {
|
||||||
|
hw.frame_composer.begin_frame();
|
||||||
|
if slot != hw.frame_composer.active_scene_id() {
|
||||||
|
match slot {
|
||||||
|
Some(slot) => assert!(hw.frame_composer.bind_scene(slot)),
|
||||||
|
None => hw.frame_composer.unbind_scene(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
hw.frame_composer.set_camera(x, y);
|
||||||
|
for sprite in sprites() {
|
||||||
|
assert!(hw.frame_composer.emit_sprite(sprite));
|
||||||
|
}
|
||||||
|
let packet = hw.frame_composer.close_game2d_packet();
|
||||||
|
assert_eq!((packet.composer.camera.x, packet.composer.camera.y), (x, y));
|
||||||
|
hw.frame_composer.render_game2d_frame_packet(&packet, &mut hw.gfx);
|
||||||
|
hw.gfx.apply_gfx2d_commands(&[Gfx2dCommand::FillRect {
|
||||||
|
rect: Rect { x: 3, y: 4, w: 13, h: 7 },
|
||||||
|
color: Color::CYAN,
|
||||||
|
}]);
|
||||||
|
hw.gfx.present();
|
||||||
|
let direct = fixture.expected(slot.map(|i| scenes[i].as_ref()), x, y, true);
|
||||||
|
let expected = if slot.is_some() {
|
||||||
|
direct
|
||||||
|
} else {
|
||||||
|
// No-scene composition preserves the existing back buffer.
|
||||||
|
let mut pixels = reference_back.clone();
|
||||||
|
for (index, &pixel) in direct.iter().enumerate() {
|
||||||
|
if pixel != Color::BLACK.raw() {
|
||||||
|
pixels[index] = pixel;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pixels
|
||||||
|
};
|
||||||
|
assert_pixels(hw.gfx.front_buffer(), &expected);
|
||||||
|
reference_back = std::mem::replace(&mut reference_front, expected);
|
||||||
|
assert_resident_identity(&hw, &scenes, &glyphs);
|
||||||
|
if let Some(i) = slot {
|
||||||
|
assert_cache(hw.frame_composer.cache().unwrap(), &scenes[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,453 @@
|
|||||||
|
use prometeu_bytecode::{
|
||||||
|
assembler::assemble,
|
||||||
|
model::{Export, SyscallDecl},
|
||||||
|
registry::Signature,
|
||||||
|
};
|
||||||
|
use prometeu_drivers::{
|
||||||
|
ControlledWallClock, GlyphBankPoolAccess, SceneBankPoolAccess, hardware::Hardware,
|
||||||
|
};
|
||||||
|
use prometeu_hal::{
|
||||||
|
asset::*,
|
||||||
|
cartridge::*,
|
||||||
|
color::Color,
|
||||||
|
glyph::Glyph,
|
||||||
|
glyph_bank::{GlyphBank, TileSize},
|
||||||
|
scene_bank::SceneBank,
|
||||||
|
scene_layer::{ParallaxFactor, SceneLayer},
|
||||||
|
scene_viewport_cache::{CachedTileEntry, SceneViewportCache},
|
||||||
|
sprite::Sprite,
|
||||||
|
tile::Tile,
|
||||||
|
tilemap::TileMap,
|
||||||
|
};
|
||||||
|
use prometeu_test_support::program::TestProgram;
|
||||||
|
use serde_json::json;
|
||||||
|
use std::{
|
||||||
|
path::PathBuf,
|
||||||
|
sync::Arc,
|
||||||
|
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
|
||||||
|
};
|
||||||
|
|
||||||
|
pub const WIDTH: usize = 640;
|
||||||
|
pub const HEIGHT: usize = 360;
|
||||||
|
|
||||||
|
pub struct CameraFixture {
|
||||||
|
pub scene: SceneBank,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn color(layer: usize, palette: u8, index: u8) -> Color {
|
||||||
|
if index == 0 {
|
||||||
|
return Color::TRANSPARENT;
|
||||||
|
}
|
||||||
|
Color::rgba(
|
||||||
|
20 + layer as u8 * 40 + index * 3,
|
||||||
|
25 + palette * 45 + index * 2,
|
||||||
|
180 - index * 11,
|
||||||
|
if index == 3 { 128 } else { 255 },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pixel_index(layer: usize, glyph: u16, x: usize, y: usize) -> u8 {
|
||||||
|
((x + 3 * y + glyph as usize * 5 + layer) % 8) as u8
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CameraFixture {
|
||||||
|
pub fn new(profile: &str, width: usize, height: usize) -> Self {
|
||||||
|
Self {
|
||||||
|
scene: SceneBank {
|
||||||
|
layers: std::array::from_fn(|i| {
|
||||||
|
let (size, x, y) = match profile {
|
||||||
|
"size16" => (TileSize::Size16, 1.0, 1.0),
|
||||||
|
"size32" => (TileSize::Size32, 1.0, 1.0),
|
||||||
|
"mixed" => [
|
||||||
|
(TileSize::Size8, 1.0, 1.0),
|
||||||
|
(TileSize::Size16, 0.5, 0.75),
|
||||||
|
(TileSize::Size32, 0.25, 0.5),
|
||||||
|
(TileSize::Size16, -0.5, 2.0),
|
||||||
|
][i],
|
||||||
|
"finite-extreme" => (TileSize::Size8, f32::MAX, -f32::MAX),
|
||||||
|
_ => (TileSize::Size8, 1.0, 1.0),
|
||||||
|
};
|
||||||
|
SceneLayer {
|
||||||
|
active: true,
|
||||||
|
glyph_asset_id: 100 + i as i32,
|
||||||
|
tile_size: size,
|
||||||
|
parallax_factor: ParallaxFactor { x, y },
|
||||||
|
tilemap: TileMap {
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
tiles: (0..width * height)
|
||||||
|
.map(|n| Tile {
|
||||||
|
active: !(n % width + n / width + i).is_multiple_of(5),
|
||||||
|
glyph: Glyph {
|
||||||
|
glyph_id: (n % 2) as u16,
|
||||||
|
palette_id: ((n % width + 3 * (n / width)) % 4) as u8,
|
||||||
|
},
|
||||||
|
flip_x: n % 2 == 0,
|
||||||
|
flip_y: n % 3 == 0,
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn glyph_bank(&self, layer: usize) -> GlyphBank {
|
||||||
|
let size = self.scene.layers[layer].tile_size;
|
||||||
|
let n = size as usize;
|
||||||
|
let mut bank = GlyphBank::with_palette_count(size, 2 * n, n, 4);
|
||||||
|
for y in 0..n {
|
||||||
|
for x in 0..2 * n {
|
||||||
|
bank.pixel_indices[y * 2 * n + x] = pixel_index(layer, (x / n) as u16, x % n, y);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for p in 0..4 {
|
||||||
|
for k in 0..16 {
|
||||||
|
bank.palette_mut(p).unwrap()[k] = color(layer, p, k as u8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bank
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn alternate_scene(&self) -> SceneBank {
|
||||||
|
let mut scene = self.scene.clone();
|
||||||
|
for layer in &mut scene.layers {
|
||||||
|
for tile in &mut layer.tilemap.tiles {
|
||||||
|
tile.active = !tile.active;
|
||||||
|
tile.glyph.palette_id = (tile.glyph.palette_id + 1) % 4;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
scene
|
||||||
|
}
|
||||||
|
|
||||||
|
fn assets(&self, second_scene: bool) -> (Vec<AssetEntry>, Vec<PreloadEntry>, Vec<u8>) {
|
||||||
|
let mut entries = Vec::new();
|
||||||
|
let mut preloads = Vec::new();
|
||||||
|
let mut bytes = Vec::new();
|
||||||
|
for i in 0..4 {
|
||||||
|
let bank = self.glyph_bank(i);
|
||||||
|
let mut payload: Vec<u8> =
|
||||||
|
bank.pixel_indices.chunks(2).map(|pair| pair[0] << 4 | pair[1]).collect();
|
||||||
|
for p in 0..4 {
|
||||||
|
for k in 0..16 {
|
||||||
|
payload.extend(color(i, p, k).raw().to_be_bytes());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
entries.push(asset(100 + i as i32, BankType::GLYPH, bytes.len(), &payload,
|
||||||
|
bank.pixel_indices.len() + 4 * 16 * 4,
|
||||||
|
json!({"tile_size": bank.tile_size as usize, "width": bank.width, "height": bank.height,
|
||||||
|
"palette_count": 4, "palette_authored": 4})));
|
||||||
|
preloads.push(PreloadEntry { asset_id: 100 + i as i32, slot: i });
|
||||||
|
bytes.extend(payload);
|
||||||
|
}
|
||||||
|
for slot in 0..if second_scene { 2 } else { 1 } {
|
||||||
|
let scene = if slot == 0 { self.scene.clone() } else { self.alternate_scene() };
|
||||||
|
let payload = scene_payload(&scene);
|
||||||
|
let decoded = scene
|
||||||
|
.layers
|
||||||
|
.iter()
|
||||||
|
.map(|l| {
|
||||||
|
SCENE_DECODED_LAYER_OVERHEAD_BYTES_V1
|
||||||
|
+ l.tilemap.tiles.len() * std::mem::size_of::<Tile>()
|
||||||
|
})
|
||||||
|
.sum();
|
||||||
|
entries.push(asset(
|
||||||
|
200 + slot as i32,
|
||||||
|
BankType::SCENE,
|
||||||
|
bytes.len(),
|
||||||
|
&payload,
|
||||||
|
decoded,
|
||||||
|
json!({}),
|
||||||
|
));
|
||||||
|
preloads.push(PreloadEntry { asset_id: 200 + slot as i32, slot });
|
||||||
|
bytes.extend(payload);
|
||||||
|
}
|
||||||
|
(entries, preloads, bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn hardware(&self, second_scene: bool) -> Hardware {
|
||||||
|
let (entries, _, bytes) = self.assets(second_scene);
|
||||||
|
let hw = Hardware::new(Arc::new(ControlledWallClock::new(0)));
|
||||||
|
hw.assets.initialize_for_cartridge(
|
||||||
|
entries.clone(),
|
||||||
|
vec![],
|
||||||
|
AssetsPayloadSource::from_bytes(bytes),
|
||||||
|
);
|
||||||
|
for (i, entry) in entries.iter().enumerate() {
|
||||||
|
let handle = hw.assets.load(entry.asset_id, if i < 4 { i } else { i - 4 }).unwrap();
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(5);
|
||||||
|
while hw.assets.status(handle) != LoadStatus::READY {
|
||||||
|
assert_ne!(hw.assets.status(handle), LoadStatus::ERROR);
|
||||||
|
assert!(Instant::now() < deadline, "asset loading timed out");
|
||||||
|
std::thread::sleep(Duration::from_millis(1));
|
||||||
|
}
|
||||||
|
assert_eq!(hw.assets.commit(handle), AssetOpStatus::Ok);
|
||||||
|
hw.assets.apply_commits();
|
||||||
|
assert_eq!(hw.assets.status(handle), LoadStatus::COMMITTED);
|
||||||
|
}
|
||||||
|
hw
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn cartridge(&self, cameras: &[(i32, i32)]) -> Cartridge {
|
||||||
|
let directory = std::env::temp_dir().join(format!(
|
||||||
|
"prometeu-camera-{}-{}",
|
||||||
|
std::process::id(),
|
||||||
|
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos()
|
||||||
|
));
|
||||||
|
std::fs::create_dir_all(&directory).unwrap();
|
||||||
|
std::fs::write(directory.join("program.pbx"), program(cameras)).unwrap();
|
||||||
|
std::fs::write(directory.join("manifest.json"), r#"{"magic":"PMTU","cartridge_version":1,"app_id":20,"title":"Camera regression","app_version":"1.0.0","app_mode":"Game","capabilities":["composer","gfx2d","asset"]}"#).unwrap();
|
||||||
|
let (asset_table, preload, bytes) = self.assets(false);
|
||||||
|
let header = serde_json::to_vec(&AssetsPackHeader { asset_table, preload }).unwrap();
|
||||||
|
let prelude = AssetsPackPrelude {
|
||||||
|
magic: ASSETS_PA_MAGIC,
|
||||||
|
schema_version: ASSETS_PA_SCHEMA_VERSION,
|
||||||
|
header_len: header.len() as u32,
|
||||||
|
payload_offset: (ASSETS_PA_PRELUDE_SIZE + header.len()) as u64,
|
||||||
|
flags: 0,
|
||||||
|
reserved: 0,
|
||||||
|
header_checksum: 0,
|
||||||
|
};
|
||||||
|
let mut pack = prelude.to_bytes().to_vec();
|
||||||
|
pack.extend(header);
|
||||||
|
pack.extend(bytes);
|
||||||
|
std::fs::write(directory.join("assets.pa"), pack).unwrap();
|
||||||
|
Cartridge(directory)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Independent pixel oracle: consult canonical tiles and glyph coordinates,
|
||||||
|
// never resolver anchors, copy offsets, cache materialization or ring indices.
|
||||||
|
pub fn expected(&self, scene: Option<&SceneBank>, x: i32, y: i32, overlay: bool) -> Vec<u32> {
|
||||||
|
let mut pixels = vec![Color::BLACK.raw(); WIDTH * HEIGHT];
|
||||||
|
for i in 0..4 {
|
||||||
|
let sprite = sprites()[i];
|
||||||
|
let size = self.scene.layers[i].tile_size as usize;
|
||||||
|
for py in 0..size {
|
||||||
|
for px in 0..size {
|
||||||
|
let sx = i64::from(sprite.x) + px as i64;
|
||||||
|
let sy = i64::from(sprite.y) + py as i64;
|
||||||
|
if sx < 0 || sy < 0 || sx >= WIDTH as i64 || sy >= HEIGHT as i64 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let index = pixel_index(
|
||||||
|
i,
|
||||||
|
sprite.glyph.glyph_id,
|
||||||
|
if sprite.flip_x { size - 1 - px } else { px },
|
||||||
|
if sprite.flip_y { size - 1 - py } else { py },
|
||||||
|
);
|
||||||
|
let c = color(i, sprite.glyph.palette_id, index);
|
||||||
|
if c.alpha() != 0 {
|
||||||
|
pixels[sy as usize * WIDTH + sx as usize] = c.raw();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let Some(scene) = scene else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let layer = &scene.layers[i];
|
||||||
|
let tile_size = layer.tile_size as i64;
|
||||||
|
let lx = i64::from(((x as f32) * layer.parallax_factor.x).floor() as i32);
|
||||||
|
let ly = i64::from(((y as f32) * layer.parallax_factor.y).floor() as i32);
|
||||||
|
for py in 0..HEIGHT {
|
||||||
|
let wy = ly + py as i64;
|
||||||
|
let ty = wy.div_euclid(tile_size);
|
||||||
|
if ty < 0 || ty >= layer.tilemap.height as i64 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for px in 0..WIDTH {
|
||||||
|
let wx = lx + px as i64;
|
||||||
|
let tx = wx.div_euclid(tile_size);
|
||||||
|
if tx < 0 || tx >= layer.tilemap.width as i64 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let tile = layer.tilemap.tiles[ty as usize * layer.tilemap.width + tx as usize];
|
||||||
|
if !tile.active {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let (fx, fy) =
|
||||||
|
(wx.rem_euclid(tile_size) as usize, wy.rem_euclid(tile_size) as usize);
|
||||||
|
let size = tile_size as usize;
|
||||||
|
let index = pixel_index(
|
||||||
|
i,
|
||||||
|
tile.glyph.glyph_id,
|
||||||
|
if tile.flip_x { size - 1 - fx } else { fx },
|
||||||
|
if tile.flip_y { size - 1 - fy } else { fy },
|
||||||
|
);
|
||||||
|
let c = color(i, tile.glyph.palette_id, index);
|
||||||
|
if c.alpha() != 0 {
|
||||||
|
pixels[py * WIDTH + px] = c.raw();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if overlay {
|
||||||
|
for py in 4..11 {
|
||||||
|
for px in 3..16 {
|
||||||
|
pixels[py * WIDTH + px] = Color::CYAN.raw();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pixels
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn asset(
|
||||||
|
id: i32,
|
||||||
|
kind: BankType,
|
||||||
|
offset: usize,
|
||||||
|
payload: &[u8],
|
||||||
|
decoded: usize,
|
||||||
|
metadata: serde_json::Value,
|
||||||
|
) -> AssetEntry {
|
||||||
|
AssetEntry {
|
||||||
|
asset_id: id,
|
||||||
|
asset_name: format!("camera-{id}"),
|
||||||
|
bank_type: kind,
|
||||||
|
offset: offset as u64,
|
||||||
|
size: payload.len() as u64,
|
||||||
|
decoded_size: decoded as u64,
|
||||||
|
codec: AssetCodec::None,
|
||||||
|
metadata,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn scene_payload(scene: &SceneBank) -> Vec<u8> {
|
||||||
|
let mut bytes = SCENE_PAYLOAD_MAGIC_V1.to_vec();
|
||||||
|
bytes.extend(SCENE_PAYLOAD_VERSION_V1.to_le_bytes());
|
||||||
|
bytes.extend(4_u16.to_le_bytes());
|
||||||
|
bytes.extend(0_u32.to_le_bytes());
|
||||||
|
for layer in &scene.layers {
|
||||||
|
bytes.push(u8::from(layer.active));
|
||||||
|
bytes.extend(layer.glyph_asset_id.to_le_bytes());
|
||||||
|
bytes.push(layer.tile_size as u8);
|
||||||
|
bytes.extend(0_u16.to_le_bytes());
|
||||||
|
bytes.extend(layer.parallax_factor.x.to_le_bytes());
|
||||||
|
bytes.extend(layer.parallax_factor.y.to_le_bytes());
|
||||||
|
bytes.extend((layer.tilemap.width as u32).to_le_bytes());
|
||||||
|
bytes.extend((layer.tilemap.height as u32).to_le_bytes());
|
||||||
|
bytes.extend((layer.tilemap.tiles.len() as u32).to_le_bytes());
|
||||||
|
bytes.extend(0_u32.to_le_bytes());
|
||||||
|
for tile in &layer.tilemap.tiles {
|
||||||
|
bytes.push(
|
||||||
|
u8::from(tile.active) | (u8::from(tile.flip_x) << 1) | (u8::from(tile.flip_y) << 2),
|
||||||
|
);
|
||||||
|
bytes.push(tile.glyph.palette_id);
|
||||||
|
bytes.extend(tile.glyph.glyph_id.to_le_bytes());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bytes
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn sprites() -> [Sprite; 4] {
|
||||||
|
std::array::from_fn(|i| Sprite {
|
||||||
|
glyph: Glyph { glyph_id: 1, palette_id: 3 },
|
||||||
|
x: [11, 620, -5, 35][i],
|
||||||
|
y: [17, 345, 20, -3][i],
|
||||||
|
layer: i as u8,
|
||||||
|
bank_id: i as u8,
|
||||||
|
active: true,
|
||||||
|
flip_x: i % 2 == 0,
|
||||||
|
flip_y: i % 2 == 1,
|
||||||
|
priority: 2,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn assert_pixels(actual: &[u32], expected: &[u32]) {
|
||||||
|
assert_eq!(actual.len(), expected.len());
|
||||||
|
assert_eq!(
|
||||||
|
actual.iter().zip(expected).position(|(a, b)| a != b),
|
||||||
|
None,
|
||||||
|
"first mismatched pixel"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn assert_cache(cache: &SceneViewportCache, scene: &SceneBank) {
|
||||||
|
for i in 0..4 {
|
||||||
|
let (ox, oy) = cache.layers[i].logical_origin();
|
||||||
|
let layer = &scene.layers[i];
|
||||||
|
for y in 0..cache.height() {
|
||||||
|
for x in 0..cache.width() {
|
||||||
|
let (sx, sy) = (i64::from(ox) + x as i64, i64::from(oy) + y as i64);
|
||||||
|
let expected = if sx < 0
|
||||||
|
|| sy < 0
|
||||||
|
|| sx >= layer.tilemap.width as i64
|
||||||
|
|| sy >= layer.tilemap.height as i64
|
||||||
|
{
|
||||||
|
CachedTileEntry::default()
|
||||||
|
} else {
|
||||||
|
let tile = layer.tilemap.tiles[sy as usize * layer.tilemap.width + sx as usize];
|
||||||
|
CachedTileEntry {
|
||||||
|
active: tile.active,
|
||||||
|
glyph_id: tile.glyph.glyph_id,
|
||||||
|
palette_id: tile.glyph.palette_id,
|
||||||
|
glyph_asset_id: layer.glyph_asset_id,
|
||||||
|
flags: u8::from(tile.flip_x) | (u8::from(tile.flip_y) << 1),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
assert_eq!(cache.layers[i].entry(x, y), expected, "layer={i} cell=({x},{y})");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn program(cameras: &[(i32, i32)]) -> Vec<u8> {
|
||||||
|
let mut source = String::from("PUSH_I32 0\nHOSTCALL 0\nPOP_N 1\n");
|
||||||
|
for &(x, y) in cameras {
|
||||||
|
source += &format!("PUSH_I32 {x}\nPUSH_I32 {y}\nHOSTCALL 1\n");
|
||||||
|
for sprite in sprites() {
|
||||||
|
source += &format!(
|
||||||
|
"PUSH_I32 1\nPUSH_I32 3\nPUSH_I32 {}\nPUSH_I32 {}\nPUSH_I32 {}\nPUSH_I32 {}\nPUSH_BOOL {}\nPUSH_BOOL {}\nPUSH_I32 2\nHOSTCALL 2\nPOP_N 1\n",
|
||||||
|
sprite.x,
|
||||||
|
sprite.y,
|
||||||
|
sprite.layer,
|
||||||
|
sprite.bank_id,
|
||||||
|
u8::from(sprite.flip_x),
|
||||||
|
u8::from(sprite.flip_y)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
source += &format!(
|
||||||
|
"PUSH_I32 3\nPUSH_I32 4\nPUSH_I32 13\nPUSH_I32 7\nPUSH_I32 {}\nHOSTCALL 3\nFRAME_SYNC\n",
|
||||||
|
Color::CYAN.raw()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
source += "RET";
|
||||||
|
let mut program = TestProgram::single(assemble(&source).unwrap(), Signature::default(), 0, 32);
|
||||||
|
program.exports = vec![Export { symbol: "main".into(), func_idx: 0 }];
|
||||||
|
program.syscalls = [
|
||||||
|
("composer", "bind_scene", 1, 1),
|
||||||
|
("composer", "set_camera", 2, 0),
|
||||||
|
("composer", "emit_sprite", 9, 1),
|
||||||
|
("gfx2d", "fill_rect", 5, 0),
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.map(|(m, n, a, r)| SyscallDecl {
|
||||||
|
module: m.into(),
|
||||||
|
name: n.into(),
|
||||||
|
version: 1,
|
||||||
|
arg_slots: a,
|
||||||
|
ret_slots: r,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
program.serialize()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Cartridge(pub PathBuf);
|
||||||
|
impl Drop for Cartridge {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
std::fs::remove_dir_all(&self.0).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn assert_resident_identity(
|
||||||
|
hw: &Hardware,
|
||||||
|
scenes: &[Arc<SceneBank>],
|
||||||
|
glyphs: &[Arc<GlyphBank>],
|
||||||
|
) {
|
||||||
|
for (slot, scene) in scenes.iter().enumerate() {
|
||||||
|
assert!(Arc::ptr_eq(scene, &hw.memory_banks.scene_bank_slot(slot).unwrap()));
|
||||||
|
}
|
||||||
|
for (slot, glyph) in glyphs.iter().enumerate() {
|
||||||
|
assert!(Arc::ptr_eq(glyph, &hw.memory_banks.glyph_bank_slot(slot).unwrap()));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -401,23 +401,89 @@ It stores tiles already resolved from the tilemap.
|
|||||||
|
|
||||||
## 9. Cache Update
|
## 9. Cache Update
|
||||||
|
|
||||||
Every frame:
|
Every camera update MUST materialize all newly exposed tiles before scene
|
||||||
|
composition. The resolver owns the master anchor, per-layer anchors, hysteresis
|
||||||
|
and refresh requests; the cache owns the materialized entries and ring mapping.
|
||||||
|
Scene and glyph banks retain their canonical content and resident identity.
|
||||||
|
|
||||||
1. Calculate:
|
### 9.1 Coordinates and numeric domain
|
||||||
- `tile_x = scroll_x / tile_size`
|
|
||||||
- `tile_y = scroll_y / tile_size`
|
|
||||||
- `offset_x = scroll_x % tile_size`
|
|
||||||
- `offset_y = scroll_y % tile_size`
|
|
||||||
|
|
||||||
2. If `tile_x` changed:
|
`composer.set_camera(x, y)` accepts signed Int32 top-left pixel coordinates,
|
||||||
- Advance `cache_origin_x`
|
including negative values, both extremes and positions outside the scene. The
|
||||||
- Reload only the new column
|
requested coordinates remain unchanged in closed Game 2D packets and snapshots.
|
||||||
|
Clamping a cache anchor MUST NOT clamp the requested camera or its public domain.
|
||||||
|
|
||||||
3. If `tile_y` changed:
|
Each layer retains the existing parallax transformation:
|
||||||
- Advance `cache_origin_y`
|
|
||||||
- Reload only the new line
|
|
||||||
|
|
||||||
Only **one row and/or column** is updated per frame.
|
```text
|
||||||
|
layer_camera = Int32_saturating(floor(f32(camera) * parallax_factor))
|
||||||
|
```
|
||||||
|
|
||||||
|
This includes the existing f32 quantization and saturating conversion. Finite
|
||||||
|
negative and large factors remain admitted; asset validation rejects nonfinite
|
||||||
|
input factors. Changing the multiplication to f64 changes this transformation
|
||||||
|
and is not part of coordinate-overflow handling. Admitted empty scene axes and
|
||||||
|
u32 scene dimensions MUST NOT produce invalid clamp bounds.
|
||||||
|
|
||||||
|
Centers, drift, scene/cache bounds, pixel-origin products and source offsets
|
||||||
|
MUST use a sufficiently wide integer representation; the current implementation
|
||||||
|
uses Int64 for these calculations and for `LayerCopyRequest` source offsets.
|
||||||
|
The guest ABI, asset layout and Game 2D packet layout remain unchanged.
|
||||||
|
|
||||||
|
The Gfx consumer computes tile-local screen coordinates in the wide domain. For
|
||||||
|
an axis with local tile coordinate `p`, tile size `t` and screen extent `s`, it
|
||||||
|
discards the tile if `p >= s` or `p + t <= 0`, before narrowing for pixel drawing.
|
||||||
|
A surviving tile satisfies `-t < p < s`; for the native 640×360 viewport and
|
||||||
|
tiles up to 32 pixels these local coordinates and subsequent pixel additions
|
||||||
|
fit Int32. Distant off-scene positions MUST NOT overflow while being clipped.
|
||||||
|
|
||||||
|
### 9.2 Anchor movement and hysteresis
|
||||||
|
|
||||||
|
The first update selects each anchor using Euclidean floor division of its
|
||||||
|
camera center by tile size, then clamps the anchor to the scene/cache bounds.
|
||||||
|
Subsequent updates preserve the previous anchor until its hysteresis stopping
|
||||||
|
bands are exceeded. In particular, selecting an anchor afresh from the camera
|
||||||
|
every frame is not equivalent: the anchor may depend on camera history.
|
||||||
|
|
||||||
|
For tile size `t`, previous anchor `a` and wide camera center `c`, the equivalent
|
||||||
|
bounded transition for an axis is:
|
||||||
|
|
||||||
|
```text
|
||||||
|
B = max(hysteresis_safe, hysteresis_trigger, t / 2)
|
||||||
|
d = c - (a * t + t / 2)
|
||||||
|
if abs(d) <= B: retain a
|
||||||
|
otherwise: a += sign(d) * ceil((abs(d) - B) / t)
|
||||||
|
then clamp the anchor using wide scene/cache bounds
|
||||||
|
```
|
||||||
|
|
||||||
|
Runtime hysteresis thresholds are nonnegative. The half-tile floor prevents
|
||||||
|
mixed-size layers from stepping past the center and immediately stepping back.
|
||||||
|
Anchor advancement MUST perform bounded arithmetic per axis/layer, without
|
||||||
|
walking tiles in proportion to raw camera distance.
|
||||||
|
|
||||||
|
### 9.3 Partial refresh and jumps
|
||||||
|
|
||||||
|
For a layer cache of `w × h` tiles and anchor displacement `(dx, dy)`:
|
||||||
|
|
||||||
|
- Initialization, scene reset and existing invalidations retain their full
|
||||||
|
materialization behavior.
|
||||||
|
- If `abs(dx) >= w` or `abs(dy) >= h`, the old and new windows have no overlap.
|
||||||
|
Refresh the full region of that layer once.
|
||||||
|
- With overlap, refresh only the newly exposed rows, columns or corner strips.
|
||||||
|
Corner strips MUST NOT materialize their intersection twice.
|
||||||
|
- Without displacement or invalidation, no refresh is required.
|
||||||
|
|
||||||
|
Move the logical ring window before applying its refresh requests. All indices
|
||||||
|
and regions MUST lie within the cache. Fast movement can expose multiple rows
|
||||||
|
or columns in one frame; a jump can require the full window. A one-row/column
|
||||||
|
limit MUST NOT leave newly exposed tiles stale.
|
||||||
|
|
||||||
|
For overlapping diagonal movement, the exposed area is
|
||||||
|
`abs(dx) * h + (w - abs(dx)) * abs(dy)`, at most `w * h`. Consequently a camera
|
||||||
|
update materializes at most the sum of the four layer-cache areas, and emits a
|
||||||
|
number of requests bounded by cache geometry. There are two master-axis and
|
||||||
|
eight layer-axis calculations. These limits are independent of raw camera
|
||||||
|
distance; they do not bound guest execution or asset loading costs.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user