Thing 2.0 cut 6b fix: plot coordinates checked as f32 and dropped points said once; random rounds bind assets and series; cells line width and alt-fits tests
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
6734bd8e91
commit
40b7fa59bd
2 changed files with 126 additions and 17 deletions
|
|
@ -1,6 +1,6 @@
|
|||
//! A Plot lowered to geometry: the domain, then Polylines, Polygons or FillRects. Pure and
|
||||
//! bounded: a series of N points gives at most N vertices (Line), 2N (Area: each run of m >= 2
|
||||
//! points adds two baseline vertices) or N rects (Bar); a non-finite point is skipped, never drawn.
|
||||
//! points adds two baseline vertices) or N rects (Bar); a non-finite or unrepresentable (f32) point is skipped with one diagnostic, never drawn.
|
||||
|
||||
use thing_contract::{PlotMark, PlotNode};
|
||||
|
||||
|
|
@ -48,19 +48,25 @@ struct Frame {
|
|||
}
|
||||
|
||||
impl Frame {
|
||||
/// A point of the series as f32 screen coordinates, `None` when either does not fit an f32.
|
||||
fn at(&self, i: usize, v: f64) -> Option<(f32, f32)> {
|
||||
let tx = (i as f64 - self.x.0) / (self.x.1 - self.x.0);
|
||||
let ty = self.value(v);
|
||||
let point = (self.rect.x as f64 + tx * self.rect.w as f64, ty);
|
||||
(point.0.is_finite() && point.1.is_finite()).then_some((point.0 as f32, point.1 as f32))
|
||||
let tx = halved(i as f64, self.x);
|
||||
let x = (self.rect.x as f64 + tx * self.rect.w as f64) as f32;
|
||||
let y = self.value(v) as f32;
|
||||
(x.is_finite() && y.is_finite()).then_some((x, y))
|
||||
}
|
||||
|
||||
/// Screen y of a value: y grows down. Halves keep a span near f64's range from overflowing.
|
||||
fn value(&self, v: f64) -> f64 {
|
||||
let t = (v - self.y.0) / (self.y.1 - self.y.0);
|
||||
self.rect.y as f64 + self.rect.h as f64 - t * self.rect.h as f64
|
||||
self.rect.y as f64 + self.rect.h as f64 - halved(v, self.y) * self.rect.h as f64
|
||||
}
|
||||
}
|
||||
|
||||
/// Where `v` falls in `(lo, hi)`, 0 to 1, computed on halves so `hi - lo` cannot overflow.
|
||||
fn halved(v: f64, (lo, hi): (f64, f64)) -> f64 {
|
||||
(v / 2.0 - lo / 2.0) / (hi / 2.0 - lo / 2.0)
|
||||
}
|
||||
|
||||
impl Painter<'_> {
|
||||
pub(super) fn plot(&mut self, n: &thing_contract::PlotNode, rect: Rect) {
|
||||
let tree = self.tree;
|
||||
|
|
@ -71,6 +77,16 @@ impl Painter<'_> {
|
|||
}
|
||||
}
|
||||
|
||||
/// A point that was not drawn is said once for the plot, whatever the reason.
|
||||
fn dropped(&mut self, n: &PlotNode) {
|
||||
self.out.diagnostics.push(Diagnostic {
|
||||
code: Code::StyleValueInvalid,
|
||||
surface: self.tree.resolved().document().record_key(),
|
||||
node: Some(n.common.id.clone()),
|
||||
detail: "series".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
fn plot_series(&mut self, n: &PlotNode, values: &[f64], rect: Rect) {
|
||||
if values.is_empty() || !(rect.w > 0.0 && rect.h > 0.0) {
|
||||
return;
|
||||
|
|
@ -97,19 +113,23 @@ impl Painter<'_> {
|
|||
crate::layout::Metrics::Pixels => 2.0,
|
||||
};
|
||||
let base = frame.value(0.0f64.clamp(y.0, y.1));
|
||||
if !base.is_finite() {
|
||||
if !(base as f32).is_finite() {
|
||||
self.dropped(n);
|
||||
return;
|
||||
}
|
||||
let mut shapes = Vec::new();
|
||||
let mut dropped = false;
|
||||
match n.mark {
|
||||
PlotMark::Bar => {
|
||||
let slot = rect.w / values.len() as f32;
|
||||
for (i, v) in values.iter().enumerate().filter(|(_, v)| v.is_finite()) {
|
||||
for (i, v) in values.iter().enumerate() {
|
||||
let top = frame.value(*v);
|
||||
let (y0, y1) = (top.min(base) as f32, top.max(base) as f32);
|
||||
if y0.is_finite() && y1.is_finite() {
|
||||
let rect = Rect { x: rect.x + slot * i as f32, y: y0, w: slot, h: y1 - y0 };
|
||||
shapes.push(RenderCommand::FillRect { rect, radius: 0.0, color: color.clone() });
|
||||
let bar = Rect { x: rect.x + slot * i as f32, y: y0, w: slot, h: y1 - y0 };
|
||||
if v.is_finite() && [bar.x, bar.y, bar.w, bar.h].iter().all(|c| c.is_finite()) {
|
||||
shapes.push(RenderCommand::FillRect { rect: bar, radius: 0.0, color: color.clone() });
|
||||
} else {
|
||||
dropped = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -131,12 +151,18 @@ impl Painter<'_> {
|
|||
for (i, v) in values.iter().enumerate() {
|
||||
match v.is_finite().then(|| frame.at(i, *v)).flatten() {
|
||||
Some(point) => run.push(point),
|
||||
None => flush(&mut run, &mut shapes),
|
||||
None => {
|
||||
dropped = true;
|
||||
flush(&mut run, &mut shapes);
|
||||
}
|
||||
}
|
||||
}
|
||||
flush(&mut run, &mut shapes);
|
||||
}
|
||||
}
|
||||
if dropped {
|
||||
self.dropped(n);
|
||||
}
|
||||
if shapes.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -594,6 +594,7 @@ fn random_documents_render_without_panic_balanced_and_equal() {
|
|||
let overflows = [Overflow::Visible, Overflow::Clip, Overflow::Scroll];
|
||||
let tokens = ["thing.surface", "thing.error", "unknown", "thing.scrim"];
|
||||
let mut refused = 0u32;
|
||||
let (mut with_image, mut with_plot) = (0u32, 0u32);
|
||||
const ROUNDS: u64 = 300;
|
||||
for round in 0..ROUNDS {
|
||||
let mut counter = 0u32;
|
||||
|
|
@ -625,7 +626,7 @@ fn random_documents_render_without_panic_balanced_and_equal() {
|
|||
initial: lit_text(["", "typed words"][(next() % 2) as usize]),
|
||||
submit: command("dismiss"),
|
||||
}),
|
||||
(8, _) => Node::Plot(PlotNode { common: common(&id), series: series_bind("s"), mark: PlotMark::Bar, x_min: None, x_max: None, y_min: None, y_max: None }),
|
||||
(8, _) => Node::Plot(PlotNode { common: common(&id), series: series_bind("s"), mark: [PlotMark::Line, PlotMark::Area, PlotMark::Bar][(next() % 3) as usize], x_min: None, x_max: None, y_min: None, y_max: None }),
|
||||
(2, d) if d < 3 => {
|
||||
let anchor = if next() % 2 == 0 { Anchor::Viewport } else { at(&generated[(next() % generated.len() as u64) as usize]) };
|
||||
let children = (0..(next() % 3)).map(|_| grow(depth + 1, next, counter, generated, sizes, overflows, tokens)).collect();
|
||||
|
|
@ -657,7 +658,19 @@ fn random_documents_render_without_panic_balanced_and_equal() {
|
|||
scroll.set(nid(id), ((next() % 400) as f32 - 100.0, [f32::NAN, 1e30, 30.0, 400.0][(next() % 4) as usize]));
|
||||
}
|
||||
let frame = [pixels(1.0), pixels(1.5), pixels(2.0), frame(80.0, 30.0, 1.0, Metrics::Cells)][(round % 4) as usize];
|
||||
let Ok(tree) = bind(&mut MemState::new(), &surface_of(root)) else {
|
||||
// Every round binds an asset entry and a series (NaN and infinities among its values), so
|
||||
// Image fit and Plot lowering run wherever the document holds them.
|
||||
let mut state = MemState::new();
|
||||
state.put(&ProviderId::new(PROVIDER), &catalog(&[("x", 50, 20)]));
|
||||
let values: Vec<f64> = (0..next() % 9)
|
||||
.map(|_| match next() % 7 {
|
||||
0 => f64::NAN,
|
||||
1 => f64::INFINITY,
|
||||
_ => (next() % 100) as f64 - 50.0,
|
||||
})
|
||||
.collect();
|
||||
state.put_state(&ProviderId::new(PROVIDER), "s", &Series { values });
|
||||
let Ok(tree) = bind(&mut state, &surface_of(root)) else {
|
||||
refused += 1;
|
||||
continue;
|
||||
};
|
||||
|
|
@ -669,11 +682,14 @@ fn random_documents_render_without_panic_balanced_and_equal() {
|
|||
let first = render(&tree, &laid, &input(&frame, &scroll, &theme), &mut measure(&frame));
|
||||
let second = render(&tree, &laid, &input(&frame, &scroll, &theme), &mut measure(&frame));
|
||||
assert_eq!(first, second, "round {round}");
|
||||
with_image += first.commands.iter().any(|c| matches!(c, RenderCommand::Image { .. })) as u32;
|
||||
with_plot += first.commands.iter().any(|c| matches!(c, RenderCommand::Polyline { .. } | RenderCommand::Polygon { .. })) as u32;
|
||||
assert!(balanced(&first.commands), "round {round}");
|
||||
assert_eq!(first.placed.len(), laid.nodes.len());
|
||||
}
|
||||
// A round that layout refuses renders nothing: keep them few enough that render is exercised.
|
||||
eprintln!("random documents: {refused} of {ROUNDS} refused");
|
||||
eprintln!("random documents: {refused} of {ROUNDS} refused; {with_image} rendered an Image, {with_plot} a Polyline or Polygon");
|
||||
assert!(with_image >= 20 && with_plot >= 20, "image {with_image}, plot {with_plot}");
|
||||
assert!(refused * 20 <= ROUNDS as u32, "{refused} of {ROUNDS} rounds were refused");
|
||||
}
|
||||
|
||||
|
|
@ -871,7 +887,7 @@ fn a_nan_splits_a_line_and_a_one_point_run_draws_nothing() {
|
|||
assert!(balanced(&split.commands));
|
||||
let lone = plotted(&[1.0, f64::NAN, 2.0, f64::INFINITY, 3.0], PlotMark::Line, [None; 4]);
|
||||
assert_eq!(lone.commands, []);
|
||||
assert_eq!(invalid(&lone), Vec::<&str>::new(), "a non-finite point is skipped, not a style fault");
|
||||
assert_eq!(invalid(&lone), ["series"], "dropped points are said once");
|
||||
assert_eq!(plotted(&[], PlotMark::Line, [None; 4]).commands, []);
|
||||
// Every point of one value: the equal ends widen by 1 and the line runs through the middle.
|
||||
assert_eq!(polylines(&plotted(&[5.0, 5.0], PlotMark::Line, [None; 4])), [vec![(0.0, 75.0), (300.0, 75.0)]]);
|
||||
|
|
@ -1065,3 +1081,70 @@ fn a_placeholder_shows_only_while_the_input_is_empty_and_a_select_shows_its_labe
|
|||
assert_eq!(lines_of(&select("b")), ["Beta"]);
|
||||
assert_eq!(lines_of(&select("zzz")), ["zzz"], "the value itself when no option matches");
|
||||
}
|
||||
|
||||
fn finite(rendered: &Rendered) -> bool {
|
||||
rendered.commands.iter().all(|c| match c {
|
||||
RenderCommand::Polyline { points, .. } | RenderCommand::Polygon { points, .. } => points.iter().all(|p| p.0.is_finite() && p.1.is_finite()),
|
||||
RenderCommand::FillRect { rect, .. } | RenderCommand::ClipPush { rect, .. } => [rect.x, rect.y, rect.w, rect.h].iter().all(|v| v.is_finite()),
|
||||
_ => true,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_emitted_plot_coordinate_is_a_finite_f32() {
|
||||
let hostile = [f64::NAN, f64::INFINITY, 1e308, -1e308, 0.0, 1.0, 2.5, f64::NEG_INFINITY];
|
||||
for mark in [PlotMark::Line, PlotMark::Area, PlotMark::Bar] {
|
||||
let bounds = [
|
||||
[None, None, None, Some(1e-300)],
|
||||
[None, None, Some(-1e300), Some(1e300)],
|
||||
[None, None, Some(-1.7e308), Some(1.7e308)],
|
||||
[None, Some(1e-300), None, None],
|
||||
[Some(-1e300), Some(1e300), None, None],
|
||||
[None; 4],
|
||||
];
|
||||
for bound in bounds {
|
||||
for values in [&hostile[..], &[0.0, 1.0], &[1e38, -1e38, 3e38], &[1.0, 2.0]] {
|
||||
let out = plotted(values, mark.clone(), bound);
|
||||
assert!(finite(&out), "{mark:?} {bound:?} {values:?}: {:?}", out.commands);
|
||||
assert!(balanced(&out.commands));
|
||||
assert!(invalid(&out).iter().filter(|d| **d == "series").count() <= 1, "said at most once");
|
||||
}
|
||||
}
|
||||
}
|
||||
// A span of 1e-300: one point sits on the axis, the other cannot be placed, and that is said once.
|
||||
let tiny = plotted(&[0.0, 1.0], PlotMark::Line, [None, None, None, Some(1e-300)]);
|
||||
assert_eq!(tiny.commands, []);
|
||||
assert_eq!(invalid(&tiny), ["series"]);
|
||||
assert_eq!(tiny.diagnostics.last().unwrap().node, Some(nid("p")));
|
||||
// A range of 1e300 either side: every point is placeable (mid-height) and nothing is dropped.
|
||||
let wide = plotted(&[1.0, 2.0], PlotMark::Line, [None, None, Some(-1e300), Some(1e300)]);
|
||||
assert_eq!(polylines(&wide), [vec![(0.0, 75.0), (300.0, 75.0)]]);
|
||||
assert_eq!(invalid(&wide), Vec::<&str>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_polyline_is_one_cell_wide_in_cells_and_two_px_in_pixels() {
|
||||
let width = |frame: &LayoutFrame| {
|
||||
let mut state = MemState::new();
|
||||
state.put_state(&ProviderId::new(PROVIDER), "s", &Series { values: vec![1.0, 2.0] });
|
||||
let out = with_state(&mut state, flat("root", plain(), vec![plot_node(PlotMark::Line, [None; 4])]), frame);
|
||||
out.commands.iter().find_map(|c| if let RenderCommand::Polyline { width, .. } = c { Some(*width) } else { None }).expect("a polyline")
|
||||
};
|
||||
assert_eq!(width(&pixels(1.0)), 2.0);
|
||||
assert_eq!(width(&frame(80.0, 30.0, 1.0, Metrics::Cells)), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_alt_line_of_a_placeholder_draws_only_when_it_fits() {
|
||||
let provider = ProviderId::new(PROVIDER);
|
||||
let in_grid = |height: f64| {
|
||||
let mut state = MemState::new();
|
||||
state.put(&provider, &catalog(&[("empty", 0, 0)]));
|
||||
let grid = BoxStyle { display: Display::Grid, grid_columns: vec![px(100.0)], grid_rows: vec![px(height)], ..plain() };
|
||||
let out = with_state(&mut state, flat("root", grid, vec![image("pic", "empty", ImageFit::Contain)]), &pixels(1.0));
|
||||
assert_eq!(placed(&out, "pic").rect, rect(0.0, 0.0, 100.0, height as f32));
|
||||
out
|
||||
};
|
||||
assert_eq!(lines_of(&in_grid(40.0)), ["alt"]);
|
||||
assert_eq!(lines_of(&in_grid(10.0)), Vec::<String>::new(), "a 16 high line does not fit 10");
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue