Merge origin/master

This commit is contained in:
Claude committed 2026-10-29 23:57:38 +00:00
commit c7cd9d4509
35 files changed
+1707 -33

No files matched your search

+33
View File
@@ -1375,6 +1375,39 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]).
Tests: `commands/engine.keys.test.ts` (jeder Befehl), `state/commandKeys.test.ts`, e2e `commandKeys.spec.ts` (jeder
registrierte Befehl: Punkte, Esc, Esc-Esc, Enter; Fokus Befehlsfeld/Fläche/Panel-Knopf; Wandzug in allen drei).
Offen: 3D-Ansicht und Layout-Blatt nur über den gemeinsamen Verteiler, nicht eigens per e2e; nicht auf dem Mac geprüft. · S
- ◐ **[100] Standard-Baustoffe und Ansichtsschraffur (SIA 400).** (29.10., Wunsch Maintainer) Kern `standards.rs`:
33 Baustoffe/Bekleidungen (Beton, Stahlbeton, Backstein, Kalksandstein, Porenbeton, Holz massiv, Brettsperrholz,
Holzwerkstoff, Mineral-/Steinwolle, EPS, XPS, Holzfaser, Trittschall, Gipskarton, Innen-/Aussenputz, Zementestrich,
Glas, Stahl, Aluminium, Naturstein, Erdreich, Kies/Sauberkeitsschicht, Luftschicht, Lattung vertikal/horizontal,
Boden-Deckel, Schindeln, Trapezblech, Faserzement, Tonziegel) je mit SIA-400-Schnittschraffur, Füll- und
Ansichtsfarbe, Ansichtsschraffur, 3D-Textur (gebündelt aus `manifest.json`, sonst nur ambientCG-Kennung →
„Textur laden" im Bauteil-Dialog) und Kennwerten (neue Felder `Component.lambda`/`density`/`fireClass` (VKF
RF1–RF4)/`elevationColor`/`surfacePattern`/`standardId`); Aufbauten Aussenwand verputzt mit Aussendämmung,
Innenwand Backstein, Holzständerwand hinterlüftet, Stahlbetondecke mit Trittschall + Estrich, Steildach Holz
gedämmt. Ansichtsschraffur (`surface_pattern.rs`): Linien/Lattung, Boden-Deckel, Läuferverband, Schindeln,
Trapezblech, Naturstein polygonal, Plattenteilung; Ausrichtung am Element (Wand: ab Wandanfang/UK; Dach:
traufparallel/Falllinie ab Traufe), je Element drehbar/versetzbar (`Wall`/`Roof.surfacePatternAngle`/`Offset`,
Attribute-Panel); Massstab: unter 0.7 mm Papierabstand jede 2./4./8. Linie, darunter weg (Ansicht bekommt den
Massstab als 3. Argument). Ansicht: sichtbare Wandseite (rechts der Achse = äusserste Schicht) mit Ansichtsfarbe
+ Muster, Dachflächen; verdeckt wie die Kanten, Maler-Tiefe der eigenen Fläche. Grundriss: Dachaufsicht je
Dachfläche (`roof-surface-pattern`). Geprüft: Rust-Tests (Muster, Ausdünnung, Ansicht, Dachaufsicht,
Bibliothek), CLI-Ansicht 1:50/1:500 und Druck-SVG Grundriss/Schnitt angesehen (Linux-Container). Offen: 3D-
Linien (render3d) nicht umgesetzt; Decken-Untersicht/Bodenbeläge ohne Muster; Schnittschraffur-Strichmuster
(Beton unbewehrt, Estrich) im Schnitt-Druck durchgezogen; ambientCG-Kennungen CorrugatedSteel005, WoodSiding008,
Chipboard001 ohne Netz nicht geprüft; nicht in der Tauri-App/macOS geprüft. · M
- ◐ **[101] Standards in neuen Projekten, „Standards laden".** (29.10.) Neu/Neu aus Musterhaus bringen die
Standards mit (`withStandards`, Kern-Abfrage `standardsMergeOps`); Ressourcen-Manager-Kopf: „Standards laden"
ergänzt nur Fehlendes (gleiche id oder gleicher Name = vorhanden, Verweise neuer Aufbauten zeigen dann auf das
vorhandene Bauteil), ein Undo-Schritt. Offen: Rückmeldung (Anzahl) nach dem Laden. · S
- ◐ **[102] Linientypen nach SIA 400 / ISO 128.** (29.10.) Standard-Linienstile: Volllinie, Strichlinie fein/grob,
Punktlinie, Strichpunktlinie (Achse), Strich-Zweipunktlinie, Grundstücksgrenze, Baulinie/Bauteilgrenze,
Bruchlinie (Zickzack), Schraffurlinien. Fehler behoben: render2d warf Punkte (AN = 0) aus dem Muster und
verschob AN/AUS (Strichpunkt wurde Strichlinie) — Szenen- und Chunk-Pfad (`gpu_compile.rs`) behalten sie, der
Shader zeichnet sie rund; Bögen mit Punkten/> 4 Einträgen über den Linien-Strichpfad; Strichmuster skalieren auf
dem Bildschirm mit dem Massstab (`dash_scale` = N/100 in Linien-, Strich- und Bogen-Uniforms, vorher fest 1:100);
SVG-Export setzt runde Kappen bei Punkten. DXF/DWG: LTYPE je Linienstil (Name, Punkt = 0) wie bisher. Geprüft:
Rust-Tests (render2d, Kern), naga-Validierung der Shader, Druck-SVG (PDF-Pfad) mit allen Typen angesehen.
Offen: Bildschirm (WebGPU) nicht angesehen; CPU-Rückfall (> 8 Einträge) verliert Punkte. · S
- ○ **[80] PDF mit Ebenen.** · M
- ◐ **[81] Automatische Aussenbemassung.** (27.10.) Befehl `autodim` (Kürzel `ab`): je Seite Öffnungs-,
Vor-/Rücksprung- und Gesamtkette. Offen: schiefe Wände, Massstab aus der Ansicht statt fest 1:100.
+13 -2
View File
@@ -702,8 +702,9 @@ impl Compiler {
/// Strichmuster (Papier-mm) → Zyklus in Modell-Metern wie `split_dash` in render2d: negative Werte
/// zu 0, Nullen weg, ungerade Länge verdoppelt. `None` = kein gültiges Muster (durchgezogen).
fn dash_cycle_m(dash: &[f64]) -> Option<Vec<f64>> {
let pat: Vec<f64> = dash.iter().map(|&d| jsnum::max(0.0, d) * LINE_DASH_MM_TO_M).filter(|&d| d > 0.0).collect();
if pat.is_empty() {
// Nullen bleiben stehen ([96]): AN = 0 ist ein Punkt (rund, wie im Szenen-Pfad `render2d`).
let pat: Vec<f64> = dash.iter().map(|&d| if d.is_finite() { jsnum::max(0.0, d) * LINE_DASH_MM_TO_M } else { 0.0 }).collect();
if pat.iter().all(|&d| d <= 0.0) {
return None;
}
let cycle: Vec<f64> = if pat.len() % 2 == 0 { pat } else { [pat.as_slice(), pat.as_slice()].concat() };
@@ -1030,6 +1031,16 @@ mod tests {
assert!(triangulate(&sq[..2]).is_empty());
}
#[test]
fn punkte_bleiben_im_strichmuster() {
// [96] Strichpunktlinie: Strich, Lücke, Punkt (0), Lücke — vier Einträge, AN/AUS nicht verschoben.
let c = dash_cycle_m(&[12.0, 1.5, 0.0, 1.5]).unwrap();
assert_eq!(c, vec![12.0 * LINE_DASH_MM_TO_M, 1.5 * LINE_DASH_MM_TO_M, 0.0, 1.5 * LINE_DASH_MM_TO_M]);
assert_eq!(dash_cycle_m(&[0.0, 1.0]).unwrap().len(), 2, "Punktlinie");
assert!(dash_cycle_m(&[0.0, 0.0]).is_none());
assert!(dash_cycle_m(&[f64::NAN]).is_none());
}
#[test]
fn linienzug_wird_zusammengefasst() {
let single = line_idx_count(&plan(vec![line(0.0, 1.0, false)]));
+2
View File
@@ -111,6 +111,8 @@ pub mod snap_model;
pub mod solid_specs;
pub mod highlight3d;
pub mod opening_presets;
pub mod surface_pattern;
pub mod standards;
#[cfg(feature = "web")]
mod web;
+128
View File
@@ -403,6 +403,88 @@ pub struct ComponentMaterial {
pub extra: Extra,
}
/// Art einer Ansichtsschraffur ([100]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, TS)]
pub enum SurfacePatternKind {
/// Parallele Linien im Abstand `spacing` (Lattung, Schalung, Stehfalz).
#[default]
#[serde(rename = "lines")]
Lines,
/// Boden-Deckel-Schalung: Deckleisten der Breite `width` im Abstand `spacing`.
#[serde(rename = "boardBatten")]
BoardBatten,
/// Läuferverband: Lagen der Höhe `height`, Stossfugen alle `spacing`, je Lage um ½ versetzt.
#[serde(rename = "runningBond")]
RunningBond,
/// Schindeln: Lagen der Höhe `height`, Stossfugen alle `spacing`, je Lage um ⅓ versetzt.
#[serde(rename = "shingles")]
Shingles,
/// Trapezblech: je Rippe (Abstand `spacing`, Obergurt `width`) vier Linien.
#[serde(rename = "trapezoid")]
Trapezoid,
/// Naturstein polygonal: unregelmässiges Netz um die Steingrösse `spacing`.
#[serde(rename = "polygonal")]
Polygonal,
/// Plattenteilung: Raster `spacing` × `height` ohne Versatz.
#[serde(rename = "grid")]
Grid,
#[serde(other)]
#[ts(skip)]
Unknown,
}
/// Richtung der Musterlinien gegenüber dem Element ([94]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, TS)]
pub enum SurfacePatternDirection {
/// Hauptlinien senkrecht (quer zur Wandachse; bei Dächern in Falllinie).
#[default]
#[serde(rename = "vertical")]
Vertical,
/// Hauptlinien waagrecht (entlang der Wandachse; bei Dächern traufparallel).
#[serde(rename = "horizontal")]
Horizontal,
#[serde(other)]
#[ts(skip)]
Unknown,
}
/// Ansichtsschraffur eines Bauteils ([100]): Muster auf sichtbaren Flächen, im Kern zu Linien gerechnet
/// (`surface_pattern.rs`). Masse in Metern am Bau; Ursprung an der Elementkante (Wandanfang/UK, Traufe).
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)]
#[serde(default)]
pub struct SurfacePattern {
#[ts(inline)]
pub kind: SurfacePatternKind,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional, inline)]
pub direction: Option<SurfacePatternDirection>,
/// Hauptabstand (m): Linien-/Rippenabstand, Steinlänge, Plattenbreite.
pub spacing: f64,
/// Lagen-/Plattenhöhe (m; Läuferverband, Schindeln, Raster). Fehlt sie, gilt `spacing`.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub height: Option<f64>,
/// Breite (m) der Deckleiste bzw. des Trapez-Obergurts.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub width: Option<f64>,
/// Grunddrehung (Grad) zusätzlich zur Richtung.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub angle: Option<f64>,
/// Strichstärke (Papier-mm); Default 0.1.
#[serde(rename = "weightMm", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub weight_mm: Option<f64>,
/// Linienfarbe; Default Vordergrund des Bauteils bzw. Dunkelgrau.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub color: Option<String>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
}
/// Ein Bauteil-Material (Component Manager) — vereint Plan-Schnittdarstellung
/// (Schraffur) und 3D-Erscheinung. Ersetzt das frühere `Material`.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)]
@@ -475,6 +557,32 @@ pub struct Component {
/// Verschneidungs-Rang: höher läuft am Stoß durch (Backbone).
#[serde(rename = "joinPriority")]
pub join_priority: f64,
/// Wärmeleitfähigkeit λ in W/(m·K) (Bemessungswert, z. B. SIA 381/1, Herstellerangabe).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub lambda: Option<f64>,
/// Rohdichte in kg/m³.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub density: Option<f64>,
/// Brandverhalten nach VKF (Brandschutzrichtlinie 13-15): "RF1" (kein Brandbeitrag), "RF2"
/// (geringer), "RF3" (zulässiger), "RF4" (unzulässig). Freitext, damit auch Zusätze („RF1 (cr)") gehen.
#[serde(rename = "fireClass", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub fire_class: Option<String>,
/// Flächenfarbe in der Ansicht (Fassade/Dachaufsicht). Fehlt sie, gilt die bisherige Farbe.
#[serde(rename = "elevationColor", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub elevation_color: Option<String>,
/// Ansichtsschraffur ([100]): Oberflächenmuster, das auf sichtbaren Flächen dieses Bauteils gezeichnet
/// wird (Ansicht, Dachaufsicht im Grundriss). Masse in Metern am Bau, Ausrichtung am Element.
#[serde(rename = "surfacePattern", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub surface_pattern: Option<SurfacePattern>,
/// Herkunft: Kennung des Standard-Eintrags ([100], „Standards laden"), damit erneutes Laden nichts verdoppelt.
#[serde(rename = "standardId", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub standard_id: Option<String>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
@@ -1980,6 +2088,16 @@ pub struct Wall {
#[serde(rename = "sliceTermination", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub slice_termination: Option<SliceTermination>,
/// Ansichtsschraffur ([100]): Drehung (Grad) des Oberflächenmusters dieses Elements gegenüber der
/// Ausrichtung am Element (Default 0).
#[serde(rename = "surfacePatternAngle", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub surface_pattern_angle: Option<f64>,
/// Ansichtsschraffur ([100]): Versatz (m) des Musterursprungs (x entlang, y quer/aufwärts) gegenüber
/// der Elementkante.
#[serde(rename = "surfacePatternOffset", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub surface_pattern_offset: Option<Vec2>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
@@ -2273,6 +2391,16 @@ pub struct Roof {
#[serde(rename = "colorPenId", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub color_pen_id: Option<String>,
/// Ansichtsschraffur ([100]): Drehung (Grad) des Oberflächenmusters dieses Elements gegenüber der
/// Ausrichtung am Element (Default 0).
#[serde(rename = "surfacePatternAngle", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub surface_pattern_angle: Option<f64>,
/// Ansichtsschraffur ([100]): Versatz (m) des Musterursprungs (x entlang, y quer/aufwärts) gegenüber
/// der Elementkante.
#[serde(rename = "surfacePatternOffset", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub surface_pattern_offset: Option<Vec2>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
+32
View File
@@ -335,6 +335,19 @@ fn roofs(c: &Ctx, out: &mut Vec<Primitive>, bounds: &mut Bounds) {
let bridges = (!merged.bridge_edges.is_empty()).then(|| merged.bridge_edges.iter().map(|&k| k as f64).collect());
out.push(polygon(ring, "none", "none", 0.0, view_hatch, greyed, bridges, Pick::Roof(&roof.id)));
}
// Ansichtsschraffur ([100]) der Eindeckung je Dachfläche (traufparallel/Falllinie, verkürzt projiziert).
if let Some(comp) = layers.first().filter(|l| !l.component_id.is_empty()).and_then(|l| p.component(&l.component_id)) {
if let Some((pat, spec)) = comp.surface_pattern.as_ref().and_then(|sp| Some((sp, crate::surface_pattern::spec_of(sp, roof.surface_pattern_angle.unwrap_or(0.0))?))) {
let off = roof.surface_pattern_offset.as_ref().map_or([0.0, 0.0], |o| [o.x, o.y]);
let w = pat.weight_mm.filter(|w| w.is_finite() && *w > 0.0).unwrap_or(0.1);
let ink = pat.color.as_deref().or(comp.foreground.as_deref()).filter(|c| !c.trim().is_empty()).unwrap_or("#3a3f47");
for plane in &geo.planes {
for (a, b) in crate::surface_pattern::segments_3d(plane, &spec, off, c.a.scale) {
out.push(line(pv([a[0], a[1]]), pv([b[0], b[1]]), "roof-surface-pattern", w, None, ink, greyed));
}
}
}
}
for ring in std::iter::once(&geo.eaves).chain(geo.eaves_holes.iter()) {
let pts: Vec<Vec2> = ring.iter().map(|q| pv(*q)).collect();
let n = pts.len();
@@ -804,6 +817,25 @@ mod tests {
assert!(r.bounds.is_some());
}
#[test]
fn dachaufsicht_mit_ansichtsschraffur() {
let mut p = sample();
p.roofs.as_mut().unwrap()[0].roof_type_id = Some("roof-warm".into());
let roof = p.roofs.as_ref().unwrap()[0].clone();
let outer = p.roof_layers(&roof)[0].component_id.clone();
let count = |p: &Project, scale: f64| {
let t = serde_json::json!({ "floor": "og", "show": ["31"], "grey": [], "scale": scale }).to_string();
let r = plan_domains(p, &PlanArgs::parse(1.0, &t).unwrap()).unwrap();
serde_json::to_string(&r.roofs).unwrap().matches("roof-surface-pattern").count()
};
assert_eq!(count(&p, 100.0), 0);
let c = p.components.iter_mut().find(|c| c.id == outer).unwrap();
c.surface_pattern = Some(SurfacePattern { kind: SurfacePatternKind::Lines, direction: Some(SurfacePatternDirection::Horizontal), spacing: 0.34, ..Default::default() });
let n = count(&p, 100.0);
assert!(n > 10, "{n}");
assert_eq!(count(&p, 5000.0), 0);
}
#[test]
fn puffer_gruppen_wie_domaenen() {
let p = sample();
+193 -9
View File
@@ -401,7 +401,10 @@ struct Item {
}
enum Pending {
Line { a: Pt, b: Pt, depth: f64 },
/// `style`: Index in die Ansichtsschraffur-Stile (Strichstärke, Farbe); ohne = Kante.
/// `paint`: Tiefe für die Maler-Reihenfolge, wenn sie von der Verdeckungstiefe abweicht (Muster-
/// linien liegen knapp vor IHRER Fläche, auch wo sie tiefer liegen als deren Mittel).
Line { a: Pt, b: Pt, depth: f64, style: Option<usize>, paint: Option<f64> },
Item { depth: f64, rank: Option<f64>, prim: Primitive },
}
@@ -441,7 +444,7 @@ fn poly_prim(pts: Vec<Vec2>, fill: &str, stroke: &str, w: f64, opening: Option<&
}
/// `generateElevationPlan`: Primitive und Ausmass; `None` ohne Ansichtslinie.
pub fn elevation_primitives(p: &Project, level: &LevelSpec, shadows: bool, mono: bool, vis: &Visibility) -> Result<Option<(Vec<Primitive>, [f64; 4])>, String> {
pub fn elevation_primitives(p: &Project, level: &LevelSpec, shadows: bool, mono: bool, vis: &Visibility, scale: f64) -> Result<Option<(Vec<Primitive>, [f64; 4])>, String> {
let Some(plane) = level.plane() else { return Ok(None) };
let frame = frame_of(&plane);
let mut walls = model3d::emit_walls(p, false)?;
@@ -479,6 +482,8 @@ pub fn elevation_primitives(p: &Project, level: &LevelSpec, shadows: bool, mono:
}
let greyed = |f: &Face| vis.has_display && category(f).is_some_and(|c| vis.greyed(c));
// Ansichtsfarbe und -schraffur ([100]) der sichtbaren Bauteilseite.
let (pattern_lines, pattern_styles) = surface_patterns(p, &mut faces, &frame, scale, mono);
let openings = collect_openings(p, &frame);
let mut occ = vec![(faces.len() + openings.len()) as f64];
for f in &faces {
@@ -560,7 +565,7 @@ pub fn elevation_primitives(p: &Project, level: &LevelSpec, shadows: bool, mono:
if coplanar_seam(fi, a, b) {
continue;
}
pending.push(Pending::Line { a, b, depth: f.depth_min - EPS * 5.0 });
pending.push(Pending::Line { a, b, depth: f.depth_min - EPS * 5.0, style: None, paint: None });
}
}
let mut prim = polygon(pts, &fill_for(f.fill), "none", 0.0, no_hatch());
@@ -593,14 +598,17 @@ pub fn elevation_primitives(p: &Project, level: &LevelSpec, shadows: bool, mono:
let e = crate::plan_elevation::xor_outline(&b);
for k in 0..e.first().copied().unwrap_or(0.0) as usize {
let i = 1 + 4 * k;
pending.push(Pending::Line { a: [e[i], e[i + 1]], b: [e[i + 2], e[i + 3]], depth: depth - EPS * 5.0 });
pending.push(Pending::Line { a: [e[i], e[i + 1]], b: [e[i + 2], e[i + 3]], depth: depth - EPS * 5.0, style: None, paint: None });
}
}
for (a, b, depth, paint, k) in pattern_lines {
pending.push(Pending::Line { a, b, depth, style: Some(k), paint: Some(paint) });
}
// Linien gebündelt gegen die Verdecker clippen (`flushPending`).
{
let mut q = vec![0.0];
for pd in &pending {
if let Pending::Line { a, b, depth } = pd {
if let Pending::Line { a, b, depth, .. } = pd {
q.extend([a[0], a[1], b[0], b[1], *depth]);
q[0] += 1.0;
}
@@ -613,7 +621,7 @@ pub fn elevation_primitives(p: &Project, level: &LevelSpec, shadows: bool, mono:
items.push(Item { depth, seq, rank, prim });
seq += 1;
}
Pending::Line { a, b, depth } => {
Pending::Line { a, b, depth, style, paint } => {
let c = if r.is_empty() {
1
} else {
@@ -630,7 +638,11 @@ pub fn elevation_primitives(p: &Project, level: &LevelSpec, shadows: bool, mono:
};
acc.add(sa[0], sa[1]);
acc.add(sb[0], sb[1]);
items.push(Item { depth, seq, rank: None, prim: outline_line(sa, sb) });
let prim = match style.and_then(|k| pattern_styles.get(k)) {
Some((w, c)) => line(v2(sa[0], sa[1]), v2(sb[0], sb[1]), "elevation-surface-pattern", *w, c),
None => outline_line(sa, sb),
};
items.push(Item { depth: paint.unwrap_or(depth), seq, rank: None, prim });
seq += 1;
}
}
@@ -737,6 +749,152 @@ pub fn elevation_primitives(p: &Project, level: &LevelSpec, shadows: bool, mono:
Ok(Some((prims, acc.bounds())))
}
/// Bauteil der sichtbaren Wandseite: rechts der Achse (Anfang → Ende) liegt die äusserste Schicht
/// (`layers[0]`), links die innerste; Stirnseiten haben keine.
fn wall_side_component<'a>(p: &'a Project, wall: &Wall, normal: [f64; 3]) -> Option<&'a Component> {
let (dx, dy) = (wall.end.x - wall.start.x, wall.end.y - wall.start.y);
let len = hypot2(dx, dy);
if !(len > 1e-9) {
return None;
}
// Plan (x, y) → Welt (x, Höhe, y); rechte Normale (dy, −dx).
let side = (dy * normal[0] - dx * normal[2]) / len;
let layers = &p.wall_type(wall)?.layers;
let l = if side > 0.7 {
layers.first()
} else if side < -0.7 {
layers.last()
} else {
None
}?;
p.component(&l.component_id)
}
/// Strichstärke und Farbe einer Ansichtsschraffur.
fn pattern_style(sp: &SurfacePattern, comp: &Component) -> (f64, String) {
let w = sp.weight_mm.filter(|w| w.is_finite() && *w > 0.0).unwrap_or(0.1);
let c = sp.color.clone().or_else(|| comp.foreground.clone()).filter(|c| !c.trim().is_empty()).unwrap_or_else(|| PATTERN_INK.into());
(w, c)
}
const PATTERN_INK: &str = "#3a3f47";
/// Linie der Ansichtsschraffur: Endpunkte, Verdeckungstiefe, Maler-Tiefe, Stil-Index.
type PatternLine = (Pt, Pt, f64, f64, usize);
/// Ansichtsfarbe (`Component.elevationColor`) der sichtbaren Seite auf die Flächen legen und die
/// Ansichtsschraffur ([100]) als Linien liefern: Wände in Wand-Koordinaten (x ab Wandanfang, y ab UK),
/// Dachflächen traufparallel/in Falllinie (`surface_pattern::segments_3d`). Tiefe je Linie = nächster
/// Endpunkt (knapp vor der Fläche), damit die Verdeckung wie bei den Kanten greift.
fn surface_patterns(p: &Project, faces: &mut [Face], frame: &[f64; 9], scale: f64, mono: bool) -> (Vec<PatternLine>, Vec<(f64, String)>) {
use crate::surface_pattern as sp;
let mut lines: Vec<PatternLine> = Vec::new();
let mut styles: Vec<(f64, String)> = Vec::new();
let (pp, nn, uu) = ([frame[0], frame[1], frame[2]], [frame[3], frame[4], frame[5]], [frame[6], frame[7], frame[8]]);
let proj = |w: [f64; 3]| -> (f64, f64, f64) {
let r = [w[0] - pp[0], w[1] - pp[1], w[2] - pp[2]];
(r[0] * uu[0] + r[1] * uu[1] + r[2] * uu[2], w[1], r[0] * nn[0] + r[1] * nn[1] + r[2] * nn[2])
};
let mut walls: HashMap<&str, &Wall> = HashMap::new();
for w in &p.walls {
walls.entry(w.id.as_str()).or_insert(w);
}
for f in faces.iter_mut() {
if f.role != Role::Wall || f.id.is_empty() || f.pts.len() < 3 {
continue;
}
let Some(wall) = walls.get(f.id.as_str()).copied() else { continue };
let Some(comp) = wall_side_component(p, wall, f.normal) else { continue };
if !mono {
if let Some(c) = comp.elevation_color.as_deref().filter(|c| !c.trim().is_empty()) {
f.fill = hex_to_rgb(c, f.fill);
}
}
let Some(pat) = comp.surface_pattern.as_ref() else { continue };
let Some(spec) = sp::spec_of(pat, wall.surface_pattern_angle.unwrap_or(0.0)) else { continue };
let (dx, dy) = (wall.end.x - wall.start.x, wall.end.y - wall.start.y);
let len = hypot2(dx, dy);
let t = [dx / len, 0.0, dy / len];
let k = t[0] * uu[0] + t[2] * uu[2];
if k.abs() < 0.05 {
continue; // fast von der Seite gesehen
}
let kd = (t[0] * nn[0] + t[2] * nn[2]) / k; // Tiefe je u entlang der Fläche
let mean_u = f.pts.iter().map(|q| q[0]).sum::<f64>() / f.pts.len() as f64;
let depth_at = |u: f64| f.depth + (u - mean_u) * kd;
let z0 = p.wall_vertical_extent(wall).0;
let (u0, _, _) = proj([wall.start.x, 0.0, wall.start.y]);
let local: Vec<sp::P> = f.pts.iter().map(|q| [(q[0] - u0) / k, q[1] - z0]).collect();
let off = wall.surface_pattern_offset.as_ref().map_or([0.0, 0.0], |o| [o.x, o.y]);
let segs = sp::segments(&local, &spec, off, scale);
if segs.is_empty() {
continue;
}
styles.push(pattern_style(pat, comp));
let si = styles.len() - 1;
for (s0, s1) in segs {
let (qa, qb) = ([u0 + k * s0[0], s0[1] + z0], [u0 + k * s1[0], s1[1] + z0]);
let d = min(depth_at(qa[0]), depth_at(qb[0])) - EPS * 5.0;
lines.push((qa, qb, d, f.depth - EPS * 5.0, si));
}
}
// Dachflächen: äusserste Schicht (Eindeckung).
for roof in p.roofs.as_deref().unwrap_or(&[]) {
let Some(comp) = p.roof_layers(roof).first().filter(|l| !l.component_id.is_empty()).and_then(|l| p.component(&l.component_id)) else { continue };
if !mono && roof.color.as_deref().is_none_or(|c| c.is_empty()) {
if let Some(c) = comp.elevation_color.as_deref().filter(|c| !c.trim().is_empty()) {
for f in faces.iter_mut().filter(|f| f.role == Role::Roof && f.id == roof.id) {
f.fill = hex_to_rgb(c, f.fill);
}
}
}
let Some(pat) = comp.surface_pattern.as_ref() else { continue };
let Some(spec) = sp::spec_of(pat, roof.surface_pattern_angle.unwrap_or(0.0)) else { continue };
let g = crate::roof::roof_geometry(&roof.params(), p.roof_base_elevation(roof));
let off = roof.surface_pattern_offset.as_ref().map_or([0.0, 0.0], |o| [o.x, o.y]);
let mut si: Option<usize> = None;
for plane in &g.planes {
if plane.len() < 3 {
continue;
}
// Flächennormale (Plan-Koordinaten, aufwärts); sichtbar, wenn sie zum Betrachter zeigt.
let mut n = [0.0; 3];
for i in 0..plane.len() {
let (a, b) = (plane[i], plane[(i + 1) % plane.len()]);
n[0] += (a[1] - b[1]) * (a[2] + b[2]);
n[1] += (a[2] - b[2]) * (a[0] + b[0]);
n[2] += (a[0] - b[0]) * (a[1] + b[1]);
}
if n[2] < 0.0 {
n = [-n[0], -n[1], -n[2]];
}
if nn[0] * n[0] + nn[1] * n[2] + nn[2] * n[1] >= -1e-9 {
continue;
}
// Maler-Tiefe der Fläche wie `project_face`: Mittel der Eckentiefen.
let face_depth = plane.iter().map(|q| proj([q[0], q[2], q[1]]).2).sum::<f64>() / plane.len() as f64;
for (a, b) in sp::segments_3d(plane, &spec, off, scale) {
let (ua, va, da) = proj([a[0], a[2], a[1]]);
let (ub, vb, db) = proj([b[0], b[2], b[1]]);
if da <= EPS || db <= EPS {
continue;
}
let k = *si.get_or_insert_with(|| {
styles.push(pattern_style(pat, comp));
styles.len() - 1
});
lines.push(([ua, va], [ub, vb], min(da, db) - EPS * 5.0, face_depth - EPS * 5.0, k));
}
}
}
if mono {
for s in &mut styles {
s.1 = PATTERN_INK.into();
}
}
(lines, styles)
}
/// Abfrage `elevationPlan`: `args` = `[mono, shadows]`, `text` = `{"level": {...}, "hasVis", "invisible",
/// "hasDisplay", "norender", "grey"}`. Puffer mit einer Gruppe und Ausmass; ohne Ansichtslinie ohne Gruppen.
pub fn elevation_plan_buf(p: &Project, args: &[f64], text: &str) -> Result<Vec<u8>, String> {
@@ -745,8 +903,10 @@ pub fn elevation_plan_buf(p: &Project, args: &[f64], text: &str) -> Result<Vec<u
let vis = Visibility::from_json(&v);
let mono = args.first().is_some_and(|&x| x != 0.0);
let shadows = args.get(1).is_some_and(|&x| x != 0.0);
// Massstab für die Ausdünnung der Ansichtsschraffur (fehlt er: 1:100).
let scale = args.get(2).copied().filter(|s| s.is_finite() && *s > 0.0).unwrap_or(100.0);
let mut w = crate::plan_buf::Writer::new(true);
if let Some((prims, bounds)) = elevation_primitives(p, &level, shadows, mono, &vis)? {
if let Some((prims, bounds)) = elevation_primitives(p, &level, shadows, mono, &vis, scale)? {
w.group(&prims);
w.bounds = Some(bounds);
}
@@ -774,7 +934,7 @@ mod tests {
let p = sample();
let l = p.drawing_levels.iter().find(|l| l.id == "ansicht-sued").unwrap();
let level = LevelSpec::from_json(&serde_json::to_value(l).unwrap());
let (prims, b) = elevation_primitives(&p, &level, true, false, &Visibility::default()).unwrap().unwrap();
let (prims, b) = elevation_primitives(&p, &level, true, false, &Visibility::default(), 100.0).unwrap().unwrap();
let json = serde_json::to_string(&prims).unwrap();
assert!(json.contains("\"wallId\":\"W1\"") && json.contains("\"openingId\":\"O1\"") && json.contains("elevation-ground"), "{json}");
assert!(json.contains("#8f959e"), "Schlagschatten fehlt");
@@ -782,4 +942,28 @@ mod tests {
// Painter: die Bodenlinie zuletzt
assert!(matches!(prims.last(), Some(Primitive::Line { cls, .. }) if cls == "elevation-ground"));
}
fn render(p: &Project, scale: f64) -> String {
let l = p.drawing_levels.iter().find(|l| l.id == "ansicht-sued").unwrap();
let level = LevelSpec::from_json(&serde_json::to_value(l).unwrap());
let (prims, _) = elevation_primitives(p, &level, false, false, &Visibility::default(), scale).unwrap().unwrap();
serde_json::to_string(&prims).unwrap()
}
#[test]
fn ansichtsschraffur_und_ansichtsfarbe_der_aussenschicht() {
let mut p = sample();
assert!(!render(&p, 50.0).contains("elevation-surface-pattern"), "ohne Muster keine Linien");
let outer = p.wall_types.iter().find(|t| t.id == "aw").unwrap().layers[0].component_id.clone();
let c = p.components.iter_mut().find(|c| c.id == outer).unwrap();
c.elevation_color = Some("#123456".into());
c.surface_pattern = Some(SurfacePattern { kind: SurfacePatternKind::Lines, spacing: 0.1, ..Default::default() });
let fine = render(&p, 50.0);
let n_fine = fine.matches("elevation-surface-pattern").count();
assert!(n_fine > 20, "{n_fine}");
assert!(fine.contains("#123456"), "Ansichtsfarbe der Aussenschicht");
let n_mid = render(&p, 200.0).matches("elevation-surface-pattern").count();
assert!(n_mid < n_fine && n_mid > 0, "{n_mid} vs {n_fine}");
assert_eq!(render(&p, 2000.0).matches("elevation-surface-pattern").count(), 0, "grob: weggelassen");
}
}
+3 -1
View File
@@ -103,7 +103,9 @@ pub fn plan_svg(parts: &mut [Part], o: &SvgOptions) -> Option<String> {
if d.is_empty() {
return Some(String::new());
}
Some(format!(" stroke-dasharray=\"{}\"", d.iter().map(|v| num(v * mm_to_m)).collect::<Vec<_>>().join(" ")))
// Punkte (AN = 0) brauchen runde Kappen, sonst sind sie unsichtbar ([96]).
let cap = if d.iter().any(|v| *v == 0.0) { " stroke-linecap=\"round\"" } else { "" };
Some(format!(" stroke-dasharray=\"{}\"{cap}", d.iter().map(|v| num(v * mm_to_m)).collect::<Vec<_>>().join(" ")))
};
match rec.tag {
T_POLYGON => {
+2
View File
@@ -82,6 +82,8 @@ pub fn run_root(lk: &crate::document::Lookup, name: &str, text: &str) -> Result<
// Stiftsätze ([K4] S3, `pens.rs`): Ops statt Projekt-Kopien.
"penRebakeOps" => json(&crate::pens::rebake_ops(root)),
"penDeleteOps" => json(&crate::pens::delete_pen_ops(root, text)),
// Standard-Bibliothek ([100]–[102], `standards.rs`): fehlende Standard-Ressourcen als Ops.
"standardsMergeOps" => json(&crate::standards::merge_ops(root)),
"penSeedOps" => {
let a: serde_json::Value = serde_json::from_str(text).map_err(|e| format!("penSeedOps: {e}"))?;
json(&crate::pens::seed_standard_ops(root, a["id"].as_str().unwrap_or(""), a["name"].as_str().unwrap_or("")))
+358
View File
@@ -0,0 +1,358 @@
//! Standard-Bibliothek ([100]–[102]): Baustoffe (Bauteile) mit Schnittschraffur nach SIA 400, Füllfarbe,
//! Ansichtsfarbe, Ansichtsschraffur, 3D-Textur (ambientCG, CC0) und Kennwerten (λ, Rohdichte, VKF-Brand-
//! verhaltensgruppe RF1–RF4), Schraffuren, Linientypen nach SIA 400 / ISO 128 und Standard-Aufbauten (Wand,
//! Decke, Dach). Neue Projekte bekommen sie, bestehende laden sie über „Standards laden" nach
//! ([`merge_ops`]: fehlende Einträge anhängen, nichts verdoppeln — gleiche id oder gleicher Name gilt als
//! vorhanden; Verweise der neuen Einträge zeigen dann auf den vorhandenen).
//!
//! Kennwerte: Bemessungs-/Richtwerte (SIA 381/1, SN EN ISO 10456, übliche Herstellerangaben), gerundet;
//! für den Nachweis gelten die Produktwerte.
use serde_json::{json, Map, Value};
use std::collections::HashMap;
/// Gebündelte Material-Bibliothek (`public/assets/materials/manifest.json`, wie `src/materials/library.ts`).
const MANIFEST: &str = include_str!("../../../public/assets/materials/manifest.json");
/// 3D-Material zu einer ambientCG-Kennung: gebündelt → mit Karten-Pfaden; sonst nur die Kennung (die
/// Karten lädt der Bauteil-Dialog bei Bedarf von ambientCG).
fn material(id: &str, size_m: f64) -> Value {
let manifest: Value = serde_json::from_str(MANIFEST).unwrap_or(Value::Null);
let hit = manifest["materials"].as_array().and_then(|a| a.iter().find(|m| m["id"] == id));
let mut m = Map::new();
m.insert("libraryId".into(), id.into());
if let Some(maps) = hit.and_then(|h| h["maps"].as_object()) {
for k in ["color", "normal", "roughness", "metalness", "displacement", "ao"] {
if let Some(v) = maps.get(k) {
m.insert(k.into(), v.clone());
}
}
}
m.insert("sizeM".into(), json!(size_m));
Value::Object(m)
}
const INK: &str = "#1a1a1a";
/// Linientypen (SIA 400 / ISO 128). Strichmuster in Papier-mm (AN/AUS, 0 = Punkt), unabhängig vom Massstab.
pub fn line_styles() -> Vec<Value> {
let dash = |id: &str, name: &str, w: f64, d: Value| json!({"id": id, "name": name, "weight": w, "color": INK, "dash": d});
vec![
dash("std-ls-voll", "Volllinie", 0.25, Value::Null),
dash("std-ls-strich-fein", "Strichlinie fein", 0.18, json!([3, 1.5])),
dash("std-ls-strich-grob", "Strichlinie grob", 0.5, json!([6, 2])),
dash("std-ls-punkt", "Punktlinie", 0.25, json!([0, 1])),
dash("std-ls-strichpunkt", "Strichpunktlinie (Achse)", 0.18, json!([12, 1.5, 0, 1.5])),
dash("std-ls-strichzweipunkt", "Strich-Zweipunktlinie", 0.18, json!([12, 1.5, 0, 1.5, 0, 1.5])),
dash("std-ls-grundstueck", "Grundstücksgrenze", 0.5, json!([8, 1.5, 0, 1.5, 0, 1.5])),
dash("std-ls-bauteilgrenze", "Baulinie / Bauteilgrenze", 0.35, json!([8, 1.5, 0, 1.5])),
json!({"id": "std-ls-bruch", "name": "Bruchlinie (Zickzack)", "weight": 0.18, "color": INK, "dash": null,
"kind": "zigzag", "zigzag": {"amplitude": 1.5, "wavelength": 4}}),
dash("std-ls-schraffur", "Schraffurlinie 0.10", 0.1, Value::Null),
dash("std-ls-schraffur-strich", "Schraffurlinie gestrichelt", 0.1, json!([1, 0.7])),
]
}
/// Schnittschraffuren (SIA 400). Abstand im Modell (Kachel 8·scale/90 m), Winkel in Grad.
pub fn hatches() -> Vec<Value> {
let h = |id: &str, name: &str, pattern: &str, scale: f64, angle: f64, rel: bool, ls: &str| {
let mut v = json!({"id": id, "name": name, "pattern": pattern, "scale": scale, "angle": angle, "color": INK});
if rel {
v["relativeToWall"] = json!(true);
}
if !ls.is_empty() {
v["lineStyleId"] = json!(ls);
}
v
};
let solid = |id: &str, name: &str, color: &str| json!({"id": id, "name": name, "pattern": "solid", "scale": 1, "angle": 0, "color": color});
let random = |id: &str, name: &str, angle: f64, density: f64, lmin: f64, lmax: f64, seed: f64| {
json!({"id": id, "name": name, "kind": "vector", "lines": "random", "pattern": "diagonal", "scale": 1, "angle": angle,
"color": INK, "lineStyleId": "std-ls-schraffur", "density": density, "lengthMin": lmin, "lengthMax": lmax, "seed": seed})
};
vec![
h("std-h-ohne", "SIA Ohne Schraffur", "none", 1.0, 0.0, false, ""),
h("std-h-stahlbeton", "SIA Stahlbeton", "crosshatch", 0.5, 45.0, false, "std-ls-schraffur"),
h("std-h-beton", "SIA Beton unbewehrt", "crosshatch", 0.6, 45.0, false, "std-ls-schraffur-strich"),
h("std-h-backstein", "SIA Backstein", "diagonal", 0.5, 45.0, true, "std-ls-schraffur"),
h("std-h-kalksandstein", "SIA Kalksandstein", "diagonal", 0.35, 135.0, true, "std-ls-schraffur"),
h("std-h-porenbeton", "SIA Porenbeton", "diagonal", 0.5, 45.0, true, "std-ls-schraffur-strich"),
h("std-h-holz", "SIA Holz (Querschnitt)", "crosshatch", 0.6, 0.0, true, "std-ls-schraffur"),
h("std-h-bsp", "SIA Brettsperrholz", "diagonal", 0.3, 90.0, true, "std-ls-schraffur"),
random("std-h-holzwerkstoff", "SIA Holzwerkstoff", 30.0, 1.4, 0.6, 1.5, 7.0),
h("std-h-daemmung-weich", "SIA Dämmung weich", "insulation", 1.0, 0.0, true, "std-ls-schraffur"),
h("std-h-eps", "SIA Dämmung EPS", "diagonal", 0.45, 0.0, true, "std-ls-schraffur"),
h("std-h-xps", "SIA Dämmung XPS", "crosshatch", 0.45, 0.0, true, "std-ls-schraffur"),
h("std-h-holzfaser", "SIA Dämmung Holzfaser", "insulation", 0.8, 0.0, true, "std-ls-schraffur-strich"),
solid("std-h-gips", "SIA Gips", "#cfcfcf"),
h("std-h-estrich", "SIA Estrich", "diagonal", 0.35, 45.0, false, "std-ls-schraffur-strich"),
solid("std-h-stahl", "SIA Stahl", INK),
solid("std-h-alu", "SIA Aluminium", "#8c8c8c"),
h("std-h-naturstein", "SIA Naturstein", "diagonal", 0.8, 45.0, false, "std-ls-voll"),
random("std-h-erdreich", "SIA Erdreich", 45.0, 0.8, 1.5, 4.0, 11.0),
random("std-h-kies", "SIA Kies / Sauberkeitsschicht", 60.0, 1.8, 0.4, 0.9, 13.0),
]
}
/// Ein Standard-Baustoff.
struct Mat<'a> {
id: &'a str,
name: &'a str,
abbrev: &'a str,
fill: &'a str,
elev: &'a str,
hatch: &'a str,
lambda: Option<f64>,
density: Option<f64>,
rf: &'a str,
tex: Option<(&'a str, f64)>,
prio: f64,
pattern: Option<Value>,
}
fn sp(kind: &str, dir: Option<&str>, spacing: f64, height: Option<f64>, width: Option<f64>) -> Option<Value> {
let mut v = json!({"kind": kind, "spacing": spacing});
if let Some(d) = dir {
v["direction"] = json!(d);
}
if let Some(h) = height {
v["height"] = json!(h);
}
if let Some(w) = width {
v["width"] = json!(w);
}
Some(v)
}
/// Baustoffe (Bauteile) mit allen Darstellungs- und Kennwerten.
pub fn components() -> Vec<Value> {
#[rustfmt::skip]
let list = [
Mat { id: "std-c-beton", name: "Beton", abbrev: "BE", fill: "#ffffff", elev: "#c4c4c0", hatch: "std-h-beton", lambda: Some(2.0), density: Some(2300.0), rf: "RF1", tex: Some(("Concrete048", 2.0)), prio: 95.0, pattern: None },
Mat { id: "std-c-stahlbeton", name: "Stahlbeton", abbrev: "STB", fill: "#ffffff", elev: "#bdbdb8", hatch: "std-h-stahlbeton", lambda: Some(2.3), density: Some(2400.0), rf: "RF1", tex: Some(("Concrete048", 2.0)), prio: 100.0, pattern: None },
Mat { id: "std-c-backstein", name: "Backstein", abbrev: "BS", fill: "#ffffff", elev: "#b5653f", hatch: "std-h-backstein", lambda: Some(0.44), density: Some(1100.0), rf: "RF1", tex: Some(("Bricks104", 1.0)), prio: 50.0, pattern: sp("runningBond", None, 0.26, Some(0.075), None) },
Mat { id: "std-c-kalksandstein", name: "Kalksandstein", abbrev: "KS", fill: "#ffffff", elev: "#e4e1d8", hatch: "std-h-kalksandstein", lambda: Some(1.0), density: Some(1800.0), rf: "RF1", tex: None, prio: 55.0, pattern: sp("runningBond", None, 0.25, Some(0.125), None) },
Mat { id: "std-c-porenbeton", name: "Porenbeton", abbrev: "PB", fill: "#ffffff", elev: "#e8e8e4", hatch: "std-h-porenbeton", lambda: Some(0.11), density: Some(400.0), rf: "RF1", tex: None, prio: 45.0, pattern: sp("runningBond", None, 0.6, Some(0.25), None) },
Mat { id: "std-c-holz", name: "Holz massiv", abbrev: "HO", fill: "#ffffff", elev: "#c8a26a", hatch: "std-h-holz", lambda: Some(0.13), density: Some(450.0), rf: "RF3", tex: Some(("Wood095", 1.0)), prio: 40.0, pattern: None },
Mat { id: "std-c-bsp", name: "Brettsperrholz", abbrev: "BSP", fill: "#ffffff", elev: "#d6b47e", hatch: "std-h-bsp", lambda: Some(0.12), density: Some(470.0), rf: "RF3", tex: Some(("Wood095", 1.0)), prio: 60.0, pattern: sp("lines", Some("horizontal"), 0.6, None, None) },
Mat { id: "std-c-holzwerkstoff", name: "Holzwerkstoff (OSB/Spanplatte)", abbrev: "OSB", fill: "#ffffff", elev: "#d9b98a", hatch: "std-h-holzwerkstoff", lambda: Some(0.13), density: Some(650.0), rf: "RF3", tex: Some(("Chipboard001", 1.0)), prio: 35.0, pattern: sp("grid", None, 1.25, Some(2.5), None) },
Mat { id: "std-c-mineralwolle", name: "Mineralwolle", abbrev: "MW", fill: "#ffffff", elev: "#efe6a8", hatch: "std-h-daemmung-weich", lambda: Some(0.035), density: Some(20.0), rf: "RF1", tex: None, prio: 20.0, pattern: None },
Mat { id: "std-c-steinwolle", name: "Steinwolle", abbrev: "SW", fill: "#ffffff", elev: "#d9cfa0", hatch: "std-h-daemmung-weich", lambda: Some(0.036), density: Some(100.0), rf: "RF1", tex: None, prio: 21.0, pattern: None },
Mat { id: "std-c-eps", name: "EPS", abbrev: "EPS", fill: "#ffffff", elev: "#f2f2f2", hatch: "std-h-eps", lambda: Some(0.034), density: Some(20.0), rf: "RF3", tex: None, prio: 22.0, pattern: None },
Mat { id: "std-c-xps", name: "XPS", abbrev: "XPS", fill: "#ffffff", elev: "#cfe3ef", hatch: "std-h-xps", lambda: Some(0.033), density: Some(35.0), rf: "RF3", tex: None, prio: 23.0, pattern: None },
Mat { id: "std-c-holzfaser", name: "Holzfaser", abbrev: "HF", fill: "#ffffff", elev: "#b08a5a", hatch: "std-h-holzfaser", lambda: Some(0.04), density: Some(140.0), rf: "RF3", tex: None, prio: 24.0, pattern: None },
Mat { id: "std-c-trittschall", name: "Trittschalldämmung", abbrev: "TSD", fill: "#ffffff", elev: "#efe6a8", hatch: "std-h-daemmung-weich", lambda: Some(0.035), density: Some(100.0), rf: "RF1", tex: None, prio: 19.0, pattern: None },
Mat { id: "std-c-gipskarton", name: "Gipskarton", abbrev: "GK", fill: "#cfcfcf", elev: "#f4f4f2", hatch: "std-h-gips", lambda: Some(0.25), density: Some(800.0), rf: "RF1", tex: Some(("Plaster001", 1.0)), prio: 12.0, pattern: None },
Mat { id: "std-c-innenputz", name: "Innenputz", abbrev: "IP", fill: "#ffffff", elev: "#f5f3ee", hatch: "std-h-ohne", lambda: Some(0.7), density: Some(1400.0), rf: "RF1", tex: Some(("Plaster001", 1.0)), prio: 10.0, pattern: None },
Mat { id: "std-c-aussenputz", name: "Aussenputz", abbrev: "AP", fill: "#ffffff", elev: "#e9e3d6", hatch: "std-h-ohne", lambda: Some(0.87), density: Some(1800.0), rf: "RF1", tex: Some(("Plaster001", 1.0)), prio: 10.0, pattern: None },
Mat { id: "std-c-zementestrich", name: "Zementestrich", abbrev: "ZE", fill: "#ffffff", elev: "#cfcac0", hatch: "std-h-estrich", lambda: Some(1.4), density: Some(2000.0), rf: "RF1", tex: Some(("Concrete048", 2.0)), prio: 30.0, pattern: None },
Mat { id: "std-c-glas", name: "Glas", abbrev: "GL", fill: "#d6ecf3", elev: "#a9c8d4", hatch: "std-h-ohne", lambda: Some(1.0), density: Some(2500.0), rf: "RF1", tex: None, prio: 70.0, pattern: None },
Mat { id: "std-c-stahl", name: "Stahl", abbrev: "ST", fill: INK, elev: "#7d8287", hatch: "std-h-stahl", lambda: Some(50.0), density: Some(7850.0), rf: "RF1", tex: Some(("Metal063", 1.0)), prio: 110.0, pattern: None },
Mat { id: "std-c-aluminium", name: "Aluminium", abbrev: "AL", fill: "#8c8c8c", elev: "#b9bcbf", hatch: "std-h-alu", lambda: Some(160.0), density: Some(2700.0), rf: "RF1", tex: Some(("Metal063", 1.0)), prio: 105.0, pattern: None },
Mat { id: "std-c-naturstein", name: "Naturstein", abbrev: "NS", fill: "#ffffff", elev: "#bcb6a8", hatch: "std-h-naturstein", lambda: Some(2.3), density: Some(2600.0), rf: "RF1", tex: Some(("Marble012", 1.0)), prio: 90.0, pattern: sp("polygonal", None, 0.45, Some(0.35), None) },
Mat { id: "std-c-erdreich", name: "Erdreich", abbrev: "ER", fill: "#ffffff", elev: "#8a7a62", hatch: "std-h-erdreich", lambda: Some(2.0), density: Some(1800.0), rf: "RF1", tex: Some(("Ground103", 2.0)), prio: 5.0, pattern: None },
Mat { id: "std-c-kies", name: "Kies / Sauberkeitsschicht", abbrev: "KI", fill: "#ffffff", elev: "#b3aca0", hatch: "std-h-kies", lambda: Some(2.0), density: Some(2000.0), rf: "RF1", tex: Some(("Gravel043", 1.0)), prio: 6.0, pattern: None },
// Bekleidungen / Eindeckungen: Ansichtsschraffur als Hauptsache.
Mat { id: "std-c-luft", name: "Luftschicht / Hinterlüftung", abbrev: "LU", fill: "#ffffff", elev: "#ffffff", hatch: "std-h-ohne", lambda: None, density: None, rf: "RF1", tex: None, prio: 1.0, pattern: None },
Mat { id: "std-c-lattung-v", name: "Holzlattung vertikal", abbrev: "LV", fill: "#ffffff", elev: "#b98d55", hatch: "std-h-holz", lambda: Some(0.13), density: Some(450.0), rf: "RF3", tex: Some(("Wood095", 1.0)), prio: 41.0, pattern: sp("lines", Some("vertical"), 0.08, None, None) },
Mat { id: "std-c-lattung-h", name: "Holzlattung horizontal", abbrev: "LH", fill: "#ffffff", elev: "#b98d55", hatch: "std-h-holz", lambda: Some(0.13), density: Some(450.0), rf: "RF3", tex: Some(("Wood095", 1.0)), prio: 41.0, pattern: sp("lines", Some("horizontal"), 0.08, None, None) },
Mat { id: "std-c-boden-deckel", name: "Holzschalung Boden-Deckel", abbrev: "BD", fill: "#ffffff", elev: "#a9824f", hatch: "std-h-holz", lambda: Some(0.13), density: Some(450.0), rf: "RF3", tex: Some(("WoodSiding008", 1.0)), prio: 41.0, pattern: sp("boardBatten", Some("vertical"), 0.2, None, Some(0.06)) },
Mat { id: "std-c-schindeln", name: "Holzschindeln", abbrev: "SCH", fill: "#ffffff", elev: "#9c8566", hatch: "std-h-holz", lambda: Some(0.13), density: Some(450.0), rf: "RF3", tex: Some(("Wood095", 0.5)), prio: 41.0, pattern: sp("shingles", None, 0.1, Some(0.12), None) },
Mat { id: "std-c-trapezblech", name: "Trapezblech", abbrev: "TB", fill: INK, elev: "#9aa1a6", hatch: "std-h-stahl", lambda: Some(50.0), density: Some(7850.0), rf: "RF1", tex: Some(("CorrugatedSteel005", 1.0)), prio: 108.0, pattern: sp("trapezoid", Some("vertical"), 0.2, None, Some(0.06)) },
Mat { id: "std-c-faserzement", name: "Faserzementplatten", abbrev: "FZ", fill: "#ffffff", elev: "#a6a8a6", hatch: "std-h-ohne", lambda: Some(0.6), density: Some(1800.0), rf: "RF1", tex: None, prio: 42.0, pattern: sp("grid", None, 1.25, Some(0.625), None) },
Mat { id: "std-c-tonziegel", name: "Tonziegel", abbrev: "ZI", fill: "#ffffff", elev: "#b3583c", hatch: "std-h-backstein", lambda: Some(1.0), density: Some(1900.0), rf: "RF1", tex: Some(("RoofingTiles013A", 1.0)), prio: 15.0, pattern: sp("grid", Some("horizontal"), 0.21, Some(0.34), None) },
];
list.iter()
.map(|m| {
let mut v = json!({"id": m.id, "name": m.name, "abbrev": m.abbrev, "color": m.fill, "background": m.fill, "hatchId": m.hatch,
"joinPriority": m.prio, "fireClass": m.rf, "elevationColor": m.elev, "standardId": m.id});
if let Some(l) = m.lambda {
v["lambda"] = json!(l);
}
if let Some(d) = m.density {
v["density"] = json!(d);
}
if let Some((id, size)) = m.tex {
v["material"] = material(id, size);
}
if let Some(p) = &m.pattern {
v["surfacePattern"] = p.clone();
}
v
})
.collect()
}
fn layer(c: &str, t: f64) -> Value {
json!({"componentId": c, "thickness": t})
}
/// Standard-Aufbauten (Schichten aussen → innen bzw. oben → unten).
pub fn wall_types() -> Vec<Value> {
vec![
json!({"id": "std-wt-aw-kompakt", "name": "Aussenwand verputzt, Aussendämmung 18 cm", "layers": [
layer("std-c-aussenputz", 0.02), layer("std-c-eps", 0.18), layer("std-c-backstein", 0.175), layer("std-c-innenputz", 0.015)]}),
json!({"id": "std-wt-iw-backstein", "name": "Innenwand Backstein 12.5 cm verputzt", "layers": [
layer("std-c-innenputz", 0.01), layer("std-c-backstein", 0.125), layer("std-c-innenputz", 0.01)]}),
json!({"id": "std-wt-holzstaender", "name": "Holzständerwand hinterlüftet", "layers": [
layer("std-c-lattung-v", 0.024), layer("std-c-luft", 0.04), layer("std-c-holzfaser", 0.06),
layer("std-c-mineralwolle", 0.2), layer("std-c-holzwerkstoff", 0.015), layer("std-c-gipskarton", 0.0125)]}),
]
}
pub fn ceiling_types() -> Vec<Value> {
vec![json!({"id": "std-ct-stb-estrich", "name": "Stahlbetondecke mit Trittschall + Zementestrich", "layers": [
layer("std-c-zementestrich", 0.08), layer("std-c-trittschall", 0.04), layer("std-c-stahlbeton", 0.24), layer("std-c-innenputz", 0.01)]})]
}
pub fn roof_types() -> Vec<Value> {
vec![json!({"id": "std-rt-steildach-holz", "name": "Steildach Holz gedämmt", "layers": [
layer("std-c-tonziegel", 0.04), layer("std-c-luft", 0.06), layer("std-c-holzfaser", 0.06),
layer("std-c-mineralwolle", 0.22), layer("std-c-holzwerkstoff", 0.015), layer("std-c-gipskarton", 0.0125)]})]
}
/// Alle Standard-Ressourcen je Projekt-Liste, in Abhängigkeitsreihenfolge.
pub fn library() -> Vec<(&'static str, Vec<Value>)> {
vec![
("lineStyles", line_styles()),
("hatches", hatches()),
("components", components()),
("wallTypes", wall_types()),
("ceilingTypes", ceiling_types()),
("roofTypes", roof_types()),
]
}
fn name_key(v: &Value) -> Option<String> {
v["name"].as_str().map(|s| s.trim().to_lowercase()).filter(|s| !s.is_empty())
}
fn remap(v: &mut Value, key: &str, ids: &HashMap<String, String>) {
if let Some(new) = v[key].as_str().and_then(|s| ids.get(s)) {
v[key] = json!(new);
}
}
/// Ops, die die fehlenden Standard-Ressourcen anhängen. Vorhanden ist ein Eintrag mit gleicher id oder
/// gleichem Namen (Gross-/Kleinschreibung egal); Verweise neuer Einträge (Schraffur → Linienstil, Bauteil →
/// Schraffur, Aufbau → Bauteil/Fugen-Linienstil) zeigen dann auf den vorhandenen Eintrag.
pub fn merge_ops(root: &Map<String, Value>) -> Vec<Value> {
let mut ids: HashMap<String, String> = HashMap::new();
let mut ops = Vec::new();
for (key, items) in library() {
let existing = root.get(key).and_then(Value::as_array);
let by_id: HashMap<&str, &Value> = existing.map(|a| a.iter().filter_map(|e| e["id"].as_str().map(|i| (i, e))).collect()).unwrap_or_default();
let by_name: HashMap<String, &str> = existing.map(|a| a.iter().filter_map(|e| Some((name_key(e)?, e["id"].as_str()?))).collect()).unwrap_or_default();
let mut add = Vec::new();
for mut item in items {
let id = item["id"].as_str().unwrap_or_default().to_string();
if by_id.contains_key(id.as_str()) {
continue;
}
if let Some(other) = name_key(&item).and_then(|n| by_name.get(&n).copied()) {
ids.insert(id, other.to_string());
continue;
}
remap(&mut item, "lineStyleId", &ids);
remap(&mut item, "hatchId", &ids);
remap(&mut item, "viewHatchId", &ids);
if let Some(layers) = item.get_mut("layers").and_then(Value::as_array_mut) {
for l in layers {
remap(l, "componentId", &ids);
remap(l, "jointLineStyleId", &ids);
}
}
add.push(item);
}
if add.is_empty() {
continue;
}
if existing.is_some() {
ops.push(json!({"kind": "add", "collection": key, "items": add}));
} else {
ops.push(json!({"kind": "setField", "key": key, "value": add}));
}
}
ops
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::Project;
fn empty_root() -> Map<String, Value> {
json!({"id": "p", "name": "P", "lineStyles": [], "hatches": [], "components": [], "wallTypes": [], "drawingLevels": [],
"walls": [], "openings": []})
.as_object()
.unwrap()
.clone()
}
fn apply(root: &Map<String, Value>, ops: &[Value]) -> Map<String, Value> {
let mut r = root.clone();
for op in ops {
match op["kind"].as_str().unwrap() {
"add" => r.get_mut(op["collection"].as_str().unwrap()).unwrap().as_array_mut().unwrap().extend(op["items"].as_array().unwrap().iter().cloned()),
"setField" => {
r.insert(op["key"].as_str().unwrap().into(), op["value"].clone());
}
k => panic!("{k}"),
}
}
r
}
#[test]
fn bibliothek_ist_vollstaendig_und_gueltig() {
let r = apply(&empty_root(), &merge_ops(&empty_root()));
let p: Project = serde_json::from_value(Value::Object(r.clone())).unwrap();
for name in [
"Beton", "Stahlbeton", "Backstein", "Kalksandstein", "Porenbeton", "Holz massiv", "Brettsperrholz", "Holzwerkstoff (OSB/Spanplatte)",
"Mineralwolle", "Steinwolle", "EPS", "XPS", "Holzfaser", "Gipskarton", "Innenputz", "Aussenputz", "Zementestrich", "Glas", "Stahl",
"Aluminium", "Naturstein", "Erdreich", "Kies / Sauberkeitsschicht",
] {
let c = p.components.iter().find(|c| c.name == name).unwrap_or_else(|| panic!("{name} fehlt"));
assert!(c.lambda.is_some() && c.density.is_some() && c.fire_class.as_deref().is_some_and(|f| f.starts_with("RF")), "{name}");
assert!(c.elevation_color.is_some() && !c.color.is_empty(), "{name}");
assert!(p.hatches.iter().any(|h| h.id == c.hatch_id), "{name}: Schraffur");
}
// Alle Verweise lösen auf
assert!(crate::project_refs::dangling_refs(&p).is_empty(), "{:?}", crate::project_refs::dangling_refs(&p));
for name in ["Aussenwand verputzt, Aussendämmung 18 cm", "Innenwand Backstein 12.5 cm verputzt", "Holzständerwand hinterlüftet"] {
assert!(p.wall_types.iter().any(|t| t.name == name), "{name}");
}
assert_eq!(p.ceiling_types.as_ref().unwrap().len(), 1);
assert_eq!(p.roof_types.as_ref().unwrap().len(), 1);
// Gebündelte Textur mit Karten, fremde nur mit Kennung
let bs = p.components.iter().find(|c| c.id == "std-c-backstein").unwrap().material.as_ref().unwrap();
assert_eq!(bs.color.as_deref(), Some("/assets/materials/Bricks104/color.jpg"));
let tb = p.components.iter().find(|c| c.id == "std-c-trapezblech").unwrap().material.as_ref().unwrap();
assert!(tb.color.is_none() && tb.library_id.as_deref() == Some("CorrugatedSteel005"));
// Linientypen
for name in ["Volllinie", "Strichlinie fein", "Strichlinie grob", "Punktlinie", "Strichpunktlinie (Achse)", "Strich-Zweipunktlinie", "Grundstücksgrenze", "Bruchlinie (Zickzack)"] {
assert!(p.line_styles.iter().any(|l| l.name == name), "{name}");
}
}
#[test]
fn zweites_laden_verdoppelt_nichts() {
let once = apply(&empty_root(), &merge_ops(&empty_root()));
assert!(merge_ops(&once).is_empty());
}
#[test]
fn gleichnamige_bleiben_und_verweise_zeigen_darauf() {
let mut root = empty_root();
root.insert("components".into(), json!([{"id": "brick", "name": "backstein ", "color": "#8c5544", "hatchId": "x", "joinPriority": 50}]));
root.insert("lineStyles".into(), json!([{"id": "thin", "name": "Schraffurlinie 0.10", "weight": 0.1, "color": "#000", "dash": null}]));
let r = apply(&root, &merge_ops(&root));
let comps = r["components"].as_array().unwrap();
assert_eq!(comps.iter().filter(|c| c["name"].as_str().unwrap().trim().eq_ignore_ascii_case("backstein")).count(), 1);
assert_eq!(comps[0]["color"], "#8c5544", "vorhandenes Bauteil unverändert");
let iw = r["wallTypes"].as_array().unwrap().iter().find(|t| t["id"] == "std-wt-iw-backstein").unwrap();
assert_eq!(iw["layers"][1]["componentId"], "brick");
let bs = r["hatches"].as_array().unwrap().iter().find(|h| h["id"] == "std-h-backstein").unwrap();
assert_eq!(bs["lineStyleId"], "thin");
}
}
+475
View File
@@ -0,0 +1,475 @@
//! Ansichtsschraffur ([100]): Oberflächenmuster eines Bauteils (Lattung, Läuferverband, Schindeln,
//! Boden-Deckel-Schalung, Trapezblech, Naturstein polygonal, Plattenteilung) als Liniensegmente auf
//! einer ebenen Fläche. Rechnet in Flächen-Koordinaten (x entlang des Elements, y aufwärts bzw. in
//! Falllinie, Meter am Bau, Ursprung an der Elementkante) und schneidet an der Fläche zu.
//!
//! Massstab: Liegen die Linien auf dem Papier enger als [`MIN_PAPER_MM`], wird ausgedünnt (jede 2., 4.,
//! 8. Linie); noch enger fällt die Linienschar weg — so wird eine Fassade in 1:500 nicht schwarz.
//! Die Aufrufer (Ansicht `plan/elevation.rs`, Dachaufsicht `plan/domains.rs`) bilden die Segmente in
//! ihre Zeichenebene ab.
use crate::model::{SurfacePattern, SurfacePatternDirection, SurfacePatternKind};
pub type P = [f64; 2];
/// Kleinster Linienabstand auf dem Papier (mm), ab dem ausgedünnt wird.
pub const MIN_PAPER_MM: f64 = 0.7;
/// Höchster Ausdünnungsfaktor; darüber fällt die Linienschar weg.
const MAX_THIN: u32 = 8;
/// Obergrenze Segmente je Fläche (Schutz gegen Unsinn wie 1 mm Abstand auf 100 m).
const MAX_SEGMENTS: usize = 60_000;
/// Geprüfte Musterwerte (alle endlich und positiv).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Spec {
pub kind: SurfacePatternKind,
pub spacing: f64,
pub height: f64,
pub width: f64,
/// Gesamtdrehung (Grad) der Musterlinien gegenüber der Fläche.
pub angle: f64,
}
fn pos(v: Option<f64>) -> Option<f64> {
v.filter(|x| x.is_finite() && *x > 0.0)
}
/// Muster eines Bauteils + Element-Drehung → [`Spec`]; `None` bei unbekannter Art oder unbrauchbaren Massen.
pub fn spec_of(sp: &SurfacePattern, element_angle_deg: f64) -> Option<Spec> {
let spacing = pos(Some(sp.spacing))?;
let natural_vertical = matches!(sp.kind, SurfacePatternKind::Lines | SurfacePatternKind::BoardBatten | SurfacePatternKind::Trapezoid);
if sp.kind == SurfacePatternKind::Unknown {
return None;
}
// Kanonisch: Linien-Arten senkrecht, Verbände/Raster mit waagrechten Lagen; die andere Richtung
// ist um 90° gedreht.
let turned = match sp.direction {
Some(SurfacePatternDirection::Vertical) => !natural_vertical,
Some(SurfacePatternDirection::Horizontal) => natural_vertical,
_ => false,
};
let base = sp.angle.filter(|a| a.is_finite()).unwrap_or(0.0);
let el = if element_angle_deg.is_finite() { element_angle_deg } else { 0.0 };
Some(Spec {
kind: sp.kind,
spacing,
height: pos(sp.height).unwrap_or(spacing),
width: pos(sp.width).unwrap_or(spacing * 0.25).min(spacing),
angle: base + el + if turned { 90.0 } else { 0.0 },
})
}
/// Ausdünnungsfaktor (1, 2, 4, 8) für einen Linienabstand `period_m` bei 1:`scale`; `None` = weglassen.
pub fn thin_factor(period_m: f64, scale: f64) -> Option<u32> {
let s = if scale.is_finite() && scale > 0.0 { scale } else { 100.0 };
let mm = period_m * 1000.0 / s;
let mut m = 1u32;
while mm * m as f64 + 1e-12 < MIN_PAPER_MM {
m *= 2;
if m > MAX_THIN {
return None;
}
}
Some(m)
}
fn point_in(pt: P, poly: &[P]) -> bool {
let mut inside = false;
let n = poly.len();
let mut j = n - 1;
for i in 0..n {
let (a, b) = (poly[i], poly[j]);
if (a[1] > pt[1]) != (b[1] > pt[1]) && pt[0] < (b[0] - a[0]) * (pt[1] - a[1]) / (b[1] - a[1]) + a[0] {
inside = !inside;
}
j = i;
}
inside
}
/// Teilstücke der Strecke a–b innerhalb des Polygons (gerade-ungerade-Regel).
pub fn clip_to_poly(a: P, b: P, poly: &[P], out: &mut Vec<(P, P)>) {
let n = poly.len();
if n < 3 {
return;
}
let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
let mut ts = vec![0.0, 1.0];
for i in 0..n {
let (c, d) = (poly[i], poly[(i + 1) % n]);
let (ex, ey) = (d[0] - c[0], d[1] - c[1]);
let den = dx * ey - dy * ex;
if den.abs() < 1e-15 {
continue;
}
let t = ((c[0] - a[0]) * ey - (c[1] - a[1]) * ex) / den;
let u = ((c[0] - a[0]) * dy - (c[1] - a[1]) * dx) / den;
if (0.0..=1.0).contains(&t) && (-1e-12..=1.0 + 1e-12).contains(&u) {
ts.push(t);
}
}
ts.sort_by(|x, y| x.total_cmp(y));
let at = |t: f64| [a[0] + dx * t, a[1] + dy * t];
let mut run: Option<(f64, f64)> = None;
for w in ts.windows(2) {
if w[1] - w[0] < 1e-12 {
continue;
}
if point_in(at((w[0] + w[1]) / 2.0), poly) {
run = Some(match run {
Some((s, e)) if (e - w[0]).abs() < 1e-12 => (s, w[1]),
Some((s, e)) => {
out.push((at(s), at(e)));
(w[0], w[1])
}
None => (w[0], w[1]),
});
}
}
if let Some((s, e)) = run {
if (e - s) * (dx * dx + dy * dy).sqrt() > 1e-9 {
out.push((at(s), at(e)));
}
}
}
/// Deterministisches Rauschen in [0, 1) je Gitterpunkt (für „polygonal").
fn hash01(i: i64, j: i64, salt: u64) -> f64 {
let mut h = (i as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ (j as u64).wrapping_mul(0xC2B2_AE3D_27D4_EB4F) ^ salt;
h ^= h >> 33;
h = h.wrapping_mul(0xFF51_AFD7_ED55_8CCD);
h ^= h >> 33;
(h >> 11) as f64 / (1u64 << 53) as f64
}
/// Liniensegmente des Musters auf der Fläche `poly` (Flächen-Koordinaten, Meter). `offset` verschiebt
/// den Musterursprung; `scale` ist der Massstabsnenner (Ausdünnung).
pub fn segments(poly: &[P], spec: &Spec, offset: P, scale: f64) -> Vec<(P, P)> {
let mut out = Vec::new();
if poly.len() < 3 || poly.iter().any(|p| !p[0].is_finite() || !p[1].is_finite()) {
return out;
}
let off = [if offset[0].is_finite() { offset[0] } else { 0.0 }, if offset[1].is_finite() { offset[1] } else { 0.0 }];
let rad = spec.angle.to_radians();
let (c, s) = (rad.cos(), rad.sin());
// Muster-Raum: q = R(−angle)·(p − off); zurück: p = R(angle)·q + off.
let to_q = |p: P| -> P {
let (x, y) = (p[0] - off[0], p[1] - off[1]);
[c * x + s * y, -s * x + c * y]
};
let to_p = |q: P| -> P { [c * q[0] - s * q[1] + off[0], s * q[0] + c * q[1] + off[1]] };
let qpoly: Vec<P> = poly.iter().map(|p| to_q(*p)).collect();
let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
for q in &qpoly {
x0 = x0.min(q[0]);
y0 = y0.min(q[1]);
x1 = x1.max(q[0]);
y1 = y1.max(q[1]);
}
let mut raw: Vec<(P, P)> = Vec::new();
let budget = |n: f64| n.is_finite() && n < MAX_SEGMENTS as f64;
// Senkrechte Linien x = k·period + d (k Vielfaches von m), über die ganze Höhe.
let vlines = |raw: &mut Vec<(P, P)>, period: f64, d: f64, m: u32| {
let k0 = ((x0 - d) / period).floor() as i64;
let k1 = ((x1 - d) / period).ceil() as i64;
if !budget((k1 - k0) as f64 / m as f64) {
return;
}
for k in k0..=k1 {
if k.rem_euclid(m as i64) == 0 {
let x = k as f64 * period + d;
raw.push(([x, y0], [x, y1]));
}
}
};
let hlines = |raw: &mut Vec<(P, P)>, period: f64, m: u32| -> (i64, i64) {
let k0 = (y0 / period).floor() as i64;
let k1 = (y1 / period).ceil() as i64;
if !budget((k1 - k0) as f64 / m as f64) {
return (0, -1);
}
for k in k0..=k1 {
if k.rem_euclid(m as i64) == 0 {
let y = k as f64 * period;
raw.push(([x0, y], [x1, y]));
}
}
(k0, k1)
};
match spec.kind {
SurfacePatternKind::Lines => {
if let Some(m) = thin_factor(spec.spacing, scale) {
vlines(&mut raw, spec.spacing, 0.0, m);
}
}
SurfacePatternKind::BoardBatten => {
if let Some(m) = thin_factor(spec.spacing, scale) {
vlines(&mut raw, spec.spacing, 0.0, m);
// Zweite Kante der Deckleiste nur, solange sie auf dem Papier getrennt bleibt.
if m == 1 && thin_factor(spec.width, scale) == Some(1) {
vlines(&mut raw, spec.spacing, spec.width, 1);
}
}
}
SurfacePatternKind::Trapezoid => {
if let Some(m) = thin_factor(spec.spacing, scale) {
let w = spec.width;
if m == 1 && thin_factor(w / 4.0, scale) == Some(1) {
// Untergurt-Kanten und Obergurt-Kanten (Stege schräg dazwischen).
for d in [0.0, w / 4.0, w * 0.75, w] {
vlines(&mut raw, spec.spacing, d, 1);
}
} else if m == 1 && thin_factor(w, scale) == Some(1) {
vlines(&mut raw, spec.spacing, 0.0, 1);
vlines(&mut raw, spec.spacing, w, 1);
} else {
vlines(&mut raw, spec.spacing, 0.0, m);
}
}
}
SurfacePatternKind::Grid => {
if let Some(m) = thin_factor(spec.height, scale) {
hlines(&mut raw, spec.height, m);
}
if let Some(m) = thin_factor(spec.spacing, scale) {
vlines(&mut raw, spec.spacing, 0.0, m);
}
}
SurfacePatternKind::RunningBond | SurfacePatternKind::Shingles => {
let Some(m) = thin_factor(spec.height, scale) else { return out };
let (k0, k1) = hlines(&mut raw, spec.height, m);
// Stossfugen nur bei voller Lagenteilung (sonst stimmt der Versatz nicht mehr).
if m == 1 && thin_factor(spec.spacing, scale) == Some(1) {
let shift = if spec.kind == SurfacePatternKind::Shingles { 1.0 / 3.0 } else { 0.5 };
let j0 = (x0 / spec.spacing).floor() as i64 - 1;
let j1 = (x1 / spec.spacing).ceil() as i64 + 1;
if budget((k1 - k0 + 1) as f64 * (j1 - j0 + 1) as f64) {
for k in k0..k1 {
let ya = k as f64 * spec.height;
let d = (k.rem_euclid(if shift == 0.5 { 2 } else { 3 }) as f64 * shift).fract() * spec.spacing;
for j in j0..=j1 {
let x = j as f64 * spec.spacing + d;
raw.push(([x, ya], [x, ya + spec.height]));
}
}
}
}
}
SurfacePatternKind::Polygonal => {
// Unregelmässiges Netz: verschobene Gitterpunkte, Kanten nach rechts/oben, je Zelle eine
// zufällige Diagonale — ergibt Drei-, Vier- und Fünfecke wie ein Polygonalmauerwerk.
let a = spec.spacing;
if thin_factor(a * 0.5, scale) != Some(1) {
return out;
}
let b = spec.height;
let i0 = (x0 / a).floor() as i64 - 1;
let i1 = (x1 / a).ceil() as i64 + 1;
let j0 = (y0 / b).floor() as i64 - 1;
let j1 = (y1 / b).ceil() as i64 + 1;
if !budget(3.0 * (i1 - i0 + 1) as f64 * (j1 - j0 + 1) as f64) {
return out;
}
let pt = |i: i64, j: i64| -> P {
let jx = (hash01(i, j, 1) - 0.5) * 0.55 * a;
let jy = (hash01(i, j, 2) - 0.5) * 0.55 * b;
[i as f64 * a + jx + if j.rem_euclid(2) == 1 { 0.5 * a } else { 0.0 }, j as f64 * b + jy]
};
for i in i0..i1 {
for j in j0..j1 {
let p = pt(i, j);
raw.push((p, pt(i + 1, j)));
raw.push((p, pt(i, j + 1)));
if hash01(i, j, 3) < 0.5 {
raw.push((p, pt(i + 1, j + 1)));
}
}
}
}
SurfacePatternKind::Unknown => {}
}
let mut clipped = Vec::new();
for (a, b) in raw {
clip_to_poly(a, b, &qpoly, &mut clipped);
if clipped.len() > MAX_SEGMENTS {
break;
}
}
out.extend(clipped.into_iter().map(|(a, b)| (to_p(a), to_p(b))));
out
}
// ── Ebene Fläche im Raum ────────────────────────────────────────────────────
pub type V3 = [f64; 3];
fn sub(a: V3, b: V3) -> V3 {
[a[0] - b[0], a[1] - b[1], a[2] - b[2]]
}
fn dot(a: V3, b: V3) -> f64 {
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
fn cross(a: V3, b: V3) -> V3 {
[a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
}
fn norm(a: V3) -> Option<V3> {
let l = dot(a, a).sqrt();
(l > 1e-12 && l.is_finite()).then(|| [a[0] / l, a[1] / l, a[2] / l])
}
/// Muster auf einer ebenen Fläche im Raum (Plan-Koordinaten `[x, y, z]`, z aufwärts), z. B. einer
/// Dachfläche: x läuft waagrecht (traufparallel), y in der Falllinie aufwärts, Ursprung am tiefsten
/// Punkt. Liefert Raum-Segmente.
pub fn segments_3d(poly: &[V3], spec: &Spec, offset: P, scale: f64) -> Vec<(V3, V3)> {
if poly.len() < 3 {
return Vec::new();
}
// Newell-Normale
let mut n = [0.0; 3];
for i in 0..poly.len() {
let (a, b) = (poly[i], poly[(i + 1) % poly.len()]);
n[0] += (a[1] - b[1]) * (a[2] + b[2]);
n[1] += (a[2] - b[2]) * (a[0] + b[0]);
n[2] += (a[0] - b[0]) * (a[1] + b[1]);
}
let Some(n) = norm(n) else { return Vec::new() };
let up = [0.0, 0.0, 1.0];
let u = norm(cross(up, n)).unwrap_or([1.0, 0.0, 0.0]);
let mut v = cross(n, u);
if v[2] < 0.0 || (v[2].abs() < 1e-12 && dot(v, [0.0, 1.0, 0.0]) < 0.0) {
v = [-v[0], -v[1], -v[2]];
}
let o = poly.iter().copied().fold(poly[0], |m, p| if p[2] < m[2] { p } else { m });
let local: Vec<P> = poly.iter().map(|p| [dot(sub(*p, o), u), dot(sub(*p, o), v)]).collect();
let back = |q: P| -> V3 { [o[0] + u[0] * q[0] + v[0] * q[1], o[1] + u[1] * q[0] + v[1] * q[1], o[2] + u[2] * q[0] + v[2] * q[1]] };
segments(&local, spec, offset, scale).into_iter().map(|(a, b)| (back(a), back(b))).collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn pat(kind: SurfacePatternKind, spacing: f64, height: Option<f64>) -> SurfacePattern {
SurfacePattern { kind, spacing, height, ..Default::default() }
}
fn rect(w: f64, h: f64) -> Vec<P> {
vec![[0.0, 0.0], [w, 0.0], [w, h], [0.0, h]]
}
#[test]
fn lattung_senkrecht_im_abstand() {
let s = spec_of(&pat(SurfacePatternKind::Lines, 0.1, None), 0.0).unwrap();
let segs = segments(&rect(1.0, 2.0), &s, [0.05, 0.0], 50.0);
// x = 0.05, 0.15 … 0.95 → 10 Linien, jede volle Höhe, senkrecht
assert_eq!(segs.len(), 10, "{segs:?}");
for (a, b) in &segs {
assert!((a[0] - b[0]).abs() < 1e-9);
assert!(((a[1] - b[1]).abs() - 2.0).abs() < 1e-9);
}
}
#[test]
fn richtung_waagrecht_und_versatz() {
let mut p = pat(SurfacePatternKind::Lines, 0.25, None);
p.direction = Some(SurfacePatternDirection::Horizontal);
let s = spec_of(&p, 0.0).unwrap();
let segs = segments(&rect(2.0, 1.0), &s, [0.0, 0.1], 50.0);
// y = 0.1, 0.35, 0.6, 0.85 (waagrecht, Ursprung um 0.1 versetzt)
let mut ys: Vec<f64> = segs.iter().map(|(a, _)| (a[1] * 1000.0).round() / 1000.0).collect();
ys.sort_by(f64::total_cmp);
ys.dedup();
assert_eq!(ys, vec![0.1, 0.35, 0.6, 0.85]);
assert!(segs.iter().all(|(a, b)| (a[1] - b[1]).abs() < 1e-9));
}
#[test]
fn element_drehung_dreht_muster() {
let s = spec_of(&pat(SurfacePatternKind::Lines, 0.2, None), 90.0).unwrap();
let segs = segments(&rect(1.0, 1.0), &s, [0.0, 0.0], 50.0);
assert!(!segs.is_empty());
assert!(segs.iter().all(|(a, b)| (a[1] - b[1]).abs() < 1e-9), "nach 90° waagrecht");
}
#[test]
fn laeuferverband_versetzte_stossfugen() {
let s = spec_of(&pat(SurfacePatternKind::RunningBond, 0.26, Some(0.08)), 0.0).unwrap();
let poly = vec![[-0.01, 0.0], [1.05, 0.0], [1.05, 0.16], [-0.01, 0.16]];
let segs = segments(&poly, &s, [0.0, 0.0], 20.0);
let joints: Vec<&(P, P)> = segs.iter().filter(|(a, b)| (a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() > 1e-6).collect();
let lage = |y: f64| -> Vec<f64> {
let mut v: Vec<f64> = joints.iter().filter(|(a, b)| a[1].min(b[1]) < y && a[1].max(b[1]) > y).map(|(a, _)| (a[0] * 1000.0).round() / 1000.0).collect();
v.sort_by(f64::total_cmp);
v
};
assert_eq!(lage(0.04), vec![0.0, 0.26, 0.52, 0.78, 1.04]);
assert_eq!(lage(0.12), vec![0.13, 0.39, 0.65, 0.91]);
}
#[test]
fn grober_massstab_duennt_aus_und_laesst_weg() {
let s = spec_of(&pat(SurfacePatternKind::Lines, 0.1, None), 0.0).unwrap();
let fein = segments(&rect(4.0, 1.0), &s, [0.05, 0.0], 100.0).len(); // 1 mm Papier
let mittel = segments(&rect(4.0, 1.0), &s, [0.05, 0.0], 200.0).len(); // 0.5 mm → jede 2.
let grob = segments(&rect(4.0, 1.0), &s, [0.05, 0.0], 2000.0).len(); // 0.05 mm → weg
assert_eq!(fein, 40);
assert_eq!(mittel, 20);
assert_eq!(grob, 0);
assert_eq!(thin_factor(0.1, 100.0), Some(1));
assert_eq!(thin_factor(0.1, 500.0), Some(4));
assert_eq!(thin_factor(0.1, 1000.0), Some(8));
assert_eq!(thin_factor(0.1, 2000.0), None);
}
#[test]
fn zuschnitt_an_schraeger_flaeche() {
// Giebeldreieck: Linien enden an den Schrägen
let tri = vec![[0.0, 0.0], [2.0, 0.0], [1.0, 1.0]];
let s = spec_of(&pat(SurfacePatternKind::Lines, 0.5, None), 0.0).unwrap();
let segs = segments(&tri, &s, [0.0, 0.0], 50.0);
let mid = segs.iter().find(|(a, _)| (a[0] - 1.0).abs() < 1e-9).unwrap();
assert!((mid.0[1].max(mid.1[1]) - 1.0).abs() < 1e-9);
let side = segs.iter().find(|(a, _)| (a[0] - 0.5).abs() < 1e-9).unwrap();
assert!((side.0[1].max(side.1[1]) - 0.5).abs() < 1e-9);
}
#[test]
fn alle_arten_liefern_linien_und_bleiben_in_der_flaeche() {
use SurfacePatternKind::*;
for kind in [Lines, BoardBatten, RunningBond, Shingles, Trapezoid, Polygonal, Grid] {
let mut p = pat(kind, 0.3, Some(0.2));
p.width = Some(0.08);
let s = spec_of(&p, 15.0).unwrap();
let segs = segments(&rect(3.0, 2.0), &s, [0.05, 0.0], 20.0);
assert!(segs.len() > 5, "{kind:?}");
for (a, b) in segs {
for q in [a, b] {
assert!(q[0] > -1e-6 && q[0] < 3.0 + 1e-6 && q[1] > -1e-6 && q[1] < 2.0 + 1e-6, "{kind:?} {q:?}");
}
}
}
}
#[test]
fn unsinn_ergibt_nichts() {
assert!(spec_of(&pat(SurfacePatternKind::Lines, 0.0, None), 0.0).is_none());
assert!(spec_of(&pat(SurfacePatternKind::Lines, f64::NAN, None), 0.0).is_none());
let s = spec_of(&pat(SurfacePatternKind::Lines, 1e-6, None), 0.0).unwrap();
assert!(segments(&rect(100.0, 100.0), &s, [0.0, 0.0], 1.0).len() <= MAX_SEGMENTS + 1);
assert!(segments(&[[0.0, 0.0], [f64::NAN, 1.0], [1.0, 1.0]], &s, [0.0, 0.0], 100.0).is_empty());
}
#[test]
fn dachflaeche_traufparallel() {
// 30°-Dachfläche, Traufe entlang x auf z = 0
let h = 0.5f64;
let poly = vec![[0.0, 0.0, 0.0], [4.0, 0.0, 0.0], [4.0, 3f64.sqrt() * h, h], [0.0, 3f64.sqrt() * h, h]];
let mut p = pat(SurfacePatternKind::Lines, 0.25, None);
p.direction = Some(SurfacePatternDirection::Horizontal);
let s = spec_of(&p, 0.0).unwrap();
let segs = segments_3d(&poly, &s, [0.0, 0.1], 50.0);
// Falllinie 1.0 m lang → Lagen bei .1, .35, .6, .85 → 4 traufparallele Linien
assert_eq!(segs.len(), 4);
assert!(segs.iter().all(|(a, b)| (a[2] - b[2]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9));
}
}
+7 -2
View File
@@ -159,6 +159,9 @@ struct Globals {
viewport_px: [f32; 2],
stroke_px: f32,
stroke_scale: f32,
/// Faktor auf die Strichmuster-Laengen (`N / 100`, wie `gpu::Globals::dash_scale`) ([96]).
dash_scale: f32,
_pad: [f32; 3],
}
#[derive(Clone, Debug, serde::Deserialize)]
@@ -625,7 +628,7 @@ impl ChunkRenderer {
let proj = projection(bounds, g.origin);
for b in &g.fill_batches {
let c = if g.greyed { [1.0, 1.0, 1.0, b.color[3]] } else { b.color };
blocks.push(Globals { view_proj: proj, color: c, viewport_px: vp, stroke_px: 0.0, stroke_scale: 1.0 });
blocks.push(Globals { view_proj: proj, color: c, viewport_px: vp, stroke_px: 0.0, stroke_scale: 1.0, dash_scale: 1.0, _pad: [0.0; 3] });
}
}
// Striche (Linien + gestrichelte) je Chunk in Maler-Reihenfolge (`stroke_order`).
@@ -641,7 +644,7 @@ impl ChunkRenderer {
(b.color, b.stroke_mm, if b.device_px { 1.0 } else if b.screen_px { meet as f32 } else { mm_px as f32 })
};
let c = if g.greyed { [GREY, GREY, GREY, color[3]] } else { color };
blocks.push(Globals { view_proj: proj, color: c, viewport_px: vp, stroke_px: stroke_mm, stroke_scale: scale });
blocks.push(Globals { view_proj: proj, color: c, viewport_px: vp, stroke_px: stroke_mm, stroke_scale: scale, dash_scale: if paper_scale_n > 0.0 && paper_scale_n.is_finite() { (paper_scale_n / 100.0) as f32 } else { 1.0 }, _pad: [0.0; 3] });
}
}
@@ -656,6 +659,8 @@ impl ChunkRenderer {
viewport_px: vp,
stroke_px: 0.0,
stroke_scale: 1.0,
dash_scale: 1.0,
_pad: [0.0; 3],
});
// Glyphen-Mesh-Puffer neu aufbauen, wenn neue Glyphen dazukamen.
if let Some(font) = self.font.as_mut() {
+17
View File
@@ -35,6 +35,10 @@ struct Globals {
viewport_px: [f32; 2],
stroke_px: f32,
stroke_scale: f32,
/// Faktor auf die Strichmuster-Laengen ([96]): Muster sind bei 1:100 kompiliert, auf dem Papier
/// gelten sie in mm — bei 1:N also `N / 100` (Papier-mm-Batches), sonst 1.
dash_scale: f32,
_pad: [f32; 3],
}
impl Default for Globals {
@@ -45,6 +49,8 @@ impl Default for Globals {
viewport_px: [1.0, 1.0],
stroke_px: 0.0,
stroke_scale: 1.0,
dash_scale: 1.0,
_pad: [0.0; 3],
}
}
}
@@ -60,6 +66,9 @@ struct ArcGlobals {
viewport_px: [f32; 2],
px_per_screen: f32,
stroke_scale: f32,
/// Faktor auf die Strichmuster-Laengen (`N / 100`, s. `Globals::dash_scale`).
dash_scale: f32,
_pad: [f32; 3],
}
/// EINE Bogen-Instanz fuer die GPU (Vertex-Puffer, step_mode Instance), 1:1 zum
@@ -738,6 +747,8 @@ impl Renderer {
// beides: px_per_screen fuer Radial-/Kappen-/Dash-AA, stroke_scale fuer die
// Papier-mm-Breite (identisch zu den Linien).
let px_per_screen = meet_scale(view_box, vw, vh);
// Strichmuster sind in Modell-Metern bei 1:100 kompiliert; auf dem Papier gelten sie in mm ([96]).
let dash_scale = if self.paper_scale_n > 0.0 && self.paper_scale_n.is_finite() { self.paper_scale_n / 100.0 } else { 1.0 };
// Frame-Uniform der Bogen-Pipeline schreiben (ein Block fuer ALLE Boegen).
queue.write_buffer(
@@ -748,6 +759,8 @@ impl Renderer {
viewport_px: [vw, vh],
px_per_screen,
stroke_scale: mm_px,
dash_scale,
_pad: [0.0; 3],
}),
);
@@ -766,6 +779,7 @@ impl Renderer {
viewport_px: [vw, vh],
stroke_px: 0.0,
stroke_scale: mm_px,
..Globals::default()
});
}
BatchKind::Dash => {
@@ -776,6 +790,8 @@ impl Renderer {
viewport_px: [vw, vh],
stroke_px: b.stroke_mm,
stroke_scale: if b.width_screen { px_per_screen } else { mm_px },
dash_scale: if b.width_screen { 1.0 } else { dash_scale },
_pad: [0.0; 3],
});
}
BatchKind::Line => {
@@ -790,6 +806,7 @@ impl Renderer {
// zoom-skalierend wie der SVG-`<pattern>`-Strich) —
// Geraete-px = Breite * meet-Skala statt * mm->px.
stroke_scale: if b.width_screen { px_per_screen } else { mm_px },
..Globals::default()
});
}
}
+11 -5
View File
@@ -133,6 +133,7 @@ struct ArcGlobals {
viewport_px : vec2<f32>,
px_per_screen : f32,
stroke_scale : f32,
dash_scale : f32,
};
@group(0) @binding(0) var<uniform> g : ArcGlobals;
@@ -232,7 +233,9 @@ fn fs_main(in : VsOut) -> @location(0) vec4<f32> {
var progress = da;
if (sweep < 0.0) { progress = -da; }
progress = max(progress, 0.0);
let s_model = progress * r_m;
// Muster mit dem Massstab mitskalieren ([96]): statt das Muster zu strecken, die Lauflaenge stauchen.
let ds = select(1.0, g.dash_scale, g.dash_scale > 0.0);
let s_model = progress * r_m / ds;
let m = s_model - dash_total * floor(s_model / dash_total);
var cyc = array<f32, 4>(in.dash.x, in.dash.y, in.dash.z, in.dash.w);
@@ -249,7 +252,7 @@ fn fs_main(in : VsOut) -> @location(0) vec4<f32> {
acc = acc + seg;
}
let px_per_m = PX_PER_M_2D * pps;
let edge_px = edge * px_per_m;
let edge_px = edge * ds * px_per_m;
// Signierter Abstand: innen "an" positiv, innen "aus" negativ.
let sdist = select(-edge_px, edge_px, cur_on);
cov_dash = smoothstep(-0.5, 0.5, sdist);
@@ -285,6 +288,7 @@ struct Globals {
viewport_px : vec2<f32>,
stroke_px : f32,
stroke_scale : f32,
dash_scale : f32,
};
@group(0) @binding(0) var<uniform> globals : Globals;
@@ -335,9 +339,11 @@ fn vs_main(
let s0 = run.x * pps;
out.sy = vec2<f32>(s0 + c.x * seg_px + ext, c.y * hw);
out.seg = vec4<f32>(s0, s0 + seg_px, run.y * pps, hw);
out.pat = vec2<f32>(run.z * pps, run.w);
out.d0 = d0 * pps;
out.d1 = d1 * pps;
// Muster bei 1:100 kompiliert, auf dem Papier in mm: mit dem Massstab mitskalieren ([96]).
let ds = select(1.0, globals.dash_scale, globals.dash_scale > 0.0);
out.pat = vec2<f32>(run.z * pps * ds, run.w);
out.d0 = d0 * pps * ds;
out.d1 = d1 * pps * ds;
return out;
}
+57 -4
View File
@@ -100,11 +100,13 @@ pub struct DashBatch {
pub width_screen: bool,
}
/// Strichmuster (Papier-mm) → Zyklus in Modell-Metern wie in `split_dash`: negative Werte zu 0,
/// Nullen weg, ungerade Laenge verdoppelt. `None` = kein gueltiges Muster (durchgezogen).
/// Strichmuster (Papier-mm) → Zyklus in Modell-Metern: negative Werte zu 0, ungerade Laenge verdoppelt.
/// Nullen bleiben stehen ([96]): ein AN-Wert 0 ist ein PUNKT (der Shader zeichnet ihn mit runden
/// Enden, wie SVG mit `stroke-linecap: round`); frueher fielen sie weg und verschoben AN/AUS (eine
/// Strichpunktlinie wurde zur Strichlinie mit ungleichen Luecken). `None` = kein gueltiges Muster.
fn dash_cycle_m(dash: &[f32]) -> Option<Vec<f32>> {
let pat: Vec<f32> = dash.iter().copied().map(|d| d.max(0.0) * DASH_MM_TO_M).filter(|d| *d > 0.0).collect();
if pat.is_empty() {
let pat: Vec<f32> = dash.iter().copied().map(|d| if d.is_finite() { d.max(0.0) * DASH_MM_TO_M } else { 0.0 }).collect();
if pat.iter().all(|d| *d <= 0.0) {
return None;
}
let cycle: Vec<f32> = if pat.len() % 2 == 0 { pat } else { [pat.as_slice(), pat.as_slice()].concat() };
@@ -952,6 +954,22 @@ fn compile_arc(geo: &mut GpuGeometry, a: &Arc, bounds: &mut Bounds) {
if sweep.abs() < 1e-6 {
return;
}
// Muster mit Punkten oder mehr Eintraegen, als der Bogen-Shader fasst (Strich-Zweipunktlinie):
// als feiner Polygonzug ueber den Linien-Strichpfad (Punkte rund, Phase durchgehend) ([96]).
if let Some(cycle) = a.dash.as_deref().filter(|d| !d.is_empty()).and_then(dash_cycle_m) {
if cycle.len() > MAX_ARC_DASH || cycle.iter().step_by(2).any(|d| *d <= 0.0) {
// Modell-Winkel = gespiegelte Bildschirm-Winkel (`to_screen` negiert Y).
let n = ((sweep.abs() / 0.03).ceil() as usize).clamp(8, 4096);
let pts: Vec<Point> = (0..=n)
.map(|i| {
let t = -(a0 + sweep * i as f32 / n as f32);
[a.center[0] + a.r * t.cos(), a.center[1] + a.r * t.sin()]
})
.collect();
stroke_dashed_or_solid(geo, &pts, false, a.color, a.width_mm, false, a.dash.as_deref(), bounds);
return;
}
}
let (dash, dash_count, dash_total) = prepare_arc_dash(a.dash.as_deref());
geo.arcs.push(ArcInstanceData {
center,
@@ -1108,6 +1126,41 @@ mod tests {
assert!(geo.dash_segments.is_empty() && !geo.line_idx.is_empty());
}
/// [96] Punkte (AN = 0) bleiben im Zyklus: Strichpunktlinie [12, 1.5, 0, 1.5] behaelt vier
/// Eintraege (Strich, Luecke, Punkt, Luecke) statt zu [12, 1.5, 1.5] zusammenzufallen.
#[test]
fn punkte_bleiben_im_muster() {
let c = dash_cycle_m(&[12.0, 1.5, 0.0, 1.5]).unwrap();
assert_eq!(c.len(), 4);
assert_eq!(c[2], 0.0);
assert!((c[0] - 12.0 * DASH_MM_TO_M).abs() < 1e-6);
let geo = compile_scene(&dashed_line([0.0, 0.0], [5.0, 0.0], vec![12.0, 1.5, 0.0, 1.5]));
assert_eq!(geo.dash_segments.len(), 1);
assert_eq!(geo.dash_segments[0].count, 4);
// Deckung: der Punkt liegt bei 13.5 mm (Muster-Raum) und ist rund sichtbar, die Luecken nicht.
let px = PX_PER_M; // 1 Bildschirm-Einheit = 1 px
let cyc: Vec<f32> = c.iter().map(|d| d * px).collect();
let total: f32 = cyc.iter().sum();
let seg = [0.0, 5.0 * px, 5.0 * px, 0.5];
let dot = (12.0 + 1.5) * DASH_MM_TO_M * px;
assert!(dash_coverage(dot, 0.0, seg, total, &cyc) < 0.01);
assert!(dash_coverage(dot - 0.7 * DASH_MM_TO_M * px, 0.0, seg, total, &cyc) > 0.5);
}
/// [96] Boegen mit Punkten/langen Mustern laufen ueber den Linien-Strichpfad.
#[test]
fn bogen_mit_punktmuster_als_strichzug() {
let scene = Scene {
arcs: vec![Arc { center: [0.0, 0.0], from: [1.0, 0.0], to: [0.0, 1.0], r: 1.0, color: [0.0, 0.0, 0.0, 1.0], width_mm: 0.25, dash: Some(vec![12.0, 1.5, 0.0, 1.5, 0.0, 1.5]) }],
..Default::default()
};
let geo = compile_scene(&scene);
assert!(geo.arcs.is_empty());
assert!(!geo.dash_segments.is_empty());
let plain = Scene { arcs: vec![Arc { dash: Some(vec![0.06, 0.04]), ..scene.arcs[0].clone() }], ..Default::default() };
assert_eq!(compile_scene(&plain).arcs.len(), 1);
}
/// Der Shader-Spiegel deckt genau die Pixel, die die frueheren Teilstuecke samt runden Kappen
/// deckten: Abstand zum naechsten `split_dash`-Stueck (Geraete-px) == `dash_coverage`.
#[test]
+2
View File
@@ -1593,6 +1593,7 @@ export default function App() {
patchPenSetColor,
patchPenSetWeight,
seedStandardPenSet,
loadStandards,
addCustomPalette,
renameCustomPalette,
deleteCustomPalette,
@@ -2547,6 +2548,7 @@ export default function App() {
onPatchPenSetColor: patchPenSetColor,
onPatchPenSetWeight: patchPenSetWeight,
onSeedStandardPenSet: seedStandardPenSet,
onLoadStandards: loadStandards,
onAddCustomPalette: addCustomPalette,
onRenameCustomPalette: renameCustomPalette,
onDeleteCustomPalette: deleteCustomPalette,
+1 -1
View File
@@ -576,7 +576,7 @@ async function execute(project: Project, file: string, command: string, rest: st
// Wie die App: verdeckte Kanten nach der Ebene, geschnittene Fenster/Türen.
plan = generateSectionPlan(o, false, { visibleCodes: allCodes, hiddenLines: lvl.hiddenLines, openings: true });
} else {
plan = generateElevationPlan(project, lvl);
plan = generateElevationPlan(project, lvl, { scaleDenominator: scale });
if (!plan) fail("keine gültige Ansichtslinie");
}
if (args.flags.get("format") === "json") {
+1 -1
View File
@@ -111,7 +111,7 @@ export async function callTool(file: string, name: string, args: Record<string,
if (!o) return text("keine gültige Schnittlinie", true);
return text(planToSvgString(generateSectionPlan(o, false, { visibleCodes: codes }), { scaleDenominator: scale }));
}
const plan = generateElevationPlan(project, lvl);
const plan = generateElevationPlan(project, lvl, { scaleDenominator: scale });
return plan ? text(planToSvgString(plan, { scaleDenominator: scale })) : text("keine gültige Ansichtslinie", true);
}
case "apply_ops": {
+1 -1
View File
@@ -57,7 +57,7 @@ export type LoadFileResult =
| { ok: false; error: string };
/** Wurzel-Abfragen des Kerns (`queries.rs::run_root`). */
export type RootQueryName = "penRebakeOps" | "penDeleteOps" | "penSeedOps" | "folderPdfPages" | "layoutTitleBlock" | "translatePatch" | "translateOps" | "selectionFilterPatch";
export type RootQueryName = "penRebakeOps" | "penDeleteOps" | "penSeedOps" | "standardsMergeOps" | "folderPdfPages" | "layoutTitleBlock" | "translatePatch" | "translateOps" | "selectionFilterPatch";
/** Abfragen des Kerns (`queries.rs`). */
export type QueryName =
+30
View File
@@ -1228,6 +1228,36 @@ export const de = {
"resources.col.prio.hint": "Höhere Priorität läuft am Stoß durch",
"resources.col.texture": "Textur",
"resources.col.material": "Material",
"material.fetchAmbient": "Textur laden",
"material.fetchAmbient.hint": "Lädt die Texturkarten dieses ambientCG-Materials (CC0) herunter.",
"resources.loadStandards": "Standards laden",
"resources.loadStandards.hint": "Ergänzt die SIA-400-Standards (Baustoffe mit Schraffur, Ansichtsschraffur, Textur und Kennwerten, Linientypen, Wand-/Decken-/Dachaufbauten). Vorhandene Einträge (gleiche id oder gleicher Name) bleiben unverändert.",
"resources.col.lambda": "Wärmeleitfähigkeit λ [W/mK]",
"resources.col.density": "Rohdichte [kg/m³]",
"resources.col.fireClass": "Brandverhalten (VKF)",
"resources.col.fireClass.none": "—",
"resources.col.elevationColor": "Ansichtsfarbe",
"resources.col.surfacePattern": "Ansichtsschraffur",
"resources.col.surfacePattern.hint": "Muster auf sichtbaren Flächen (Ansicht, Dachaufsicht): Masse in Metern am Bau, Ausrichtung am Element; bei grobem Massstab ausgedünnt.",
"resources.surfacePattern.none": "Keine",
"resources.surfacePattern.lines": "Lattung / Schalung (Linien)",
"resources.surfacePattern.boardBatten": "Boden-Deckel-Schalung",
"resources.surfacePattern.runningBond": "Läuferverband",
"resources.surfacePattern.shingles": "Schindeln",
"resources.surfacePattern.trapezoid": "Trapezblech",
"resources.surfacePattern.polygonal": "Naturstein polygonal",
"resources.surfacePattern.grid": "Plattenteilung",
"resources.surfacePattern.direction": "Richtung",
"resources.surfacePattern.direction.auto": "Standard",
"resources.surfacePattern.direction.vertical": "Senkrecht",
"resources.surfacePattern.direction.horizontal": "Waagrecht",
"resources.surfacePattern.spacing": "Abstand / Länge [m]",
"resources.surfacePattern.height": "Lagenhöhe [m]",
"resources.surfacePattern.width": "Leisten-/Gurtbreite [m]",
"objinfo.surfacePattern": "Ansichtsschraffur",
"objinfo.surfacePattern.angle": "Drehung [°]",
"objinfo.surfacePattern.offsetX": "Versatz entlang [m]",
"objinfo.surfacePattern.offsetY": "Versatz quer [m]",
"resources.col.color.hint": "Grundfarbe — 3D-Diffusfarbe + Fallback für Vorder-/Hintergrund, falls dort keine eigene Farbe gesetzt ist",
"resources.col.foreground": "Vordergrund",
"resources.col.foreground.hint": "Farbe der Muster-/Schraffurlinien (Vordergrund)",
+30
View File
@@ -1221,6 +1221,36 @@ export const en: Record<TranslationKey, string> = {
"resources.col.prio.hint": "Higher priority runs through at the join",
"resources.col.texture": "Texture",
"resources.col.material": "Material",
"material.fetchAmbient": "Load texture",
"material.fetchAmbient.hint": "Downloads the texture maps of this ambientCG material (CC0).",
"resources.loadStandards": "Load standards",
"resources.loadStandards.hint": "Adds the SIA 400 standards (materials with hatch, surface pattern, texture and physical values, line types, wall/ceiling/roof build-ups). Existing entries (same id or same name) stay unchanged.",
"resources.col.lambda": "Thermal conductivity λ [W/mK]",
"resources.col.density": "Density [kg/m³]",
"resources.col.fireClass": "Reaction to fire (VKF)",
"resources.col.fireClass.none": "—",
"resources.col.elevationColor": "Elevation colour",
"resources.col.surfacePattern": "Surface pattern",
"resources.col.surfacePattern.hint": "Pattern drawn on visible faces (elevation, roof top view): sizes in metres on site, oriented along the element; thinned at coarse scales.",
"resources.surfacePattern.none": "None",
"resources.surfacePattern.lines": "Battens / boarding (lines)",
"resources.surfacePattern.boardBatten": "Board and batten",
"resources.surfacePattern.runningBond": "Running bond",
"resources.surfacePattern.shingles": "Shingles",
"resources.surfacePattern.trapezoid": "Trapezoidal sheet",
"resources.surfacePattern.polygonal": "Polygonal stone",
"resources.surfacePattern.grid": "Panel grid",
"resources.surfacePattern.direction": "Direction",
"resources.surfacePattern.direction.auto": "Default",
"resources.surfacePattern.direction.vertical": "Vertical",
"resources.surfacePattern.direction.horizontal": "Horizontal",
"resources.surfacePattern.spacing": "Spacing / length [m]",
"resources.surfacePattern.height": "Course height [m]",
"resources.surfacePattern.width": "Batten / flange width [m]",
"objinfo.surfacePattern": "Surface pattern",
"objinfo.surfacePattern.angle": "Rotation [°]",
"objinfo.surfacePattern.offsetX": "Offset along [m]",
"objinfo.surfacePattern.offsetY": "Offset across [m]",
"resources.col.color.hint": "Base color — 3D diffuse color + fallback for foreground/background when they have no color of their own",
"resources.col.foreground": "Foreground",
"resources.col.foreground.hint": "Color of the pattern/hatch lines (foreground)",
+30
View File
@@ -0,0 +1,30 @@
import { describe, expect, it } from "vitest";
import { emptyProject, sampleProject } from "./sampleProject";
import { standardsMergeOps, withStandards } from "./standards";
describe("Standard-Bibliothek ([100]–[102])", () => {
it("bringt Baustoffe, Linientypen und Aufbauten in ein neues Projekt", () => {
const p = withStandards({ ...emptyProject, components: [], hatches: [], lineStyles: [], wallTypes: [], ceilingTypes: [], roofTypes: [] });
const stb = p.components.find((c) => c.name === "Stahlbeton")!;
expect(stb.lambda).toBe(2.3);
expect(stb.fireClass).toBe("RF1");
expect(p.hatches.some((h) => h.id === stb.hatchId)).toBe(true);
expect(p.components.find((c) => c.name === "Backstein")!.surfacePattern?.kind).toBe("runningBond");
expect(p.lineStyles.find((l) => l.name === "Strichpunktlinie (Achse)")!.dash).toEqual([12, 1.5, 0, 1.5]);
expect(p.wallTypes.map((t) => t.name)).toContain("Holzständerwand hinterlüftet");
expect(p.ceilingTypes?.length).toBe(1);
expect(p.roofTypes?.length).toBe(1);
expect(standardsMergeOps(p)).toEqual([]);
});
it("verdoppelt im bestehenden Projekt nichts und nutzt gleichnamige Einträge", () => {
const p = withStandards(sampleProject);
const names = p.components.map((c) => c.name.toLowerCase());
expect(names.filter((n) => n === "backstein").length).toBe(1);
// Beispiel-Bauteil „Backstein" (id brick) bleibt und wird vom Standard-Aufbau benutzt
const iw = p.wallTypes.find((t) => t.id === "std-wt-iw-backstein")!;
expect(iw.layers[1].componentId).toBe("brick");
expect(p.components.length).toBeGreaterThan(sampleProject.components.length);
expect(standardsMergeOps(p)).toEqual([]);
});
});
+19
View File
@@ -0,0 +1,19 @@
// Standard-Bibliothek ([100]–[102]) aus dem Rust-Kern (`src-tauri/core/src/standards.rs`): Baustoffe mit
// SIA-400-Schnittschraffur, Ansichtsfarbe/-schraffur, 3D-Textur und Kennwerten (λ, Rohdichte, VKF-RF),
// Linientypen nach SIA 400 / ISO 128 und Standard-Aufbauten. Hier nur dünne Fassaden: der Kern liefert die
// Ops, die fehlende Einträge anhängen (gleiche id oder gleicher Name gilt als vorhanden).
import type { Project } from "./types";
import type { CoreOp } from "../core/ops";
import { applyOps } from "../core/ops";
import { documentFor } from "../core/document";
/** Ops, die die fehlenden Standard-Ressourcen anhängen („Standards laden"); leer, wenn alles da ist. */
export function standardsMergeOps(project: Project): CoreOp[] {
return documentFor(project).queryRoot<CoreOp[]>("standardsMergeOps");
}
/** Projekt mit allen Standard-Ressourcen (für neue Projekte). */
export function withStandards(project: Project): Project {
return applyOps(project, standardsMergeOps(project));
}
+61
View File
@@ -329,6 +329,26 @@ export type Component = {
abbrev?: string;
/** Verschneidungs-Rang: höher läuft am Stoß durch (Backbone). */
joinPriority: number;
/** Wärmeleitfähigkeit λ in W/(m·K) (Bemessungswert, z. B. SIA 381/1, Herstellerangabe). */
lambda?: number;
/** Rohdichte in kg/m³. */
density?: number;
/**
* Brandverhalten nach VKF (Brandschutzrichtlinie 13-15): "RF1" (kein Brandbeitrag), "RF2"
* (geringer), "RF3" (zulässiger), "RF4" (unzulässig). Freitext, damit auch Zusätze („RF1 (cr)") gehen.
*/
fireClass?: string;
/** Flächenfarbe in der Ansicht (Fassade/Dachaufsicht). Fehlt sie, gilt die bisherige Farbe. */
elevationColor?: string;
/**
* Ansichtsschraffur ([100]): Oberflächenmuster, das auf sichtbaren Flächen dieses Bauteils gezeichnet
* wird (Ansicht, Dachaufsicht im Grundriss). Masse in Metern am Bau, Ausrichtung am Element.
*/
surfacePattern?: SurfacePattern;
/**
* Herkunft: Kennung des Standard-Eintrags ([100], „Standards laden"), damit erneutes Laden nichts verdoppelt.
*/
standardId?: string;
};
/**
@@ -2233,6 +2253,16 @@ export type Roof = {
color?: string;
/** Stift-Kopplung von `color` (s. `Component.colorPenId`-Doku). */
colorPenId?: string;
/**
* Ansichtsschraffur ([100]): Drehung (Grad) des Oberflächenmusters dieses Elements gegenüber der
* Ausrichtung am Element (Default 0).
*/
surfacePatternAngle?: number;
/**
* Ansichtsschraffur ([100]): Versatz (m) des Musterursprungs (x entlang, y quer/aufwärts) gegenüber
* der Elementkante.
*/
surfacePatternOffset?: Vec2;
};
/**
@@ -2608,6 +2638,27 @@ export type SunStudy = {
show: boolean;
};
/**
* Ansichtsschraffur eines Bauteils ([100]): Muster auf sichtbaren Flächen, im Kern zu Linien gerechnet
* (`surface_pattern.rs`). Masse in Metern am Bau; Ursprung an der Elementkante (Wandanfang/UK, Traufe).
*/
export type SurfacePattern = {
kind: "lines" | "boardBatten" | "runningBond" | "shingles" | "trapezoid" | "polygonal" | "grid";
direction?: "vertical" | "horizontal";
/** Hauptabstand (m): Linien-/Rippenabstand, Steinlänge, Plattenbreite. */
spacing: number;
/** Lagen-/Plattenhöhe (m; Läuferverband, Schindeln, Raster). Fehlt sie, gilt `spacing`. */
height?: number;
/** Breite (m) der Deckleiste bzw. des Trapez-Obergurts. */
width?: number;
/** Grunddrehung (Grad) zusätzlich zur Richtung. */
angle?: number;
/** Strichstärke (Papier-mm); Default 0.1. */
weightMm?: number;
/** Linienfarbe; Default Vordergrund des Bauteils bzw. Dunkelgrau. */
color?: string;
};
/** Schwenkrichtung der Tür relativ zur Wandachse. */
export type SwingSide = "left" | "right";
@@ -2879,6 +2930,16 @@ export type Wall = {
* Additiv; Alt-Projekte laden unverändert (Default = "both").
*/
sliceTermination?: SliceTermination;
/**
* Ansichtsschraffur ([100]): Drehung (Grad) des Oberflächenmusters dieses Elements gegenüber der
* Ausrichtung am Element (Default 0).
*/
surfacePatternAngle?: number;
/**
* Ansichtsschraffur ([100]): Versatz (m) des Musterursprungs (x entlang, y quer/aufwärts) gegenüber
* der Elementkante.
*/
surfacePatternOffset?: Vec2;
};
/**
+2
View File
@@ -53,6 +53,7 @@ import {
SectionLineSection,
DetailRefSection,
} from "./ObjectInfoPanel";
import { SurfacePatternPlacement } from "./SurfacePatternPlacement";
/** UI-Zustand des 3-Optionen-Quellen-Dropdowns (nicht 1:1 das Modell-Feld:
* „custom" ist abgeleitet aus „ist ein expliziter Wert gesetzt?", nicht
@@ -785,6 +786,7 @@ export function AttributesPanel() {
{sel.wall && <WallSection wall={sel.wall} host={host} />}
{sel.ceiling && <CeilingSection ceiling={sel.ceiling} host={host} />}
{sel.roof && <RoofSection roof={sel.roof} host={host} />}
{(sel.wall || sel.roof) && <SurfacePatternPlacement kind={sel.wall ? "wall" : "roof"} id={sel.id} host={host} />}
{sel.opening && <OpeningSection opening={sel.opening} host={host} />}
{sel.stair && <StairSection stair={sel.stair} host={host} />}
{sel.room && <RoomSection room={sel.room} roomId={sel.id} host={host} />}
+53
View File
@@ -0,0 +1,53 @@
// Ansichtsschraffur am Element ([100]): Drehung und Versatz des Oberflächenmusters je Wand bzw. Dach
// (das Muster selbst gehört zum Bauteil der sichtbaren Schicht). Nur sichtbar, wenn ein Bauteil des
// Elements ein Muster trägt.
import { t } from "../i18n";
import type { usePanelHost } from "./host";
export function SurfacePatternPlacement({
kind,
id,
host,
}: {
kind: "wall" | "roof";
id: string;
host: ReturnType<typeof usePanelHost>;
}) {
const p = host.project;
const el = kind === "wall" ? p.walls.find((w) => w.id === id) : p.roofs?.find((r) => r.id === id);
if (!el || !host.onSetSurfacePatternPlacement) return null;
const typeId = kind === "wall" ? (el as { wallTypeId?: string }).wallTypeId : (el as { roofTypeId?: string }).roofTypeId;
const types = kind === "wall" ? p.wallTypes : p.roofTypes ?? [];
const layers = types.find((tp) => tp.id === typeId)?.layers ?? [];
const hasPattern = layers.some((l) => p.components.find((c) => c.id === l.componentId)?.surfacePattern);
if (!hasPattern) return null;
const angle = el.surfacePatternAngle ?? 0;
const off = el.surfacePatternOffset ?? { x: 0, y: 0 };
const set = host.onSetSurfacePatternPlacement;
const field = (key: Parameters<typeof t>[0], value: number, step: number, apply: (v: number) => void) => (
<div className="objinfo-field">
<span className="objinfo-flabel">{t(key)}</span>
<input
type="number"
className="objinfo-text"
step={step}
value={Number(value.toFixed(3))}
title={t(key)}
onChange={(e) => {
const v = Number(e.target.value);
if (Number.isFinite(v)) apply(v);
}}
/>
</div>
);
return (
<>
<div className="objinfo-sep" />
<div className="objinfo-section-label">{t("objinfo.surfacePattern")}</div>
{field("objinfo.surfacePattern.angle", angle, 1, (v) => set({ surfacePatternAngle: v || undefined }))}
{field("objinfo.surfacePattern.offsetX", off.x, 0.01, (x) => set({ surfacePatternOffset: { x, y: off.y } }))}
{field("objinfo.surfacePattern.offsetY", off.y, 0.01, (y) => set({ surfacePatternOffset: { x: off.x, y } }))}
</>
);
}
+2
View File
@@ -394,6 +394,8 @@ export interface PanelHostValue {
* "both" = heutiges Verhalten, "below"/"above" = die Wand endet an der Decke.
*/
onSetWallSliceTermination: (termination: SliceTermination) => void;
/** Ansichtsschraffur ([100]) an der gewählten Wand bzw. am gewählten Dach drehen/versetzen. */
onSetSurfacePatternPlacement?: (patch: { surfacePatternAngle?: number; surfacePatternOffset?: { x: number; y: number } }) => void;
/** Weist der Wand einen Wandtyp-Preset (mehrschichtiger Aufbau) zu. */
onSetWallType: (wallTypeId: string) => void;
/** Setzt die Gesamtdicke einer einschichtigen Wand (Meter). */
+3 -1
View File
@@ -22,6 +22,8 @@ export interface ElevationOptions {
*/
visibleCodes?: Set<string>;
categoryDisplay?: CategoryDisplayResolver;
/** Massstabsnenner (1:N) für die Ausdünnung der Ansichtsschraffur ([100]); Default 100. */
scaleDenominator?: number;
}
/**
@@ -32,7 +34,7 @@ export function generateElevationPlan(project: Project, level: DrawingLevel, opt
if (!hasLine(level)) return null;
const shadows = opts.shadows ?? level.shadows ?? false;
const text = JSON.stringify({ level: levelArg(level), ...visibilityArgs(project, opts.visibleCodes, opts.categoryDisplay) });
const buf = decodePlanBuf(documentFor(project).queryBin("elevationPlan", [opts.mono ? 1 : 0, shadows ? 1 : 0], text));
const buf = decodePlanBuf(documentFor(project).queryBin("elevationPlan", [opts.mono ? 1 : 0, shadows ? 1 : 0, opts.scaleDenominator ?? 100], text));
if (buf.groups.length === 0) return null;
const b = buf.bounds ?? [0, 0, 1, 1];
return lazyPlan(
+4
View File
@@ -57,6 +57,7 @@ import {
PEN_FALLBACK_COLOR,
PEN_FALLBACK_WEIGHT,
} from "../model/penSets";
import { standardsMergeOps } from "../model/standards";
import { reorderByIds } from "../model/reorder";
import { transformMutation } from "../tools/transform";
import type { CopyMode, TransformOp, TransformSelection } from "../tools/transform";
@@ -182,6 +183,8 @@ export interface ProjectSlice {
patchPenSetWeight: (setId: string, penId: string, weight: number) => void;
/** Ersetzt `pens`/legt einen neuen Satz mit der 255er-CAD-Standardpalette an (s. `model/penSets.ts`). */
seedStandardPenSet: () => void;
/** Ergänzt die fehlenden SIA-400-Standards (Baustoffe, Schraffuren, Linientypen, Aufbauten; [100]–[102]). */
loadStandards: () => void;
// ── Benutzerdefinierte Farbpaletten (s. model/types.ts::CustomPalette) ────
addCustomPalette: () => void;
@@ -1022,6 +1025,7 @@ export function createProjectSlice(
}),
seedStandardPenSet: () => applyChange((p) => seedStandardPenSetOps(p)),
loadStandards: () => applyChange((p) => standardsMergeOps(p)),
addCustomPalette: () =>
applyChange(
+4
View File
@@ -787,6 +787,10 @@ export function usePanelHostBase(opts: {
if (selection?.kind === "wall")
updateWall(selection.id, { referenceOffset: offset ?? undefined });
},
onSetSurfacePatternPlacement: (patch) => {
if (selection?.kind === "wall") updateWall(selection.id, patch, "surface-pattern");
else if (selection?.kind === "roof") updateRoof(selection.id, patch, "surface-pattern");
},
onSetWallSliceTermination: (termination) => {
if (selection?.kind === "wall")
// "both" ist der Default ⇒ als undefined speichern (Alt-Projekt-Parität).
+2
View File
@@ -113,6 +113,7 @@ export function useProjectActions(
const patchPenSetColor = useStore((s) => s.patchPenSetColor);
const patchPenSetWeight = useStore((s) => s.patchPenSetWeight);
const seedStandardPenSet = useStore((s) => s.seedStandardPenSet);
const loadStandards = useStore((s) => s.loadStandards);
const addCustomPalette = useStore((s) => s.addCustomPalette);
const renameCustomPalette = useStore((s) => s.renameCustomPalette);
const deleteCustomPalette = useStore((s) => s.deleteCustomPalette);
@@ -423,6 +424,7 @@ export function useProjectActions(
patchPenSetColor,
patchPenSetWeight,
seedStandardPenSet,
loadStandards,
addCustomPalette,
renameCustomPalette,
deleteCustomPalette,
+6 -3
View File
@@ -39,6 +39,7 @@ import {
import type { LockInfo } from "../native/projectFile";
import { addRecentProject, removeRecentProject } from "./recentProjects";
import { emptyProject, sampleProject } from "../model/sampleProject";
import { withStandards } from "../model/standards";
import type { Project } from "../model/types";
import type { PlanViewHandle } from "../views/plan/PlanView";
@@ -366,8 +367,10 @@ export function useProjectFileActions(
// `guardDiscard`: bei ungespeicherten Änderungen erst der Dialog, s. o.
const onNewProject = () => guardDiscard(() => {
releaseCurrentProjectLock();
getState().loadProject(emptyProject);
lastSavedProjectRef.current = emptyProject;
// Neue Projekte bringen die SIA-400-Standards mit ([100]–[102]).
const next = withStandards(emptyProject);
getState().loadProject(next);
lastSavedProjectRef.current = next;
});
// Übernimmt ein neues, noch UNGESPEICHERTES Projekt aus Vorlagen-Inhalt
@@ -390,7 +393,7 @@ export function useProjectFileActions(
// Startzustand, s. state/projectSlice.ts).
const onNewProjectFromSample = () => guardDiscard(() => {
releaseCurrentProjectLock();
const next = structuredClone(sampleProject);
const next = withStandards(structuredClone(sampleProject));
getState().loadProject(next);
lastSavedProjectRef.current = next;
});
+12
View File
@@ -151,6 +151,8 @@ export interface ResourceManagerHandlers {
onPatchPenSetWeight?: (setId: string, penId: string, weight: number) => void;
/** Ersetzt `pens`/legt einen neuen Satz mit der 255er-CAD-Standardpalette an. */
onSeedStandardPenSet?: () => void;
/** Ergänzt die fehlenden SIA-400-Standards ([100]–[102], „Standards laden"). */
onLoadStandards?: () => void;
/**
* Farbpaletten (Tab „Paletten"): eigene Paletten verwalten + Sichtbarkeit
* der Bänke im Farbwahl-Popover. Optional wie die Stift-Handler.
@@ -318,6 +320,16 @@ export function ResourceManager({
</span>
{t("resources.title")}
</div>
{handlers.onLoadStandards && (
<button
className="res-add res-load-standards"
title={t("resources.loadStandards.hint")}
onPointerDown={(e) => e.stopPropagation()}
onClick={() => handlers.onLoadStandards?.()}
>
{t("resources.loadStandards")}
</button>
)}
{!windowed && (
<button
className="res-close"
@@ -0,0 +1,88 @@
// Bauteil-Kennwerte und Ansichtsschraffur ([100]–[101]): λ, Rohdichte, VKF-Brandverhalten, Ansichtsfarbe und
// das Oberflächenmuster (Art, Richtung, Masse). Teil des Bauteil-Details im Ressourcen-Manager.
import type { Component, SurfacePattern } from "../../model/types";
import { t } from "../../i18n";
import { ColorField, FieldRow, NumberField, SelectField } from "./fields";
type Kind = SurfacePattern["kind"];
const KINDS: Kind[] = ["lines", "boardBatten", "runningBond", "shingles", "trapezoid", "polygonal", "grid"];
const FIRE = ["", "RF1", "RF2", "RF3", "RF4"];
/** Vorgaben je Musterart (Meter), damit ein neu gewähltes Muster sofort sinnvoll aussieht. */
const DEFAULTS: Record<Kind, Omit<SurfacePattern, "kind">> = {
lines: { spacing: 0.08 },
boardBatten: { spacing: 0.2, width: 0.06 },
runningBond: { spacing: 0.26, height: 0.075 },
shingles: { spacing: 0.1, height: 0.12 },
trapezoid: { spacing: 0.2, width: 0.06 },
polygonal: { spacing: 0.45, height: 0.35 },
grid: { spacing: 1.25, height: 0.625 },
};
const posOrUndef = (v: number) => (Number.isFinite(v) && v > 0 ? v : undefined);
export function ComponentStandardFields({
component,
onPatch,
}: {
component: Component;
onPatch: (patch: Partial<Component>) => void;
}) {
const sp = component.surfacePattern;
const patchPattern = (p: Partial<SurfacePattern>) => sp && onPatch({ surfacePattern: { ...sp, ...p } });
return (
<>
<FieldRow label={t("resources.col.lambda")}>
<NumberField value={component.lambda ?? 0} step={0.001} min={0} onChange={(v) => onPatch({ lambda: posOrUndef(v) })} />
</FieldRow>
<FieldRow label={t("resources.col.density")}>
<NumberField value={component.density ?? 0} step={10} min={0} onChange={(v) => onPatch({ density: posOrUndef(v) })} />
</FieldRow>
<FieldRow label={t("resources.col.fireClass")}>
<SelectField
value={component.fireClass ?? ""}
onChange={(v) => onPatch({ fireClass: v || undefined })}
options={FIRE.map((f) => ({ value: f, label: f || t("resources.col.fireClass.none") }))}
/>
</FieldRow>
<FieldRow label={t("resources.col.elevationColor")}>
<ColorField color={component.elevationColor ?? component.color} onChange={(elevationColor) => onPatch({ elevationColor })} />
</FieldRow>
<FieldRow label={t("resources.col.surfacePattern")} hint={t("resources.col.surfacePattern.hint")}>
<SelectField
value={sp?.kind ?? ""}
onChange={(k) => onPatch({ surfacePattern: k ? { ...DEFAULTS[k as Kind], kind: k as Kind } : undefined })}
options={[
{ value: "", label: t("resources.surfacePattern.none") },
...KINDS.map((k) => ({ value: k, label: t(`resources.surfacePattern.${k}`) })),
]}
/>
</FieldRow>
{sp && (
<>
<FieldRow label={t("resources.surfacePattern.direction")}>
<SelectField
value={sp.direction ?? ""}
onChange={(d) => patchPattern({ direction: (d || undefined) as SurfacePattern["direction"] })}
options={[
{ value: "", label: t("resources.surfacePattern.direction.auto") },
{ value: "vertical", label: t("resources.surfacePattern.direction.vertical") },
{ value: "horizontal", label: t("resources.surfacePattern.direction.horizontal") },
]}
/>
</FieldRow>
<FieldRow label={t("resources.surfacePattern.spacing")}>
<NumberField value={sp.spacing} step={0.01} min={0.005} onChange={(v) => v > 0 && patchPattern({ spacing: v })} />
</FieldRow>
<FieldRow label={t("resources.surfacePattern.height")}>
<NumberField value={sp.height ?? sp.spacing} step={0.005} min={0} onChange={(v) => patchPattern({ height: posOrUndef(v) })} />
</FieldRow>
<FieldRow label={t("resources.surfacePattern.width")}>
<NumberField value={sp.width ?? 0} step={0.005} min={0} onChange={(v) => patchPattern({ width: posOrUndef(v) })} />
</FieldRow>
</>
)}
</>
);
}
+22
View File
@@ -21,6 +21,7 @@ import { HatchSwatch } from "../hatchPreview";
import { t } from "../../i18n";
import { activePenSet, resolvePenColor } from "../../model/penSets";
import { PenColorField } from "../PenColorField";
import { ComponentStandardFields } from "./ComponentStandardFields";
import {
DeleteButton,
FieldRow,
@@ -45,6 +46,7 @@ function MaterialCell({
onClear: () => void;
}) {
const [open, setOpen] = useState(false);
const [fetching, setFetching] = useState(false);
const label = materialLabel(material);
return (
<>
@@ -61,6 +63,24 @@ function MaterialCell({
)}
<span className="res-material-name">{label}</span>
</button>
{material?.libraryId && !material.color && (
// Standard-Bauteil mit ambientCG-Kennung ohne gebündelte Karten ([100]): bei Bedarf laden.
<button
className="res-add"
disabled={fetching}
title={t("material.fetchAmbient.hint")}
onClick={() => {
const id = material.libraryId!;
setFetching(true);
fetchMaterialMaps(id, "1K", material.sizeM ?? DEFAULT_TILE_SIZE_M)
.then(({ material: m }) => onAssign(m))
.catch((e) => console.error("[ambientcg] download failed:", e))
.finally(() => setFetching(false));
}}
>
{t("material.fetchAmbient")}
</button>
)}
{open && (
<MaterialPicker
material={material}
@@ -87,6 +107,7 @@ function materialLabel(m: ComponentMaterial | undefined): string {
if (m.libraryId) {
const asset = MATERIAL_LIBRARY.find((a) => a.id === m.libraryId);
if (asset) return asset.name;
if (!m.color) return `ambientCG ${m.libraryId}`;
}
return t("material.uploaded");
}
@@ -739,6 +760,7 @@ function ComponentDetail({
onClear={() => onPatch({ material: undefined })}
/>
</FieldRow>
<ComponentStandardFields component={component} onPatch={onPatch} />
</div>
</div>
);
+3 -3
View File
@@ -665,7 +665,7 @@ function useCrossKindOverlay(
let prims: Primitive[];
if (l.kind === "elevation") {
prims =
generateElevationPlan(project, l, { mono, visibleCodes, categoryDisplay })?.primitives ?? [];
generateElevationPlan(project, l, { mono, visibleCodes, categoryDisplay, scaleDenominator })?.primitives ?? [];
} else if (l.kind === "section") {
const sOut = sectionOutputs[l.id];
prims = sOut
@@ -1142,9 +1142,9 @@ function SectionPlanView({
const elevationPlan = useMemo(
() =>
isElevation
? generateElevationPlan(inputs.project, inputs.level, { mono, visibleCodes, categoryDisplay })
? generateElevationPlan(inputs.project, inputs.level, { mono, visibleCodes, categoryDisplay, scaleDenominator })
: null,
[isElevation, inputs, mono, visibleCodes, categoryDisplay],
[isElevation, inputs, mono, visibleCodes, categoryDisplay, scaleDenominator],
);
const sectionPlan = useMemo(