From db0bf279b55261276915780c52f5d1da877c228a Mon Sep 17 00:00:00 2001 From: timohueser Date: Sat, 21 Nov 2026 19:13:14 +0100 Subject: [PATCH 01/20] trailview-features: a pair has a part at each end of both chains, and its record the heading of its frame line A pair is one part of two chains, so the bake pairs two openings only where each chain has a part at both of its ends. The record of a pair takes the heading of the opening farther in, square to the frame line that holds both openings, as its mate's metres are. Co-Authored-By: Claude Opus 5.5 --- .../src/parts/ladder.rs | 27 ++++++++++++++++--- host/obc-trailview-features/src/parts/mod.rs | 2 +- .../obc-trailview-features/src/parts/tests.rs | 16 +++++++++-- 3 files changed, 38 insertions(+), 7 deletions(-) diff --git a/host/obc-trailview-features/src/parts/ladder.rs b/host/obc-trailview-features/src/parts/ladder.rs index c984879b0..56192e6df 100644 --- a/host/obc-trailview-features/src/parts/ladder.rs +++ b/host/obc-trailview-features/src/parts/ladder.rs @@ -16,9 +16,10 @@ pub use obc_trailview_parts::Part as Kind; /// The numbers of a drawn opening (Plan 8 of the design): metres, `left` and `right` per metre out from the frame's /// outer edge, and in a pair the mate's opening and the metres to its axis to the left; `height` is the inside height -/// of the tube's chord there. +/// of the tube's chord there; `heading` is square to its frame line, into the tube of the opening farther in. #[derive(Clone, Debug, PartialEq)] pub(crate) struct Numbers { + pub heading: f64, pub height: f64, pub collar: f64, pub face: f64, @@ -260,15 +261,23 @@ pub(crate) fn decide(tubes: &[Tube], openings: &mut [Opening], input: &Input, me rung[i] = Some(r); kinds[i] = k; } - // Rung 5: the pairs, nearest first, each end in one pair at most. + // Rung 5: the pairs, nearest first, each end in one pair at most. A pair is one part of two chains, so each of them + // has a part at both of its ends. let mut mate: Vec> = vec![None; n]; let is_hill = |i: usize| hill.contains(&i); + let whole: Vec = (0..tubes.len()) + .map(|t| { + let at = |end: usize| openings.iter().position(|o| o.tube == t && o.end == end); + (0..2).all(|end| at(end).is_some_and(|i| !kinds[i].is_empty())) + }) + .collect(); for x in &near { let (a, c) = (x.a, x.b); if !is_hill(a) || !is_hill(c) || mate[a].is_some() || mate[c].is_some() { continue; } - if tubes[openings[a].tube].rail != tubes[openings[c].tube].rail { + let (ta, tc) = (openings[a].tube, openings[c].tube); + if tubes[ta].rail != tubes[tc].rail || !whole[ta] || !whole[tc] { continue; } mate[a] = Some(c); @@ -506,5 +515,15 @@ fn numbers( let lowest = under.chain(collar_ground).fold(floor, f64::min); let mate = mate.map(|m| (m, axis(m) - axis(i))); let numbers = if kind == Kind::Free { (Vec::new(), Vec::new()) } else { (left, right) }; - Numbers { height: h, collar, face, left: numbers.0, right: numbers.1, foot: lowest - b.foot_m - floor, mate } + let heading = openings[far].heading(); + Numbers { + heading, + height: h, + collar, + face, + left: numbers.0, + right: numbers.1, + foot: lowest - b.foot_m - floor, + mate, + } } diff --git a/host/obc-trailview-features/src/parts/mod.rs b/host/obc-trailview-features/src/parts/mod.rs index afc21c139..443e6451c 100644 --- a/host/obc-trailview-features/src/parts/mod.rs +++ b/host/obc-trailview-features/src/parts/mod.rs @@ -548,7 +548,7 @@ fn records(tubes: &[Tube], openings: &[Opening], decided: &ladder::Decided, inpu let look = if kind == Kind::Rock { "rock" } else { input.rules.groups[tubes[o.tube].group].look.as_str() }; t.insert("look".into(), look.into()); t.insert("part".into(), kind.name().into()); - t.insert("heading".into(), format!("{}", (o.heading() * 1000.0).round() / 1000.0)); + t.insert("heading".into(), format!("{}", (n.heading * 1000.0).round() / 1000.0)); t.insert("collar".into(), num(n.collar)); if kind != Kind::Free { t.insert("face".into(), num(n.face)); diff --git a/host/obc-trailview-features/src/parts/tests.rs b/host/obc-trailview-features/src/parts/tests.rs index 65444c4fa..2fbb4ef83 100644 --- a/host/obc-trailview-features/src/parts/tests.rs +++ b/host/obc-trailview-features/src/parts/tests.rs @@ -224,8 +224,8 @@ fn a_pair_has_one_frame_line_and_a_way_in_a_wider_tube_has_no_part() { let west = ends.iter().find(|t| t["mate"] == "20").expect("the west pair"); assert_eq!((west["part"].as_str(), west["shift"].as_str(), west["mate_shift"].as_str()), ("pair", "3", "0")); assert!(ends.iter().any(|t| t["mate"] == "-20" && t["shift"] == "0")); - // A pair is not built yet: the device keeps the moved stretch a tunnel, and so does the measure of the numbers. - assert_eq!(placed.metrics["measured_again"].as_u64(), Some(0)); + // A pair is built: the device opens the moved stretch, so the measure reads the four openings near it again. + assert_eq!(placed.metrics["measured_again"].as_u64(), Some(4)); // The first tube widens to the far edge of the footway and its margin. let foot_half = widths().way("tunnel", &tags(&FOOT), false).half_m; assert_eq!(west["half"], num(2.5 + foot_half + 0.6)); @@ -239,6 +239,18 @@ fn a_pair_has_one_frame_line_and_a_way_in_a_wider_tube_has_no_part() { assert_eq!(of(&placed, a), [(vec![Arch, Free], "hill")]); assert_eq!(of(&placed, b)[0], (vec![Arch, Free], "hill")); assert_eq!(placed.metrics["pairs_that_do_not_reach"].as_u64(), Some(1)); + // A pair is one part of two chains: where the second chain forks in the hill, so that its end there has no part, + // the two are no pair. + let mut case = Case::default(); + let a = case.tunnel(&ROAD, (0.0, 200.0), 0.0); + let b = case.tunnel(&ROAD, (3.0, 200.0), 20.0); + for n in [60.0, -20.0] { + case.ways.push(("tunnel", tags(&ROAD), vec![part(&[[200.0, 20.0], [210.0, n]], &[500.0; 2])])); + } + let placed = case.place(&site(&ridge(200.0, 1.0), &[], false), &mut Vec::new()); + assert_eq!(of(&placed, a)[0], (vec![Arch, Free], "hill")); + assert_eq!(of(&placed, b)[0], (vec![Arch, Free], "hill")); + assert_eq!(placed.tags[&b]["parts"], "arch none"); } #[test] From d23e85387d50da8ee4537271915f6f8a29b1d5ea Mon Sep 17 00:00:00 2001 From: timohueser Date: Sat, 21 Nov 2026 19:13:14 +0100 Subject: [PATCH 02/20] trailview-parts: the pair, the rim of an opening in the rock and of a free tube end, and a closed free end - A pair has an end at its mate's opening too. Each opening draws the head wall of both with its own hole, on its side of the middle between the two tubes' walls; along the chains, the inside and the shell of each tube end at that middle where the other tube is near, and faces close the steps where the floors, rooms or shells differ. - Rock and free ends: a rim hugs the opening (no head wall, no wings), in the end's look; a free end's shell runs its collar from it. - A free end covered at its opening has no opening: its tube ends in a dark face, with no box in front and no daylight. - All five kinds are built. The ground plan opens and widens the approach of a pair's mate too. - The mesh keeps only the vertices that a face uses. Co-Authored-By: Claude Opus 5.5 --- host/obc-ground-plan/src/openings.rs | 20 +- host/obc-trailview-parts/src/arch.rs | 319 +++++++++++++++------- host/obc-trailview-parts/src/boxes.rs | 20 +- host/obc-trailview-parts/src/footprint.rs | 8 +- host/obc-trailview-parts/src/lib.rs | 30 +- host/obc-trailview-parts/src/mesh.rs | 116 +++++++- host/obc-trailview-parts/src/tests.rs | 195 ++++++++++++- host/obc-trailview-parts/src/tube.rs | 302 ++++++++++++++++---- 8 files changed, 812 insertions(+), 198 deletions(-) diff --git a/host/obc-ground-plan/src/openings.rs b/host/obc-ground-plan/src/openings.rs index d8cfd0e26..8138c181f 100644 --- a/host/obc-ground-plan/src/openings.rs +++ b/host/obc-ground-plan/src/openings.rs @@ -1,6 +1,6 @@ //! The built tunnel ends of a cell's input (`obc-trailview-parts`): the openings that its ground reaches. -use obc_trailview_parts::{built_ends, Chord, End, Rules}; +use obc_trailview_parts::{mouths, Chord, End, Rules}; use crate::frame::GlobalPoint; use crate::graph::OpenEnd; @@ -48,19 +48,15 @@ pub fn built(input: &CellInput) -> Built { _ => {} } } - let built = built_ends(&ends, &chords, rules); let [x0, y0, x1, y1] = input.key.grown(); - let (mut open, mut mouths) = (Vec::new(), Vec::new()); - for (end, _) in ends.iter().zip(&built).filter(|(_, &b)| b) { - mouths.push(Mouth { at: end.at.map(|v| v * FRAME), into: end.way_in(), half_m: end.half }); - let ways = [Some((end.way, end.shift)), end.mate_way.zip(end.mate_shift)]; - for (way, shift_m) in ways.into_iter().flatten() { - if (x0..=x1).contains(&way[0]) && (y0..=y1).contains(&way[1]) { - open.push(OpenEnd { way: GlobalPoint { x: way[0], y: way[1] }, shift_m }); - } + let (mut open, mut out) = (Vec::new(), Vec::new()); + for m in mouths(&ends, &chords, rules) { + out.push(Mouth { at: m.at.map(|v| v * FRAME), into: m.into, half_m: m.half }); + if (x0..=x1).contains(&m.way[0]) && (y0..=y1).contains(&m.way[1]) { + open.push(OpenEnd { way: GlobalPoint { x: m.way[0], y: m.way[1] }, shift_m: m.shift }); } } - Built { open, mouths } + Built { open, mouths: out } } #[cfg(test)] @@ -220,7 +216,7 @@ mod tests { #[test] fn a_chain_with_an_end_that_is_not_built_keeps_its_tunnel_way() { - let (graph, mesh) = build(&input(Some("arch free"))); + let (graph, mesh) = build(&input(Some("arch none"))); let (develop_graph, develop) = build(&input(None)); assert_eq!((&graph.ways, &graph.samples), (&develop_graph.ways, &develop_graph.samples)); assert_eq!(mesh.to_bytes(), develop.to_bytes()); diff --git a/host/obc-trailview-parts/src/arch.rs b/host/obc-trailview-parts/src/arch.rs index db72c77bc..1f9e772fc 100644 --- a/host/obc-trailview-parts/src/arch.rs +++ b/host/obc-trailview-parts/src/arch.rs @@ -1,19 +1,22 @@ -//! The arch: a head wall on the frame line, with a frame round the opening and wings whose tops follow the rows of -//! the bake; the outer shell of the part; and the dark face in the opening. +//! The head of a part at its opening. An arch: a head wall on the frame line, with a frame round the opening and wings +//! whose tops follow the rows of the bake; the two openings of a pair have one. A rim: the head wall of an opening in +//! the rock and of a free tube end hugs the opening. Then the outer shell of the part and the dark face in the opening. +//! A free end covered at its opening ends in the hill, closed by a dark face, with no head. use crate::boxes; -use crate::mesh::{flagged, flat, outline, Builder, Corner, Station, VOID}; -use crate::tube::{self, direction, inward, spring, Net}; -use crate::Section; +use crate::mesh::{flagged, flat, outline, Builder, Clip, Corner, Station, VOID}; +use crate::tube::{self, cut_face, direction, inward, spring, steps, top_at, Net}; +use crate::{Part, Section}; /// A piece of the shell: its start and end station across to the left of the way in, its chord's height and section, /// and the chord and its vertex at the end. pub type Piece = (Station, Station, f64, Section, usize, usize); -/// The pieces of the shell of end e: per chord from the back of the head wall to `to` metres in. +/// The pieces of the shell of end e: per chord from the back of the head wall, or from the frame line of a closed end, +/// to `to` metres in. pub fn collar(net: &Net, e: usize, to: f64) -> Vec { let design = &net.rules.design; - let from = design.face_m - design.recess_m; + let from = if net.closed(e) { 0.0 } else { design.face_m - design.recess_m }; let mut out = Vec::new(); for (c, forward, start) in net.walk(e, to) { let chord = &net.chords[c]; @@ -30,16 +33,58 @@ pub fn collar(net: &Net, e: usize, to: f64) -> Vec { out } -/// The top of the head wall `t` metres across to the left of its axis, over the opening's floor: `face` over the -/// frame, then the rows of the wings, a value per metre out from the frame's outer edge `edge`. A wing's top is at most -/// a line that falls to its coping's height `coping` at the end of its row: `slope` metres per metre, or more steeply -/// where the row is too short to fall from `face` at the frame's edge. So the top goes on from the head wall with no -/// step, and where the ground goes on past the row, the coping goes into it and no high face ends the wall. -fn top(end: &crate::End, edge: f64, (coping, slope): (f64, f64), t: f64) -> f64 { - let (row, d) = if t > edge { - (&end.left, t - edge) - } else if t < -edge { - (&end.right, -t - edge) +/// Whether end e's head is a rim that hugs its opening, not a head wall with wings. +fn rim(net: &Net, e: usize) -> bool { + matches!(net.ends[e].part, Part::Rock | Part::Free) +} + +/// The metres to the left of end e's axis of the outer edges of its frame: of its opening, or of both openings of a +/// pair. +fn edges(net: &Net, e: usize) -> (f64, f64) { + let shell = net.rules.ladder.bake.shell_m; + let edge = half(net, e) + shell; + match (net.mate[e], net.ends[e].mate) { + (Some(m), Some(a)) => { + let other = half(net, m) + shell; + ((-edge).min(a - other), edge.max(a + other)) + } + _ => (-edge, edge), + } +} + +/// The inside half-width of end e's tube at its opening. +fn half(net: &Net, e: usize) -> f64 { + net.opening(e).map_or(net.ends[e].half, |(c, _)| net.chords[c].half) +} + +/// The outline of end e's rim, round its opening's outline grown by the frame and the shell. +fn rim_outline(net: &Net, e: usize) -> Vec { + let (end, design) = (&net.ends[e], &net.rules.design); + let grow = design.frame_m + net.rules.ladder.bake.shell_m; + let sp = spring(net, end.section, end.height); + outline(end.section, half(net, e) + grow, end.height + grow, sp, design.arch_segments) +} + +/// The metres to the left of end e's axis of the two ends of its head: of its rim, or of its head wall with its wings. +pub fn wide(net: &Net, e: usize) -> (f64, f64) { + if rim(net, e) { + let o = rim_outline(net, e); + return (o[0][0], o[o.len() - 1][0]); + } + let (end, (lo, hi)) = (&net.ends[e], edges(net, e)); + (lo - end.right.len() as f64, hi + end.left.len() as f64) +} + +/// The top of a head wall `t` metres across to the left of its axis, over the opening's floor: `face` over the frame +/// from `lo` to `hi`, then the rows of the wings, a value per metre out. A wing's top is at most a line that falls to +/// its coping's height `coping` at the end of its row: `slope` metres per metre, or more steeply where the row is too +/// short to fall from `face` at the frame's edge. So the top goes on from the head wall with no step, and where the +/// ground goes on past the row, the coping goes into it and no high face ends the wall. +fn top(end: &crate::End, (lo, hi): (f64, f64), (coping, slope): (f64, f64), t: f64) -> f64 { + let (row, d) = if t > hi { + (&end.left, t - hi) + } else if t < lo { + (&end.right, lo - t) } else { return end.face; }; @@ -53,83 +98,162 @@ fn top(end: &crate::End, edge: f64, (coping, slope): (f64, f64), t: f64) -> f64 along.min(coping + slope.max((end.face - coping) / len) * (len - d)) } -/// The faces of the arch at end e: its head wall, the sill, the reveal and the frame round the opening, the dark face -/// in it, and the shell of its collar. The head wall and the shell go down to one level (`boxes::foot`); the sill lies `lift_m` under the floor, under the road of the tube and of the ground. Faces that meet share -/// the corners of their edges. +/// End e's opening outline grown by `grow`, from the sill up its side to a corner at the floor's height there, where the +/// tube's wall stands on the floor, and on over its top. +fn grown(net: &Net, e: usize, grow: f64) -> Vec { + let Some((c, _)) = net.opening(e) else { return Vec::new() }; + let (chord, design) = (&net.chords[c], &net.rules.design); + let pieces = tube::floor_pieces(net, chord); + let sp = spring(net, chord.section, chord.height); + let o = outline(chord.section, chord.half + grow, chord.height + grow, sp, design.arch_segments); + let (first, last) = (o[0][0], o[o.len() - 1][0]); + let sides = |x: f64, top: f64| [[x, -design.lift_m], [x, top]]; + let mut out = sides(first, pieces[0].2).to_vec(); + out.extend_from_slice(&o[1..o.len() - 1]); + out.extend(sides(last, pieces[pieces.len() - 1].2).into_iter().rev()); + out +} + +/// The cut of a pair at end e's frame line: the metres to the left of its axis of the middle between its tube's wall and +/// the mate's, and the side of the mate (1 to the left). +fn pair_cut(net: &Net, e: usize) -> Option<(f64, f64)> { + let (m, a) = (net.mate[e]?, net.ends[e].mate?); + Some(((a + a.signum() * (half(net, e) - half(net, m))) / 2.0, a.signum())) +} + +/// The faces of the head at end e: its head wall or rim, the sill, the reveal and the frame round the opening, the dark +/// face in it, and the shell of its collar. The head and the shell go down to one level (`boxes::foot`); the sill lies +/// `lift_m` under the floor, under the road of the tube and of the ground. Faces that meet share the corners of their +/// edges. Each opening of a pair draws the head wall of both with its own hole, on its side of the middle between their +/// walls, and closes the reveal where the two holes differ there. pub fn faces f64>(b: &mut Builder, net: &Net, e: usize) { let end = &net.ends[e]; - let Some((c, _)) = net.opening(e) else { return }; + let Some((c, k)) = net.opening(e) else { return }; let chord = &net.chords[c]; let look = &net.rules.looks[&end.look]; let (design, bake) = (&net.rules.design, &net.rules.ladder.bake); - let (n, sill, foot) = (design.arch_segments, -design.lift_m, boxes::foot(net, e)); - let (half, edge) = (chord.half, chord.half + bake.shell_m); + let (sill, foot) = (-design.lift_m, boxes::foot(net, e)); + let half = chord.half; let sp = spring(net, chord.section, chord.height); - let pieces = tube::floor_pieces(net, chord); - // An outline of the opening grown by `grow`, from the sill up its side to a corner at the floor's height there, - // where the tube's wall stands on the floor, and on over its top. - let grown = |grow: f64| { - let o = outline(chord.section, half + grow, chord.height + grow, sp, n); - let (first, last) = (o[0][0], o[o.len() - 1][0]); - let sides = |x: f64, top: f64| [[x, sill], [x, top]]; - let mut out = sides(first, pieces[0].2).to_vec(); - out.extend_from_slice(&o[1..o.len() - 1]); - out.extend(sides(last, pieces[pieces.len() - 1].2).into_iter().rev()); - out - }; - let (inner, hole) = (grown(0.0), grown(design.frame_m)); - let (front, ring, back) = - (net.frame(e, -design.recess_m), net.frame(e, 0.0), net.frame(e, design.face_m - design.recess_m)); let reach = boxes::reach(net, e); let shell = collar(net, e, reach.shell); - let (h, section) = shell.first().map_or((chord.height, chord.section), |p| (p.2, p.3)); let into = end.way_in(); let (inward_, outward) = (flat(into), flat([-into[0], -into[1]])); - let wide = (-(edge + end.right.len() as f64), edge + end.left.len() as f64); - let top = |t: f64| top(end, edge, (bake.coping_m, design.wing_slope), t); - let wall = Wall { top: &top, wide, edge, foot, coping: bake.coping_m, face: look.face, cope: look.coping }; - // The sill is split where the pieces of the floor meet the front of the tube. - let hw = hole[0][0].abs(); - let sills: Vec = - [-hw].into_iter().chain(pieces.iter().map(|p| p.0)).chain([pieces[pieces.len() - 1].1, hw]).collect(); - let front_top = wall.face(b, &front, &hole, &sills, outward); - // The back's hole is the outside of the collar's shell, which goes on from it. - let back_top = wall.face(b, &back, &tube::shell_outline(net, section, half, h, foot - back.z), &[], inward_); - b.strip((&front, &front_top), (&back, &back_top), look.coping, [0.0, 0.0, 1.0]); - for t in [wide.0, wide.1] { - wall.column( - b, - (&front, t, &wall.side(&front, t, &[])), - (&back, t, &wall.side(&back, t, &[])), - front.out([t.signum(), 0.0]), - ); - } - // The sill from the front to the frame line, the reveal, and the frame round the opening. - for w in sills.windows(2) { - let line = [[w[0], sill], [w[1], sill]]; - b.strip((&front, &line), (&ring, &line), look.face, [0.0, 0.0, 1.0]); - } - for k in 0..hole.len() - 1 { - b.strip( - (&front, &hole[k..k + 2]), - (&ring, &hole[k..k + 2]), - look.face, - front.out(inward(hole[k], hole[k + 1], sp)), - ); - b.strip((&ring, &hole[k..k + 2]), (&ring, &inner[k..k + 2]), look.frame, outward); - } - // The dark face in the opening, which the viewer draws where the terrain is coarse. - let dark = flagged(net.rules.inside.void, VOID); - let st = net.frame(e, design.void_m); - let centre = b.at(&st, [0.0, chord.height / 2.0], dark); - let rim: Vec = inner.iter().map(|&c| b.at(&st, c, dark)).collect(); - for k in 0..rim.len() { - b.triangle(centre, rim[k], rim[(k + 1) % rim.len()], outward); + if net.closed(e) { + closed(b, net, (e, c, k), foot); + } else { + let pieces = tube::floor_pieces(net, chord); + let (inner, hole) = (grown(net, e, 0.0), grown(net, e, design.frame_m)); + let (front, ring, back) = + (net.frame(e, -design.recess_m), net.frame(e, 0.0), net.frame(e, design.face_m - design.recess_m)); + let (h, section) = shell.first().map_or((chord.height, chord.section), |p| (p.2, p.3)); + let cut = pair_cut(net, e); + b.clip(cut.map(|(x, side)| { + let (p, q, r) = (front.at([x, 0.0]), back.at([x, 0.0]), front.at([x + side, 0.0])); + Clip { a: [p[0], p[1]], b: [q[0], q[1]], away: [r[0] - p[0], r[1] - p[1]] } + })); + let wide = wide(net, e); + let (rim, edges) = (rim(net, e), edges(net, e)); + let rim_line = rim_outline(net, e); + // The rows of a pair are over the floor of its record's opening, the end of the input before its mate. + let record = net.mate[e].filter(|&m| m < e).map_or(0.0, |m| net.ends[m].z - end.z); + let top = |t: f64| { + if rim { + top_at(&rim_line, t).unwrap_or(0.0) + } else { + top(end, edges, (bake.coping_m + record, design.wing_slope), t) + } + }; + let (edges, coping, cope) = if rim { (wide, 0.0, look.face) } else { (edges, bake.coping_m, look.coping) }; + let wall = Wall { top: &top, wide, edges, foot, coping, face: look.face, cope }; + // The sill is split where the pieces of the floor meet the front of the tube. + let hw = hole[0][0].abs(); + let sills: Vec = + [-hw].into_iter().chain(pieces.iter().map(|p| p.0)).chain([pieces[pieces.len() - 1].1, hw]).collect(); + let front_top = wall.face(b, &front, &hole, &sills, outward); + // The back's hole is the outside of the collar's shell, which goes on from it. + let back_top = wall.face(b, &back, &tube::shell_outline(net, section, half, h, foot - back.z), &[], inward_); + b.strip((&front, &front_top), (&back, &back_top), cope, [0.0, 0.0, 1.0]); + for t in [wide.0, wide.1] { + wall.column( + b, + (&front, t, &wall.side(&front, t, &[])), + (&back, t, &wall.side(&back, t, &[])), + front.out([t.signum(), 0.0]), + ); + } + // The sill from the front to the frame line, the reveal, and the frame round the opening. + for w in sills.windows(2) { + let line = [[w[0], sill], [w[1], sill]]; + b.strip((&front, &line), (&ring, &line), look.face, [0.0, 0.0, 1.0]); + } + for k in 0..hole.len() - 1 { + b.strip( + (&front, &hole[k..k + 2]), + (&ring, &hole[k..k + 2]), + look.face, + front.out(inward(hole[k], hole[k + 1], sp)), + ); + b.strip((&ring, &hole[k..k + 2]), (&ring, &inner[k..k + 2]), look.frame, outward); + } + // The dark face in the opening, which the viewer draws where the terrain is coarse. + let dark = flagged(net.rules.inside.void, VOID); + let st = net.frame(e, design.void_m); + let centre = b.at(&st, [0.0, chord.height / 2.0], dark); + let rim_v: Vec = inner.iter().map(|&c| b.at(&st, c, dark)).collect(); + for k in 0..rim_v.len() { + b.triangle(centre, rim_v[k], rim_v[(k + 1) % rim_v.len()], outward); + } + b.clip(None); + // Where the two holes of a pair differ at the middle, the reveal closes the step, from the front to the frame + // line: under the higher sill and over the lower top. + if let (Some((x, side)), Some(m)) = (cut, net.mate[e]) { + let other = grown(net, m, design.frame_m); + let span = |st: &Station, s: f64| { + let df = net.frame(m, s).z - st.z; + let own = (sill, top_at(&hole, x)?); + let them = top_at(&other, x - net.ends[e].mate?).map(|t| (sill + df, t + df)); + Some(steps(own, them)) + }; + if let (Some(a), Some(z)) = (span(&front, -design.recess_m), span(&ring, 0.0)) { + for i in 0..2 { + cut_face( + b, + (&front, &ring), + (x, a[i].0, a[i].1), + (x, z[i].0, z[i].1), + look.face, + front.out([-side, 0.0]), + ); + } + } + } } - let run: Vec<_> = shell.iter().map(|p| (p.0, p.1, p.2, p.3)).collect(); + let run: Vec<_> = shell.iter().map(|p| (p.0, p.1, p.2, p.3, p.4)).collect(); tube::shell(b, net, &run, half, foot, look.shell, reach.then); if let Some(&(s, t, _, _, c, k)) = shell.last().filter(|_| reach.closed) { + b.clip(net.clip(c, (&s, &t)).map(|c| c.0)); end_face(b, net, (c, k), &t, foot, look.shell, flat([t.x - s.x, t.y - s.y])); + b.clip(None); + } +} + +/// The front of a closed end e at chord c's vertex k: the face that closes its shell on the frame line, and over the +/// inside of its tube a dark face that the viewer always draws, seen from inside. +fn closed f64>(b: &mut Builder, net: &Net, (e, c, k): (usize, usize, usize), foot: f64) { + let (end, chord) = (&net.ends[e], &net.chords[c]); + let (ring, into) = (net.frame(e, 0.0), net.ends[e].way_in()); + let look = &net.rules.looks[&end.look]; + end_face(b, net, (c, k), &ring, foot, look.shell, flat([-into[0], -into[1]])); + // The room's outline round, from the right wall's foot: up and over, down the left wall, back across the floor. + let (right, left) = room(net, (c, k)); + let mut round = right; + round.extend(left[1..left.len() - 1].iter().rev()); + let dark = net.rules.inside.void; + let centre = b.at(&ring, [0.0, chord.height / 2.0], dark); + let rim: Vec = round.iter().map(|&c| b.at(&ring, c, dark)).collect(); + for k in 0..rim.len() { + b.triangle(centre, rim[k], rim[(k + 1) % rim.len()], flat(into)); } } @@ -147,19 +271,29 @@ fn end_face f64>( out: [f64; 3], ) { let chord = &net.chords[c]; - let sp = spring(net, chord.section, chord.height); let shell = tube::shell_outline(net, chord.section, chord.half, chord.height, foot - t.z); + let n = shell.len(); + let (right, left) = room(net, (c, k)); + b.strip((t, &shell[..n - 1]), (t, &right), colour, out); + let bottom = [shell[0], shell[n - 1], shell[n - 2]]; + b.strip((t, &bottom), (t, &left), colour, out); +} + +/// The room of chord c at its vertex k, as the inside draws it there, in two runs from the right wall's foot to the +/// left spring: up the right wall and over the vault; across the floor (each piece's top, and both tops where two +/// pieces meet) and up the left wall. A wall has the spring of a lower chord that goes on there. +fn room(net: &Net, (c, k): (usize, usize)) -> (Vec, Vec) { + let chord = &net.chords[c]; + let sp = spring(net, chord.section, chord.height); let inner = outline(chord.section, chord.half, chord.height, sp, net.rules.design.arch_segments); let (n, pieces) = (inner.len(), tube::floor_pieces(net, chord)); let lower = net.lower(c, k).map(|l| spring(net, chord.section, l)); - // The inside's wall from the floor at `x` up to the spring, with the spring of a lower chord between. let wall = |x: f64, floor: f64| { let mut w = vec![[x, floor]]; w.extend(lower.filter(|&l| l > floor && l < sp).map(|l| [x, l])); w.push([x, sp]); w }; - // The floor from the right wall to the left: each piece's top, and both tops where two pieces meet. let mut floor: Vec = vec![[pieces[0].0, pieces[0].2]]; for w in pieces.windows(2) { floor.push([w[0].1, w[0].2]); @@ -169,11 +303,8 @@ fn end_face f64>( floor.dedup(); let right: Vec = wall(inner[0][0], pieces[0].2).into_iter().chain(inner[2..n - 1].iter().copied()).collect(); - let mut left = floor.clone(); - left.extend(wall(inner[n - 1][0], pieces[pieces.len() - 1].2).into_iter().skip(1)); - b.strip((t, &shell[..n - 1]), (t, &right), colour, out); - let bottom = [shell[0], shell[n - 1], shell[n - 2]]; - b.strip((t, &bottom), (t, &left), colour, out); + floor.extend(wall(inner[n - 1][0], pieces[pieces.len() - 1].2).into_iter().skip(1)); + (right, floor) } /// Whole metres from a to b, with a and b. @@ -192,12 +323,12 @@ fn metres(a: f64, b: f64) -> Vec { out } -/// A face of a head wall: its top over the opening's floor, flat out to `edge` across and per metre out past it, the -/// metres across of its two ends, the height of its foot, the depth of its coping and its colours. +/// A face of a head wall: its top over the opening's floor, flat or round between `edges` across and per metre out past +/// them, the metres across of its two ends, the height of its foot, the depth of its coping and its colours. struct Wall<'a> { top: &'a dyn Fn(f64) -> f64, wide: (f64, f64), - edge: f64, + edges: (f64, f64), foot: f64, coping: f64, face: u32, @@ -245,17 +376,17 @@ impl Wall<'_> { sills: &[f64], out: [f64; 3], ) -> Vec { - let (n, hw, foot, (wide, edge)) = (hole.len(), hole[0][0].abs(), self.foot - st.z, (self.wide, self.edge)); + let (n, hw, foot, (wide, edges)) = (hole.len(), hole[0][0].abs(), self.foot - st.z, (self.wide, self.edges)); // The side of the hole up to where its top starts. let rise = hole.iter().position(|p| p[0] != hole[0][0]).unwrap() - 1; let jamb: Vec = [foot].into_iter().chain(hole[..=rise].iter().map(|p| p[1])).collect(); let mut columns: Vec<(f64, Side)> = - (metres(wide.0, -edge).into_iter().filter(|&t| t < -hw)).map(|t| (t, self.side(st, t, &[]))).collect(); + (metres(wide.0, edges.0).into_iter().filter(|&t| t < -hw)).map(|t| (t, self.side(st, t, &[]))).collect(); columns.push((-hw, self.side(st, -hw, &jamb))); let over: Vec<(f64, Side)> = hole[rise..n - rise].iter().map(|p| (p[0], self.side(st, p[0], &[p[1]]))).collect(); let mut left = vec![(hw, self.side(st, hw, &jamb))]; - left.extend((metres(edge, wide.1).into_iter().filter(|&t| t > hw)).map(|t| (t, self.side(st, t, &[])))); + left.extend((metres(edges.1, wide.1).into_iter().filter(|&t| t > hw)).map(|t| (t, self.side(st, t, &[])))); for list in [&columns, &over, &left] { for w in list.windows(2) { self.column(b, (st, w[0].0, &w[0].1), (st, w[1].0, &w[1].1), out); diff --git a/host/obc-trailview-parts/src/boxes.rs b/host/obc-trailview-parts/src/boxes.rs index 54f3a61d6..8fe1ed4a2 100644 --- a/host/obc-trailview-parts/src/boxes.rs +++ b/host/obc-trailview-parts/src/boxes.rs @@ -191,7 +191,7 @@ impl Line { } /// The boxes of built end e: the opening's, from the front of the head wall to the frame line, its outline grown to -/// the middle of the wall round it; then one per straight piece of the tube's axis out to its reach, each at the +/// the middle of the wall round it, but at a closed end; then one per straight piece of the tube's axis out to its reach, each at the /// middle of the wall of its section, its ends in the planes of the tube's rings there. pub fn boxes(net: &Net, e: usize) -> Vec<[f64; BOX]> { let Some((c0, _)) = net.opening(e) else { return Vec::new() }; @@ -207,20 +207,10 @@ pub fn boxes(net: &Net, e: usize) -> Vec<[f64; BOX]> { let sp = spring(net, first.section, first.height); let (roof, spring_at) = roof_of(front.z, first.height, sp, first.section, design.frame_m + wall); let (half, rise) = (first.half + design.frame_m + wall, (ring.z - front.z) / design.recess_m); - let mut out = vec![[ - front.x, - front.y, - into[0], - into[1], - design.recess_m, - half, - roof, - front.z + lift, - rise, - spring_at, - 0.0, - 0.0, - ]]; + let opening = + [front.x, front.y, into[0], into[1], design.recess_m, half, roof, front.z + lift, rise, spring_at, 0.0, 0.0]; + // A closed end has no opening. + let mut out = if net.closed(e) { Vec::new() } else { vec![opening] }; // The axis from the frame line: per chord of the walk its far vertex, with the height and section that end there. let reach = reach(net, e).boxes; let mut axis = vec![Axis { p: end.at, z: end.z, ring }]; diff --git a/host/obc-trailview-parts/src/footprint.rs b/host/obc-trailview-parts/src/footprint.rs index 306191dc9..f76bfc1c5 100644 --- a/host/obc-trailview-parts/src/footprint.rs +++ b/host/obc-trailview-parts/src/footprint.rs @@ -1,15 +1,15 @@ //! The ring that a part takes from the ground. -use crate::arch::collar; +use crate::arch::{collar, wide}; use crate::tube::Net; -/// The ring of end e, in world units, in order round it: the head wall and its wings from front to back, and the -/// collar's shell along its chords out to `collar`. +/// The ring of end e, in world units, in order round it: its head from front to back (the head wall of both openings +/// of a pair), and the collar's shell along its chords out to `collar`. pub fn ring(net: &Net, e: usize) -> Vec<[f64; 2]> { let end = &net.ends[e]; let (design, bake) = (&net.rules.design, &net.rules.ladder.bake); let edge = end.half + bake.shell_m; - let (wide_r, wide_l) = (-(edge + end.right.len() as f64), edge + end.left.len() as f64); + let (wide_r, wide_l) = wide(net, e); let (front, back) = (net.frame(e, -design.recess_m), net.frame(e, design.face_m - design.recess_m)); let xy = |p: [f64; 3]| [p[0], p[1]]; let mut out = vec![xy(front.at([wide_r, 0.0])), xy(front.at([wide_l, 0.0])), xy(back.at([wide_l, 0.0]))]; diff --git a/host/obc-trailview-parts/src/lib.rs b/host/obc-trailview-parts/src/lib.rs index 8597d34b0..4cfde3d88 100644 --- a/host/obc-trailview-parts/src/lib.rs +++ b/host/obc-trailview-parts/src/lib.rs @@ -50,7 +50,7 @@ impl Part { } /// The kinds of part that the builder makes. A chain draws as parts only where both of its ends are of these kinds. -pub const BUILT: &[Part] = &[Part::Arch, Part::Box]; +pub const BUILT: &[Part] = &[Part::Arch, Part::Pair, Part::Rock, Part::Box, Part::Free]; /// Whether all ends of a chain are built; `None` is an end with no part of its own. pub fn built(ends: &[Option]) -> bool { @@ -253,7 +253,7 @@ fn near(square: [f64; 4], points: &[[f64; 2]], reach: f64) -> bool { pub fn meshes(square: [f64; 4], ends: &[End], chords: &[Chord], rules: &Rules) -> Mesh { let net = Net::new(ends, chords, rules); let mut b = mesh::Builder::new(|p| net.daylight(p)); - for (e, end) in ends.iter().enumerate() { + for (e, end) in net.ends.iter().enumerate() { if net.built_end(e) && holds(square, end.at) { arch::faces(&mut b, &net, e); } @@ -272,7 +272,7 @@ pub fn volumes(ends: &[End], chords: &[Chord], rules: &Rules) -> Volumes { let net = Net::new(ends, chords, rules); let lift = rules.design.lift_m; let mut out = Volumes::default(); - for e in (0..ends.len()).filter(|&e| net.built_end(e)) { + for e in (0..net.ends.len()).filter(|&e| net.built_end(e)) { for words in boxes::boxes(&net, e) { out.boxes.extend(words); } @@ -302,15 +302,29 @@ pub fn near_volumes(square: [f64; 4], boxes: &[f64], floors: &[f64], rules: &Rul Volumes { boxes: boxes.flatten().copied().collect(), floors: floors.flatten().copied().collect() } } -/// Per end, whether it is built: its part and the chain of the chord at its opening are built. -pub fn built_ends(ends: &[End], chords: &[Chord], rules: &Rules) -> Vec { +/// An opening of a built end, two of a pair: its point, its unit way into the tube and its inside half-width, and the +/// end vertex of its way and the metres along that way to it (`way`, `shift`). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Mouth { + pub at: [f64; 2], + pub into: [f64; 2], + pub half: f64, + pub way: [i64; 2], + pub shift: f64, +} + +/// The openings of the built ends. +pub fn mouths(ends: &[End], chords: &[Chord], rules: &Rules) -> Vec { let net = Net::new(ends, chords, rules); - (0..ends.len()).map(|e| net.built_end(e)).collect() + (net.ends.iter().enumerate()) + .filter(|&(e, _)| net.built_end(e)) + .map(|(_, end)| Mouth { at: end.at, into: end.way_in(), half: end.half, way: end.way, shift: end.shift }) + .collect() } -/// Per built end, the ring that its part takes from the ground: round its head wall and wings, from front to back, +/// Per built end with an opening, the ring that its part takes from the ground: round its head, from front to back, /// and its collar. pub fn footprints(ends: &[End], chords: &[Chord], rules: &Rules) -> Vec> { let net = Net::new(ends, chords, rules); - (0..ends.len()).filter(|&e| net.built_end(e)).map(|e| footprint::ring(&net, e)).collect() + (0..net.ends.len()).filter(|&e| net.built_end(e) && !net.closed(e)).map(|e| footprint::ring(&net, e)).collect() } diff --git a/host/obc-trailview-parts/src/mesh.rs b/host/obc-trailview-parts/src/mesh.rs index 22ea90007..892aed03a 100644 --- a/host/obc-trailview-parts/src/mesh.rs +++ b/host/obc-trailview-parts/src/mesh.rs @@ -1,6 +1,8 @@ //! Faces as the viewer's structure meshes hold them (`structures/mesh.ts`), and the stations and cross-sections that //! the parts sweep. +use std::collections::HashMap; + use crate::{metres_per_unit, Mesh, Section}; /// Words of a vertex: x, y (i32 world units), z (f32), colour and flags, across and half-width of a road face @@ -99,19 +101,57 @@ pub struct Paint { pub const PLAIN: Paint = Paint { across: 0.0, half: 0.0, sleepers: NO_SLEEPERS }; +/// A vertical plane through two world points in plan that takes off the faces on one side of it: the side of `away`, +/// a world direction. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Clip { + pub a: [f64; 2], + pub b: [f64; 2], + pub away: [f64; 2], +} + +impl Clip { + /// How far a world point lies on the side that the plane takes off, in world units. + fn side(&self, p: [f64; 3]) -> f64 { + let n = [self.b[1] - self.a[1], self.a[0] - self.b[0]]; + let l = libm::hypot(n[0], n[1]).max(f64::MIN_POSITIVE); + let sign = if n[0] * self.away[0] + n[1] * self.away[1] >= 0.0 { 1.0 } else { -1.0 }; + sign * ((p[0] - self.a[0]) * n[0] + (p[1] - self.a[1]) * n[1]) / l + } +} + /// Collects faces. Each face is wound counter-clockwise seen from the side that `out` points to (east, north, up), -/// so the back faces cull. +/// so the back faces cull. With a clip, the part of a face past its plane is not drawn. pub struct Builder f64> { words: Vec, indices: Vec, points: Vec<[f64; 3]>, + looks: Vec<(u32, Paint)>, daylight: L, + clip: Option, + /// The vertex where the clip's plane cuts the edge between two vertices. + cuts: HashMap<(u32, u32), u32>, } impl f64> Builder { /// A builder whose vertices take their daylight from `daylight` of their world point. pub fn new(daylight: L) -> Self { - Builder { words: Vec::new(), indices: Vec::new(), points: Vec::new(), daylight } + Builder { + words: Vec::new(), + indices: Vec::new(), + points: Vec::new(), + looks: Vec::new(), + daylight, + clip: None, + cuts: HashMap::new(), + } + } + + /// The clip of the faces from now on. + pub fn clip(&mut self, clip: Option) { + if clip != self.clip { + (self.clip, self.cuts) = (clip, HashMap::new()); + } } pub fn vertex(&mut self, p: [f64; 3], colour: u32, paint: Paint) -> u32 { @@ -127,9 +167,54 @@ impl f64> Builder { (light as f32).to_bits(), ]); self.points.push(p); + self.looks.push((colour, paint)); (self.points.len() - 1) as u32 } + /// The vertex where the clip's plane cuts the edge from vertex i to j, which lie at `di` and `dj` from it. + fn cut(&mut self, (i, di): (u32, f64), (j, dj): (u32, f64)) -> u32 { + let key = (i.min(j), i.max(j)); + if let Some(&v) = self.cuts.get(&key) { + return v; + } + let (u, p, q) = (di / (di - dj), self.points[i as usize], self.points[j as usize]); + let ((colour, a), z) = (self.looks[i as usize], self.looks[j as usize].1); + let mix = |a: f64, b: f64| a + (b - a) * u; + let paint = Paint { across: mix(a.across, z.across), half: a.half, sleepers: mix(a.sleepers, z.sleepers) }; + let v = self.vertex([mix(p[0], q[0]), mix(p[1], q[1]), mix(p[2], q[2])], colour, paint); + self.cuts.insert(key, v); + v + } + + /// A triangle in its winding, without its part past the clip's plane. + fn emit(&mut self, t: [u32; 3]) { + let Some(clip) = self.clip else { + self.indices.extend(t); + return; + }; + let d = t.map(|v| clip.side(self.points[v as usize])); + // Within a hundredth of a world unit of the plane, a point lies on it. + let off = |x: f64| x > 0.01; + if !d.iter().any(|&x| off(x)) { + self.indices.extend(t); + return; + } + // The corners on the near side, and the points where an edge crosses the plane, in the winding. + let mut keep = Vec::with_capacity(4); + for k in 0..3 { + let (i, j) = (k, (k + 1) % 3); + if !off(d[i]) { + keep.push(t[i]); + } + if off(d[i]) != off(d[j]) { + keep.push(self.cut((t[i], d[i]), (t[j], d[j]))); + } + } + for k in 1..keep.len().saturating_sub(1) { + self.indices.extend([keep[0], keep[k], keep[k + 1]]); + } + } + pub fn at(&mut self, s: &Station, c: Corner, colour: u32) -> u32 { self.vertex(s.at(c), colour, PLAIN) } @@ -140,12 +225,13 @@ impl f64> Builder { if n.iter().all(|c| c.abs() < 1e-12) { return; } - let facing = n[0] * out[0] + n[1] * out[1] + n[2] * out[2] >= 0.0; - self.indices.extend(if facing { - [v[0], v[1], v[2], v[0], v[2], v[3]] + if n[0] * out[0] + n[1] * out[1] + n[2] * out[2] >= 0.0 { + self.emit([v[0], v[1], v[2]]); + self.emit([v[0], v[2], v[3]]); } else { - [v[0], v[2], v[1], v[0], v[3], v[2]] - }); + self.emit([v[0], v[2], v[1]]); + self.emit([v[0], v[3], v[2]]); + } } /// A triangle turned to face `out`. A triangle of no area makes no face. @@ -155,7 +241,7 @@ impl f64> Builder { return; } let facing = n[0] * out[0] + n[1] * out[1] + n[2] * out[2] >= 0.0; - self.indices.extend(if facing { [a, b, c] } else { [a, c, b] }); + self.emit(if facing { [a, b, c] } else { [a, c, b] }); } /// The faces between two polylines that run side by side from a common start to a common end: the corners `a` at @@ -192,8 +278,20 @@ impl f64> Builder { } } + /// The mesh of the faces, with the vertices that a face uses. pub fn mesh(self) -> Mesh { - Mesh { vertices: self.words, indices: self.indices } + let mut to = vec![u32::MAX; self.points.len()]; + let mut vertices = Vec::with_capacity(self.words.len()); + let indices = (self.indices.iter()) + .map(|&i| { + if to[i as usize] == u32::MAX { + to[i as usize] = (vertices.len() / WORDS) as u32; + vertices.extend_from_slice(&self.words[i as usize * WORDS..(i as usize + 1) * WORDS]); + } + to[i as usize] + }) + .collect(); + Mesh { vertices, indices } } /// The normal of a, b, c, d by their diagonals, in metres east, north and up. diff --git a/host/obc-trailview-parts/src/tests.rs b/host/obc-trailview-parts/src/tests.rs index 6844ba61c..0cfc33d18 100644 --- a/host/obc-trailview-parts/src/tests.rs +++ b/host/obc-trailview-parts/src/tests.rs @@ -149,7 +149,7 @@ fn boxes_fit(name: &str, ends: &[End], chords: &[Chord]) -> (usize, usize) { // Within the rounding of a box's words and of a sample: a millimetre. let tol = 1e-3; let (mut room, mut solid) = (0, 0); - for e in (0..ends.len()).filter(|&e| net.built_end(e)) { + for e in (0..net.ends.len()).filter(|&e| net.built_end(e)) { let list = boxes::boxes(&net, e); let small: Vec<[f64; BOX]> = list.iter().map(|b| shrunk(b, MARGIN_M)).collect(); let held = |boxes: &[[f64; BOX]], p: [f64; 3]| { @@ -161,7 +161,7 @@ fn boxes_fit(name: &str, ends: &[End], chords: &[Chord]) -> (usize, usize) { let first = &net.chords[c0]; let sp = tube::spring(&net, first.section, first.height); // The room: the opening's hole from the front of the head wall to the frame line. - for k in 0..=4 { + for k in (0..=4).filter(|_| !net.closed(e)) { let st = net.frame(e, -design.recess_m * (1.0 - k as f64 / 4.0)); for a in [-1.0, -0.5, 0.0, 0.5, 1.0] { let hw = first.half + design.frame_m; @@ -210,7 +210,7 @@ fn boxes_fit(name: &str, ends: &[End], chords: &[Chord]) -> (usize, usize) { } // Each box of the tube, grown by the margin: points of its sides, its floor and its roof, at shares 0 to 1 // between its end planes, inside the drawn shell. - let m = metres_per_unit(ends[e].at[1]); + let m = metres_per_unit(net.ends[e].at[1]); for (i, b) in list.iter().enumerate().skip(1) { let lu = mesh::left_of([b[2], b[3]]); let (depth, half, roof, floor, spring) = (b[4], b[5] + MARGIN_M, b[6] + MARGIN_M, b[7], b[9]); @@ -473,14 +473,15 @@ fn open_edges(mesh: &Mesh) -> (Edges, Edges) { fn not_closed(ends: &[End], chords: &[Chord]) -> (Edges, Edges) { let rules = Rules::embedded(); let net = Net::new(ends, chords, rules); - let feet: Vec = (0..ends.len()).filter(|&e| net.built_end(e)).map(|e| boxes::foot(&net, e)).collect(); - // Per end whose shell a face closes, the station of that face. - let faces: Vec = (0..ends.len()) - .filter(|&e| net.built_end(e)) + let built = || (0..net.ends.len()).filter(|&e| net.built_end(e)); + let feet: Vec = built().map(|e| boxes::foot(&net, e)).collect(); + // Per end whose shell a face closes, the station of that face; and the front of a closed end. + let faces: Vec = (built()) .filter_map(|e| { let r = boxes::reach(&net, e); arch::collar(&net, e, r.shell).last().filter(|_| r.closed).map(|p| p.1) }) + .chain(built().filter(|&e| net.closed(e)).map(|e| net.frame(e, 0.0))) .collect(); // Within the rounding of a vertex to whole world units. let at_foot = |p: [f64; 3]| feet.iter().any(|f| (p[2] - f).abs() < 1e-3); @@ -648,3 +649,183 @@ fn the_faces_along_a_tube_face_out_of_its_shell_and_into_its_room() { assert!(out > 20 && inside > 20, "{name}: {out} faces of the shell, {inside} inside"); } } + +/// A tube as one of `part` at both ends, of a way of `class`. +fn kind((mut ends, mut chords): (Vec, Vec), part: Part, class: &str) -> (Vec, Vec) { + for e in &mut ends { + e.part = part; + } + for c in &mut chords { + (c.ends, c.class) = ([Some(part); 2], class.into()); + } + (ends, chords) +} + +/// Two road tubes 40 m east from a pair at each end: the first on the line 0 m north, the second `apart` metres north +/// with its floor `dz` higher; each of two chords. +fn pair(apart: f64, dz: f64) -> (Vec, Vec) { + let pi = std::f64::consts::PI; + let mut ends = vec![end(0.0, 0.0, 500.0, 0.0, 6.0), end(40.0, 0.0, 500.2, pi, 3.0)]; + // Into the tubes from the west the second lies to the left, from the east to the right. + for (e, mate) in ends.iter_mut().zip([apart, -apart]) { + (e.part, e.mate, e.mate_way, e.mate_shift) = (Part::Pair, Some(mate), Some([1, 1]), Some(0.0)); + } + let mut chords = Vec::new(); + for (north, z) in [(0.0, 500.0), (apart, 500.0 + dz)] { + for (a, b) in [(0.0, 20.0), (20.0, 40.0)] { + let mut c = chord([a, north, z + a * 0.005], [b, north, z + b * 0.005], 5.0, a); + c.ends = [Some(Part::Pair); 2]; + chords.push(c); + } + } + (ends, chords) +} + +/// The triangles of a mesh in metres east, north and up, but the dark faces of the openings and the lamps. +fn solid(mesh: &Mesh) -> Vec<[[f64; 3]; 3]> { + let point = |i: u32| { + let w = &mesh.vertices[i as usize * WORDS..]; + let p = metric([w[0] as i32 as f64, w[1] as i32 as f64]); + [p[0], p[1], f32::from_bits(w[2]) as f64] + }; + let shown = |i: u32| (mesh.vertices[i as usize * WORDS + 3] >> 24) & (mesh::VOID | mesh::LAMP) == 0; + mesh.indices.chunks(3).filter(|t| shown(t[0])).map(|t| [point(t[0]), point(t[1]), point(t[2])]).collect() +} + +/// The first face that a ray from `o` along `d` meets within `far` metres: its distance, and whether the ray meets its +/// front, or the front of a face at the same distance (two faces back to back). +fn hit(faces: &[[[f64; 3]; 3]], o: [f64; 3], d: [f64; 3], far: f64) -> Option<(f64, bool)> { + let sub = |a: [f64; 3], b: [f64; 3]| [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; + let cross = + |a: [f64; 3], b: [f64; 3]| [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; + let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + let mut best: Option<(f64, bool)> = None; + for [a, b, c] in faces { + let (e1, e2) = (sub(*b, *a), sub(*c, *a)); + let p = cross(d, e2); + let det = dot(e1, p); + if det.abs() < 1e-12 { + continue; + } + let tv = sub(o, *a); + let (u, q) = (dot(tv, p) / det, cross(tv, e1)); + let (v, t) = (dot(d, q) / det, dot(e2, q) / det); + if u < -1e-9 || v < -1e-9 || u + v > 1.0 + 1e-9 || t <= 1e-6 || t > far { + continue; + } + let front = dot(cross(e1, e2), d) < 0.0; + best = match best { + Some(b) if (t - b.0).abs() < 1e-6 => Some((b.0, b.1 || front)), + Some(b) if b.0 < t => Some(b), + _ => Some((t, front)), + }; + } + best +} + +#[test] +fn the_two_tubes_of_a_pair_are_one_room_and_one_head_wall() { + let rules = Rules::embedded(); + let frame = rules.design.frame_m; + // Tubes 7 m apart, 4.5 m wide each: their rooms overlap by 2 m, so they are cut in the middle; with the second's + // floor 0.8 m higher, faces close the steps there. Tubes 10.5 m apart do not overlap. + for (apart, dz) in [(7.0, 0.0), (7.0, 0.8), (10.5, 0.0)] { + let name = format!("{apart} m apart, {dz} m higher"); + let (ends, chords) = pair(apart, dz); + let (room, box_points) = boxes_fit(&name, &ends, &chords); + assert!(room > 200 && box_points > 100, "{name}: {room} room samples, {box_points} box samples"); + let mesh = meshes([0.0, 0.0, 1.07e9, 1.07e9], &ends, &chords, rules); + let faces = solid(&mesh); + let o = tube::outline_of(&Net::new(&ends, &chords, rules), 0); + // Each tube's room on its side of the middle: no face lies in it. A face in the middle lies within the rounding + // of its vertices to world units. + let mid = apart / 2.0; + let inside = |p: [f64; 3]| { + let (axis, z) = if p[1] < mid { (0.0, 500.0) } else { (apart, 500.0 + dz) }; + if (p[1] - mid).abs() < 0.05 { + return false; + } + let (x, up) = (p[1] - axis, p[2] - z - p[0] * 0.005); + p[0] > 0.5 + && p[0] < 39.5 + && x.abs() < 4.45 + && up > 0.25 + && tube::top_at(&o, x).is_some_and(|t| up < t - 0.05) + }; + for f in &faces { + let c = [0, 1, 2].map(|k| (f[0][k] + f[1][k] + f[2][k]) / 3.0); + assert!(!inside(c), "{name}: a face in the room at {c:?}"); + } + // From inside the room, every way across meets the front of a face: the room is closed at the middle. + for (north, up) in [(-3.0, 1.0), (0.0, 2.5), (2.5, 4.0), (apart - 2.5, 4.0), (apart, 2.5), (apart + 3.0, 1.0)] { + let z = if north < mid { 500.0 } else { 500.0 + dz }; + for k in 0..24 { + let a = (k as f64 * 15.0 + 7.0).to_radians(); + let d = [0.0, libm::cos(a), libm::sin(a)]; + let got = hit(&faces, [20.0, north, z + 0.1 + up], d, 30.0); + assert!(got.is_some_and(|h| h.1), "{name}: from {north} m north, {up} m up, at {a} rad: {got:?}"); + } + } + // One head wall: in front of the frame line, a ray east meets its front between the two holes, but none in a + // hole; where the holes overlap, they are one opening. + let holes_meet = apart < 2.0 * (4.5 + frame); + { + let north = mid; + let got = hit(&faces, [-3.0, north, 501.0], [1.0, 0.0, 0.0], 10.0); + if holes_meet { + assert!(got.is_none_or(|h| h.0 > 3.5), "{name}: the middle of one opening: {got:?}"); + } else { + assert!(got.is_some_and(|h| h.1 && h.0 < 3.0), "{name}: the head wall between the holes: {got:?}"); + } + } + for north in [0.0, apart] { + let got = hit(&faces, [-3.0, north, 502.5], [1.0, 0.0, 0.0], 10.0); + assert!(got.is_none_or(|h| h.0 > 3.5), "{name}: the hole at {north} m north: {got:?}"); + } + } +} + +#[test] +fn a_rim_hugs_its_opening_and_a_covered_free_end_is_closed() { + let rules = Rules::embedded(); + let d = &rules.design; + let (shell, frame) = (rules.ladder.bake.shell_m, d.frame_m); + // An opening in the rock and a free tube end: the head is a rim round the opening, 0.95 m wide, with no wings. + for (name, (ends, chords)) in [ + ("rock", kind(bent(30.0, 20.0), Part::Rock, "footway")), + ("free", kind(tube(), Part::Free, "primary")), + ("closed", kind(tube(), Part::Free, "primary")), + ] { + let mut ends = ends; + if name == "closed" { + ends[0].collar = 0.0; + } + let (room, box_points) = boxes_fit(name, &ends, &chords); + assert!(room > 100 && box_points > 50, "{name}: {room} room samples, {box_points} box samples"); + let (open, crowded) = not_closed(&ends, &chords); + assert!(open.is_empty(), "{name}: {} open edges, the first {:?}", open.len(), &open[..open.len().min(4)]); + assert!( + crowded.is_empty(), + "{name}: {} crowded edges, the first {:?}", + crowded.len(), + &crowded[..crowded.len().min(4)] + ); + let net = Net::new(&ends, &chords, rules); + let ring = footprints(&ends, &chords, rules); + let (at, st) = (ends[0].at, net.frame(0, 0.0)); + let (l, m) = (mesh::left_of(ends[0].way_in()), metres_per_unit(at[1])); + let across = |p: [f64; 2]| ((p[0] - at[0]) * l[0] + (p[1] - at[1]) * l[1]) * m; + if name == "closed" { + // No opening: its first box starts on the frame line, no daylight comes from it, and it has no ring. + assert_eq!(boxes::boxes(&net, 0)[0][..2], at); + assert_eq!(net.daylight(st.at([0.0, 2.0])), 0.0); + assert_eq!(ring.len(), 1); + } else { + // The ring's head: from the front's right end to its left end and back, then the back's right end. + let head = [ring[0][0], ring[0][1], ring[0][2], ring[0][ring[0].len() - 1]]; + let wide = head.iter().map(|&p| across(p).abs()).fold(0.0, f64::max); + let half = 4.5; + assert!(wide <= half + frame + shell + 1e-6, "{name}: the ring reaches {wide} m across"); + } + } +} diff --git a/host/obc-trailview-parts/src/tube.rs b/host/obc-trailview-parts/src/tube.rs index 6133d040b..3b7618f0b 100644 --- a/host/obc-trailview-parts/src/tube.rs +++ b/host/obc-trailview-parts/src/tube.rs @@ -3,8 +3,8 @@ use std::collections::HashMap; -use crate::mesh::{flagged, flat, left_of, outline, Builder, Corner, Paint, Station, BORE, LAMP, PAINT}; -use crate::{built, metres_per_unit, Bore, Chord, End, Rules, Section}; +use crate::mesh::{flagged, flat, left_of, outline, Builder, Clip, Corner, Paint, Station, BORE, LAMP, PAINT}; +use crate::{built, metres_per_unit, Bore, Chord, End, Part, Rules, Section}; /// An end's point lies within this of the vertex of its tube's chord. const END_M: f64 = 0.5; @@ -35,9 +35,14 @@ pub fn direction(c: &Chord) -> ([f64; 2], f64) { /// The chords of a tile by their vertices, and per end the chord vertex at its opening. pub struct Net<'a> { - pub ends: &'a [End], + /// The ends of the input, then per pair an end at the opening of its mate, which has no head wall of its own. + pub ends: Vec, pub chords: &'a [Chord], pub rules: &'a Rules, + /// The count of the input's ends. + inputs: usize, + /// Per end, the other end of its pair. + pub mate: Vec>, at: HashMap<[u64; 2], Vec>, /// Per end, the chord and vertex at its opening, where its chain is built. opening: Vec>, @@ -45,36 +50,98 @@ pub struct Net<'a> { end_at: HashMap<(usize, usize), usize>, /// Per end, the rise of its floor per metre in, over its first `face_m`. slope: Vec, + /// Per chord, the chords of the other tube of a pair at an end of its chain. + beside: Vec>, } impl<'a> Net<'a> { - pub fn new(ends: &'a [End], chords: &'a [Chord], rules: &'a Rules) -> Net<'a> { + pub fn new(inputs: &[End], chords: &'a [Chord], rules: &'a Rules) -> Net<'a> { let mut at: HashMap<[u64; 2], Vec> = HashMap::new(); for (c, chord) in chords.iter().enumerate() { for k in 0..2 { at.entry(key(vertex(chord, k))).or_default().push(c); } } - let mut opening = vec![None; ends.len()]; - let mut end_at = HashMap::new(); - for (e, end) in ends.iter().enumerate() { - let m = metres_per_unit(end.at[1]); + // The chord vertex nearest a point, within `END_M`. + let nearest = |p: [f64; 2]| { + let m = metres_per_unit(p[1]); let gap = |c: usize, k: usize| { let v = vertex(&chords[c], k); - libm::hypot(v[0] - end.at[0], v[1] - end.at[1]) * m + libm::hypot(v[0] - p[0], v[1] - p[1]) * m }; - let nearest = + let near = (0..chords.len()).flat_map(|c| [(c, 0), (c, 1)]).min_by(|x, y| gap(x.0, x.1).total_cmp(&gap(y.0, y.1))); - if let Some((c, k)) = nearest.filter(|&(c, k)| gap(c, k) <= END_M) { - if built(&[Some(end.part)]) && built(&chords[c].ends) { - opening[e] = Some((c, k)); - end_at.insert((c, k), e); - } + near.filter(|&(c, k)| gap(c, k) <= END_M) + }; + let mut ends = inputs.to_vec(); + let mut mate = vec![None; ends.len()]; + for (e, end) in inputs.iter().enumerate() { + let Some(across) = end.mate.filter(|_| end.part == Part::Pair) else { continue }; + let (l, m) = (left_of(end.way_in()), metres_per_unit(end.at[1])); + let p = [end.at[0] + l[0] * across / m, end.at[1] + l[1] * across / m]; + let (Some((c, k)), Some(way), Some(shift)) = (nearest(p), end.mate_way, end.mate_shift) else { continue }; + let (chord, z) = (&chords[c], vertex(&chords[c], k)[2]); + mate[e] = Some(ends.len()); + mate.push(Some(e)); + // Its numbers over its own floor. + let up = |v: f64| v + end.z - z; + ends.push(End { + at: p, + z, + section: chord.section, + half: chord.half, + height: chord.height, + face: up(end.face), + left: end.left.iter().map(|&v| up(v)).collect(), + right: end.right.iter().map(|&v| up(v)).collect(), + foot: up(end.foot), + mate: Some(-across), + way, + shift, + mate_way: Some(end.way), + mate_shift: Some(end.shift), + ..end.clone() + }); + } + let mut opening: Vec> = (ends.iter()) + .map(|end| nearest(end.at).filter(|&(c, _)| built(&[Some(end.part)]) && built(&chords[c].ends))) + .collect(); + // A pair is built where both of its openings are. + for e in 0..ends.len() { + if mate[e].is_some_and(|m| opening[m].is_none()) || (ends[e].part == Part::Pair && mate[e].is_none()) { + opening[e] = None; } } - let mut net = Net { ends, chords, rules, at, opening, end_at, slope: vec![0.0; ends.len()] }; + let end_at = (0..ends.len()).filter_map(|e| opening[e].map(|o| (o, e))).collect(); + let n = ends.len(); + let mut net = Net { + ends, + chords, + rules, + inputs: inputs.len(), + mate, + at, + opening, + end_at, + slope: vec![0.0; n], + beside: vec![Vec::new(); chords.len()], + }; let run = rules.design.face_m; - net.slope = (0..ends.len()).map(|e| net.floor_at(e, run).map_or(0.0, |(s, z)| (z - ends[e].z) / s)).collect(); + net.slope = (0..n).map(|e| net.floor_at(e, run).map_or(0.0, |(s, z)| (z - net.ends[e].z) / s)).collect(); + let pairs: Vec<(usize, usize)> = + (0..net.inputs).filter(|&e| net.built_end(e)).filter_map(|e| net.mate[e].map(|m| (e, m))).collect(); + for (e, m) in pairs { + let tube = |e: usize| net.walk(e, f64::INFINITY).into_iter().map(|w| w.0).collect::>(); + let (a, b) = (tube(e), tube(m)); + for (one, other) in [(&a, &b), (&b, &a)] { + for &c in one { + let list = &mut net.beside[c]; + list.extend(other.iter().copied()); + list.sort_unstable(); + list.dedup(); + } + } + } net } @@ -190,33 +257,30 @@ impl<'a> Net<'a> { out } - /// The share of daylight at a world point: over the openings whose section over the tube's floor, grown by the shell - /// and a metre to each side, holds the point from the front of the head wall to `daylight_m` in, `1 − smoothstep(0, daylight_m, - /// m)` of the metres m in from the frame line, the largest; 0 with none. + /// The share of daylight at a world point: over the openings (not the closed ends) whose section over the tube's floor, grown by the shell + /// and a metre to each side, holds the point from the front of the head wall to `daylight_m` in, `1 − smoothstep(0, + /// daylight_m, m)` of the metres m in from the frame line, the largest; 0 with none. pub fn daylight(&self, p: [f64; 3]) -> f64 { let (shell, reach, front) = (self.rules.ladder.bake.shell_m, self.rules.design.daylight_m, self.rules.design.recess_m); let mut most: f64 = 0.0; - for (e, end) in self.ends.iter().enumerate() { + for (e, end) in self.ends.iter().enumerate().filter(|&(e, _)| !self.closed(e)) { let (d, m) = (end.way_in(), metres_per_unit(end.at[1])); let l = left_of(d); - let mates = [Some(0.0), end.mate]; - for q in mates.iter().flatten().map(|a| [end.at[0] + l[0] * a / m, end.at[1] + l[1] * a / m]) { - let (dx, dy) = (p[0] - q[0], p[1] - q[1]); - let (along, beside) = ((dx * d[0] + dy * d[1]) * m, (dx * l[0] + dy * l[1]) * m); - if beside.abs() > end.half + shell + 1.0 || along < -front || along > reach { - continue; - } - // Over the tube's floor at that metre; in front of the frame line, over the frame's. - let floor = if along > 0.0 { - self.floor_at(e, along).map_or(end.z, |f| f.1) - } else { - end.z + self.slope[e] * along - }; - if (end.foot..=end.height + shell).contains(&(p[2] - floor)) { - let t = (along / reach).clamp(0.0, 1.0); - most = most.max(1.0 - t * t * (3.0 - 2.0 * t)); - } + let (dx, dy) = (p[0] - end.at[0], p[1] - end.at[1]); + let (along, beside) = ((dx * d[0] + dy * d[1]) * m, (dx * l[0] + dy * l[1]) * m); + if beside.abs() > end.half + shell + 1.0 || along < -front || along > reach { + continue; + } + // Over the tube's floor at that metre; in front of the frame line, over the frame's. + let floor = if along > 0.0 { + self.floor_at(e, along).map_or(end.z, |f| f.1) + } else { + end.z + self.slope[e] * along + }; + if (end.foot..=end.height + shell).contains(&(p[2] - floor)) { + let t = (along / reach).clamp(0.0, 1.0); + most = most.max(1.0 - t * t * (3.0 - 2.0 * t)); } } most @@ -240,6 +304,48 @@ impl<'a> Net<'a> { pub fn opening(&self, e: usize) -> Option<(usize, usize)> { self.opening[e] } + + /// Whether end e is a free end covered at its opening: its tube ends in the hill there, with no opening. + pub fn closed(&self, e: usize) -> bool { + self.ends[e].part == Part::Free && self.ends[e].collar <= 0.0 + } + + /// Where a station across chord c meets the other tube of a pair: the middle between the walls of the two tubes on + /// the station's line, as far as their shells can reach; the nearest. + pub fn cut(&self, c: usize, st: &Station) -> Option { + let (own, shell) = (&self.chords[c], self.rules.ladder.bake.shell_m); + let mut best: Option = None; + for &o in &self.beside[c] { + let other = &self.chords[o]; + // The station's line meets the chord: st + x·across = a + u·(b − a). + let (dx, dy) = (other.b[0] - other.a[0], other.b[1] - other.a[1]); + let det = dx * st.ay - st.ax * dy; + if det.abs() < 1e-12 { + continue; + } + let (px, py) = (other.a[0] - st.x, other.a[1] - st.y); + let (x, u) = ((dx * py - dy * px) / det, (st.ax * py - st.ay * px) / det); + if !(-1e-9..=1.0 + 1e-9).contains(&u) || x.abs() > own.half + other.half + 2.0 * shell { + continue; + } + if best.is_none_or(|b| x.abs() < b.axis.abs()) { + let middle = (x + x.signum() * (own.half - other.half)) / 2.0; + let floor = other.a[2] + u * (other.b[2] - other.a[2]); + best = Some(Cut { x: middle, axis: x, other: o, floor }); + } + } + best + } + + /// The clip at the cuts of chord c at two stations across it: the plane through them that takes off the other tube's + /// side; None where either has none. + pub fn clip(&self, c: usize, (s, t): (&Station, &Station)) -> Option<(Clip, Cut, Cut)> { + let (cs, ct) = (self.cut(c, s)?, self.cut(c, t)?); + let (a, z) = (s.at([cs.x, 0.0]), t.at([ct.x, 0.0])); + let side = s.at([cs.axis, 0.0]); + let away = [side[0] - a[0], side[1] - a[1]]; + Some((Clip { a: [a[0], a[1]], b: [z[0], z[1]], away }, cs, ct)) + } } /// The floor of a tube across: per piece from the right, its metres across and the height of its top. A road or a @@ -291,6 +397,56 @@ pub fn inward(a: Corner, b: Corner, spring: f64) -> Corner { [-(a[0] + b[0]), -(a[1] + b[1] - 2.0 * spring)] } +/// Where a station meets the other tube of a pair (`Net::cut`): the metres across the station to the middle between their +/// walls, and the other tube there: its chord, the floor at that point (a world height) and its axis across the station. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Cut { + pub x: f64, + pub axis: f64, + pub other: usize, + pub floor: f64, +} + +/// The top of an outline at `x` across, the highest of its segments there; None outside it. +pub fn top_at(o: &[Corner], x: f64) -> Option { + let mut top: Option = None; + for w in o.windows(2) { + let (p, q) = (w[0], w[1]); + let (lo, hi) = (p[0].min(q[0]), p[0].max(q[0])); + if x < lo - 1e-9 || x > hi + 1e-9 { + continue; + } + let y = if hi - lo < 1e-12 { p[1].max(q[1]) } else { p[1] + (q[1] - p[1]) * (x - p[0]) / (q[0] - p[0]) }; + top = Some(top.map_or(y, |t: f64| t.max(y))); + } + top +} + +/// The face in the plane of a cut from station s to station t: at each, from the height `lo` up to `hi` at `x` across; +/// nothing where `hi` is not over `lo`. +pub fn cut_face f64>( + b: &mut Builder, + (s, t): (&Station, &Station), + at_s: (f64, f64, f64), + at_t: (f64, f64, f64), + colour: u32, + out: [f64; 3], +) { + let side = |(x, lo, hi): (f64, f64, f64)| [[x, lo], [x, hi.max(lo)]]; + if at_s.2 > at_s.1 + 1e-6 || at_t.2 > at_t.1 + 1e-6 { + b.strip((s, &side(at_s)), (t, &side(at_t)), colour, out); + } +} + +/// Where two spans at a cut differ: of the own span from `lo` to `hi`, the part under the other's span and the part over +/// it, each (lo, hi); the whole own span where the other has none. +pub fn steps((lo, hi): (f64, f64), other: Option<(f64, f64)>) -> [(f64, f64); 2] { + match other { + Some((olo, ohi)) => [(lo, olo.clamp(lo, hi)), (ohi.clamp(lo, hi), hi)], + None => [(lo, hi), (hi, hi)], + } +} + /// The corners of a wall from its foot to its spring at `x`, with the spring of a lower section that goes on at that /// ring between: the step face there meets the wall at it. fn wall_side(x: f64, foot: f64, spring: f64, lower: Option) -> Vec { @@ -313,6 +469,9 @@ pub fn inside f64>(b: &mut Builder, net: &Net, c: usize) { let sp = spring(net, chord.section, chord.height); let bore = |colour: u32| flagged(colour, BORE); let across = |c: Corner| s.mix(&t, 0.5).out(c); + // Of two tubes of a pair, each draws its side of the middle between their walls. + let cut = net.clip(c, (&s, &t)); + b.clip(cut.map(|c| c.0)); // A box section is cast: its rock bore is lined. let cast = chord.section == Section::Box; let (wall, vault) = match bore_of { @@ -369,9 +528,10 @@ pub fn inside f64>(b: &mut Builder, net: &Net, c: usize) { for k in 0..2 { step(b, net, c, k, &o, vault); } - // At an opening, the front of the floor goes down to the sill, `lift_m` under the floor. Each side of a piece has + // At an opening (not a closed end), the front of the floor goes down to the sill, `lift_m` under the floor. Each side of a piece has // a corner at the top of each piece beside it, which is the corner of a face there. - for (k, r) in [(0, &s), (1, &t)].into_iter().filter(|(k, _)| net.opening_at(c, *k)) { + let open = |k: usize| net.end_at(c, k).is_some_and(|e| !net.closed(e)); + for (k, r) in [(0, &s), (1, &t)].into_iter().filter(|(k, _)| open(*k)) { let out = flat(if k == 0 { [-d[0], -d[1]] } else { d }); for &(a0, a1, top) in &pieces { let side = |x: f64| { @@ -384,10 +544,34 @@ pub fn inside f64>(b: &mut Builder, net: &Net, c: usize) { b.strip((r, &side(a0)), (r, &side(a1)), bore(inside.walk), out); } } - if bore_of != Bore::Road { - return; + if bore_of == Bore::Road { + lamps(b, net, c, (&s, &t)); } - // A lamp under the crown where the metres along pass a multiple of the spacing. + b.clip(None); + // At the cut, a face closes the room where the other tube's floor is higher or its roof lower. + let Some((_, cs, ct)) = cut else { return }; + let span = |st: &Station, cut: &Cut| { + let f = |p: &[(f64, f64, f64)], x: f64| p.iter().find(|q| x >= q.0 - 1e-9 && x <= q.1 + 1e-9).map(|q| q.2); + let own = f(&pieces, cut.x).zip(top_at(&o, cut.x))?; + let other = &net.chords[cut.other]; + let mut oo = inside_outline(net, other); + let (op, m) = (floor_pieces(net, other), oo.len() - 1); + (oo[0][1], oo[m][1]) = (op[0].2, op[op.len() - 1].2); + let (xl, df) = (cut.x - cut.axis, cut.floor - st.z); + Some(steps(own, f(&op, xl).zip(top_at(&oo, xl)).map(|(lo, hi)| (lo + df, hi + df)))) + }; + if let (Some([ls, us]), Some([lt, ut])) = (span(&s, &cs), span(&t, &ct)) { + let out = across([-cs.axis.signum(), 0.0]); + cut_face(b, (&s, &t), (cs.x, ls.0, ls.1), (ct.x, lt.0, lt.1), bore(inside.walk), out); + cut_face(b, (&s, &t), (cs.x, us.0, us.1), (ct.x, ut.0, ut.1), bore(vault), out); + } +} + +/// The lamps of chord c of a road bore, from ring s to ring t: one under the crown where the metres along pass a multiple +/// of the spacing. +fn lamps f64>(b: &mut Builder, net: &Net, c: usize, (s, t): (&Station, &Station)) { + let (chord, design, inside) = (&net.chords[c], &net.rules.design, &net.rules.inside); + let length = direction(chord).1; let mut at = (chord.along / design.lamp_spacing_m).ceil() * design.lamp_spacing_m; while at < chord.along + length { let m = at - chord.along; @@ -428,14 +612,18 @@ pub struct Meets { pub lower: Option<(f64, Section)>, } -/// The outer shell of a run of pieces, each its start and end station and its chord's height and section, with the -/// inside half-width `half`; its walls go down to the world height `foot`. Where two pieces of different height meet, -/// a face closes the step, facing the lower one; so too after the last piece where a lower shell goes on (`meets`). -/// There the walls have a corner at the foot of the shell that goes on. +/// A piece of a run of shell: its start and end station, its chord's height and section, and the chord. +pub type Run = (Station, Station, f64, Section, usize); + +/// The outer shell of a run of pieces, with the inside half-width `half`; its walls go down to the world height `foot`. +/// Where two pieces of different height meet, a face closes the step, facing the lower one; so too after the last piece +/// where a lower shell goes on (`meets`). There the walls have a corner at the foot of the shell that goes on. Of two +/// tubes of a pair, each draws its side of the middle between their walls, and a face closes the step where its shell is +/// the higher there. pub fn shell f64>( b: &mut Builder, net: &Net, - pieces: &[(Station, Station, f64, Section)], + pieces: &[Run], half: f64, foot: f64, colour: u32, @@ -444,7 +632,22 @@ pub fn shell f64>( let last = |i: usize| i + 1 == pieces.len(); let next_of = |i: usize| pieces.get(i + 1).map(|p| (p.2, p.3)).or(meets.lower.filter(|_| last(i))); let outer = |st: &Station, h: f64, section: Section| shell_outline(net, section, half, h, foot - st.z); - for (i, (s, t, h, section)) in pieces.iter().enumerate() { + for (i, &(ref s, ref t, ref h, ref section, c)) in pieces.iter().enumerate() { + let cut = net.clip(c, (s, t)); + b.clip(cut.map(|c| c.0)); + if let Some((_, cs, ct)) = cut { + // The other tube's shell top at the cut, over this station's floor. + let top = |st: &Station, cut: &Cut| { + let own = top_at(&outer(st, *h, *section), cut.x)?; + let other = &net.chords[cut.other]; + let o = shell_outline(net, other.section, other.half, other.height, foot - cut.floor); + Some((own, top_at(&o, cut.x - cut.axis)? + cut.floor - st.z)) + }; + if let (Some((os, xs)), Some((ot, xt))) = (top(s, &cs), top(t, &ct)) { + let out = s.mix(t, 0.5).out([cs.axis.signum(), 0.0]); + cut_face(b, (s, t), (cs.x, xs.min(os), os), (ct.x, xt.min(ot), ot), colour, out); + } + } let (sp, top) = (spring(net, *section, *h), shell_spring(net, *section, *h)); let (os, ot) = (outer(s, *h, *section), outer(t, *h, *section)); let n = os.len(); @@ -481,6 +684,7 @@ pub fn shell f64>( b.strip((t, &tall[j..j + 2]), (t, &low[j..j + 2]), colour, toward); } } + b.clip(None); } #[cfg(test)] From 21f4cac395726c1a25dbc634a1977b141d666cd8 Mon Sep 17 00:00:00 2001 From: timohueser Date: Sat, 21 Nov 2026 19:13:14 +0100 Subject: [PATCH 03/20] data-steps: features revision 36 Co-Authored-By: Claude Opus 5.5 --- host/obc-data-steps/src/planner.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/host/obc-data-steps/src/planner.rs b/host/obc-data-steps/src/planner.rs index a31e1dd22..2e1c6d5dd 100644 --- a/host/obc-data-steps/src/planner.rs +++ b/host/obc-data-steps/src/planner.rs @@ -71,7 +71,7 @@ pub static PLANNER_SNOW: Layer = whole("planner/snow", 2, &[&WEB_PLANNER]); /// holds what the stamp worker makes of the tiles; `stamp_version` of `specs/trailview-tiles.md` says /// which stamp code made it. pub static PLANNER_TRAILVIEW_FEATURES: Layer = - Layer { revision: 35, ..whole("planner/trailview-features", 4, &[&WEB_PLANNER]) }; + Layer { revision: 36, ..whole("planner/trailview-features", 4, &[&WEB_PLANNER]) }; /// The TrailView ruleset, `rules.json` of `specs/trailview-tiles.md`. Its format is `format` of /// `rules.json`, `FORMAT` of `tools/trailview/rules.py`. pub static PLANNER_TRAILVIEW_RULES: Layer = From 32d6d759ef4e32a63580e21713a87166c2abb4f9 Mon Sep 17 00:00:00 2001 From: timohueser Date: Sat, 21 Nov 2026 19:27:50 +0100 Subject: [PATCH 04/20] trailview-parts: two built tubes whose shells overlap meet at the middle between their walls, with no gap A tube finds the other by its cells, not by the record of its pair, so a tube in a tile with no record of its pair ends at the middle too. A station a metre past a chord still meets it, as the two openings of a pair lie on their frame line within the rounding of the record. Where one ring of a chord meets the other tube, the plane runs along the chord. Each tube runs 5 cm past the middle, as its vertices are rounded to world units. Co-Authored-By: Claude Opus 5.5 --- host/obc-trailview-parts/src/arch.rs | 1 + host/obc-trailview-parts/src/tube.rs | 115 +++++++++++++++++++-------- 2 files changed, 83 insertions(+), 33 deletions(-) diff --git a/host/obc-trailview-parts/src/arch.rs b/host/obc-trailview-parts/src/arch.rs index 1f9e772fc..460220226 100644 --- a/host/obc-trailview-parts/src/arch.rs +++ b/host/obc-trailview-parts/src/arch.rs @@ -149,6 +149,7 @@ pub fn faces f64>(b: &mut Builder, net: &Net, e: usize) { let (h, section) = shell.first().map_or((chord.height, chord.section), |p| (p.2, p.3)); let cut = pair_cut(net, e); b.clip(cut.map(|(x, side)| { + let x = x + side * tube::OVERLAP_M; let (p, q, r) = (front.at([x, 0.0]), back.at([x, 0.0]), front.at([x + side, 0.0])); Clip { a: [p[0], p[1]], b: [q[0], q[1]], away: [r[0] - p[0], r[1] - p[1]] } })); diff --git a/host/obc-trailview-parts/src/tube.rs b/host/obc-trailview-parts/src/tube.rs index 3b7618f0b..f63129375 100644 --- a/host/obc-trailview-parts/src/tube.rs +++ b/host/obc-trailview-parts/src/tube.rs @@ -39,8 +39,6 @@ pub struct Net<'a> { pub ends: Vec, pub chords: &'a [Chord], pub rules: &'a Rules, - /// The count of the input's ends. - inputs: usize, /// Per end, the other end of its pair. pub mate: Vec>, at: HashMap<[u64; 2], Vec>, @@ -50,10 +48,19 @@ pub struct Net<'a> { end_at: HashMap<(usize, usize), usize>, /// Per end, the rise of its floor per metre in, over its first `face_m`. slope: Vec, - /// Per chord, the chords of the other tube of a pair at an end of its chain. - beside: Vec>, + /// Per chord, its tube: the chords that its vertices join. + tube: Vec, + /// The built chords by the cells (`CELL_M`) that they come within reach of. + cells: HashMap<[i64; 2], Vec>, + /// The world units of a cell. + cell: f64, } +/// The side of a cell of `Net::cells`, in metres. +const CELL_M: f64 = 16.0; +/// Two tubes that meet at a cut each run this far past it: two world units, as each vertex is rounded to one. +pub const OVERLAP_M: f64 = 0.05; + impl<'a> Net<'a> { pub fn new(inputs: &[End], chords: &'a [Chord], rules: &'a Rules) -> Net<'a> { let mut at: HashMap<[u64; 2], Vec> = HashMap::new(); @@ -118,27 +125,47 @@ impl<'a> Net<'a> { ends, chords, rules, - inputs: inputs.len(), mate, at, opening, end_at, slope: vec![0.0; n], - beside: vec![Vec::new(); chords.len()], + tube: Vec::new(), + cells: HashMap::new(), + cell: 1.0, }; let run = rules.design.face_m; net.slope = (0..n).map(|e| net.floor_at(e, run).map_or(0.0, |(s, z)| (z - net.ends[e].z) / s)).collect(); - let pairs: Vec<(usize, usize)> = - (0..net.inputs).filter(|&e| net.built_end(e)).filter_map(|e| net.mate[e].map(|m| (e, m))).collect(); - for (e, m) in pairs { - let tube = |e: usize| net.walk(e, f64::INFINITY).into_iter().map(|w| w.0).collect::>(); - let (a, b) = (tube(e), tube(m)); - for (one, other) in [(&a, &b), (&b, &a)] { - for &c in one { - let list = &mut net.beside[c]; - list.extend(other.iter().copied()); - list.sort_unstable(); - list.dedup(); + // The tubes: each chord takes the least tube of the chords at its vertices, until none changes. + net.tube = (0..chords.len()).collect(); + loop { + let mut changed = false; + for list in net.at.values() { + let least = list.iter().map(|&c| net.tube[c]).min().unwrap_or(0); + for &c in list { + if net.tube[c] != least { + (net.tube[c], changed) = (least, true); + } + } + } + if !changed { + break; + } + } + // The cells of the built chords, each grown by the farthest reach of a cut. + if let Some(first) = chords.first() { + net.cell = CELL_M / metres_per_unit(first.a[1]); + let shell = rules.ladder.bake.shell_m; + let reach = 2.0 * chords.iter().map(|c| c.half + shell).fold(0.0, f64::max) / metres_per_unit(first.a[1]); + let cell = net.cell; + let at = |v: f64| libm::floor(v / cell) as i64; + for (c, chord) in chords.iter().enumerate().filter(|&(c, _)| built(&chords[c].ends)) { + let lo = [chord.a[0].min(chord.b[0]) - reach, chord.a[1].min(chord.b[1]) - reach]; + let hi = [chord.a[0].max(chord.b[0]) + reach, chord.a[1].max(chord.b[1]) + reach]; + for x in at(lo[0])..=at(hi[0]) { + for y in at(lo[1])..=at(hi[1]) { + net.cells.entry([x, y]).or_default().push(c); + } } } } @@ -310,12 +337,14 @@ impl<'a> Net<'a> { self.ends[e].part == Part::Free && self.ends[e].collar <= 0.0 } - /// Where a station across chord c meets the other tube of a pair: the middle between the walls of the two tubes on - /// the station's line, as far as their shells can reach; the nearest. + /// Where a station across chord c meets another built tube whose shell overlaps its own there: the middle between + /// their walls on the station's line; the nearest. A tube that lies over or under it by more than half their heights + /// does not meet it. pub fn cut(&self, c: usize, st: &Station) -> Option { let (own, shell) = (&self.chords[c], self.rules.ladder.bake.shell_m); + let key = [libm::floor(st.x / self.cell) as i64, libm::floor(st.y / self.cell) as i64]; let mut best: Option = None; - for &o in &self.beside[c] { + for &o in self.cells.get(&key).into_iter().flatten().filter(|&&o| self.tube[o] != self.tube[c]) { let other = &self.chords[o]; // The station's line meets the chord: st + x·across = a + u·(b − a). let (dx, dy) = (other.b[0] - other.a[0], other.b[1] - other.a[1]); @@ -325,26 +354,46 @@ impl<'a> Net<'a> { } let (px, py) = (other.a[0] - st.x, other.a[1] - st.y); let (x, u) = ((dx * py - dy * px) / det, (st.ax * py - st.ay * px) / det); - if !(-1e-9..=1.0 + 1e-9).contains(&u) || x.abs() > own.half + other.half + 2.0 * shell { + // A metre past either vertex still counts: the two openings of a pair lie on their frame line within the + // rounding of the record. + let past = 1.0 / direction(other).1.max(1.0); + let floor = other.a[2] + u * (other.b[2] - other.a[2]); + if !(-past..=1.0 + past).contains(&u) + || x.abs() > own.half + other.half + 2.0 * shell + || (floor - st.z).abs() > (own.height + other.height) / 2.0 + { continue; } if best.is_none_or(|b| x.abs() < b.axis.abs()) { let middle = (x + x.signum() * (own.half - other.half)) / 2.0; - let floor = other.a[2] + u * (other.b[2] - other.a[2]); best = Some(Cut { x: middle, axis: x, other: o, floor }); } } best } - /// The clip at the cuts of chord c at two stations across it: the plane through them that takes off the other tube's - /// side; None where either has none. - pub fn clip(&self, c: usize, (s, t): (&Station, &Station)) -> Option<(Clip, Cut, Cut)> { - let (cs, ct) = (self.cut(c, s)?, self.cut(c, t)?); - let (a, z) = (s.at([cs.x, 0.0]), t.at([ct.x, 0.0])); - let side = s.at([cs.axis, 0.0]); - let away = [side[0] - a[0], side[1] - a[1]]; - Some((Clip { a: [a[0], a[1]], b: [z[0], z[1]], away }, cs, ct)) + /// The clip of chord c from station s to t at its cuts: the plane through them that takes off the other tube's + /// side, and the cuts; where one station has none, the plane through the other's along the chord. + pub fn clip(&self, c: usize, (s, t): (&Station, &Station)) -> Option<(Clip, Option, Option)> { + let (cs, ct) = (self.cut(c, s), self.cut(c, t)); + let (a, z, cut) = match (cs, ct) { + (Some(x), Some(y)) => (s.at([x.x, 0.0]), t.at([y.x, 0.0]), x), + (Some(x), None) => { + (s.at([x.x, 0.0]), [s.at([x.x, 0.0])[0] + t.x - s.x, s.at([x.x, 0.0])[1] + t.y - s.y, 0.0], x) + } + (None, Some(y)) => { + (t.at([y.x, 0.0]), [t.at([y.x, 0.0])[0] + t.x - s.x, t.at([y.x, 0.0])[1] + t.y - s.y, 0.0], y) + } + (None, None) => return None, + }; + let st = if cs.is_some() { s } else { t }; + let (far, near) = (st.at([cut.axis, 0.0]), st.at([cut.x, 0.0])); + let away = [far[0] - near[0], far[1] - near[1]]; + // The two tubes overlap by `OVERLAP_M` at the plane, so the rounding of their vertices opens no gap there. + let l = libm::hypot(away[0], away[1]).max(f64::MIN_POSITIVE); + let d = OVERLAP_M / metres_per_unit(st.y) / l; + let (a, z) = ([a[0] + away[0] * d, a[1] + away[1] * d], [z[0] + away[0] * d, z[1] + away[1] * d]); + Some((Clip { a, b: z, away }, cs, ct)) } } @@ -549,7 +598,7 @@ pub fn inside f64>(b: &mut Builder, net: &Net, c: usize) { } b.clip(None); // At the cut, a face closes the room where the other tube's floor is higher or its roof lower. - let Some((_, cs, ct)) = cut else { return }; + let Some((_, Some(cs), Some(ct))) = cut else { return }; let span = |st: &Station, cut: &Cut| { let f = |p: &[(f64, f64, f64)], x: f64| p.iter().find(|q| x >= q.0 - 1e-9 && x <= q.1 + 1e-9).map(|q| q.2); let own = f(&pieces, cut.x).zip(top_at(&o, cut.x))?; @@ -576,7 +625,7 @@ fn lamps f64>(b: &mut Builder, net: &Net, c: usize, (s, t) while at < chord.along + length { let m = at - chord.along; let (p, q) = (((m - design.lamp_m / 2.0) / length).max(0.0), ((m + design.lamp_m / 2.0) / length).min(1.0)); - let (sp, sq) = (s.mix(&t, p), s.mix(&t, q)); + let (sp, sq) = (s.mix(t, p), s.mix(t, q)); let up = chord.height - LAMP_DROP_M; let light = flagged(inside.lamp, LAMP); let v = [ @@ -635,7 +684,7 @@ pub fn shell f64>( for (i, &(ref s, ref t, ref h, ref section, c)) in pieces.iter().enumerate() { let cut = net.clip(c, (s, t)); b.clip(cut.map(|c| c.0)); - if let Some((_, cs, ct)) = cut { + if let Some((_, Some(cs), Some(ct))) = cut { // The other tube's shell top at the cut, over this station's floor. let top = |st: &Station, cut: &Cut| { let own = top_at(&outer(st, *h, *section), cut.x)?; From ff27de6a7b9941a71341809b3026395a9dfa9fcd Mon Sep 17 00:00:00 2001 From: timohueser Date: Sat, 21 Nov 2026 19:30:21 +0100 Subject: [PATCH 05/20] trailview-parts: a head ends at the middle between its tube and a near opening that leads the same way Not only the head of a pair: two built ends that are no pair, whose axes pass within reach of a head, and that lead the same way within pair_max_m and pair_max_deg at one level, end their heads at the middle between their walls. So two underpasses, two arches or a free end beside an arch side by side do not stand in each other's openings. Co-Authored-By: Claude Opus 5.5 --- host/obc-trailview-parts/src/arch.rs | 50 +++++++++++++++++++-------- host/obc-trailview-parts/src/tests.rs | 25 +++++++++++--- 2 files changed, 55 insertions(+), 20 deletions(-) diff --git a/host/obc-trailview-parts/src/arch.rs b/host/obc-trailview-parts/src/arch.rs index 460220226..38470aeb7 100644 --- a/host/obc-trailview-parts/src/arch.rs +++ b/host/obc-trailview-parts/src/arch.rs @@ -42,10 +42,10 @@ fn rim(net: &Net, e: usize) -> bool { /// pair. fn edges(net: &Net, e: usize) -> (f64, f64) { let shell = net.rules.ladder.bake.shell_m; - let edge = half(net, e) + shell; + let edge = half_at(net, e) + shell; match (net.mate[e], net.ends[e].mate) { (Some(m), Some(a)) => { - let other = half(net, m) + shell; + let other = half_at(net, m) + shell; ((-edge).min(a - other), edge.max(a + other)) } _ => (-edge, edge), @@ -53,7 +53,7 @@ fn edges(net: &Net, e: usize) -> (f64, f64) { } /// The inside half-width of end e's tube at its opening. -fn half(net: &Net, e: usize) -> f64 { +fn half_at(net: &Net, e: usize) -> f64 { net.opening(e).map_or(net.ends[e].half, |(c, _)| net.chords[c].half) } @@ -62,7 +62,7 @@ fn rim_outline(net: &Net, e: usize) -> Vec { let (end, design) = (&net.ends[e], &net.rules.design); let grow = design.frame_m + net.rules.ladder.bake.shell_m; let sp = spring(net, end.section, end.height); - outline(end.section, half(net, e) + grow, end.height + grow, sp, design.arch_segments) + outline(end.section, half_at(net, e) + grow, end.height + grow, sp, design.arch_segments) } /// The metres to the left of end e's axis of the two ends of its head: of its rim, or of its head wall with its wings. @@ -114,11 +114,30 @@ fn grown(net: &Net, e: usize, grow: f64) -> Vec { out } -/// The cut of a pair at end e's frame line: the metres to the left of its axis of the middle between its tube's wall and -/// the mate's, and the side of the mate (1 to the left). -fn pair_cut(net: &Net, e: usize) -> Option<(f64, f64)> { - let (m, a) = (net.mate[e]?, net.ends[e].mate?); - Some(((a + a.signum() * (half(net, e) - half(net, m))) / 2.0, a.signum())) +/// Where end e's head ends at another opening near it: the metres to the left of its axis of the middle between its +/// tube's wall and the other's, the side of the other (1 to the left), the other end, and whether the two lie on one +/// frame line. The other is the mate of a pair, or else the nearest built end that leads the same way within +/// `pair_max_m` and `pair_max_deg`, at its floor's height, whose axis passes within reach of e's head. +fn head_cut(net: &Net, e: usize) -> Option<(f64, f64, usize, bool)> { + let middle = |a: f64, m: usize| (a + a.signum() * (half_at(net, e) - half_at(net, m))) / 2.0; + if let (Some(m), Some(a)) = (net.mate[e], net.ends[e].mate) { + return Some((middle(a, m), a.signum(), m, true)); + } + let (end, bake) = (&net.ends[e], &net.rules.ladder.bake); + let (into, k) = (end.way_in(), crate::metres_per_unit(end.at[1])); + let left = crate::mesh::left_of(into); + let (right_end, left_end) = wide(net, e); + let near = (0..net.ends.len()).filter(|&m| m != e && net.built_end(m) && !net.closed(m)).filter_map(|m| { + let other = &net.ends[m]; + let (d, o) = (other.way_in(), [(other.at[0] - end.at[0]) * k, (other.at[1] - end.at[1]) * k]); + let (along, across) = (o[0] * into[0] + o[1] * into[1], o[0] * left[0] + o[1] * left[1]); + let reach = if across > 0.0 { left_end } else { -right_end } + half_at(net, m) + bake.shell_m; + let same_way = d[0] * into[0] + d[1] * into[1] >= libm::cos(bake.pair_max_deg.to_radians()); + let level = (other.z - end.z).abs() <= (end.height + other.height) / 2.0; + (same_way && level && along.abs() <= bake.pair_max_m && across.abs() < reach).then_some((m, along, across)) + }); + let (m, along, a) = near.min_by(|x, y| x.2.abs().total_cmp(&y.2.abs()))?; + Some((middle(a, m), a.signum(), m, along.abs() < 0.5)) } /// The faces of the head at end e: its head wall or rim, the sill, the reveal and the frame round the opening, the dark @@ -147,8 +166,8 @@ pub fn faces f64>(b: &mut Builder, net: &Net, e: usize) { let (front, ring, back) = (net.frame(e, -design.recess_m), net.frame(e, 0.0), net.frame(e, design.face_m - design.recess_m)); let (h, section) = shell.first().map_or((chord.height, chord.section), |p| (p.2, p.3)); - let cut = pair_cut(net, e); - b.clip(cut.map(|(x, side)| { + let cut = head_cut(net, e); + b.clip(cut.map(|(x, side, ..)| { let x = x + side * tube::OVERLAP_M; let (p, q, r) = (front.at([x, 0.0]), back.at([x, 0.0]), front.at([x + side, 0.0])); Clip { a: [p[0], p[1]], b: [q[0], q[1]], away: [r[0] - p[0], r[1] - p[1]] } @@ -206,14 +225,15 @@ pub fn faces f64>(b: &mut Builder, net: &Net, e: usize) { b.triangle(centre, rim_v[k], rim_v[(k + 1) % rim_v.len()], outward); } b.clip(None); - // Where the two holes of a pair differ at the middle, the reveal closes the step, from the front to the frame - // line: under the higher sill and over the lower top. - if let (Some((x, side)), Some(m)) = (cut, net.mate[e]) { + // Where two holes on one frame line differ at the middle, the reveal closes the step, from the front to the + // frame line: under the higher sill and over the lower top. + if let Some((x, side, m, true)) = cut { let other = grown(net, m, design.frame_m); + let a = 2.0 * x - side * (half - half_at(net, m)); let span = |st: &Station, s: f64| { let df = net.frame(m, s).z - st.z; let own = (sill, top_at(&hole, x)?); - let them = top_at(&other, x - net.ends[e].mate?).map(|t| (sill + df, t + df)); + let them = top_at(&other, x - a).map(|t| (sill + df, t + df)); Some(steps(own, them)) }; if let (Some(a), Some(z)) = (span(&front, -design.recess_m), span(&ring, 0.0)) { diff --git a/host/obc-trailview-parts/src/tests.rs b/host/obc-trailview-parts/src/tests.rs index 0cfc33d18..2c53f2ea5 100644 --- a/host/obc-trailview-parts/src/tests.rs +++ b/host/obc-trailview-parts/src/tests.rs @@ -681,6 +681,20 @@ fn pair(apart: f64, dz: f64) -> (Vec, Vec) { (ends, chords) } +/// The two road tubes of `pair` as four arches: no end has a mate. +fn side_by_side(apart: f64) -> (Vec, Vec) { + let (mut ends, mut chords) = pair(apart, 0.0); + let pi = std::f64::consts::PI; + ends.extend([end(0.0, apart, 500.0, 0.0, 6.0), end(40.0, apart, 500.2, pi, 3.0)]); + for e in &mut ends { + (e.part, e.mate, e.mate_way, e.mate_shift) = (Part::Arch, None, None, None); + } + for c in &mut chords { + c.ends = [Some(Part::Arch); 2]; + } + (ends, chords) +} + /// The triangles of a mesh in metres east, north and up, but the dark faces of the openings and the lamps. fn solid(mesh: &Mesh) -> Vec<[[f64; 3]; 3]> { let point = |i: u32| { @@ -724,14 +738,15 @@ fn hit(faces: &[[[f64; 3]; 3]], o: [f64; 3], d: [f64; 3], far: f64) -> Option<(f } #[test] -fn the_two_tubes_of_a_pair_are_one_room_and_one_head_wall() { +fn the_two_tubes_of_a_pair_are_one_room_and_one_head_wall_and_two_near_heads_end_between() { let rules = Rules::embedded(); let frame = rules.design.frame_m; // Tubes 7 m apart, 4.5 m wide each: their rooms overlap by 2 m, so they are cut in the middle; with the second's - // floor 0.8 m higher, faces close the steps there. Tubes 10.5 m apart do not overlap. - for (apart, dz) in [(7.0, 0.0), (7.0, 0.8), (10.5, 0.0)] { - let name = format!("{apart} m apart, {dz} m higher"); - let (ends, chords) = pair(apart, dz); + // floor 0.8 m higher, faces close the steps there. Tubes 10.5 m apart do not overlap. Two arches that are no pair + // end their head walls at the middle too. + for (apart, dz, paired) in [(7.0, 0.0, true), (7.0, 0.8, true), (10.5, 0.0, true), (10.5, 0.0, false)] { + let name = format!("{apart} m apart, {dz} m higher, a pair: {paired}"); + let (ends, chords) = if paired { pair(apart, dz) } else { side_by_side(apart) }; let (room, box_points) = boxes_fit(&name, &ends, &chords); assert!(room > 200 && box_points > 100, "{name}: {room} room samples, {box_points} box samples"); let mesh = meshes([0.0, 0.0, 1.07e9, 1.07e9], &ends, &chords, rules); From ebac942888eaea571c40a73bb76242ae8051e4df Mon Sep 17 00:00:00 2001 From: timohueser Date: Sat, 21 Nov 2026 19:42:01 +0100 Subject: [PATCH 06/20] trailview-parts: a tube and a head end at the meeting with a near tube on each side, not only the nearest A tube between two others ends at the middle on each side, and so does a head with a near opening on each side: the mate of a pair on its side, else the nearest one that leads the same way. The mesh builder clips by several planes. Co-Authored-By: Claude Opus 5.5 --- host/obc-trailview-parts/src/arch.rs | 52 +++++++++------ host/obc-trailview-parts/src/mesh.rs | 68 +++++++++---------- host/obc-trailview-parts/src/tests.rs | 93 +++++++++++++++----------- host/obc-trailview-parts/src/tube.rs | 94 +++++++++++++++------------ 4 files changed, 172 insertions(+), 135 deletions(-) diff --git a/host/obc-trailview-parts/src/arch.rs b/host/obc-trailview-parts/src/arch.rs index 38470aeb7..8bff63d60 100644 --- a/host/obc-trailview-parts/src/arch.rs +++ b/host/obc-trailview-parts/src/arch.rs @@ -114,15 +114,12 @@ fn grown(net: &Net, e: usize, grow: f64) -> Vec { out } -/// Where end e's head ends at another opening near it: the metres to the left of its axis of the middle between its -/// tube's wall and the other's, the side of the other (1 to the left), the other end, and whether the two lie on one -/// frame line. The other is the mate of a pair, or else the nearest built end that leads the same way within +/// Where end e's head ends at the openings near it, on each side at most one: the metres to the left of its axis of the +/// middle between its tube's wall and the other's, the side of the other (1 to the left), the other end, and whether the +/// two lie on one frame line. On its side, the mate of a pair; else the nearest built end that leads the same way within /// `pair_max_m` and `pair_max_deg`, at its floor's height, whose axis passes within reach of e's head. -fn head_cut(net: &Net, e: usize) -> Option<(f64, f64, usize, bool)> { +fn head_cuts(net: &Net, e: usize) -> Vec<(f64, f64, usize, bool)> { let middle = |a: f64, m: usize| (a + a.signum() * (half_at(net, e) - half_at(net, m))) / 2.0; - if let (Some(m), Some(a)) = (net.mate[e], net.ends[e].mate) { - return Some((middle(a, m), a.signum(), m, true)); - } let (end, bake) = (&net.ends[e], &net.rules.ladder.bake); let (into, k) = (end.way_in(), crate::metres_per_unit(end.at[1])); let left = crate::mesh::left_of(into); @@ -131,13 +128,24 @@ fn head_cut(net: &Net, e: usize) -> Option<(f64, f64, usize, bool)> { let other = &net.ends[m]; let (d, o) = (other.way_in(), [(other.at[0] - end.at[0]) * k, (other.at[1] - end.at[1]) * k]); let (along, across) = (o[0] * into[0] + o[1] * into[1], o[0] * left[0] + o[1] * left[1]); + if net.mate[e] == Some(m) { + return end.mate.map(|a| (m, 0.0, a, true)); + } let reach = if across > 0.0 { left_end } else { -right_end } + half_at(net, m) + bake.shell_m; let same_way = d[0] * into[0] + d[1] * into[1] >= libm::cos(bake.pair_max_deg.to_radians()); let level = (other.z - end.z).abs() <= (end.height + other.height) / 2.0; - (same_way && level && along.abs() <= bake.pair_max_m && across.abs() < reach).then_some((m, along, across)) + (same_way && level && along.abs() <= bake.pair_max_m && across.abs() < reach) + .then_some((m, along, across, false)) }); - let (m, along, a) = near.min_by(|x, y| x.2.abs().total_cmp(&y.2.abs()))?; - Some((middle(a, m), a.signum(), m, along.abs() < 0.5)) + let mut sides: [Option<(usize, f64, f64, bool)>; 2] = [None, None]; + for n in near { + let side = &mut sides[usize::from(n.2 > 0.0)]; + // The mate first, then the nearest across. + if side.is_none_or(|s| !s.3 && (n.3 || n.2.abs() < s.2.abs())) { + *side = Some(n); + } + } + sides.into_iter().flatten().map(|(m, along, a, _)| (middle(a, m), a.signum(), m, along.abs() < 0.5)).collect() } /// The faces of the head at end e: its head wall or rim, the sill, the reveal and the frame round the opening, the dark @@ -166,12 +174,16 @@ pub fn faces f64>(b: &mut Builder, net: &Net, e: usize) { let (front, ring, back) = (net.frame(e, -design.recess_m), net.frame(e, 0.0), net.frame(e, design.face_m - design.recess_m)); let (h, section) = shell.first().map_or((chord.height, chord.section), |p| (p.2, p.3)); - let cut = head_cut(net, e); - b.clip(cut.map(|(x, side, ..)| { - let x = x + side * tube::OVERLAP_M; - let (p, q, r) = (front.at([x, 0.0]), back.at([x, 0.0]), front.at([x + side, 0.0])); - Clip { a: [p[0], p[1]], b: [q[0], q[1]], away: [r[0] - p[0], r[1] - p[1]] } - })); + let cuts = head_cuts(net, e); + b.clip( + (cuts.iter()) + .map(|&(x, side, ..)| { + let x = x + side * tube::OVERLAP_M; + let (p, q, r) = (front.at([x, 0.0]), back.at([x, 0.0]), front.at([x + side, 0.0])); + Clip { a: [p[0], p[1]], b: [q[0], q[1]], away: [r[0] - p[0], r[1] - p[1]] } + }) + .collect(), + ); let wide = wide(net, e); let (rim, edges) = (rim(net, e), edges(net, e)); let rim_line = rim_outline(net, e); @@ -224,10 +236,10 @@ pub fn faces f64>(b: &mut Builder, net: &Net, e: usize) { for k in 0..rim_v.len() { b.triangle(centre, rim_v[k], rim_v[(k + 1) % rim_v.len()], outward); } - b.clip(None); + b.clip(Vec::new()); // Where two holes on one frame line differ at the middle, the reveal closes the step, from the front to the // frame line: under the higher sill and over the lower top. - if let Some((x, side, m, true)) = cut { + for &(x, side, m, _) in cuts.iter().filter(|c| c.3) { let other = grown(net, m, design.frame_m); let a = 2.0 * x - side * (half - half_at(net, m)); let span = |st: &Station, s: f64| { @@ -253,9 +265,9 @@ pub fn faces f64>(b: &mut Builder, net: &Net, e: usize) { let run: Vec<_> = shell.iter().map(|p| (p.0, p.1, p.2, p.3, p.4)).collect(); tube::shell(b, net, &run, half, foot, look.shell, reach.then); if let Some(&(s, t, _, _, c, k)) = shell.last().filter(|_| reach.closed) { - b.clip(net.clip(c, (&s, &t)).map(|c| c.0)); + b.clip(net.clips(c, (&s, &t)).iter().map(|c| c.0).collect()); end_face(b, net, (c, k), &t, foot, look.shell, flat([t.x - s.x, t.y - s.y])); - b.clip(None); + b.clip(Vec::new()); } } diff --git a/host/obc-trailview-parts/src/mesh.rs b/host/obc-trailview-parts/src/mesh.rs index 892aed03a..853313c71 100644 --- a/host/obc-trailview-parts/src/mesh.rs +++ b/host/obc-trailview-parts/src/mesh.rs @@ -121,16 +121,16 @@ impl Clip { } /// Collects faces. Each face is wound counter-clockwise seen from the side that `out` points to (east, north, up), -/// so the back faces cull. With a clip, the part of a face past its plane is not drawn. +/// so the back faces cull. The part of a face past the plane of a clip is not drawn. pub struct Builder f64> { words: Vec, indices: Vec, points: Vec<[f64; 3]>, looks: Vec<(u32, Paint)>, daylight: L, - clip: Option, - /// The vertex where the clip's plane cuts the edge between two vertices. - cuts: HashMap<(u32, u32), u32>, + clips: Vec, + /// The vertex where the plane of a clip cuts the edge between two vertices. + cuts: HashMap<(usize, u32, u32), u32>, } impl f64> Builder { @@ -142,15 +142,15 @@ impl f64> Builder { points: Vec::new(), looks: Vec::new(), daylight, - clip: None, + clips: Vec::new(), cuts: HashMap::new(), } } - /// The clip of the faces from now on. - pub fn clip(&mut self, clip: Option) { - if clip != self.clip { - (self.clip, self.cuts) = (clip, HashMap::new()); + /// The clips of the faces from now on. + pub fn clip(&mut self, clips: Vec) { + if clips != self.clips { + (self.clips, self.cuts) = (clips, HashMap::new()); } } @@ -171,9 +171,9 @@ impl f64> Builder { (self.points.len() - 1) as u32 } - /// The vertex where the clip's plane cuts the edge from vertex i to j, which lie at `di` and `dj` from it. - fn cut(&mut self, (i, di): (u32, f64), (j, dj): (u32, f64)) -> u32 { - let key = (i.min(j), i.max(j)); + /// The vertex where the plane of clip k cuts the edge from vertex i to j, which lie at `di` and `dj` from it. + fn cut(&mut self, k: usize, (i, di): (u32, f64), (j, dj): (u32, f64)) -> u32 { + let key = (k, i.min(j), i.max(j)); if let Some(&v) = self.cuts.get(&key) { return v; } @@ -186,32 +186,32 @@ impl f64> Builder { v } - /// A triangle in its winding, without its part past the clip's plane. + /// A triangle in its winding, without its parts past the planes of the clips. fn emit(&mut self, t: [u32; 3]) { - let Some(clip) = self.clip else { - self.indices.extend(t); - return; - }; - let d = t.map(|v| clip.side(self.points[v as usize])); - // Within a hundredth of a world unit of the plane, a point lies on it. - let off = |x: f64| x > 0.01; - if !d.iter().any(|&x| off(x)) { - self.indices.extend(t); - return; - } - // The corners on the near side, and the points where an edge crosses the plane, in the winding. - let mut keep = Vec::with_capacity(4); - for k in 0..3 { - let (i, j) = (k, (k + 1) % 3); - if !off(d[i]) { - keep.push(t[i]); + let mut poly = t.to_vec(); + for k in 0..self.clips.len() { + let clip = self.clips[k]; + let d: Vec = poly.iter().map(|&v| clip.side(self.points[v as usize])).collect(); + // Within a hundredth of a world unit of the plane, a point lies on it. + let off = |x: f64| x > 0.01; + if !d.iter().any(|&x| off(x)) { + continue; } - if off(d[i]) != off(d[j]) { - keep.push(self.cut((t[i], d[i]), (t[j], d[j]))); + // The corners on the near side, and the points where an edge crosses the plane, in the winding. + let mut keep = Vec::with_capacity(poly.len() + 1); + for i in 0..poly.len() { + let j = (i + 1) % poly.len(); + if !off(d[i]) { + keep.push(poly[i]); + } + if off(d[i]) != off(d[j]) { + keep.push(self.cut(k, (poly[i], d[i]), (poly[j], d[j]))); + } } + poly = keep; } - for k in 1..keep.len().saturating_sub(1) { - self.indices.extend([keep[0], keep[k], keep[k + 1]]); + for k in 1..poly.len().saturating_sub(1) { + self.indices.extend([poly[0], poly[k], poly[k + 1]]); } } diff --git a/host/obc-trailview-parts/src/tests.rs b/host/obc-trailview-parts/src/tests.rs index 2c53f2ea5..f3ef1d9f9 100644 --- a/host/obc-trailview-parts/src/tests.rs +++ b/host/obc-trailview-parts/src/tests.rs @@ -670,24 +670,27 @@ fn pair(apart: f64, dz: f64) -> (Vec, Vec) { for (e, mate) in ends.iter_mut().zip([apart, -apart]) { (e.part, e.mate, e.mate_way, e.mate_shift) = (Part::Pair, Some(mate), Some([1, 1]), Some(0.0)); } - let mut chords = Vec::new(); - for (north, z) in [(0.0, 500.0), (apart, 500.0 + dz)] { - for (a, b) in [(0.0, 20.0), (20.0, 40.0)] { - let mut c = chord([a, north, z + a * 0.005], [b, north, z + b * 0.005], 5.0, a); - c.ends = [Some(Part::Pair); 2]; - chords.push(c); - } - } + let mut chords = [lane(0.0, 500.0), lane(apart, 500.0 + dz)].concat(); + chords.iter_mut().for_each(|c| c.ends = [Some(Part::Pair); 2]); (ends, chords) } -/// The two road tubes of `pair` as four arches: no end has a mate. -fn side_by_side(apart: f64) -> (Vec, Vec) { - let (mut ends, mut chords) = pair(apart, 0.0); - let pi = std::f64::consts::PI; - ends.extend([end(0.0, apart, 500.0, 0.0, 6.0), end(40.0, apart, 500.2, pi, 3.0)]); +/// The two chords of a road tube 40 m east on the line `north` metres north, its floor from z rising 0.5 %. +fn lane(north: f64, z: f64) -> Vec { + [(0.0, 20.0), (20.0, 40.0)] + .map(|(a, b)| chord([a, north, z + a * 0.005], [b, north, z + b * 0.005], 5.0, a)) + .to_vec() +} + +/// Road tubes as those of `pair`, on the lines `norths` metres north, with an arch at each end: no end has a mate. +fn row(norths: &[f64]) -> (Vec, Vec) { + let (mut ends, mut chords) = (Vec::new(), Vec::new()); + for &north in norths { + ends.extend([end(0.0, north, 500.0, 0.0, 6.0), end(40.0, north, 500.2, std::f64::consts::PI, 3.0)]); + chords.extend(lane(north, 500.0)); + } for e in &mut ends { - (e.part, e.mate, e.mate_way, e.mate_shift) = (Part::Arch, None, None, None); + e.part = Part::Arch; } for c in &mut chords { c.ends = [Some(Part::Arch); 2]; @@ -738,30 +741,41 @@ fn hit(faces: &[[[f64; 3]; 3]], o: [f64; 3], d: [f64; 3], far: f64) -> Option<(f } #[test] -fn the_two_tubes_of_a_pair_are_one_room_and_one_head_wall_and_two_near_heads_end_between() { +fn the_tubes_of_a_pair_or_side_by_side_are_one_room_and_their_heads_end_between() { let rules = Rules::embedded(); let frame = rules.design.frame_m; // Tubes 7 m apart, 4.5 m wide each: their rooms overlap by 2 m, so they are cut in the middle; with the second's - // floor 0.8 m higher, faces close the steps there. Tubes 10.5 m apart do not overlap. Two arches that are no pair - // end their head walls at the middle too. - for (apart, dz, paired) in [(7.0, 0.0, true), (7.0, 0.8, true), (10.5, 0.0, true), (10.5, 0.0, false)] { - let name = format!("{apart} m apart, {dz} m higher, a pair: {paired}"); - let (ends, chords) = if paired { pair(apart, dz) } else { side_by_side(apart) }; + // floor 0.8 m higher, faces close the steps there. Tubes 10.5 m apart do not overlap. Arches that are no pair end + // their head walls at the middle too, the middle tube of three on both sides. + let cases: [(&[f64], f64, bool); 5] = [ + (&[0.0, 7.0], 0.0, true), + (&[0.0, 7.0], 0.8, true), + (&[0.0, 10.5], 0.0, true), + (&[0.0, 10.5], 0.0, false), + (&[0.0, 7.0, 14.0], 0.0, false), + ]; + for (norths, dz, paired) in cases { + let name = format!("tubes at {norths:?} m north, the second {dz} m higher, a pair: {paired}"); + let (ends, chords) = if paired { pair(norths[1], dz) } else { row(norths) }; let (room, box_points) = boxes_fit(&name, &ends, &chords); assert!(room > 200 && box_points > 100, "{name}: {room} room samples, {box_points} box samples"); let mesh = meshes([0.0, 0.0, 1.07e9, 1.07e9], &ends, &chords, rules); let faces = solid(&mesh); let o = tube::outline_of(&Net::new(&ends, &chords, rules), 0); - // Each tube's room on its side of the middle: no face lies in it. A face in the middle lies within the rounding - // of its vertices to world units. - let mid = apart / 2.0; + // A point's tube, the nearest; and its floor at the opening. + let of = |north: f64| { + let i = (0..norths.len()).min_by(|&i, &j| (north - norths[i]).abs().total_cmp(&(north - norths[j]).abs())); + let i = i.unwrap(); + (norths[i], if i == 1 { 500.0 + dz } else { 500.0 }) + }; + let middles: Vec = norths.windows(2).map(|w| (w[0] + w[1]) / 2.0).collect(); + // Each tube's room up to the middles: no face lies in it. A face in a middle lies within the rounding of its + // vertices to world units. let inside = |p: [f64; 3]| { - let (axis, z) = if p[1] < mid { (0.0, 500.0) } else { (apart, 500.0 + dz) }; - if (p[1] - mid).abs() < 0.05 { - return false; - } + let (axis, z) = of(p[1]); let (x, up) = (p[1] - axis, p[2] - z - p[0] * 0.005); - p[0] > 0.5 + middles.iter().all(|m| (p[1] - m).abs() >= 0.05) + && p[0] > 0.5 && p[0] < 39.5 && x.abs() < 4.45 && up > 0.25 @@ -771,9 +785,14 @@ fn the_two_tubes_of_a_pair_are_one_room_and_one_head_wall_and_two_near_heads_end let c = [0, 1, 2].map(|k| (f[0][k] + f[1][k] + f[2][k]) / 3.0); assert!(!inside(c), "{name}: a face in the room at {c:?}"); } - // From inside the room, every way across meets the front of a face: the room is closed at the middle. - for (north, up) in [(-3.0, 1.0), (0.0, 2.5), (2.5, 4.0), (apart - 2.5, 4.0), (apart, 2.5), (apart + 3.0, 1.0)] { - let z = if north < mid { 500.0 } else { 500.0 + dz }; + // From inside the room, every way across meets the front of a face: the room is closed at the middles. + let (first, last) = (norths[0], norths[norths.len() - 1]); + let mut from = vec![(first - 3.0, 1.0), (last + 3.0, 1.0)]; + for &n in norths { + from.extend([(n - 2.5, 4.0), (n, 2.5), (n + 2.5, 4.0)]); + } + for (north, up) in from { + let z = of(north).1; for k in 0..24 { let a = (k as f64 * 15.0 + 7.0).to_radians(); let d = [0.0, libm::cos(a), libm::sin(a)]; @@ -781,19 +800,17 @@ fn the_two_tubes_of_a_pair_are_one_room_and_one_head_wall_and_two_near_heads_end assert!(got.is_some_and(|h| h.1), "{name}: from {north} m north, {up} m up, at {a} rad: {got:?}"); } } - // One head wall: in front of the frame line, a ray east meets its front between the two holes, but none in a - // hole; where the holes overlap, they are one opening. - let holes_meet = apart < 2.0 * (4.5 + frame); - { - let north = mid; + // One head wall: in front of the frame line, a ray east meets its front between two holes, but none in a hole; + // where the holes overlap, they are one opening. + for &north in &middles { let got = hit(&faces, [-3.0, north, 501.0], [1.0, 0.0, 0.0], 10.0); - if holes_meet { + if norths[1] - norths[0] < 2.0 * (4.5 + frame) { assert!(got.is_none_or(|h| h.0 > 3.5), "{name}: the middle of one opening: {got:?}"); } else { assert!(got.is_some_and(|h| h.1 && h.0 < 3.0), "{name}: the head wall between the holes: {got:?}"); } } - for north in [0.0, apart] { + for &north in norths { let got = hit(&faces, [-3.0, north, 502.5], [1.0, 0.0, 0.0], 10.0); assert!(got.is_none_or(|h| h.0 > 3.5), "{name}: the hole at {north} m north: {got:?}"); } diff --git a/host/obc-trailview-parts/src/tube.rs b/host/obc-trailview-parts/src/tube.rs index f63129375..db146f400 100644 --- a/host/obc-trailview-parts/src/tube.rs +++ b/host/obc-trailview-parts/src/tube.rs @@ -337,13 +337,13 @@ impl<'a> Net<'a> { self.ends[e].part == Part::Free && self.ends[e].collar <= 0.0 } - /// Where a station across chord c meets another built tube whose shell overlaps its own there: the middle between - /// their walls on the station's line; the nearest. A tube that lies over or under it by more than half their heights - /// does not meet it. - pub fn cut(&self, c: usize, st: &Station) -> Option { + /// Where a station across chord c meets other built tubes whose shells overlap its own there: on each side (to the + /// right, to the left) the nearest, at the middle between their walls on the station's line. A tube that lies over + /// or under it by more than half their heights does not meet it. + pub fn cuts(&self, c: usize, st: &Station) -> [Option; 2] { let (own, shell) = (&self.chords[c], self.rules.ladder.bake.shell_m); let key = [libm::floor(st.x / self.cell) as i64, libm::floor(st.y / self.cell) as i64]; - let mut best: Option = None; + let mut best: [Option; 2] = [None, None]; for &o in self.cells.get(&key).into_iter().flatten().filter(|&&o| self.tube[o] != self.tube[c]) { let other = &self.chords[o]; // The station's line meets the chord: st + x·across = a + u·(b − a). @@ -364,36 +364,43 @@ impl<'a> Net<'a> { { continue; } - if best.is_none_or(|b| x.abs() < b.axis.abs()) { + let side = &mut best[usize::from(x > 0.0)]; + if side.is_none_or(|b| x.abs() < b.axis.abs()) { let middle = (x + x.signum() * (own.half - other.half)) / 2.0; - best = Some(Cut { x: middle, axis: x, other: o, floor }); + *side = Some(Cut { x: middle, axis: x, other: o, floor }); } } best } - /// The clip of chord c from station s to t at its cuts: the plane through them that takes off the other tube's - /// side, and the cuts; where one station has none, the plane through the other's along the chord. - pub fn clip(&self, c: usize, (s, t): (&Station, &Station)) -> Option<(Clip, Option, Option)> { - let (cs, ct) = (self.cut(c, s), self.cut(c, t)); - let (a, z, cut) = match (cs, ct) { - (Some(x), Some(y)) => (s.at([x.x, 0.0]), t.at([y.x, 0.0]), x), - (Some(x), None) => { - (s.at([x.x, 0.0]), [s.at([x.x, 0.0])[0] + t.x - s.x, s.at([x.x, 0.0])[1] + t.y - s.y, 0.0], x) - } - (None, Some(y)) => { - (t.at([y.x, 0.0]), [t.at([y.x, 0.0])[0] + t.x - s.x, t.at([y.x, 0.0])[1] + t.y - s.y, 0.0], y) - } - (None, None) => return None, - }; - let st = if cs.is_some() { s } else { t }; - let (far, near) = (st.at([cut.axis, 0.0]), st.at([cut.x, 0.0])); - let away = [far[0] - near[0], far[1] - near[1]]; - // The two tubes overlap by `OVERLAP_M` at the plane, so the rounding of their vertices opens no gap there. - let l = libm::hypot(away[0], away[1]).max(f64::MIN_POSITIVE); - let d = OVERLAP_M / metres_per_unit(st.y) / l; - let (a, z) = ([a[0] + away[0] * d, a[1] + away[1] * d], [z[0] + away[0] * d, z[1] + away[1] * d]); - Some((Clip { a, b: z, away }, cs, ct)) + /// The clips of chord c from station s to t at its cuts, on each side where it has one: the plane through them + /// that takes off the other tube's side, and the cuts; where one station has none, the plane through the other's + /// along the chord. + pub fn clips(&self, c: usize, (s, t): (&Station, &Station)) -> Vec<(Clip, Option, Option)> { + let (at_s, at_t) = (self.cuts(c, s), self.cuts(c, t)); + let mut out = Vec::new(); + for (cs, ct) in at_s.into_iter().zip(at_t) { + let (st, cut) = match (cs, ct) { + (Some(x), _) => (s, x), + (None, Some(y)) => (t, y), + (None, None) => continue, + }; + let (far, near) = (st.at([cut.axis, 0.0]), st.at([cut.x, 0.0])); + let away = [far[0] - near[0], far[1] - near[1]]; + // The two tubes overlap by `OVERLAP_M` at the plane, so the rounding of their vertices opens no gap there. + let l = libm::hypot(away[0], away[1]).max(f64::MIN_POSITIVE); + let d = OVERLAP_M / metres_per_unit(st.y) / l; + let shift = |p: [f64; 3]| [p[0] + away[0] * d, p[1] + away[1] * d]; + let (a, z) = match (cs, ct) { + (Some(x), Some(y)) => (shift(s.at([x.x, 0.0])), shift(t.at([y.x, 0.0]))), + _ => { + let a = shift(near); + (a, [a[0] + t.x - s.x, a[1] + t.y - s.y]) + } + }; + out.push((Clip { a, b: z, away }, cs, ct)); + } + out } } @@ -518,9 +525,9 @@ pub fn inside f64>(b: &mut Builder, net: &Net, c: usize) { let sp = spring(net, chord.section, chord.height); let bore = |colour: u32| flagged(colour, BORE); let across = |c: Corner| s.mix(&t, 0.5).out(c); - // Of two tubes of a pair, each draws its side of the middle between their walls. - let cut = net.clip(c, (&s, &t)); - b.clip(cut.map(|c| c.0)); + // Of two tubes that meet, each draws its side of the middle between their walls. + let cuts = net.clips(c, (&s, &t)); + b.clip(cuts.iter().map(|c| c.0).collect()); // A box section is cast: its rock bore is lined. let cast = chord.section == Section::Box; let (wall, vault) = match bore_of { @@ -596,9 +603,8 @@ pub fn inside f64>(b: &mut Builder, net: &Net, c: usize) { if bore_of == Bore::Road { lamps(b, net, c, (&s, &t)); } - b.clip(None); - // At the cut, a face closes the room where the other tube's floor is higher or its roof lower. - let Some((_, Some(cs), Some(ct))) = cut else { return }; + b.clip(Vec::new()); + // At a cut, a face closes the room where the other tube's floor is higher or its roof lower. let span = |st: &Station, cut: &Cut| { let f = |p: &[(f64, f64, f64)], x: f64| p.iter().find(|q| x >= q.0 - 1e-9 && x <= q.1 + 1e-9).map(|q| q.2); let own = f(&pieces, cut.x).zip(top_at(&o, cut.x))?; @@ -609,10 +615,12 @@ pub fn inside f64>(b: &mut Builder, net: &Net, c: usize) { let (xl, df) = (cut.x - cut.axis, cut.floor - st.z); Some(steps(own, f(&op, xl).zip(top_at(&oo, xl)).map(|(lo, hi)| (lo + df, hi + df)))) }; - if let (Some([ls, us]), Some([lt, ut])) = (span(&s, &cs), span(&t, &ct)) { - let out = across([-cs.axis.signum(), 0.0]); - cut_face(b, (&s, &t), (cs.x, ls.0, ls.1), (ct.x, lt.0, lt.1), bore(inside.walk), out); - cut_face(b, (&s, &t), (cs.x, us.0, us.1), (ct.x, ut.0, ut.1), bore(vault), out); + for (cs, ct) in cuts.iter().filter_map(|c| c.1.zip(c.2)) { + if let (Some([ls, us]), Some([lt, ut])) = (span(&s, &cs), span(&t, &ct)) { + let out = across([-cs.axis.signum(), 0.0]); + cut_face(b, (&s, &t), (cs.x, ls.0, ls.1), (ct.x, lt.0, lt.1), bore(inside.walk), out); + cut_face(b, (&s, &t), (cs.x, us.0, us.1), (ct.x, ut.0, ut.1), bore(vault), out); + } } } @@ -682,9 +690,9 @@ pub fn shell f64>( let next_of = |i: usize| pieces.get(i + 1).map(|p| (p.2, p.3)).or(meets.lower.filter(|_| last(i))); let outer = |st: &Station, h: f64, section: Section| shell_outline(net, section, half, h, foot - st.z); for (i, &(ref s, ref t, ref h, ref section, c)) in pieces.iter().enumerate() { - let cut = net.clip(c, (s, t)); - b.clip(cut.map(|c| c.0)); - if let Some((_, Some(cs), Some(ct))) = cut { + let cuts = net.clips(c, (s, t)); + b.clip(cuts.iter().map(|c| c.0).collect()); + for (cs, ct) in cuts.iter().filter_map(|c| c.1.zip(c.2)) { // The other tube's shell top at the cut, over this station's floor. let top = |st: &Station, cut: &Cut| { let own = top_at(&outer(st, *h, *section), cut.x)?; @@ -733,7 +741,7 @@ pub fn shell f64>( b.strip((t, &tall[j..j + 2]), (t, &low[j..j + 2]), colour, toward); } } - b.clip(None); + b.clip(Vec::new()); } #[cfg(test)] From f63558a09b4030688f4e78d571685b98bb124dc8 Mon Sep 17 00:00:00 2001 From: timohueser Date: Sat, 21 Nov 2026 19:42:29 +0100 Subject: [PATCH 07/20] specs: a pair needs a part at both ends of its two chains, and its heading is square to its frame line Co-Authored-By: Claude Opus 5.5 --- specs/trailview-features.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/specs/trailview-features.md b/specs/trailview-features.md index cba4848b5..b2f76ac21 100644 --- a/specs/trailview-features.md +++ b/specs/trailview-features.md @@ -588,8 +588,9 @@ Each opening takes the first kind of part that fits, by these rungs in order: the floor of the tube, as for every part. A short chain under a building only has no part. 4. An end that meets no way and is covered at its opening: `free`. 5. An end whose first covered metre lies within `collar_max_m`: `pair` where an opening of another chain of the same - family (rail or not) at that rung lies within `pair_max_m` and `pair_max_deg` (the nearest pairs first, each - opening in one pair); else `rock` for a group with `rock` covered within `rock_cover_max_m`; else `arch`. + family (rail or not) at that rung lies within `pair_max_m` and `pair_max_deg`, and each of the two chains has a + part at both of its ends (the nearest pairs first, each opening in one pair); else `rock` for a group with `rock` + covered within `rock_cover_max_m`; else `arch`. 6. Else `free`. The two openings of a pair lie on the frame line of the opening farther in: the other one moves in along its way to @@ -627,7 +628,7 @@ The tags, numbers in metres with at most 2 decimals, the values of a row separat | `along` | tube | The metres along the stroke of its way at the first vertex | | `ends` | tube | The parts of the chain's two ends, the end behind the first vertex first: `arch`, `pair`, `rock`, `box`, `free`, or `none` for an end with no part of its own | | `part` | end | `arch`, `pair`, `rock`, `box` or `free` | -| `heading` | end | Radians from x to y of world coordinates, into the tube, three decimals | +| `heading` | end | Radians from x to y of world coordinates, into the tube, three decimals; of `pair`, into the tube of the opening farther in, square to the frame line | | `collar` | end | The collar; of `free`, the length of its shell | | `face`, `left`, `right` | end | Not on `free` | | `foot` | end | | From 6276fec75e392532a5adef0243b036d9d7c660b7 Mon Sep 17 00:00:00 2001 From: timohueser Date: Sat, 21 Nov 2026 19:46:19 +0100 Subject: [PATCH 08/20] trailview-parts: comments fit the line and name the general cut Co-Authored-By: Claude Opus 5.5 --- host/obc-trailview-parts/src/arch.rs | 12 ++++++------ host/obc-trailview-parts/src/boxes.rs | 4 ++-- host/obc-trailview-parts/src/tube.rs | 25 +++++++++++++------------ 3 files changed, 21 insertions(+), 20 deletions(-) diff --git a/host/obc-trailview-parts/src/arch.rs b/host/obc-trailview-parts/src/arch.rs index 8bff63d60..99df60ca2 100644 --- a/host/obc-trailview-parts/src/arch.rs +++ b/host/obc-trailview-parts/src/arch.rs @@ -98,8 +98,8 @@ fn top(end: &crate::End, (lo, hi): (f64, f64), (coping, slope): (f64, f64), t: f along.min(coping + slope.max((end.face - coping) / len) * (len - d)) } -/// End e's opening outline grown by `grow`, from the sill up its side to a corner at the floor's height there, where the -/// tube's wall stands on the floor, and on over its top. +/// End e's opening outline grown by `grow`, from the sill up its side to a corner at the floor's height there, where +/// the tube's wall stands on the floor, and on over its top. fn grown(net: &Net, e: usize, grow: f64) -> Vec { let Some((c, _)) = net.opening(e) else { return Vec::new() }; let (chord, design) = (&net.chords[c], &net.rules.design); @@ -114,10 +114,10 @@ fn grown(net: &Net, e: usize, grow: f64) -> Vec { out } -/// Where end e's head ends at the openings near it, on each side at most one: the metres to the left of its axis of the -/// middle between its tube's wall and the other's, the side of the other (1 to the left), the other end, and whether the -/// two lie on one frame line. On its side, the mate of a pair; else the nearest built end that leads the same way within -/// `pair_max_m` and `pair_max_deg`, at its floor's height, whose axis passes within reach of e's head. +/// Where end e's head ends at the openings near it, on each side at most one: the metres to the left of its axis of +/// the middle between its tube's wall and the other's, the side of the other (1 to the left), the other end, and +/// whether the two lie on one frame line. On its side, the mate of a pair; else the nearest built end that leads the +/// same way within `pair_max_m` and `pair_max_deg`, at its floor's height, whose axis passes within reach of e's head. fn head_cuts(net: &Net, e: usize) -> Vec<(f64, f64, usize, bool)> { let middle = |a: f64, m: usize| (a + a.signum() * (half_at(net, e) - half_at(net, m))) / 2.0; let (end, bake) = (&net.ends[e], &net.rules.ladder.bake); diff --git a/host/obc-trailview-parts/src/boxes.rs b/host/obc-trailview-parts/src/boxes.rs index 8fe1ed4a2..15626e873 100644 --- a/host/obc-trailview-parts/src/boxes.rs +++ b/host/obc-trailview-parts/src/boxes.rs @@ -191,8 +191,8 @@ impl Line { } /// The boxes of built end e: the opening's, from the front of the head wall to the frame line, its outline grown to -/// the middle of the wall round it, but at a closed end; then one per straight piece of the tube's axis out to its reach, each at the -/// middle of the wall of its section, its ends in the planes of the tube's rings there. +/// the middle of the wall round it, but at a closed end; then one per straight piece of the tube's axis out to its +/// reach, each at the middle of the wall of its section, its ends in the planes of the tube's rings there. pub fn boxes(net: &Net, e: usize) -> Vec<[f64; BOX]> { let Some((c0, _)) = net.opening(e) else { return Vec::new() }; let (end, design, bake) = (&net.ends[e], &net.rules.design, &net.rules.ladder.bake); diff --git a/host/obc-trailview-parts/src/tube.rs b/host/obc-trailview-parts/src/tube.rs index db146f400..50162e528 100644 --- a/host/obc-trailview-parts/src/tube.rs +++ b/host/obc-trailview-parts/src/tube.rs @@ -35,7 +35,7 @@ pub fn direction(c: &Chord) -> ([f64; 2], f64) { /// The chords of a tile by their vertices, and per end the chord vertex at its opening. pub struct Net<'a> { - /// The ends of the input, then per pair an end at the opening of its mate, which has no head wall of its own. + /// The ends of the input, then per pair an end at the opening of its mate. pub ends: Vec, pub chords: &'a [Chord], pub rules: &'a Rules, @@ -284,9 +284,10 @@ impl<'a> Net<'a> { out } - /// The share of daylight at a world point: over the openings (not the closed ends) whose section over the tube's floor, grown by the shell - /// and a metre to each side, holds the point from the front of the head wall to `daylight_m` in, `1 − smoothstep(0, - /// daylight_m, m)` of the metres m in from the frame line, the largest; 0 with none. + /// The share of daylight at a world point: over the openings (not the closed ends) whose section over the tube's + /// floor, grown by the shell and a metre to each side, holds the point from the front of the head wall to + /// `daylight_m` in, `1 − smoothstep(0, daylight_m, m)` of the metres m in from the frame line, the largest; 0 with + /// none. pub fn daylight(&self, p: [f64; 3]) -> f64 { let (shell, reach, front) = (self.rules.ladder.bake.shell_m, self.rules.design.daylight_m, self.rules.design.recess_m); @@ -453,8 +454,8 @@ pub fn inward(a: Corner, b: Corner, spring: f64) -> Corner { [-(a[0] + b[0]), -(a[1] + b[1] - 2.0 * spring)] } -/// Where a station meets the other tube of a pair (`Net::cut`): the metres across the station to the middle between their -/// walls, and the other tube there: its chord, the floor at that point (a world height) and its axis across the station. +/// Where a station meets another tube (`Net::cuts`): the metres across the station to the middle between their walls, +/// and the other tube there: its chord, the floor at that point (a world height) and its axis across the station. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Cut { pub x: f64, @@ -494,8 +495,8 @@ pub fn cut_face f64>( } } -/// Where two spans at a cut differ: of the own span from `lo` to `hi`, the part under the other's span and the part over -/// it, each (lo, hi); the whole own span where the other has none. +/// Where two spans at a cut differ: of the own span from `lo` to `hi`, the part under the other's span and the part +/// over it, each (lo, hi); the whole own span where the other has none. pub fn steps((lo, hi): (f64, f64), other: Option<(f64, f64)>) -> [(f64, f64); 2] { match other { Some((olo, ohi)) => [(lo, olo.clamp(lo, hi)), (ohi.clamp(lo, hi), hi)], @@ -584,8 +585,8 @@ pub fn inside f64>(b: &mut Builder, net: &Net, c: usize) { for k in 0..2 { step(b, net, c, k, &o, vault); } - // At an opening (not a closed end), the front of the floor goes down to the sill, `lift_m` under the floor. Each side of a piece has - // a corner at the top of each piece beside it, which is the corner of a face there. + // At an opening (not a closed end), the front of the floor goes down to the sill, `lift_m` under the floor. Each + // side of a piece has a corner at the top of each piece beside it, which is the corner of a face there. let open = |k: usize| net.end_at(c, k).is_some_and(|e| !net.closed(e)); for (k, r) in [(0, &s), (1, &t)].into_iter().filter(|(k, _)| open(*k)) { let out = flat(if k == 0 { [-d[0], -d[1]] } else { d }); @@ -675,8 +676,8 @@ pub type Run = (Station, Station, f64, Section, usize); /// The outer shell of a run of pieces, with the inside half-width `half`; its walls go down to the world height `foot`. /// Where two pieces of different height meet, a face closes the step, facing the lower one; so too after the last piece /// where a lower shell goes on (`meets`). There the walls have a corner at the foot of the shell that goes on. Of two -/// tubes of a pair, each draws its side of the middle between their walls, and a face closes the step where its shell is -/// the higher there. +/// tubes that meet, each draws its side of the middle between their walls, and a face closes the step where its shell +/// is the higher there. pub fn shell f64>( b: &mut Builder, net: &Net, From c07d6c33ecf196f2370758f975b451c1334e9b9b Mon Sep 17 00:00:00 2001 From: timohueser Date: Sat, 21 Nov 2026 19:57:26 +0100 Subject: [PATCH 09/20] trailview-parts: the cuts' map shares the openings' map type, and a step takes max and min, not clamp `f64::clamp` checks its bounds and so brings the formatting of floats into the WASM (about 24 kB raw). A clip's map of cut vertices and the tubes' cells take key and value types that the crate's maps already have. Co-Authored-By: Claude Opus 5.5 --- host/obc-trailview-parts/src/mesh.rs | 12 +++++++----- host/obc-trailview-parts/src/tube.rs | 13 ++++++++----- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/host/obc-trailview-parts/src/mesh.rs b/host/obc-trailview-parts/src/mesh.rs index 853313c71..165461aba 100644 --- a/host/obc-trailview-parts/src/mesh.rs +++ b/host/obc-trailview-parts/src/mesh.rs @@ -129,8 +129,10 @@ pub struct Builder f64> { looks: Vec<(u32, Paint)>, daylight: L, clips: Vec, - /// The vertex where the plane of a clip cuts the edge between two vertices. - cuts: HashMap<(usize, u32, u32), u32>, + /// The vertex where the plane of clip k (one of at most four) cuts the edge between two vertices, by the lower + /// vertex and k, and the higher vertex. Its key and value have the types of `Net`'s map of openings, so the WASM + /// holds the code of one map of that type. + cuts: HashMap<(usize, usize), usize>, } impl f64> Builder { @@ -173,16 +175,16 @@ impl f64> Builder { /// The vertex where the plane of clip k cuts the edge from vertex i to j, which lie at `di` and `dj` from it. fn cut(&mut self, k: usize, (i, di): (u32, f64), (j, dj): (u32, f64)) -> u32 { - let key = (k, i.min(j), i.max(j)); + let key = (i.min(j) as usize * 4 + k, i.max(j) as usize); if let Some(&v) = self.cuts.get(&key) { - return v; + return v as u32; } let (u, p, q) = (di / (di - dj), self.points[i as usize], self.points[j as usize]); let ((colour, a), z) = (self.looks[i as usize], self.looks[j as usize].1); let mix = |a: f64, b: f64| a + (b - a) * u; let paint = Paint { across: mix(a.across, z.across), half: a.half, sleepers: mix(a.sleepers, z.sleepers) }; let v = self.vertex([mix(p[0], q[0]), mix(p[1], q[1]), mix(p[2], q[2])], colour, paint); - self.cuts.insert(key, v); + self.cuts.insert(key, v as usize); v } diff --git a/host/obc-trailview-parts/src/tube.rs b/host/obc-trailview-parts/src/tube.rs index 50162e528..40d9a98b6 100644 --- a/host/obc-trailview-parts/src/tube.rs +++ b/host/obc-trailview-parts/src/tube.rs @@ -50,8 +50,9 @@ pub struct Net<'a> { slope: Vec, /// Per chord, its tube: the chords that its vertices join. tube: Vec, - /// The built chords by the cells (`CELL_M`) that they come within reach of. - cells: HashMap<[i64; 2], Vec>, + /// The built chords by the cells (`CELL_M`) that they come within reach of; a cell's key is its two indices' bits, + /// so the WASM holds the code of one map of that type. + cells: HashMap<[u64; 2], Vec>, /// The world units of a cell. cell: f64, } @@ -159,12 +160,13 @@ impl<'a> Net<'a> { let reach = 2.0 * chords.iter().map(|c| c.half + shell).fold(0.0, f64::max) / metres_per_unit(first.a[1]); let cell = net.cell; let at = |v: f64| libm::floor(v / cell) as i64; + let key = |x: i64, y: i64| [x as u64, y as u64]; for (c, chord) in chords.iter().enumerate().filter(|&(c, _)| built(&chords[c].ends)) { let lo = [chord.a[0].min(chord.b[0]) - reach, chord.a[1].min(chord.b[1]) - reach]; let hi = [chord.a[0].max(chord.b[0]) + reach, chord.a[1].max(chord.b[1]) + reach]; for x in at(lo[0])..=at(hi[0]) { for y in at(lo[1])..=at(hi[1]) { - net.cells.entry([x, y]).or_default().push(c); + net.cells.entry(key(x, y)).or_default().push(c); } } } @@ -343,7 +345,7 @@ impl<'a> Net<'a> { /// or under it by more than half their heights does not meet it. pub fn cuts(&self, c: usize, st: &Station) -> [Option; 2] { let (own, shell) = (&self.chords[c], self.rules.ladder.bake.shell_m); - let key = [libm::floor(st.x / self.cell) as i64, libm::floor(st.y / self.cell) as i64]; + let key = [libm::floor(st.x / self.cell) as i64 as u64, libm::floor(st.y / self.cell) as i64 as u64]; let mut best: [Option; 2] = [None, None]; for &o in self.cells.get(&key).into_iter().flatten().filter(|&&o| self.tube[o] != self.tube[c]) { let other = &self.chords[o]; @@ -499,7 +501,8 @@ pub fn cut_face f64>( /// over it, each (lo, hi); the whole own span where the other has none. pub fn steps((lo, hi): (f64, f64), other: Option<(f64, f64)>) -> [(f64, f64); 2] { match other { - Some((olo, ohi)) => [(lo, olo.clamp(lo, hi)), (ohi.clamp(lo, hi), hi)], + // `max` and `min`, not `clamp`: its check of the bounds would bring the formatting of floats into the WASM. + Some((olo, ohi)) => [(lo, olo.max(lo).min(hi)), (ohi.max(lo).min(hi), hi)], None => [(lo, hi), (hi, hi)], } } From bd57096708a151df1ada9b4f67179ad4438d84d1 Mon Sep 17 00:00:00 2001 From: timohueser Date: Sat, 21 Nov 2026 19:57:26 +0100 Subject: [PATCH 10/20] wasm: the recorded size of the parts bridge with the pair, the rim and the cut of tubes Co-Authored-By: Claude Opus 5.5 --- builder/wasm/wasm_size_guard.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/builder/wasm/wasm_size_guard.py b/builder/wasm/wasm_size_guard.py index 69d996ec3..ec235a5b0 100644 --- a/builder/wasm/wasm_size_guard.py +++ b/builder/wasm/wasm_size_guard.py @@ -45,10 +45,11 @@ "raw_wasm": round(GROUND_PLAN_MARGIN_GZIPPED * GROUND_PLAN_MEASURED["raw_wasm"] / GROUND_PLAN_MEASURED["gzipped"]), } -# Measured in CI on the build of the tunnel parts' arch, tube, boxes and underpasses, with a tile's volumes built once -# and selected per node, with wasm-pack 0.15.0 and rustc 1.100.0. The margin is the ground plan's, raw by the same -# fraction. -PARTS_MEASURED = {"gzipped": 125_922, "raw_wasm": 293_466} +# Measured on the build of the tunnel parts' arch, tube, boxes and underpasses, with a tile's volumes built once and +# selected per node, and the pair, the rim, the closed free end and the cut of two tubes that meet: locally with +# wasm-pack 0.15.0 and rustc 1.99.0, which gives develop's build before it about 2 kB more than CI. The margin is the +# ground plan's, raw by the same fraction. +PARTS_MEASURED = {"gzipped": 142_428, "raw_wasm": 321_839} PARTS_MARGIN = { "gzipped": GROUND_PLAN_MARGIN_GZIPPED, "raw_wasm": round(GROUND_PLAN_MARGIN_GZIPPED * PARTS_MEASURED["raw_wasm"] / PARTS_MEASURED["gzipped"]), From 2908211e87ab4f3c27488fee966958dce1566548 Mon Sep 17 00:00:00 2001 From: timohueser Date: Sat, 21 Nov 2026 20:32:03 +0100 Subject: [PATCH 11/20] wasm: the parts and ground plan bridges' sizes as CI measures this branch Co-Authored-By: Claude Opus 5.5 --- builder/wasm/wasm_size_guard.py | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/builder/wasm/wasm_size_guard.py b/builder/wasm/wasm_size_guard.py index ec235a5b0..00b67e0a2 100644 --- a/builder/wasm/wasm_size_guard.py +++ b/builder/wasm/wasm_size_guard.py @@ -32,9 +32,9 @@ # the sidewalks' slabs with their ends, rings and kerbs, and the portal line's levels with the cover's sides. # The owner allows about 60 kB of code growth for the crossing block, stated in its pull request and recorded here. # The built tunnel ends (obc-trailview-parts) with their open stretches and the approaches to their openings add -# about 36 kB gzipped; measured on that build with wasm-pack 0.15.0 and rustc 1.99.0, which gives the build before it -# about 5 kB more than CI. -GROUND_PLAN_MEASURED = {"gzipped": 828_795, "raw_wasm": 2_129_601} +# about 36 kB gzipped; the openings of a pair's mate (the parts' `mouths`) about 2 kB more, measured in CI with +# wasm-pack 0.15.0 and rustc 1.100.0. +GROUND_PLAN_MEASURED = {"gzipped": 831_466, "raw_wasm": 2_134_754} # The owner's margin: compiler and dependency updates move the size by a few kilobytes and must not fail # unrelated pull requests; real growth past the margin still fails. Raw gets the same fraction as gzipped. # A pull request that changes the bridge's code records its own CI size here; the margin is only for toolchain @@ -45,11 +45,10 @@ "raw_wasm": round(GROUND_PLAN_MARGIN_GZIPPED * GROUND_PLAN_MEASURED["raw_wasm"] / GROUND_PLAN_MEASURED["gzipped"]), } -# Measured on the build of the tunnel parts' arch, tube, boxes and underpasses, with a tile's volumes built once and -# selected per node, and the pair, the rim, the closed free end and the cut of two tubes that meet: locally with -# wasm-pack 0.15.0 and rustc 1.99.0, which gives develop's build before it about 2 kB more than CI. The margin is the -# ground plan's, raw by the same fraction. -PARTS_MEASURED = {"gzipped": 142_428, "raw_wasm": 321_839} +# Measured in CI on the build of the tunnel parts' arch, tube, boxes and underpasses, with a tile's volumes built once +# and selected per node, and the pair, the rim, the closed free end and the cut of two tubes that meet, with wasm-pack +# 0.15.0 and rustc 1.100.0. The margin is the ground plan's, raw by the same fraction. +PARTS_MEASURED = {"gzipped": 140_824, "raw_wasm": 321_998} PARTS_MARGIN = { "gzipped": GROUND_PLAN_MARGIN_GZIPPED, "raw_wasm": round(GROUND_PLAN_MARGIN_GZIPPED * PARTS_MEASURED["raw_wasm"] / PARTS_MEASURED["gzipped"]), From ff722bd087010ae344aeb7ac1ffab02c6e228de9 Mon Sep 17 00:00:00 2001 From: timohueser Date: Sat, 21 Nov 2026 21:40:44 +0100 Subject: [PATCH 12/20] trailview-parts: tubes meet only where both are, heads only where a tube crosses the frame line A clip holds between two stations that both meet the other tube; where the other starts or ends inside a piece, the clip ends there and a face closes the shell. One test (`Net::meets`) serves tubes and heads, with the middle measured square to each tube's chord, so both find one plane at any angle. A cut head closes its section. The tube labels come from one union-find walk, made only for the meshes. Each tube of a pair takes its own collar (`mate_collar`). Co-Authored-By: Claude Opus 5.5 --- host/obc-trailview-parts/src/arch.rs | 85 +++---- host/obc-trailview-parts/src/lib.rs | 31 ++- host/obc-trailview-parts/src/mesh.rs | 71 ++++-- host/obc-trailview-parts/src/tests.rs | 71 +++++- host/obc-trailview-parts/src/tube.rs | 349 ++++++++++++++++++-------- 5 files changed, 418 insertions(+), 189 deletions(-) diff --git a/host/obc-trailview-parts/src/arch.rs b/host/obc-trailview-parts/src/arch.rs index 99df60ca2..3ac82c8d9 100644 --- a/host/obc-trailview-parts/src/arch.rs +++ b/host/obc-trailview-parts/src/arch.rs @@ -5,7 +5,7 @@ use crate::boxes; use crate::mesh::{flagged, flat, outline, Builder, Clip, Corner, Station, VOID}; -use crate::tube::{self, cut_face, direction, inward, spring, steps, top_at, Net}; +use crate::tube::{self, cut_face, direction, inward, spring, top_at, Net}; use crate::{Part, Section}; /// A piece of the shell: its start and end station across to the left of the way in, its chord's height and section, @@ -43,7 +43,7 @@ fn rim(net: &Net, e: usize) -> bool { fn edges(net: &Net, e: usize) -> (f64, f64) { let shell = net.rules.ladder.bake.shell_m; let edge = half_at(net, e) + shell; - match (net.mate[e], net.ends[e].mate) { + match (net.mate[e], net.ends[e].mate.map(|m| m.across)) { (Some(m), Some(a)) => { let other = half_at(net, m) + shell; ((-edge).min(a - other), edge.max(a + other)) @@ -114,38 +114,14 @@ fn grown(net: &Net, e: usize, grow: f64) -> Vec { out } -/// Where end e's head ends at the openings near it, on each side at most one: the metres to the left of its axis of -/// the middle between its tube's wall and the other's, the side of the other (1 to the left), the other end, and -/// whether the two lie on one frame line. On its side, the mate of a pair; else the nearest built end that leads the -/// same way within `pair_max_m` and `pair_max_deg`, at its floor's height, whose axis passes within reach of e's head. -fn head_cuts(net: &Net, e: usize) -> Vec<(f64, f64, usize, bool)> { - let middle = |a: f64, m: usize| (a + a.signum() * (half_at(net, e) - half_at(net, m))) / 2.0; - let (end, bake) = (&net.ends[e], &net.rules.ladder.bake); - let (into, k) = (end.way_in(), crate::metres_per_unit(end.at[1])); - let left = crate::mesh::left_of(into); - let (right_end, left_end) = wide(net, e); - let near = (0..net.ends.len()).filter(|&m| m != e && net.built_end(m) && !net.closed(m)).filter_map(|m| { - let other = &net.ends[m]; - let (d, o) = (other.way_in(), [(other.at[0] - end.at[0]) * k, (other.at[1] - end.at[1]) * k]); - let (along, across) = (o[0] * into[0] + o[1] * into[1], o[0] * left[0] + o[1] * left[1]); - if net.mate[e] == Some(m) { - return end.mate.map(|a| (m, 0.0, a, true)); - } - let reach = if across > 0.0 { left_end } else { -right_end } + half_at(net, m) + bake.shell_m; - let same_way = d[0] * into[0] + d[1] * into[1] >= libm::cos(bake.pair_max_deg.to_radians()); - let level = (other.z - end.z).abs() <= (end.height + other.height) / 2.0; - (same_way && level && along.abs() <= bake.pair_max_m && across.abs() < reach) - .then_some((m, along, across, false)) - }); - let mut sides: [Option<(usize, f64, f64, bool)>; 2] = [None, None]; - for n in near { - let side = &mut sides[usize::from(n.2 > 0.0)]; - // The mate first, then the nearest across. - if side.is_none_or(|s| !s.3 && (n.3 || n.2.abs() < s.2.abs())) { - *side = Some(n); - } - } - sides.into_iter().flatten().map(|(m, along, a, _)| (middle(a, m), a.signum(), m, along.abs() < 0.5)).collect() +/// Where end e's head ends at another part: on each side, the nearest built tube that crosses its frame line within +/// reach of the head (`Net::meets` with the head's metres across): the metres across to the middle between the two +/// tubes' walls, and the side (1 to the left). The mate of a pair crosses it at its opening. +fn head_cuts(net: &Net, e: usize) -> Vec<(f64, f64)> { + let Some((c, _)) = net.opening(e) else { return Vec::new() }; + let (right, left) = wide(net, e); + let cuts = net.meets(c, &net.frame(e, 0.0), [-right, left], tube::MEET_PAST_M); + cuts.into_iter().flatten().map(|cut| (cut.x, cut.axis.signum())).collect() } /// The faces of the head at end e: its head wall or rim, the sill, the reveal and the frame round the opening, the dark @@ -177,10 +153,10 @@ pub fn faces f64>(b: &mut Builder, net: &Net, e: usize) { let cuts = head_cuts(net, e); b.clip( (cuts.iter()) - .map(|&(x, side, ..)| { + .map(|&(x, side)| { let x = x + side * tube::OVERLAP_M; let (p, q, r) = (front.at([x, 0.0]), back.at([x, 0.0]), front.at([x + side, 0.0])); - Clip { a: [p[0], p[1]], b: [q[0], q[1]], away: [r[0] - p[0], r[1] - p[1]] } + Clip { a: [p[0], p[1]], b: [q[0], q[1]], away: [r[0] - p[0], r[1] - p[1]], bound: None } }) .collect(), ); @@ -237,27 +213,24 @@ pub fn faces f64>(b: &mut Builder, net: &Net, e: usize) { b.triangle(centre, rim_v[k], rim_v[(k + 1) % rim_v.len()], outward); } b.clip(Vec::new()); - // Where two holes on one frame line differ at the middle, the reveal closes the step, from the front to the - // frame line: under the higher sill and over the lower top. - for &(x, side, m, _) in cuts.iter().filter(|c| c.3) { - let other = grown(net, m, design.frame_m); - let a = 2.0 * x - side * (half - half_at(net, m)); - let span = |st: &Station, s: f64| { - let df = net.frame(m, s).z - st.z; - let own = (sill, top_at(&hole, x)?); - let them = top_at(&other, x - a).map(|t| (sill + df, t + df)); - Some(steps(own, them)) + // At a cut, a face closes the head's section, facing the other part: from the foot to the top, but the hole + // from the front to the frame line and the room from there to the back. Where the other part's head stands + // on the same line, it lies in that head's wall. + for &(x, side) in &cuts { + let solid = |st: &Station, (lo, hi): (Option, Option)| { + let (foot, top) = (foot - st.z, top(x).max(foot - st.z)); + match lo.zip(hi).filter(|(l, h)| h > l) { + Some((l, h)) => [(foot, l.clamp(foot, top)), (h.clamp(foot, top), top)], + None => [(foot, top), (top, top)], + } }; - if let (Some(a), Some(z)) = (span(&front, -design.recess_m), span(&ring, 0.0)) { + let floor = pieces.iter().find(|p| x >= p.0 - 1e-9 && x <= p.1 + 1e-9).map(|p| p.2); + let hole_span = (top_at(&hole, x).map(|_| sill), top_at(&hole, x)); + let room_span = (floor, top_at(&inner, x)); + for (s0, s1, span) in [(&front, &ring, hole_span), (&ring, &back, room_span)] { + let (a, z) = (solid(s0, span), solid(s1, span)); for i in 0..2 { - cut_face( - b, - (&front, &ring), - (x, a[i].0, a[i].1), - (x, z[i].0, z[i].1), - look.face, - front.out([-side, 0.0]), - ); + cut_face(b, (s0, s1), (x, a[i].0, a[i].1), (x, z[i].0, z[i].1), look.face, front.out([side, 0.0])); } } } @@ -265,7 +238,7 @@ pub fn faces f64>(b: &mut Builder, net: &Net, e: usize) { let run: Vec<_> = shell.iter().map(|p| (p.0, p.1, p.2, p.3, p.4)).collect(); tube::shell(b, net, &run, half, foot, look.shell, reach.then); if let Some(&(s, t, _, _, c, k)) = shell.last().filter(|_| reach.closed) { - b.clip(net.clips(c, (&s, &t)).iter().map(|c| c.0).collect()); + b.clip(net.clips(c, (&s, &t)).iter().map(|m| m.clip).collect()); end_face(b, net, (c, k), &t, foot, look.shell, flat([t.x - s.x, t.y - s.y])); b.clip(Vec::new()); } diff --git a/host/obc-trailview-parts/src/lib.rs b/host/obc-trailview-parts/src/lib.rs index 4cfde3d88..b9f47aa9c 100644 --- a/host/obc-trailview-parts/src/lib.rs +++ b/host/obc-trailview-parts/src/lib.rs @@ -123,12 +123,20 @@ pub struct End { pub left: Vec, pub right: Vec, pub foot: f64, - /// The metres to the left from its axis to the other tube of a pair. - pub mate: Option, + /// The other tube of a pair. + pub mate: Option, pub way: [i64; 2], pub shift: f64, - pub mate_way: Option<[i64; 2]>, - pub mate_shift: Option, +} + +/// The other tube of a pair: the metres to the left from the end's axis to its axis, and its `way`, `shift` and +/// `collar`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Mate { + pub across: f64, + pub way: [i64; 2], + pub shift: f64, + pub collar: f64, } impl End { @@ -156,11 +164,18 @@ impl End { left: if walls { row(tags, "left")? } else { Vec::new() }, right: if walls { row(tags, "right")? } else { Vec::new() }, foot: number(tags, "foot")?, - mate: pair.then(|| number(tags, "mate")).transpose()?, + mate: pair + .then(|| -> Result { + Ok(Mate { + across: number(tags, "mate")?, + way: vertex(tags, "mate_way")?, + shift: number(tags, "mate_shift")?, + collar: number(tags, "mate_collar")?, + }) + }) + .transpose()?, way: vertex(tags, "way")?, shift: number(tags, "shift")?, - mate_way: pair.then(|| vertex(tags, "mate_way")).transpose()?, - mate_shift: pair.then(|| number(tags, "mate_shift")).transpose()?, }) } @@ -251,7 +266,7 @@ fn near(square: [f64; 4], points: &[[f64; 2]], reach: f64) -> bool { /// The faces of the parts that a square draws: of each built end whose point it holds, and of each chord of a built /// chain whose `a` it holds, so each face draws in one square. pub fn meshes(square: [f64; 4], ends: &[End], chords: &[Chord], rules: &Rules) -> Mesh { - let net = Net::new(ends, chords, rules); + let net = Net::new(ends, chords, rules).meeting(); let mut b = mesh::Builder::new(|p| net.daylight(p)); for (e, end) in net.ends.iter().enumerate() { if net.built_end(e) && holds(square, end.at) { diff --git a/host/obc-trailview-parts/src/mesh.rs b/host/obc-trailview-parts/src/mesh.rs index 165461aba..faec01fb2 100644 --- a/host/obc-trailview-parts/src/mesh.rs +++ b/host/obc-trailview-parts/src/mesh.rs @@ -102,15 +102,24 @@ pub struct Paint { pub const PLAIN: Paint = Paint { across: 0.0, half: 0.0, sleepers: NO_SLEEPERS }; /// A vertical plane through two world points in plan that takes off the faces on one side of it: the side of `away`, -/// a world direction. +/// a world direction. With a bound, only on the side of a second vertical plane: the plane through a world point square +/// to a world direction, on the side that the direction points to. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Clip { pub a: [f64; 2], pub b: [f64; 2], pub away: [f64; 2], + pub bound: Option<([f64; 2], [f64; 2])>, } impl Clip { + /// How far a world point lies outside the bound, in world units: negative where the clip holds. + fn outside(&self, p: [f64; 3]) -> f64 { + let Some((at, dir)) = self.bound else { return -1.0 }; + let l = libm::hypot(dir[0], dir[1]).max(f64::MIN_POSITIVE); + -((p[0] - at[0]) * dir[0] + (p[1] - at[1]) * dir[1]) / l + } + /// How far a world point lies on the side that the plane takes off, in world units. fn side(&self, p: [f64; 3]) -> f64 { let n = [self.b[1] - self.a[1], self.a[0] - self.b[0]]; @@ -151,6 +160,7 @@ impl f64> Builder { /// The clips of the faces from now on. pub fn clip(&mut self, clips: Vec) { + debug_assert!(clips.len() <= 2, "a key of a cut vertex holds the planes of two clips"); if clips != self.clips { (self.clips, self.cuts) = (clips, HashMap::new()); } @@ -173,7 +183,7 @@ impl f64> Builder { (self.points.len() - 1) as u32 } - /// The vertex where the plane of clip k cuts the edge from vertex i to j, which lie at `di` and `dj` from it. + /// The vertex where plane k cuts the edge from vertex i to j, which lie at `di` and `dj` past it. fn cut(&mut self, k: usize, (i, di): (u32, f64), (j, dj): (u32, f64)) -> u32 { let key = (i.min(j) as usize * 4 + k, i.max(j) as usize); if let Some(&v) = self.cuts.get(&key) { @@ -188,32 +198,47 @@ impl f64> Builder { v } - /// A triangle in its winding, without its parts past the planes of the clips. + /// A convex polygon's parts on the near side of plane k and past it (more than a hundredth of a world unit), each + /// in the polygon's winding; where an edge crosses the plane, a vertex of both. + fn halves(&mut self, k: usize, poly: &[u32], past: impl Fn([f64; 3]) -> f64) -> (Vec, Vec) { + let d: Vec = poly.iter().map(|&v| past(self.points[v as usize]) - 0.01).collect(); + if d.iter().all(|&x| x <= 0.0) { + return (poly.to_vec(), Vec::new()); + } + if d.iter().all(|&x| x > 0.0) { + return (Vec::new(), poly.to_vec()); + } + let (mut near, mut far) = (Vec::with_capacity(poly.len() + 1), Vec::with_capacity(poly.len() + 1)); + for i in 0..poly.len() { + let j = (i + 1) % poly.len(); + if d[i] > 0.0 { &mut far } else { &mut near }.push(poly[i]); + if (d[i] > 0.0) != (d[j] > 0.0) { + let v = self.cut(k, (poly[i], d[i]), (poly[j], d[j])); + near.push(v); + far.push(v); + } + } + (near, far) + } + + /// A triangle in its winding, without its parts past the planes of the clips. Plane 2k is the cut of clip k, plane + /// 2k + 1 its bound; `clips` holds at most one clip per side, so a key of a cut vertex holds four planes. fn emit(&mut self, t: [u32; 3]) { - let mut poly = t.to_vec(); + let mut polys = vec![t.to_vec()]; for k in 0..self.clips.len() { let clip = self.clips[k]; - let d: Vec = poly.iter().map(|&v| clip.side(self.points[v as usize])).collect(); - // Within a hundredth of a world unit of the plane, a point lies on it. - let off = |x: f64| x > 0.01; - if !d.iter().any(|&x| off(x)) { - continue; - } - // The corners on the near side, and the points where an edge crosses the plane, in the winding. - let mut keep = Vec::with_capacity(poly.len() + 1); - for i in 0..poly.len() { - let j = (i + 1) % poly.len(); - if !off(d[i]) { - keep.push(poly[i]); - } - if off(d[i]) != off(d[j]) { - keep.push(self.cut(k, (poly[i], d[i]), (poly[j], d[j]))); - } + let mut next = Vec::with_capacity(polys.len() + 1); + for poly in polys { + let (held, free) = self.halves(2 * k + 1, &poly, |p| clip.outside(p)); + let (kept, _) = self.halves(2 * k, &held, |p| clip.side(p)); + next.extend([free, kept].into_iter().filter(|p| p.len() >= 3)); } - poly = keep; + polys = next; } - for k in 1..poly.len().saturating_sub(1) { - self.indices.extend([poly[0], poly[k], poly[k + 1]]); + for poly in polys { + for k in 1..poly.len() - 1 { + self.indices.extend([poly[0], poly[k], poly[k + 1]]); + } } } diff --git a/host/obc-trailview-parts/src/tests.rs b/host/obc-trailview-parts/src/tests.rs index f3ef1d9f9..54a47810d 100644 --- a/host/obc-trailview-parts/src/tests.rs +++ b/host/obc-trailview-parts/src/tests.rs @@ -668,7 +668,8 @@ fn pair(apart: f64, dz: f64) -> (Vec, Vec) { let mut ends = vec![end(0.0, 0.0, 500.0, 0.0, 6.0), end(40.0, 0.0, 500.2, pi, 3.0)]; // Into the tubes from the west the second lies to the left, from the east to the right. for (e, mate) in ends.iter_mut().zip([apart, -apart]) { - (e.part, e.mate, e.mate_way, e.mate_shift) = (Part::Pair, Some(mate), Some([1, 1]), Some(0.0)); + e.part = Part::Pair; + e.mate = Some(Mate { across: mate, way: [1, 1], shift: 0.0, collar: e.collar }); } let mut chords = [lane(0.0, 500.0), lane(apart, 500.0 + dz)].concat(); chords.iter_mut().for_each(|c| c.ends = [Some(Part::Pair); 2]); @@ -861,3 +862,71 @@ fn a_rim_hugs_its_opening_and_a_covered_free_end_is_closed() { } } } + +/// Arches at both ends of road tubes along polylines of metres east and north at the floor 500 m: an end at the first +/// vertex leads along the first chord, one at the last vertex back along the last. +fn tubes(lines: &[&[[f64; 2]]]) -> (Vec, Vec) { + let (mut ends, mut chords) = (Vec::new(), Vec::new()); + for line in lines { + let n = line.len(); + let heading = |a: [f64; 2], b: [f64; 2]| libm::atan2(-(b[1] - a[1]), b[0] - a[0]); + ends.push(end(line[0][0], line[0][1], 500.0, heading(line[0], line[1]), 6.0)); + ends.push(end(line[n - 1][0], line[n - 1][1], 500.0, heading(line[n - 1], line[n - 2]), 6.0)); + let mut along = 0.0; + for w in line.windows(2) { + chords.push(chord([w[0][0], w[0][1], 500.0], [w[1][0], w[1][1], 500.0], 5.0, along)); + along += libm::hypot(w[1][0] - w[0][0], w[1][1] - w[0][1]); + } + } + (ends, chords) +} + +#[test] +fn two_tubes_meet_only_where_both_are_and_a_cut_head_is_closed() { + let rules = Rules::embedded(); + let faces_of = + |(ends, chords): &(Vec, Vec)| solid(&meshes([0.0, 0.0, 1.07e9, 1.07e9], ends, chords, rules)); + let north = [0.0, 1.0, 0.0]; + // Staggered openings: a tube 7 m north starts 3 m after the first, so their rooms overlap from there on. Before + // it, the first tube keeps its wall; after it, a way north meets the second's far wall; a way west in the first's + // wall, from the second's room, meets the face that closes the first's shell where its cut begins. + let staggered = tubes(&[&[[0.0, 0.0], [10.0, 0.0], [40.0, 0.0]], &[[3.0, 7.0], [10.0, 7.0], [40.0, 7.0]]]); + let faces = faces_of(&staggered); + for east in [0.5, 1.5, 2.5, 2.95] { + let got = hit(&faces, [east, 0.0, 502.5], north, 30.0); + assert!(got.is_some_and(|h| h.1 && h.0 < 5.1), "staggered, {east} m east: {got:?}"); + } + for east in [5.0, 15.0] { + let got = hit(&faces, [east, 0.0, 502.5], north, 30.0); + assert!(got.is_some_and(|h| h.1 && h.0 > 11.0), "staggered, {east} m east: {got:?}"); + } + for up in [1.0, 2.0] { + let got = hit(&faces, [6.0, 4.7, 500.0 + up], [-1.0, 0.0, 0.0], 30.0); + assert!(got.is_some_and(|h| h.1 && h.0 < 3.2), "staggered, the first's shell {up} m up: {got:?}"); + } + // A tube beside the first for 20 m that turns away north: past the turn, the first keeps its wall. + let away = tubes(&[&[[0.0, 0.0], [100.0, 0.0]], &[[0.0, 7.0], [20.0, 7.0], [50.0, 40.0]]]); + let faces = faces_of(&away); + for east in [30.0, 60.0, 90.0] { + let got = hit(&faces, [east, 0.0, 502.5], north, 30.0); + assert!(got.is_some_and(|h| h.1 && h.0 < 5.1), "turns away, {east} m east: {got:?}"); + } + assert!(hit(&faces, [10.0, 0.0, 502.5], north, 30.0).is_some_and(|h| h.1 && h.0 > 11.0), "turns away, 10 m east"); + // Two arches on one frame line, the first's head wall 2 m taller: over the lower wall, a way to the taller one + // meets the face that closes it at the middle. + let mut taller = row(&[0.0, 7.0]); + taller.0[0].face = 9.1; + let faces = faces_of(&taller); + for up in [7.6, 8.6] { + let got = hit(&faces, [0.15, 7.0, 500.0 + up], [0.0, -1.0, 0.0], 30.0); + assert!(got.is_some_and(|h| h.1 && (h.0 - 3.5).abs() < 0.2), "taller, {up} m up: {got:?}"); + } + // Two arches whose frame lines lie 3 m apart: the first's tube crosses the second's line, so the second's head + // ends at the middle, closed over the first's tube; the second does not cross the first's line, so the first's + // head wall stays whole. + let faces = faces_of(&staggered); + let got = hit(&faces, [3.15, 0.0, 506.2], north, 30.0); + assert!(got.is_some_and(|h| h.1 && (h.0 - 3.5).abs() < 0.2), "frame lines apart, the second's head: {got:?}"); + let got = hit(&faces, [-5.0, 5.0, 506.2], [1.0, 0.0, 0.0], 30.0); + assert!(got.is_some_and(|h| h.1 && h.0 < 5.1), "frame lines apart, the first's head: {got:?}"); +} diff --git a/host/obc-trailview-parts/src/tube.rs b/host/obc-trailview-parts/src/tube.rs index 40d9a98b6..e39fa135d 100644 --- a/host/obc-trailview-parts/src/tube.rs +++ b/host/obc-trailview-parts/src/tube.rs @@ -4,7 +4,7 @@ use std::collections::HashMap; use crate::mesh::{flagged, flat, left_of, outline, Builder, Clip, Corner, Paint, Station, BORE, LAMP, PAINT}; -use crate::{built, metres_per_unit, Bore, Chord, End, Part, Rules, Section}; +use crate::{built, metres_per_unit, Bore, Chord, End, Mate, Part, Rules, Section}; /// An end's point lies within this of the vertex of its tube's chord. const END_M: f64 = 0.5; @@ -48,19 +48,46 @@ pub struct Net<'a> { end_at: HashMap<(usize, usize), usize>, /// Per end, the rise of its floor per metre in, over its first `face_m`. slope: Vec, - /// Per chord, its tube: the chords that its vertices join. + /// Per chord, its tube: the chords that its vertices join; made by `meeting`. tube: Vec, /// The built chords by the cells (`CELL_M`) that they come within reach of; a cell's key is its two indices' bits, - /// so the WASM holds the code of one map of that type. + /// so the WASM holds the code of one map of that type. Made by `meeting`. cells: HashMap<[u64; 2], Vec>, /// The world units of a cell. cell: f64, } +/// Where a station across chord c meets another tube (`Net::meets`), on one side: the metres across the station to +/// the middle between their walls and to the other's axis on its line, the other's chord, and the other's floor (a +/// world height) and its metres across from its axis at that middle. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Cut { + pub x: f64, + pub axis: f64, + pub other: usize, + pub floor: f64, + pub across: f64, +} + +/// Where a piece of a tube meets another tube on one side: the clip that takes off the other's side, the stations +/// that bound the stretch where both meet with their cuts, and the station where the clip ends inside the piece. +#[derive(Clone, Copy, Debug)] +pub struct Meeting { + pub clip: Clip, + pub from: (Station, Cut), + pub to: (Station, Cut), + pub end: Option, +} + /// The side of a cell of `Net::cells`, in metres. const CELL_M: f64 = 16.0; /// Two tubes that meet at a cut each run this far past it: two world units, as each vertex is rounded to one. pub const OVERLAP_M: f64 = 0.05; +/// A station meets a tube this far past the vertices of its chords: the openings of a pair lie on one frame line within +/// a few centimetres of the rounding of their record. +pub const MEET_PAST_M: f64 = 0.1; +/// Halvings of a piece to find where another tube starts or ends on it: to a millimetre of a 10 m chord. +const MEET_HALVES: usize = 14; impl<'a> Net<'a> { pub fn new(inputs: &[End], chords: &'a [Chord], rules: &'a Rules) -> Net<'a> { @@ -84,10 +111,10 @@ impl<'a> Net<'a> { let mut ends = inputs.to_vec(); let mut mate = vec![None; ends.len()]; for (e, end) in inputs.iter().enumerate() { - let Some(across) = end.mate.filter(|_| end.part == Part::Pair) else { continue }; + let Some(other) = end.mate.filter(|_| end.part == Part::Pair) else { continue }; let (l, m) = (left_of(end.way_in()), metres_per_unit(end.at[1])); - let p = [end.at[0] + l[0] * across / m, end.at[1] + l[1] * across / m]; - let (Some((c, k)), Some(way), Some(shift)) = (nearest(p), end.mate_way, end.mate_shift) else { continue }; + let p = [end.at[0] + l[0] * other.across / m, end.at[1] + l[1] * other.across / m]; + let Some((c, k)) = nearest(p) else { continue }; let (chord, z) = (&chords[c], vertex(&chords[c], k)[2]); mate[e] = Some(ends.len()); mate.push(Some(e)); @@ -103,11 +130,10 @@ impl<'a> Net<'a> { left: end.left.iter().map(|&v| up(v)).collect(), right: end.right.iter().map(|&v| up(v)).collect(), foot: up(end.foot), - mate: Some(-across), - way, - shift, - mate_way: Some(end.way), - mate_shift: Some(end.shift), + collar: other.collar, + mate: Some(Mate { across: -other.across, way: end.way, shift: end.shift, collar: end.collar }), + way: other.way, + shift: other.shift, ..end.clone() }); } @@ -137,40 +163,6 @@ impl<'a> Net<'a> { }; let run = rules.design.face_m; net.slope = (0..n).map(|e| net.floor_at(e, run).map_or(0.0, |(s, z)| (z - net.ends[e].z) / s)).collect(); - // The tubes: each chord takes the least tube of the chords at its vertices, until none changes. - net.tube = (0..chords.len()).collect(); - loop { - let mut changed = false; - for list in net.at.values() { - let least = list.iter().map(|&c| net.tube[c]).min().unwrap_or(0); - for &c in list { - if net.tube[c] != least { - (net.tube[c], changed) = (least, true); - } - } - } - if !changed { - break; - } - } - // The cells of the built chords, each grown by the farthest reach of a cut. - if let Some(first) = chords.first() { - net.cell = CELL_M / metres_per_unit(first.a[1]); - let shell = rules.ladder.bake.shell_m; - let reach = 2.0 * chords.iter().map(|c| c.half + shell).fold(0.0, f64::max) / metres_per_unit(first.a[1]); - let cell = net.cell; - let at = |v: f64| libm::floor(v / cell) as i64; - let key = |x: i64, y: i64| [x as u64, y as u64]; - for (c, chord) in chords.iter().enumerate().filter(|&(c, _)| built(&chords[c].ends)) { - let lo = [chord.a[0].min(chord.b[0]) - reach, chord.a[1].min(chord.b[1]) - reach]; - let hi = [chord.a[0].max(chord.b[0]) + reach, chord.a[1].max(chord.b[1]) + reach]; - for x in at(lo[0])..=at(hi[0]) { - for y in at(lo[1])..=at(hi[1]) { - net.cells.entry(key(x, y)).or_default().push(c); - } - } - } - } net } @@ -340,14 +332,81 @@ impl<'a> Net<'a> { self.ends[e].part == Part::Free && self.ends[e].collar <= 0.0 } - /// Where a station across chord c meets other built tubes whose shells overlap its own there: on each side (to the - /// right, to the left) the nearest, at the middle between their walls on the station's line. A tube that lies over - /// or under it by more than half their heights does not meet it. - pub fn cuts(&self, c: usize, st: &Station) -> [Option; 2] { + /// The same net, ready for `meets`: the tube of each chord (one walk over the vertices, a union of the chords at + /// each) and the cells of the built chords. + pub fn meeting(mut self) -> Self { + let n = self.chords.len(); + let mut parent: Vec = (0..n).collect(); + let root = |p: &mut Vec, mut i: usize| { + while p[i] != i { + p[i] = p[p[i]]; + i = p[i]; + } + i + }; + for list in self.at.values() { + let r = root(&mut parent, list[0]); + for &c in &list[1..] { + let o = root(&mut parent, c); + if o != r { + parent[o] = r; + } + } + } + self.tube = (0..n).map(|i| root(&mut parent, i)).collect(); + // The cells of the built chords, each grown by the farthest reach of a tube's cut. + let Some(first) = self.chords.first() else { return self }; + let m = metres_per_unit(first.a[1]); + self.cell = CELL_M / m; + let shell = self.rules.ladder.bake.shell_m; + let reach = 2.0 * self.chords.iter().map(|c| c.half + shell).fold(0.0, f64::max) / m; + let cell = self.cell; + let at = |v: f64| libm::floor(v / cell) as i64; + for (c, chord) in self.chords.iter().enumerate().filter(|&(_, ch)| built(&ch.ends)) { + let lo = [chord.a[0].min(chord.b[0]) - reach, chord.a[1].min(chord.b[1]) - reach]; + let hi = [chord.a[0].max(chord.b[0]) + reach, chord.a[1].max(chord.b[1]) + reach]; + for x in at(lo[0])..=at(hi[0]) { + for y in at(lo[1])..=at(hi[1]) { + self.cells.entry([x as u64, y as u64]).or_default().push(c); + } + } + } + self + } + + /// Where the line of a station across chord c meets another built tube, on each side (to the right, to the left) + /// the nearest: where the other's chord crosses the line, or passes within `past` metres of its vertices, within + /// `reach` of that side (the own part's metres across from its axis) and the other's half and shell, at the floor's + /// level within half their heights. The cut is at the middle between the two tubes' walls, measured square to each + /// tube's own chord, so both find one plane at any angle. A tube meets another for its inside and shell with the + /// reach of its shell; a head with the reach of its wall, and so where the other crosses its frame line. Needs + /// `meeting`. + pub fn meets(&self, c: usize, st: &Station, reach: [f64; 2], past: f64) -> [Option; 2] { let (own, shell) = (&self.chords[c], self.rules.ladder.bake.shell_m); - let key = [libm::floor(st.x / self.cell) as i64 as u64, libm::floor(st.y / self.cell) as i64 as u64]; + let m = metres_per_unit(st.y); + let cell = |dx: i64, dy: i64| { + [(libm::floor(st.x / self.cell) as i64 + dx) as u64, (libm::floor(st.y / self.cell) as i64 + dy) as u64] + }; + // The cells round the station's, where a reach passes the cell's growth. + let ring = i64::from(reach.iter().fold(0.0f64, |r, &x| r.max(x)) > own.half + shell + 1e-9); + let mut seen: Vec = Vec::new(); + for dx in -ring..=ring { + for dy in -ring..=ring { + seen.extend( + self.cells.get(&cell(dx, dy)).into_iter().flatten().filter(|&&o| self.tube[o] != self.tube[c]), + ); + } + } + seen.sort_unstable(); + seen.dedup(); + let unit = |d: [f64; 2]| { + let l = libm::hypot(d[0], d[1]).max(f64::MIN_POSITIVE); + [d[0] / l, d[1] / l] + }; + let dot = |a: [f64; 2], b: [f64; 2]| a[0] * b[0] + a[1] * b[1]; + let (own_dir, line) = (unit([own.b[0] - own.a[0], own.b[1] - own.a[1]]), [st.ax, st.ay]); let mut best: [Option; 2] = [None, None]; - for &o in self.cells.get(&key).into_iter().flatten().filter(|&&o| self.tube[o] != self.tube[c]) { + for o in seen { let other = &self.chords[o]; // The station's line meets the chord: st + x·across = a + u·(b − a). let (dx, dy) = (other.b[0] - other.a[0], other.b[1] - other.a[1]); @@ -357,51 +416,85 @@ impl<'a> Net<'a> { } let (px, py) = (other.a[0] - st.x, other.a[1] - st.y); let (x, u) = ((dx * py - dy * px) / det, (st.ax * py - st.ay * px) / det); - // A metre past either vertex still counts: the two openings of a pair lie on their frame line within the - // rounding of the record. - let past = 1.0 / direction(other).1.max(1.0); - let floor = other.a[2] + u * (other.b[2] - other.a[2]); + let past = past / direction(other).1.max(MEET_PAST_M); + let side = usize::from(x > 0.0); + let floor_at = |u: f64| other.a[2] + u.clamp(0.0, 1.0) * (other.b[2] - other.a[2]); if !(-past..=1.0 + past).contains(&u) - || x.abs() > own.half + other.half + 2.0 * shell - || (floor - st.z).abs() > (own.height + other.height) / 2.0 + || x.abs() > reach[side] + other.half + shell + || (floor_at(u) - st.z).abs() > (own.height + other.height) / 2.0 + || best[side].is_some_and(|b| b.axis.abs() <= x.abs()) { continue; } - let side = &mut best[usize::from(x > 0.0)]; - if side.is_none_or(|b| x.abs() < b.axis.abs()) { - let middle = (x + x.signum() * (own.half - other.half)) / 2.0; - *side = Some(Cut { x: middle, axis: x, other: o, floor }); + // Signed metres from each tube's axis toward the other: linear along the station's line. + let o_dir = unit([dx, dy]); + let mut na = unit(left_of(own_dir)); + if dot(na, line) * x < 0.0 { + na = [-na[0], -na[1]]; + } + let mut nb = unit(left_of(o_dir)); + if dot(nb, [st.x - other.a[0], st.y - other.a[1]]) < 0.0 { + nb = [-nb[0], -nb[1]]; } + let (a0, ka) = (dot([st.x - own.a[0], st.y - own.a[1]], na) * m, dot(line, na) * m); + let (b0, kb) = (dot([st.x - other.a[0], st.y - other.a[1]], nb) * m, dot(line, nb) * m); + if (ka - kb).abs() <= 1e-9 { + continue; + } + let middle = (b0 - a0 + own.half - other.half) / (ka - kb); + let p = [st.x + middle * st.ax, st.y + middle * st.ay]; + let len = libm::hypot(dx, dy).max(f64::MIN_POSITIVE); + let along = dot([p[0] - other.a[0], p[1] - other.a[1]], o_dir) / len; + let across = (b0 + kb * middle).abs(); + best[side] = Some(Cut { x: middle, axis: x, other: o, floor: floor_at(along), across }); } best } - /// The clips of chord c from station s to t at its cuts, on each side where it has one: the plane through them - /// that takes off the other tube's side, and the cuts; where one station has none, the plane through the other's - /// along the chord. - pub fn clips(&self, c: usize, (s, t): (&Station, &Station)) -> Vec<(Clip, Option, Option)> { - let (at_s, at_t) = (self.cuts(c, s), self.cuts(c, t)); + /// Where station s and t across chord c meet another tube for its inside and shell (`meets` with the reach of its + /// shell): on each side, the clip that takes off the other's side between the two stations' cuts. Where only one + /// station meets it, the clip holds from that station to where the other tube starts or ends on the piece (found + /// by halves, with no metres past its vertices), and no farther. + pub fn clips(&self, c: usize, (s, t): (&Station, &Station)) -> Vec { + let reach = self.chords[c].half + self.rules.ladder.bake.shell_m; + let at = |u: f64, side: usize, past: f64| { + let st = s.mix(t, u); + self.meets(c, &st, [reach; 2], past)[side].map(|cut| (st, cut)) + }; let mut out = Vec::new(); - for (cs, ct) in at_s.into_iter().zip(at_t) { - let (st, cut) = match (cs, ct) { - (Some(x), _) => (s, x), - (None, Some(y)) => (t, y), + for side in 0..2 { + let ends = (at(0.0, side, MEET_PAST_M), at(1.0, side, MEET_PAST_M)); + let (from, to, end) = match ends { + (Some(a), Some(z)) => (a, z, None), (None, None) => continue, + (a, z) => { + // From the station that meets, halves to the last point that still meets. + let (mut lo, mut hi) = if a.is_some() { (0.0, 1.0) } else { (1.0, 0.0) }; + for _ in 0..MEET_HALVES { + let mid = (lo + hi) / 2.0; + if at(mid, side, 0.0).is_some() { + lo = mid; + } else { + hi = mid; + } + } + let Some(last) = at(lo, side, 0.0) else { continue }; + let first = a.or(z).expect("one station meets"); + if (lo - if a.is_some() { 0.0 } else { 1.0 }).abs() * direction(&self.chords[c]).1 < MEET_PAST_M { + continue; + } + (first, last, Some(last.0)) + } }; - let (far, near) = (st.at([cut.axis, 0.0]), st.at([cut.x, 0.0])); + let (far, near) = (from.0.at([from.1.axis, 0.0]), from.0.at([from.1.x, 0.0])); let away = [far[0] - near[0], far[1] - near[1]]; // The two tubes overlap by `OVERLAP_M` at the plane, so the rounding of their vertices opens no gap there. let l = libm::hypot(away[0], away[1]).max(f64::MIN_POSITIVE); - let d = OVERLAP_M / metres_per_unit(st.y) / l; + let d = OVERLAP_M / metres_per_unit(s.y) / l; let shift = |p: [f64; 3]| [p[0] + away[0] * d, p[1] + away[1] * d]; - let (a, z) = match (cs, ct) { - (Some(x), Some(y)) => (shift(s.at([x.x, 0.0])), shift(t.at([y.x, 0.0]))), - _ => { - let a = shift(near); - (a, [a[0] + t.x - s.x, a[1] + t.y - s.y]) - } - }; - out.push((Clip { a, b: z, away }, cs, ct)); + let (a, z) = (shift(from.0.at([from.1.x, 0.0])), shift(to.0.at([to.1.x, 0.0]))); + let bound = end.map(|e| ([e.x, e.y], [from.0.x - e.x, from.0.y - e.y])); + out.push(Meeting { clip: Clip { a, b: z, away, bound }, from, to, end }); } out } @@ -456,16 +549,6 @@ pub fn inward(a: Corner, b: Corner, spring: f64) -> Corner { [-(a[0] + b[0]), -(a[1] + b[1] - 2.0 * spring)] } -/// Where a station meets another tube (`Net::cuts`): the metres across the station to the middle between their walls, -/// and the other tube there: its chord, the floor at that point (a world height) and its axis across the station. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct Cut { - pub x: f64, - pub axis: f64, - pub other: usize, - pub floor: f64, -} - /// The top of an outline at `x` across, the highest of its segments there; None outside it. pub fn top_at(o: &[Corner], x: f64) -> Option { let mut top: Option = None; @@ -530,8 +613,8 @@ pub fn inside f64>(b: &mut Builder, net: &Net, c: usize) { let bore = |colour: u32| flagged(colour, BORE); let across = |c: Corner| s.mix(&t, 0.5).out(c); // Of two tubes that meet, each draws its side of the middle between their walls. - let cuts = net.clips(c, (&s, &t)); - b.clip(cuts.iter().map(|c| c.0).collect()); + let meetings = net.clips(c, (&s, &t)); + b.clip(meetings.iter().map(|m| m.clip).collect()); // A box section is cast: its rock bore is lined. let cast = chord.section == Section::Box; let (wall, vault) = match bore_of { @@ -616,10 +699,11 @@ pub fn inside f64>(b: &mut Builder, net: &Net, c: usize) { let mut oo = inside_outline(net, other); let (op, m) = (floor_pieces(net, other), oo.len() - 1); (oo[0][1], oo[m][1]) = (op[0].2, op[op.len() - 1].2); - let (xl, df) = (cut.x - cut.axis, cut.floor - st.z); + let (xl, df) = (cut.across, cut.floor - st.z); Some(steps(own, f(&op, xl).zip(top_at(&oo, xl)).map(|(lo, hi)| (lo + df, hi + df)))) }; - for (cs, ct) in cuts.iter().filter_map(|c| c.1.zip(c.2)) { + for m in &meetings { + let ((s, cs), (t, ct)) = (m.from, m.to); if let (Some([ls, us]), Some([lt, ut])) = (span(&s, &cs), span(&t, &ct)) { let out = across([-cs.axis.signum(), 0.0]); cut_face(b, (&s, &t), (cs.x, ls.0, ls.1), (ct.x, lt.0, lt.1), bore(inside.walk), out); @@ -694,19 +778,29 @@ pub fn shell f64>( let next_of = |i: usize| pieces.get(i + 1).map(|p| (p.2, p.3)).or(meets.lower.filter(|_| last(i))); let outer = |st: &Station, h: f64, section: Section| shell_outline(net, section, half, h, foot - st.z); for (i, &(ref s, ref t, ref h, ref section, c)) in pieces.iter().enumerate() { - let cuts = net.clips(c, (s, t)); - b.clip(cuts.iter().map(|c| c.0).collect()); - for (cs, ct) in cuts.iter().filter_map(|c| c.1.zip(c.2)) { + let meetings = net.clips(c, (s, t)); + // Where a clip ends inside the piece, a face closes the shell past the middle, toward the clip. It lies on the + // clip's bound, so it draws unclipped. + b.clip(Vec::new()); + for m in &meetings { + if let Some(e) = m.end { + let out = flat([m.from.0.x - e.x, m.from.0.y - e.y]); + end_section(b, net, c, (*h, *section, half, foot), &e, (m.to.1.x, m.from.1.axis.signum()), colour, out); + } + } + b.clip(meetings.iter().map(|m| m.clip).collect()); + for m in &meetings { + let ((ms, cs), (mt, ct)) = (m.from, m.to); // The other tube's shell top at the cut, over this station's floor. let top = |st: &Station, cut: &Cut| { let own = top_at(&outer(st, *h, *section), cut.x)?; let other = &net.chords[cut.other]; let o = shell_outline(net, other.section, other.half, other.height, foot - cut.floor); - Some((own, top_at(&o, cut.x - cut.axis)? + cut.floor - st.z)) + Some((own, top_at(&o, cut.across)? + cut.floor - st.z)) }; - if let (Some((os, xs)), Some((ot, xt))) = (top(s, &cs), top(t, &ct)) { - let out = s.mix(t, 0.5).out([cs.axis.signum(), 0.0]); - cut_face(b, (s, t), (cs.x, xs.min(os), os), (ct.x, xt.min(ot), ot), colour, out); + if let (Some((os, xs)), Some((ot, xt))) = (top(&ms, &cs), top(&mt, &ct)) { + let out = ms.mix(&mt, 0.5).out([cs.axis.signum(), 0.0]); + cut_face(b, (&ms, &mt), (cs.x, xs.min(os), os), (ct.x, xt.min(ot), ot), colour, out); } } let (sp, top) = (spring(net, *section, *h), shell_spring(net, *section, *h)); @@ -748,6 +842,59 @@ pub fn shell f64>( b.clip(Vec::new()); } +/// The face at station `st` across chord c that closes a shell where its clip ends: the shell's section past the +/// middle `x` on the side `side` (1 to the left), between its outside and its room, from its foot up; facing `out`. +#[allow(clippy::too_many_arguments)] +fn end_section f64>( + b: &mut Builder, + net: &Net, + c: usize, + (h, section, half, foot): (f64, Section, f64, f64), + st: &Station, + (x, side): (f64, f64), + colour: u32, + out: [f64; 3], +) { + let chord = &net.chords[c]; + // In the frame mirrored to the side, so the part past the middle runs to rising metres across. + let mirror = |o: Vec| { + let mut m: Vec = o.into_iter().map(|p| [side * p[0], p[1]]).collect(); + if side < 0.0 { + m.reverse(); + } + m + }; + let xm = side * x; + let base = foot - st.z; + let shell = mirror(shell_outline(net, section, half, h, base)); + let Some(top) = top_at(&shell, xm) else { return }; + let past = |o: &[Corner]| o.iter().copied().filter(|p| p[0] > xm + 1e-9).collect::>(); + let mut outside = vec![[xm, top]]; + outside.extend(past(&shell)); + outside.push([xm, base]); + let pieces = floor_pieces(net, chord); + let mut room = inside_outline(net, chord); + let n = room.len(); + (room[0][1], room[n - 1][1]) = (pieces[0].2, pieces[pieces.len() - 1].2); + let room = mirror(room); + let mut floor: Vec = pieces.iter().flat_map(|p| [[p.0, p.2], [p.1, p.2]]).collect(); + floor.dedup(); + let floor = mirror(floor); + let inner = match (top_at(&room, xm), floor.iter().rev().find(|p| p[0] <= xm + 1e-9)) { + (Some(roof), Some(&[_, level])) => { + let mut i = vec![[xm, roof]]; + i.extend(past(&room)); + i.extend(past(&floor).into_iter().rev()); + i.push([xm, level]); + i.dedup(); + i + } + _ => vec![[xm, top], [xm, base]], + }; + let back = |o: Vec| o.into_iter().map(|p| [side * p[0], p[1]]).collect::>(); + b.strip((st, &back(outside)), (st, &back(inner)), colour, out); +} + #[cfg(test)] pub(crate) fn outline_of(net: &Net, c: usize) -> Vec { inside_outline(net, &net.chords[c]) From 570f77d307afe8d1a42f11380f10891f9bfb5c13 Mon Sep 17 00:00:00 2001 From: timohueser Date: Sat, 21 Nov 2026 21:40:44 +0100 Subject: [PATCH 13/20] trailview-features: each tube of a pair has its own collar; cap and foot over both tubes The record of a pair writes `mate_collar`; the device stops the ground plan's stamps of each way at its own tube's collar. The face of a pair holds its band over the higher crown and its cap over the lower; the foot reads both collars and both floors. One map of the opening at each tube end serves `whole` and `spans`. Co-Authored-By: Claude Opus 5.5 --- .../web/src/lib/trailview/structures/parts.ts | 4 +- .../src/parts/ladder.rs | 84 ++++++++++--------- host/obc-trailview-features/src/parts/mod.rs | 3 +- .../obc-trailview-features/src/parts/tests.rs | 13 ++- 4 files changed, 59 insertions(+), 45 deletions(-) diff --git a/builder/web/src/lib/trailview/structures/parts.ts b/builder/web/src/lib/trailview/structures/parts.ts index 4a360741d..5df07d33b 100644 --- a/builder/web/src/lib/trailview/structures/parts.ts +++ b/builder/web/src/lib/trailview/structures/parts.ts @@ -136,10 +136,10 @@ export function partStamps(list: Feature[], tile: Node, lines: Line[]): PartStam }; for (const { kind, tags } of list) { if (kind !== 'tunnel-end') continue; - for (const [way, shift] of [[tags.way, tags.shift], [tags.mate_way, tags.mate_shift]]) { + for (const [way, shift, collar] of [[tags.way, tags.shift, tags.collar], [tags.mate_way, tags.mate_shift, tags.mate_collar]]) { // `way` is in the frame of the ground plan, 16 units to a world unit. const [x, y] = way?.split(' ').map(Number) ?? []; - for (const [line, end] of at.get(`${x / 16},${y / 16}`) ?? []) stop(line, end, Number(shift) + Number(tags.collar) + COVER_START_M); + for (const [line, end] of at.get(`${x / 16},${y / 16}`) ?? []) stop(line, end, Number(shift) + Number(collar) + COVER_START_M); } } return out; diff --git a/host/obc-trailview-features/src/parts/ladder.rs b/host/obc-trailview-features/src/parts/ladder.rs index 56192e6df..dd3ccf31b 100644 --- a/host/obc-trailview-features/src/parts/ladder.rs +++ b/host/obc-trailview-features/src/parts/ladder.rs @@ -15,8 +15,9 @@ use super::{along_dir, built_openings, counts, distance, first_way_m, left_of, o pub use obc_trailview_parts::Part as Kind; /// The numbers of a drawn opening (Plan 8 of the design): metres, `left` and `right` per metre out from the frame's -/// outer edge, and in a pair the mate's opening and the metres to its axis to the left; `height` is the inside height -/// of the tube's chord there; `heading` is square to its frame line, into the tube of the opening farther in. +/// outer edge, and in a pair the mate's opening, the metres to its axis to the left and its collar; `height` is the +/// inside height of the tube's chord there; `heading` is square to its frame line, into the tube of the opening farther +/// in. #[derive(Clone, Debug, PartialEq)] pub(crate) struct Numbers { pub heading: f64, @@ -26,7 +27,7 @@ pub(crate) struct Numbers { pub left: Vec, pub right: Vec, pub foot: f64, - pub mate: Option<(usize, f64)>, + pub mate: Option<(usize, f64, f64)>, } /// An opening's decision: every kind that fits in the order of the rungs, the part of the end (the first; also the @@ -265,12 +266,12 @@ pub(crate) fn decide(tubes: &[Tube], openings: &mut [Opening], input: &Input, me // has a part at both of its ends. let mut mate: Vec> = vec![None; n]; let is_hill = |i: usize| hill.contains(&i); - let whole: Vec = (0..tubes.len()) - .map(|t| { - let at = |end: usize| openings.iter().position(|o| o.tube == t && o.end == end); - (0..2).all(|end| at(end).is_some_and(|i| !kinds[i].is_empty())) - }) - .collect(); + // The opening at each end of each tube. + let mut at_end: Vec<[Option; 2]> = vec![[None; 2]; tubes.len()]; + for (i, o) in openings.iter().enumerate() { + at_end[o.tube][o.end].get_or_insert(i); + } + let whole: Vec = at_end.iter().map(|e| e.iter().all(|i| i.is_some_and(|i| !kinds[i].is_empty()))).collect(); for x in &near { let (a, c) = (x.a, x.b); if !is_hill(a) || !is_hill(c) || mate[a].is_some() || mate[c].is_some() { @@ -378,17 +379,17 @@ pub(crate) fn decide(tubes: &[Tube], openings: &mut [Opening], input: &Input, me let refitted = (0..n).filter(|&i| kinds[i].first().copied() != before[i]).count(); // The floor of each tube with a part, from opening to opening; an end with no opening holds the end vertex. Its // chord at an opening gives the opening its inside height. - let spans: Vec> = (0..tubes.len()) - .map(|t| { - let at = |end: usize| openings.iter().position(|o| o.tube == t && o.end == end); - let with = [at(0), at(1)].into_iter().flatten().any(|i| !kinds[i].is_empty()); - let s0 = at(0).map_or(0.0, |i| openings[i].s); - let s1 = at(1).map_or(tubes[t].curve.len, |i| openings[i].s); + let spans: Vec> = (tubes.iter().zip(&at_end)) + .map(|(t, &[a, z])| { + let with = [a, z].into_iter().flatten().any(|i| !kinds[i].is_empty()); + let s0 = a.map_or(0.0, |i| openings[i].s); + let s1 = z.map_or(t.curve.len, |i| openings[i].s); (with && s1 - s0 > 1e-6).then_some([s0, s1]) }) .collect(); let (floors, floor_metrics) = floor::floors(tubes, &spans, (&half, &height), input); let end_height = |o: &Opening| floors[o.tube].as_ref().map_or(height[o.tube], |f| f.end_height(o.end)); + let heights: Vec = openings.iter().map(end_height).collect(); // The numbers of each drawn opening. let mut ends: Vec = Vec::with_capacity(n); for i in 0..n { @@ -396,9 +397,8 @@ pub(crate) fn decide(tubes: &[Tube], openings: &mut [Opening], input: &Input, me // A pair has one record, at the opening of the lower feature id. let drawn = mate[i].is_none_or(|m| (openings[i].way_id, i) < (openings[m].way_id, m)); let m = Measured { sites: &sites, rights: &rights, cover: &cover, moved: &moved }; - let h = end_height(&openings[i]); let numbers = (kind.filter(|_| drawn)) - .map(|kind| numbers(i, kind, (mate[i], far_of[i]), &m, (openings, tubes), (&half, h), input)); + .map(|kind| numbers(i, kind, (mate[i], far_of[i]), &m, (openings, tubes), (&half, &heights), input)); ends.push(End { kinds: kinds[i].clone(), kind, rung: rung[i].unwrap_or_default(), numbers }); } let shown = |e: &End| match e.kind { @@ -433,15 +433,15 @@ struct Measured<'a> { moved: &'a [f64], } -/// The numbers of drawn opening i of `kind` (Plan 8) with the inside height `h` there: its frame is its own, or in a -/// pair the frame line of the opening farther in, which holds both. +/// The numbers of drawn opening i of `kind` (Plan 8), with the inside height of each opening: its frame is its own, or +/// in a pair the frame line of the opening farther in, which holds both. fn numbers( i: usize, kind: Kind, (mate, far): (Option, usize), m: &Measured, (openings, tubes): (&[Opening], &[Tube]), - (half, h): (&[f64], f64), + (half, heights): (&[f64], &[f64]), input: &Input, ) -> Numbers { let Measured { sites, rights, cover, moved } = *m; @@ -465,8 +465,11 @@ fn numbers( .filter_map(ground) .collect(); let highest = frame.iter().copied().fold(f64::NEG_INFINITY, f64::max); - let mut face = (h + b.shell_m + b.band_m).max(highest - floor + b.coping_m); - face = face.min(h + b.shell_m + b.face_over_crown_max_m); + // The wall holds its band over the higher crown of the frame's tubes, and fits the ground up to its cap over the + // lower. + let crowns = members.iter().map(|&k| openings[k].floor - floor + heights[k] + b.shell_m); + let (low, high) = crowns.fold((f64::INFINITY, f64::NEG_INFINITY), |(l, h), c| (l.min(c), h.max(c))); + let mut face = (high + b.band_m).max((highest - floor + b.coping_m).min(low + b.face_over_crown_max_m)); // A deck over the frame line or its wing walls: its underside lies over the floor (a way that goes on from the // opening on a deck lies at the floor, not over it). for &(x, under) in &site.decks { @@ -498,28 +501,33 @@ fn numbers( let (left, right) = (wing(hi, 1.0), wing(lo, -1.0)); let collar_of = |k: usize| cover[k].map(|d| (d - moved[k]).max(0.0)); let half_chain = t.curve.len / 2.0; - let collar = match kind { - Kind::Pair => members.iter().filter_map(|&k| collar_of(k)).fold(0.0, f64::max), - Kind::Arch | Kind::Rock => collar_of(i).expect("an arch is covered within its collar"), - Kind::Box => collar_of(i).unwrap_or(f64::INFINITY).min(half_chain), - Kind::Free => collar_of(i).unwrap_or(f64::INFINITY).min(b.free_max_m).min(half_chain), - }; - // The lowest ground under the frame, its wing walls and the collar. - let own = sites[i].as_ref().expect("a measured opening"); + // Each tube of a pair has its own collar. + let collars: Vec = (members.iter()) + .map(|&k| match kind { + Kind::Pair | Kind::Arch | Kind::Rock => collar_of(k).expect("an arch is covered within its collar"), + Kind::Box => collar_of(k).unwrap_or(f64::INFINITY).min(half_chain), + Kind::Free => collar_of(k).unwrap_or(f64::INFINITY).min(b.free_max_m).min(half_chain), + }) + .collect(); + // The lowest ground under the frame, its wing walls and the collars, and the floors. let (from, to) = (lo - right.len() as f64, hi + left.len() as f64); let under = (from.ceil() as i64..=to.floor() as i64).filter_map(|x| ground(x as f64)); - let collar_ground = (own.stations.iter()) - .skip(moved[i].round() as usize) - .take(collar.ceil() as usize + 1) - .flat_map(|st| st.iter().flatten().copied()); - let lowest = under.chain(collar_ground).fold(floor, f64::min); - let mate = mate.map(|m| (m, axis(m) - axis(i))); + let collar_ground = members.iter().zip(&collars).flat_map(|(&k, collar)| { + let site = sites[k].as_ref().expect("a measured opening"); + (site.stations.iter()) + .skip(moved[k].round() as usize) + .take(collar.ceil() as usize + 1) + .flat_map(|st| st.iter().flatten().copied()) + }); + let floors = members.iter().map(|&k| openings[k].floor); + let lowest = under.chain(collar_ground).chain(floors).fold(floor, f64::min); + let mate = mate.map(|m| (m, axis(m) - axis(i), collars[1])); let numbers = if kind == Kind::Free { (Vec::new(), Vec::new()) } else { (left, right) }; let heading = openings[far].heading(); Numbers { heading, - height: h, - collar, + height: heights[i], + collar: collars[0], face, left: numbers.0, right: numbers.1, diff --git a/host/obc-trailview-features/src/parts/mod.rs b/host/obc-trailview-features/src/parts/mod.rs index 443e6451c..be59a3206 100644 --- a/host/obc-trailview-features/src/parts/mod.rs +++ b/host/obc-trailview-features/src/parts/mod.rs @@ -558,10 +558,11 @@ fn records(tubes: &[Tube], openings: &[Opening], decided: &ladder::Decided, inpu t.insert("foot".into(), num(n.foot)); t.insert("way".into(), format!("{} {}", o.way[0], o.way[1])); t.insert("shift".into(), num(o.shift)); - if let Some((mate, m)) = n.mate.as_ref().map(|(i, m)| (&openings[*i], *m)) { + if let Some((mate, m, collar)) = n.mate.map(|(i, m, collar)| (&openings[i], m, collar)) { t.insert("mate".into(), num(m)); t.insert("mate_way".into(), format!("{} {}", mate.way[0], mate.way[1])); t.insert("mate_shift".into(), num(mate.shift)); + t.insert("mate_collar".into(), num(collar)); } let part = Part { outer: false, points: vec![o.p], z: Some(vec![o.floor]), plan: None }; features.push(("tunnel-end", t, part)); diff --git a/host/obc-trailview-features/src/parts/tests.rs b/host/obc-trailview-features/src/parts/tests.rs index 2fbb4ef83..209eed5e7 100644 --- a/host/obc-trailview-features/src/parts/tests.rs +++ b/host/obc-trailview-features/src/parts/tests.rs @@ -207,13 +207,15 @@ fn each_rung_gives_its_kinds_in_the_order_of_the_rungs() { #[test] fn a_pair_has_one_frame_line_and_a_way_in_a_wider_tube_has_no_part() { use Kind::*; - // Two road tunnels 20 m apart under one ridge; the second starts 3 m farther in. A footway 2.5 m beside the first - // lies in its tube. + // Two road tunnels 20 m apart under one ridge, which rises half as fast over the second; the second starts 3 m + // farther in. A footway 2.5 m beside the first lies in its tube. let mut case = Case::default(); let a = case.tunnel(&ROAD, (0.0, 200.0), 0.0); let b = case.tunnel(&ROAD, (3.0, 200.0), 20.0); let foot = case.tunnel(&FOOT, (0.0, 200.0), 2.5); - let placed = case.place(&site(&ridge(200.0, 1.0), &[], false), &mut Vec::new()); + let (steep, gentle) = (ridge(200.0, 1.0), ridge(200.0, 0.5)); + let ground = |p: [f64; 2]| if p[1] < 10.0 { steep(p) } else { gentle(p) }; + let placed = case.place(&site(&ground, &[], false), &mut Vec::new()); assert_eq!(of(&placed, a), vec![(vec![Pair, Arch, Free], "hill"); 2]); assert_eq!(of(&placed, b), vec![(vec![Pair, Arch, Free], "hill"); 2]); assert_eq!(of(&placed, foot), vec![(vec![], "same tube"); 2]); @@ -223,7 +225,10 @@ fn a_pair_has_one_frame_line_and_a_way_in_a_wider_tube_has_no_part() { assert_eq!(ends.len(), 2); let west = ends.iter().find(|t| t["mate"] == "20").expect("the west pair"); assert_eq!((west["part"].as_str(), west["shift"].as_str(), west["mate_shift"].as_str()), ("pair", "3", "0")); - assert!(ends.iter().any(|t| t["mate"] == "-20" && t["shift"] == "0")); + let east = ends.iter().find(|t| t["mate"] == "-20" && t["shift"] == "0").expect("the east pair"); + // Each tube has its own collar: the hill over the second comes later, and the first moved 3 m in. + assert_eq!((west["collar"].as_str(), west["mate_collar"].as_str()), ("4", "9")); + assert_eq!((east["collar"].as_str(), east["mate_collar"].as_str()), ("7", "12")); // A pair is built: the device opens the moved stretch, so the measure reads the four openings near it again. assert_eq!(placed.metrics["measured_again"].as_u64(), Some(4)); // The first tube widens to the far edge of the footway and its margin. From dd672231339b4597569dbc0218430bd0aac410bf Mon Sep 17 00:00:00 2001 From: timohueser Date: Sat, 21 Nov 2026 21:40:44 +0100 Subject: [PATCH 14/20] specs: each tube of a pair has its own collar; the face and foot of a pair read both tubes Co-Authored-By: Claude Opus 5.5 --- specs/trailview-features.md | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/specs/trailview-features.md b/specs/trailview-features.md index b2f76ac21..e39df0e4d 100644 --- a/specs/trailview-features.md +++ b/specs/trailview-features.md @@ -604,17 +604,16 @@ other. The numbers, in metres over the floor of the opening unless named: - `collar`: the metres to the first covered metre. For `box` it is at most half the chain. For `free` it is at most - `free_max_m` and half the chain, and that limit where no metre is covered. For `pair` it is the larger of the - two tubes. + `free_max_m` and half the chain, and that limit where no metre is covered. Each tube of a pair has its own. - `face`: the highest ground on the frame line plus `coping_m`, at least `height` + `shell_m` + `band_m`, at most `height` + `shell_m` + `face_over_crown_max_m`, and at most the underside of a deck over the frame line or its wing - walls less `coping_m`. A deck is over them where that lies over the floor: a way that goes on from the opening on a + walls less `coping_m`. In a pair, the least is over the higher crown of the two tubes and the most over the lower. A deck is over them where that lies over the floor: a way that goes on from the opening on a deck is not. So a deck can make `face` lower than `height` + `shell_m`. - `left`, `right`: a row of wall tops, one per metre out from the outer edge of the frame, the ground plus `coping_m`, from `coping_m` up to `face`. A row ends before the first metre whose ground lies under the floor + `wing_ground_m`, or at `wing_max_m`, and has one value at least. `left` is to the left of the way into the tube. -- `foot`: the lowest ground under the frame, its wing walls and its collar, less `foot_m`. The floor counts as ground - there, so `foot` is at most −`foot_m`. +- `foot`: the lowest ground under the frame, its wing walls and its collars, less `foot_m`. The floors count as + ground there, so `foot` is at most −`foot_m`. The tags, numbers in metres with at most 2 decimals, the values of a row separated by a space: @@ -635,7 +634,7 @@ The tags, numbers in metres with at most 2 decimals, the values of a row separat | `way` | end | The end vertex of the way of the opening, `x y` in the frame of the ground plan (2^34 units per side): the point that each zoom-13 tile holds, a quarter unit times 32, or a whole unit times 128 on a way with no alignment | | `shift` | end | The metres along that way from `way` to the opening; 0 where it did not move | | `mate` | `pair` | The metres to the left from its axis to the axis of the other tube | -| `mate_way`, `mate_shift` | `pair` | `way` and `shift` of the other opening | +| `mate_way`, `mate_shift`, `mate_collar` | `pair` | `way`, `shift` and `collar` of the other opening | Each `tunnel-tube` has the two vertices of one chord of the tube from opening to opening, in the rising metres along the stroke of its way, so a tile that holds a piece of the tube holds whole records. A chain end with no opening From 2b8eda50316967e2c5e849b21324d8d722f42f2c Mon Sep 17 00:00:00 2001 From: timohueser Date: Sat, 21 Nov 2026 21:47:17 +0100 Subject: [PATCH 15/20] trailview-parts: test a pair whose tubes run 25 degrees apart from one frame line Co-Authored-By: Claude Opus 5.5 --- host/obc-trailview-parts/src/tests.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/host/obc-trailview-parts/src/tests.rs b/host/obc-trailview-parts/src/tests.rs index 54a47810d..7e5ee31a4 100644 --- a/host/obc-trailview-parts/src/tests.rs +++ b/host/obc-trailview-parts/src/tests.rs @@ -912,6 +912,27 @@ fn two_tubes_meet_only_where_both_are_and_a_cut_head_is_closed() { assert!(got.is_some_and(|h| h.1 && h.0 < 5.1), "turns away, {east} m east: {got:?}"); } assert!(hit(&faces, [10.0, 0.0, 502.5], north, 30.0).is_some_and(|h| h.1 && h.0 > 11.0), "turns away, 10 m east"); + // A pair whose tubes run 25 degrees apart from one frame line, their rooms overlapping there: both find one plane, + // so a way north from the first meets the second's far wall, and a way up anywhere between their axes meets a + // vault. + let t = libm::tan(25f64.to_radians()); + let mut angled = tubes(&[ + &[[0.0, 0.0], [10.0, 0.0], [40.0, 0.0]], + &[[0.0, 7.0], [10.0, 7.0 + 10.0 * t], [40.0, 7.0 + 40.0 * t]], + ]); + angled.0.remove(2); + angled.0[0].part = Part::Pair; + angled.0[0].mate = Some(Mate { across: 7.0, way: [1, 1], shift: 0.0, collar: 6.0 }); + angled.1.iter_mut().for_each(|c| c.ends = [Some(Part::Pair), Some(Part::Arch)]); + let faces = faces_of(&angled); + for east in [1.0, 2.0, 3.0] { + let got = hit(&faces, [east, 0.0, 502.5], north, 30.0); + assert!(got.is_some_and(|h| h.1 && h.0 > 11.0), "angled, {east} m east: {got:?}"); + for k in 0..=20 { + let p = [east, 2.0 + 0.2 * f64::from(k), 500.5]; + assert!(hit(&faces, p, [0.0, 0.0, 1.0], 30.0).is_some_and(|h| h.1), "angled: a way up at {p:?}"); + } + } // Two arches on one frame line, the first's head wall 2 m taller: over the lower wall, a way to the taller one // meets the face that closes it at the middle. let mut taller = row(&[0.0, 7.0]); From 948828bfcf214125eda399eab66278a86df4039b Mon Sep 17 00:00:00 2001 From: timohueser Date: Sat, 21 Nov 2026 21:53:58 +0100 Subject: [PATCH 16/20] trailview-parts: a head's closing faces bound their spans with max and min, not clamp `clamp` with variable bounds brings the formatting of floats into the WASM. Co-Authored-By: Claude Opus 5.5 --- host/obc-trailview-parts/src/arch.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/host/obc-trailview-parts/src/arch.rs b/host/obc-trailview-parts/src/arch.rs index 3ac82c8d9..2297e1af9 100644 --- a/host/obc-trailview-parts/src/arch.rs +++ b/host/obc-trailview-parts/src/arch.rs @@ -217,10 +217,11 @@ pub fn faces f64>(b: &mut Builder, net: &Net, e: usize) { // from the front to the frame line and the room from there to the back. Where the other part's head stands // on the same line, it lies in that head's wall. for &(x, side) in &cuts { + // `max` and `min`, not `clamp`: its check of the bounds would bring the formatting of floats into the WASM. let solid = |st: &Station, (lo, hi): (Option, Option)| { let (foot, top) = (foot - st.z, top(x).max(foot - st.z)); match lo.zip(hi).filter(|(l, h)| h > l) { - Some((l, h)) => [(foot, l.clamp(foot, top)), (h.clamp(foot, top), top)], + Some((l, h)) => [(foot, l.max(foot).min(top)), (h.max(foot).min(top), top)], None => [(foot, top), (top, top)], } }; From 8e5c5f4879a3567eb1a1bd61bc1430442a693c79 Mon Sep 17 00:00:00 2001 From: timohueser Date: Sat, 21 Nov 2026 22:05:31 +0100 Subject: [PATCH 17/20] trailview-parts: a clip takes off the other's side of the own axis Where a narrow tube lies in a wide one's room, the middle between their walls lies past the narrow one's axis: the clip took off the wide tube's own room. It now takes off the side toward the other tube's axis. Co-Authored-By: Claude Opus 5.5 --- host/obc-trailview-parts/src/tests.rs | 18 ++++++++++++++++++ host/obc-trailview-parts/src/tube.rs | 5 +++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/host/obc-trailview-parts/src/tests.rs b/host/obc-trailview-parts/src/tests.rs index 7e5ee31a4..cef9b4d79 100644 --- a/host/obc-trailview-parts/src/tests.rs +++ b/host/obc-trailview-parts/src/tests.rs @@ -912,6 +912,24 @@ fn two_tubes_meet_only_where_both_are_and_a_cut_head_is_closed() { assert!(got.is_some_and(|h| h.1 && h.0 < 5.1), "turns away, {east} m east: {got:?}"); } assert!(hit(&faces, [10.0, 0.0, 502.5], north, 30.0).is_some_and(|h| h.1 && h.0 > 11.0), "turns away, 10 m east"); + // A path tube whose axis lies 3 m from a road tube's, in the road's room: the middle lies past the path's axis. A + // way up from either room meets a vault, and a way north from the path's axis meets its far wall. + let mut inner = tubes(&[&[[0.0, 0.0], [10.0, 0.0], [40.0, 0.0]], &[[0.0, 3.0], [10.0, 3.0], [40.0, 3.0]]]); + for e in &mut inner.0[2..] { + (e.half, e.height) = (0.9, 2.6); + } + for c in &mut inner.1[2..] { + (c.half, c.height) = (0.9, 2.6); + } + let faces = faces_of(&inner); + for east in [2.0, 10.0, 30.0] { + for y in [-2.0, 0.0, 2.0, 3.0] { + let p = [east, y, 501.0]; + assert!(hit(&faces, p, [0.0, 0.0, 1.0], 30.0).is_some_and(|h| h.1), "a path in a road's room: up at {p:?}"); + } + let got = hit(&faces, [east, 3.0, 501.0], north, 30.0); + assert!(got.is_some_and(|h| h.1 && h.0 < 1.0), "a path in a road's room: north at {east} m: {got:?}"); + } // A pair whose tubes run 25 degrees apart from one frame line, their rooms overlapping there: both find one plane, // so a way north from the first meets the second's far wall, and a way up anywhere between their axes meets a // vault. diff --git a/host/obc-trailview-parts/src/tube.rs b/host/obc-trailview-parts/src/tube.rs index e39fa135d..f8d8a5807 100644 --- a/host/obc-trailview-parts/src/tube.rs +++ b/host/obc-trailview-parts/src/tube.rs @@ -486,8 +486,9 @@ impl<'a> Net<'a> { (first, last, Some(last.0)) } }; - let (far, near) = (from.0.at([from.1.axis, 0.0]), from.0.at([from.1.x, 0.0])); - let away = [far[0] - near[0], far[1] - near[1]]; + // Toward the other's side of the own axis: where a narrow tube lies in a wide one's room, the middle lies + // past the narrow one's axis. + let away = [from.0.ax * from.1.axis.signum(), from.0.ay * from.1.axis.signum()]; // The two tubes overlap by `OVERLAP_M` at the plane, so the rounding of their vertices opens no gap there. let l = libm::hypot(away[0], away[1]).max(f64::MIN_POSITIVE); let d = OVERLAP_M / metres_per_unit(s.y) / l; From 156e7692d429946aec98a9be99f1ca1c026dc93a Mon Sep 17 00:00:00 2001 From: timohueser Date: Sat, 21 Nov 2026 22:23:30 +0100 Subject: [PATCH 18/20] trailview-parts: a tube is met between the planes of its rings; a head ends at an approach and over the heights it spans `Net::meets` reads where the other tube runs from the planes of its rings (at an opening its frame line, at a bend its mitre), not from its chord's vertices: the two openings of a pair lie on one frame line, and their chord vertices up to half a metre off it. A head also ends where the approach of an opening behind its frame line crosses it (within `pair_max_m`), so it keeps out of the way to that opening, and it meets a tube whose room overlaps its wall from its foot to its top, so a pair whose floors lie far apart still ends at the middle. `Meet` holds how a part looks for other tubes. Co-Authored-By: Claude Opus 5.5 --- host/obc-trailview-parts/src/arch.rs | 16 ++++--- host/obc-trailview-parts/src/tests.rs | 12 +++--- host/obc-trailview-parts/src/tube.rs | 60 ++++++++++++++++++++------- 3 files changed, 62 insertions(+), 26 deletions(-) diff --git a/host/obc-trailview-parts/src/arch.rs b/host/obc-trailview-parts/src/arch.rs index 2297e1af9..63d4ecf1a 100644 --- a/host/obc-trailview-parts/src/arch.rs +++ b/host/obc-trailview-parts/src/arch.rs @@ -115,12 +115,18 @@ fn grown(net: &Net, e: usize, grow: f64) -> Vec { } /// Where end e's head ends at another part: on each side, the nearest built tube that crosses its frame line within -/// reach of the head (`Net::meets` with the head's metres across): the metres across to the middle between the two -/// tubes' walls, and the side (1 to the left). The mate of a pair crosses it at its opening. -fn head_cuts(net: &Net, e: usize) -> Vec<(f64, f64)> { +/// reach of the head, or whose opening's approach crosses it within `pair_max_m` of the opening, and whose room +/// overlaps the head from its foot to its top (`Net::meets` with the head's metres across and heights): the metres +/// across to the middle between the two tubes' walls, and the side (1 to the left). The mate of a pair crosses it at +/// its opening; the approach keeps a head out of the way to an opening behind it. +fn head_cuts(net: &Net, e: usize, foot: f64) -> Vec<(f64, f64)> { let Some((c, _)) = net.opening(e) else { return Vec::new() }; + let (end, chord, (design, bake)) = (&net.ends[e], &net.chords[c], (&net.rules.design, &net.rules.ladder.bake)); let (right, left) = wide(net, e); - let cuts = net.meets(c, &net.frame(e, 0.0), [-right, left], tube::MEET_PAST_M); + let st = net.frame(e, 0.0); + let up = [foot - st.z, end.face.max(chord.height + design.frame_m + bake.shell_m)]; + let meet = tube::Meet { across: [-right, left], past: tube::MEET_PAST_M, approach: bake.pair_max_m, up: Some(up) }; + let cuts = net.meets(c, &st, meet); cuts.into_iter().flatten().map(|cut| (cut.x, cut.axis.signum())).collect() } @@ -150,7 +156,7 @@ pub fn faces f64>(b: &mut Builder, net: &Net, e: usize) { let (front, ring, back) = (net.frame(e, -design.recess_m), net.frame(e, 0.0), net.frame(e, design.face_m - design.recess_m)); let (h, section) = shell.first().map_or((chord.height, chord.section), |p| (p.2, p.3)); - let cuts = head_cuts(net, e); + let cuts = head_cuts(net, e, foot); b.clip( (cuts.iter()) .map(|&(x, side)| { diff --git a/host/obc-trailview-parts/src/tests.rs b/host/obc-trailview-parts/src/tests.rs index cef9b4d79..ee393eb8a 100644 --- a/host/obc-trailview-parts/src/tests.rs +++ b/host/obc-trailview-parts/src/tests.rs @@ -960,12 +960,14 @@ fn two_tubes_meet_only_where_both_are_and_a_cut_head_is_closed() { let got = hit(&faces, [0.15, 7.0, 500.0 + up], [0.0, -1.0, 0.0], 30.0); assert!(got.is_some_and(|h| h.1 && (h.0 - 3.5).abs() < 0.2), "taller, {up} m up: {got:?}"); } - // Two arches whose frame lines lie 3 m apart: the first's tube crosses the second's line, so the second's head - // ends at the middle, closed over the first's tube; the second does not cross the first's line, so the first's - // head wall stays whole. + // Two arches whose frame lines lie 3 m apart: the first's tube crosses the second's line, and the second's approach + // the first's, so both heads end at the middle, closed: a way over the first's tube meets the second's head, a way + // in the second's approach meets the first's head, both at the middle; the way into the second meets no face. let faces = faces_of(&staggered); let got = hit(&faces, [3.15, 0.0, 506.2], north, 30.0); assert!(got.is_some_and(|h| h.1 && (h.0 - 3.5).abs() < 0.2), "frame lines apart, the second's head: {got:?}"); - let got = hit(&faces, [-5.0, 5.0, 506.2], [1.0, 0.0, 0.0], 30.0); - assert!(got.is_some_and(|h| h.1 && h.0 < 5.1), "frame lines apart, the first's head: {got:?}"); + let got = hit(&faces, [0.15, 7.0, 506.2], [0.0, -1.0, 0.0], 30.0); + assert!(got.is_some_and(|h| h.1 && (h.0 - 3.5).abs() < 0.2), "frame lines apart, the first's head: {got:?}"); + let got = hit(&faces, [-5.0, 7.0, 502.0], [1.0, 0.0, 0.0], 30.0); + assert!(got.is_none(), "frame lines apart, the way into the second: {got:?}"); } diff --git a/host/obc-trailview-parts/src/tube.rs b/host/obc-trailview-parts/src/tube.rs index f8d8a5807..6f0a10967 100644 --- a/host/obc-trailview-parts/src/tube.rs +++ b/host/obc-trailview-parts/src/tube.rs @@ -79,12 +79,23 @@ pub struct Meeting { pub end: Option, } +/// How a part looks for other tubes from a station's line (`Net::meets`): the metres across to each side (to the right, +/// to the left); the metres past the planes of the other's rings, and on from a ring at an opening along the line of +/// its approach; and the heights over the station's floor that the part's faces span, or None for a room. +#[derive(Clone, Copy, Debug)] +pub struct Meet { + pub across: [f64; 2], + pub past: f64, + pub approach: f64, + pub up: Option<[f64; 2]>, +} + /// The side of a cell of `Net::cells`, in metres. const CELL_M: f64 = 16.0; /// Two tubes that meet at a cut each run this far past it: two world units, as each vertex is rounded to one. pub const OVERLAP_M: f64 = 0.05; -/// A station meets a tube this far past the vertices of its chords: the openings of a pair lie on one frame line within -/// a few centimetres of the rounding of their record. +/// A station meets a tube this far past the planes of its rings: the two openings of a pair lie on one frame line within +/// the rounding of their record. pub const MEET_PAST_M: f64 = 0.1; /// Halvings of a piece to find where another tube starts or ends on it: to a millimetre of a 10 m chord. const MEET_HALVES: usize = 14; @@ -375,13 +386,15 @@ impl<'a> Net<'a> { } /// Where the line of a station across chord c meets another built tube, on each side (to the right, to the left) - /// the nearest: where the other's chord crosses the line, or passes within `past` metres of its vertices, within - /// `reach` of that side (the own part's metres across from its axis) and the other's half and shell, at the floor's - /// level within half their heights. The cut is at the middle between the two tubes' walls, measured square to each - /// tube's own chord, so both find one plane at any angle. A tube meets another for its inside and shell with the - /// reach of its shell; a head with the reach of its wall, and so where the other crosses its frame line. Needs - /// `meeting`. - pub fn meets(&self, c: usize, st: &Station, reach: [f64; 2], past: f64) -> [Option; 2] { + /// the nearest, as `meet` looks: where the other's chord crosses the line between the planes of its rings (or past + /// them), within the own part's metres across from its axis and the other's half and shell; where the other's room + /// overlaps the heights that the own faces span (a head), or where its floor lies within half their heights of the + /// station's (a room). The cut is at the middle between the two tubes' walls, measured square to each tube's own + /// chord, so both find one plane at any angle. A tube meets another for its inside and shell with the reach of its + /// shell; a head with the reach of its wall, and so where the other or the approach of its opening crosses its + /// frame line. Needs `meeting`. + pub fn meets(&self, c: usize, st: &Station, meet: Meet) -> [Option; 2] { + let reach = meet.across; let (own, shell) = (&self.chords[c], self.rules.ladder.bake.shell_m); let m = metres_per_unit(st.y); let cell = |dx: i64, dy: i64| { @@ -416,18 +429,32 @@ impl<'a> Net<'a> { } let (px, py) = (other.a[0] - st.x, other.a[1] - st.y); let (x, u) = ((dx * py - dy * px) / det, (st.ax * py - st.ay * px) / det); - let past = past / direction(other).1.max(MEET_PAST_M); let side = usize::from(x > 0.0); let floor_at = |u: f64| other.a[2] + u.clamp(0.0, 1.0) * (other.b[2] - other.a[2]); - if !(-past..=1.0 + past).contains(&u) - || x.abs() > reach[side] + other.half + shell - || (floor_at(u) - st.z).abs() > (own.height + other.height) / 2.0 + // The other tube runs between the planes of its two rings: at an opening its frame line, at a bend the mitre. + let o_dir = unit([dx, dy]); + let crossing = st.at([x, 0.0]); + let between = |k: usize, into: f64| { + let r = self.ring(o, k); + let n = unit([r.ay, -r.ax]); + let n = if dot(n, o_dir) * into >= 0.0 { n } else { [-n[0], -n[1]] }; + let on = if self.end_at.contains_key(&(o, k)) { meet.approach } else { 0.0 }; + dot([crossing[0] - r.x, crossing[1] - r.y], n) * m >= -(meet.past + on) + }; + let df = floor_at(u) - st.z; + let level = match meet.up { + Some([lo, hi]) => df < hi && df + other.height > lo, + None => df.abs() <= (own.height + other.height) / 2.0, + }; + if x.abs() > reach[side] + other.half + shell + || !level || best[side].is_some_and(|b| b.axis.abs() <= x.abs()) + || !between(0, 1.0) + || !between(1, -1.0) { continue; } // Signed metres from each tube's axis toward the other: linear along the station's line. - let o_dir = unit([dx, dy]); let mut na = unit(left_of(own_dir)); if dot(na, line) * x < 0.0 { na = [-na[0], -na[1]]; @@ -454,12 +481,13 @@ impl<'a> Net<'a> { /// Where station s and t across chord c meet another tube for its inside and shell (`meets` with the reach of its /// shell): on each side, the clip that takes off the other's side between the two stations' cuts. Where only one /// station meets it, the clip holds from that station to where the other tube starts or ends on the piece (found - /// by halves, with no metres past its vertices), and no farther. + /// by halves, with no metres past its rings), and no farther. pub fn clips(&self, c: usize, (s, t): (&Station, &Station)) -> Vec { let reach = self.chords[c].half + self.rules.ladder.bake.shell_m; let at = |u: f64, side: usize, past: f64| { let st = s.mix(t, u); - self.meets(c, &st, [reach; 2], past)[side].map(|cut| (st, cut)) + let meet = Meet { across: [reach; 2], past, approach: 0.0, up: None }; + self.meets(c, &st, meet)[side].map(|cut| (st, cut)) }; let mut out = Vec::new(); for side in 0..2 { From 3ac162ba6337009289f8b06f3b62f8810479a688 Mon Sep 17 00:00:00 2001 From: timohueser Date: Sat, 21 Nov 2026 22:26:13 +0100 Subject: [PATCH 19/20] wasm: the parts bridge's size with the cut only where both tubes are and a head's closed cut Co-Authored-By: Claude Opus 5.5 --- builder/wasm/wasm_size_guard.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/builder/wasm/wasm_size_guard.py b/builder/wasm/wasm_size_guard.py index 00b67e0a2..b6df86785 100644 --- a/builder/wasm/wasm_size_guard.py +++ b/builder/wasm/wasm_size_guard.py @@ -46,9 +46,10 @@ } # Measured in CI on the build of the tunnel parts' arch, tube, boxes and underpasses, with a tile's volumes built once -# and selected per node, and the pair, the rim, the closed free end and the cut of two tubes that meet, with wasm-pack -# 0.15.0 and rustc 1.100.0. The margin is the ground plan's, raw by the same fraction. -PARTS_MEASURED = {"gzipped": 140_824, "raw_wasm": 321_998} +# and selected per node, and the pair, the rim, the closed free end and the cut of two tubes that meet only where both +# are, with the closed cut of a head, with wasm-pack 0.15.0 and rustc 1.100.0. The margin is the ground plan's, raw by +# the same fraction. +PARTS_MEASURED = {"gzipped": 148_615, "raw_wasm": 335_534} PARTS_MARGIN = { "gzipped": GROUND_PLAN_MARGIN_GZIPPED, "raw_wasm": round(GROUND_PLAN_MARGIN_GZIPPED * PARTS_MEASURED["raw_wasm"] / PARTS_MEASURED["gzipped"]), From e9e4f3094436254bc2fd0f9270c359449e012b8a Mon Sep 17 00:00:00 2001 From: timohueser Date: Sat, 21 Nov 2026 23:05:51 +0100 Subject: [PATCH 20/20] wasm: the parts and ground plan bridges' sizes as CI measures 3ac162ba6 Co-Authored-By: Claude Opus 5.5 --- builder/wasm/wasm_size_guard.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/builder/wasm/wasm_size_guard.py b/builder/wasm/wasm_size_guard.py index b6df86785..15a550d03 100644 --- a/builder/wasm/wasm_size_guard.py +++ b/builder/wasm/wasm_size_guard.py @@ -34,7 +34,7 @@ # The built tunnel ends (obc-trailview-parts) with their open stretches and the approaches to their openings add # about 36 kB gzipped; the openings of a pair's mate (the parts' `mouths`) about 2 kB more, measured in CI with # wasm-pack 0.15.0 and rustc 1.100.0. -GROUND_PLAN_MEASURED = {"gzipped": 831_466, "raw_wasm": 2_134_754} +GROUND_PLAN_MEASURED = {"gzipped": 831_313, "raw_wasm": 2_133_837} # The owner's margin: compiler and dependency updates move the size by a few kilobytes and must not fail # unrelated pull requests; real growth past the margin still fails. Raw gets the same fraction as gzipped. # A pull request that changes the bridge's code records its own CI size here; the margin is only for toolchain @@ -49,7 +49,7 @@ # and selected per node, and the pair, the rim, the closed free end and the cut of two tubes that meet only where both # are, with the closed cut of a head, with wasm-pack 0.15.0 and rustc 1.100.0. The margin is the ground plan's, raw by # the same fraction. -PARTS_MEASURED = {"gzipped": 148_615, "raw_wasm": 335_534} +PARTS_MEASURED = {"gzipped": 147_785, "raw_wasm": 335_603} PARTS_MARGIN = { "gzipped": GROUND_PLAN_MARGIN_GZIPPED, "raw_wasm": round(GROUND_PLAN_MARGIN_GZIPPED * PARTS_MEASURED["raw_wasm"] / PARTS_MEASURED["gzipped"]),