Skip to content
156 changes: 155 additions & 1 deletion astraweave-gameplay/src/weaving.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,18 @@ pub fn apply_weave_op(
if matches!(op.kind, WeaveOpKind::CollapseBridge) && op.b.is_none() {
anyhow::bail!("Collapse needs A->B");
}
let wind = if matches!(op.kind, WeaveOpKind::RedirectWind) {
let end = op.b.unwrap_or(op.a + vec3(1.0, 0.0, 0.0));
Some(
wind_direction(op.a, end)
.ok_or_else(|| anyhow::anyhow!("weave origin is outside the island"))?,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking. This string is now the failure for every wind_direction reject, including a zero delta, a square that underflows (1e-23), and a square that overflows (1.9e19). None of those origins are outside ±2048.

non_finite_wind_endpoint_does_not_spend_weather locks contains("outside the island") for NaN and 1.9e19, so the false reason is part of the test contract. The world effect is still right: budget unchanged, previous wind unchanged (weave_op_edges_fail_closed passed, 18/18). A distinct message would only help the caller tell a bad direction from a bad origin. The same sentence on the geometry bail below is accurate for a dropped cell.

)
} else {
None
};
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 @@ -83,7 +95,9 @@ pub fn apply_weave_op(
});
}
if matches!(op.kind, WeaveOpKind::RedirectWind) {
let dir = (op.b.unwrap_or(op.a + vec3(1.0, 0.0, 0.0)) - op.a).normalize_or_zero();
let Some(dir) = wind else {
anyhow::bail!("weave origin is outside the island");
};
phys.set_wind(dir, 10.0);
log("Weave: Wind redirected".into());
}
Expand Down Expand Up @@ -147,6 +161,28 @@ pub fn apply_weave_op(
Ok(consequence)
}

fn wind_direction(from: glam::Vec3, to: glam::Vec3) -> Option<glam::Vec3> {
let delta = to - from;
if !(delta.x.is_finite() && delta.y.is_finite() && delta.z.is_finite()) {
return None;
}
let len2 = delta.length_squared();
if !len2.is_finite() {
return None;
}
Some(delta.normalize_or_zero())
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}

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 +699,122 @@ 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);
}

#[test]
fn non_finite_wind_endpoint_does_not_spend_weather() {
let mut world = create_test_world();
let mut physics = create_test_physics();
let nav_src = vec![];
let mut budget = create_test_budget();
let mut logger = |_: String| {};
for endpoint in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
let op = WeaveOp {
kind: WeaveOpKind::RedirectWind,
a: vec3(0.0, 0.0, 0.0),
b: Some(vec3(endpoint, 0.0, 1.0)),
budget_cost: 1,
};
let err = apply_weave_op(
&mut world,
&mut physics,
&nav_src,
&mut budget,
&op,
&mut logger,
)
.expect_err("a non-finite wind endpoint must not succeed");
assert!(err.to_string().contains("outside the island"));
assert_eq!(budget.weather_ops, 3, "{endpoint}");
}
physics.wind = vec3(3.0, 0.0, 0.0);
let huge = WeaveOp {
kind: WeaveOpKind::RedirectWind,
a: vec3(0.0, 0.0, 0.0),
b: Some(vec3(1.9e19, 0.0, 0.0)),
budget_cost: 1,
};
let err = apply_weave_op(
&mut world,
&mut physics,
&nav_src,
&mut budget,
&huge,
&mut logger,
)
.expect_err("a wind endpoint whose square overflows must not succeed");
assert!(err.to_string().contains("outside the island"));
assert_eq!(budget.weather_ops, 3);
assert_eq!(physics.wind, vec3(3.0, 0.0, 0.0));
}
}
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
53 changes: 49 additions & 4 deletions astraweave-weaving/src/field.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,33 @@ 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. Floors after scaling to millimetres (`div_euclid`),
/// so `-1.5` is cell `-2`, not `-1`.
///
/// 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. The predecessor finite `f32` is `2147483520`, which fits.
if milli < i32::MIN as f32 || milli >= i32::MAX as f32 {
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 @@ -233,6 +255,29 @@ impl SimField for TestSimField {
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));
let predecessor = f32::from_bits((i32::MAX as f32).to_bits() - 1);
assert_eq!(predecessor, 2_147_483_520.0);
assert!(predecessor < i32::MAX as f32);
}

#[test]
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);
Expand Down
Loading
Loading