Merge branch 'worktree-agent-aa2baaef4ed68d2da' into claude/practical-noether-1hb2s1
This commit is contained in:
51 files changed
+1869
-38
No files matched your search
@@ -879,6 +879,81 @@ fn column_ops(v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
|
||||
)
|
||||
}
|
||||
|
||||
/// [149] Baum am Punkt `at`: Ebene „13" (Bäume), falls vorhanden, sonst die aktive; Abmessungen, Form,
|
||||
/// Bestand und Laub/Nadel aus den Werkzeug-Vorgaben (fehlende/unsinnige Werte: Vorgaben aus `tree.rs`).
|
||||
fn tree_ops(p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
|
||||
use crate::tree::*;
|
||||
let num = |k: &str, d: f64| opt_n(v, k).filter(|x| *x > 0.0 && x.is_finite()).unwrap_or(d);
|
||||
let height = num("height", DEFAULT_HEIGHT);
|
||||
let crown_base = opt_n(v, "crownBase").filter(|x| *x >= 0.0 && x.is_finite()).unwrap_or(DEFAULT_CROWN_BASE).min(0.9 * height);
|
||||
let pick = |k: &str, allowed: &[&str]| -> Value { s(allowed.iter().copied().find(|a| *a == s_of(v, k)).unwrap_or(allowed[0])) };
|
||||
let cat = if p.layer_category(TREE_CATEGORY).is_some() { TREE_CATEGORY } else { ctx.cat };
|
||||
let mut f = vec![
|
||||
("id", s(&ids.next("tree"))),
|
||||
("type", s("tree")),
|
||||
("floorId", s(ctx.level)),
|
||||
("categoryCode", s(cat)),
|
||||
("position", pv(p_of(v, "at"))),
|
||||
("trunkDiameter", js_num(num("trunkDiameter", DEFAULT_TRUNK_DIAMETER))),
|
||||
("crownDiameter", js_num(num("crownDiameter", DEFAULT_CROWN_DIAMETER))),
|
||||
("crownBase", js_num(crown_base)),
|
||||
("height", js_num(height)),
|
||||
("shape", pick("shape", &["round", "oval", "columnar", "conical"])),
|
||||
("status", pick("status", &["existing", "new", "remove"])),
|
||||
("foliage", pick("foliage", &["deciduous", "conifer"])),
|
||||
];
|
||||
let species = s_of(v, "species").trim();
|
||||
if !species.is_empty() {
|
||||
f.push(("species", s(species)));
|
||||
}
|
||||
add_op("trees", vec![obj(f)])
|
||||
}
|
||||
|
||||
/// [149] „Kreise in Bäume umwandeln": die gewählten Kreise (`ids`), sonst alle Kreise der Baum-Ebene auf der
|
||||
/// aktiven Ebene, werden Baum-Objekte (Kronendurchmesser = Kreisdurchmesser, Höhe = `sunStudy.treeHeight`
|
||||
/// bzw. Vorgabe, Ebene und Geschoss des Kreises); die Kreise entfallen. Ein Undo-Schritt.
|
||||
fn circles_to_trees_ops(root: &Map<String, Value>, p: &Project, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> Vec<Op> {
|
||||
use crate::tree::*;
|
||||
let chosen: Vec<&str> = arr(field(v, "ids")).iter().filter_map(Value::as_str).collect();
|
||||
let is_tree_cat = |code: &str| {
|
||||
code == TREE_CATEGORY || p.layer_category(code).is_some_and(|c| {
|
||||
let n = c.name.to_lowercase();
|
||||
n.contains("baum") || n.contains("bäume") || n.contains("tree")
|
||||
})
|
||||
};
|
||||
let h = p.sun_study.as_ref().and_then(|s| s.tree_height).filter(|h| *h > 0.0 && h.is_finite()).unwrap_or(crate::sun::DEFAULT_TREE_HEIGHT);
|
||||
let (mut src, mut out) = (Vec::new(), Vec::new());
|
||||
for d in &p.drawings2d {
|
||||
let crate::model::Drawing2DGeom::Circle { center, r } = &d.geom else { continue };
|
||||
let pick = if chosen.is_empty() { d.level_id == ctx.level && is_tree_cat(&d.category_code) } else { chosen.contains(&d.id.as_str()) };
|
||||
if !pick || !(*r > 0.0 && r.is_finite() && center.x.is_finite() && center.y.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
let cat = if is_tree_cat(&d.category_code) { d.category_code.as_str() } else if p.layer_category(TREE_CATEGORY).is_some() { TREE_CATEGORY } else { d.category_code.as_str() };
|
||||
src.push(d.id.as_str());
|
||||
out.push(obj(vec![
|
||||
("id", s(&ids.next("tree"))),
|
||||
("type", s("tree")),
|
||||
("floorId", s(&d.level_id)),
|
||||
("categoryCode", s(cat)),
|
||||
("position", pv((center.x, center.y))),
|
||||
("trunkDiameter", js_num(DEFAULT_TRUNK_DIAMETER.min(*r))),
|
||||
("crownDiameter", js_num(2.0 * r)),
|
||||
("crownBase", js_num(DEFAULT_CROWN_BASE.min(0.4 * h))),
|
||||
("height", js_num(h)),
|
||||
("shape", s("round")),
|
||||
("status", s("existing")),
|
||||
("foliage", s("deciduous")),
|
||||
]));
|
||||
}
|
||||
if out.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
let mut ops = remove_op(root, "drawings2d", &src);
|
||||
ops.extend(add_op("trees", out));
|
||||
ops
|
||||
}
|
||||
|
||||
/// Grundriss einer Stütze ohne Drehung (`columnFootprint`: rund 32 Punkte, sonst 4 Ecken).
|
||||
fn column_footprint(at: V, v: &Value) -> Vec<V> {
|
||||
let size = n_of(v, "size");
|
||||
@@ -988,6 +1063,8 @@ pub fn ops(root: &Map<String, Value>, p: &Project, v: &Value) -> Option<Vec<Op>>
|
||||
"opening" => opening_ops(root, p, v, &ctx, ids),
|
||||
"roof" => roof_ops(p, v, &ctx, ids),
|
||||
"column" => column_ops(v, &ctx, ids),
|
||||
"tree" => tree_ops(p, v, &ctx, ids),
|
||||
"circlesToTrees" => circles_to_trees_ops(root, p, v, &ctx, ids),
|
||||
"extrude" => extrude_ops(root, v, &ctx, ids),
|
||||
_ => return crate::cmd_draw::ops(root, p, v, &ctx, ids).or_else(|| crate::cmd_solid::ops(root, p, v, &ctx, ids)),
|
||||
})
|
||||
@@ -1067,6 +1144,15 @@ pub fn preview_req(root: &Map<String, Value>, project: &Project, req: &Req, pts:
|
||||
out.poly(&column_footprint(*at, v));
|
||||
}
|
||||
}
|
||||
"tree" => {
|
||||
// [149] Kronenkreis und Stamm am Cursor.
|
||||
if let Some(at) = pts.first() {
|
||||
let d = opt_n(v, "crownDiameter").filter(|x| *x > 0.0 && x.is_finite()).unwrap_or(crate::tree::DEFAULT_CROWN_DIAMETER);
|
||||
let t = opt_n(v, "trunkDiameter").filter(|x| *x > 0.0 && x.is_finite()).unwrap_or(crate::tree::DEFAULT_TRUNK_DIAMETER);
|
||||
out.poly(&circle_pts(*at, d / 2.0, 32));
|
||||
out.poly(&circle_pts(*at, t / 2.0, 12));
|
||||
}
|
||||
}
|
||||
"rect4" => {
|
||||
// Aufgezogenes Rechteck (Dach, Deckenaussparung, Textrahmen …): erste Ecke + Cursor.
|
||||
if pts.len() >= 2 {
|
||||
@@ -1213,6 +1299,39 @@ mod tests {
|
||||
assert_eq!(items(&o, 1)[0]["wallTypeId"], "WT-s-1");
|
||||
}
|
||||
|
||||
/// [149] Baum setzen (Ebene 13, Vorgaben, Unsinn verworfen) und Kreise in Bäume umwandeln.
|
||||
#[test]
|
||||
fn baum_setzen_und_kreise_umwandeln() {
|
||||
let r = root(json!({"layers": [{"code": "13", "name": "Bäume", "color": "#000"}], "drawings2d": [
|
||||
{"id": "k1", "type": "drawing2d", "levelId": "F1", "categoryCode": "13", "geom": {"shape": "circle", "center": {"x": 3, "y": 4}, "r": 2.5}},
|
||||
{"id": "k2", "type": "drawing2d", "levelId": "F1", "categoryCode": "20", "geom": {"shape": "circle", "center": {"x": 0, "y": 0}, "r": 1}},
|
||||
{"id": "k3", "type": "drawing2d", "levelId": "F2", "categoryCode": "13", "geom": {"shape": "circle", "center": {"x": 0, "y": 0}, "r": 1}}
|
||||
], "sunStudy": {"when": "2026-06-21T10:00:00Z", "show": true, "treeHeight": 14}}));
|
||||
let p = crate::model::lenient::typed_for_test(&r);
|
||||
let o = ops(&r, &p, &req(json!({"cmd": "tree", "at": [1, 2], "crownDiameter": 7, "height": 15, "shape": "conical", "status": "new", "foliage": "conifer", "species": " Picea abies "}))).unwrap();
|
||||
let t = &items(&o, 0)[0];
|
||||
assert_eq!(t["categoryCode"], "13");
|
||||
assert_eq!((t["crownDiameter"].as_f64(), t["height"].as_f64(), t["trunkDiameter"].as_f64()), (Some(7.0), Some(15.0), Some(crate::tree::DEFAULT_TRUNK_DIAMETER)));
|
||||
assert_eq!((t["shape"].as_str(), t["status"].as_str(), t["foliage"].as_str(), t["species"].as_str()), (Some("conical"), Some("new"), Some("conifer"), Some("Picea abies")));
|
||||
let _: crate::model::Tree = serde_json::from_value(t.clone()).unwrap();
|
||||
// Unsinn: Vorgaben, unbekannte Form → rund.
|
||||
let o = ops(&r, &p, &req(json!({"cmd": "tree", "at": [0, 0], "height": -3, "shape": "weide"}))).unwrap();
|
||||
let t = &items(&o, 0)[0];
|
||||
assert_eq!((t["height"].as_f64(), t["shape"].as_str()), (Some(crate::tree::DEFAULT_HEIGHT), Some("round")));
|
||||
// Umwandeln ohne Auswahl: nur Kreise der Baum-Ebene auf der aktiven Ebene.
|
||||
let o = ops(&r, &p, &req(json!({"cmd": "circlesToTrees"}))).unwrap();
|
||||
assert_eq!(o[0].to_json()["ids"], json!(["k1"]));
|
||||
let t = &items(&o, 1)[0];
|
||||
assert_eq!((t["crownDiameter"].as_f64(), t["height"].as_f64(), t["floorId"].as_str()), (Some(5.0), Some(14.0), Some("F1")));
|
||||
assert_eq!(t["position"], json!({"x": 3, "y": 4}));
|
||||
// Mit Auswahl: genau die gewählten Kreise (auch anderer Ebene).
|
||||
let o = ops(&r, &p, &req(json!({"cmd": "circlesToTrees", "ids": ["k2", "k3"]}))).unwrap();
|
||||
assert_eq!(o[0].to_json()["ids"], json!(["k2", "k3"]));
|
||||
assert_eq!(items(&o, 1)[1]["floorId"], "F2");
|
||||
// Nichts zu tun: keine Ops.
|
||||
assert!(ops(&r, &p, &req(json!({"cmd": "circlesToTrees", "ids": ["fehlt"]}))).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn treppe_stufen_aus_auftritt() {
|
||||
assert_eq!(steps_from_tread(0.29, 3.0), 10.0);
|
||||
|
||||
@@ -20,7 +20,7 @@ use std::collections::HashMap;
|
||||
|
||||
/// Listen der Zwischenablage: (Schlüssel in `clip`, Projekt-Liste, id-Präfix, Geschoss-Feld).
|
||||
/// Reihenfolge = Reihenfolge der ids und der Ops (Wände vor Öffnungen).
|
||||
const LISTS: [(&str, &str, &str, &str); 9] = [
|
||||
const LISTS: [(&str, &str, &str, &str); 10] = [
|
||||
("walls", "walls", "W", "floorId"),
|
||||
("drawings", "drawings2d", "dr2d", "levelId"),
|
||||
("ceilings", "ceilings", "C", "floorId"),
|
||||
@@ -30,6 +30,7 @@ const LISTS: [(&str, &str, &str, &str); 9] = [
|
||||
("rooms", "rooms", "RM", "floorId"),
|
||||
("extrudedSolids", "extrudedSolids", "extrude", "levelId"),
|
||||
("columns", "columns", "column", "floorId"),
|
||||
("trees", "trees", "tree", "floorId"),
|
||||
];
|
||||
|
||||
/// Ops des Einfügens: je Liste ein `add` (leere Listen ohne Op).
|
||||
|
||||
@@ -272,6 +272,13 @@ fn mv_column(c: &Value, xf: &Xf) -> Value {
|
||||
with_all(c, vec![("position", pt(nb.0, nb.1)), ("rotation", js_num(jsnum::atan2(nt.1 - nb.1, nt.0 - nb.0)))])
|
||||
}
|
||||
|
||||
/// [149] Baum: nur die Stammmitte (die Krone ist rund).
|
||||
fn mv_tree(t: &Value, xf: &Xf) -> Value {
|
||||
let (x, y) = xy(field(t, "position").unwrap_or(&Value::Null));
|
||||
let n = xf.apply(x, y);
|
||||
with(t, "position", pt(n.0, n.1))
|
||||
}
|
||||
|
||||
fn mv_ceiling(c: &Value, xf: &Xf) -> Value {
|
||||
let mut f = vec![("outline", xf.pts(field(c, "outline")))];
|
||||
if truthy(field(c, "openings")) {
|
||||
@@ -532,6 +539,8 @@ pub struct Sel {
|
||||
pub room_ids: Option<Vec<String>>,
|
||||
/// Gewählte Öffnungen ([144]): Wandöffnungen gleiten beim Verschieben entlang ihrer Wand.
|
||||
pub opening_ids: Option<Vec<String>>,
|
||||
/// [149] Gewählte Bäume.
|
||||
pub tree_ids: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
fn nonempty(s: &Option<String>) -> Option<&str> {
|
||||
@@ -586,6 +595,7 @@ enum Kind {
|
||||
Roof,
|
||||
Stair,
|
||||
Room,
|
||||
Tree,
|
||||
}
|
||||
|
||||
/// Dächer nur bei Verschieben/Skalieren (der Umriss ist an die Weltachsen gebunden, der First folgt
|
||||
@@ -620,6 +630,7 @@ fn gather<'a>(root: &'a Map<String, Value>, sel: &Sel, op: &str, ignore_lock: bo
|
||||
}
|
||||
each("stairs", Ids::opt(&sel.stair_ids), Kind::Stair);
|
||||
each("rooms", Ids::opt(&sel.room_ids), Kind::Room);
|
||||
each("trees", Ids::opt(&sel.tree_ids), Kind::Tree);
|
||||
out
|
||||
}
|
||||
|
||||
@@ -794,6 +805,10 @@ pub fn transform_result(root: &Map<String, Value>, p: &Project, req: &TransformR
|
||||
if !rooms.is_empty() {
|
||||
patch("rooms", &|r| rooms.has(r) && !locked(r), &|r| mv_room(r, &xf));
|
||||
}
|
||||
let trees = Ids::opt(&sel.tree_ids);
|
||||
if !trees.is_empty() {
|
||||
patch("trees", &|t| trees.has(t) && !locked(t), &|t| mv_tree(t, &xf));
|
||||
}
|
||||
// Öffnungen in bewegten Dächern/Decken ([103]) folgen ihrem Wirt.
|
||||
let hosts: std::collections::HashSet<&str> =
|
||||
items.iter().filter(|(k, _)| matches!(k, Kind::Roof | Kind::Ceiling)).filter_map(|(_, e)| id_of(e)).collect();
|
||||
@@ -809,7 +824,7 @@ pub fn transform_result(root: &Map<String, Value>, p: &Project, req: &TransformR
|
||||
|
||||
// Kopien (Kopie/Reihe/Verteilen bzw. gespiegelte Kopie).
|
||||
let mut ids = IdGen::new(&req.stamp);
|
||||
let mut new: [Vec<Value>; 8] = Default::default();
|
||||
let mut new: [Vec<Value>; 9] = Default::default();
|
||||
let mut new_openings = Vec::new();
|
||||
for t in copy_ts(op, &req.mode, req.count.0) {
|
||||
let xf = Xf::of(op, &pts, t);
|
||||
@@ -824,6 +839,7 @@ pub fn transform_result(root: &Map<String, Value>, p: &Project, req: &TransformR
|
||||
Kind::Roof => "RF",
|
||||
Kind::Stair => "ST",
|
||||
Kind::Room => "RM",
|
||||
Kind::Tree => "tree",
|
||||
})
|
||||
.collect();
|
||||
let new_ids: Vec<String> = prefixes.iter().map(|p| ids.next(p)).collect();
|
||||
@@ -848,6 +864,7 @@ pub fn transform_result(root: &Map<String, Value>, p: &Project, req: &TransformR
|
||||
Kind::Roof => (5, mv_roof(e, &xf)),
|
||||
Kind::Stair => (6, mv_stair(e, &xf, k_at(t))),
|
||||
Kind::Room => (7, mv_room(e, &xf)),
|
||||
Kind::Tree => (8, mv_tree(e, &xf)),
|
||||
};
|
||||
new[slot].push(with(&v, "id", Value::String(new_id.clone())));
|
||||
}
|
||||
@@ -869,7 +886,7 @@ pub fn transform_result(root: &Map<String, Value>, p: &Project, req: &TransformR
|
||||
}
|
||||
}
|
||||
}
|
||||
let keys = ["walls", "drawings2d", "extrudedSolids", "columns", "ceilings", "roofs", "stairs", "rooms"];
|
||||
let keys = ["walls", "drawings2d", "extrudedSolids", "columns", "ceilings", "roofs", "stairs", "rooms", "trees"];
|
||||
for (key, items) in keys.iter().zip(new) {
|
||||
ops.extend(add(key, items));
|
||||
}
|
||||
@@ -1177,6 +1194,14 @@ fn item_preview(p: &Project, kind: Kind, e: &Value, xf: &Xf, out: &mut Pending)
|
||||
Kind::Ceiling | Kind::Roof => s.poly(&mapped(&pts_of(field(e, "outline")), xf)),
|
||||
Kind::Room => s.poly(&mapped(&pts_of(field(e, "boundary")), xf)),
|
||||
Kind::Stair => stair_preview(e, xf, s),
|
||||
Kind::Tree => {
|
||||
// [149] Kronenkreis um die verschobene Stammmitte.
|
||||
let (x, y) = pt("position");
|
||||
let c = xf.apply(x, y);
|
||||
let d = field(e, "crownDiameter").and_then(Value::as_f64).filter(|d| *d > 0.0 && d.is_finite()).unwrap_or(crate::tree::DEFAULT_CROWN_DIAMETER);
|
||||
let ring: Vec<(f64, f64)> = crate::tree::circle([c.0, c.1], d / 2.0, 24).into_iter().map(|q| (q[0], q[1])).collect();
|
||||
s.poly(&ring);
|
||||
}
|
||||
Kind::Drawing => {
|
||||
let at = s.buf.len();
|
||||
out.drawings.push((at, with_geom(e, mv_geom(field(e, "geom").unwrap_or(&Value::Null), xf))));
|
||||
@@ -1337,6 +1362,25 @@ mod tests {
|
||||
v.as_object().unwrap().clone()
|
||||
}
|
||||
|
||||
/// [149] Bäume: Verschieben (gesperrte bleiben), Kopieren mit neuer id.
|
||||
#[test]
|
||||
fn baeume_verschieben_und_kopieren() {
|
||||
let r = root(json!({"trees":[{"id":"t","position":{"x":1,"y":2},"crownDiameter":5},{"id":"z","position":{"x":0,"y":0},"locked":true}]}));
|
||||
let run = |mode: &str| {
|
||||
let req: TransformReq = serde_json::from_value(json!({"sel":{"wallIds":[],"treeIds":["t","z"]},"op":"move","pts":[[0, 0], [3, 1]],"mode":mode,"count":1,"stamp":"s"})).unwrap();
|
||||
transform_ops(&r, &Project::default(), &req).iter().map(|o| o.to_json()).collect::<Vec<_>>()
|
||||
};
|
||||
let ops = run("move");
|
||||
assert_eq!(ops.len(), 1);
|
||||
assert_eq!(ops[0]["entity"]["position"], json!({"x":4,"y":3}));
|
||||
assert_eq!(ops[0]["entity"]["crownDiameter"], json!(5));
|
||||
let ops = run("copy");
|
||||
assert_eq!(ops.len(), 1);
|
||||
assert_eq!(ops[0]["collection"], "trees");
|
||||
assert_eq!(ops[0]["items"][0]["id"], "tree-s-1");
|
||||
assert_eq!(ops[0]["items"][0]["position"], json!({"x":4,"y":3}));
|
||||
}
|
||||
|
||||
/// [T2] Bogenwand: Verschieben/Drehen behalten den Bulge, Spiegeln kehrt ihn um.
|
||||
#[test]
|
||||
fn bogenwand_spiegeln_kehrt_bulge() {
|
||||
|
||||
@@ -48,6 +48,9 @@ impl<'a> Explode<'a> {
|
||||
for c in p.columns.as_deref().unwrap_or(&[]) {
|
||||
floor_of.insert(&c.id, &c.floor_id);
|
||||
}
|
||||
for t in p.trees.as_deref().unwrap_or(&[]) {
|
||||
floor_of.insert(&t.id, &t.floor_id);
|
||||
}
|
||||
// [137] Freie Körper (Pick, Hervorhebung) folgen ihrem Geschoss.
|
||||
for s in p.extruded_solids.as_deref().unwrap_or(&[]) {
|
||||
floor_of.insert(&s.id, &s.level_id);
|
||||
@@ -151,10 +154,12 @@ pub fn parts(p: &Project, layered: bool, detail: f64, for_section: bool, gap: f6
|
||||
for (g, dz) in groups {
|
||||
let pick = |fid: &str| ex.in_group(fid, g);
|
||||
q.columns = p.columns.as_ref().map(|v| v.iter().filter(|c| pick(&c.floor_id)).cloned().collect());
|
||||
q.trees = p.trees.as_ref().map(|v| v.iter().filter(|t| pick(&t.floor_id)).cloned().collect());
|
||||
q.stairs = p.stairs.as_ref().map(|v| v.iter().filter(|s| pick(&s.floor_id)).cloned().collect());
|
||||
q.roofs = p.roofs.as_ref().map(|v| v.iter().filter(|r| pick(&r.floor_id)).cloned().collect());
|
||||
q.openings = p.openings.as_ref().map(|v| v.iter().filter(|o| pick(ex.floor_of.get(o.id.as_str()).copied().unwrap_or(""))).cloned().collect());
|
||||
out.column_meshes.extend(shifted(model3d::emit_columns(&q), dz, shift_mesh));
|
||||
out.column_meshes.extend(shifted(model3d::emit_trees(&q), dz, shift_mesh));
|
||||
out.stair_meshes.extend(shifted(model3d::emit_stair_meshes(&q), dz, shift_mesh));
|
||||
out.stair_railings.extend(shifted(model3d::emit_stair_railings(&q), dz, shift_mesh));
|
||||
out.roof_meshes.extend(shifted(model3d::emit_roofs(&q, None)?, dz, shift_mesh));
|
||||
@@ -225,6 +230,12 @@ pub fn pick_geometry(p: &Project, gap: f64) -> Result<PickGeometry, String> {
|
||||
v[1] += dz;
|
||||
}
|
||||
}
|
||||
for t in &mut g.trees {
|
||||
let dz = ex.of(&t.tree_id);
|
||||
for v in t.tris.iter_mut().flatten() {
|
||||
v[1] += dz;
|
||||
}
|
||||
}
|
||||
for o in &mut g.opening_meshes {
|
||||
let dz = ex.of(&o.opening_id);
|
||||
for v in o.tris.iter_mut().flatten() {
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
/// Projekt-Listen, die verschoben werden (jedes Element hat eine `id`), in Op-Reihenfolge.
|
||||
pub const TRANSLATED_LISTS: [&str; 10] = ["walls", "ceilings", "roofs", "stairs", "rooms", "columns", "extrudedSolids", "drawings2d", "context", "drawingLevels"];
|
||||
pub const TRANSLATED_LISTS: [&str; 11] = ["walls", "ceilings", "roofs", "stairs", "rooms", "columns", "extrudedSolids", "drawings2d", "context", "drawingLevels", "trees"];
|
||||
|
||||
fn shift(p: &Value, dx: f64, dy: f64) -> Value {
|
||||
let c = |k: &str| p.get(k).and_then(Value::as_f64).unwrap_or(f64::NAN);
|
||||
@@ -161,6 +161,7 @@ fn shift_element(key: &str, e: &Value, dx: f64, dy: f64) -> (Value, bool) {
|
||||
set(&mut m, "stampAnchor", c);
|
||||
}
|
||||
"columns" => shift_pts_fields(&mut m, &["position"], dx, dy, &[]),
|
||||
"trees" => shift_pts_fields(&mut m, &["position"], dx, dy, &[]),
|
||||
"extrudedSolids" => {
|
||||
shift_pts_fields(&mut m, &[], dx, dy, &["points"]);
|
||||
let c = if truthy(e.get("circle")) {
|
||||
|
||||
@@ -26,6 +26,8 @@ pub struct Args {
|
||||
/// [137] Stützen und freie Körper (Prisma über dem Grundriss).
|
||||
pub columns: Vec<String>,
|
||||
pub solids: Vec<String>,
|
||||
/// [149] Bäume (Umriss-Prisma Kronendurchmesser × Fuss bis Spitze).
|
||||
pub trees: Vec<String>,
|
||||
pub rgb: [f64; 3],
|
||||
/// Explosionsabstand ([65], `explode3d.rs`; fehlt/0 = aus): Linien folgen dem auseinandergezogenen Modell.
|
||||
#[serde(default)]
|
||||
@@ -214,6 +216,17 @@ pub fn selection_highlight_lines(p: &Project, a: &Args) -> Result<Vec<f32>, Stri
|
||||
lift(&mut out, n, &col.id);
|
||||
}
|
||||
}
|
||||
let trees = set(&a.trees);
|
||||
if !trees.is_empty() {
|
||||
let list = p.trees.as_deref().unwrap_or(&[]);
|
||||
for (i, g) in crate::tree::geoms(p) {
|
||||
if trees.contains(list[i].id.as_str()) {
|
||||
let n = out.v.len();
|
||||
out.prism_edges(&crate::tree::circle(g.c, g.crown_r, 12), g.base, g.top);
|
||||
lift(&mut out, n, &list[i].id);
|
||||
}
|
||||
}
|
||||
}
|
||||
for s in p.extruded_solids.as_deref().unwrap_or(&[]) {
|
||||
if solids.contains(s.id.as_str()) {
|
||||
let z0 = crate::model3d::solid_base_z(p, s);
|
||||
|
||||
@@ -50,6 +50,7 @@ const REC_OPENING_SOLID: f64 = 15.0;
|
||||
const REC_WALL_ARC: f64 = 16.0;
|
||||
const REC_WALL_ARC_SOLID: f64 = 17.0;
|
||||
const REC_GRID: f64 = 18.0;
|
||||
const REC_TREE: f64 = 19.0;
|
||||
|
||||
/// Toleranz des Kerns (`wall_bands.rs::EPS`) für „Öffnung trifft Band".
|
||||
const BAND_EPS: f64 = 1e-4;
|
||||
@@ -1354,6 +1355,46 @@ pub fn ifc_export_data(src: &Project, opt: &IfcOptions) -> Result<Flat, String>
|
||||
}
|
||||
f.num(REC_END_COLUMNS);
|
||||
|
||||
// ── Bäume ([149]) → IfcGeographicElement (IFC2x3: IfcBuildingElementProxy), Netz Stamm + Krone ──
|
||||
let trees = p.trees.as_deref().unwrap_or(&[]);
|
||||
for (i, g) in crate::tree::geoms(&p) {
|
||||
let t = &trees[i];
|
||||
let structure = structure_of(&t.floor_id);
|
||||
let base = base_of(structure);
|
||||
let (mut positions, mut indices) = g.trunk_mesh(8);
|
||||
let (cp, ci) = g.crown_mesh(8, 12);
|
||||
let at = (positions.len() / 3) as u32;
|
||||
positions.extend(cp);
|
||||
indices.extend(ci.iter().map(|k| at + k));
|
||||
for z in positions.iter_mut().skip(2).step_by(3) {
|
||||
*z -= base;
|
||||
}
|
||||
let status = match t.status {
|
||||
TreeStatus::New => "new",
|
||||
TreeStatus::Remove => "remove",
|
||||
_ => "existing",
|
||||
};
|
||||
let mut props = vec![ident("Status", status), ident("Foliage", if t.foliage == TreeFoliage::Conifer { "conifer" } else { "deciduous" })];
|
||||
if let Some(sp) = t.species.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
|
||||
props.push(Prop::Label("Species", sp.to_string()));
|
||||
}
|
||||
let mut psets = vec![Pset { name: "Dossier_Tree", props }];
|
||||
psets.extend(qto(
|
||||
"Dossier_Qto_Tree",
|
||||
vec![
|
||||
Qty { name: "Height", kind: QtyKind::Length, value: g.top - g.base },
|
||||
Qty { name: "CrownDiameter", kind: QtyKind::Length, value: 2.0 * g.crown_r },
|
||||
Qty { name: "TrunkDiameter", kind: QtyKind::Length, value: 2.0 * g.trunk_r },
|
||||
Qty { name: "CrownBaseHeight", kind: QtyKind::Length, value: g.crown_bottom - g.base },
|
||||
],
|
||||
));
|
||||
let (id, name) = (f.str(&t.id), f.str(&crate::tree::label(t)));
|
||||
f.nums(&[REC_TREE, structure, id, name]);
|
||||
w_psets(&mut f, &psets);
|
||||
// Zwei getrennte geschlossene Körper: nicht als ein dichtes Netz melden (IFC2x3: Flächenmodell).
|
||||
w_mesh(&mut f, &positions, &indices, false);
|
||||
}
|
||||
|
||||
// ── Achsraster ([112]) → IfcGrid (U-/V-Achsen als Linienzüge in Welt-XY) ──
|
||||
for d in &p.drawings2d {
|
||||
let Some(spec) = crate::grid::Spec::of(&d.geom) else { continue };
|
||||
@@ -1475,6 +1516,24 @@ mod tests {
|
||||
text.split('\0').map(String::from).collect()
|
||||
}
|
||||
|
||||
/// [149] Baum als eigener Datensatz (nach den Stützen): Name = Art, Netz Stamm + Krone relativ zur
|
||||
/// Geschoss-UK, Höhe als Menge.
|
||||
#[test]
|
||||
fn baum_datensatz() {
|
||||
let mut p = sample();
|
||||
let floor = p.drawing_levels.iter().find(|l| l.kind == DrawingLevelKind::Floor).unwrap().id.clone();
|
||||
let mut t = Tree { id: "T1".into(), r#type: "tree".into(), floor_id: "eg".into(), category_code: "13".into(), position: Vec2 { x: 20.0, y: 5.0 }, trunk_diameter: 0.4, crown_diameter: 6.0, crown_base: 3.0, height: 12.0, species: Some("Quercus robur".into()), ..Default::default() };
|
||||
t.floor_id = floor;
|
||||
p.trees = Some(vec![t]);
|
||||
let f = ifc_export_data(&p, &IfcOptions::default()).unwrap();
|
||||
let s = strings(&f);
|
||||
assert!(s.iter().any(|x| x == "T1") && s.iter().any(|x| x == "Quercus robur") && s.iter().any(|x| x == "Dossier_Qto_Tree"));
|
||||
assert!(f.nums.windows(2).any(|w| w == [REC_END_COLUMNS, REC_TREE]), "Baum direkt nach den Stützen");
|
||||
// Ohne Bäume kein Datensatz.
|
||||
p.trees = None;
|
||||
assert!(!strings(&ifc_export_data(&p, &IfcOptions::default()).unwrap()).iter().any(|x| x == "Dossier_Qto_Tree"));
|
||||
}
|
||||
|
||||
/// [G3]/[103] Formöffnung und Dachfenster als Öffnungskörper-Datensatz mit Wirt.
|
||||
#[test]
|
||||
fn formoeffnung_und_dachfenster() {
|
||||
|
||||
@@ -17,6 +17,7 @@ pub mod roof;
|
||||
pub mod roof_skeleton;
|
||||
pub mod flat_read;
|
||||
pub mod sun;
|
||||
pub mod tree;
|
||||
pub mod site_rules;
|
||||
pub mod auto_dimensions;
|
||||
pub mod kennzahlen;
|
||||
|
||||
@@ -438,6 +438,15 @@ pub fn mesh_export_data(src: &Project, opt: &MeshOptions) -> Result<Flat, String
|
||||
groups.push(g);
|
||||
}
|
||||
p.columns = columns;
|
||||
// [149] Bäume: je Baum eine Gruppe (Stamm + Krone).
|
||||
let trees = p.trees.take();
|
||||
for t in trees.as_deref().unwrap_or(&[]) {
|
||||
let mut g = Group::new(format!("Baum_{}", sanitize_name(&t.id)), "tree", &t.id, level_of(Some(&t.floor_id)));
|
||||
p.trees = Some(vec![t.clone()]);
|
||||
add_meshes(&mut g, &mut mats, &model3d::emit_trees(&p), "Baum");
|
||||
groups.push(g);
|
||||
}
|
||||
p.trees = trees;
|
||||
let stairs = p.stairs.take();
|
||||
for st in stairs.as_deref().unwrap_or(&[]) {
|
||||
let mut g = Group::new(format!("Treppe_{}", sanitize_name(&st.id)), "stair", &st.id, level_of(Some(&st.floor_id)));
|
||||
|
||||
@@ -3880,6 +3880,113 @@ pub struct Column {
|
||||
pub extra: Extra,
|
||||
}
|
||||
|
||||
/// Kronenform eines Baums ([149]): Grundform der Silhouette (Schnitt/Ansicht), des 3D-Körpers und
|
||||
/// des Schattenwerfers.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, TS)]
|
||||
pub enum TreeShape {
|
||||
/// Kugelig (Laubbaum, Krone ≈ Kugel/Ellipsoid über dem Kronenansatz).
|
||||
#[default]
|
||||
#[serde(rename = "round")]
|
||||
Round,
|
||||
/// Oval (Krone höher als breit, Ellipsoid).
|
||||
#[serde(rename = "oval")]
|
||||
Oval,
|
||||
/// Säulenförmig (schlanker, hoher Zylinder mit gerundeten Enden).
|
||||
#[serde(rename = "columnar")]
|
||||
Columnar,
|
||||
/// Kegel (Nadelbaum, Spitze oben).
|
||||
#[serde(rename = "conical")]
|
||||
Conical,
|
||||
#[serde(other)]
|
||||
#[ts(skip)]
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// Bestand eines Baums ([149]) nach Plankonvention: bestehend (schwarz), neu (rot/Planung),
|
||||
/// zu fällen (gelb bzw. durchgekreuzt).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, TS)]
|
||||
pub enum TreeStatus {
|
||||
#[default]
|
||||
#[serde(rename = "existing")]
|
||||
Existing,
|
||||
#[serde(rename = "new")]
|
||||
New,
|
||||
#[serde(rename = "remove")]
|
||||
Remove,
|
||||
#[serde(other)]
|
||||
#[ts(skip)]
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// Laub- oder Nadelbaum ([149]) — Planzeichen der Krone (Laub: Wellenkranz, Nadel: Zacken).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, TS)]
|
||||
pub enum TreeFoliage {
|
||||
#[default]
|
||||
#[serde(rename = "deciduous")]
|
||||
Deciduous,
|
||||
#[serde(rename = "conifer")]
|
||||
Conifer,
|
||||
#[serde(other)]
|
||||
#[ts(skip)]
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// Ein Baum ([149]) — eigenes Objekt der Umgebung mit Stamm, Krone und Höhe. Grundriss/Situation
|
||||
/// (Kronenkreis mit Planzeichen, Stamm), Schnitt/Ansicht (Silhouette nach Form), 3D (Stamm-Zylinder +
|
||||
/// Krone), Schatten (Sonnenstudie), IFC (IfcGeographicElement). Fuss auf dem Gelände an `position`
|
||||
/// (sonst auf der Geschoss-UK) plus `baseOffset`.
|
||||
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)]
|
||||
#[serde(default)]
|
||||
pub struct Tree {
|
||||
pub id: String,
|
||||
#[ts(type = "\"tree\"")]
|
||||
pub r#type: String,
|
||||
/// Zugehörige Zeichnungsebene (Geschoss), auf der der Baum im Grundriss erscheint.
|
||||
#[serde(rename = "floorId")]
|
||||
pub floor_id: String,
|
||||
/// Grafik-Kategorie (Ebene), Vorgabe "13" (Bäume).
|
||||
#[serde(rename = "categoryCode")]
|
||||
pub category_code: String,
|
||||
/// Objekt-Sperre, analog `Wall.locked`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub locked: Option<bool>,
|
||||
/// Stammmitte im Grundriss (Meter).
|
||||
pub position: Vec2,
|
||||
/// Stammdurchmesser (m, > 0).
|
||||
#[serde(rename = "trunkDiameter")]
|
||||
pub trunk_diameter: f64,
|
||||
/// Kronendurchmesser (m, > 0).
|
||||
#[serde(rename = "crownDiameter")]
|
||||
pub crown_diameter: f64,
|
||||
/// Höhe des Kronenansatzes über dem Fuss (m, ≥ 0, < `height`).
|
||||
#[serde(rename = "crownBase")]
|
||||
pub crown_base: f64,
|
||||
/// Gesamthöhe über dem Fuss (m, > 0).
|
||||
pub height: f64,
|
||||
/// Kronenform.
|
||||
pub shape: TreeShape,
|
||||
/// Bestehend / neu / zu fällen.
|
||||
pub status: TreeStatus,
|
||||
/// Laub- oder Nadelbaum.
|
||||
pub foliage: TreeFoliage,
|
||||
/// Optionaler Art-Name (z. B. „Quercus robur"), erscheint als Beschriftung im Grundriss.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub species: Option<String>,
|
||||
/// Höhenversatz des Fusses gegenüber Gelände bzw. Geschoss-UK (m, Vorgabe 0).
|
||||
#[serde(rename = "baseOffset", default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub base_offset: Option<f64>,
|
||||
/// Optionale Übersteuerung der Strichfarbe; sonst gilt die Kategorie-Farbe bzw. die Bestandsfarbe.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub color: Option<String>,
|
||||
#[serde(flatten)]
|
||||
#[ts(skip)]
|
||||
pub extra: Extra,
|
||||
}
|
||||
|
||||
/// Gruppe (Vectorworks-artig) — reine Mitgliedschaft je Elementart, siehe
|
||||
/// {@link Project.groups}. Alle ID-Listen sind additiv; ein Element gehört
|
||||
/// NIE zu mehr als einer Gruppe auf derselben Ebene (das Werkzeug/der Befehl
|
||||
@@ -4892,6 +4999,11 @@ pub struct Project {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub columns: Option<Vec<Column>>,
|
||||
/// Bäume ([149]) — eigene Objekte mit Stamm, Krone und Höhe, siehe {@link Tree}. Optional, damit
|
||||
/// bestehende Projekte ohne `trees` gültig bleiben (Default: leer behandeln).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub trees: Option<Vec<Tree>>,
|
||||
/// Gruppen (Vectorworks-artig: Cmd+G fasst die Auswahl zu einer Einheit
|
||||
/// zusammen; Doppelklick betritt die Gruppe zum Bearbeiten, alles andere
|
||||
/// wird dabei gedimmt/gesperrt — s. `state/useGroupState.ts`). Eine Gruppe
|
||||
@@ -5729,6 +5841,12 @@ impl Project {
|
||||
None => Default::default(),
|
||||
};
|
||||
}
|
||||
"trees" => {
|
||||
self.trees = match v {
|
||||
Some(v) => <Option<Vec<Tree>>>::deserialize(v).map_err(|e| e.to_string())?,
|
||||
None => Default::default(),
|
||||
};
|
||||
}
|
||||
"groups" => {
|
||||
self.groups = match v {
|
||||
Some(v) => <Option<Vec<Group>>>::deserialize(v).map_err(|e| e.to_string())?,
|
||||
|
||||
@@ -36,6 +36,7 @@ impl Project {
|
||||
"context" => put_opt(&mut self.context, i, v),
|
||||
"extrudedSolids" => put_opt(&mut self.extruded_solids, i, v),
|
||||
"columns" => put_opt(&mut self.columns, i, v),
|
||||
"trees" => put_opt(&mut self.trees, i, v),
|
||||
"groups" => put_opt(&mut self.groups, i, v),
|
||||
"layouts" => put_opt(&mut self.layouts, i, v),
|
||||
_ => Ok(false),
|
||||
|
||||
@@ -313,6 +313,36 @@ pub fn emit_columns(p: &Project) -> Vec<RMesh> {
|
||||
out
|
||||
}
|
||||
|
||||
/// [149] Bäume als Meshes: je Baum Stamm (Zylinder, 8 Seiten) und Krone (Rotationskörper, 8 Ringe × 12
|
||||
/// Seiten; Form nach `shape`), Fuss auf dem Gelände (`tree::bases`). Im 3D bei den Stützen eingereiht.
|
||||
pub fn emit_trees(p: &Project) -> Vec<RMesh> {
|
||||
let mut out = Vec::new();
|
||||
let trees = p.trees.as_deref().unwrap_or(&[]);
|
||||
for (i, g) in crate::tree::geoms(p) {
|
||||
let (trunk_rgb, crown_rgb) = crate::tree::colors(&trees[i]);
|
||||
let (positions, indices) = g.trunk_mesh(8);
|
||||
out.push(RMesh { crease_angle: None, positions, indices, kind: "extrusion", color: trunk_rgb, vertex_colors: None, material_index: None });
|
||||
let (positions, indices) = g.crown_mesh(8, 12);
|
||||
out.push(RMesh { crease_angle: None, positions, indices, kind: "extrusion", color: crown_rgb, vertex_colors: None, material_index: None });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// [149] Bäume als Welt-Dreiecke (Stamm + Krone, wie [`emit_trees`]) für den 3D-Pick.
|
||||
pub fn pick_trees(p: &Project) -> Vec<PickTree> {
|
||||
let trees = p.trees.as_deref().unwrap_or(&[]);
|
||||
crate::tree::geoms(p)
|
||||
.into_iter()
|
||||
.map(|(i, g)| {
|
||||
let (tp, ti) = g.trunk_mesh(8);
|
||||
let (cp, ci) = g.crown_mesh(8, 12);
|
||||
let mut tris = extrusion_tris(&tp, &ti);
|
||||
tris.extend(extrusion_tris(&cp, &ci));
|
||||
PickTree { tris, tree_id: trees[i].id.clone() }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
// ── Wände ───────────────────────────────────────────────────────────────────
|
||||
|
||||
use crate::joins::{self, JoinLayer, JoinWall, Reference, WallCuts};
|
||||
@@ -2378,7 +2408,7 @@ pub fn parts(p: &Project, layered: bool, detail: f64, for_section: bool) -> Resu
|
||||
walls: emit_walls(p, layered)?,
|
||||
slabs,
|
||||
context_meshes: emit_context_meshes(p),
|
||||
column_meshes: emit_columns(p),
|
||||
column_meshes: { let mut m = emit_columns(p); m.extend(emit_trees(p)); m },
|
||||
opening_meshes: emit_opening_meshes(p, detail),
|
||||
stair_meshes: emit_stair_meshes(p),
|
||||
stair_railings: emit_stair_railings(p),
|
||||
@@ -2537,6 +2567,14 @@ pub struct PickColumn {
|
||||
pub column_id: String,
|
||||
}
|
||||
|
||||
/// [149] Baum für den 3D-Pick.
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PickTree {
|
||||
pub tris: Vec<Tri>,
|
||||
pub tree_id: String,
|
||||
}
|
||||
|
||||
/// [137] Öffnung ohne Wand (Dach, Decke, Gaube) für den 3D-Pick: Welt-Dreiecke ihrer Teile.
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -2594,6 +2632,8 @@ pub struct PickGeometry {
|
||||
/// [137] Kreise, Bögen, Ellipsen und Texte als flache Pick-Flächen.
|
||||
#[serde(rename = "drawingMeshes")]
|
||||
pub drawing_meshes: Vec<PickDrawingMesh>,
|
||||
/// [149] Bäume (Stamm + Krone).
|
||||
pub trees: Vec<PickTree>,
|
||||
}
|
||||
|
||||
/// Öffnungen als Quader (Laibung zu Laibung, Wanddicke, Brüstung bis Sturz) für Pick und Hervorhebung.
|
||||
@@ -2747,6 +2787,7 @@ pub fn pick_geometry(p: &Project) -> Result<PickGeometry, String> {
|
||||
drawings: pick_drawing_segs(p, &HashMap::new()),
|
||||
stair_meshes: pick_stair_railings(p),
|
||||
drawing_meshes: pick_drawing_meshes(p, &HashMap::new()),
|
||||
trees: pick_trees(p),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -2900,6 +2941,32 @@ fn pick_columns(p: &Project) -> Vec<PickColumn> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// [149] Bäume im 3D (Stamm + Krone bei den Stützen-Meshes), im Pick und mit Fuss auf dem Gelände.
|
||||
#[test]
|
||||
fn baeume_im_3d_und_pick() {
|
||||
let mut p = sample();
|
||||
let n0 = parts(&p, true, 1.0, false).unwrap().column_meshes.len();
|
||||
p.trees = Some(vec![Tree { id: "T1".into(), r#type: "tree".into(), floor_id: "eg".into(), category_code: "13".into(), position: Vec2 { x: 20.0, y: 5.0 }, trunk_diameter: 0.4, crown_diameter: 6.0, crown_base: 3.0, height: 12.0, species: Some("Quercus robur".into()), ..Default::default() }, Tree { id: "T2".into(), shape: TreeShape::Conical, foliage: TreeFoliage::Conifer, base_offset: Some(0.5), ..Tree { id: "T1".into(), r#type: "tree".into(), floor_id: "eg".into(), category_code: "13".into(), position: Vec2 { x: 20.0, y: 5.0 }, trunk_diameter: 0.4, crown_diameter: 6.0, crown_base: 3.0, height: 12.0, species: Some("Quercus robur".into()), ..Default::default() } }]);
|
||||
let m = parts(&p, true, 1.0, false).unwrap().column_meshes;
|
||||
assert_eq!(m.len(), n0 + 4);
|
||||
let crown = &m[n0 + 1];
|
||||
assert_eq!(crown.color, crate::tree::CROWN_RGB);
|
||||
assert_eq!(m[n0 + 3].color, crate::tree::CONIFER_RGB);
|
||||
let zmax = crown.positions.chunks_exact(3).map(|q| q[2]).fold(f64::NEG_INFINITY, f64::max);
|
||||
let base = p.floor("eg").map_or(0.0, |f| f.base_elevation.unwrap_or(0.0));
|
||||
assert!((zmax - (base + 12.0)).abs() < 1e-9, "{zmax}");
|
||||
let z2 = m[n0 + 2].positions.chunks_exact(3).map(|q| q[2]).fold(f64::INFINITY, f64::min);
|
||||
assert!((z2 - (base + 0.5)).abs() < 1e-9, "Fuss mit Versatz: {z2}");
|
||||
// Wenige Dreiecke je Baum.
|
||||
assert!(m[n0..].iter().map(|x| x.indices.len() / 3).sum::<usize>() < 2 * 250);
|
||||
let g = pick_geometry(&p).unwrap();
|
||||
assert_eq!(g.trees.len(), 2);
|
||||
assert_eq!(g.trees[0].tree_id, "T1");
|
||||
// Welt-Dreiecke (x, Höhe, y): Höhe bis zur Spitze.
|
||||
let h = g.trees[0].tris.iter().flatten().map(|v| v[1]).fold(f64::NEG_INFINITY, f64::max);
|
||||
assert!((h - (base + 12.0)).abs() < 1e-9);
|
||||
}
|
||||
|
||||
/// [112] Achsraster mit `show3d` erscheint als Boden-Spur (eine Strecke je Achse), ohne Flag nicht.
|
||||
#[test]
|
||||
fn achsraster_im_3d_nur_mit_flag() {
|
||||
|
||||
@@ -240,7 +240,7 @@ impl Model3dCache {
|
||||
walls: Vec::new(),
|
||||
slabs,
|
||||
context_meshes: model3d::emit_context_meshes(p),
|
||||
column_meshes: model3d::emit_columns(p),
|
||||
column_meshes: { let mut m = model3d::emit_columns(p); m.extend(model3d::emit_trees(p)); m },
|
||||
opening_meshes: Vec::new(),
|
||||
stair_meshes: model3d::emit_stair_meshes(p),
|
||||
stair_railings: model3d::emit_stair_railings(p),
|
||||
|
||||
@@ -29,6 +29,7 @@ pub const NOT_FOR_DRAWINGS: &[&str] = &[
|
||||
"stairs",
|
||||
"rooms",
|
||||
"columns",
|
||||
"trees",
|
||||
"extrudedSolids",
|
||||
"context",
|
||||
"groups",
|
||||
|
||||
@@ -1095,6 +1095,8 @@ fn domains_before(c: &Ctx, out: &mut DomainPrims, bounds: &mut Bounds) -> Result
|
||||
super::walls::plan_walls(c, c.a.reference_lines, &mut out.walls, bounds)?;
|
||||
super::stairs::plan_stairs(c, &mut out.stairs, bounds);
|
||||
columns(c, &mut out.columns);
|
||||
// [149] Bäume (Planzeichen) mit den Stützen in einer Gruppe.
|
||||
super::trees::plan_trees(c, &mut out.columns);
|
||||
solids(c, &mut out.solids);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1481,6 +1481,17 @@ pub fn elevation_primitives_with(p: &Project, level: &LevelSpec, shadows: bool,
|
||||
};
|
||||
pending.push(Pending::Item { depth: f.depth, rank: Some(rank), prim });
|
||||
}
|
||||
// [149] Bäume: Silhouette (Krone gefüllt, Stamm) in der Maler-Reihenfolge; Bauteile davor verdecken sie.
|
||||
for (depth, tree) in super::trees::view_trees(p, level, vis, Some(super::trees::view_crown_fill(mono))) {
|
||||
for prim in tree {
|
||||
if let Primitive::Polygon { pts, .. } = &prim {
|
||||
for q in pts {
|
||||
acc.add(q.x, q.y);
|
||||
}
|
||||
}
|
||||
pending.push(Pending::Item { depth, rank: None, prim });
|
||||
}
|
||||
}
|
||||
// Kanten exakt ([G4]): Umriss, Knicke und Silhouetten der Flächen, verdeckt durch Flächen und
|
||||
// Öffnungen davor; Facetten-Fugen der Bogenwände ([T2]) fallen über die Glättungsgruppe weg.
|
||||
let edges = elevation_edges(p, &faces, &openings, &frame, level.hidden_lines);
|
||||
|
||||
@@ -34,6 +34,7 @@ pub mod sketch;
|
||||
pub mod ceiling_plan;
|
||||
pub mod line_ends;
|
||||
pub mod stamp_place;
|
||||
pub mod trees;
|
||||
pub(crate) mod wall_columns;
|
||||
#[cfg(test)]
|
||||
pub(crate) mod wall_join_tests;
|
||||
@@ -3282,6 +3282,12 @@ pub fn section_plan_buf(p: &Project, args: &[f64], text: &str) -> Result<Vec<u8>
|
||||
w.post = super::extras::sketch_post(Some(level.sketch), scale);
|
||||
// Strichstärken nach Massstab ([32]) wie im Grundriss.
|
||||
super::extras::scale_line_weights(p, scale, &mut prims);
|
||||
// [149] Bäume hinter der Schnittebene: transparente Silhouette unter dem Schnitt (Bauteile verdecken sie).
|
||||
let mut trees: Vec<Primitive> = super::trees::view_trees(p, &level, &vis, None).into_iter().flat_map(|(_, t)| t).collect();
|
||||
let bounds = super::trees::union_bounds(bounds, &trees);
|
||||
super::extras::scale_line_weights(p, scale, &mut trees);
|
||||
trees.extend(prims);
|
||||
let prims = trees;
|
||||
w.group(&prims);
|
||||
let mut ops = if openings { section_opening_primitives(p, &level, &vis)? } else { Vec::new() };
|
||||
super::extras::scale_line_weights(p, scale, &mut ops);
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
//! [149] Bäume im Grundriss (Situation) und in Schnitt/Ansicht. Geometrie aus `crate::tree`.
|
||||
//!
|
||||
//! Grundriss (Tusche, übliche Plankonvention): Kronenumriss als Planzeichen — Laubbaum mit Wellenkranz,
|
||||
//! Nadelbaum mit Zackenkranz —, Stamm als Kreis in Stammdicke. **Bestehend**: Strich in der Ebenenfarbe
|
||||
//! (sonst Tusche), Stamm gefüllt. **Neu**: rot (Planungsfarbe), Stamm offen. **Zu fällen**: gelb, Krone
|
||||
//! gestrichelt und durchgekreuzt (das Kreuz trägt die Aussage auch im Schwarz-Weiss-Druck). Eine eigene
|
||||
//! Farbe (`color`) übersteuert. Pick: unsichtbare Kronenfläche mit `contextObjectId = "@tree:<id>"`.
|
||||
//!
|
||||
//! Schnitt/Ansicht: vereinfachte Silhouette nach Form (Kronenprofil gespiegelt) und Stamm.
|
||||
|
||||
use super::domains::Ctx;
|
||||
use super::prim::Primitive;
|
||||
use super::section::{LevelSpec, Visibility};
|
||||
use super::style::{no_hatch, MONO_INK};
|
||||
use crate::model::*;
|
||||
use crate::tree::{TreeGeom, TREE_PICK_PREFIX};
|
||||
|
||||
/// Planungsfarbe „neu" und Abbruchfarbe „zu fällen".
|
||||
pub const NEW_COLOR: &str = "#c8102e";
|
||||
pub const REMOVE_COLOR: &str = "#d4a017";
|
||||
const CROWN_MM: f64 = 0.18;
|
||||
const TRUNK_MM: f64 = 0.25;
|
||||
const REMOVE_DASH: [f64; 2] = [1.5, 1.0];
|
||||
/// Strich der Silhouette in Schnitt/Ansicht.
|
||||
const VIEW_INK: &str = "#2b3039";
|
||||
const VIEW_CROWN_MM: f64 = 0.18;
|
||||
const VIEW_TRUNK_MM: f64 = 0.13;
|
||||
/// Füllung der Krone in der farbigen Ansicht (Tusche: weiss).
|
||||
const VIEW_CROWN_FILL: &str = "#e3ead9";
|
||||
/// Füllung des Stamms in der farbigen Ansicht.
|
||||
const VIEW_TRUNK_FILL: &str = "#d8cbb8";
|
||||
|
||||
fn v(x: f64, y: f64) -> Vec2 {
|
||||
Vec2 { x, y }
|
||||
}
|
||||
|
||||
/// Pick-Id eines Baums (Feld `contextObjectId`).
|
||||
pub fn pick_id(id: &str) -> String {
|
||||
format!("{TREE_PICK_PREFIX}{id}")
|
||||
}
|
||||
|
||||
fn poly(pts: Vec<Vec2>, fill: &str, stroke: &str, w: f64, pick: Option<String>, greyed: Option<bool>) -> Primitive {
|
||||
Primitive::Polygon {
|
||||
pts,
|
||||
fill: fill.into(),
|
||||
stroke: stroke.into(),
|
||||
stroke_width_mm: w,
|
||||
hatch: no_hatch(),
|
||||
greyed,
|
||||
opacity: None,
|
||||
no_stroke_edges: None,
|
||||
wall_id: None,
|
||||
drawing_id: None,
|
||||
ceiling_id: None,
|
||||
opening_id: None,
|
||||
stair_id: None,
|
||||
room_id: None,
|
||||
extruded_solid_id: None,
|
||||
context_object_id: pick,
|
||||
column_id: None,
|
||||
roof_id: None,
|
||||
section_line_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn line(a: Vec2, b: Vec2, cls: &str, w: f64, color: &str, dash: Option<&[f64]>, greyed: Option<bool>) -> Primitive {
|
||||
Primitive::Line {
|
||||
a,
|
||||
b,
|
||||
cls: cls.into(),
|
||||
weight_mm: w,
|
||||
dash: dash.map(|d| Some(d.to_vec())),
|
||||
zigzag: None,
|
||||
motif: None,
|
||||
color: Some(color.into()),
|
||||
drawing_id: None,
|
||||
opening_id: None,
|
||||
stair_id: None,
|
||||
greyed,
|
||||
opacity: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Kronenumriss im Grundriss: Wellenkranz (Laub) bzw. Zackenkranz (Nadel) um `c` mit Radius `r`.
|
||||
pub fn crown_outline(c: [f64; 2], r: f64, foliage: TreeFoliage) -> Vec<[f64; 2]> {
|
||||
// Etwa ein Bogen je 0.9 m Umfang, 7 bis 28.
|
||||
let n = ((std::f64::consts::TAU * r / 0.9).round() as usize).clamp(7, 28);
|
||||
let tau = std::f64::consts::TAU;
|
||||
let at = |t: f64, rr: f64| [c[0] + rr * crate::jsnum::cos(t), c[1] + rr * crate::jsnum::sin(t)];
|
||||
if foliage == TreeFoliage::Conifer {
|
||||
(0..2 * n).map(|i| at(i as f64 / (2 * n) as f64 * tau, if i % 2 == 0 { r } else { 0.8 * r })).collect()
|
||||
} else {
|
||||
let k = 6;
|
||||
(0..n * k)
|
||||
.map(|i| {
|
||||
let t = i as f64 / (n * k) as f64 * tau;
|
||||
let s = crate::jsnum::sin(t * n as f64 / 2.0).abs();
|
||||
at(t, r * (0.88 + 0.12 * s))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Strichfarbe eines Baums im Grundriss.
|
||||
fn ink(t: &Tree, cat: Option<&LayerCategory>) -> String {
|
||||
if let Some(c) = t.color.as_deref().filter(|c| !c.is_empty()) {
|
||||
return c.to_string();
|
||||
}
|
||||
match t.status {
|
||||
TreeStatus::New => NEW_COLOR.into(),
|
||||
TreeStatus::Remove => REMOVE_COLOR.into(),
|
||||
_ => cat.map(|k| k.color.as_str()).filter(|c| !c.is_empty()).unwrap_or(MONO_INK).to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Baum-Symbole des Grundrisses (Bäume dieses Geschosses mit sichtbarer Ebene).
|
||||
pub(super) fn plan_trees(c: &Ctx, out: &mut Vec<Primitive>) {
|
||||
let p = c.p;
|
||||
let Some(trees) = p.trees.as_deref() else { return };
|
||||
if trees.iter().all(|t| t.floor_id != c.a.floor) {
|
||||
return;
|
||||
}
|
||||
for (i, g) in crate::tree::geoms(p) {
|
||||
let t = &trees[i];
|
||||
if t.floor_id != c.a.floor || !c.vis(&t.category_code, &t.id) {
|
||||
continue;
|
||||
}
|
||||
out.extend(tree_symbol(t, &g, c.cat(&t.category_code), Some(c.greyed(&t.category_code))));
|
||||
}
|
||||
}
|
||||
|
||||
/// Planzeichen eines Baums (Grundriss): Pick-Fläche, Kronenumriss, Stamm, ggf. Kreuz.
|
||||
pub fn tree_symbol(t: &Tree, g: &TreeGeom, cat: Option<&LayerCategory>, greyed: Option<bool>) -> Vec<Primitive> {
|
||||
let color = ink(t, cat);
|
||||
let ring = crown_outline(g.c, g.crown_r, t.foliage);
|
||||
let pts: Vec<Vec2> = ring.iter().map(|q| v(q[0], q[1])).collect();
|
||||
let mut out = vec![poly(pts.clone(), "none", "none", 0.0, Some(pick_id(&t.id)), greyed)];
|
||||
let remove = t.status == TreeStatus::Remove;
|
||||
let dash = remove.then_some(&REMOVE_DASH[..]);
|
||||
for k in 0..pts.len() {
|
||||
out.push(line(pts[k], pts[(k + 1) % pts.len()], "tree-crown", CROWN_MM, &color, dash, greyed));
|
||||
}
|
||||
let trunk: Vec<Vec2> = crate::tree::circle(g.c, g.trunk_r, 16).into_iter().map(|q| v(q[0], q[1])).collect();
|
||||
let fill = if t.status == TreeStatus::New { "#ffffff".to_string() } else { color.clone() };
|
||||
out.push(poly(trunk, &fill, &color, TRUNK_MM, None, greyed));
|
||||
if remove {
|
||||
let d = g.crown_r * 0.9 * std::f64::consts::FRAC_1_SQRT_2;
|
||||
let (x, y) = (g.c[0], g.c[1]);
|
||||
out.push(line(v(x - d, y - d), v(x + d, y + d), "tree-remove", CROWN_MM, &color, None, greyed));
|
||||
out.push(line(v(x - d, y + d), v(x + d, y - d), "tree-remove", CROWN_MM, &color, None, greyed));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Bäume in Schnitt/Ansicht: je Baum (Tiefe der Stammmitte, Silhouette: Krone + Stamm). Nur Bäume vor der
|
||||
/// Blickrichtung (Mitte höchstens einen Kronenradius vor der Ebene) und innerhalb der Ansichtstiefe.
|
||||
/// `fill`: Kronenfüllung (`None` = transparent).
|
||||
pub fn view_trees(p: &Project, level: &LevelSpec, vis: &Visibility, fill: Option<&str>) -> Vec<(f64, Vec<Primitive>)> {
|
||||
let Some(trees) = p.trees.as_deref().filter(|t| !t.is_empty()) else { return vec![] };
|
||||
let Some(plane) = level.plane() else { return vec![] };
|
||||
let [nx, _, nz] = plane.normal;
|
||||
let nl = nx.hypot(nz);
|
||||
if !(nl > 0.0) {
|
||||
return vec![];
|
||||
}
|
||||
// Welt (x, Höhe, y): Ebene durch (p0.x, ·, p0.y); u = Blick-Rechts wie `elevation::frame_of`.
|
||||
let (nx, nz) = (nx / nl, nz / nl);
|
||||
let (ux, uz) = (nz, -nx);
|
||||
let (px, pz) = (plane.point[0], plane.point[2]);
|
||||
let mut out = Vec::new();
|
||||
for (i, g) in crate::tree::geoms(p) {
|
||||
let t = &trees[i];
|
||||
if vis.has_vis && !vis.visible(&t.category_code) || vis.has_display && !vis.render(&t.category_code) {
|
||||
continue;
|
||||
}
|
||||
let (rx, rz) = (g.c[0] - px, g.c[1] - pz);
|
||||
let depth = rx * nx + rz * nz;
|
||||
if depth < -g.crown_r || level.depth.is_some_and(|d| d > 0.0 && depth - g.crown_r > d) {
|
||||
continue;
|
||||
}
|
||||
let s = rx * ux + rz * uz;
|
||||
let (crown, trunk) = g.silhouette(s, 24);
|
||||
let greyed = Some(vis.has_display && vis.greyed(&t.category_code));
|
||||
let pick = Some(pick_id(&t.id));
|
||||
let to = |r: &[[f64; 2]]| r.iter().map(|q| v(q[0], q[1])).collect::<Vec<Vec2>>();
|
||||
let stroke = t.color.as_deref().filter(|c| !c.is_empty()).unwrap_or(VIEW_INK);
|
||||
let trunk_fill = fill.map(|f| if f == "#ffffff" { f } else { VIEW_TRUNK_FILL });
|
||||
let prims = vec![
|
||||
poly(to(&trunk), trunk_fill.unwrap_or("none"), stroke, VIEW_TRUNK_MM, pick.clone(), greyed),
|
||||
poly(to(&crown), fill.unwrap_or("none"), stroke, VIEW_CROWN_MM, pick, greyed),
|
||||
];
|
||||
out.push((depth, prims));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Ausmass `bounds` vereinigt mit den Polygon-Ecken von `prims` (Silhouetten in Schnitt/Ansicht).
|
||||
pub fn union_bounds(bounds: [f64; 4], prims: &[Primitive]) -> [f64; 4] {
|
||||
let mut b = bounds;
|
||||
for q in prims {
|
||||
if let Primitive::Polygon { pts, .. } = q {
|
||||
for v in pts.iter().filter(|v| v.x.is_finite() && v.y.is_finite()) {
|
||||
b = [b[0].min(v.x), b[1].min(v.y), b[2].max(v.x), b[3].max(v.y)];
|
||||
}
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// Füllung der Krone in der Ansicht.
|
||||
pub fn view_crown_fill(mono: bool) -> &'static str {
|
||||
if mono {
|
||||
"#ffffff"
|
||||
} else {
|
||||
VIEW_CROWN_FILL
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::plan::domains::{plan_domains, PlanArgs};
|
||||
|
||||
fn project(trees: serde_json::Value) -> Project {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"id": "p", "name": "P", "lineStyles": [], "hatches": [], "components": [], "wallTypes": [],
|
||||
"drawingLevels": [
|
||||
{"id": "eg", "name": "EG", "kind": "floor", "visible": true, "locked": false, "floorHeight": 3.0, "cutHeight": 1.0, "baseElevation": 0},
|
||||
{"id": "an", "name": "Ansicht Süd", "kind": "elevation", "visible": true, "locked": false, "floorHeight": 3.0, "linePoints": [{"x": -20, "y": -10}, {"x": 20, "y": -10}]}
|
||||
],
|
||||
"layers": [{"code": "13", "name": "Bäume", "color": "#000000", "lw": 0.13, "visible": true, "locked": false}],
|
||||
"walls": [], "openings": [], "drawings2d": [], "trees": trees
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn tree(id: &str, x: f64, status: &str, foliage: &str) -> serde_json::Value {
|
||||
serde_json::json!({"id": id, "type": "tree", "floorId": "eg", "categoryCode": "13", "position": {"x": x, "y": 0},
|
||||
"trunkDiameter": 0.4, "crownDiameter": 6, "crownBase": 3, "height": 12, "shape": "round", "status": status, "foliage": foliage})
|
||||
}
|
||||
|
||||
fn plan(p: &Project, codes: &[&str]) -> Vec<Primitive> {
|
||||
let text = serde_json::json!({"floor": "eg", "show": codes, "global": true}).to_string();
|
||||
let a = PlanArgs::parse(1.0, &text).unwrap();
|
||||
plan_domains(p, &a).unwrap().columns
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn planzeichen_nach_bestand_und_laub() {
|
||||
let p = project(serde_json::json!([tree("a", 0.0, "existing", "deciduous"), tree("b", 10.0, "new", "conifer"), tree("c", 20.0, "remove", "deciduous")]));
|
||||
let prims = plan(&p, &["13"]);
|
||||
let pick = |id: &str| prims.iter().filter(|q| matches!(q, Primitive::Polygon { context_object_id: Some(c), .. } if *c == pick_id(id))).count();
|
||||
assert_eq!((pick("a"), pick("b"), pick("c")), (1, 1, 1));
|
||||
let lines = |color: &str, dashed: bool| prims.iter().filter(|q| matches!(q, Primitive::Line { color: Some(c), dash, .. } if c == color && dash.is_some() == dashed)).count();
|
||||
// Bestehend: Tusche, durchgezogen; neu: rot; zu fällen: gelb, gestrichelt + 2 Kreuzlinien.
|
||||
assert!(lines("#000000", false) > 20);
|
||||
assert!(lines(NEW_COLOR, false) > 10);
|
||||
assert!(lines(REMOVE_COLOR, true) > 20 && lines(REMOVE_COLOR, false) == 2);
|
||||
// Stamm: gefüllt (bestehend) bzw. weiss (neu).
|
||||
let trunk_fill = |color: &str| prims.iter().filter(|q| matches!(q, Primitive::Polygon { fill, stroke, .. } if stroke == color && fill != "none")).map(|q| if let Primitive::Polygon { fill, .. } = q { fill.clone() } else { String::new() }).collect::<Vec<_>>();
|
||||
assert_eq!(trunk_fill("#000000"), vec!["#000000".to_string()]);
|
||||
assert_eq!(trunk_fill(NEW_COLOR), vec!["#ffffff".to_string()]);
|
||||
// Kronenumriss im Kronenradius (Wellenkranz zwischen 0.88 r und r).
|
||||
if let Some(Primitive::Polygon { pts, .. }) = prims.iter().find(|q| matches!(q, Primitive::Polygon { context_object_id: Some(c), .. } if *c == pick_id("a"))) {
|
||||
let r: Vec<f64> = pts.iter().map(|q| q.x.hypot(q.y)).collect();
|
||||
assert!(r.iter().all(|&x| x <= 3.0 + 1e-9 && x >= 0.88 * 3.0 - 1e-9));
|
||||
}
|
||||
// Ausgeblendete Ebene: nichts.
|
||||
assert!(plan(&p, &["20"]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn silhouette_in_der_ansicht() {
|
||||
let p = project(serde_json::json!([tree("a", 0.0, "existing", "deciduous"), tree("hinten", 5.0, "existing", "deciduous")]));
|
||||
let l = p.drawing_levels.iter().find(|l| l.id == "an").unwrap();
|
||||
let level = LevelSpec::from_json(&serde_json::to_value(l).unwrap());
|
||||
let (prims, _) = crate::plan::elevation::elevation_primitives(&p, &level, false, true, &Visibility::default(), 100.0).unwrap().unwrap();
|
||||
let crowns: Vec<&Primitive> = prims.iter().filter(|q| matches!(q, Primitive::Polygon { context_object_id: Some(c), pts, .. } if *c == pick_id("a") && pts.len() > 4)).collect();
|
||||
assert_eq!(crowns.len(), 1);
|
||||
if let Primitive::Polygon { pts, .. } = crowns[0] {
|
||||
let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
|
||||
let (mut zl, mut zh) = (f64::INFINITY, f64::NEG_INFINITY);
|
||||
for q in pts {
|
||||
lo = lo.min(q.x);
|
||||
hi = hi.max(q.x);
|
||||
zl = zl.min(q.y);
|
||||
zh = zh.max(q.y);
|
||||
}
|
||||
assert!((hi - lo - 6.0).abs() < 1e-6 && (zl - 3.0).abs() < 1e-9 && (zh - 12.0).abs() < 1e-9, "{lo} {hi} {zl} {zh}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ const REQUIRED_ARRAYS: [&str; 3] = ["walls", "layers", "drawingLevels"];
|
||||
const DEFAULT_ARRAYS: [&str; 5] = ["lineStyles", "hatches", "components", "wallTypes", "drawings2d"];
|
||||
|
||||
/// Bekannte Felder von `Project` (für die Meldung unbekannter Felder).
|
||||
const KNOWN_KEYS: [&str; 53] = [
|
||||
const KNOWN_KEYS: [&str; 54] = [
|
||||
"formatVersion", "id", "name", "lineStyles", "textStyles", "hatches", "components", "wallTypes",
|
||||
"ceilingTypes", "roofTypes", "blockDefs", "doorTypes", "windowTypes", "stairTypes", "pens",
|
||||
"penSets", "activePenSetId", "customPalettes", "builtinPaletteBanks", "drawingLevels", "layers",
|
||||
@@ -23,7 +23,7 @@ const KNOWN_KEYS: [&str; 53] = [
|
||||
"extrudedSolids", "columns", "groups", "parametricWalls", "overrideRules", "viewSnapshots",
|
||||
"viewSnapshotFolders", "viewTemplates", "layouts", "masterLayouts", "layoutFolders", "publishSets", "publishLog", "projectNumber", "referenceElevationMasl",
|
||||
"geoAnchor", "roomProgram", "roomProgramTolerance", "parcelArea", "sunStudy", "siteRules", "scaleLineWeights",
|
||||
"lineCap", "lineJoin",
|
||||
"lineCap", "lineJoin", "trees",
|
||||
];
|
||||
|
||||
/// Ergebnis des Einlesens.
|
||||
|
||||
@@ -917,6 +917,11 @@ fn collect(p: &Project, k: [f64; 2], cut: Option<f64>, ground: Option<&Ground>)
|
||||
clouds.push(crown);
|
||||
}
|
||||
}
|
||||
// [149] Bäume als eigene Objekte: Stamm (Prisma) + Krone (Punktwolke) nach eigener Höhe, Krone und Form.
|
||||
for (_, g) in crate::tree::geoms(p) {
|
||||
prisms.push((Prism { footprint: g.trunk_ring(8), z_bottom: g.base, z_top: g.trunk_top() }, vec![]));
|
||||
clouds.push(g.crown_points());
|
||||
}
|
||||
// Nur zur Sonne gewandte Dachflächen (Aussennormale): durch sie verlässt jeder Strahl den Körper.
|
||||
roof_faces.retain(|f| f.first().is_some_and(|r| {
|
||||
let n = newell(r);
|
||||
@@ -1312,4 +1317,31 @@ mod terrain_tests {
|
||||
}));
|
||||
assert!(shadow_polygons_project(&p4, sun, None).is_empty());
|
||||
}
|
||||
|
||||
/// [149] Baum-Objekt: Schattenlänge nach eigener Höhe und Krone (nicht `sunStudy.treeHeight`), Form zählt.
|
||||
#[test]
|
||||
fn baum_objekt_schatten_nach_hoehe() {
|
||||
let sun = SunPosition { azimuth: 180.0, elevation: 45.0 };
|
||||
let mk = |h: f64, d: f64, shape: &str| {
|
||||
project_json(serde_json::json!({
|
||||
"sunStudy": {"when": "2026-06-21T10:00:00Z", "show": true, "treeHeight": 30.0},
|
||||
"trees": [{"id": "t", "type": "tree", "floorId": "eg", "categoryCode": "13", "position": {"x": 0, "y": 0},
|
||||
"trunkDiameter": 0.4, "crownDiameter": d, "crownBase": 2.0, "height": h, "shape": shape,
|
||||
"status": "existing", "foliage": "deciduous"}]
|
||||
}))
|
||||
};
|
||||
// 45°: Spitze (Kegel) wirft bis y = h, Kronenbreite ±r.
|
||||
let b = bbox(&shadow_polygons_project(&mk(12.0, 4.0, "conical"), sun, None));
|
||||
assert!((b[3] - 12.0).abs() < 0.05 && (b[2] - 2.0).abs() < 0.05 && b[1] > -0.3, "{b:?}");
|
||||
let b6 = bbox(&shadow_polygons_project(&mk(6.0, 4.0, "conical"), sun, None));
|
||||
assert!((b6[3] - 6.0).abs() < 0.05, "{b6:?}");
|
||||
// Breitere Krone, breiterer Schatten; runde Krone endet vor der Spitze-Länge (Kugel: z_c + r·√2).
|
||||
let wide = bbox(&shadow_polygons_project(&mk(12.0, 8.0, "round"), sun, None));
|
||||
assert!((wide[2] - 4.0).abs() < 0.05, "{wide:?}");
|
||||
let a_small = area(&shadow_polygons_project(&mk(12.0, 4.0, "round"), sun, None));
|
||||
let a_wide = area(&shadow_polygons_project(&mk(12.0, 8.0, "round"), sun, None));
|
||||
assert!(a_wide > 2.0 * a_small, "{a_small} {a_wide}");
|
||||
// Kein Baum: kein Schatten.
|
||||
assert!(shadow_polygons_project(&project_json(serde_json::json!({"trees": []})), sun, None).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
//! [149] Baum als eigenes Objekt (`Project.trees`): Abmessungen mit Vorgaben, Kronenprofil nach Form
|
||||
//! (rund, oval, säulenförmig, kegelförmig), Fusshöhe auf dem Gelände, 3D-Netz (Stamm-Zylinder + Krone als
|
||||
//! Rotationskörper mit wenigen Polygonen), Schattenwerfer (Stamm-Prisma + Kronen-Punktwolke) und die
|
||||
//! Silhouette für Schnitt/Ansicht. Das Grundriss-Symbol entsteht in `plan/trees.rs`.
|
||||
//!
|
||||
//! Lage: Fuss an `position` auf dem sichtbaren Gelände (inkl. Baugruben, wie der Schattenwurf [142]),
|
||||
//! sonst auf der UK des Geschosses; dazu `baseOffset`. Höhen über dem Fuss: Kronenansatz `crownBase`,
|
||||
//! Spitze `height`.
|
||||
|
||||
use crate::jsnum;
|
||||
use crate::model::*;
|
||||
|
||||
/// Vorgaben (m), wenn ein Wert fehlt oder unsinnig ist.
|
||||
pub const DEFAULT_TRUNK_DIAMETER: f64 = 0.3;
|
||||
pub const DEFAULT_CROWN_DIAMETER: f64 = 5.0;
|
||||
pub const DEFAULT_HEIGHT: f64 = 10.0;
|
||||
pub const DEFAULT_CROWN_BASE: f64 = 2.5;
|
||||
/// Ebene der Bäume (SIA-Ebenenliste).
|
||||
pub const TREE_CATEGORY: &str = "13";
|
||||
/// Präfix der Pick-Id im Feld `contextObjectId` der Plan-Primitive (`@` = keine Kontext-Element-Id).
|
||||
pub const TREE_PICK_PREFIX: &str = "@tree:";
|
||||
|
||||
/// Stamm- und Kronenfarbe im 3D (sRGB 0–1).
|
||||
pub const TRUNK_RGB: [f64; 3] = [0.42, 0.32, 0.22];
|
||||
pub const CROWN_RGB: [f64; 3] = [0.45, 0.58, 0.33];
|
||||
pub const CONIFER_RGB: [f64; 3] = [0.29, 0.45, 0.30];
|
||||
|
||||
/// Aufgelöste Abmessungen eines Baums in absoluten Höhen.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct TreeGeom {
|
||||
/// Stammmitte.
|
||||
pub c: [f64; 2],
|
||||
/// Fuss (absolute Höhe).
|
||||
pub base: f64,
|
||||
pub trunk_r: f64,
|
||||
pub crown_r: f64,
|
||||
/// Kronenansatz und Spitze (absolute Höhen), `crown_bottom < top`.
|
||||
pub crown_bottom: f64,
|
||||
pub top: f64,
|
||||
pub shape: TreeShape,
|
||||
}
|
||||
|
||||
fn pos(v: f64, d: f64) -> f64 {
|
||||
if v > 0.0 && v.is_finite() {
|
||||
v
|
||||
} else {
|
||||
d
|
||||
}
|
||||
}
|
||||
|
||||
impl TreeGeom {
|
||||
/// Abmessungen des Baums mit Fuss `base`; `None` bei unbrauchbarer Lage.
|
||||
pub fn of(t: &Tree, base: f64) -> Option<TreeGeom> {
|
||||
if !(t.position.x.is_finite() && t.position.y.is_finite() && base.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let h = pos(t.height, DEFAULT_HEIGHT);
|
||||
let crown_r = pos(t.crown_diameter, DEFAULT_CROWN_DIAMETER) / 2.0;
|
||||
// Stamm nie dicker als die Krone.
|
||||
let trunk_r = jsnum::min(pos(t.trunk_diameter, DEFAULT_TRUNK_DIAMETER) / 2.0, crown_r * 0.8);
|
||||
// Kronenansatz zwischen 0 und 90 % der Höhe.
|
||||
let cb = if t.crown_base.is_finite() { t.crown_base.clamp(0.0, 0.9 * h) } else { jsnum::min(DEFAULT_CROWN_BASE, 0.5 * h) };
|
||||
Some(TreeGeom { c: [t.position.x, t.position.y], base, trunk_r, crown_r, crown_bottom: base + cb, top: base + h, shape: t.shape })
|
||||
}
|
||||
|
||||
/// Kronenprofil als (z, r) von unten nach oben, `n` Abschnitte (≥ 2); an den Enden r = 0 (Pole).
|
||||
pub fn profile(&self, n: usize) -> Vec<(f64, f64)> {
|
||||
let n = n.max(2);
|
||||
let (zb, zt, r) = (self.crown_bottom, self.top, self.crown_r);
|
||||
let h = zt - zb;
|
||||
let at = |u: f64| zb + u * h;
|
||||
let half = |s: f64| -> f64 { (1.0 - s * s).max(0.0).sqrt() };
|
||||
match self.shape {
|
||||
TreeShape::Conical => {
|
||||
// Kegel: flache Unterseite (5 % der Kronenhöhe), dann gerade zur Spitze.
|
||||
vec![(zb, 0.0), (at(0.05), r), (at(0.5), r * 0.5 / 0.95), (zt, 0.0)]
|
||||
}
|
||||
_ => (0..=n)
|
||||
.map(|i| {
|
||||
let u = i as f64 / n as f64;
|
||||
let rr = match self.shape {
|
||||
TreeShape::Oval => {
|
||||
// Eiform: breiteste Stelle bei 40 % der Kronenhöhe.
|
||||
let w = 0.4;
|
||||
let s = if u < w { (u - w) / w } else { (u - w) / (1.0 - w) };
|
||||
r * half(s)
|
||||
}
|
||||
TreeShape::Columnar => {
|
||||
// Superellipse (Exponent 4): fast senkrechte Flanken, gerundete Enden.
|
||||
let s = 2.0 * u - 1.0;
|
||||
r * (1.0 - s.powi(4)).max(0.0).powf(0.25)
|
||||
}
|
||||
_ => r * half(2.0 * u - 1.0),
|
||||
};
|
||||
(at(u), if i == 0 || i == n { 0.0 } else { rr })
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Oberkante des Stamms: ein Stück in die Krone hinein (keine Lücke unter der Krone).
|
||||
pub fn trunk_top(&self) -> f64 {
|
||||
self.crown_bottom + 0.25 * (self.top - self.crown_bottom)
|
||||
}
|
||||
|
||||
/// Stamm-Querschnitt als Ring (`n` Ecken, gegen den Uhrzeigersinn).
|
||||
pub fn trunk_ring(&self, n: usize) -> Vec<[f64; 2]> {
|
||||
circle(self.c, self.trunk_r, n)
|
||||
}
|
||||
|
||||
/// Krone als Rotationskörper: Positionen (x, y, z) und Dreiecke (aussen gegen den Uhrzeigersinn).
|
||||
pub fn crown_mesh(&self, rings: usize, seg: usize) -> (Vec<f64>, Vec<u32>) {
|
||||
lathe(self.c, &self.profile(rings), seg)
|
||||
}
|
||||
|
||||
/// Stamm als Prisma: Positionen und Dreiecke.
|
||||
pub fn trunk_mesh(&self, seg: usize) -> (Vec<f64>, Vec<u32>) {
|
||||
crate::columns3d::prism(&self.trunk_ring(seg), self.base, self.trunk_top())
|
||||
}
|
||||
|
||||
/// Punkte der Krone (für den Schatten als konvexe Hülle der projizierten Punkte).
|
||||
pub fn crown_points(&self) -> Vec<[f64; 3]> {
|
||||
let (pos, _) = self.crown_mesh(8, 16);
|
||||
pos.chunks_exact(3).map(|q| [q[0], q[1], q[2]]).collect()
|
||||
}
|
||||
|
||||
/// Silhouette in einer lotrechten Ebene: Umriss der Krone und des Stamms als (s, z), wobei `s` die
|
||||
/// Lage der Stammmitte entlang der Ebene ist.
|
||||
pub fn silhouette(&self, s: f64, n: usize) -> (Vec<[f64; 2]>, Vec<[f64; 2]>) {
|
||||
let prof = self.profile(n);
|
||||
let mut crown: Vec<[f64; 2]> = prof.iter().map(|&(z, r)| [s + r, z]).collect();
|
||||
crown.extend(prof.iter().rev().skip(1).take(prof.len().saturating_sub(2)).map(|&(z, r)| [s - r, z]));
|
||||
crown.dedup();
|
||||
let tr = self.trunk_r;
|
||||
let trunk = vec![[s - tr, self.base], [s + tr, self.base], [s + tr, self.crown_bottom], [s - tr, self.crown_bottom]];
|
||||
(crown, trunk)
|
||||
}
|
||||
}
|
||||
|
||||
/// Kreis als Ring mit `n` Ecken (gegen den Uhrzeigersinn).
|
||||
pub fn circle(c: [f64; 2], r: f64, n: usize) -> Vec<[f64; 2]> {
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
let t = i as f64 / n as f64 * std::f64::consts::TAU;
|
||||
[c[0] + r * jsnum::cos(t), c[1] + r * jsnum::sin(t)]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Rotationskörper um die lotrechte Achse durch `c` aus dem Profil (z, r); r = 0 an einem Ende = Pol.
|
||||
pub fn lathe(c: [f64; 2], prof: &[(f64, f64)], seg: usize) -> (Vec<f64>, Vec<u32>) {
|
||||
let seg = seg.max(3);
|
||||
let mut pos: Vec<f64> = Vec::new();
|
||||
// Je Profilpunkt: Index des ersten Eckpunkts und ob Pol (ein Punkt).
|
||||
let mut rows: Vec<(u32, bool)> = Vec::new();
|
||||
for &(z, r) in prof {
|
||||
let start = (pos.len() / 3) as u32;
|
||||
if r <= 1e-9 {
|
||||
pos.extend([c[0], c[1], z]);
|
||||
rows.push((start, true));
|
||||
} else {
|
||||
for q in circle(c, r, seg) {
|
||||
pos.extend([q[0], q[1], z]);
|
||||
}
|
||||
rows.push((start, false));
|
||||
}
|
||||
}
|
||||
let mut idx: Vec<u32> = Vec::new();
|
||||
let s = seg as u32;
|
||||
for w in rows.windows(2) {
|
||||
let ((a0, pa), (b0, pb)) = (w[0], w[1]);
|
||||
for j in 0..s {
|
||||
let k = (j + 1) % s;
|
||||
let (a, b) = if pa { (a0, a0) } else { (a0 + j, a0 + k) };
|
||||
let (cc, d) = if pb { (b0, b0) } else { (b0 + k, b0 + j) };
|
||||
if a != b && b != cc {
|
||||
idx.extend([a, b, cc]);
|
||||
}
|
||||
if cc != d && a != d {
|
||||
idx.extend([a, cc, d]);
|
||||
}
|
||||
}
|
||||
}
|
||||
(pos, idx)
|
||||
}
|
||||
|
||||
/// Fusshöhen aller Bäume (`Project.trees`, gleiche Reihenfolge): Gelände an der Stammmitte (sichtbares
|
||||
/// Geländenetz inkl. Baugruben), sonst UK des Geschosses; plus `baseOffset`.
|
||||
pub fn bases(p: &Project) -> Vec<f64> {
|
||||
let trees = p.trees.as_deref().unwrap_or(&[]);
|
||||
if trees.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let site = crate::excavation::terrains(p).into_iter().find(|t| t.hidden != Some(true)).map(|t| crate::excavation::site_terrain(p, t)).filter(|st| !st.current().tris.is_empty());
|
||||
let idx = site.as_ref().map(|st| (crate::terrain::TinIndex::new(st.current()), st.datum));
|
||||
trees
|
||||
.iter()
|
||||
.map(|t| {
|
||||
let floor = p.floor(&t.floor_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0));
|
||||
let ground = idx.as_ref().and_then(|(i, datum)| i.z_at(t.position.x, t.position.y).map(|z| z - datum)).filter(|z| z.is_finite());
|
||||
ground.unwrap_or(floor) + t.base_offset.filter(|o| o.is_finite()).unwrap_or(0.0)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Abmessungen aller darstellbaren Bäume mit ihrem Index in `Project.trees`.
|
||||
pub fn geoms(p: &Project) -> Vec<(usize, TreeGeom)> {
|
||||
let b = bases(p);
|
||||
p.trees.as_deref().unwrap_or(&[]).iter().zip(b).enumerate().filter_map(|(i, (t, base))| TreeGeom::of(t, base).map(|g| (i, g))).collect()
|
||||
}
|
||||
|
||||
/// Stamm- und Kronenfarbe eines Baums im 3D.
|
||||
pub fn colors(t: &Tree) -> ([f64; 3], [f64; 3]) {
|
||||
(TRUNK_RGB, if t.foliage == TreeFoliage::Conifer { CONIFER_RGB } else { CROWN_RGB })
|
||||
}
|
||||
|
||||
/// Bezeichnung (Objekt-Info, IFC): Art-Name, sonst „Baum".
|
||||
pub fn label(t: &Tree) -> String {
|
||||
t.species.as_deref().map(str::trim).filter(|s| !s.is_empty()).map_or_else(|| "Baum".to_string(), str::to_string)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn tree(shape: &str) -> Tree {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"id": "t", "type": "tree", "floorId": "eg", "categoryCode": "13", "position": {"x": 1, "y": 2},
|
||||
"trunkDiameter": 0.4, "crownDiameter": 6, "crownBase": 3, "height": 12, "shape": shape,
|
||||
"status": "existing", "foliage": "deciduous"
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Volumen eines geschlossenen Netzes (Divergenzsatz), positiv bei Aussennormalen.
|
||||
fn volume(pos: &[f64], idx: &[u32]) -> f64 {
|
||||
let p = |i: u32| [pos[i as usize * 3], pos[i as usize * 3 + 1], pos[i as usize * 3 + 2]];
|
||||
idx.chunks_exact(3)
|
||||
.map(|t| {
|
||||
let (a, b, c) = (p(t[0]), p(t[1]), p(t[2]));
|
||||
(a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6.0
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modell_mit_vorgaben_und_hin_und_zurueck() {
|
||||
let t = tree("oval");
|
||||
assert_eq!(t.shape, TreeShape::Oval);
|
||||
let back: Tree = serde_json::from_value(serde_json::to_value(&t).unwrap()).unwrap();
|
||||
assert_eq!(back, t);
|
||||
// Fehlende/unsinnige Werte: Vorgaben.
|
||||
let mut u = t.clone();
|
||||
u.height = f64::NAN;
|
||||
u.crown_diameter = -1.0;
|
||||
u.trunk_diameter = 0.0;
|
||||
u.crown_base = 99.0;
|
||||
let g = TreeGeom::of(&u, 0.0).unwrap();
|
||||
assert_eq!(g.top, DEFAULT_HEIGHT);
|
||||
assert_eq!(g.crown_r, DEFAULT_CROWN_DIAMETER / 2.0);
|
||||
assert_eq!(g.trunk_r, DEFAULT_TRUNK_DIAMETER / 2.0);
|
||||
assert!((g.crown_bottom - 0.9 * DEFAULT_HEIGHT).abs() < 1e-12);
|
||||
u.position.x = f64::NAN;
|
||||
assert!(TreeGeom::of(&u, 0.0).is_none());
|
||||
// Unbekannte Form/Bestand lesen sich ohne Fehler.
|
||||
let w: Tree = serde_json::from_value(serde_json::json!({"id": "x", "shape": "weide", "status": "?"})).unwrap();
|
||||
assert_eq!(w.shape, TreeShape::Unknown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn netz_geschlossen_aussen_und_flach() {
|
||||
for shape in ["round", "oval", "columnar", "conical"] {
|
||||
let g = TreeGeom::of(&tree(shape), 1.0).unwrap();
|
||||
let (pos, idx) = g.crown_mesh(8, 12);
|
||||
assert!(crate::wall_mesh_cut::is_watertight(&pos, &idx, 1e-9), "{shape}: Krone nicht dicht");
|
||||
let v = volume(&pos, &idx);
|
||||
assert!(v > 0.0, "{shape}: Krone innen nach aussen ({v})");
|
||||
// Niedrige Polygonzahl.
|
||||
assert!(idx.len() / 3 <= 200, "{shape}: {} Dreiecke", idx.len() / 3);
|
||||
// Ausdehnung: Kronenradius, Kronenansatz bis Spitze.
|
||||
let zs: Vec<f64> = pos.chunks_exact(3).map(|q| q[2]).collect();
|
||||
assert!((zs.iter().cloned().fold(f64::INFINITY, f64::min) - 4.0).abs() < 1e-9);
|
||||
assert!((zs.iter().cloned().fold(f64::NEG_INFINITY, f64::max) - 13.0).abs() < 1e-9);
|
||||
let rmax = pos.chunks_exact(3).map(|q| (q[0] - 1.0).hypot(q[1] - 2.0)).fold(0.0, f64::max);
|
||||
assert!(rmax <= 3.0 + 1e-9 && rmax > 2.5, "{shape}: {rmax}");
|
||||
let (tp, ti) = g.trunk_mesh(8);
|
||||
assert!(volume(&tp, &ti).abs() > 0.0);
|
||||
}
|
||||
// Kegel: Volumen ≈ π r² h / 3 (unten flach).
|
||||
let g = TreeGeom::of(&tree("conical"), 0.0).unwrap();
|
||||
let (pos, idx) = g.crown_mesh(8, 48);
|
||||
let v = volume(&pos, &idx);
|
||||
let cone = std::f64::consts::PI * 9.0 * 9.0 / 3.0;
|
||||
assert!((v / cone - 1.0).abs() < 0.1, "{v} vs {cone}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn silhouette_nach_form() {
|
||||
let g = TreeGeom::of(&tree("columnar"), 0.0).unwrap();
|
||||
let (crown, trunk) = g.silhouette(5.0, 16);
|
||||
let xs = |r: &[[f64; 2]]| (r.iter().map(|q| q[0]).fold(f64::INFINITY, f64::min), r.iter().map(|q| q[0]).fold(f64::NEG_INFINITY, f64::max));
|
||||
let (a, b) = xs(&crown);
|
||||
assert!((a - 2.0).abs() < 1e-6 && (b - 8.0).abs() < 1e-6, "{a} {b}");
|
||||
assert!((xs(&trunk).0 - 4.8).abs() < 1e-12);
|
||||
// Säule ist auf halber Höhe zwischen Viertel und Dreiviertel fast voll breit, die Kugel nicht.
|
||||
let width_at = |g: &TreeGeom, u: f64| {
|
||||
let z = g.crown_bottom + u * (g.top - g.crown_bottom);
|
||||
let pr = g.profile(64);
|
||||
pr.windows(2).find(|w| w[0].0 <= z && z <= w[1].0).map(|w| w[0].1.max(w[1].1)).unwrap()
|
||||
};
|
||||
let round = TreeGeom::of(&tree("round"), 0.0).unwrap();
|
||||
assert!(width_at(&g, 0.25) > 0.95 * 3.0 && width_at(&round, 0.25) < 0.9 * 3.0);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user