Skip to content
84 changes: 84 additions & 0 deletions astraweave-gameplay/src/weaving.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ pub fn apply_weave_op(
if matches!(op.kind, WeaveOpKind::CollapseBridge) && op.b.is_none() {
anyhow::bail!("Collapse needs A->B");
}
if !legacy_geometry_kept(kind, &compiled) {
anyhow::bail!("weave origin is outside the island");
}
match op.kind {
WeaveOpKind::ReinforcePath | WeaveOpKind::RaisePlatform | WeaveOpKind::CollapseBridge => {
if budget.terrain_edits <= 0 {
Expand Down Expand Up @@ -147,6 +150,16 @@ pub fn apply_weave_op(
Ok(consequence)
}

fn legacy_geometry_kept(kind: u8, compiled: &astraweave_weaving::CompiledOp) -> bool {
match kind {
0 | 4 => compiled.fortify.is_some(),
1 => compiled.collapse.is_some(),
2 | 3 => compiled.write_count > 0,
5 => compiled.ice_min_milli.is_some(),
_ => false,
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -663,4 +676,75 @@ mod tests {
"RedirectWind must decrement weather_ops by exactly 1"
);
}

#[test]
fn dropped_origin_does_not_spend_budget_or_return_a_consequence() {
let mut world = create_test_world();
let mut physics = create_test_physics();
let nav_src = vec![];
let mut budget = create_test_budget();
let op = WeaveOp {
kind: WeaveOpKind::FreezeWater,
a: vec3(1.0e20, f32::NAN, f32::INFINITY),
b: None,
budget_cost: 1,
};
let mut logger = |_: String| {};
let err = apply_weave_op(
&mut world,
&mut physics,
&nav_src,
&mut budget,
&op,
&mut logger,
)
.expect_err("a dropped freeze must not succeed");
assert!(err.to_string().contains("outside the island"));
assert_eq!(budget.weather_ops, 3);
assert_eq!(budget.terrain_edits, 5);

let reinforce = WeaveOp {
kind: WeaveOpKind::ReinforcePath,
a: vec3(f32::NEG_INFINITY, 0.0, 0.0),
b: None,
budget_cost: 1,
};
let err = apply_weave_op(
&mut world,
&mut physics,
&nav_src,
&mut budget,
&reinforce,
&mut logger,
)
.expect_err("a dropped reinforce must not succeed");
assert!(err.to_string().contains("outside the island"));
assert_eq!(budget.terrain_edits, 5);
}

#[test]
fn far_collapse_endpoint_does_not_spend_budget() {
let mut world = create_test_world();
let mut physics = create_test_physics();
let nav_src = vec![];
let mut budget = create_test_budget();
let op = WeaveOp {
kind: WeaveOpKind::CollapseBridge,
a: vec3(0.0, 0.0, 0.0),
b: Some(vec3(1.0e20, 0.0, (i32::MAX as f32) / 1000.0)),
budget_cost: 1,
};
let mut logger = |_: String| {};
let err = apply_weave_op(
&mut world,
&mut physics,
&nav_src,
&mut budget,
&op,
&mut logger,
)
.expect_err("a far collapse endpoint must not succeed");
assert!(err.to_string().contains("outside the island"));
assert_eq!(budget.terrain_edits, 5);
}
}
10 changes: 8 additions & 2 deletions astraweave-weaving/src/eval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ use crate::field::{
encode_write, FieldWrite, NullField, Shape, SimField, WriteOp, CELL_MM, MAX_FIELD_WRITES,
};
use crate::mod_queue::{
WeaveCommand, WeaveNode, WeaveScratch, KIND_DECAY, KIND_DENSITY, KIND_GRAVITY, KIND_HEAT,
KIND_PHASE, KIND_VOLUME, KIND_WIND, MAX_WEAVE_COMMANDS,
WeaveCommand, WeaveNode, WeaveScratch, ISLAND_HALF_CELLS, KIND_DECAY, KIND_DENSITY,
KIND_GRAVITY, KIND_HEAT, KIND_PHASE, KIND_VOLUME, KIND_WIND, MAX_WEAVE_COMMANDS,
};
use crate::templates::{builtin, writes_for, TEMPLATE_FREEZE};
use astraweave_nav::{NavChange, NavChangeKind};
Expand Down Expand Up @@ -230,6 +230,12 @@ fn store_writes(frame: &mut WeaveFrame, writes: &[FieldWrite]) -> u32 {
}

fn push_ice(frame: &mut WeaveFrame, tick: u64, seq: u32, origin: [i32; 3], radius: u8) {
debug_assert!(
origin
.iter()
.all(|cell| (-ISLAND_HALF_CELLS..=ISLAND_HALF_CELLS).contains(cell)),
"freeze origin is outside the island; queue_weave rejects it before writes are stored"
);
let radius = radius as i32;
let min_milli = [
(origin[0] - radius) * CELL_MM,
Expand Down
48 changes: 44 additions & 4 deletions astraweave-weaving/src/field.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,32 @@ pub fn gravity_mm_s2(milli_g: i32) -> i32 {
milli_g.saturating_mul(981) / 100
}

/// Nearest cell from metres. Truncates toward zero after scaling to millimetres.
/// Cell index from metres. Truncates toward zero after scaling to millimetres.
///
/// Returns `None` when `m` is not finite or `m * 1000` does not fit in `i32`.
/// The float-to-int cast saturates, so that range is rejected before the cast.
/// The replay path passes cell coordinates and does not call this.
pub fn meters_to_cell(m: f32) -> i32 {
let milli = (m * 1000.0) as i32;
milli.div_euclid(CELL_MM)
pub fn meters_to_cell(m: f32) -> Option<i32> {
if !m.is_finite() {
return None;
}
let milli = m * 1000.0;
// `i32::MAX as f32` is `2^31`. `>` lets that value through and `as i32`
// saturates. Every smaller finite `f32` is at most `2147483392` and fits.
if milli < i32::MIN as f32 || milli >= i32::MAX as f32 {
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
return None;
}
Some((milli as i32).div_euclid(CELL_MM))
}

/// `cell * CELL_MM` when the product fits in `i32`. Does not saturate.
pub fn cell_to_milli(cell: i32) -> Option<i32> {
cell.checked_mul(CELL_MM)
}

/// Three cell coordinates scaled to millimetres, or `None` if any product overflows.
pub fn milli_corner(x: Option<i32>, y: Option<i32>, z: Option<i32>) -> Option<[i32; 3]> {
Some([cell_to_milli(x?)?, cell_to_milli(y?)?, cell_to_milli(z?)?])
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
Expand Down Expand Up @@ -234,6 +255,25 @@ mod tests {
use super::*;

#[test]
fn meters_to_cell_rejects_non_finite_and_the_i32_edge() {
let positive = (i32::MAX as f32) / 1000.0;
assert!(
meters_to_cell(positive).is_none(),
"nearest f32 to 2^31/1000 ({positive}) must not saturate"
);
let negative = (i32::MIN as f32) / 1000.0;
assert_eq!(
meters_to_cell(negative),
Some(-2_147_484),
"negative edge ({negative}) must stay negative and must not saturate"
);
assert!(meters_to_cell(f32::NAN).is_none());
assert!(meters_to_cell(f32::INFINITY).is_none());
assert!(meters_to_cell(f32::NEG_INFINITY).is_none());
assert_eq!(meters_to_cell(1.0), Some(1));
assert_eq!(meters_to_cell(-1.5), Some(-2));
}

fn gravity_conversion_matches_9810() {
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
assert_eq!(gravity_mm_s2(WORLD_GRAVITY_MILLI_G), -9810);
assert_eq!(gravity_mm_s2(0), 0);
Expand Down
160 changes: 137 additions & 23 deletions astraweave-weaving/src/legacy.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Compiles the six legacy ops into templates and director rectangles.

use crate::field::{meters_to_cell, FieldWrite, WriteOp};
use crate::field::{meters_to_cell, milli_corner, FieldWrite, WriteOp};
use crate::mod_queue::ISLAND_HALF_CELLS;
use crate::templates::{
builtin, writes_for, MAX_NODES, TEMPLATE_DENSITY, TEMPLATE_FREEZE, TEMPLATE_LOWER_WATER,
TEMPLATE_WIND,
Expand Down Expand Up @@ -51,7 +52,9 @@ pub fn compile_legacy(kind: u8, points: LegacyPoints) -> CompiledOp {
};
let tick = points.tick;
let seq = points.seq;
let origin = [meters_to_cell(ax), meters_to_cell(ay), meters_to_cell(az)];
let Some(origin) = cell_origin(ax, ay, az) else {
return empty_compiled();
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
};
let mut compiled = CompiledOp {
writes: writes_for(&builtin(TEMPLATE_DENSITY).unwrap(), origin, 1).0,
write_count: 0,
Expand All @@ -77,15 +80,17 @@ pub fn compile_legacy(kind: u8, points: LegacyPoints) -> CompiledOp {
compiled.write_count = count;
}
1 => {
if let (Some(bx), Some(bz)) = (bx, bz) {
if let (Some(bx), Some(by), Some(bz)) = (bx, by, bz) {
if cell_origin(bx, by, bz).is_none() {
return empty_compiled();
}
compiled.collapse = Some(DirectorCollapse {
ax: ax as i32,
ay: az as i32,
bx: bx as i32,
by: bz as i32,
});
}
let _ = by;
}
2 => {
let (mods, count) = writes_for(&builtin(TEMPLATE_WIND).unwrap(), origin, 1);
Expand All @@ -110,31 +115,63 @@ pub fn compile_legacy(kind: u8, points: LegacyPoints) -> CompiledOp {
compiled.writes = mods;
compiled.write_count = count;
let radius = template.ice_radius as i32;
let min_milli = [
(origin[0] - radius) * crate::field::CELL_MM,
origin[1] * crate::field::CELL_MM,
(origin[2] - radius) * crate::field::CELL_MM,
];
let max_milli = [
(origin[0] + radius + 1) * crate::field::CELL_MM,
(origin[1] + 1) * crate::field::CELL_MM,
(origin[2] + radius + 1) * crate::field::CELL_MM,
];
compiled.ice_min_milli = Some(min_milli);
compiled.ice_max_milli = Some(max_milli);
compiled.nav = Some(NavChange::new(
tick,
seq,
min_milli,
max_milli,
NavChangeKind::Weave,
));
if let (Some(min_milli), Some(max_milli)) = (
milli_corner(
origin[0].checked_sub(radius),
Some(origin[1]),
origin[2].checked_sub(radius),
),
milli_corner(
origin[0]
.checked_add(radius)
.and_then(|cell| cell.checked_add(1)),
origin[1].checked_add(1),
origin[2]
.checked_add(radius)
.and_then(|cell| cell.checked_add(1)),
),
) {
compiled.ice_min_milli = Some(min_milli);
compiled.ice_max_milli = Some(max_milli);
compiled.nav = Some(NavChange::new(
tick,
seq,
min_milli,
max_milli,
NavChangeKind::Weave,
));
}
}
_ => {}
}
compiled
}

fn cell_origin(x: f32, y: f32, z: f32) -> Option<[i32; 3]> {
let origin = [meters_to_cell(x)?, meters_to_cell(y)?, meters_to_cell(z)?];
if origin
.iter()
.all(|cell| (-ISLAND_HALF_CELLS..=ISLAND_HALF_CELLS).contains(cell))
{
Some(origin)
} else {
None
}
}

fn empty_compiled() -> CompiledOp {
let (writes, _) = writes_for(&builtin(TEMPLATE_DENSITY).unwrap(), [0, 0, 0], 1);
CompiledOp {
writes,
write_count: 0,
fortify: None,
collapse: None,
ice_min_milli: None,
ice_max_milli: None,
nav: None,
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -176,4 +213,81 @@ mod tests {
let rect = compiled.fortify.unwrap();
assert_eq!((rect.x0, rect.y0, rect.x1, rect.y1), (4, 4, 6, 6));
}

#[test]
fn far_origin_does_not_saturate_into_a_milli_aabb() {
let compiled = compile_legacy(
5,
LegacyPoints {
a: [1.0e20, 0.0, 0.0],
b: None,
tick: 4,
seq: 2,
},
);
assert_eq!(compiled.write_count, 0);
assert!(compiled.ice_min_milli.is_none());
assert!(compiled.nav.is_none());
let edge = compile_legacy(
5,
LegacyPoints {
a: [ISLAND_HALF_CELLS as f32, 0.0, 0.0],
b: None,
tick: 1,
seq: 1,
},
);
let min = edge.ice_min_milli.unwrap();
assert_eq!(min[0], (ISLAND_HALF_CELLS - 2) * crate::field::CELL_MM);
assert_eq!(min[1], 0);
}

#[test]
fn non_finite_and_i32_edge_origins_drop_the_op() {
for origin in [
f32::NAN,
f32::INFINITY,
f32::NEG_INFINITY,
(i32::MAX as f32) / 1000.0,
(i32::MIN as f32) / 1000.0,
] {
let compiled = compile_legacy(
5,
LegacyPoints {
a: [origin, 0.0, 0.0],
b: None,
tick: 1,
seq: 1,
},
);
assert_eq!(compiled.write_count, 0, "{origin}");
assert!(compiled.ice_min_milli.is_none(), "{origin}");
}
}

#[test]
fn far_collapse_endpoint_is_rejected() {
let compiled = compile_legacy(
1,
LegacyPoints {
a: [0.0, 0.0, 0.0],
b: Some([1.0e20, 0.0, 0.0]),
tick: 0,
seq: 0,
},
);
assert!(compiled.collapse.is_none());
assert_eq!(compiled.write_count, 0);
let kept = compile_legacy(
1,
LegacyPoints {
a: [0.0, 0.0, 0.0],
b: Some([10.0, 0.0, 10.0]),
tick: 0,
seq: 0,
},
);
let line = kept.collapse.unwrap();
assert_eq!((line.ax, line.ay, line.bx, line.by), (0, 0, 10, 10));
}
}
Loading
Loading