[140] Plandarstellung Teil 6: Raumstempel weichen Treppen, Türschwenk, Bemassung, Koten, Texten und Symbolen aus; Unterbau (Kies, Magerbeton, Erdreich) im Schnitt 1:100 schraffiert; CLI-SVG setzt Stempel wie gemessen (Inter, 12 pt fett, 0.8×), Zeilen im zentrierten Block; Stempel-Griff an der gezeichneten Lage; Goldens neu

This commit is contained in:
Claude committed 2026-11-06 16:59:31 +00:00
1 parent f29ffde6f8
commit 016c02e28c
29 files changed
+808 -90

No files matched your search

+164 -15
View File
@@ -707,6 +707,11 @@ fn stamp_candidates(ring: &[[f64; 2]], pole: Vec2) -> Vec<Vec2> {
out
}
/// Ausmass eines Rings `[x0, y0, x1, y1]`.
fn ring_bounds(ring: &[[f64; 2]]) -> [f64; 4] {
ring.iter().fold([f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY], |b, q| [b[0].min(q[0]), b[1].min(q[1]), b[2].max(q[0]), b[3].max(q[1])])
}
/// Namenszeilen auf `n` Zeichen kürzen (n − 1 Zeichen und Punkt), Leerzeichen am Schnitt weg.
fn abbreviate(text: &str, n: usize) -> String {
text.split('\n')
@@ -715,7 +720,71 @@ fn abbreviate(text: &str, n: usize) -> String {
.join("\n")
}
fn rooms(c: &Ctx, out: &mut Vec<Primitive>, bounds: &mut Bounds) {
/// [140] Hindernisse für Raumstempel aus den schon erzeugten Domänen: Treppen (alle Striche), Türschwenk-Bögen,
/// Stützen, Beschriftungen des Kontexts (Höhenlinien-Koten) und die Zeichnungen, denen Stempel ausweichen
/// (Bemassung, Koten, Texte, Symbole; `drawings::stamp_obstacle_prims`).
fn stamp_obstacles(c: &Ctx, d: &DomainPrims) -> super::stamp_place::Obstacles {
let mut o = super::stamp_place::Obstacles::default();
for q in d.stairs.iter().chain(&d.columns) {
o.add_prim(q);
}
for q in &d.walls {
if matches!(q, Primitive::Arc { opening_id: Some(_), .. }) {
o.add_prim(q);
}
}
for q in &d.context {
if matches!(q, Primitive::DrawingText { .. }) {
o.add_prim(q);
}
}
for q in super::drawings::stamp_obstacle_prims(c) {
o.add_prim(&q);
}
o
}
/// [140] Bis zu diesem Abstand (Papier-mm) zum nächsten Hindernis zählt eine Stempel-Lage als frei; freiere
/// Lagen gewinnen nichts mehr (der Stempel bleibt am Pol, wenn er dort so viel Luft hat).
const STAMP_CLEAR_MM: f64 = 2.0;
/// [140] Lage eines Stempels (`w` × `h`) unter `candidates` (Pol zuerst, dann nach Abstand zum Pol): erst mit
/// Luft (1.3 × Breite/Höhe), dann knapp im Raum; unter diesen die freieste Lage (Abstand zu `obst` bis
/// `clear`, Gleichstand → näher am Pol). Liegt jede Lage auf einem Hindernis, die mit der geringsten
/// Überdeckung (`Obstacles::overlap`, Gleichstand → mit Luft, dann näher am Pol); ohne Hindernisse wie bisher.
fn place_stamp(ring: &[[f64; 2]], candidates: &[Vec2], obst: &super::stamp_place::Obstacles, clear: f64, w: f64, h: f64) -> Option<Vec2> {
let inside = |q: &Vec2, k: f64| crate::room_area::rect_in_ring(ring, q.x, q.y, k * w / 2.0, k * h / 2.0);
if !obst.is_empty() {
for k in [1.3, 1.0] {
let mut best: Option<(f64, Vec2)> = None;
for q in candidates.iter().filter(|q| inside(q, k)) {
let d = obst.clearance(*q, w / 2.0, h / 2.0).min(clear);
if d > 0.0 && best.is_none_or(|(b, _)| d > b) {
best = Some((d, *q));
}
}
if let Some((_, q)) = best {
return Some(q);
}
}
let mut best: Option<(f64, Vec2)> = None;
for k in [1.3, 1.0] {
for q in candidates.iter().filter(|q| inside(q, k)) {
let n = obst.overlap(*q, w / 2.0, h / 2.0);
if best.is_none_or(|(b, _)| n < b) {
best = Some((n, *q));
}
}
}
if let Some((_, q)) = best {
return Some(q);
}
}
let fit = |k: f64| candidates.iter().copied().find(|q| inside(q, k));
fit(1.3).or_else(|| fit(1.0))
}
fn rooms(c: &Ctx, out: &mut Vec<Primitive>, bounds: &mut Bounds, obstacles: &super::stamp_place::Obstacles) {
for room in c.p.rooms.as_deref().unwrap_or(&[]).iter().filter(|r| r.floor_id == c.a.floor && c.shown(&r.category_code)) {
for q in &room.boundary {
bounds.acc(q.x, q.y);
@@ -756,11 +825,10 @@ fn rooms(c: &Ctx, out: &mut Vec<Primitive>, bounds: &mut Bounds) {
}
};
let candidates = if room.stamp_anchor.is_some() { vec![at] } else { stamp_candidates(&pts, pole) };
// Mit Luft (1.3 × Breite/Höhe) zuerst, damit der Stempel nicht an der Wand klebt; sonst knapp.
let place = |w: f64, h: f64| {
let fit = |k: f64| candidates.iter().copied().find(|q| crate::room_area::rect_in_ring(&pts, q.x, q.y, k * w / 2.0, k * h / 2.0));
fit(1.3).or_else(|| fit(1.0))
};
// [140] Teil 6: ohne eigenen Anker weicht der Stempel anderem Planinhalt im Raum aus (`place_stamp`).
let obst = if room.stamp_anchor.is_some() { Default::default() } else { obstacles.within(ring_bounds(&pts)) };
let clear = STAMP_CLEAR_MM * c.a.scale / 1000.0;
let place = |w: f64, h: f64| place_stamp(&pts, &candidates, &obst, clear, w, h);
let (extra_lines, base_pt, name, placed) = fit_room_stamp(&doc, extra_lines, if small { ROOM_STAMP_SMALL_PT } else { ROOM_STAMP_PT }, c.a.scale, &place);
let at = placed.unwrap_or(at);
let doc = name.unwrap_or(doc);
@@ -951,7 +1019,7 @@ pub fn plan_domains(p: &Project, a: &PlanArgs) -> Result<DomainPrims, String> {
let mut drawings = super::drawings::Out::default();
super::drawings::plan_drawings(&c, &mut super::drawings::Sink::new(super::drawings::Target::Vec(&mut drawings), super::drawings::Keep::All), &mut bounds)?;
out.drawings = drawings;
domains_after(&c, &mut out);
domains_after(&c, &mut out, &mut bounds);
out.bounds = bounds.get();
Ok(out)
}
@@ -964,7 +1032,6 @@ fn domains_before(c: &Ctx, out: &mut DomainPrims, bounds: &mut Bounds) -> Result
}
ceilings(c, &mut out.ceilings, bounds)?;
roofs(c, &mut out.roofs, bounds);
rooms(c, &mut out.rooms, bounds);
super::walls::plan_walls(c, c.a.reference_lines, &mut out.walls, bounds)?;
super::stairs::plan_stairs(c, &mut out.stairs, bounds);
columns(c, &mut out.columns);
@@ -972,12 +1039,18 @@ fn domains_before(c: &Ctx, out: &mut DomainPrims, bounds: &mut Bounds) -> Result
Ok(())
}
/// Kontext und Schnittlinien (projektglobal, nur mit `global`).
fn domains_after(c: &Ctx, out: &mut DomainPrims) {
if c.a.global && !super::ceiling_plan::is_ceiling_level(c.p, &c.a.floor) {
/// Kontext und Schnittlinien (projektglobal, nur mit `global`), zuletzt die Räume: ihre Stempel weichen dem
/// übrigen Inhalt aus ([`stamp_obstacles`]), darum nach allen anderen Domänen (Gruppen-Reihenfolge bleibt).
fn domains_after(c: &Ctx, out: &mut DomainPrims, bounds: &mut Bounds) {
let ceiling = super::ceiling_plan::is_ceiling_level(c.p, &c.a.floor);
if c.a.global && !ceiling {
super::context::plan_context(c, &mut out.context);
super::context::plan_section_lines(c, &mut out.sections);
}
if !ceiling {
let obstacles = stamp_obstacles(c, out);
rooms(c, &mut out.rooms, bounds, &obstacles);
}
}
/// Reihenfolge der Gruppen im Plan-Puffer der Abfrage `planDomains`: Schatten und Baurecht
@@ -992,6 +1065,7 @@ pub fn plan_domains_buf(p: &Project, a: &PlanArgs) -> Result<Vec<u8>, String> {
let mut d = DomainPrims::default();
let mut bounds = Bounds::new();
domains_before(&c, &mut d, &mut bounds)?;
domains_after(&c, &mut d, &mut bounds);
let mut w = crate::plan::buf::Writer::new(true);
w.post = super::extras::post_for(p, a);
let (under, violations) = extras_of(p, a);
@@ -1003,8 +1077,6 @@ pub fn plan_domains_buf(p: &Project, a: &PlanArgs) -> Result<Vec<u8>, String> {
let start = w.begin_group();
super::drawings::plan_drawings(&c, &mut super::drawings::Sink::new(super::drawings::Target::Buf(&mut w), super::drawings::Keep::All), &mut bounds)?;
w.end_group(start);
domains_after(&c, &mut d);
apply_voids(p, a, &mut d);
for g in [&d.solids, &d.context, &d.sections] {
w.group(g);
}
@@ -1116,7 +1188,17 @@ pub fn plan_domains_cached(p: &Project, revs: &crate::document::Revs, cache: &mu
/// Cache bzw. neu (dann aufgenommen).
fn assemble_cached(c: &Ctx, revs: &crate::document::Revs, cc: &mut super::cache::CtxCache, w: &mut crate::plan::buf::Writer, have: &HashSet<u64>) -> Result<Vec<super::drawings::ChunkOut>, String> {
use super::cache::{selection_sig, RestEntry, NOT_FOR_REST};
let sig = (revs.max_except(NOT_FOR_REST), format!("{}\u{3}{}", selection_sig(c.a), c.a.sun_when.unwrap_or(f64::NAN).to_bits()));
// [140] Raumstempel weichen Zeichnungen aus (Bemassung, Koten, Texte, Symbole): deren Stand gehört in den
// Schlüssel, die übrigen Zeichnungen nicht.
let stamps = revs.item_stamps("drawings2d").filter(|s| s.len() == c.p.drawings2d.len());
let obstacle_sig = c.p.drawings2d.iter().enumerate().filter(|(_, d)| super::drawings::is_stamp_obstacle(&d.geom)).fold(0u64, |h, (i, d)| {
let v = match stamps {
Some(s) => s[i],
None => serde_json::to_string(d).map_or(0, |t| t.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ b as u64).wrapping_mul(0x0000_0100_0000_01b3))),
};
(h ^ v).wrapping_mul(0x9E37_79B9_7F4A_7C15).rotate_left(17)
});
let sig = (revs.max_except(NOT_FOR_REST), format!("{}\u{3}{}\u{3}{obstacle_sig}", selection_sig(c.a), c.a.sun_when.unwrap_or(f64::NAN).to_bits()));
if cc.rest.as_ref().is_some_and(|r| r.sig != sig) {
cc.rest = None;
}
@@ -1127,7 +1209,7 @@ fn assemble_cached(c: &Ctx, revs: &crate::document::Revs, cc: &mut super::cache:
let mut d = DomainPrims::default();
let mut b = Bounds::new();
domains_before(c, &mut d, &mut b)?;
domains_after(c, &mut d);
domains_after(c, &mut d, &mut b);
let (under, violations) = extras_of(c.p, c.a);
let extra = super::extras::extra_bounds(c.p, &under, |k| c.shown(k));
apply_voids(c.p, c.a, &mut d);
@@ -1304,6 +1386,73 @@ mod tests {
assert!(crate::room_area::rect_in_ring(&ring, at.x, at.y, w / 2.0, 0.1), "{at:?} {w}");
}
/// [140] Teil 6: Raumstempel ohne eigenen Anker weichen Koten, Texten, Bemassung und Treppen im Raum aus;
/// ohne Hindernis bleibt er am Pol, mit eigenem Anker auch mit Hindernis.
#[test]
fn raumstempel_weicht_hindernissen_aus() {
let mut p = sample();
let r = p.rooms.as_mut().unwrap().iter_mut().find(|r| r.floor_id == "eg").unwrap();
let q = [(0.0, 0.0), (7.0, 0.0), (7.0, 5.0), (0.0, 5.0)];
r.boundary = q.iter().map(|&(x, y)| Vec2 { x: x + 50.0, y: y + 50.0 }).collect();
r.stamp_anchor = None;
r.stamp = None;
let id = r.id.clone();
let t = serde_json::json!({ "floor": "eg", "show": ["20", "60", "80"], "grey": [], "scale": 100 }).to_string();
let a = PlanArgs::parse(1.0, &t).unwrap();
let stamp = |p: &Project| {
let out = plan_domains(p, &a).unwrap();
out.rooms.iter().find_map(|q| match q { Primitive::Text { at, room_id: Some(rid), doc, extra_lines, base_pt, .. } if *rid == id => Some((*at, doc.clone(), extra_lines.clone(), *base_pt)), _ => None }).unwrap()
};
let (pole, ..) = stamp(&p);
assert!((pole.x - 53.5).abs() < 1e-9 && (pole.y - 52.5).abs() < 1e-9, "ohne Hindernis am Pol: {pole:?}");
let mk = |geom: serde_json::Value| -> Drawing2D { serde_json::from_value(serde_json::json!({ "id": "k", "type": "drawing2d", "levelId": "eg", "categoryCode": "80", "geom": geom })).unwrap() };
// Kote und Text mitten im Raum, eine Bemassung quer durch den Raum knapp unter der Mitte.
p.drawings2d.push(mk(serde_json::json!({ "shape": "kote", "at": { "x": 53.4, "y": 52.4 }, "value": 0.0, "kind": "okFertig", "rotation": 0.0 })));
p.drawings2d.push(mk(serde_json::json!({ "shape": "text", "at": { "x": 53.0, "y": 52.7 }, "text": "Hinweis", "height": 0.25, "angle": 0.0 })));
p.drawings2d.push(mk(serde_json::json!({ "shape": "dimension", "pts": [{ "x": 50.0, "y": 52.0 }, { "x": 57.0, "y": 52.0 }], "offset": 0.0 })));
let (at, doc, extra, pt) = stamp(&p);
assert!((at.x - pole.x).hypot(at.y - pole.y) > 0.3, "weggerückt: {at:?}");
let (w, h) = stamp_size_m(&doc, &extra, pt, 100.0);
let ring: Vec<[f64; 2]> = q.iter().map(|&(x, y)| [x + 50.0, y + 50.0]).collect();
assert!(crate::room_area::rect_in_ring(&ring, at.x, at.y, w / 2.0, h / 2.0));
let c = Ctx::new(&p, &a);
let mut o = super::super::stamp_place::Obstacles::default();
for q in super::super::drawings::stamp_obstacle_prims(&c) {
o.add_prim(&q);
}
assert!(!o.is_empty());
assert!(o.clearance(at, w / 2.0, h / 2.0) > 0.0, "frei: {at:?}");
assert_eq!(extra.len(), 2, "Stempel bleibt vollständig");
// Eigener Anker: bleibt, auch auf dem Hindernis.
p.rooms.as_mut().unwrap().iter_mut().find(|r| r.id == id).unwrap().stamp_anchor = Some(pole);
assert_eq!(stamp(&p).0, pole);
// Kein freier Platz (Text über den ganzen Raum): wie bisher am Pol.
p.rooms.as_mut().unwrap().iter_mut().find(|r| r.id == id).unwrap().stamp_anchor = None;
p.drawings2d.clear();
p.drawings2d.push(mk(serde_json::json!({ "shape": "text", "at": { "x": 49.0, "y": 49.0 }, "text": "XXXXXXXXXXXXXXXXXXXXXXXXXX", "height": 6.0, "angle": 0.0 })));
assert_eq!(stamp(&p).0, pole);
}
/// [140] Teil 6: Treppe und Türschwenk sind Hindernisse (Strecken bzw. Sektor), Bogenwände nicht.
#[test]
fn stempel_hindernisse_aus_domaenen() {
let p = sample();
let t = serde_json::json!({ "floor": "eg", "show": ["20", "21", "30", "40", "50", "60"], "grey": [], "scale": 100 }).to_string();
let a = PlanArgs::parse(1.0, &t).unwrap();
let c = Ctx::new(&p, &a);
let d = plan_domains(&p, &a).unwrap();
let o = stamp_obstacles(&c, &d);
let doors = d.walls.iter().filter(|q| matches!(q, Primitive::Arc { opening_id: Some(_), .. })).count();
assert!(doors > 0 && !o.is_empty());
// Jeder Schwenk-Mittelpunkt (Bogenmitte zur Angel hin) liegt im Hindernis.
for q in &d.walls {
if let Primitive::Arc { center, from, to, opening_id: Some(_), .. } = q {
let m = Vec2 { x: (center.x * 2.0 + from.x + to.x) / 4.0, y: (center.y * 2.0 + from.y + to.y) / 4.0 };
assert_eq!(o.clearance(m, 0.001, 0.001), 0.0);
}
}
}
/// [140] Teil 5: Schnittflächen ab 1:100 schwarz (Wände als Sammelfläche ohne Fugen/Schraffur, Stützen
/// schwarz), 1:50 mit Schichten und Schraffur; Ebene „Schnittflächen schraffiert" übersteuert das 1:100.
#[test]
+23
View File
@@ -1407,6 +1407,29 @@ pub fn plan_drawings(c: &Ctx, sink: &mut Sink, bounds: &mut Bounds) -> Result<()
Ok(())
}
/// [140] Zeichnungsarten, denen Raumstempel ausweichen (Bemassung, Koten, Texte, Symbole/Möbel als Blöcke,
/// Detailverweise, Punktmarken). Linien, Flächen, Raster und Bilder nicht: sie laufen oft durch ganze Räume.
pub fn is_stamp_obstacle(g: &Drawing2DGeom) -> bool {
matches!(g, Drawing2DGeom::Dimension { .. } | Drawing2DGeom::Kote { .. } | Drawing2DGeom::Text { .. } | Drawing2DGeom::Block { .. } | Drawing2DGeom::Detailref { .. } | Drawing2DGeom::Pointmarker { .. })
}
/// [140] Primitive der gezeichneten Zeichnungen des Geschosses, denen Raumstempel ausweichen
/// ([`is_stamp_obstacle`]), wie [`plan_drawings`] sie zeichnet.
pub fn stamp_obstacle_prims(c: &Ctx) -> Vec<Primitive> {
let mut out = Out::default();
let mut memo = Memo::default();
let mut sink = Sink::new(Target::Vec(&mut out), Keep::All);
for d in c.p.drawings2d.iter().filter(|d| is_stamp_obstacle(&d.geom) && on_floor(c, d)) {
let m = memo.get(c, d);
if !m.shown {
continue;
}
// Fehler einer Zeichnung: ohne sie weiter (Hindernisse sind nur ein Hinweis für die Lage).
let _ = emit(c, d, Attrs::with(d, &m.ov, m.cat), &d.geom, m.greyed, c.a.scale, &mut sink, 0);
}
out.prims
}
/// Mittlere Grösse eines Stücks der 2D-Zeichnungen (Elemente) und Obergrenze.
const CHUNK_MEAN: u64 = 256;
const CHUNK_MAX: usize = 2048;
+4 -1
View File
@@ -111,6 +111,9 @@ pub struct StampLine {
pub style: TextStyleIn,
/// Versatz der Grundlinie vom Anker nach unten (Meter).
pub down: f64,
/// [140] Versatz der Zeile vom Anker nach rechts (Meter; Block um den Anker zentriert,
/// `text_layout::stamp_line_offsets`).
pub dx: f64,
}
/// Text-Eingabe je Text-Eintrag (aus dem Text-JSON gesetzt, s. [`crate::plan::text::dxf_text`]).
@@ -899,7 +902,7 @@ impl Ctx<'_> {
Prim::Stamp { at, lines } => {
for l in lines {
let st = self.style_of(Some(&l.style));
self.flat.add_text2(b, layer, V2 { x: at.x, y: at.y - l.down }, l.height, 0.0, &l.text, l.align, st);
self.flat.add_text2(b, layer, V2 { x: at.x + l.dx, y: at.y - l.down }, l.height, 0.0, &l.text, l.align, st);
}
}
Prim::Polygon { pts, fill, stroke, hatch } => {
+1
View File
@@ -33,6 +33,7 @@ pub mod pick;
pub mod sketch;
pub mod ceiling_plan;
pub mod line_ends;
pub mod stamp_place;
mod wall_columns;
#[cfg(test)]
mod wall_join_tests;
+4 -3
View File
@@ -27,7 +27,7 @@ use crate::jsnum;
use crate::plan::buf::{whole, Rec, View, F_COLOR, F_DASH_NULL, F_OPACITY, T_ARC, T_CIRCLE, T_DRAWING_ARC, T_DRAWING_TEXT, T_IMAGE, T_LINE, T_POLYGON, T_TEXT};
use crate::plan::parts::{greyed_of, Part};
use crate::plan::text::{SingleText, StampText};
use crate::text_layout::{place_lines, stamp_block, wrap_doc_to_lines, Line, LayoutOpts, LineAlign, PT_TO_MM, TEXT_LINE_HEIGHT_MULT};
use crate::text_layout::{place_lines, stamp_block, stamp_line_offsets, wrap_doc_to_lines, Line, LayoutOpts, LineAlign, PT_TO_MM, TEXT_LINE_HEIGHT_MULT};
use std::f64::consts::PI;
/// Optionen: Massstab-Nenner, Blatt (mm) und Ausmass des Plans (`Plan.bounds`).
@@ -612,8 +612,9 @@ fn stamp_node(out: &mut Out, t: &StampText, m: Map, opacity: String) {
}
let attrs: Vec<(&str, String)> = if opacity.is_empty() { Vec::new() } else { vec![("opacity", opacity)] };
out.tagged(&["X"], &attrs);
for p in &placed {
line_node(out, &p.line, "", c.x, p.y);
// [140] Zeilen im gemessenen, um den Anker zentrierten Block (`stamp_line_offsets`).
for (p, dx) in placed.iter().zip(stamp_line_offsets(&placed)) {
line_node(out, &p.line, "", c.x + dx, p.y);
}
}
+57 -5
View File
@@ -2392,13 +2392,27 @@ pub fn merge_thin_cuts(cuts: &[Cut], scale: f64) -> Vec<Cut> {
/// `generateSectionPlan`: Primitive (u → x, Höhe → y) und Ausmass.
pub fn section_primitives(out: &Output, mono: bool, hidden_lines: bool, vis: &Visibility) -> (Vec<Primitive>, [f64; 4]) {
section_primitives_at(out, mono, hidden_lines, vis, 0.0, Detail::Mittel, false)
section_primitives_at(out, mono, hidden_lines, vis, 0.0, Detail::Mittel, false, &HashSet::new())
}
/// [140] Bauteile (ids) aus losen Schüttungen/Unterbau (`standards::is_loose_fill`: Kies, Magerbeton,
/// Erdreich …): im Schnitt ab 1:100 nicht schwarz.
pub fn loose_fill_components(p: &Project) -> HashSet<String> {
p.components.iter().filter(|c| crate::standards::is_loose_fill(c)).map(|c| c.id.clone()).collect()
}
/// [140] Bleibt eine Schnittfläche ab 1:100 schraffiert? Schichten aus losen Schüttungen/Unterbau
/// (`loose`, Bauteil-ids) bzw. mit Schraffur Erdreich/Kies — sie tragen nicht und bilden keinen Raum.
fn loose_cut(cp: &Cut, loose: &HashSet<String>) -> bool {
cp.component_id.as_deref().is_some_and(|id| loose.contains(id)) || cp.hatch.as_ref().is_some_and(|h| matches!(h.pattern, HatchPattern::Earth | HatchPattern::Gravel))
}
/// [`section_primitives`] beim Massstab 1:`scale` (dünne Schichten zusammengefasst, [`merge_thin_cuts`];
/// Detail „fein" zeigt alle Schichten, `style::simplify_thin_layers`). Ab 1:100 (`style::solid_cut`, ausser
/// `cut_hatch`/„fein") sind die geschnittenen Flächen schwarz ohne Fugen und Schraffur, nur mit dem Umriss.
pub fn section_primitives_at(out: &Output, mono: bool, hidden_lines: bool, vis: &Visibility, scale: f64, detail: Detail, cut_hatch: bool) -> (Vec<Primitive>, [f64; 4]) {
/// `cut_hatch`/„fein") sind die geschnittenen Flächen schwarz ohne Fugen und Schraffur, nur mit dem Umriss —
/// ausser Schichten aus losen Schüttungen/Unterbau (`loose`, s. [`loose_cut`]): die bleiben schraffiert.
#[allow(clippy::too_many_arguments)]
pub fn section_primitives_at(out: &Output, mono: bool, hidden_lines: bool, vis: &Visibility, scale: f64, detail: Detail, cut_hatch: bool, loose: &HashSet<String>) -> (Vec<Primitive>, [f64; 4]) {
let black = solid_cut(detail, scale, cut_hatch);
let thin_scale = if simplify_thin_layers(detail, scale) && !black { scale } else { 0.0 };
let merged = plain_thin_insulation(merge_thin_cuts(&out.cuts, thin_scale), thin_scale);
@@ -2438,6 +2452,7 @@ pub fn section_primitives_at(out: &Output, mono: bool, hidden_lines: bool, vis:
let fill = cp.fill.as_deref().unwrap_or(HATCH_PAPER);
let hatch = cp.hatch.clone().unwrap_or_else(section_hatch);
let solid = hatch.pattern == HatchPattern::Solid;
let black = black && !loose_cut(cp, loose);
let (fill, hatch) = if black {
(HATCH_INK.to_string(), no_hatch())
} else if mono {
@@ -2958,7 +2973,7 @@ pub fn section_plan_buf(p: &Project, args: &[f64], text: &str) -> Result<Vec<u8>
let hidden = v.get("hiddenLines").and_then(|b| b.as_bool()).unwrap_or(false);
let scale = v.get("scale").and_then(|s| s.as_f64()).filter(|s| *s > 0.0 && s.is_finite()).unwrap_or(100.0);
let detail = Detail::parse(v.get("detail").and_then(|d| d.as_str()).unwrap_or("mittel"));
let (mut prims, bounds) = section_primitives_at(&out, mono, hidden, &vis, scale, detail, level.cut_hatch);
let (mut prims, bounds) = section_primitives_at(&out, mono, hidden, &vis, scale, detail, level.cut_hatch, &loose_fill_components(p));
w.post = super::extras::sketch_post(Some(level.sketch), scale);
// Strichstärken nach Massstab ([32]) wie im Grundriss.
super::extras::scale_line_weights(p, scale, &mut prims);
@@ -3172,6 +3187,43 @@ mod tests {
assert_eq!(merge_thin_cuts(&cuts, 20.0).len(), 4);
}
/// [140] Teil 6: Unterbau-Schichten (Kies, Magerbeton, Erdreich) bleiben im Schnitt 1:100 schraffiert mit
/// Fuge; die Bodenplatte darüber schwarz. Erkannt am Bauteil (`loose_fill_components`) oder an der Schraffur.
#[test]
fn unterbau_im_schnitt_1_100_nicht_schwarz() {
let rect = |v0: f64, v1: f64| vec![[0.0, v1], [5.0, v1], [5.0, v0], [0.0, v0]];
let cut = |comp: &str, v0: f64, v1: f64, pattern: HatchPattern| {
let mut c = Cut::new(Kind::Slab, 0, rect(v0, v1));
c.component_id = Some(comp.into());
c.source_id = Some("c-bodenplatte".into());
c.hatch = Some(HatchRender { pattern, ..section_hatch() });
c.fill = Some(HATCH_PAPER.into());
c
};
let out = Output {
cuts: vec![cut("std-c-stahlbeton", -0.25, 0.0, HatchPattern::Diagonal), cut("mager", -0.3, -0.25, HatchPattern::Diagonal), cut("std-c-kies", -0.4, -0.3, HatchPattern::Gravel)],
..Default::default()
};
let loose: HashSet<String> = ["mager".to_string()].into();
let fills = |scale: f64, loose: &HashSet<String>| -> Vec<(String, HatchPattern, String)> {
let (prims, _) = section_primitives_at(&out, true, false, &Visibility::default(), scale, Detail::Mittel, false, loose);
prims.iter().filter_map(|q| match q { Primitive::Polygon { fill, hatch, stroke, ceiling_id: Some(_), .. } => Some((fill.clone(), hatch.pattern, stroke.clone())), _ => None }).collect()
};
let f = fills(100.0, &loose);
assert_eq!(f[0], (HATCH_INK.to_string(), HatchPattern::None, "none".to_string()), "Platte schwarz");
assert_eq!(f[1].1, HatchPattern::Diagonal, "Magerbeton (Bauteil) schraffiert");
assert_ne!(f[1].0, HATCH_INK);
assert_eq!(f[2].1, HatchPattern::Gravel, "Kies (Schraffur) schraffiert");
assert_ne!(f[2].2, "none", "mit Fuge");
// Ohne Bauteil-Liste: nur die Kies-Schraffur erkannt.
let f = fills(100.0, &HashSet::new());
assert_eq!(f[1].0, HATCH_INK);
assert_eq!(f[2].1, HatchPattern::Gravel);
// Musterhaus komplex: die Kies-Schicht der Bodenplatte ist ein loses Bauteil.
let p = sample();
assert!(loose_fill_components(&p).iter().all(|id| p.components.iter().any(|c| &c.id == id && crate::standards::is_loose_fill(c))));
}
/// [140] Teil 5: Schnitt 1:100 — geschnittene Flächen schwarz ohne Fuge/Schraffur, Umriss bleibt;
/// 1:50, „fein" und `cutHatch` mit Schraffur und Fugen.
#[test]
@@ -3181,7 +3233,7 @@ mod tests {
let out = compute_section(&p, &l, &[]).unwrap().unwrap();
let vis = Visibility::default();
let stat = |scale: f64, detail: Detail, cut_hatch: bool| {
let (prims, _) = section_primitives_at(&out, true, false, &vis, scale, detail, cut_hatch);
let (prims, _) = section_primitives_at(&out, true, false, &vis, scale, detail, cut_hatch, &loose_fill_components(&p));
let cuts: Vec<_> = prims.iter().filter_map(|q| match q { Primitive::Polygon { fill, hatch, stroke, wall_id, ceiling_id, .. } if wall_id.is_some() || ceiling_id.is_some() => Some((fill.clone(), hatch.pattern, stroke.clone())), _ => None }).collect();
let outline = prims.iter().filter(|q| matches!(q, Primitive::Line { cls, .. } if cls == "section-cut-outline")).count();
(cuts, outline)
+303
View File
@@ -0,0 +1,303 @@
//! [140] Hindernisse für Raumstempel: anderer Planinhalt im Raum (Treppen, Türschwenk-Bögen, Bemassung,
//! Koten, Texte, Symbole, Höhenlinien-Beschriftungen), dem ein Stempel ohne eigenen Anker ausweicht.
//! Hindernisse sind Strecken und Flächen (Türschwenk als Kreissektor, Text als gedrehtes Rechteck); die
//! Lage eines Stempel-Rechtecks wird nach seinem Abstand zum nächsten Hindernis bewertet (0 = überlappt).
use super::prim::Primitive;
use crate::jsmath::hypot2;
use crate::jsnum;
use crate::model::Vec2;
type P = [f64; 2];
/// Gewicht einer überdeckten Fläche (Text, Türschwenk) gegenüber einer gekreuzten Strecke ([`Obstacles::overlap`]):
/// ein überdeckter Text ist schlimmer als ein paar gekreuzte Treppenstufen.
pub const AREA_WEIGHT: f64 = 8.0;
/// Hindernisse eines Geschosses in Modell-Metern.
#[derive(Default, Debug, Clone)]
pub struct Obstacles {
segs: Vec<[P; 2]>,
/// Geschlossene Flächen (Ringe, ohne Wiederholung des ersten Punkts).
areas: Vec<Vec<P>>,
}
/// Strecken eines Bogens (CCW von `a0` um `sweep`) als Punktfolge.
fn arc_pts(c: Vec2, r: f64, a0: f64, sweep: f64) -> Vec<P> {
let n = ((sweep.abs() / (std::f64::consts::PI / 16.0)).ceil() as usize).clamp(2, 64);
(0..=n)
.map(|i| {
let a = a0 + sweep * i as f64 / n as f64;
[c.x + r * jsnum::cos(a), c.y + r * jsnum::sin(a)]
})
.collect()
}
fn finite(p: &P) -> bool {
p[0].is_finite() && p[1].is_finite()
}
impl Obstacles {
pub fn is_empty(&self) -> bool {
self.segs.is_empty() && self.areas.is_empty()
}
pub fn seg(&mut self, a: P, b: P) {
if finite(&a) && finite(&b) {
self.segs.push([a, b]);
}
}
pub fn area(&mut self, ring: Vec<P>) {
if ring.len() >= 3 && ring.iter().all(finite) {
self.areas.push(ring);
}
}
fn polyline(&mut self, pts: &[P]) {
for w in pts.windows(2) {
self.seg(w[0], w[1]);
}
}
/// Text als Rechteck: Grundlinie links am Anker, Breite aus der Schriftmetrik (Inter), Höhe von
/// 0.25 Schriftgrösse unter bis 0.95 über der Grundlinie, gedreht um `angle` (Bogenmass, CCW).
pub fn text(&mut self, at: Vec2, text: &str, height: f64, angle: f64) {
if !(height > 0.0) || text.trim().is_empty() {
return;
}
let w = crate::text_layout::text_width_em(text, false) * height;
let (c, s) = (jsnum::cos(angle), jsnum::sin(angle));
let ring = [[0.0, -0.25 * height], [w, -0.25 * height], [w, 0.95 * height], [0.0, 0.95 * height]]
.iter()
.map(|q| [at.x + q[0] * c - q[1] * s, at.y + q[0] * s + q[1] * c])
.collect();
self.area(ring);
}
/// Ein Primitiv als Hindernis übernehmen: Linien/Bögen/Kreise als Strecken, Polygone als Kanten,
/// Bögen mit Öffnung (Türschwenk) als Kreissektor, Texte als Rechteck. Raumstempel nicht.
pub fn add_prim(&mut self, q: &Primitive) {
match q {
Primitive::Line { a, b, .. } => self.seg([a.x, a.y], [b.x, b.y]),
Primitive::Polygon { pts, .. } => {
let ring: Vec<P> = pts.iter().map(|v| [v.x, v.y]).collect();
if ring.len() >= 2 {
self.polyline(&ring);
self.seg(ring[ring.len() - 1], ring[0]);
}
}
Primitive::Arc { center, from, to, r, opening_id, .. } => {
let a0 = jsnum::atan2(from.y - center.y, from.x - center.x);
let mut sweep = jsnum::atan2(to.y - center.y, to.x - center.x) - a0;
while sweep < 0.0 && sweep.is_finite() {
sweep += 2.0 * std::f64::consts::PI;
}
if !sweep.is_finite() || !(*r > 0.0) {
return;
}
let pts = arc_pts(*center, *r, a0, sweep);
if opening_id.is_some() {
// Türschwenk: die überstrichene Fläche bleibt frei.
let mut ring = vec![[center.x, center.y]];
ring.extend(pts);
self.area(ring);
} else {
self.polyline(&pts);
}
}
Primitive::DrawingArc { center, r, a0, a1, .. } => {
let mut sweep = a1 - a0;
while sweep < 0.0 && sweep.is_finite() {
sweep += 2.0 * std::f64::consts::PI;
}
if sweep.is_finite() && *r > 0.0 {
self.polyline(&arc_pts(*center, *r, *a0, sweep));
}
}
Primitive::DrawingCircle { center, r, .. } => {
if *r > 0.0 {
let mut ring = arc_pts(*center, *r, 0.0, 2.0 * std::f64::consts::PI);
ring.pop();
self.area(ring);
}
}
Primitive::DrawingText { at, text, height_m, angle, .. } => self.text(*at, text, *height_m, *angle),
Primitive::Text { .. } | Primitive::DrawingTextPath { .. } | Primitive::DrawingImage { .. } => {}
}
}
/// Nur die Hindernisse, die das Rechteck `[x0, y0, x1, y1]` berühren (je Raum vorab gefiltert).
pub fn within(&self, b: [f64; 4]) -> Obstacles {
let hit = |pts: &[P]| {
let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
for q in pts {
x0 = x0.min(q[0]);
y0 = y0.min(q[1]);
x1 = x1.max(q[0]);
y1 = y1.max(q[1]);
}
x1 >= b[0] && x0 <= b[2] && y1 >= b[1] && y0 <= b[3]
};
Obstacles { segs: self.segs.iter().filter(|s| hit(&s[..])).copied().collect(), areas: self.areas.iter().filter(|a| hit(a)).cloned().collect() }
}
/// Wie stark überdeckt das Rechteck (Mitte `c`, halbe Breite/Höhe) Hindernisse? Jede geschnittene Strecke
/// zählt 1, jede berührte Fläche (Text, Türschwenk) [`AREA_WEIGHT`] — für die Wahl, wenn keine Lage frei ist.
pub fn overlap(&self, c: Vec2, hw: f64, hh: f64) -> f64 {
let r = [c.x - hw, c.y - hh, c.x + hw, c.y + hh];
let segs = self.segs.iter().filter(|s| seg_hits_rect(s[0], s[1], r)).count() as f64;
let areas = self.areas.iter().filter(|a| point_in_ring(a, [c.x, c.y]) || (0..a.len()).any(|i| seg_hits_rect(a[i], a[(i + 1) % a.len()], r))).count() as f64;
segs + AREA_WEIGHT * areas
}
/// Abstand des achsparallelen Rechtecks (Mitte `c`, halbe Breite/Höhe) zum nächsten Hindernis;
/// 0, wenn es eines schneidet oder enthält bzw. in einer Fläche liegt. Ohne Hindernisse: unendlich.
pub fn clearance(&self, c: Vec2, hw: f64, hh: f64) -> f64 {
let r = [c.x - hw, c.y - hh, c.x + hw, c.y + hh];
let mut d = f64::INFINITY;
for s in &self.segs {
d = d.min(seg_rect_dist(s[0], s[1], r));
if d <= 0.0 {
return 0.0;
}
}
for a in &self.areas {
if point_in_ring(a, [c.x, c.y]) {
return 0.0;
}
for i in 0..a.len() {
d = d.min(seg_rect_dist(a[i], a[(i + 1) % a.len()], r));
if d <= 0.0 {
return 0.0;
}
}
}
d
}
}
fn point_in_ring(ring: &[P], p: P) -> bool {
let mut inside = false;
let n = ring.len();
let mut j = n - 1;
for i in 0..n {
let (a, b) = (ring[i], ring[j]);
if (a[1] > p[1]) != (b[1] > p[1]) && p[0] < (b[0] - a[0]) * (p[1] - a[1]) / (b[1] - a[1]) + a[0] {
inside = !inside;
}
j = i;
}
inside
}
fn pt_rect_dist(p: P, r: [f64; 4]) -> f64 {
let dx = (r[0] - p[0]).max(0.0).max(p[0] - r[2]);
let dy = (r[1] - p[1]).max(0.0).max(p[1] - r[3]);
hypot2(dx, dy)
}
fn pt_seg_dist(p: P, a: P, b: P) -> f64 {
let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
let l2 = dx * dx + dy * dy;
let t = if l2 > 0.0 { (((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / l2).clamp(0.0, 1.0) } else { 0.0 };
hypot2(p[0] - (a[0] + t * dx), p[1] - (a[1] + t * dy))
}
/// Schneidet die Strecke das Rechteck (Liang–Barsky)?
fn seg_hits_rect(a: P, b: P, r: [f64; 4]) -> bool {
let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
let (mut t0, mut t1) = (0.0f64, 1.0f64);
for (p, q) in [(-dx, a[0] - r[0]), (dx, r[2] - a[0]), (-dy, a[1] - r[1]), (dy, r[3] - a[1])] {
if p == 0.0 {
if q < 0.0 {
return false;
}
} else {
let t = q / p;
if p < 0.0 {
t0 = t0.max(t);
} else {
t1 = t1.min(t);
}
if t0 > t1 {
return false;
}
}
}
true
}
/// Abstand Strecke–Rechteck (0 bei Schnitt).
fn seg_rect_dist(a: P, b: P, r: [f64; 4]) -> f64 {
if seg_hits_rect(a, b, r) {
return 0.0;
}
let corners = [[r[0], r[1]], [r[2], r[1]], [r[2], r[3]], [r[0], r[3]]];
let mut d = pt_rect_dist(a, r).min(pt_rect_dist(b, r));
for c in corners {
d = d.min(pt_seg_dist(c, a, b));
}
d
}
#[cfg(test)]
mod tests {
use super::*;
fn v(x: f64, y: f64) -> Vec2 {
Vec2 { x, y }
}
#[test]
fn abstand_zu_strecken_und_flaechen() {
let mut o = Obstacles::default();
o.seg([0.0, 0.0], [10.0, 0.0]);
assert_eq!(o.clearance(v(5.0, 2.0), 1.0, 1.0), 1.0);
assert_eq!(o.clearance(v(5.0, 0.5), 1.0, 1.0), 0.0, "Strecke schneidet das Rechteck");
let mut a = Obstacles::default();
a.area(vec![[0.0, 0.0], [4.0, 0.0], [4.0, 4.0], [0.0, 4.0]]);
assert_eq!(a.clearance(v(2.0, 2.0), 0.5, 0.5), 0.0, "Rechteck liegt in der Fläche");
assert!((a.clearance(v(7.0, 2.0), 1.0, 1.0) - 2.0).abs() < 1e-12);
assert_eq!(Obstacles::default().clearance(v(0.0, 0.0), 1.0, 1.0), f64::INFINITY);
// Überdeckung: Strecken zählen 1, Flächen (auch ganz umschlossen) mehr.
let mut m = Obstacles::default();
m.seg([0.0, 0.0], [0.0, 10.0]);
m.seg([1.0, 0.0], [1.0, 10.0]);
m.area(vec![[5.0, 5.0], [5.2, 5.0], [5.2, 5.2]]);
assert_eq!(m.overlap(v(0.5, 5.0), 1.0, 0.5), 2.0);
assert_eq!(m.overlap(v(5.0, 5.0), 1.0, 1.0), AREA_WEIGHT);
assert_eq!(m.overlap(v(3.0, 2.0), 0.5, 0.5), 0.0);
// Unsinn wird verworfen.
let mut n = Obstacles::default();
n.seg([f64::NAN, 0.0], [1.0, 1.0]);
n.area(vec![[0.0, 0.0], [1.0, f64::NAN], [1.0, 1.0]]);
assert!(n.is_empty());
}
#[test]
fn tuerschwenk_als_sektor_text_als_rechteck() {
let mut o = Obstacles::default();
let arc = Primitive::Arc {
center: v(0.0, 0.0),
from: v(1.0, 0.0),
to: v(0.0, 1.0),
r: 1.0,
cls: "door".into(),
weight_mm: 0.13,
dash: None,
color: None,
opening_id: Some("o".into()),
stair_id: None,
greyed: None,
opacity: None,
};
o.add_prim(&arc);
assert_eq!(o.clearance(v(0.3, 0.3), 0.05, 0.05), 0.0, "im Schwenkbereich");
assert!(o.clearance(v(-1.0, -1.0), 0.1, 0.1) > 0.5);
let mut t = Obstacles::default();
t.text(v(0.0, 0.0), "±0.00", 0.2, 0.0);
assert_eq!(t.clearance(v(0.3, 0.05), 0.01, 0.01), 0.0);
assert!(t.clearance(v(0.3, 1.0), 0.01, 0.01) > 0.5);
}
}
+80 -28
View File
@@ -17,6 +17,50 @@ use std::collections::HashMap;
use serde_json::Value;
use std::f64::consts::PI;
/// [140] Raumstempel (Text-JSON eines `text`-Primitivs) als `<text>`-Block wie gemessen und wie die Plan-Ansicht
/// ([`crate::text_layout::stamp_block`]): Name mit seinen Auszeichnungen (Stempel: 12 pt fett), Zusatzzeilen
/// 0.8 × Grundgrösse, Zeilenvorschub 1.3, Block um den Anker zentriert; Schrift Inter (Rückfall sans-serif).
/// `x`/`y0` = Anker in SVG-Koordinaten, `mm_to_m` = Modell-Meter je Papier-mm.
fn stamp_svg(v: &Value, x: f64, y0: f64, mm_to_m: f64) -> String {
use crate::model::RichTextDoc;
use crate::text_layout::{stamp_block, stamp_line_offsets, LineAlign, PT_TO_MM};
let doc: RichTextDoc = v.get("doc").and_then(|d| serde_json::from_value(d.clone()).ok()).unwrap_or_default();
let extra: Vec<crate::plan::prim::StampLine> = v.get("extraLines").and_then(|d| serde_json::from_value(d.clone()).ok()).unwrap_or_default();
let rows: Vec<(&str, LineAlign)> = extra.iter().map(|l| (l.text.as_str(), LineAlign::of(Some(l.align)))).collect();
let color = jstr(v, "color").unwrap_or("");
let o = op_json(v);
// In Papier-mm setzen (Schriftgrössen auf 1/1000 gerundet), dann in Modell-Meter umrechnen.
let placed = stamp_block(&doc, &rows, jnum(v, "basePt"), PT_TO_MM, color, 0.0);
let dx = stamp_line_offsets(&placed);
placed
.iter()
.zip(dx)
.filter(|(p, _)| p.line.tspans.iter().any(|t| !t.text.is_empty()))
.map(|(p, dx)| {
let spans: String = p
.line
.tspans
.iter()
.map(|t| {
let mut a = format!(" font-size=\"{}\" fill=\"{}\"", num(t.font_size * mm_to_m), esc(&t.fill));
if let Some(w) = t.font_weight() {
a.push_str(&format!(" font-weight=\"{w}\""));
}
if let Some(st) = t.font_style() {
a.push_str(&format!(" font-style=\"{st}\""));
}
if let Some(f) = &t.font_family {
a.push_str(&format!(" font-family=\"{}\"", esc(f)));
}
format!("<tspan{a}>{}</tspan>", esc(&t.text))
})
.collect();
format!("<text x=\"{}\" y=\"{}\" font-family=\"Inter, sans-serif\" text-anchor=\"{}\"{o}>{spans}</text>", num(x + dx * mm_to_m), num(y0 + p.y * mm_to_m), p.line.align.anchor())
})
.collect::<Vec<_>>()
.join("\n")
}
/// `num()`: gerundet auf 1e-5, nicht endlich → "0".
fn num(v: f64) -> String {
if v.is_finite() {
@@ -335,34 +379,7 @@ pub fn plan_svg(parts: &mut [Part], o: &SvgOptions) -> Option<String> {
esc(jstr(&v, "text").unwrap_or(""))
));
} else {
let size = (jnum(&v, "basePt") * 0.3528) * mm_to_m;
// plainText(doc): Absätze (Runs verkettet) mit "\n".
let doc = v.get("doc").and_then(|d| d.get("paragraphs")).and_then(Value::as_array);
let plain = doc
.map(|ps| {
ps.iter()
.map(|p| p.get("runs").and_then(Value::as_array).map(|rs| rs.iter().map(|r| jstr(r, "text").unwrap_or("")).collect::<String>()).unwrap_or_default())
.collect::<Vec<_>>()
.join("\n")
})
.unwrap_or_default();
let mut lines = vec![plain];
if let Some(ex) = v.get("extraLines").and_then(Value::as_array) {
for l in ex {
lines.push(jstr(l, "text").unwrap_or("").to_owned());
}
}
let color = esc(jstr(&v, "color").unwrap_or(""));
let o = op_json(&v);
for (k, ln) in lines.iter().filter(|s| !s.is_empty()).enumerate() {
out.push(format!(
"<text x=\"{}\" y=\"{}\" font-size=\"{}\" fill=\"{color}\" font-family=\"sans-serif\" text-anchor=\"middle\"{o}>{}</text>",
xs(ax),
num(top - ay + k as f64 * size * 1.2),
num(size),
esc(ln)
));
}
out.push(stamp_svg(&v, ax, top - ay, mm_to_m));
}
}
_ => {}
@@ -401,6 +418,41 @@ mod tests {
assert_eq!(op(false, Some(1.0)), "");
}
/// [140] Raumstempel wie gemessen (`stamp_block`): Name in seinen Auszeichnungen (fett, eigene Grösse),
/// Zusatzzeilen 0.8 ×, Block um den Anker zentriert, Schrift Inter mit sans-serif-Rückfall.
#[test]
fn raumstempel_wie_gemessen() {
use crate::model::{Align, Marks, Vec2};
use crate::plan::buf::{View, Writer};
use crate::plan::prim::{Primitive, StampLine};
let bold = Marks { bold: Some(true), size_pt: Some(12.0), ..Default::default() };
let doc = crate::text_layout::doc_from_text("Wohnen", &bold);
let mut w = Writer::new(true);
let g = w.begin_group();
w.push(&Primitive::Text { at: Vec2 { x: 2.0, y: 2.0 }, doc, extra_lines: vec![StampLine { text: "20.00 m²".into(), align: Align::Center }], base_pt: 10.0, color: "#111111".into(), room_id: Some("r".into()), greyed: None, opacity: None });
w.end_group(g);
let bytes = w.finish();
let view = View::parse(&bytes).unwrap();
let n = view.len();
let mut parts = vec![Part::new(view, 0, n).unwrap()];
let o = SvgOptions { scale_denominator: 100.0, margin_m: 0.0, min_x: 0.0, min_y: 0.0, max_x: 4.0, max_y: 4.0, hatch: false, line_ends: LineEnds::default() };
let svg = plan_svg(&mut parts, &o).unwrap();
let texts: Vec<&str> = svg.lines().filter(|l| l.starts_with("<text")).collect();
assert_eq!(texts.len(), 2, "{svg}");
assert!(texts.iter().all(|t| t.contains("font-family=\"Inter, sans-serif\"")), "{texts:?}");
// 12 pt = 4.233 mm Papier = 0.4233 m bei 1:100; Zusatzzeile 0.8 × 10 pt = 0.28222 m.
assert!(texts[0].contains("font-size=\"0.4233\"") && texts[0].contains("font-weight=\"700\""), "{}", texts[0]);
assert!(texts[1].contains("font-size=\"0.28222\"") && !texts[1].contains("font-weight") && texts[1].contains("text-anchor=\"middle\""), "{}", texts[1]);
let x = |t: &str| t.split("x=\"").nth(1).unwrap().split('"').next().unwrap().parse::<f64>().unwrap();
// Linksbündiger Name beginnt am linken Rand des um den Anker zentrierten Blocks (breiteste Zeile).
let w = crate::text_layout::text_width_em("Wohnen", true) * 0.4233;
assert!(texts[0].contains("text-anchor=\"start\"") && (x(texts[0]) - (2.0 - w / 2.0)).abs() < 1e-4, "{}", texts[0]);
assert_eq!(x(texts[1]), 2.0);
// Block um den Anker (SVG y = 4 − 2 = 2) zentriert: erste Grundlinie darüber, zweite darunter.
let y = |t: &str| t.split("y=\"").nth(1).unwrap().split('"').next().unwrap().parse::<f64>().unwrap();
assert!(y(texts[0]) < 2.0 && y(texts[1]) > 2.0, "{texts:?}");
}
/// [146] Wand-Umrisse als volle Linie bzw. offene Kantenläufe (Stossfugen nicht gestrichen) werden
/// an der gemeinsamen Ecke zu EINEM Zug genäht (Gehrung statt zweier flacher Enden = keine Kerbe);
/// Enden und Ecken stehen einmal am umschliessenden `<g>`.
+10 -3
View File
@@ -13,7 +13,7 @@ use crate::plan::buf::{whole, T_DRAWING_TEXT, T_TEXT};
use crate::plan::dxf::{StampLine as DxfLine, TextIn, TextStyleIn};
use crate::plan::parts::{in_ranges, Part};
use crate::plan::scene::{to_rgba, Rgba, SText};
use crate::text_layout::{doc_from_text, doc_to_lines, font_name_of, is_blank, plain_text, split_ws, stamp_block, wrap_doc_to_lines, LayoutOpts, LineAlign, Placed, PT_TO_MM, TEXT_LINE_HEIGHT_MULT};
use crate::text_layout::{doc_from_text, doc_to_lines, font_name_of, is_blank, plain_text, split_ws, stamp_block, stamp_line_offsets, wrap_doc_to_lines, LayoutOpts, LineAlign, Placed, PT_TO_MM, TEXT_LINE_HEIGHT_MULT};
use serde::{Deserialize, Deserializer};
fn num<'de, D: Deserializer<'de>>(d: D) -> Result<f64, D::Error> {
@@ -169,11 +169,15 @@ fn stamp_scene(t: &StampText, forced: bool, mm_to_m: f64, out: &mut Vec<SText>)
let base_h = base_mm * mm_to_m;
let line_gap = base_h * 1.3;
let total_h = base_h + (flat.len() - 1) as f64 * line_gap;
// [140] Zeilen im gemessenen, um den Anker zentrierten Block (`stamp_line_offsets`, Papier-mm).
let extra: Vec<(&str, LineAlign)> = t.extra_lines.iter().map(|l| (l.text.as_str(), LineAlign::of(Some(l.align)))).collect();
let offsets = stamp_line_offsets(&stamp_block(&t.doc, &extra, t.base_pt, PT_TO_MM, "#000000", 0.0));
for (k, (content, size, c, align)) in flat.into_iter().enumerate() {
if is_blank(&content) {
continue;
}
push(out, t.at.x, t.at.y + total_h / 2.0 - base_h * 0.8 - k as f64 * line_gap, content, size, c, align);
let dx = offsets.get(k).copied().unwrap_or(0.0) * mm_to_m;
push(out, t.at.x + dx, t.at.y + total_h / 2.0 - base_h * 0.8 - k as f64 * line_gap, content, size, c, align);
}
}
@@ -248,7 +252,9 @@ fn stamp_lines(p: &StampText, scale: f64, family: &dyn Fn(Option<&str>) -> Strin
let unit_per_pt = (0.0254 / 72.0) * scale;
let extra: Vec<(&str, LineAlign)> = p.extra_lines.iter().map(|l| (l.text.as_str(), LineAlign::of(Some(l.align)))).collect();
let mut out = Vec::new();
for Placed { line, y } in stamp_block(&p.doc, &extra, p.base_pt, unit_per_pt, p.color.as_deref().unwrap_or("#000000"), 0.0) {
let placed = stamp_block(&p.doc, &extra, p.base_pt, unit_per_pt, p.color.as_deref().unwrap_or("#000000"), 0.0);
let offsets = stamp_line_offsets(&placed);
for (Placed { line, y }, dx) in placed.into_iter().zip(offsets) {
let text = line.content();
let Some(first) = line.tspans.first() else { continue };
if is_blank(&text) {
@@ -259,6 +265,7 @@ fn stamp_lines(p: &StampText, scale: f64, family: &dyn Fn(Option<&str>) -> Strin
align: line.align.code() as f64,
style: TextStyleIn { family: family(first.font_family.as_deref()), bold: first.bold, italic: first.italic },
down: y,
dx,
text,
});
}
+31
View File
@@ -564,6 +564,21 @@ pub fn update_ops(root: &Map<String, Value>, selected: &[String]) -> Vec<Value>
ops
}
/// [140] Baustoffe, die nicht tragen und keinen Raum bilden: lose bzw. ungebundene Schüttungen und Unterbau
/// (Kies, Schotter, Splitt, Sand, Sauberkeitsschicht/Magerbeton, Erdreich, Humus). Im Schnitt 1:100 bleiben
/// sie schraffiert statt schwarz (`plan::section`). Erkannt an der Standard-Kennung (`std-c-kies`,
/// `std-c-erdreich`) oder an Name/Kürzel (Gross-/Kleinschreibung egal, deutsch und englisch).
pub fn is_loose_fill(c: &crate::model::Component) -> bool {
const STD: [&str; 2] = ["std-c-kies", "std-c-erdreich"];
const WORDS: [&str; 16] = ["kies", "schotter", "splitt", "sand", "sauberkeit", "magerbeton", "erdreich", "humus", "rollierung", "koffer", "gravel", "ballast", "soil", "lean concrete", "blinding", "hardcore"];
if STD.contains(&c.id.as_str()) || c.standard_id.as_deref().is_some_and(|s| STD.contains(&s)) {
return true;
}
let name = c.name.to_lowercase();
// „Sandstein“, „Kalksandstein“ sind Mauerwerk, keine Schüttung.
WORDS.iter().any(|w| name.contains(w)) && !name.contains("stein")
}
#[cfg(test)]
mod tests {
use super::*;
@@ -591,6 +606,22 @@ mod tests {
r
}
/// [140] Lose Schüttungen/Unterbau erkannt, tragende und raumbildende Baustoffe (auch Dämmung) nicht.
#[test]
fn lose_schuettungen() {
let comps: Vec<crate::model::Component> = components().into_iter().map(|v| serde_json::from_value(v).unwrap()).collect();
let loose: Vec<&str> = comps.iter().filter(|c| is_loose_fill(c)).map(|c| c.id.as_str()).collect();
assert_eq!(loose, ["std-c-erdreich", "std-c-kies"]);
let named = |n: &str| crate::model::Component { id: "x".into(), name: n.into(), ..comps[0].clone() };
assert!(is_loose_fill(&named("Magerbeton C8/10")));
assert!(is_loose_fill(&named("Schotter / Koffer")));
assert!(!is_loose_fill(&named("Kalksandstein")));
assert!(!is_loose_fill(&named("Stahlbeton")));
let mut renamed = named("Unterlage");
renamed.standard_id = Some("std-c-kies".into());
assert!(is_loose_fill(&renamed));
}
/// [100] Leuchten: Symbol Deckenleuchte (Kreis mit Kreuz) und Kategorie „Leuchten“, nur einmal.
#[test]
fn leuchten_symbol_und_kategorie() {
+18
View File
@@ -596,6 +596,24 @@ pub fn text_width_em(text: &str, bold: bool) -> f64 {
w as f64 / 1000.0 * if bold { 1.05 } else { 1.0 }
}
/// [140] Waagrechte Lage jeder Zeile eines Raumstempels relativ zum Anker (gleiche Einheiten wie die Zeilen):
/// der Block ist so breit wie seine breiteste Zeile ([`stamp_block_size`]) und um den Anker zentriert; eine
/// linksbündige Zeile beginnt am linken Blockrand (−Breite/2), eine rechtsbündige endet am rechten (+Breite/2),
/// eine zentrierte steht am Anker. So liegt der gezeichnete Stempel im gemessenen Rechteck, mit dem
/// `plan::domains` ihn im Raum einpasst (vorher begann eine linksbündige Namenszeile am Anker).
pub fn stamp_line_offsets(placed: &[Placed]) -> Vec<f64> {
let width = |p: &Placed| p.line.tspans.iter().map(|t| text_width_em(&t.text, t.bold) * t.font_size).sum::<f64>();
let w = placed.iter().map(width).fold(0.0, f64::max);
placed
.iter()
.map(|p| match p.line.align {
LineAlign::Left => -w / 2.0,
LineAlign::Center => 0.0,
LineAlign::Right => w / 2.0,
})
.collect()
}
/// [140] Ausmass eines Raumstempels ([`stamp_block`]) in Einheiten von `unit_per_pt`: Breite der breitesten
/// Zeile (Summe der Tspans mit echter Metrik, [`text_width_em`]) und Höhe des Blocks (erste Zeile plus
/// Zeilenvorschübe, wie die Zentrierung in [`stamp_block_refs`]).
+3 -1
View File
@@ -108,7 +108,9 @@ pub fn text_stamp_block(prim_json: &str, unit_per_pt: f64, x0: f64, y0: f64) ->
let extra: Vec<(&str, LineAlign)> = p.extra_lines.iter().map(|l| (l.text.as_str(), LineAlign::of(Some(l.align)))).collect();
let color = p.color.as_deref().unwrap_or("#000000");
let placed = stamp_block_refs(&p.doc, &extra, p.base_pt, unit_per_pt, color, y0);
let at: Vec<(f64, f64)> = placed.iter().map(|q| (x0, q.1)).collect();
// [140] Zeilen im gemessenen, um den Anker zentrierten Block (`stamp_line_offsets`).
let dx = crate::text_layout::stamp_line_offsets(&crate::text_layout::stamp_block(&p.doc, &extra, p.base_pt, unit_per_pt, color, y0));
let at: Vec<(f64, f64)> = placed.iter().enumerate().map(|(k, q)| (x0 + dx.get(k).copied().unwrap_or(0.0), q.1)).collect();
let lines: Vec<LineRef> = placed.into_iter().map(|q| q.0).collect();
let n = p.doc.paragraphs.len();
encode_lines(&lines, &at, |t| {