[K4] Parametrische Wände im Kern: Regeln, Duplikate, Bedingungen (parametric_walls.rs)
model/parametricWalls.ts ist Fassade (Zähler der Wand-ids bleibt dort); TS-Rechnung gelöscht.
This commit is contained in:
6 files changed
+545
-455
No files matched your search
@@ -417,7 +417,7 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern
|
||||
(`insertAfterCode`) ging in TS verloren (die Ebene mit dem Ziel wurde übersprungen), jetzt steht es hinter dem Original.
|
||||
Offen: vertikale Ausdehnungen (`model/wall.ts`: `wallVerticalExtent` …, Kern hat `model/helpers.rs` schon — Aufrufer in
|
||||
`toSection`/`voids`/`geometry/opening`/Viewport fallen mit dem Plan-Port bzw. brauchen eine Abfrage je Bauteil),
|
||||
Parametrik-Regeln (`parametricWalls.ts`); Undo-Verlauf als Liste in der UI [84].
|
||||
Undo-Verlauf als Liste in der UI [84].
|
||||
**Stiftsätze im Kern (29.10.):** `pens.rs` (Standardpalette mit 255 Stiften, Freie-Farbe-Palette, `hsl_to_hex`, Neu-Backen
|
||||
der Stift-Farben/-Strichstärken `rebake_ops`, Standardsatz anlegen `seed_standard_ops`, Stift löschen samt Verweisen in
|
||||
Bauteilen und im Kategorien-Baum `delete_pen_ops`). Rechnung auf der rohen Projekt-Wurzel (`serde_json`, verlustfrei) und
|
||||
@@ -443,6 +443,15 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern
|
||||
Eltern) für alle drei Bäume, 6000 Ordner-Blätter, 8000 Löschen/Nachfahren/Verschieben (je Layout, Master, Ausschnitt),
|
||||
3000 Blattgrössen, 6000 Titelblöcke (Unicode-Leerraum, Massstäbe 0/1e21/1e-7, doppelte Layout-ids), 4000 Ordner-PDF-Seiten.
|
||||
Abweichung (gewollt): kaputte `parentId`-Ketten (Kreis, Selbstverweis) in `collectFolderLayouts` enden jetzt (TS: Stapelüberlauf).
|
||||
**Parametrische Wände im Kern (29.10.):** `parametric_walls.rs` (Raster-, Modul-, bedingte-Dicke-, Referenzlinien- und
|
||||
Sequenz-Regel, Duplikat-Entfernung, `exterior`/`interior`/`bearing`) auf `serde_json::Value` (vorhandene Wände behalten
|
||||
unbekannte Felder), `Math.round/min/max/atan2` über `jsnum`; zustandslose Bindung `parametric_call`
|
||||
(`web/parametric_walls.rs`), `model/parametricWalls.ts` ist Fassade mit gleichen Signaturen und hält nur den Zähler der
|
||||
Wand-ids. Die App ruft die Engine noch nirgends auf (nur Tests): die Regel-UI fehlt weiterhin. Gleichheit (einmalig, Test
|
||||
gelöscht): 3000 Zufallsregelwerke (verschachtelte Sequenzen, Raster mit/ohne gridId, Grenzpolygone mit 1–5 Punkten, Referenzwand
|
||||
vorhanden/fehlend, fehlende/negative/0-Abstände, Toleranz 0/0,01/0,5) und 4000 Einzel-Regeln/Bedingungen/Duplikat-Listen,
|
||||
Wand-ids samt Zähler gleich, Ergebnis zeichengleich bis auf die Schlüsselreihenfolge von Wänden mit `wallTypeId: undefined`.
|
||||
Abweichung (gewollt): Achsen je Aufruf auf 1 000 000 begrenzt (TS rechnete bei absurd kleinem Abstand endlos).
|
||||
- ◐ **S4 Typen aus Rust**: `types.ts` wird aus den Rust-Strukturen erzeugt (ts-rs); Datei-I/O (`projectFormat`, Migration, IFC/DXF/
|
||||
STEP-Ex- und -Import) im Kern.
|
||||
**Typen (28.10.):** Das Rust-Modell (`core/src/model/generated.rs`, `manual.rs`) ist die Quelle; ts-rs 12 (MIT, nur
|
||||
|
||||
@@ -77,6 +77,7 @@ pub mod levels;
|
||||
pub mod pens;
|
||||
pub mod folder_tree;
|
||||
pub mod layout_model;
|
||||
pub mod parametric_walls;
|
||||
|
||||
#[cfg(feature = "web")]
|
||||
mod web;
|
||||
@@ -0,0 +1,425 @@
|
||||
//! Parametrische Wand-Engine ([K4] S3, vorher `src/model/parametricWalls.ts`): löst `ParametricWall`-Regelwerke
|
||||
//! (Raster, Modul, bedingte Dicke, Referenzlinie, Sequenz) zu Wänden auf. Rechnung auf `serde_json::Value`
|
||||
//! (die bestehenden Wände behalten ihre unbekannten Felder), Zahlen wie in JS (`Math.round/min/max/atan2`
|
||||
//! über `jsnum`). Die laufende Nummer der erzeugten Wand-ids (`pw-<Geschoss>-<Art>-<n>`) ist Zustand der
|
||||
//! TS-Fassade: sie reicht den Zähler hinein und bekommt den neuen zurück.
|
||||
//!
|
||||
//! Abweichung zur TS-Fassung: Achspositionen sind auf 1 000 000 je Aufruf begrenzt (TS rechnete bei
|
||||
//! absurd kleinem Abstand praktisch endlos bzw. bis zum Speicherende).
|
||||
|
||||
use crate::jsnum;
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
const MAX_AXES: usize = 1_000_000;
|
||||
|
||||
/// Arbeitskontext (`RuleCtx`): Geschoss-id, Standard-Wandtyp, Kontext (Geschoss, Rasterachsen, Grenze) und
|
||||
/// die bisher erzeugten bzw. vorhandenen Wände.
|
||||
pub struct Ctx<'a> {
|
||||
pub floor_id: &'a Value,
|
||||
pub default_wall_type: &'a Value,
|
||||
pub context: &'a Value,
|
||||
pub existing: Vec<Value>,
|
||||
}
|
||||
|
||||
fn num(v: Option<&Value>) -> Option<f64> {
|
||||
v.and_then(Value::as_f64)
|
||||
}
|
||||
|
||||
fn present<'a>(v: Option<&'a Value>) -> Option<&'a Value> {
|
||||
v.filter(|v| !v.is_null())
|
||||
}
|
||||
|
||||
/// `${x}` für ids: Text, sonst `undefined` wie in JS.
|
||||
fn floor_text(v: &Value) -> String {
|
||||
match v {
|
||||
Value::String(s) => s.clone(),
|
||||
Value::Null => "undefined".into(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Zähler für Wand-ids (`makeWallId`): erhöht und liefert `pw-<prefix>-<n>`.
|
||||
fn make_wall_id(counter: &mut u64, prefix: &str) -> String {
|
||||
*counter += 1;
|
||||
format!("pw-{prefix}-{counter}")
|
||||
}
|
||||
|
||||
fn point(v: Option<&Value>) -> (f64, f64) {
|
||||
(num(v.and_then(|p| p.get("x"))).unwrap_or(f64::NAN), num(v.and_then(|p| p.get("y"))).unwrap_or(f64::NAN))
|
||||
}
|
||||
|
||||
fn dist2(a: (f64, f64), b: (f64, f64)) -> f64 {
|
||||
let dx = a.0 - b.0;
|
||||
let dy = a.1 - b.1;
|
||||
(dx * dx + dy * dy).sqrt()
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Bounds {
|
||||
min_x: f64,
|
||||
max_x: f64,
|
||||
min_y: f64,
|
||||
max_y: f64,
|
||||
}
|
||||
|
||||
/// Bounding-Box des Kontexts (`computeBounds`): Grenzpolygon oder Standardbereich `0 … spacing × 10`.
|
||||
fn compute_bounds(context: &Value, spacing: f64) -> Bounds {
|
||||
if let Some(pts) = context.get("boundaryGeometry").and_then(|b| b.get("boundary")).and_then(Value::as_array) {
|
||||
if pts.len() >= 2 {
|
||||
let mut b = Bounds { min_x: f64::INFINITY, max_x: f64::NEG_INFINITY, min_y: f64::INFINITY, max_y: f64::NEG_INFINITY };
|
||||
for p in pts {
|
||||
let (x, y) = point(Some(p));
|
||||
if x < b.min_x {
|
||||
b.min_x = x;
|
||||
}
|
||||
if x > b.max_x {
|
||||
b.max_x = x;
|
||||
}
|
||||
if y < b.min_y {
|
||||
b.min_y = y;
|
||||
}
|
||||
if y > b.max_y {
|
||||
b.max_y = y;
|
||||
}
|
||||
}
|
||||
return b;
|
||||
}
|
||||
}
|
||||
let extent = spacing * 10.0;
|
||||
Bounds { min_x: 0.0, max_x: extent, min_y: 0.0, max_y: extent }
|
||||
}
|
||||
|
||||
/// Gleichmässige Achspositionen in `[min, max]` (`generateAxisPositions`).
|
||||
fn axis_positions(min: f64, max: f64, spacing: f64) -> Vec<f64> {
|
||||
// `!(max > min)` fängt auch NaN ab (TS: die Schleife lief dann nicht)
|
||||
if spacing <= 0.0 || max <= min || spacing.is_nan() || min.is_nan() || max.is_nan() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut pos = min;
|
||||
while pos <= max + 1e-6 && out.len() < MAX_AXES {
|
||||
out.push(jsnum::round(pos * 1e6) / 1e6);
|
||||
pos += spacing;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Wand „aussen" = beide Endpunkte am Rand der Bounding-Box (`isExteriorWall`).
|
||||
fn is_exterior(wall: &Value, ctx: &Ctx) -> bool {
|
||||
let b = compute_bounds(ctx.context, 1.0);
|
||||
let tol = 0.1;
|
||||
let on_edge = |p: (f64, f64)| (p.0 - b.min_x).abs() <= tol || (p.0 - b.max_x).abs() <= tol || (p.1 - b.min_y).abs() <= tol || (p.1 - b.max_y).abs() <= tol;
|
||||
on_edge(point(wall.get("start"))) && on_edge(point(wall.get("end")))
|
||||
}
|
||||
|
||||
/// Erfüllt die Wand die Bedingung einer Regel „bedingte Dicke" (`matchesCondition`)?
|
||||
pub fn matches_condition(wall: &Value, condition: &str, ctx: &Ctx) -> bool {
|
||||
match condition {
|
||||
"exterior" => is_exterior(wall, ctx),
|
||||
"interior" => !is_exterior(wall, ctx),
|
||||
"bearing" => {
|
||||
let (s, e) = (point(wall.get("start")), point(wall.get("end")));
|
||||
let dx = (e.0 - s.0).abs();
|
||||
let dy = (e.1 - s.1).abs();
|
||||
let len = (dx * dx + dy * dy).sqrt();
|
||||
if len < 1e-6 {
|
||||
return false;
|
||||
}
|
||||
let angle = jsnum::atan2(dy, dx);
|
||||
let ten = (10.0 * std::f64::consts::PI) / 180.0;
|
||||
angle <= ten || angle >= std::f64::consts::PI / 2.0 - ten
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Entspricht die Wand dem Ziel einer Referenzlinien-Regel (`matchesTarget`)?
|
||||
pub fn matches_target(wall: &Value, target: &str, ctx: &Ctx) -> bool {
|
||||
match target {
|
||||
"all" => true,
|
||||
"exterior" => is_exterior(wall, ctx),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Neue Wand `{id, type, floorId, categoryCode, start, end, wallTypeId, height, referenceLine?}`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn new_wall(id: String, floor_id: &Value, start: (f64, f64), end: (f64, f64), wall_type_id: Option<&Value>, height: f64, reference_line: Option<&Value>) -> Value {
|
||||
let mut m = Map::new();
|
||||
m.insert("id".into(), Value::String(id));
|
||||
m.insert("type".into(), json!("wall"));
|
||||
m.insert("floorId".into(), floor_id.clone());
|
||||
m.insert("categoryCode".into(), json!("20"));
|
||||
m.insert("start".into(), json!({"x": start.0, "y": start.1}));
|
||||
m.insert("end".into(), json!({"x": end.0, "y": end.1}));
|
||||
if let Some(w) = wall_type_id {
|
||||
m.insert("wallTypeId".into(), w.clone());
|
||||
}
|
||||
m.insert("height".into(), json!(height));
|
||||
if let Some(r) = reference_line {
|
||||
m.insert("referenceLine".into(), r.clone());
|
||||
}
|
||||
Value::Object(m)
|
||||
}
|
||||
|
||||
/// Wandtyp-id der Regel oder des Standard-Wandtyps (`rule.wallTypeId ?? defaultWallType.id`).
|
||||
fn wall_type_id<'a>(rule: &'a Value, ctx: &'a Ctx) -> Option<&'a Value> {
|
||||
present(rule.get("wallTypeId")).or_else(|| present(ctx.default_wall_type.get("id")))
|
||||
}
|
||||
|
||||
/// Höhe der Regel oder des Geschosses (`rule.height ?? floor.floorHeight ?? 2.6`).
|
||||
fn rule_height(rule: &Value, ctx: &Ctx) -> f64 {
|
||||
num(present(rule.get("height"))).or_else(|| num(present(ctx.context.get("floor").and_then(|f| f.get("floorHeight"))))).unwrap_or(2.6)
|
||||
}
|
||||
|
||||
/// Raster-Regel: Wände entlang gleichmässiger X-/Y-Achsen (`applyGridRule`).
|
||||
fn apply_grid(rule: &Value, ctx: &Ctx, counter: &mut u64) -> Vec<Value> {
|
||||
let spacing = num(present(rule.get("spacing"))).unwrap_or(3.0);
|
||||
let type_id = wall_type_id(rule, ctx);
|
||||
let reference = present(rule.get("referenceLine"));
|
||||
let height = rule_height(rule, ctx);
|
||||
let floor = floor_text(ctx.floor_id);
|
||||
let b = compute_bounds(ctx.context, spacing);
|
||||
let dirs = rule.get("directions").and_then(Value::as_str);
|
||||
let grid_axes = present(ctx.context.get("gridAxes"));
|
||||
let use_grid = present(rule.get("gridId")).is_some() && grid_axes.is_some();
|
||||
let axes_of = |key: &str| -> Vec<f64> { grid_axes.and_then(|g| g.get(key)).and_then(Value::as_array).map(|a| a.iter().map(|v| num(Some(v)).unwrap_or(f64::NAN)).collect()).unwrap_or_default() };
|
||||
let mut walls = Vec::new();
|
||||
if dirs == Some("x") || dirs == Some("both") {
|
||||
let axes = if use_grid { axes_of("x") } else { axis_positions(b.min_x, b.max_x, spacing) };
|
||||
for ax in axes {
|
||||
let id = make_wall_id(counter, &format!("{floor}-gx"));
|
||||
walls.push(new_wall(id, ctx.floor_id, (ax, b.min_y), (ax, b.max_y), type_id, height, reference));
|
||||
}
|
||||
}
|
||||
if dirs == Some("y") || dirs == Some("both") {
|
||||
let axes = if use_grid { axes_of("y") } else { axis_positions(b.min_y, b.max_y, spacing) };
|
||||
for ay in axes {
|
||||
let id = make_wall_id(counter, &format!("{floor}-gy"));
|
||||
walls.push(new_wall(id, ctx.floor_id, (b.min_x, ay), (b.max_x, ay), type_id, height, reference));
|
||||
}
|
||||
}
|
||||
walls
|
||||
}
|
||||
|
||||
/// Modul-Regel: Querwände an den Teilungspunkten einer Referenzspanne (`applyModuleRule`).
|
||||
fn apply_module(rule: &Value, ctx: &Ctx, counter: &mut u64) -> Vec<Value> {
|
||||
let type_id = wall_type_id(rule, ctx);
|
||||
let reference = present(rule.get("referenceLine"));
|
||||
let height = rule_height(rule, ctx);
|
||||
let floor = floor_text(ctx.floor_id);
|
||||
let module_size = num(rule.get("moduleSize")).unwrap_or(f64::NAN);
|
||||
let b = compute_bounds(ctx.context, module_size);
|
||||
let dir_x = rule.get("direction").and_then(Value::as_str) == Some("x");
|
||||
let bbox = if dir_x { (b.min_x, b.max_x, b.min_y, b.max_y) } else { (b.min_y, b.max_y, b.min_x, b.max_x) };
|
||||
let ref_wall = present(rule.get("referenceWallId")).and_then(|id| ctx.existing.iter().find(|w| w.get("id") == Some(id)));
|
||||
let (span_start, span_end, perp_start, perp_end) = match ref_wall {
|
||||
Some(w) => {
|
||||
let (s, e) = (point(w.get("start")), point(w.get("end")));
|
||||
if dir_x {
|
||||
(jsnum::min(s.0, e.0), jsnum::max(s.0, e.0), b.min_y, b.max_y)
|
||||
} else {
|
||||
(jsnum::min(s.1, e.1), jsnum::max(s.1, e.1), b.min_x, b.max_x)
|
||||
}
|
||||
}
|
||||
None => bbox,
|
||||
};
|
||||
let dividers: Vec<f64> = axis_positions(span_start, span_end, module_size).into_iter().filter(|p| *p > span_start + 1e-6 && *p < span_end - 1e-6).collect();
|
||||
dividers
|
||||
.into_iter()
|
||||
.map(|pos| {
|
||||
if dir_x {
|
||||
let id = make_wall_id(counter, &format!("{floor}-mx"));
|
||||
new_wall(id, ctx.floor_id, (pos, perp_start), (pos, perp_end), type_id, height, reference)
|
||||
} else {
|
||||
let id = make_wall_id(counter, &format!("{floor}-my"));
|
||||
new_wall(id, ctx.floor_id, (perp_start, pos), (perp_end, pos), type_id, height, reference)
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Kopie von `w` mit gesetzten Feldern (`{...w, id, key: v}`).
|
||||
fn copy_with(w: &Value, fields: &[(&str, Value)]) -> Value {
|
||||
let mut m = w.as_object().cloned().unwrap_or_default();
|
||||
for (k, v) in fields {
|
||||
m.insert((*k).to_string(), v.clone());
|
||||
}
|
||||
Value::Object(m)
|
||||
}
|
||||
|
||||
fn text(v: Option<&Value>) -> &str {
|
||||
v.and_then(Value::as_str).unwrap_or("")
|
||||
}
|
||||
|
||||
/// Führt eine Regel aus (`applyRule`); unbekannter Typ → leer.
|
||||
pub fn apply_rule(rule: &Value, ctx: &Ctx, counter: &mut u64) -> Vec<Value> {
|
||||
match rule.get("type").and_then(Value::as_str) {
|
||||
Some("grid") => apply_grid(rule, ctx, counter),
|
||||
Some("module") => apply_module(rule, ctx, counter),
|
||||
Some("conditional-thickness") => {
|
||||
let floor = floor_text(ctx.floor_id);
|
||||
let cond = text(rule.get("condition"));
|
||||
ctx.existing
|
||||
.iter()
|
||||
.filter(|w| matches_condition(w, cond, ctx))
|
||||
.map(|w| {
|
||||
let id = make_wall_id(counter, &format!("{floor}-ct"));
|
||||
let mut fields = vec![("id", Value::String(id))];
|
||||
if let Some(t) = rule.get("wallTypeId") {
|
||||
fields.push(("wallTypeId", t.clone()));
|
||||
} else {
|
||||
fields.push(("wallTypeId", Value::Null));
|
||||
}
|
||||
let mut out = copy_with(w, &fields);
|
||||
// `wallTypeId: undefined` entfernt das Feld (JSON), ein Wert bleibt
|
||||
if rule.get("wallTypeId").is_none() {
|
||||
out.as_object_mut().map(|m| m.shift_remove("wallTypeId"));
|
||||
}
|
||||
out
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
Some("reference-line") => {
|
||||
let floor = floor_text(ctx.floor_id);
|
||||
let target = text(rule.get("target"));
|
||||
ctx.existing
|
||||
.iter()
|
||||
.filter(|w| matches_target(w, target, ctx))
|
||||
.map(|w| {
|
||||
let id = make_wall_id(counter, &format!("{floor}-rl"));
|
||||
let mut fields = vec![("id", Value::String(id))];
|
||||
if let Some(r) = rule.get("referenceLine") {
|
||||
fields.push(("referenceLine", r.clone()));
|
||||
}
|
||||
let mut out = copy_with(w, &fields);
|
||||
if rule.get("referenceLine").is_none() {
|
||||
out.as_object_mut().map(|m| m.shift_remove("referenceLine"));
|
||||
}
|
||||
out
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
Some("sequence") => {
|
||||
let mut result: Vec<Value> = Vec::new();
|
||||
for sub in rule.get("rules").and_then(Value::as_array).map_or(&[][..], Vec::as_slice) {
|
||||
let sub_ctx = Ctx { floor_id: ctx.floor_id, default_wall_type: ctx.default_wall_type, context: ctx.context, existing: ctx.existing.iter().chain(result.iter()).cloned().collect() };
|
||||
let walls = apply_rule(sub, &sub_ctx, counter);
|
||||
let produced = !walls.is_empty();
|
||||
result.extend(walls);
|
||||
if rule.get("stopOnMatch") == Some(&Value::Bool(true)) && produced {
|
||||
break;
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Entfernt doppelte Wände (gleicher Start/Ende innerhalb `tolerance`, auch umgekehrt); die erste bleibt.
|
||||
pub fn deduplicate(walls: Vec<Value>, tolerance: f64) -> Vec<Value> {
|
||||
let mut unique: Vec<Value> = Vec::new();
|
||||
for c in walls {
|
||||
let (cs, ce) = (point(c.get("start")), point(c.get("end")));
|
||||
let dup = unique.iter().any(|u| {
|
||||
let (us, ue) = (point(u.get("start")), point(u.get("end")));
|
||||
let fwd = dist2(cs, us) <= tolerance && dist2(ce, ue) <= tolerance;
|
||||
let rev = dist2(cs, ue) <= tolerance && dist2(ce, us) <= tolerance;
|
||||
fwd || rev
|
||||
});
|
||||
if !dup {
|
||||
unique.push(c);
|
||||
}
|
||||
}
|
||||
unique
|
||||
}
|
||||
|
||||
/// Löst ein Regelwerk zu Wänden für ein Geschoss auf (`resolveParametricWall`): jede Regel sieht die
|
||||
/// vorhandenen und die bisher erzeugten Wände, danach werden Duplikate entfernt.
|
||||
pub fn resolve(parametric_wall: &Value, ctx: &Ctx, tolerance: f64, counter: &mut u64) -> Vec<Value> {
|
||||
let mut generated: Vec<Value> = Vec::new();
|
||||
for rule in parametric_wall.get("rules").and_then(Value::as_array).map_or(&[][..], Vec::as_slice) {
|
||||
let rc = Ctx { floor_id: ctx.floor_id, default_wall_type: ctx.default_wall_type, context: ctx.context, existing: ctx.existing.iter().chain(generated.iter()).cloned().collect() };
|
||||
let walls = apply_rule(rule, &rc, counter);
|
||||
generated.extend(walls);
|
||||
}
|
||||
deduplicate(generated, tolerance)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn ctx_of<'a>(floor_id: &'a Value, wt: &'a Value, context: &'a Value, existing: Vec<Value>) -> Ctx<'a> {
|
||||
Ctx { floor_id, default_wall_type: wt, context, existing }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raster_in_beide_richtungen() {
|
||||
let (f, wt, cx) = (json!("f1"), json!({"id": "wt0"}), json!({"floor": {"floorHeight": 3.0}}));
|
||||
let mut n = 0;
|
||||
let w = apply_rule(&json!({"type": "grid", "spacing": 3, "directions": "both"}), &ctx_of(&f, &wt, &cx, vec![]), &mut n);
|
||||
assert_eq!(w.len(), 22); // 0..30 je Richtung (11 Achsen)
|
||||
assert_eq!(n, 22);
|
||||
assert_eq!(w[0]["id"], "pw-f1-gx-1");
|
||||
assert_eq!(w[0]["start"], json!({"x": 0.0, "y": 0.0}));
|
||||
assert_eq!(w[0]["end"], json!({"x": 0.0, "y": 30.0}));
|
||||
assert_eq!(w[0]["wallTypeId"], "wt0");
|
||||
assert_eq!(w[0]["height"], 3.0);
|
||||
assert_eq!(w[11]["id"], "pw-f1-gy-12");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modul_mit_referenzwand_und_begrenzung() {
|
||||
let (f, wt) = (json!("f"), json!({"id": "w"}));
|
||||
let cx = json!({"floor": {}, "boundaryGeometry": {"boundary": [{"x": 0, "y": 0}, {"x": 10, "y": 6}]}});
|
||||
let ref_wall = json!({"id": "r", "start": {"x": 2, "y": 0}, "end": {"x": 8, "y": 0}});
|
||||
let mut n = 0;
|
||||
let rule = json!({"type": "module", "direction": "x", "moduleSize": 2, "referenceWallId": "r", "referenceLine": "center"});
|
||||
let w = apply_rule(&rule, &ctx_of(&f, &wt, &cx, vec![ref_wall]), &mut n);
|
||||
let xs: Vec<f64> = w.iter().map(|w| w["start"]["x"].as_f64().unwrap()).collect();
|
||||
assert_eq!(xs, vec![4.0, 6.0]); // 2 und 8 sind Spannenenden
|
||||
assert_eq!(w[0]["start"]["y"], 0.0);
|
||||
assert_eq!(w[0]["end"]["y"], 6.0);
|
||||
assert_eq!(w[0]["referenceLine"], "center");
|
||||
assert_eq!(w[0]["height"], 2.6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bedingte_dicke_und_referenzlinie_kopieren() {
|
||||
let (f, wt, cx) = (json!("f"), json!({"id": "w"}), json!({"floor": {}, "boundaryGeometry": {"boundary": [{"x": 0, "y": 0}, {"x": 10, "y": 10}]}}));
|
||||
let outer = json!({"id": "a", "start": {"x": 0, "y": 0}, "end": {"x": 10, "y": 0}, "extra": 1});
|
||||
let inner = json!({"id": "b", "start": {"x": 5, "y": 3}, "end": {"x": 5, "y": 7}});
|
||||
let mut n = 10;
|
||||
let c = ctx_of(&f, &wt, &cx, vec![outer.clone(), inner.clone()]);
|
||||
let ct = apply_rule(&json!({"type": "conditional-thickness", "condition": "exterior", "wallTypeId": "dick"}), &c, &mut n);
|
||||
assert_eq!(ct.len(), 1);
|
||||
assert_eq!(ct[0]["id"], "pw-f-ct-11");
|
||||
assert_eq!(ct[0]["wallTypeId"], "dick");
|
||||
assert_eq!(ct[0]["extra"], 1);
|
||||
let rl = apply_rule(&json!({"type": "reference-line", "target": "all", "referenceLine": "left"}), &c, &mut n);
|
||||
assert_eq!(rl.len(), 2);
|
||||
assert_eq!(rl[1]["referenceLine"], "left");
|
||||
assert!(apply_rule(&json!({"type": "reference-line", "target": "tag"}), &c, &mut n).is_empty());
|
||||
assert!(matches_condition(&inner, "interior", &c));
|
||||
assert!(matches_condition(&inner, "bearing", &c));
|
||||
assert!(!matches_condition(&json!({"start": {"x": 0, "y": 0}, "end": {"x": 5, "y": 5}}), "bearing", &c));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequenz_und_duplikate() {
|
||||
let (f, wt, cx) = (json!("f"), json!({"id": "w"}), json!({"floor": {}}));
|
||||
let mut n = 0;
|
||||
let seq = json!({"type": "sequence", "stopOnMatch": true, "rules": [
|
||||
{"type": "conditional-thickness", "condition": "exterior", "wallTypeId": "x"},
|
||||
{"type": "grid", "spacing": 5, "directions": "x"},
|
||||
{"type": "grid", "spacing": 5, "directions": "y"},
|
||||
]});
|
||||
let w = apply_rule(&seq, &ctx_of(&f, &wt, &cx, vec![]), &mut n);
|
||||
// Die erste Regel findet keine Wand; die x-Regel liefert 0, 5 … 50 (11 Achsen) und stoppt die Sequenz.
|
||||
assert_eq!(w.len(), 11);
|
||||
assert!(w.iter().all(|w| w["start"]["y"] == 0.0 && w["end"]["y"] == 50.0));
|
||||
assert_eq!(deduplicate(vec![w[0].clone(), w[0].clone(), w[1].clone()], 0.01).len(), 2);
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,7 @@ mod drawings;
|
||||
mod layers;
|
||||
mod pens;
|
||||
mod layout_model;
|
||||
mod parametric_walls;
|
||||
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
//! Bindungen der parametrischen Wand-Engine (`crate::parametric_walls`): zustandslos, JSON hinein, JSON hinaus.
|
||||
//! Der Zähler der Wand-ids reist mit (`counter`), Zustand hält die TS-Fassade. Kaputte Eingaben → leerer Text.
|
||||
|
||||
use crate::parametric_walls::{self as pw, Ctx};
|
||||
use serde_json::{json, Value};
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
fn walls_of(v: &Value) -> Vec<Value> {
|
||||
v.as_array().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Rechnung `name`: `resolve` (`{parametricWall, floorId, context, defaultWallType, tolerance, counter}`),
|
||||
/// `applyRule` (`{rule, ctx: {floorId, defaultWallType, context, existingWalls}, counter}`), `matchesCondition` /
|
||||
/// `matchesTarget` (`{wall, condition|target, ctx}`), `deduplicate` (`{walls, tolerance}`).
|
||||
#[wasm_bindgen]
|
||||
pub fn parametric_call(name: &str, arg_json: &str) -> String {
|
||||
let Ok(a) = serde_json::from_str::<Value>(arg_json) else { return String::new() };
|
||||
let null = Value::Null;
|
||||
let counter = a["counter"].as_u64().unwrap_or(0);
|
||||
let out = match name {
|
||||
"resolve" => {
|
||||
let context = a.get("context").unwrap_or(&null);
|
||||
let existing = walls_of(context.get("existingWalls").unwrap_or(&null));
|
||||
let ctx = Ctx {
|
||||
floor_id: a.get("floorId").unwrap_or(&null),
|
||||
default_wall_type: a.get("defaultWallType").unwrap_or(&null),
|
||||
context,
|
||||
existing,
|
||||
};
|
||||
let mut n = counter;
|
||||
let walls = pw::resolve(a.get("parametricWall").unwrap_or(&null), &ctx, a["tolerance"].as_f64().unwrap_or(0.01), &mut n);
|
||||
json!({"walls": walls, "counter": n})
|
||||
}
|
||||
"applyRule" | "matchesCondition" | "matchesTarget" => {
|
||||
let c = a.get("ctx").unwrap_or(&null);
|
||||
let ctx = Ctx {
|
||||
floor_id: c.get("floorId").unwrap_or(&null),
|
||||
default_wall_type: c.get("defaultWallType").unwrap_or(&null),
|
||||
context: c.get("context").unwrap_or(&null),
|
||||
existing: walls_of(c.get("existingWalls").unwrap_or(&null)),
|
||||
};
|
||||
let wall = a.get("wall").unwrap_or(&null);
|
||||
match name {
|
||||
"applyRule" => {
|
||||
let mut n = counter;
|
||||
let walls = pw::apply_rule(a.get("rule").unwrap_or(&null), &ctx, &mut n);
|
||||
json!({"walls": walls, "counter": n})
|
||||
}
|
||||
"matchesCondition" => json!(pw::matches_condition(wall, a["condition"].as_str().unwrap_or(""), &ctx)),
|
||||
_ => json!(pw::matches_target(wall, a["target"].as_str().unwrap_or(""), &ctx)),
|
||||
}
|
||||
}
|
||||
"deduplicate" => json!(pw::deduplicate(walls_of(a.get("walls").unwrap_or(&null)), a["tolerance"].as_f64().unwrap_or(0.01))),
|
||||
_ => return String::new(),
|
||||
};
|
||||
out.to_string()
|
||||
}
|
||||
+51
-454
@@ -1,9 +1,10 @@
|
||||
// Parametrische Wand-Engine — löst ParametricWall-Regelwerke zu Wall[]-Arrays auf.
|
||||
//
|
||||
// Dieses Modul ist ABSICHTLICH frei von React-, Store- und App.tsx-Importen.
|
||||
// Es ist eine reine Modell-Schicht: Eingabe ist ein ParametricWall-Regelwerk +
|
||||
// Kontext (Geschoss, Grid-Achsen, bestehende Wände), Ausgabe sind neue Wall[]-
|
||||
// Objekte, die direkt in project.walls eingefügt werden können.
|
||||
// Die Rechnung liegt im Rust-Kern ([K4] S3, `src-tauri/core/src/parametric_walls.rs`); dieses Modul ist
|
||||
// die dünne Fassade mit den bisherigen Signaturen und frei von React-, Store- und App.tsx-Importen.
|
||||
// Eingabe ist ein ParametricWall-Regelwerk + Kontext (Geschoss, Grid-Achsen, bestehende Wände), Ausgabe
|
||||
// sind neue Wall[]-Objekte, die direkt in project.walls eingefügt werden können. Der Zähler der erzeugten
|
||||
// Wand-ids (`pw-<Geschoss>-<Art>-<n>`, sessionlokal, nicht persistent) ist der einzige Zustand und liegt hier.
|
||||
//
|
||||
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
|
||||
|
||||
@@ -20,6 +21,7 @@ import type {
|
||||
Wall,
|
||||
WallType,
|
||||
} from "./types";
|
||||
import { core } from "../engine/coreWasm";
|
||||
|
||||
// ── Kontext-Typen ─────────────────────────────────────────────────────────
|
||||
|
||||
@@ -53,22 +55,26 @@ interface RuleCtx {
|
||||
floorId: string;
|
||||
defaultWallType: WallType;
|
||||
context: ParametricContext;
|
||||
/** Wände, die bisher durch frühere Regeln erzeugt wurden (veränderbar). */
|
||||
/** Wände, die bisher durch frühere Regeln erzeugt wurden. */
|
||||
existingWalls: Wall[];
|
||||
}
|
||||
|
||||
// ── ID-Hilfsfunktion ──────────────────────────────────────────────────────
|
||||
// ── Kern-Aufruf ───────────────────────────────────────────────────────────
|
||||
|
||||
/** Einfacher Zähler für generierte Wand-IDs (sessionlokal, nicht persistent). */
|
||||
let _idCounter = 0;
|
||||
/** Laufende Nummer der erzeugten Wand-ids (sessionlokal, nicht persistent). */
|
||||
let idCounter = 0;
|
||||
|
||||
/**
|
||||
* Erzeugt eine eindeutige ID für eine parametrisch generierte Wand.
|
||||
* Format: „pw-<parametricWallId>-<counter>".
|
||||
*/
|
||||
function makeWallId(prefix: string): string {
|
||||
_idCounter += 1;
|
||||
return `pw-${prefix}-${_idCounter}`;
|
||||
function call<T>(name: string, arg: unknown): T {
|
||||
const out = core().parametric_call(name, JSON.stringify(arg));
|
||||
if (out === "") throw new Error(`Kern: Parametrik-Rechnung „${name}" fehlgeschlagen`);
|
||||
return JSON.parse(out) as T;
|
||||
}
|
||||
|
||||
/** Rechnung mit Wand-Ergebnis: schreibt den Zähler der ids fort. */
|
||||
function walls(name: string, arg: Record<string, unknown>): Wall[] {
|
||||
const r = call<{ walls: Wall[]; counter: number }>(name, { ...arg, counter: idCounter });
|
||||
idCounter = r.counter;
|
||||
return r.walls;
|
||||
}
|
||||
|
||||
// ── Öffentliche API ───────────────────────────────────────────────────────
|
||||
@@ -100,465 +106,56 @@ export function resolveParametricWall(
|
||||
defaultWallType: WallType,
|
||||
tolerance = 0.01,
|
||||
): Wall[] {
|
||||
const ctx: RuleCtx = {
|
||||
floorId,
|
||||
defaultWallType,
|
||||
context,
|
||||
existingWalls: context.existingWalls ?? [],
|
||||
};
|
||||
|
||||
const generated: Wall[] = [];
|
||||
|
||||
for (const rule of parametricWall.rules) {
|
||||
const ruleWalls = applyRule(rule, {
|
||||
...ctx,
|
||||
existingWalls: [...ctx.existingWalls, ...generated],
|
||||
});
|
||||
generated.push(...ruleWalls);
|
||||
}
|
||||
|
||||
return deduplicateWalls(generated, tolerance);
|
||||
return walls("resolve", { parametricWall, floorId, context, defaultWallType, tolerance });
|
||||
}
|
||||
|
||||
// ── Rule-Dispatcher ───────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Dispatcher: delegiert eine Regel an die passende Implementierung.
|
||||
* Alle Branches sind exhaustiv — unbekannte Typen geben leer zurück.
|
||||
* Dispatcher: delegiert eine Regel an die passende Implementierung (Raster, Modul, bedingte Dicke,
|
||||
* Referenzlinie, Sequenz); unbekannte Typen geben leer zurück.
|
||||
*
|
||||
* @param rule - Die auszuführende Regel.
|
||||
* @param ctx - Interner Arbeitskontext.
|
||||
* @returns Wall[]-Array, das diese Regel erzeugt oder verändert hat.
|
||||
*/
|
||||
export function applyRule(rule: ParametricRule, ctx: RuleCtx): Wall[] {
|
||||
switch (rule.type) {
|
||||
case "grid":
|
||||
return applyGridRule(rule, ctx);
|
||||
case "module":
|
||||
return applyModuleRule(rule, ctx);
|
||||
case "conditional-thickness":
|
||||
return applyConditionalThicknessRule(rule, ctx);
|
||||
case "reference-line":
|
||||
return applyReferenceLineRule(rule, ctx);
|
||||
case "sequence":
|
||||
return applySequenceRule(rule, ctx);
|
||||
default: {
|
||||
// TypeScript exhaustiveness-Guard: niemals erreicht bei vollständiger Union.
|
||||
const _exhaustive: never = rule;
|
||||
void _exhaustive;
|
||||
return [];
|
||||
}
|
||||
}
|
||||
return walls("applyRule", { rule, ctx });
|
||||
}
|
||||
|
||||
// ── Regel-Implementierungen ────────────────────────────────────────────────
|
||||
/** Raster-Regel: Wände entlang gleichmäßiger X-/Y-Achsen (Rasterachsen aus `gridAxes` oder `spacing`). */
|
||||
export const applyGridRule = (rule: GridRule, ctx: RuleCtx): Wall[] => applyRule(rule, ctx);
|
||||
|
||||
/** Modul-Regel: Querwände an den Teilungspunkten einer Referenzspanne (Geschoss-Ausdehnung oder Referenzwand). */
|
||||
export const applyModuleRule = (rule: ModuleRule, ctx: RuleCtx): Wall[] => applyRule(rule, ctx);
|
||||
|
||||
/** Bedingte-Dicken-Regel: MODIFIZIERTE KOPIEN passender Wände mit neuem `wallTypeId` (Originale bleiben). */
|
||||
export const applyConditionalThicknessRule = (rule: ConditionalThicknessRule, ctx: RuleCtx): Wall[] => applyRule(rule, ctx);
|
||||
|
||||
/** Referenzlinien-Regel: MODIFIZIERTE KOPIEN passender Wände mit gesetzter `referenceLine`. */
|
||||
export const applyReferenceLineRule = (rule: ReferenceLineRule, ctx: RuleCtx): Wall[] => applyRule(rule, ctx);
|
||||
|
||||
/** Sequenz-Regel: führt Unterregeln der Reihe nach aus (`stopOnMatch`: Abbruch nach dem ersten produktiven Schritt). */
|
||||
export const applySequenceRule = (rule: SequenceRule, ctx: RuleCtx): Wall[] => applyRule(rule, ctx);
|
||||
|
||||
/**
|
||||
* Raster-Regel: generiert Wände entlang gleichmäßiger X-/Y-Achsen.
|
||||
*
|
||||
* MVP-Verhalten:
|
||||
* - Rasterachsen aus `context.gridAxes` ODER gleichmäßigem `spacing`.
|
||||
* - Standardbereich: 0 … `defaultExtent` (10 Einheiten × Spacing), wenn keine
|
||||
* Grenzgeometrie vorhanden.
|
||||
* - Clipping durch `context.boundaryGeometry` (nur einfache Bounding-Box, MVP).
|
||||
* - Je Achse eine Wand senkrecht zur Richtung.
|
||||
*
|
||||
* @param rule - GridRule-Parameter.
|
||||
* @param ctx - Arbeitskontext (Geschoss, Wandtyp, …).
|
||||
* @returns Wall[]-Array mit generierten Rasterwänden.
|
||||
* Entfernt doppelte Wände aus der generierten Liste: gleicher Start- und Endpunkt innerhalb `tolerance`
|
||||
* (Meter), auch umgekehrt (A→B = B→A); behält jeweils die ERSTE Instanz.
|
||||
*/
|
||||
export function applyGridRule(rule: GridRule, ctx: RuleCtx): Wall[] {
|
||||
const walls: Wall[] = [];
|
||||
const spacing = rule.spacing ?? 3.0;
|
||||
const wallTypeId = rule.wallTypeId ?? ctx.defaultWallType.id;
|
||||
const referenceLine = rule.referenceLine;
|
||||
const height = rule.height ?? (ctx.context.floor.floorHeight ?? 2.6);
|
||||
const floorId = ctx.floorId;
|
||||
const categoryCode = "20";
|
||||
|
||||
// Bereich aus Grenzpolygon (Bounding-Box) oder Standardbereich ermitteln.
|
||||
const { minX, maxX, minY, maxY } = computeBounds(ctx.context, spacing);
|
||||
|
||||
// X-Richtung: Wände parallel zur Y-Achse (also senkrecht zur X-Richtung).
|
||||
if (rule.directions === "x" || rule.directions === "both") {
|
||||
const axes = rule.gridId != null && ctx.context.gridAxes
|
||||
? ctx.context.gridAxes.x
|
||||
: generateAxisPositions(minX, maxX, spacing);
|
||||
|
||||
for (const axisX of axes) {
|
||||
const wall: Wall = {
|
||||
id: makeWallId(`${floorId}-gx`),
|
||||
type: "wall",
|
||||
floorId,
|
||||
categoryCode,
|
||||
start: { x: axisX, y: minY },
|
||||
end: { x: axisX, y: maxY },
|
||||
wallTypeId,
|
||||
height,
|
||||
...(referenceLine != null ? { referenceLine } : {}),
|
||||
};
|
||||
walls.push(wall);
|
||||
}
|
||||
}
|
||||
|
||||
// Y-Richtung: Wände parallel zur X-Achse (also senkrecht zur Y-Richtung).
|
||||
if (rule.directions === "y" || rule.directions === "both") {
|
||||
const axes = rule.gridId != null && ctx.context.gridAxes
|
||||
? ctx.context.gridAxes.y
|
||||
: generateAxisPositions(minY, maxY, spacing);
|
||||
|
||||
for (const axisY of axes) {
|
||||
const wall: Wall = {
|
||||
id: makeWallId(`${floorId}-gy`),
|
||||
type: "wall",
|
||||
floorId,
|
||||
categoryCode,
|
||||
start: { x: minX, y: axisY },
|
||||
end: { x: maxX, y: axisY },
|
||||
wallTypeId,
|
||||
height,
|
||||
...(referenceLine != null ? { referenceLine } : {}),
|
||||
};
|
||||
walls.push(wall);
|
||||
}
|
||||
}
|
||||
|
||||
return walls;
|
||||
export function deduplicateWalls(input: Wall[], tolerance = 0.01): Wall[] {
|
||||
return call<Wall[]>("deduplicate", { walls: input, tolerance });
|
||||
}
|
||||
|
||||
/**
|
||||
* Modul-Regel: unterteilt eine Referenzspanne proportional in Felder.
|
||||
*
|
||||
* MVP-Verhalten:
|
||||
* - Spanne aus Geschoss-Ausdehnung (Bounding-Box) oder Referenzwand.
|
||||
* - Teilungspunkte im `moduleSize`-Abstand.
|
||||
* - Querwände (senkrecht zur `direction`) an jedem Teilungspunkt.
|
||||
*
|
||||
* @param rule - ModuleRule-Parameter.
|
||||
* @param ctx - Arbeitskontext.
|
||||
* @returns Wall[]-Array mit Querwänden an Modul-Teilungspunkten.
|
||||
* Prüft, ob eine Wand die Bedingung einer ConditionalThicknessRule erfüllt: „exterior" (am Rand der
|
||||
* Bounding-Box des Kontexts), „interior" (Gegenteil), „bearing" (Wand liegt innerhalb 10° einer Achse);
|
||||
* sonst immer `false`.
|
||||
*/
|
||||
export function applyModuleRule(rule: ModuleRule, ctx: RuleCtx): Wall[] {
|
||||
const walls: Wall[] = [];
|
||||
const wallTypeId = rule.wallTypeId ?? ctx.defaultWallType.id;
|
||||
const referenceLine = rule.referenceLine;
|
||||
const height = rule.height ?? (ctx.context.floor.floorHeight ?? 2.6);
|
||||
const floorId = ctx.floorId;
|
||||
const categoryCode = "20";
|
||||
|
||||
const { minX, maxX, minY, maxY } = computeBounds(ctx.context, rule.moduleSize);
|
||||
|
||||
// Referenzwand: falls angegeben, Spanne aus dieser Wand ableiten.
|
||||
let spanStart: number;
|
||||
let spanEnd: number;
|
||||
let perpStart: number;
|
||||
let perpEnd: number;
|
||||
|
||||
if (rule.referenceWallId != null) {
|
||||
const refWall = ctx.existingWalls.find((w) => w.id === rule.referenceWallId);
|
||||
if (refWall != null) {
|
||||
// Spanne entlang der Hauptachse der Referenzwand.
|
||||
if (rule.direction === "x") {
|
||||
spanStart = Math.min(refWall.start.x, refWall.end.x);
|
||||
spanEnd = Math.max(refWall.start.x, refWall.end.x);
|
||||
perpStart = minY;
|
||||
perpEnd = maxY;
|
||||
} else {
|
||||
spanStart = Math.min(refWall.start.y, refWall.end.y);
|
||||
spanEnd = Math.max(refWall.start.y, refWall.end.y);
|
||||
perpStart = minX;
|
||||
perpEnd = maxX;
|
||||
}
|
||||
} else {
|
||||
// Referenzwand nicht gefunden: Fallback auf Bounding-Box.
|
||||
spanStart = rule.direction === "x" ? minX : minY;
|
||||
spanEnd = rule.direction === "x" ? maxX : maxY;
|
||||
perpStart = rule.direction === "x" ? minY : minX;
|
||||
perpEnd = rule.direction === "x" ? maxY : maxX;
|
||||
}
|
||||
} else {
|
||||
spanStart = rule.direction === "x" ? minX : minY;
|
||||
spanEnd = rule.direction === "x" ? maxX : maxY;
|
||||
perpStart = rule.direction === "x" ? minY : minX;
|
||||
perpEnd = rule.direction === "x" ? maxY : maxX;
|
||||
}
|
||||
|
||||
// Modul-Teilungspunkte (ohne Start und Ende der Spanne selbst).
|
||||
const positions = generateAxisPositions(spanStart, spanEnd, rule.moduleSize);
|
||||
// Ersten und letzten Punkt herausfiltern, da das dort bereits Außenwände gibt.
|
||||
const dividers = positions.filter((p) => p > spanStart + 1e-6 && p < spanEnd - 1e-6);
|
||||
|
||||
for (const pos of dividers) {
|
||||
const wall: Wall = rule.direction === "x"
|
||||
? {
|
||||
id: makeWallId(`${floorId}-mx`),
|
||||
type: "wall",
|
||||
floorId,
|
||||
categoryCode,
|
||||
start: { x: pos, y: perpStart },
|
||||
end: { x: pos, y: perpEnd },
|
||||
wallTypeId,
|
||||
height,
|
||||
...(referenceLine != null ? { referenceLine } : {}),
|
||||
}
|
||||
: {
|
||||
id: makeWallId(`${floorId}-my`),
|
||||
type: "wall",
|
||||
floorId,
|
||||
categoryCode,
|
||||
start: { x: perpStart, y: pos },
|
||||
end: { x: perpEnd, y: pos },
|
||||
wallTypeId,
|
||||
height,
|
||||
...(referenceLine != null ? { referenceLine } : {}),
|
||||
};
|
||||
walls.push(wall);
|
||||
}
|
||||
|
||||
return walls;
|
||||
export function matchesCondition(wall: Wall, condition: string, ctx: RuleCtx): boolean {
|
||||
return call<boolean>("matchesCondition", { wall, condition, ctx });
|
||||
}
|
||||
|
||||
/**
|
||||
* Bedingte-Dicken-Regel: weist bestehenden Wänden einen neuen Wandtyp zu,
|
||||
* wenn eine Bedingung erfüllt ist.
|
||||
*
|
||||
* Gibt MODIFIZIERTE KOPIEN der passenden Wände zurück (keine Mutation).
|
||||
* Die Originalwände in `existingWalls` bleiben unverändert.
|
||||
*
|
||||
* @param rule - ConditionalThicknessRule-Parameter.
|
||||
* @param ctx - Arbeitskontext (enthält die zu prüfenden Wände).
|
||||
* @returns Wall[]-Array mit geändertem `wallTypeId` für passende Wände.
|
||||
*/
|
||||
export function applyConditionalThicknessRule(
|
||||
rule: ConditionalThicknessRule,
|
||||
ctx: RuleCtx,
|
||||
): Wall[] {
|
||||
return ctx.existingWalls
|
||||
.filter((w) => matchesCondition(w, rule.condition, ctx))
|
||||
.map((w) => ({ ...w, id: makeWallId(`${ctx.floorId}-ct`), wallTypeId: rule.wallTypeId }));
|
||||
}
|
||||
|
||||
/**
|
||||
* Referenzlinien-Regel: setzt `referenceLine` bei passenden Wänden einheitlich.
|
||||
*
|
||||
* Gibt MODIFIZIERTE KOPIEN der passenden Wände zurück.
|
||||
*
|
||||
* @param rule - ReferenceLineRule-Parameter.
|
||||
* @param ctx - Arbeitskontext.
|
||||
* @returns Wall[]-Array mit gesetzter `referenceLine`.
|
||||
*/
|
||||
export function applyReferenceLineRule(
|
||||
rule: ReferenceLineRule,
|
||||
ctx: RuleCtx,
|
||||
): Wall[] {
|
||||
return ctx.existingWalls
|
||||
.filter((w) => matchesTarget(w, rule.target, ctx))
|
||||
.map((w) => ({
|
||||
...w,
|
||||
id: makeWallId(`${ctx.floorId}-rl`),
|
||||
referenceLine: rule.referenceLine,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sequenz-Regel: führt Unterregeln in Reihenfolge aus.
|
||||
*
|
||||
* Jede Unterregel erhält das bisherige Ergebnis als `existingWalls`, sodass
|
||||
* spätere Regeln die früheren verfeinern können (z. B. Raster → Dicke → Linie).
|
||||
* Mit `stopOnMatch=true` bricht die Sequenz nach dem ersten produktiven Schritt ab.
|
||||
*
|
||||
* @param rule - SequenceRule-Parameter (enthält `rules[]`).
|
||||
* @param ctx - Arbeitskontext.
|
||||
* @returns Wall[]-Array (Summe aller Unterregel-Ausgaben, oder Abbruch bei stopOnMatch).
|
||||
*/
|
||||
export function applySequenceRule(rule: SequenceRule, ctx: RuleCtx): Wall[] {
|
||||
let result: Wall[] = [];
|
||||
|
||||
for (const subrule of rule.rules) {
|
||||
const subruleCtx: RuleCtx = {
|
||||
...ctx,
|
||||
existingWalls: [...ctx.existingWalls, ...result],
|
||||
};
|
||||
const subruleWalls = applyRule(subrule, subruleCtx);
|
||||
result = [...result, ...subruleWalls];
|
||||
|
||||
if (rule.stopOnMatch === true && subruleWalls.length > 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// ── Hilfsfunktionen ───────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Entfernt doppelte Wände aus der generierten Liste.
|
||||
*
|
||||
* Zwei Wände gelten als Duplikat, wenn Start- und Endpunkt jeweils innerhalb
|
||||
* `tolerance` (Meter) übereinstimmen — sowohl in der gleichen als auch in der
|
||||
* umgekehrten Orientierung (A→B = B→A).
|
||||
*
|
||||
* Behält jeweils die ERSTE Instanz; spätere Duplikate werden verworfen.
|
||||
*
|
||||
* @param walls - Eingabe-Wall[]-Array (wird nicht mutiert).
|
||||
* @param tolerance - Abstandsschwelle in Metern (Default 0.01 m = 1 cm).
|
||||
* @returns Bereinigte Wall[]-Liste ohne Duplikate.
|
||||
*/
|
||||
export function deduplicateWalls(walls: Wall[], tolerance = 0.01): Wall[] {
|
||||
const unique: Wall[] = [];
|
||||
|
||||
for (const candidate of walls) {
|
||||
const isDuplicate = unique.some((existing) => {
|
||||
const fwd =
|
||||
dist2(candidate.start, existing.start) <= tolerance &&
|
||||
dist2(candidate.end, existing.end) <= tolerance;
|
||||
const rev =
|
||||
dist2(candidate.start, existing.end) <= tolerance &&
|
||||
dist2(candidate.end, existing.start) <= tolerance;
|
||||
return fwd || rev;
|
||||
});
|
||||
|
||||
if (!isDuplicate) {
|
||||
unique.push(candidate);
|
||||
}
|
||||
}
|
||||
|
||||
return unique;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft, ob eine Wand die Bedingung einer ConditionalThicknessRule erfüllt.
|
||||
*
|
||||
* MVP-Implementierung:
|
||||
* • „exterior" — Wand liegt am Rand der Bounding-Box des Kontexts
|
||||
* (innerhalb einer großzügigen Toleranz).
|
||||
* • „interior" — Gegenteil von „exterior".
|
||||
* • „bearing" — Wand ist in der Primärrichtung (X oder Y) ausgerichtet
|
||||
* (einfaches Heuristikum für MVP).
|
||||
* • Sonstige — immer `false` (Phase 3: Wall.tags[]).
|
||||
*
|
||||
* @param wall - Zu prüfende Wand.
|
||||
* @param condition - Bedingungsstring aus der Regel.
|
||||
* @param ctx - Arbeitskontext (enthält Grenzgeometrie).
|
||||
* @returns `true`, wenn die Bedingung zutrifft.
|
||||
*/
|
||||
export function matchesCondition(
|
||||
wall: Wall,
|
||||
condition: string,
|
||||
ctx: RuleCtx,
|
||||
): boolean {
|
||||
if (condition === "exterior") {
|
||||
return isExteriorWall(wall, ctx);
|
||||
}
|
||||
if (condition === "interior") {
|
||||
return !isExteriorWall(wall, ctx);
|
||||
}
|
||||
if (condition === "bearing") {
|
||||
// Heuristikum: Wand ist „tragend", wenn sie in X- oder Y-Richtung läuft
|
||||
// (nahezu horizontal/vertikal). Phase 3: strukturelle Klassifizierung.
|
||||
const dx = Math.abs(wall.end.x - wall.start.x);
|
||||
const dy = Math.abs(wall.end.y - wall.start.y);
|
||||
const len = Math.sqrt(dx * dx + dy * dy);
|
||||
if (len < 1e-6) return false;
|
||||
const angleFromX = Math.atan2(dy, dx);
|
||||
// Gilt als tragend, wenn Winkel innerhalb 10° von X- oder Y-Achse liegt.
|
||||
const tenDeg = (10 * Math.PI) / 180;
|
||||
return (
|
||||
angleFromX <= tenDeg ||
|
||||
angleFromX >= Math.PI / 2 - tenDeg
|
||||
);
|
||||
}
|
||||
// Unbekannte Bedingung — Phase 3: Tag-Matching.
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft, ob eine Wand dem Ziel einer ReferenceLineRule entspricht.
|
||||
*
|
||||
* @param wall - Zu prüfende Wand.
|
||||
* @param target - Zielstring aus der Regel.
|
||||
* @param ctx - Arbeitskontext.
|
||||
* @returns `true`, wenn die Wand dem Ziel entspricht.
|
||||
*/
|
||||
export function matchesTarget(
|
||||
wall: Wall,
|
||||
target: string,
|
||||
ctx: RuleCtx,
|
||||
): boolean {
|
||||
if (target === "all") return true;
|
||||
if (target === "exterior") return isExteriorWall(wall, ctx);
|
||||
// Unbekanntes Ziel — Phase 3: Tag-Matching.
|
||||
return false;
|
||||
}
|
||||
|
||||
// ── Interne Hilfsfunktionen ───────────────────────────────────────────────
|
||||
|
||||
/** Euklidischer Abstand zweier 2D-Punkte. */
|
||||
function dist2(a: Vec2, b: Vec2): number {
|
||||
const dx = a.x - b.x;
|
||||
const dy = a.y - b.y;
|
||||
return Math.sqrt(dx * dx + dy * dy);
|
||||
}
|
||||
|
||||
/**
|
||||
* Berechnet die Bounding-Box des Kontexts.
|
||||
* Nutzt `boundaryGeometry`, falls vorhanden; sonst einen Standardbereich,
|
||||
* der auf `spacing` basiert (0 … spacing × 10).
|
||||
*/
|
||||
function computeBounds(
|
||||
context: ParametricContext,
|
||||
spacing: number,
|
||||
): { minX: number; maxX: number; minY: number; maxY: number } {
|
||||
if (context.boundaryGeometry != null && context.boundaryGeometry.boundary.length >= 2) {
|
||||
const pts = context.boundaryGeometry.boundary;
|
||||
let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
|
||||
for (const p of pts) {
|
||||
if (p.x < minX) minX = p.x;
|
||||
if (p.x > maxX) maxX = p.x;
|
||||
if (p.y < minY) minY = p.y;
|
||||
if (p.y > maxY) maxY = p.y;
|
||||
}
|
||||
return { minX, maxX, minY, maxY };
|
||||
}
|
||||
// Standardbereich: 10 Einheiten × Spacing.
|
||||
const extent = spacing * 10;
|
||||
return { minX: 0, maxX: extent, minY: 0, maxY: extent };
|
||||
}
|
||||
|
||||
/**
|
||||
* Generiert gleichmäßig verteilte Achspositionen im Intervall [min, max].
|
||||
* Die erste Position liegt bei `min`, jede weitere `spacing` danach.
|
||||
* Enthält `max`, wenn dieser exakt auf einem Rasterpunkt liegt (±1e-6).
|
||||
*/
|
||||
function generateAxisPositions(min: number, max: number, spacing: number): number[] {
|
||||
if (spacing <= 0 || max <= min) return [];
|
||||
const positions: number[] = [];
|
||||
let pos = min;
|
||||
while (pos <= max + 1e-6) {
|
||||
positions.push(Math.round(pos * 1e6) / 1e6); // Rundungsfehler vermeiden
|
||||
pos += spacing;
|
||||
}
|
||||
return positions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Klassifiziert eine Wand als „außen" (Rand der Bounding-Box) oder „innen".
|
||||
*
|
||||
* MVP: Eine Wand gilt als außen, wenn BEIDE ihrer Endpunkte auf oder nahe
|
||||
* am Rand der Bounding-Box des Kontexts liegen (±`edgeTolerance`).
|
||||
*/
|
||||
function isExteriorWall(wall: Wall, ctx: RuleCtx): boolean {
|
||||
const { minX, maxX, minY, maxY } = computeBounds(ctx.context, 1.0);
|
||||
const edgeTol = 0.1; // 10 cm Toleranz am Rand.
|
||||
|
||||
const isOnEdge = (p: Vec2): boolean =>
|
||||
Math.abs(p.x - minX) <= edgeTol ||
|
||||
Math.abs(p.x - maxX) <= edgeTol ||
|
||||
Math.abs(p.y - minY) <= edgeTol ||
|
||||
Math.abs(p.y - maxY) <= edgeTol;
|
||||
|
||||
return isOnEdge(wall.start) && isOnEdge(wall.end);
|
||||
/** Prüft, ob eine Wand dem Ziel einer ReferenceLineRule entspricht („all", „exterior"). */
|
||||
export function matchesTarget(wall: Wall, target: string, ctx: RuleCtx): boolean {
|
||||
return call<boolean>("matchesTarget", { wall, target, ctx });
|
||||
}
|
||||
|
||||
// DrawingLevel-Re-Export für Konsumenten, die keinen eigenen types-Import wollen.
|
||||
|
||||
Reference in new issue
Block a user