[K4][G10] Merge: Aufräumen (tote TS-/Rust-Doppelspuren), id-Index, Commit ohne Kopie, Punkttyp im Kern; Tests unter Last stabil
CLAUDE.md: Dokument im Kern, Modulkarte nachgeführt. Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
53 files changed
+1293
-1043
No files matched your search
@@ -654,9 +654,9 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern
|
||||
Last; Stand nach dem Nachtrag unten): Wand-Griff an Position 10/1500/2990 32/150/315 µs → 28/116/262 µs (dominiert von der
|
||||
linearen id-Suche), Polylinien-Griff 78 → 58 µs, Polylinien-Kante 72 → 57 µs, Wand verschieben 131 → 115 µs, Griff an einer
|
||||
5000-Punkte-Polylinie 13,7 → 9,1 ms; Griff-Liste der 5000-Punkte-Polylinie 2,7 → 1,1 ms (kleine Polylinie 2 µs, gleich).
|
||||
Nicht in der Tauri-App geprüft (vitest/Linux, e2e im Browser). Offen: `setPolylineVertexType`
|
||||
Nicht in der Tauri-App geprüft (vitest/Linux, e2e im Browser). ~~Offen: `setPolylineVertexType`
|
||||
(rechnet in `geometry/polylineVertexType.ts`), die lineare id-Suche je Mausschritt (im Kern beim Rechnen und beim Commit,
|
||||
in TS in `applyOps`) und der Commit grosser Polylinien (~9 ms bei 5000 Punkten: Verlauf/Prüfung in `document.rs`/`ops.rs`).
|
||||
in TS in `applyOps`) und der Commit grosser Polylinien (~9 ms bei 5000 Punkten: Verlauf/Prüfung in `document.rs`/`ops.rs`).~~ Erledigt 29.10., s. „Leistung nach der Zusammenführung“.
|
||||
**Objekt-Info im Kern (29.10.)** — erledigt damit (4): `selection_info.rs` (vorher `deriveSelection` in `state/selectionInfo.ts`,
|
||||
~800 Zeilen Rechnung) liefert als Wurzel-Abfrage `selectionInfo` den Kontrakt `Selection` für das erste gewählte Element
|
||||
(Vorrang wie bisher): effektive Farbe/Strichstärke/Schraffur/Vorder-/Hintergrund (Element → Linienstil → Ebene → Bauteil),
|
||||
@@ -726,6 +726,50 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern
|
||||
löschen (`editors/splitJoin.ts`, App) — dort ersetzt `cutSegment` per `replace` mit NEUER id (hängt an statt
|
||||
zu ersetzen; beim Port prüfen); Fang-Kandidaten aus dem Modell (`tools/snapping.ts`: `baseSegments`,
|
||||
Kreise, Raum-Anker; Nahmodus ab 2000 Zeichnungen) → `snap.rs`.
|
||||
**Leistung nach der Zusammenführung (29.10.)** — erledigt damit die Offen-Punkte der Griffe/Objekt-Info:
|
||||
(a) **id-Suche indiziert:** der Positions-Index des Dokuments (`PosCache`) wird ab der ersten Suche gebaut (Listen
|
||||
≥ 32), überlebt `add` am Ende und ist über `Lookup` (`Document::lookup`) auch für die Wurzel-Abfragen da — Griffe
|
||||
(`grips::run`) und Objekt-Info (`selection_info::derive`) suchen nicht mehr linear; die Fassade schickt keine
|
||||
Lage-Hinweise mehr (`at` entfällt, TS-`findIndex` je Darstellung weg). TS-`applyOps` bekommt je Op die vom Kern
|
||||
getroffene Position (`doc_last_hits` nach Commit/Griff/Undo/Redo, nachgeprüft) und sucht nicht mehr; ohne Hinweis
|
||||
(`findItem`) hilft `indexOfId` (Index je Listen-Linie, ab der zweiten Suche — ein `Map` über 20 000 ids kostet in
|
||||
V8 ~6 ms, das 20-fache einer linearen Suche). (b) **Commit ohne Kopie:** die Ops gehen ins Dokument über (Prüfung
|
||||
der Werte vor, der doppelten ids nach dem Anwenden, `ops::value_problems`/`add_dup_problem`); der Verlauf hält nur
|
||||
noch die inversen Ops, den Redo-Schritt liefert das Rückgängigmachen selbst (Inverse der Inversen) — halber
|
||||
Verlaufsspeicher, keine Vorwärts-Kopie/-Verdichtung je Mausschritt. Nativ: Commit einer 5000-Punkte-Polylinie
|
||||
4,1 → 1,5 ms (`messung_grosse_polylinie`). (c) **Dach-Firsthöhe** nach Inhalt gemerkt (Hash + Vergleich, bis 4096
|
||||
Einträge) statt der letzten 16 Dächer. (d) **`setPolylineVertexType` im Kern:** `polyline_vertex.rs` (Ecke/Bogen/
|
||||
Spline, `tan` neu in `jsnum`), Griff-Änderung `vertexType`, Kontextmenü über `polyline_vertex_info`; TS-Rechnung
|
||||
gelöscht (`withVertexType`). Gleichheit (einmalig, Test gelöscht): 143 880 Fälle (offene/geschlossene Polylinien,
|
||||
doppelte/kollineare Punkte, fehlende Bögen, Massstäbe 1e-4…1e5) bitgleich, `vertexTypeOf`/`canSetVertexType` gleich.
|
||||
Abweichung (gewollt): keine Änderung → keine Op (vorher ein leerer Undo-Schritt), ein Index ohne Punkt ändert nichts.
|
||||
Messung (vitest/Store, 3000 Wände + 20 000 Zeichnungen + 40 Dächer, `objectInfo.perf.test.ts`, alt/neu abwechselnd,
|
||||
Container stark unter Last — Werte streuen ±50 %): Objekt-Info Zeichnung (Pos. 10 000) 257–304 → 10–15 µs, Wand
|
||||
91–316 → 36–209 µs (ruhig gemessen: 47 µs, davon Kern 36 µs), Dach (40 im Wechsel) 44–109 → 40–102 µs; Griff an
|
||||
Zeichnung 15 000 1,9–4,9 ms → 0,19–0,34 ms, Wand an Pos. 1500/2990 129–418 → 55–122 µs; Griff 5000-Punkte-Polylinie
|
||||
14–16 → 6,6–10 ms (Rest: JSON 200 KB hin und Parse in TS ≈ 2 ms, neue Polylinie im Kern); Punkttyp kleine Polylinie
|
||||
~1 ms → 0,2–0,5 ms, 5000 Punkte 18–22 → 9–16 ms; Auswahl (300 Wände) verschieben unverändert (5–11 ms). Bleibt:
|
||||
die Kopie der Liste in TS je Änderung (`slice` von 20 000 Elementen ≈ 0,14 ms) — Preis der unveränderlichen
|
||||
Leseansicht. Nicht in der Tauri-App geprüft.
|
||||
**Aufräumen nach den parallelen Ports (29.10.):** Suche nach toten Exporten (Skript über alle `src/**/*.ts`:
|
||||
Export ohne Nutzer ausser Tests/Fassade) und toten Bindungen (`#[wasm_bindgen]` ohne TS-Aufrufer), dazu
|
||||
`cargo clippy` (dead_code, auch Web-Build). Gelöscht (TS): `wallVerticalExtent`/`ceilingVerticalExtent`/
|
||||
`columnVerticalExtent` (`model/wall.ts`, Aufrufer `toSection`/`voids`/`sectionOpenings`/`toElevation` gab es
|
||||
nicht mehr; Tests über die Kern-Abfrage `verticalExtents` bzw. Rust-Tests), `openingVerticalExtent`/
|
||||
`wallAxisFrame`/`openingCenter` (`geometry/opening.ts`), `isValidOutline`/`outlineCentroid`, `getStairType`/
|
||||
`openingsOfWall`/`openingLabel`/`columnLabel`/`getComponent` (`types.ts`), `MONO_INK`/`WALL_FALLBACK_MM`,
|
||||
`scatterStrokes`, `ShaderProgram`, `SLAB_RGB`/`DRAWING_LINE_FALLBACK_RGB`, `booleanMesh` samt Typen,
|
||||
`meshBytesToImportedMeshes`, `IDEAL_RISER`, `bulgeBetweenAngles`, `pointSegDistPx`, `coreReady`. Bindungen:
|
||||
`doc_query`, `core_version`, `drawing3d_line_verts`/`drawing3d_pick_segs` (`web/drawing2d_3d.rs`),
|
||||
`bulge_between_angles`, `scatter_strokes_flat`. Rust zusammengelegt: Höhenregeln (UK/OK von Wand/Stütze/Decke,
|
||||
Geschoss-Bindung) einmal in `model/helpers.rs::heights` für typisierte Sicht und rohe Wurzel (`selection_info.rs`);
|
||||
JS-Wahrheitswert `truthy` (vorher je eine Kopie in `geo_translate`/`layers`/`pens`) aus `grips`; `finite` →
|
||||
`jsnum::or_zero` (Kopien in `kennzahlen`/`flaechen`/`room_program`); JS-`String(v)` einmal in
|
||||
`js_fmt::js_string` (vorher `project_format` und `selection_info`, letztere ohne Listen); `arr` aus `grips`.
|
||||
Bleibt bewusst: TS-Fassaden,
|
||||
die nur Tests nutzen (`solidVolume`, `withoutHoles`, `straightSkeleton`, `stairCut`, `triangulate`,
|
||||
Schraffur-Clipping in `glPlanHatch.ts`, `subtractRings` — prüfen Kern-Bindungen von TS aus), mehrere
|
||||
`signed_area`/`bbox`-Varianten in Rust (verschiedene Punkt-Typen, teils mit JS-Semantik `jsnum::min`).
|
||||
- ◐ **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
|
||||
|
||||
+267
-150
@@ -8,9 +8,10 @@
|
||||
|
||||
use crate::model::Project;
|
||||
pub use crate::ops::Op;
|
||||
use crate::ops::{has_dup, id_of, unique_ids, History};
|
||||
use crate::ops::{has_dup, id_of, unique_ids, History, Step};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Map, Value};
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
@@ -28,9 +29,12 @@ pub struct Document {
|
||||
revs: Revs,
|
||||
/// Caches der Plan-Erzeugung (`plan::cache`), gültig über [`Revs`].
|
||||
plan_cache: crate::plan::cache::PlanCache,
|
||||
/// id → Position je Liste über die Aufrufe hinweg (eine Änderung an einem Element einer grossen
|
||||
/// Liste sucht dann nicht jedes Mal linear); jede Op ausser `replace` verwirft ihre Liste.
|
||||
pos: PosCache,
|
||||
/// id → Position je Liste über die Aufrufe hinweg (s. [`PosCache`]); in einer `RefCell`, damit auch
|
||||
/// lesende Abfragen ([`Lookup`]) den Index bauen und nutzen.
|
||||
pos: RefCell<PosCache>,
|
||||
/// Je Op der zuletzt angewendeten Folge (Commit, Abgleich, Undo/Redo) die Position des von `replace`
|
||||
/// getroffenen Elements: TS führt die Leseansicht damit ohne Suche nach ([`Document::last_hits`]).
|
||||
last_hits: Vec<Option<usize>>,
|
||||
}
|
||||
|
||||
/// Änderungsstände ([K4], Caches der Ableitungen): ein globaler Zähler; jede Op vergibt ihrem Feld
|
||||
@@ -92,53 +96,91 @@ impl Revs {
|
||||
&self.items[key]
|
||||
}
|
||||
|
||||
/// Element-Stände nach einer Op auf der Liste nachführen (`before` = Länge vor der Op).
|
||||
fn item_op(&mut self, op: &Op, before: usize, removed: Option<&[bool]>, hit: Option<usize>) {
|
||||
let key = op.key();
|
||||
/// Element-Stände nach einer Op auf der Liste `key` nachführen (`before` = Länge vor der Op).
|
||||
fn item_op(&mut self, key: &str, shape: Shape, before: usize, removed: Option<&[bool]>, hit: Option<usize>) {
|
||||
self.touch(key);
|
||||
let Some(mut v) = self.items.remove(key) else { return };
|
||||
if v.len() != before {
|
||||
return;
|
||||
}
|
||||
match op {
|
||||
Op::Add { items, at, .. } => {
|
||||
match shape {
|
||||
Shape::Add { n, at } => {
|
||||
let at = at.map_or(v.len(), |a| a.min(v.len()));
|
||||
let start = self.counter;
|
||||
self.counter += items.len() as u64;
|
||||
v.splice(at..at, start + 1..=start + items.len() as u64);
|
||||
self.counter += n as u64;
|
||||
v.splice(at..at, start + 1..=start + n as u64);
|
||||
}
|
||||
Op::Replace { .. } => match hit {
|
||||
Shape::Replace => match hit {
|
||||
Some(i) if i < v.len() => v[i] = self.next(),
|
||||
Some(_) => return,
|
||||
None => v.push(self.next()),
|
||||
},
|
||||
Op::Remove { .. } => match removed {
|
||||
Shape::Remove => match removed {
|
||||
Some(keep) if keep.len() == v.len() => {
|
||||
let mut k = keep.iter();
|
||||
v.retain(|_| *k.next().unwrap_or(&false));
|
||||
}
|
||||
_ => return,
|
||||
},
|
||||
Op::Reorder { .. } | Op::SetField { .. } => return,
|
||||
Shape::Other => return,
|
||||
}
|
||||
self.items.insert(key.to_owned(), v);
|
||||
}
|
||||
}
|
||||
|
||||
/// id → Position je Liste für die Dauer einer Op-Folge. Nur `replace` sucht darüber; jede andere Op
|
||||
/// auf der Liste verwirft den Eintrag. Erst die zweite Suche in derselben Liste baut den Index —
|
||||
/// ein einzelner Drag-Schritt bleibt bei der linearen Suche, Serien (Auswahl verschieben: hunderte
|
||||
/// `replace`) kosten so O(Liste + Ops) statt O(Liste · Ops). Gleiche Semantik wie `position`
|
||||
/// (erstes Vorkommen). Schlüssel ist ein Hash der id (keine Text-Kopien); jeder Treffer wird an der
|
||||
/// Liste nachgeprüft, bei einer Kollision sucht `find` linear.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct PosCache(HashMap<String, PosEntry>);
|
||||
/// Art einer Op für die Element-Stände (die Op selbst ist beim Nachführen schon ins Dokument übergegangen).
|
||||
#[derive(Clone, Copy)]
|
||||
enum Shape {
|
||||
Add { n: usize, at: Option<usize> },
|
||||
Replace,
|
||||
Remove,
|
||||
Other,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum PosEntry {
|
||||
/// Einmal linear gesucht.
|
||||
Once,
|
||||
Built(HashMap<u64, usize>),
|
||||
impl Shape {
|
||||
fn of(op: &Op) -> Shape {
|
||||
match op {
|
||||
Op::Add { items, at, .. } => Shape::Add { n: items.len(), at: *at },
|
||||
Op::Replace { .. } => Shape::Replace,
|
||||
Op::Remove { .. } => Shape::Remove,
|
||||
Op::Reorder { .. } | Op::SetField { .. } => Shape::Other,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// id → Position je Liste, über die Aufrufe hinweg im Dokument gehalten: `replace` (Commit, Undo/Redo)
|
||||
/// und die Abfragen, die ein Element per id suchen (Griffe, Objekt-Info, s. [`Lookup`]), finden es ab
|
||||
/// der ersten Suche über den Index statt linear (eine Änderung an einem Element einer grossen Liste
|
||||
/// kostete je Mausschritt eine lineare Suche im Kern und eine in TS). `add` am Ende führt den Index
|
||||
/// nach, jede andere Struktur-Op (`add` mitten hinein, `remove`, `reorder`, `setField`) verwirft ihn.
|
||||
/// Kleine Listen bleiben linear. Gleiche Semantik wie `position` (erstes Vorkommen). Schlüssel ist ein
|
||||
/// Hash der id (keine Text-Kopien); jeder Treffer wird an der Liste nachgeprüft, bei einer Kollision
|
||||
/// sucht `find` linear.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct PosCache(HashMap<String, IdIndex>);
|
||||
|
||||
/// Index id-Hash → Position einer Liste.
|
||||
type IdIndex = HashMap<u64, usize, std::hash::BuildHasherDefault<IdHasher>>;
|
||||
|
||||
/// Ab dieser Länge baut `find` einen Index (darunter ist die lineare Suche billiger).
|
||||
const INDEX_MIN_LEN: usize = 32;
|
||||
|
||||
/// Reicht den schon gestreuten id-Hash ([`id_hash`]) durch (kein zweites Hashen).
|
||||
#[derive(Default)]
|
||||
struct IdHasher(u64);
|
||||
|
||||
impl std::hash::Hasher for IdHasher {
|
||||
fn finish(&self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
fn write(&mut self, bytes: &[u8]) {
|
||||
for b in bytes {
|
||||
self.0 = (self.0 ^ *b as u64).wrapping_mul(0x0000_0100_0000_01b3);
|
||||
}
|
||||
}
|
||||
fn write_u64(&mut self, n: u64) {
|
||||
self.0 = n;
|
||||
}
|
||||
}
|
||||
|
||||
/// FNV-1a über die id.
|
||||
@@ -152,32 +194,28 @@ impl PosCache {
|
||||
let Some(id) = id else {
|
||||
return linear(None);
|
||||
};
|
||||
match self.0.get(collection) {
|
||||
Some(PosEntry::Built(m)) => match m.get(&id_hash(id)) {
|
||||
Some(&i) if list.get(i).and_then(id_of) == Some(id) => Some(i),
|
||||
Some(_) => linear(Some(id)),
|
||||
None => None,
|
||||
},
|
||||
Some(PosEntry::Once) => {
|
||||
let mut m: HashMap<u64, usize> = HashMap::with_capacity(list.len());
|
||||
for (i, e) in list.iter().enumerate() {
|
||||
if let Some(x) = id_of(e) {
|
||||
m.entry(id_hash(x)).or_insert(i);
|
||||
}
|
||||
if list.len() < INDEX_MIN_LEN {
|
||||
return linear(Some(id));
|
||||
}
|
||||
let m = self.0.entry(collection.to_owned()).or_insert_with(|| {
|
||||
let mut m = IdIndex::with_capacity_and_hasher(list.len(), Default::default());
|
||||
for (i, e) in list.iter().enumerate() {
|
||||
if let Some(x) = id_of(e) {
|
||||
m.entry(id_hash(x)).or_insert(i);
|
||||
}
|
||||
self.0.insert(collection.to_owned(), PosEntry::Built(m));
|
||||
self.find(collection, list, Some(id))
|
||||
}
|
||||
None => {
|
||||
self.0.insert(collection.to_owned(), PosEntry::Once);
|
||||
linear(Some(id))
|
||||
}
|
||||
m
|
||||
});
|
||||
match m.get(&id_hash(id)) {
|
||||
Some(&i) if list.get(i).and_then(id_of) == Some(id) => Some(i),
|
||||
Some(_) => linear(Some(id)),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Element `id` wurde an Position `at` angehängt (`replace` ohne Treffer).
|
||||
/// Element `id` wurde an Position `at` angehängt (`replace` ohne Treffer, `add` am Ende).
|
||||
fn pushed(&mut self, collection: &str, id: Option<&str>, at: usize) {
|
||||
if let (Some(PosEntry::Built(m)), Some(id)) = (self.0.get_mut(collection), id) {
|
||||
if let (Some(m), Some(id)) = (self.0.get_mut(collection), id) {
|
||||
m.entry(id_hash(id)).or_insert(at);
|
||||
}
|
||||
}
|
||||
@@ -187,6 +225,29 @@ impl PosCache {
|
||||
}
|
||||
}
|
||||
|
||||
/// Elemente der Projekt-Wurzel per id finden: im Dokument über dessen Positions-Index ([`PosCache`]),
|
||||
/// sonst (Tests, Wurzel ohne Dokument) linear. Für Abfragen auf der rohen Wurzel (Griffe, Objekt-Info).
|
||||
pub struct Lookup<'a> {
|
||||
pub root: &'a Map<String, Value>,
|
||||
pos: Option<&'a RefCell<PosCache>>,
|
||||
}
|
||||
|
||||
impl<'a> Lookup<'a> {
|
||||
/// Ohne Index (lineare Suche).
|
||||
pub fn plain(root: &'a Map<String, Value>) -> Self {
|
||||
Lookup { root, pos: None }
|
||||
}
|
||||
|
||||
/// Erstes Element mit `id` in der Liste `collection`.
|
||||
pub fn find(&self, collection: &str, id: &str) -> Option<&'a Value> {
|
||||
let list = self.root.get(collection).and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]);
|
||||
match self.pos {
|
||||
Some(pos) => pos.borrow_mut().find(collection, list, Some(id)).map(|i| &list[i]),
|
||||
None => list.iter().find(|e| id_of(e) == Some(id)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Document {
|
||||
pub fn from_json(text: &str) -> Result<Document, String> {
|
||||
match serde_json::from_str::<Value>(text) {
|
||||
@@ -204,7 +265,7 @@ impl Document {
|
||||
self.dirty.clear();
|
||||
self.dirty_items.clear();
|
||||
self.revs.reset();
|
||||
self.pos = PosCache::default();
|
||||
self.pos = RefCell::default();
|
||||
self.history.clear();
|
||||
}
|
||||
|
||||
@@ -272,6 +333,17 @@ impl Document {
|
||||
&self.root
|
||||
}
|
||||
|
||||
/// Je Op der zuletzt angewendeten Folge die Position des von `replace` getroffenen Elements (None =
|
||||
/// keine `replace`-Op oder kein Treffer); nach einer Zurückweisung leer.
|
||||
pub fn last_hits(&self) -> &[Option<usize>] {
|
||||
&self.last_hits
|
||||
}
|
||||
|
||||
/// Die Wurzel mit dem Positions-Index des Dokuments (Suche per id, s. [`Lookup`]).
|
||||
pub fn lookup(&self) -> Lookup<'_> {
|
||||
Lookup { root: &self.root, pos: Some(&self.pos) }
|
||||
}
|
||||
|
||||
pub fn field(&self, key: &str) -> Option<&Value> {
|
||||
self.root.get(key)
|
||||
}
|
||||
@@ -285,60 +357,70 @@ impl Document {
|
||||
}
|
||||
|
||||
|
||||
/// Wendet eine Op ohne Aufzeichnung an (Semantik wie `applyOps` in TS). Liefert bei `replace`
|
||||
/// mit Treffer dessen Position; führt die Änderungsstände nach.
|
||||
fn apply_raw(&mut self, op: &Op, pos: &mut PosCache) -> Option<usize> {
|
||||
if !matches!(op, Op::Replace { .. }) {
|
||||
pos.forget(op.key());
|
||||
/// Wendet eine Op ohne Aufzeichnung an (Semantik wie `applyOps` in TS); die Op geht ins Dokument
|
||||
/// über (keine Kopie). Liefert bei `replace` mit Treffer dessen Position; führt die Änderungsstände
|
||||
/// nach.
|
||||
fn apply_raw(&mut self, op: Op, pos: &mut PosCache) -> Option<usize> {
|
||||
let key = op.key().to_owned();
|
||||
let shape = Shape::of(&op);
|
||||
// `add` am Ende einer vorhandenen Liste lässt die Positionen stehen (Index wird nachgeführt).
|
||||
let current = self.root.get(&key).and_then(Value::as_array).map(Vec::len);
|
||||
let appended = matches!(op, Op::Add { at, .. } if current.is_some_and(|n| at.is_none_or(|a| a >= n)));
|
||||
if !matches!(op, Op::Replace { .. }) && !appended {
|
||||
pos.forget(&key);
|
||||
}
|
||||
let before = self.root.get(op.key()).and_then(Value::as_array).map_or(0, Vec::len);
|
||||
let before = current.unwrap_or(0);
|
||||
let mut hit = None;
|
||||
let mut removed = None;
|
||||
match op {
|
||||
Op::SetField { key, value, at } => match value {
|
||||
Some(v) => match at {
|
||||
Some(i) if !self.root.contains_key(key) => {
|
||||
let i = (*i).min(self.root.len());
|
||||
self.root.shift_insert(i, key.clone(), v.clone());
|
||||
Some(i) if !self.root.contains_key(&key) => {
|
||||
let i = i.min(self.root.len());
|
||||
self.root.shift_insert(i, key, v);
|
||||
}
|
||||
_ => {
|
||||
self.root.insert(key.clone(), v.clone());
|
||||
self.root.insert(key, v);
|
||||
}
|
||||
},
|
||||
None => {
|
||||
self.root.shift_remove(key);
|
||||
self.root.shift_remove(&key);
|
||||
}
|
||||
},
|
||||
Op::Add { collection, items, at } => {
|
||||
let list = self.list_mut(collection);
|
||||
let list = self.list_mut(&collection);
|
||||
let at = at.map_or(list.len(), |a| a.min(list.len()));
|
||||
list.splice(at..at, items.iter().cloned());
|
||||
if appended {
|
||||
for (k, e) in items.iter().enumerate() {
|
||||
pos.pushed(&collection, id_of(e), at + k);
|
||||
}
|
||||
}
|
||||
list.splice(at..at, items);
|
||||
}
|
||||
Op::Replace { collection, entity } => {
|
||||
let list = self.list_mut(collection);
|
||||
let id = id_of(entity);
|
||||
match pos.find(collection, list, id) {
|
||||
let list = self.list_mut(&collection);
|
||||
match pos.find(&collection, list, id_of(&entity)) {
|
||||
Some(i) => {
|
||||
list[i] = entity.clone();
|
||||
list[i] = entity;
|
||||
hit = Some(i);
|
||||
}
|
||||
None => {
|
||||
list.push(entity.clone());
|
||||
pos.pushed(collection, id, list.len() - 1);
|
||||
pos.pushed(&collection, id_of(&entity), list.len());
|
||||
list.push(entity);
|
||||
}
|
||||
}
|
||||
}
|
||||
Op::Remove { collection, ids } => {
|
||||
let drop: HashSet<&str> = ids.iter().map(String::as_str).collect();
|
||||
let tracked = self.revs.items.contains_key(collection.as_str());
|
||||
let list = self.list_mut(collection);
|
||||
let list = self.list_mut(&collection);
|
||||
if tracked {
|
||||
removed = Some(list.iter().map(|e| !id_of(e).is_some_and(|i| drop.contains(i))).collect::<Vec<bool>>());
|
||||
}
|
||||
list.retain(|e| !id_of(e).is_some_and(|i| drop.contains(i)));
|
||||
}
|
||||
Op::Reorder { collection, ids } => {
|
||||
let list = std::mem::take(self.list_mut(collection));
|
||||
let list = std::mem::take(self.list_mut(&collection));
|
||||
let listed: HashSet<&str> = ids.iter().map(String::as_str).collect();
|
||||
let mut by_id: HashMap<&str, &Value> = HashMap::new();
|
||||
for e in &list {
|
||||
@@ -349,44 +431,44 @@ impl Document {
|
||||
}
|
||||
let mut ordered: Vec<Value> = ids.iter().filter_map(|id| by_id.get(id.as_str()).map(|e| (*e).clone())).collect();
|
||||
ordered.extend(list.iter().filter(|e| !id_of(e).is_some_and(|i| listed.contains(i))).cloned());
|
||||
*self.list_mut(collection) = ordered;
|
||||
*self.list_mut(&collection) = ordered;
|
||||
}
|
||||
}
|
||||
self.revs.item_op(op, before, removed.as_deref(), hit);
|
||||
self.revs.item_op(&key, shape, before, removed.as_deref(), hit);
|
||||
hit
|
||||
}
|
||||
|
||||
/// Nach einer angenommenen Op: was die typisierte Sicht neu lesen muss (ein Element nach
|
||||
/// `replace` mit Treffer, sonst das Feld).
|
||||
fn mark_dirty(&mut self, op: &Op, hit: Option<usize>) {
|
||||
match (op, hit) {
|
||||
(Op::Replace { collection, .. }, Some(i)) if self.typed.is_some() => self.dirty_items.push((collection.clone(), i)),
|
||||
fn mark_dirty(&mut self, key: String, replace: bool, hit: Option<usize>) {
|
||||
match hit {
|
||||
Some(i) if replace && self.typed.is_some() => self.dirty_items.push((key, i)),
|
||||
_ => {
|
||||
self.dirty.insert(op.key().to_owned());
|
||||
self.dirty.insert(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Wendet eine Op an und liefert (inverse Ops in Anwendungsreihenfolge, ob die Vorwärts-Op als
|
||||
/// `add` aufzuzeichnen ist — `replace` ohne Treffer). Listen bekommen feine Inverse (`replace` ↔ altes Element, `add` ↔ `remove`,
|
||||
/// Wendet eine Op an und liefert (inverse Ops in Anwendungsreihenfolge, Treffer-Position bei
|
||||
/// `replace`). Listen bekommen feine Inverse (`replace` ↔ altes Element, `add` ↔ `remove`,
|
||||
/// `remove` ↔ `add` an den alten Positionen, `reorder` ↔ alte Reihenfolge), wo das exakt ist
|
||||
/// (`add`: ids neu und eindeutig; `reorder`: alle ids eindeutig); sonst (fehlendes Feld, kein
|
||||
/// Array, Alt-Doppelungen) wird das ganze Feld samt Position gesichert. Ohne Hash über die ganze
|
||||
/// Liste — ein Drag-Schritt kostet nur das Suchen des Elements.
|
||||
fn apply_recorded(&mut self, op: &Op, pos: &mut PosCache) -> (Vec<Op>, bool, Option<usize>) {
|
||||
/// Liste — ein Drag-Schritt kostet nur das Suchen des Elements; das neue Element geht ohne Kopie
|
||||
/// ins Dokument, das alte in die inverse Op.
|
||||
fn apply_recorded(&mut self, op: Op, pos: &mut PosCache) -> (Vec<Op>, Option<usize>) {
|
||||
let key = op.key();
|
||||
let old = self.root.get(key);
|
||||
let snapshot = || {
|
||||
let at = self.root.keys().position(|k| k == key);
|
||||
Op::SetField { key: key.to_owned(), value: old.cloned(), at }
|
||||
};
|
||||
let clean = match op {
|
||||
let clean = match &op {
|
||||
Op::SetField { .. } => None,
|
||||
Op::Reorder { .. } => old.and_then(Value::as_array).filter(|a| a.iter().all(|e| id_of(e).is_some()) && unique_ids(a)),
|
||||
_ => old.and_then(Value::as_array),
|
||||
};
|
||||
let mut as_add = false;
|
||||
let inverse = match (op, clean) {
|
||||
let inverse = match (&op, clean) {
|
||||
(_, None) => vec![snapshot()],
|
||||
(Op::Add { collection, items, .. }, Some(list)) => {
|
||||
let mut new_ids: HashSet<&str> = HashSet::with_capacity(items.len());
|
||||
@@ -401,17 +483,14 @@ impl Document {
|
||||
(Op::Replace { collection, entity }, Some(list)) => match pos.find(collection, list, id_of(entity)) {
|
||||
Some(i) => {
|
||||
// Direkt ersetzen (spart die zweite Suche in `apply_raw`).
|
||||
let list = self.root.get_mut(key).and_then(Value::as_array_mut).expect("Liste geprüft");
|
||||
let n = list.len();
|
||||
let prev = std::mem::replace(&mut list[i], entity.clone());
|
||||
self.revs.item_op(op, n, None, Some(i));
|
||||
return (vec![Op::Replace { collection: collection.clone(), entity: prev }], false, Some(i));
|
||||
}
|
||||
None => {
|
||||
// Aufgezeichnet als `add` (so trifft jedes aufgezeichnete `replace` ein vorhandenes Element).
|
||||
as_add = true;
|
||||
vec![Op::Remove { collection: collection.clone(), ids: vec![id_of(entity).unwrap_or("").to_owned()] }]
|
||||
let Op::Replace { collection, entity } = op else { unreachable!() };
|
||||
let list = self.root.get_mut(&collection).and_then(Value::as_array_mut).expect("Liste geprüft");
|
||||
let prev = std::mem::replace(&mut list[i], entity);
|
||||
self.revs.item_op(&collection, Shape::Replace, n, None, Some(i));
|
||||
return (vec![Op::Replace { collection, entity: prev }], Some(i));
|
||||
}
|
||||
None => vec![Op::Remove { collection: collection.clone(), ids: vec![id_of(entity).unwrap_or("").to_owned()] }],
|
||||
},
|
||||
(Op::Remove { collection, ids }, Some(list)) => {
|
||||
let drop: HashSet<&str> = ids.iter().map(String::as_str).collect();
|
||||
@@ -435,116 +514,128 @@ impl Document {
|
||||
(Op::SetField { .. }, Some(_)) => unreachable!("setField hat keine Liste"),
|
||||
};
|
||||
let hit = self.apply_raw(op, pos);
|
||||
(inverse, as_add, hit)
|
||||
(inverse, hit)
|
||||
}
|
||||
|
||||
/// Wendet `ops` atomar an und prüft sie (`ops::validate`). Verstösse → `Err(Meldungen)`,
|
||||
/// Dokument unverändert. Ok → (je Op: als `add` aufzuzeichnen, inverse Ops). `sanitize`: die Ops
|
||||
/// können Nicht-endlich-Marken enthalten (s. `ops.rs`).
|
||||
fn apply_checked(&mut self, ops: &[Op], sanitize: bool) -> Result<(Vec<bool>, Vec<Op>), Vec<String>> {
|
||||
/// Wendet `ops` an und liefert die inversen Ops (Anwendungsreihenfolge), ohne Prüfung (Undo/Redo:
|
||||
/// die Inverse eines Schritts ist der Gegenschritt).
|
||||
fn apply_inverting(&mut self, ops: Vec<Op>) -> Vec<Op> {
|
||||
let mut pos = self.pos.take();
|
||||
self.last_hits.clear();
|
||||
let mut inverses: Vec<Vec<Op>> = Vec::with_capacity(ops.len());
|
||||
for op in ops {
|
||||
let (key, replace) = (op.key().to_owned(), matches!(op, Op::Replace { .. }));
|
||||
let (inv, hit) = self.apply_recorded(op, &mut pos);
|
||||
self.mark_dirty(key, replace, hit);
|
||||
self.last_hits.push(hit);
|
||||
inverses.push(inv);
|
||||
}
|
||||
*self.pos.get_mut() = pos;
|
||||
inverses.into_iter().rev().flatten().collect()
|
||||
}
|
||||
|
||||
/// Wendet `ops` atomar an und prüft sie (`ops::validate`, Werte vor dem Anwenden, neue doppelte ids
|
||||
/// danach — die Ops gehen ohne Kopie ins Dokument über). Verstösse → `Err(Meldungen)`, Dokument
|
||||
/// unverändert. Ok → inverse Ops. `sanitize`: die Ops können Nicht-endlich-Marken enthalten
|
||||
/// (s. `ops.rs`).
|
||||
fn apply_checked(&mut self, ops: Vec<Op>, sanitize: bool) -> Result<Vec<Op>, Vec<String>> {
|
||||
// Alt-Doppelungen der Listen merken, in die eingefügt oder die gesetzt wird.
|
||||
let mut had_dup: HashSet<String> = HashSet::new();
|
||||
for op in ops {
|
||||
for op in &ops {
|
||||
if matches!(op, Op::Add { .. } | Op::SetField { .. }) && !had_dup.contains(op.key()) && has_dup(self.root.get(op.key())) {
|
||||
had_dup.insert(op.key().to_owned());
|
||||
}
|
||||
}
|
||||
let mut inverses: Vec<Vec<Op>> = Vec::with_capacity(ops.len());
|
||||
let mut as_add: Vec<bool> = Vec::with_capacity(ops.len());
|
||||
let mut hits: Vec<Option<usize>> = Vec::with_capacity(ops.len());
|
||||
let mut pos = std::mem::take(&mut self.pos);
|
||||
let had = |k: &str| had_dup.contains(k);
|
||||
let n = ops.len();
|
||||
let mut inverses: Vec<Vec<Op>> = Vec::with_capacity(n);
|
||||
let mut hits: Vec<Option<usize>> = Vec::with_capacity(n);
|
||||
// Je Op: Feld, ob `replace`, ob `add`, Befunde der Werte.
|
||||
let mut info: Vec<(String, bool, bool, Vec<String>)> = Vec::with_capacity(n);
|
||||
let mut pos = self.pos.take();
|
||||
for op in ops {
|
||||
let (inv, add, hit) = self.apply_recorded(op, &mut pos);
|
||||
let mut found = Vec::new();
|
||||
crate::ops::value_problems(&op, &had, &mut found);
|
||||
info.push((op.key().to_owned(), matches!(op, Op::Replace { .. }), matches!(op, Op::Add { .. }), found));
|
||||
let (inv, hit) = self.apply_recorded(op, &mut pos);
|
||||
inverses.push(inv);
|
||||
as_add.push(add);
|
||||
hits.push(hit);
|
||||
}
|
||||
let problems = crate::ops::validate(&self.root, ops, &|k| had_dup.contains(k));
|
||||
let mut problems = Vec::new();
|
||||
let mut dup_checked: HashSet<&str> = HashSet::new();
|
||||
for (key, _, add, found) in &mut info {
|
||||
problems.append(found);
|
||||
if *add && dup_checked.insert(key.as_str()) {
|
||||
problems.extend(crate::ops::add_dup_problem(&self.root, key, &had));
|
||||
}
|
||||
}
|
||||
if !problems.is_empty() {
|
||||
// Nach der Rücknahme gilt keine gemerkte Position mehr sicher.
|
||||
let mut pos = PosCache::default();
|
||||
for inv in inverses.iter().rev() {
|
||||
for inv in inverses.into_iter().rev() {
|
||||
for op in inv {
|
||||
self.apply_raw(op, &mut pos);
|
||||
}
|
||||
}
|
||||
self.last_hits.clear();
|
||||
return Err(problems);
|
||||
}
|
||||
self.pos = pos;
|
||||
*self.pos.get_mut() = pos;
|
||||
if sanitize {
|
||||
// Angenommene Nicht-endlich-Marken (zu tief für die Prüfung) als null speichern.
|
||||
let keys: HashSet<&str> = ops.iter().map(Op::key).collect();
|
||||
let keys: HashSet<&str> = info.iter().map(|i| i.0.as_str()).collect();
|
||||
for k in keys {
|
||||
if let Some(v) = self.root.get_mut(k) {
|
||||
crate::ops::sanitize_non_finite(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (op, hit) in ops.iter().zip(hits) {
|
||||
self.mark_dirty(op, hit);
|
||||
for ((key, replace, _, _), hit) in info.into_iter().zip(&hits) {
|
||||
self.mark_dirty(key, replace, *hit);
|
||||
}
|
||||
Ok((as_add, inverses.into_iter().rev().flatten().collect()))
|
||||
self.last_hits = hits;
|
||||
Ok(inverses.into_iter().rev().flatten().collect())
|
||||
}
|
||||
|
||||
/// Wendet `ops` atomar an, ohne Verlauf (Abgleich des Spiegels). Verstösse (NaN, neue
|
||||
/// doppelte ids) → `Err(Meldungen)`, Dokument unverändert.
|
||||
pub fn apply(&mut self, ops: &[Op]) -> Result<(), Vec<String>> {
|
||||
self.apply_checked(ops, false).map(|_| ())
|
||||
self.apply_checked(ops.to_vec(), false).map(|_| ())
|
||||
}
|
||||
|
||||
/// Wie [`Document::apply`]; `sanitize` = die Ops können Nicht-endlich-Marken enthalten.
|
||||
pub fn apply_marked(&mut self, ops: &[Op], sanitize: bool) -> Result<(), Vec<String>> {
|
||||
/// Wie [`Document::apply`] (die Ops gehen ins Dokument über); `sanitize` = die Ops können
|
||||
/// Nicht-endlich-Marken enthalten.
|
||||
pub fn apply_marked(&mut self, ops: Vec<Op>, sanitize: bool) -> Result<(), Vec<String>> {
|
||||
self.apply_checked(ops, sanitize).map(|_| ())
|
||||
}
|
||||
|
||||
/// Eine Benutzer-Änderung: anwenden, prüfen und als Undo-Schritt aufzeichnen (`key` =
|
||||
/// `coalesceKey`, `now` = Zeit in ms für das Koaleszenz-Fenster). Die Ops gehen in den Verlauf
|
||||
/// über (Redo) — das Dokument hält eigene Kopien, so wird jedes Element nur einmal kopiert.
|
||||
/// `coalesceKey`, `now` = Zeit in ms für das Koaleszenz-Fenster). Die Ops gehen ohne Kopie ins
|
||||
/// Dokument über; der Verlauf hält nur die inversen Ops (den Redo-Schritt liefert das Rückgängig-
|
||||
/// machen selbst: die Inverse der Inversen, s. [`Document::undo`]).
|
||||
pub fn commit(&mut self, ops: Vec<Op>, key: Option<&str>, now: f64, sanitize: bool) -> Result<(), Vec<String>> {
|
||||
let (as_add, inverse) = self.apply_checked(&ops, sanitize)?;
|
||||
// Normalisiert: `replace` ohne Treffer wird als `add` aufgezeichnet (so trifft jedes
|
||||
// aufgezeichnete `replace` ein vorhandenes Element, s. `ops::compact`).
|
||||
let mut forward: Vec<Op> = ops
|
||||
.into_iter()
|
||||
.zip(as_add)
|
||||
.map(|(op, add)| match op {
|
||||
Op::Replace { collection, entity } if add => Op::Add { collection, items: vec![entity], at: None },
|
||||
op => op,
|
||||
})
|
||||
.collect();
|
||||
if sanitize {
|
||||
// Angenommene Nicht-endlich-Marken auch im Verlauf als null.
|
||||
crate::ops::sanitize_ops(&mut forward);
|
||||
}
|
||||
self.history.record(forward, inverse, key, now);
|
||||
let inverse = self.apply_checked(ops, sanitize)?;
|
||||
self.history.record(inverse, key, now);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn apply_unchecked(&mut self, ops: &[Op]) {
|
||||
let mut pos = std::mem::take(&mut self.pos);
|
||||
for op in ops {
|
||||
let hit = self.apply_raw(op, &mut pos);
|
||||
self.mark_dirty(op, hit);
|
||||
}
|
||||
self.pos = pos;
|
||||
}
|
||||
|
||||
/// Einen Schritt zurück; liefert die angewendeten Ops (für die TS-Leseansicht), `None` = nichts.
|
||||
/// Die dabei entstehenden Inversen sind der Redo-Schritt.
|
||||
pub fn undo(&mut self) -> Option<Vec<Op>> {
|
||||
let step = self.history.pop_undo()?;
|
||||
self.apply_unchecked(&step.inverse);
|
||||
let ops = step.inverse.clone();
|
||||
self.history.push_redo(step);
|
||||
Some(ops)
|
||||
let ops = self.history.pop_undo()?.ops;
|
||||
let applied = ops.clone();
|
||||
let redo = self.apply_inverting(ops);
|
||||
self.history.push_redo(Step::new(redo));
|
||||
Some(applied)
|
||||
}
|
||||
|
||||
/// Einen Schritt vor; liefert die angewendeten Ops, `None` = nichts.
|
||||
pub fn redo(&mut self) -> Option<Vec<Op>> {
|
||||
let step = self.history.pop_redo()?;
|
||||
self.apply_unchecked(&step.forward);
|
||||
let ops = step.forward.clone();
|
||||
self.history.push_undo(step);
|
||||
Some(ops)
|
||||
let ops = self.history.pop_redo()?.ops;
|
||||
let applied = ops.clone();
|
||||
let undo = self.apply_inverting(ops);
|
||||
self.history.push_undo(Step::new(undo));
|
||||
Some(applied)
|
||||
}
|
||||
|
||||
pub fn history(&self) -> &History {
|
||||
@@ -887,6 +978,32 @@ mod tests {
|
||||
assert!(d.history().bytes() <= 20_000 && d.history().undo_depth() < 20 && d.history().undo_depth() >= 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "Messung: cargo test --release -- --ignored --nocapture"]
|
||||
fn messung_grosse_polylinie() {
|
||||
use std::time::Instant;
|
||||
let pts: Vec<Value> = (0..5000).map(|k| json!({"x": k as f64 * 0.1, "y": (k as f64 / 50.0).sin()})).collect();
|
||||
let mut drawings: Vec<Value> = (0..20000).map(|i| json!({"id": format!("d{i}"), "levelId": "eg", "geom": {"shape": "polyline", "closed": false, "pts": [{"x": i, "y": 1}, {"x": i + 1, "y": 2}]}})).collect();
|
||||
drawings[19000] = json!({"id": "d19000", "levelId": "eg", "geom": {"shape": "polyline", "closed": false, "pts": pts}});
|
||||
let mut d = Document::from_json(&json!({"id": "p", "drawings2d": drawings}).to_string()).unwrap();
|
||||
let n = 30;
|
||||
let (mut run, mut json, mut commit) = (0.0, 0.0, 0.0);
|
||||
for k in 0..n {
|
||||
let req: crate::grips::Request = serde_json::from_value(json!({"op": "moveGrip", "drawingId": "d19000", "index": 2500, "pt": [250.0 + (k % 5) as f64 * 0.01, 3], "scale": 100})).unwrap();
|
||||
let t = Instant::now();
|
||||
let res = crate::grips::run(&d.lookup(), &req).unwrap();
|
||||
run += t.elapsed().as_secs_f64();
|
||||
let t = Instant::now();
|
||||
let text = crate::grips::result_json(&res);
|
||||
json += t.elapsed().as_secs_f64();
|
||||
let t = Instant::now();
|
||||
d.commit(res.ops, Some("g"), k as f64, text.contains("\\u0001")).unwrap();
|
||||
commit += t.elapsed().as_secs_f64();
|
||||
}
|
||||
let ms = |x: f64| x * 1e3 / n as f64;
|
||||
eprintln!("Polylinie 5000 Punkte: Griff {:.2} ms, JSON {:.2} ms, Commit {:.2} ms", ms(run), ms(json), ms(commit));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "Messung: cargo test --release -- --ignored --nocapture"]
|
||||
fn messung_grosses_projekt() {
|
||||
|
||||
@@ -81,13 +81,7 @@ fn area_kind(r: &Room) -> usize {
|
||||
kennzahlen::category_index(r.sia_category)
|
||||
}
|
||||
|
||||
fn finite(v: f64) -> f64 {
|
||||
if v.is_finite() {
|
||||
v
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
use crate::jsnum::or_zero as finite;
|
||||
|
||||
/// Woher das Gebäudevolumen kommt.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
|
||||
@@ -20,15 +20,7 @@ fn shift_all(v: Option<&Value>, dx: f64, dy: f64) -> Value {
|
||||
Value::Array(v.and_then(Value::as_array).map(|a| a.iter().map(|p| shift(p, dx, dy)).collect()).unwrap_or_default())
|
||||
}
|
||||
|
||||
fn truthy(v: Option<&Value>) -> bool {
|
||||
match v {
|
||||
None | Some(Value::Null) => false,
|
||||
Some(Value::Bool(b)) => *b,
|
||||
Some(Value::Number(n)) => n.as_f64().is_some_and(|f| f != 0.0 && !f.is_nan()),
|
||||
Some(Value::String(s)) => !s.is_empty(),
|
||||
Some(_) => true,
|
||||
}
|
||||
}
|
||||
use crate::grips::truthy;
|
||||
|
||||
/// `{...m, key: v}` — ein vorhandener Schlüssel behält seine Stelle; `None` = `undefined` (Feld entfällt).
|
||||
fn set(m: &mut Map<String, Value>, key: &str, v: Option<Value>) {
|
||||
|
||||
+63
-15
@@ -14,6 +14,7 @@
|
||||
//! Abweichung (gewollt): Ein Griff-Index, unter dem kein Punkt liegt (negativ, gebrochen, zu gross), ist
|
||||
//! keine Änderung — TS warf dort beim Lesen von `undefined` einen Fehler.
|
||||
|
||||
pub use crate::document::Lookup;
|
||||
use crate::jsmath::hypot2;
|
||||
use crate::jsnum;
|
||||
use crate::ops::{id_of, Op};
|
||||
@@ -160,7 +161,7 @@ fn calc(f: f64) -> Pass {
|
||||
Pass { f, v: Some(js_num(f)) }
|
||||
}
|
||||
|
||||
pub(crate) fn arr(v: Option<&Value>) -> &[Value] {
|
||||
pub fn arr(v: Option<&Value>) -> &[Value] {
|
||||
v.and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[])
|
||||
}
|
||||
|
||||
@@ -266,6 +267,8 @@ pub struct Request {
|
||||
thickness: N,
|
||||
pt: [N; 2],
|
||||
delta: [N; 2],
|
||||
/// Punkttyp der Polylinie (`vertexType`: "corner" | "arc" | "spline").
|
||||
vertex_type: Option<String>,
|
||||
}
|
||||
|
||||
impl Request {
|
||||
@@ -343,19 +346,21 @@ pub fn result_json(r: &GripResult) -> String {
|
||||
String::from_utf8(out).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Führt eine Griff-Änderung aus (`req.op` wählt die Art, s. `src/state/gripOps.ts`).
|
||||
pub fn run(root: &Map<String, Value>, req: &Request) -> Result<GripResult, String> {
|
||||
/// Führt eine Griff-Änderung aus (`req.op` wählt die Art, s. `src/state/gripOps.ts`). Das Element
|
||||
/// sucht `lk` (im Dokument über den Positions-Index, je Mausschritt keine lineare Suche).
|
||||
pub fn run(lk: &Lookup, req: &Request) -> Result<GripResult, String> {
|
||||
let root = lk.root;
|
||||
let r = req;
|
||||
let op = req.op.as_str();
|
||||
let patch = |coll: &str, id: Option<&str>, f: &dyn Fn(&Value) -> Option<Value>| -> Vec<Op> {
|
||||
id.and_then(|id| find(root, coll, id)).and_then(f).map(|e| vec![replace(coll, e)]).unwrap_or_default()
|
||||
id.and_then(|id| lk.find(coll, id)).and_then(f).map(|e| vec![replace(coll, e)]).unwrap_or_default()
|
||||
};
|
||||
Ok(match op {
|
||||
"moveGrip" | "moveBy" | "moveEdge" => {
|
||||
let (did, wid) = (r.s("drawingId"), r.s("wallId"));
|
||||
// Jedes Element nur einmal suchen (lineare Suche, je Mausschritt).
|
||||
let d = did.and_then(|i| find(root, "drawings2d", i));
|
||||
let w = wid.and_then(|i| find(root, "walls", i));
|
||||
// Jedes Element nur einmal suchen.
|
||||
let d = did.and_then(|i| lk.find("drawings2d", i));
|
||||
let w = wid.and_then(|i| lk.find("walls", i));
|
||||
// Objekt-Sperre: gesperrte Elemente lassen sich anwählen, aber nicht ziehen.
|
||||
if d.is_some_and(|d| truthy(field(d, "locked"))) || w.is_some_and(|w| truthy(field(w, "locked"))) {
|
||||
return Ok(GripResult::default());
|
||||
@@ -453,9 +458,16 @@ pub fn run(root: &Map<String, Value>, req: &Request) -> Result<GripResult, Strin
|
||||
let (seg, (x, y)) = (r.n("seg"), r.p("pt"));
|
||||
patch("drawings2d", r.s("id"), &|d| insert_point(d, seg, x, y)).into()
|
||||
}
|
||||
"vertexType" => {
|
||||
let Some(t) = req.vertex_type.as_deref().and_then(crate::polyline_vertex::VertexType::parse) else {
|
||||
return Ok(GripResult::default());
|
||||
};
|
||||
let index = r.n("index");
|
||||
patch("drawings2d", r.s("id"), &|d| vertex_type(d, index, t)).into()
|
||||
}
|
||||
"deletePoint" => {
|
||||
let index = r.n("index");
|
||||
let Some(d) = r.s("id").and_then(|i| find(root, "drawings2d", i)) else { return Ok(GripResult::default()) };
|
||||
let Some(d) = r.s("id").and_then(|i| lk.find("drawings2d", i)) else { return Ok(GripResult::default()) };
|
||||
let g = field(d, "geom").unwrap_or(&Value::Null);
|
||||
if field(g, "shape").and_then(Value::as_str) != Some("polyline") {
|
||||
return Ok(GripResult::default());
|
||||
@@ -927,6 +939,42 @@ fn roof_grip(r: &Value, index: f64, x: f64, y: f64) -> Option<Value> {
|
||||
/// Punkt in Segment `seg` einer Polylinie einfügen. Ein Bogen wird exakt über die Kreisgeometrie in der
|
||||
/// Winkel-Mitte geteilt (wie `kernel2d` Bogen-Segmente zuschneidet); eine Näherung über tessellierte
|
||||
/// Punkte wäre zu ungenau. Die Bulge-Liste wird nur mitgeführt, wenn es eine gab.
|
||||
/// Punkttyp `t` am Punkt `index` einer Polylinie (`setPolylineVertexType`, `polyline_vertex.rs`): die
|
||||
/// Bulges der beiden anliegenden Segmente; `bulge` steht danach am Ende der Geometrie und fällt weg,
|
||||
/// wenn alle Segmente gerade sind. Gesperrt, keine Polylinie, Index ohne Punkt oder keine Änderung →
|
||||
/// None (kein leerer Undo-Schritt).
|
||||
fn vertex_type(d: &Value, index: f64, t: crate::polyline_vertex::VertexType) -> Option<Value> {
|
||||
use crate::polyline_vertex::{index_of, with_type, Poly};
|
||||
if truthy(field(d, "locked")) {
|
||||
return None;
|
||||
}
|
||||
let g = field(d, "geom")?;
|
||||
if shape(g) != "polyline" {
|
||||
return None;
|
||||
}
|
||||
let pts: Vec<(f64, f64)> = arr(field(g, "pts")).iter().map(xy).collect();
|
||||
let i = index_of(index, pts.len())?;
|
||||
// `g.bulge?.[k] ?? 0`
|
||||
let bulge: Vec<f64> = arr(field(g, "bulge")).iter().map(|b| if b.is_null() { 0.0 } else { num_of(Some(b)) }).collect();
|
||||
let nb = with_type(&Poly { pts: &pts, closed: truthy(field(g, "closed")), bulge: &bulge }, i, t);
|
||||
let new_bulge = nb.iter().any(|b| *b != 0.0).then(|| Value::Array(nb.into_iter().map(js_num).collect()));
|
||||
// Unverändert (ohne die grosse Geometrie zu vergleichen): gleiche Bögen, `bulge` steht schon am Ende.
|
||||
let last_key = g.as_object().and_then(|m| m.keys().last()).map(String::as_str);
|
||||
let same = match (field(g, "bulge"), &new_bulge) {
|
||||
(None, None) => true,
|
||||
(Some(old), Some(new)) => old == new && last_key == Some("bulge"),
|
||||
_ => false,
|
||||
};
|
||||
if same {
|
||||
return None;
|
||||
}
|
||||
let mut geom = with_opt(g, vec![("bulge", None)]);
|
||||
if let (Value::Object(m), Some(b)) = (&mut geom, new_bulge) {
|
||||
m.insert("bulge".into(), b);
|
||||
}
|
||||
Some(with_geom(d, geom))
|
||||
}
|
||||
|
||||
fn insert_point(d: &Value, seg: f64, x: f64, y: f64) -> Option<Value> {
|
||||
let g = field(d, "geom")?;
|
||||
if shape(g) != "polyline" {
|
||||
@@ -1204,18 +1252,18 @@ mod tests {
|
||||
#[test]
|
||||
fn wand_griff_und_sperre() {
|
||||
let r = root(json!({"walls": [{"id": "w", "start": {"x": 0, "y": 0}, "end": {"x": 1, "y": 0}, "extra": 1}]}));
|
||||
let res = run(&r, &rq(json!({"op": "moveGrip", "wallId": "w", "index": 1, "pt": [2, 3]}))).unwrap();
|
||||
let res = run(&Lookup::plain(&r), &rq(json!({"op": "moveGrip", "wallId": "w", "index": 1, "pt": [2, 3]}))).unwrap();
|
||||
assert_eq!(entity(&res).to_string(), r#"{"id":"w","start":{"x":0,"y":0},"end":{"x":2,"y":3},"extra":1}"#);
|
||||
let locked = root(json!({"walls": [{"id": "w", "locked": true, "start": {"x": 0, "y": 0}, "end": {"x": 1, "y": 0}}]}));
|
||||
assert!(run(&locked, &rq(json!({"op": "moveGrip", "wallId": "w", "index": 1, "pt": [2, 3]}))).unwrap().ops.is_empty());
|
||||
assert!(run(&Lookup::plain(&locked), &rq(json!({"op": "moveGrip", "wallId": "w", "index": 1, "pt": [2, 3]}))).unwrap().ops.is_empty());
|
||||
// Fehlendes Element: keine Op.
|
||||
assert!(run(&r, &rq(json!({"op": "moveGrip", "wallId": "x", "index": 1, "pt": [2, 3]}))).unwrap().ops.is_empty());
|
||||
assert!(run(&Lookup::plain(&r), &rq(json!({"op": "moveGrip", "wallId": "x", "index": 1, "pt": [2, 3]}))).unwrap().ops.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kreis_wird_ellipse() {
|
||||
let r = root(json!({"drawings2d": [{"id": "d", "geom": {"shape": "circle", "center": {"x": 0, "y": 0}, "r": 1}}]}));
|
||||
let res = run(&r, &rq(json!({"op": "moveGrip", "drawingId": "d", "index": 0, "pt": [2, 0]}))).unwrap();
|
||||
let res = run(&Lookup::plain(&r), &rq(json!({"op": "moveGrip", "drawingId": "d", "index": 0, "pt": [2, 0]}))).unwrap();
|
||||
assert_eq!(entity(&res)["geom"].to_string(), r#"{"shape":"ellipse","center":{"x":0,"y":0},"rx":2,"ry":1,"rotation":0}"#);
|
||||
}
|
||||
|
||||
@@ -1231,14 +1279,14 @@ mod tests {
|
||||
#[test]
|
||||
fn nan_als_marke() {
|
||||
let r = root(json!({"walls": [{"id": "w", "start": {"x": 0, "y": 0}, "end": {"x": 1, "y": 0}}]}));
|
||||
let res = run(&r, &rq(json!({"op": "moveBy", "wallId": "w", "delta": ["\u{1}NaN", 0]}))).unwrap();
|
||||
let res = run(&Lookup::plain(&r), &rq(json!({"op": "moveBy", "wallId": "w", "delta": ["\u{1}NaN", 0]}))).unwrap();
|
||||
assert_eq!(entity(&res)["start"]["x"], json!("\u{1}NaN"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn punkt_loeschen_mindestzahl() {
|
||||
let r = root(json!({"drawings2d": [{"id": "d", "geom": {"shape": "polyline", "closed": false, "pts": [{"x": 0, "y": 0}, {"x": 1, "y": 0}]}}]}));
|
||||
let res = run(&r, &rq(json!({"op": "deletePoint", "id": "d", "index": 0}))).unwrap();
|
||||
let res = run(&Lookup::plain(&r), &rq(json!({"op": "deletePoint", "id": "d", "index": 0}))).unwrap();
|
||||
assert_eq!(res.notice, Some("alert.polylineMinPoints"));
|
||||
assert!(res.ops.is_empty());
|
||||
}
|
||||
@@ -1249,7 +1297,7 @@ mod tests {
|
||||
"wallTypes": [{"id": "wt", "name": "W", "layers": [{"componentId": "c", "thickness": 0.2}]}],
|
||||
"ceilings": [{"id": "c1", "wallTypeId": "wt", "thickness": 0.3}, {"id": "c2", "wallTypeId": "wt"}],
|
||||
}));
|
||||
let ops = run(&r, &rq(json!({"op": "ceilingThickness", "id": "c1", "thickness": 0.25, "newId": "ct-1", "newName": "Decke"}))).unwrap().ops;
|
||||
let ops = run(&Lookup::plain(&r), &rq(json!({"op": "ceilingThickness", "id": "c1", "thickness": 0.25, "newId": "ct-1", "newName": "Decke"}))).unwrap().ops;
|
||||
assert_eq!(crate::ops::ops_to_json(&ops), r#"[{"kind":"add","collection":"ceilingTypes","items":[{"id":"ct-1","name":"Decke","layers":[{"componentId":"c","thickness":0.25}]}]},{"kind":"replace","collection":"ceilings","entity":{"id":"c1","wallTypeId":"wt","ceilingTypeId":"ct-1"}}]"#);
|
||||
}
|
||||
|
||||
|
||||
@@ -109,6 +109,19 @@ pub fn js_number(x: f64) -> String {
|
||||
format!("{sign}{body}")
|
||||
}
|
||||
|
||||
/// JS-`String(v)` eines JSON-Werts (Meldungen, Anzeige-Texte).
|
||||
pub fn js_string(v: &serde_json::Value) -> String {
|
||||
use serde_json::Value;
|
||||
match v {
|
||||
Value::Null => "null".into(),
|
||||
Value::Bool(b) => b.to_string(),
|
||||
Value::Number(n) => n.as_f64().map_or(n.to_string(), js_number),
|
||||
Value::String(s) => s.clone(),
|
||||
Value::Array(a) => a.iter().map(|x| if x.is_null() { String::new() } else { js_string(x) }).collect::<Vec<_>>().join(","),
|
||||
Value::Object(_) => "[object Object]".into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! - `Math.min/max` liefern bei NaN NaN (Rust `f64::min/max` ignorieren NaN).
|
||||
//! - `Math.round` rundet halbe Werte Richtung +∞ (Rust `round` weg von 0).
|
||||
//! - `x | 0` ist ToInt32 (Rest modulo 2³², Rust `as i32` sättigt).
|
||||
//! - `Math.pow` (`x ** 3`) und Trigonometrie: im Web-Build (wasm32 + Feature "web") ruft der Kern `Math.cos/sin/atan2/acos`
|
||||
//! - `Math.pow` (`x ** 3`) und Trigonometrie: im Web-Build (wasm32 + Feature "web") ruft der Kern `Math.cos/sin/tan/atan2/acos`
|
||||
//! der laufenden JS-Engine. Nur so sind die Werte bitgleich zur bisherigen TS-Fassung — V8
|
||||
//! (glibc-abgeleitete sin/cos), JavaScriptCore (System-libm von macOS) und Rusts libm (musl)
|
||||
//! unterscheiden sich in einzelnen Fällen in der letzten Stelle. Nativ (`cargo test`, Tauri)
|
||||
@@ -25,6 +25,12 @@ mod trig {
|
||||
fn js_acos(x: f64) -> f64;
|
||||
#[wasm_bindgen(js_namespace = Math, js_name = pow)]
|
||||
fn js_pow(x: f64, y: f64) -> f64;
|
||||
#[wasm_bindgen(js_namespace = Math, js_name = tan)]
|
||||
fn js_tan(x: f64) -> f64;
|
||||
}
|
||||
#[inline]
|
||||
pub fn tan(x: f64) -> f64 {
|
||||
js_tan(x)
|
||||
}
|
||||
#[inline]
|
||||
pub fn pow(x: f64, y: f64) -> f64 {
|
||||
@@ -71,9 +77,23 @@ mod trig {
|
||||
pub fn pow(x: f64, y: f64) -> f64 {
|
||||
x.powf(y)
|
||||
}
|
||||
#[inline]
|
||||
pub fn tan(x: f64) -> f64 {
|
||||
x.tan()
|
||||
}
|
||||
}
|
||||
|
||||
pub use trig::{acos, atan2, cos, pow, sin};
|
||||
pub use trig::{acos, atan2, cos, pow, sin, tan};
|
||||
|
||||
/// Endliche Zahl oder 0 (NaN/±∞ → 0; Summen der Kennzahlen/Flächen).
|
||||
#[inline]
|
||||
pub fn or_zero(v: f64) -> f64 {
|
||||
if v.is_finite() {
|
||||
v
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
|
||||
/// `Math.min(a, b)` (NaN gewinnt; −0 < +0).
|
||||
#[inline]
|
||||
|
||||
@@ -11,13 +11,7 @@ use crate::flat_read::signed_area;
|
||||
/// Anzahl der SIA-416-Blattkategorien (Reihenfolge: `room_area::CATEGORIES`).
|
||||
pub const CATEGORIES: usize = crate::room_area::CATEGORIES.len();
|
||||
|
||||
fn finite(v: f64) -> f64 {
|
||||
if v.is_finite() {
|
||||
v
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
use crate::jsnum::or_zero as finite;
|
||||
|
||||
/// Volumen (m³): Grundfläche (Polygon `points` oder Kreis mit Radius `circle_r`, NaN = kein
|
||||
/// Kreis), Höhe, Verjüngung `taper` (0 = Prisma, 1 = Spitze; ausserhalb geklemmt, NaN = 0).
|
||||
|
||||
@@ -11,16 +11,7 @@ use std::collections::HashSet;
|
||||
|
||||
type Tree = Vec<Value>;
|
||||
|
||||
/// JS-Wahrheitswert eines JSON-Werts (`if (c.visible)`).
|
||||
fn truthy(v: Option<&Value>) -> bool {
|
||||
match v {
|
||||
None | Some(Value::Null) => false,
|
||||
Some(Value::Bool(b)) => *b,
|
||||
Some(Value::Number(n)) => n.as_f64().is_some_and(|f| f != 0.0 && !f.is_nan()),
|
||||
Some(Value::String(s)) => !s.is_empty(),
|
||||
Some(_) => true,
|
||||
}
|
||||
}
|
||||
use crate::grips::truthy;
|
||||
|
||||
fn code_of(c: &Value) -> Option<&str> {
|
||||
c.get("code").and_then(Value::as_str)
|
||||
|
||||
@@ -91,6 +91,7 @@ pub mod project_refs;
|
||||
pub mod commands;
|
||||
pub mod cmd_transform;
|
||||
pub mod cmd_edit;
|
||||
pub mod polyline_vertex;
|
||||
|
||||
#[cfg(feature = "web")]
|
||||
mod web;
|
||||
@@ -147,7 +147,7 @@ impl Project {
|
||||
VerticalAnchor::Custom { z } => Some(*z),
|
||||
VerticalAnchor::Floor { floor_id, offset } => {
|
||||
let f = self.floor(floor_id)?;
|
||||
Some(f.base_elevation.unwrap_or(0.0) + offset.unwrap_or(0.0))
|
||||
Some(heights::floor_anchor(f.base_elevation.unwrap_or(0.0), offset.unwrap_or(0.0)))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -155,16 +155,12 @@ impl Project {
|
||||
/// (UK, OK) einer Wand in Metern (`wallVerticalExtent`).
|
||||
pub fn wall_vertical_extent(&self, w: &Wall) -> (f64, f64) {
|
||||
let floor_base = self.floor(&w.floor_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0));
|
||||
let bottom = self.resolve_anchor(w.bottom.as_ref()).unwrap_or(floor_base);
|
||||
let top = self.resolve_anchor(w.top.as_ref()).unwrap_or(bottom + w.height);
|
||||
(bottom, top)
|
||||
heights::element(floor_base, self.resolve_anchor(w.bottom.as_ref()), self.resolve_anchor(w.top.as_ref()), w.height)
|
||||
}
|
||||
|
||||
pub fn ceiling_vertical_extent(&self, c: &Ceiling) -> (f64, f64) {
|
||||
let floor_top = self.floor(&c.floor_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0) + f.floor_height.unwrap_or(0.0));
|
||||
let top = self.resolve_anchor(c.top.as_ref()).unwrap_or(floor_top);
|
||||
let bottom = self.resolve_anchor(c.bottom.as_ref()).unwrap_or(top - self.ceiling_thickness(c));
|
||||
(bottom, top)
|
||||
heights::ceiling(floor_top, self.resolve_anchor(c.bottom.as_ref()), self.resolve_anchor(c.top.as_ref()), || self.ceiling_thickness(c))
|
||||
}
|
||||
|
||||
pub fn stair_vertical_extent(&self, s: &Stair) -> (f64, f64) {
|
||||
@@ -179,9 +175,7 @@ impl Project {
|
||||
|
||||
pub fn column_vertical_extent(&self, c: &Column) -> (f64, f64) {
|
||||
let floor_base = self.floor(&c.floor_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0));
|
||||
let bottom = self.resolve_anchor(c.bottom.as_ref()).unwrap_or(floor_base);
|
||||
let top = self.resolve_anchor(c.top.as_ref()).unwrap_or(bottom + c.height);
|
||||
(bottom, top)
|
||||
heights::element(floor_base, self.resolve_anchor(c.bottom.as_ref()), self.resolve_anchor(c.top.as_ref()), c.height)
|
||||
}
|
||||
|
||||
/// Traufhöhe (absolutes Z): `baseElevation`, sonst Oberkante des Geschosses (`roofBaseElevation`).
|
||||
@@ -256,3 +250,43 @@ impl Stair {
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
/// Höhenregeln (UK/OK) — eine Fassung für die typisierte Sicht (oben) und die rohe Projekt-Wurzel
|
||||
/// (`selection_info.rs`: Objekt-Info, 3D-Griffe); die Aufrufer lösen nur ihre Eingaben auf.
|
||||
pub mod heights {
|
||||
/// Bindung „Geschoss“: Basis des Geschosses + Versatz.
|
||||
pub fn floor_anchor(base: f64, offset: f64) -> f64 {
|
||||
base + offset
|
||||
}
|
||||
|
||||
/// Wand/Stütze: UK aus der Bindung `bottom`, sonst Geschoss-Basis; OK aus `top`, sonst UK + Höhe.
|
||||
pub fn element(floor_base: f64, bottom: Option<f64>, top: Option<f64>, height: f64) -> (f64, f64) {
|
||||
let zb = bottom.unwrap_or(floor_base);
|
||||
(zb, top.unwrap_or(zb + height))
|
||||
}
|
||||
|
||||
/// Decke: OK aus `top`, sonst Geschoss-Oberkante; UK aus `bottom`, sonst OK − Dicke (die Decke wächst
|
||||
/// nach unten; die Dicke wird nur dann bestimmt).
|
||||
pub fn ceiling(floor_top: f64, bottom: Option<f64>, top: Option<f64>, thickness: impl FnOnce() -> f64) -> (f64, f64) {
|
||||
let zt = top.unwrap_or(floor_top);
|
||||
(bottom.unwrap_or_else(|| zt - thickness()), zt)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn wand_stuetze_und_decke() {
|
||||
// Geschoss-Basis + Höhe; Bindungen übersteuern UK/OK unabhängig.
|
||||
assert_eq!(element(0.0, None, None, 3.0), (0.0, 3.0));
|
||||
assert_eq!(element(0.0, Some(0.5), Some(floor_anchor(3.0, 0.0)), 3.0), (0.5, 3.0));
|
||||
assert_eq!(element(2.8, Some(1.0), None, 2.0), (1.0, 3.0));
|
||||
// Decke: OK = Geschoss-Oberkante, UK = OK − Dicke; die Dicke nur ohne UK-Bindung.
|
||||
assert_eq!(ceiling(2.6, None, None, || 0.25), (2.35, 2.6));
|
||||
assert_eq!(ceiling(2.6, Some(2.2), None, || panic!("Dicke nicht gebraucht")), (2.2, 2.6));
|
||||
assert_eq!(ceiling(2.6, None, Some(3.0), || 0.2), (2.8, 3.0));
|
||||
assert_eq!(floor_anchor(2.8, 0.1), 2.8 + 0.1);
|
||||
}
|
||||
}
|
||||
}
|
||||
+65
-67
@@ -203,21 +203,6 @@ pub fn sanitize_non_finite(v: &mut Value) {
|
||||
}
|
||||
}
|
||||
|
||||
fn op_values_mut(op: &mut Op) -> Vec<&mut Value> {
|
||||
match op {
|
||||
Op::Add { items, .. } => items.iter_mut().collect(),
|
||||
Op::Replace { entity, .. } => vec![entity],
|
||||
Op::SetField { value: Some(v), .. } => vec![v],
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn sanitize_ops(ops: &mut [Op]) {
|
||||
for op in ops {
|
||||
op_values_mut(op).into_iter().for_each(sanitize_non_finite);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Validierung ([7]) ────────────────────────────────────────────────────────
|
||||
|
||||
/// Prüft eine angewendete Op-Folge (bitgleich zur früheren TS-Fassung `validateOps`): nicht
|
||||
@@ -228,41 +213,51 @@ pub fn validate(after: &Map<String, Value>, ops: &[Op], had_dup: &dyn Fn(&str) -
|
||||
let mut problems = Vec::new();
|
||||
let mut dup_checked: HashSet<&str> = HashSet::new();
|
||||
for op in ops {
|
||||
match op {
|
||||
Op::Add { collection, .. } | Op::Replace { collection, .. } => {
|
||||
let ents: &[Value] = match op {
|
||||
Op::Add { items, .. } => items,
|
||||
Op::Replace { entity, .. } => std::slice::from_ref(entity),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
for e in ents {
|
||||
if let Some(bad) = find_non_finite(e, 0) {
|
||||
problems.push(format!("„{collection}\" {}: {bad} ist nicht endlich.", id_of(e).unwrap_or("undefined")));
|
||||
}
|
||||
}
|
||||
if matches!(op, Op::Add { .. }) && dup_checked.insert(collection) {
|
||||
if let Some(list) = after.get(collection) {
|
||||
if is_id_list(list) && !unique_ids(list.as_array().unwrap()) && !had_dup(collection) {
|
||||
problems.push(format!("Doppelte ids in „{collection}\"."));
|
||||
}
|
||||
}
|
||||
}
|
||||
value_problems(op, had_dup, &mut problems);
|
||||
if let Op::Add { collection, .. } = op {
|
||||
if dup_checked.insert(collection) {
|
||||
problems.extend(add_dup_problem(after, collection, had_dup));
|
||||
}
|
||||
Op::SetField { key, value, .. } => {
|
||||
if let Some(bad) = value.as_ref().and_then(non_finite_mark) {
|
||||
problems.push(format!("Feld „{key}\": {bad} ist nicht endlich."));
|
||||
} else if let Some(v) = value {
|
||||
if is_entity_list(v) && !unique_ids(v.as_array().unwrap()) && !had_dup(key) {
|
||||
problems.push(format!("Doppelte ids in „{key}\"."));
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
problems
|
||||
}
|
||||
|
||||
/// Der Teil von [`validate`], der nur die Op selbst liest (vor dem Anwenden prüfbar): nicht endliche
|
||||
/// Zahlen in Elementen und Feldwerten, doppelte ids in einer gesetzten Liste.
|
||||
pub fn value_problems(op: &Op, had_dup: &dyn Fn(&str) -> bool, problems: &mut Vec<String>) {
|
||||
match op {
|
||||
Op::Add { collection, .. } | Op::Replace { collection, .. } => {
|
||||
let ents: &[Value] = match op {
|
||||
Op::Add { items, .. } => items,
|
||||
Op::Replace { entity, .. } => std::slice::from_ref(entity),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
for e in ents {
|
||||
if let Some(bad) = find_non_finite(e, 0) {
|
||||
problems.push(format!("„{collection}\" {}: {bad} ist nicht endlich.", id_of(e).unwrap_or("undefined")));
|
||||
}
|
||||
}
|
||||
}
|
||||
Op::SetField { key, value, .. } => {
|
||||
if let Some(bad) = value.as_ref().and_then(non_finite_mark) {
|
||||
problems.push(format!("Feld „{key}\": {bad} ist nicht endlich."));
|
||||
} else if let Some(v) = value {
|
||||
if is_entity_list(v) && !unique_ids(v.as_array().unwrap()) && !had_dup(key) {
|
||||
problems.push(format!("Doppelte ids in „{key}\"."));
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Der Teil von [`validate`] nach dem Anwenden: doppelte ids in der Liste `collection` nach einem `add`.
|
||||
pub fn add_dup_problem(after: &Map<String, Value>, collection: &str, had_dup: &dyn Fn(&str) -> bool) -> Option<String> {
|
||||
let list = after.get(collection)?;
|
||||
(is_id_list(list) && !unique_ids(list.as_array().unwrap()) && !had_dup(collection)).then(|| format!("Doppelte ids in „{collection}\"."))
|
||||
}
|
||||
|
||||
/// Wie [`validate`] mit dem Projekt vor den Ops (für die TS-Fassade `validateOps`).
|
||||
pub fn validate_ops(after: &Map<String, Value>, ops: &[Op], before: Option<&Map<String, Value>>) -> Vec<String> {
|
||||
validate(after, ops, &|k| before.is_some_and(|b| has_dup(b.get(k))))
|
||||
@@ -291,14 +286,22 @@ pub fn validate_project(root: &Map<String, Value>) -> Vec<String> {
|
||||
|
||||
// ── Verlauf ([8]) ────────────────────────────────────────────────────────────
|
||||
|
||||
/// Ein Undo-Schritt: Vorwärts-Ops (Redo) und inverse Ops (Undo), beide in Anwendungsreihenfolge.
|
||||
/// Ein Schritt des Verlaufs: die Ops, die ihn anwenden (Undo-Stapel: die inversen Ops der Änderung,
|
||||
/// Redo-Stapel: die Änderung), in Anwendungsreihenfolge. Die Gegenrichtung entsteht beim Anwenden
|
||||
/// (`Document::undo`/`redo`: die Inverse der Inversen) — so hält der Verlauf jedes Element nur einmal.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Step {
|
||||
pub forward: Vec<Op>,
|
||||
pub inverse: Vec<Op>,
|
||||
pub ops: Vec<Op>,
|
||||
bytes: usize,
|
||||
}
|
||||
|
||||
impl Step {
|
||||
pub fn new(ops: Vec<Op>) -> Step {
|
||||
let bytes = ops_bytes(&ops);
|
||||
Step { ops, bytes }
|
||||
}
|
||||
}
|
||||
|
||||
/// Geschätzter Speicherbedarf eines JSON-Werts (Bytes).
|
||||
fn approx_bytes(v: &Value) -> usize {
|
||||
match v {
|
||||
@@ -460,8 +463,8 @@ impl History {
|
||||
}
|
||||
}
|
||||
|
||||
/// Zeichnet eine angewendete Änderung auf.
|
||||
pub fn record(&mut self, forward: Vec<Op>, inverse: Vec<Op>, key: Option<&str>, now: f64) {
|
||||
/// Zeichnet eine angewendete Änderung auf (`inverse` = die Ops, die sie zurücknehmen).
|
||||
pub fn record(&mut self, inverse: Vec<Op>, key: Option<&str>, now: f64) {
|
||||
for s in self.redo.drain(..) {
|
||||
self.bytes -= s.bytes;
|
||||
}
|
||||
@@ -475,19 +478,15 @@ impl History {
|
||||
match self.undo.back_mut().filter(|_| merge) {
|
||||
Some(top) => {
|
||||
self.bytes -= top.bytes;
|
||||
let mut fwd = std::mem::take(&mut top.forward);
|
||||
fwd.extend(forward);
|
||||
top.forward = compact(fwd);
|
||||
let mut inv = inverse;
|
||||
inv.append(&mut top.inverse);
|
||||
top.inverse = compact(inv);
|
||||
top.bytes = ops_bytes(&top.forward) + ops_bytes(&top.inverse);
|
||||
inv.append(&mut top.ops);
|
||||
*top = Step::new(compact(inv));
|
||||
self.bytes += top.bytes;
|
||||
}
|
||||
None => {
|
||||
let bytes = ops_bytes(&forward) + ops_bytes(&inverse);
|
||||
self.bytes += bytes;
|
||||
self.undo.push_back(Step { forward, inverse, bytes });
|
||||
let s = Step::new(inverse);
|
||||
self.bytes += s.bytes;
|
||||
self.undo.push_back(s);
|
||||
}
|
||||
}
|
||||
while self.undo.len() > self.max_steps || (self.bytes > self.max_bytes && self.undo.len() > 1) {
|
||||
@@ -611,21 +610,20 @@ mod tests {
|
||||
fn verlauf_koalesziert_und_begrenzt() {
|
||||
let mut h = History { max_steps: 3, ..Default::default() };
|
||||
let op = |n: i32| ops(json!([{"kind":"setField","key":"s","value":n}]));
|
||||
h.record(op(1), op(0), Some("k"), 0.0);
|
||||
h.record(op(2), op(1), Some("k"), 100.0);
|
||||
h.record(op(0), Some("k"), 0.0);
|
||||
h.record(op(1), Some("k"), 100.0);
|
||||
assert_eq!(h.undo_depth(), 1);
|
||||
h.record(op(3), op(2), Some("k"), 600.0);
|
||||
h.record(op(2), Some("k"), 600.0);
|
||||
assert_eq!(h.undo_depth(), 2);
|
||||
h.record(op(4), op(3), None, 700.0);
|
||||
h.record(op(5), op(4), None, 800.0);
|
||||
h.record(op(3), None, 700.0);
|
||||
h.record(op(4), None, 800.0);
|
||||
assert_eq!(h.undo_depth(), 3);
|
||||
h.begin_group();
|
||||
h.record(op(6), op(5), None, 900.0);
|
||||
h.record(op(7), op(6), Some("x"), 901.0);
|
||||
h.record(op(5), None, 900.0);
|
||||
h.record(op(6), Some("x"), 901.0);
|
||||
h.end_group();
|
||||
assert_eq!(h.undo_depth(), 3);
|
||||
let s = h.pop_undo().unwrap();
|
||||
assert_eq!(s.inverse, op(5));
|
||||
assert_eq!(s.forward, op(7));
|
||||
assert_eq!(s.ops, op(5));
|
||||
}
|
||||
}
|
||||
@@ -12,16 +12,7 @@ pub const PEN_FALLBACK_COLOR: &str = "#9aa0a6";
|
||||
/// Strichstärke (mm) eines Stifts ohne Eintrag.
|
||||
pub const PEN_FALLBACK_WEIGHT: f64 = 0.18;
|
||||
|
||||
/// JS-Wahrheitswert (`if (x.colorPenId)`).
|
||||
fn truthy(v: Option<&Value>) -> bool {
|
||||
match v {
|
||||
None | Some(Value::Null) => false,
|
||||
Some(Value::Bool(b)) => *b,
|
||||
Some(Value::Number(n)) => n.as_f64().is_some_and(|f| f != 0.0 && !f.is_nan()),
|
||||
Some(Value::String(s)) => !s.is_empty(),
|
||||
Some(_) => true,
|
||||
}
|
||||
}
|
||||
use crate::grips::truthy;
|
||||
|
||||
/// Schlüssel des Stifts als Objekt-Schlüssel (JS: `pens[penId]`, eine Zahl wird zu Text).
|
||||
fn key_of(v: &Value) -> Option<String> {
|
||||
|
||||
@@ -0,0 +1,358 @@
|
||||
//! Punkttypen einer Polylinie ([K4] S3, vorher `src/geometry/polylineVertexType.ts`; ArchiCAD/
|
||||
//! Vectorworks-artig): Eckpunkt, Bogenpunkt, Splinepunkt. Rein als Umrechnung der Segment-Bögen
|
||||
//! (`bulge`) der beiden am Punkt anliegenden Segmente — alle Renderer/Exporte verstehen Bulges
|
||||
//! bereits, es gibt also kein neues Geometrie-Feld.
|
||||
//!
|
||||
//! - Eckpunkt: beide Segmente gerade (bulge 0).
|
||||
//! - Bogenpunkt: EIN Kreisbogen durch Vorgänger, Punkt und Nachfolger.
|
||||
//! - Splinepunkt: tangential glatter Übergang — die Tangente im Punkt ist parallel zur Verbindung
|
||||
//! Vorgänger→Nachfolger (wie bei einer Catmull-Rom-Kurve), beide Segmente werden zu Bögen, die
|
||||
//! diese Tangente teilen.
|
||||
//!
|
||||
//! Die Bögen werden über ihren SCHEITELPUNKT bestimmt und mit `bulge::from_sagitta_point` in einen
|
||||
//! Bulge übersetzt — so bleibt die Vorzeichen-Konvention an EINER Stelle. Rechenreihenfolge und
|
||||
//! Zahlsemantik wie in der früheren TS-Fassung (`Math.hypot`/`sin`/`cos`/`atan2`/`tan` über
|
||||
//! `jsmath`/`jsnum`), Ergebnis bitgleich.
|
||||
|
||||
use crate::jsmath::hypot2;
|
||||
use crate::jsnum;
|
||||
|
||||
type P = (f64, f64);
|
||||
|
||||
const EPS: f64 = 1e-9;
|
||||
|
||||
/// Punkttyp.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum VertexType {
|
||||
Corner,
|
||||
Arc,
|
||||
Spline,
|
||||
}
|
||||
|
||||
impl VertexType {
|
||||
pub fn parse(s: &str) -> Option<VertexType> {
|
||||
match s {
|
||||
"corner" => Some(VertexType::Corner),
|
||||
"arc" => Some(VertexType::Arc),
|
||||
"spline" => Some(VertexType::Spline),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Kennzahl für die flache Grenze (0 Ecke, 1 Bogen, 2 Spline).
|
||||
pub fn code(self) -> f64 {
|
||||
match self {
|
||||
VertexType::Corner => 0.0,
|
||||
VertexType::Arc => 1.0,
|
||||
VertexType::Spline => 2.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Polylinie: Punkte, geschlossen, Bulge je Segment (fehlend = 0).
|
||||
pub struct Poly<'a> {
|
||||
pub pts: &'a [P],
|
||||
pub closed: bool,
|
||||
pub bulge: &'a [f64],
|
||||
}
|
||||
|
||||
impl Poly<'_> {
|
||||
fn b(&self, k: Option<usize>) -> f64 {
|
||||
k.and_then(|k| self.bulge.get(k).copied()).unwrap_or(0.0)
|
||||
}
|
||||
|
||||
/// Indizes des ein- und ausgehenden Segments von Punkt `i` (None = keins).
|
||||
fn adjacent(&self, i: usize) -> (Option<usize>, Option<usize>) {
|
||||
let n = self.pts.len();
|
||||
let in_seg = if i > 0 { Some(i - 1) } else if self.closed { Some(n - 1) } else { None };
|
||||
let out_seg = if i + 1 < n { Some(i) } else if self.closed { Some(n - 1) } else { None };
|
||||
(in_seg, out_seg)
|
||||
}
|
||||
|
||||
/// Nachbarpunkte von `i` (None an offenen Enden).
|
||||
fn neighbors(&self, i: usize) -> (Option<P>, Option<P>) {
|
||||
let n = self.pts.len();
|
||||
let prev = if i > 0 { Some(self.pts[i - 1]) } else if self.closed { Some(self.pts[n - 1]) } else { None };
|
||||
let next = if i + 1 < n { Some(self.pts[i + 1]) } else if self.closed { Some(self.pts[0]) } else { None };
|
||||
(prev, next)
|
||||
}
|
||||
}
|
||||
|
||||
/// Punkt-Index aus einer JS-Zahl: nur ganze Zahlen im Bereich (sonst kein Punkt).
|
||||
pub fn index_of(i: f64, n: usize) -> Option<usize> {
|
||||
(i.fract() == 0.0 && i >= 0.0 && i < n as f64).then_some(i as usize)
|
||||
}
|
||||
|
||||
fn sub(a: P, b: P) -> P {
|
||||
(a.0 - b.0, a.1 - b.1)
|
||||
}
|
||||
|
||||
fn cross(a: P, b: P) -> f64 {
|
||||
a.0 * b.1 - a.1 * b.0
|
||||
}
|
||||
|
||||
/// `Math.sign`.
|
||||
fn sign(x: f64) -> f64 {
|
||||
if x > 0.0 {
|
||||
1.0
|
||||
} else if x < 0.0 {
|
||||
-1.0
|
||||
} else {
|
||||
x
|
||||
}
|
||||
}
|
||||
|
||||
/// `x || 1` für Zahlen (0, −0, NaN → 1).
|
||||
fn or_one(x: f64) -> f64 {
|
||||
if x == 0.0 || x.is_nan() {
|
||||
1.0
|
||||
} else {
|
||||
x
|
||||
}
|
||||
}
|
||||
|
||||
/// Bogen-Parameter `[cx, cy, r, a0, a1, sweep]` (wie `bulgeArc` in TS), None = gerade/entartet.
|
||||
fn bulge_arc(a: P, b: P, bulge: f64) -> Option<[f64; 6]> {
|
||||
if !(bulge.abs() >= EPS) {
|
||||
return None;
|
||||
}
|
||||
let r = crate::bulge::arc(a.0, a.1, b.0, b.1, bulge);
|
||||
(r.len() >= 6).then(|| [r[0], r[1], r[2], r[3], r[4], r[5]])
|
||||
}
|
||||
|
||||
fn from_sagitta(a: P, b: P, p: P) -> f64 {
|
||||
crate::bulge::from_sagitta_point(a.0, a.1, b.0, b.1, p.0, p.1)
|
||||
}
|
||||
|
||||
/// Umkreismittelpunkt von a, b, c (None bei kollinearen Punkten).
|
||||
fn circumcenter(a: P, b: P, c: P) -> Option<P> {
|
||||
let d = 2.0 * (a.0 * (b.1 - c.1) + b.0 * (c.1 - a.1) + c.0 * (a.1 - b.1));
|
||||
if d.abs() < EPS {
|
||||
return None;
|
||||
}
|
||||
let (a2, b2, c2) = (a.0 * a.0 + a.1 * a.1, b.0 * b.0 + b.1 * b.1, c.0 * c.0 + c.1 * c.1);
|
||||
Some((
|
||||
(a2 * (b.1 - c.1) + b2 * (c.1 - a.1) + c2 * (a.1 - b.1)) / d,
|
||||
(a2 * (c.0 - b.0) + b2 * (a.0 - c.0) + c2 * (b.0 - a.0)) / d,
|
||||
))
|
||||
}
|
||||
|
||||
/// Bulge des Kreisbogens a→b auf dem Kreis um `c`, und zwar des Bogens, der NICHT durch `other`
|
||||
/// läuft (Scheitel auf der anderen Seite der Sehne als `other`).
|
||||
fn bulge_on_circle(a: P, b: P, c: P, other: P) -> f64 {
|
||||
let r = hypot2(a.0 - c.0, a.1 - c.1);
|
||||
let mid = ((a.0 + b.0) / 2.0, (a.1 + b.1) / 2.0);
|
||||
let mut u = sub(mid, c);
|
||||
let mut len = hypot2(u.0, u.1);
|
||||
if len < EPS {
|
||||
let d = sub(b, a);
|
||||
u = (-d.1, d.0);
|
||||
len = hypot2(u.0, u.1);
|
||||
}
|
||||
u = (u.0 / len, u.1 / len);
|
||||
let side = |p: P| sign(cross(sub(b, a), sub(p, a)));
|
||||
let cand1 = (c.0 + u.0 * r, c.1 + u.1 * r);
|
||||
let cand2 = (c.0 - u.0 * r, c.1 - u.1 * r);
|
||||
let apex = if side(cand1) != side(other) { cand1 } else { cand2 };
|
||||
from_sagitta(a, b, apex)
|
||||
}
|
||||
|
||||
/// Tangente (Fahrtrichtung a→b) des Bulge-Bogens am Anfang bzw. Ende.
|
||||
fn arc_tangent(a: P, b: P, bulge: f64, at_end: bool) -> P {
|
||||
let Some(arc) = bulge_arc(a, b, bulge) else {
|
||||
let d = sub(b, a);
|
||||
let l = or_one(hypot2(d.0, d.1));
|
||||
return (d.0 / l, d.1 / l);
|
||||
};
|
||||
let ang = if at_end { arc[3] + arc[5] } else { arc[3] };
|
||||
let s = or_one(sign(arc[5]));
|
||||
(-jsnum::sin(ang) * s, jsnum::cos(ang) * s)
|
||||
}
|
||||
|
||||
/// Bulge des Bogens a→b mit gegebener Tangente `t` am Ende (`at_end`) bzw. Anfang. Betrag aus dem
|
||||
/// Winkel Sehne↔Tangente, Vorzeichen NUMERISCH gewählt (die Variante, deren tatsächliche Tangente zu
|
||||
/// `t` passt).
|
||||
fn bulge_with_tangent(a: P, b: P, t: P, at_end: bool) -> f64 {
|
||||
let c = sub(b, a);
|
||||
let ang = jsnum::atan2(cross(c, t), c.0 * t.0 + c.1 * t.1).abs();
|
||||
let mag = bulge_from_apex_angle(a, b, ang).abs();
|
||||
if mag < 1e-9 {
|
||||
return 0.0;
|
||||
}
|
||||
let dot = |v: P| v.0 * t.0 + v.1 * t.1;
|
||||
if dot(arc_tangent(a, b, mag, at_end)) >= dot(arc_tangent(a, b, -mag, at_end)) {
|
||||
mag
|
||||
} else {
|
||||
-mag
|
||||
}
|
||||
}
|
||||
|
||||
/// Bogen über der Sehne a→b mit halbem Öffnungswinkel |half| (Sehne↔Tangente); Vorzeichen: >0 Scheitel
|
||||
/// links der Sehne, <0 rechts. Über den Scheitelpunkt in einen Bulge übersetzt.
|
||||
fn bulge_from_apex_angle(a: P, b: P, half: f64) -> f64 {
|
||||
if half.abs() < 1e-6 {
|
||||
return 0.0;
|
||||
}
|
||||
// Begrenzen: knapp unter einem Halbkreis je Segment (sonst kippt der Bogen).
|
||||
let h2 = jsnum::max(-std::f64::consts::PI / 2.0 + 0.01, jsnum::min(std::f64::consts::PI / 2.0 - 0.01, half));
|
||||
let d = sub(b, a);
|
||||
let chord = hypot2(d.0, d.1);
|
||||
if chord < EPS {
|
||||
return 0.0;
|
||||
}
|
||||
let left = (-d.1 / chord, d.0 / chord);
|
||||
let s = (chord / 2.0) * jsnum::tan(h2 / 2.0); // Pfeilhöhe
|
||||
let apex = ((a.0 + b.0) / 2.0 + left.0 * s, (a.1 + b.1) / 2.0 + left.1 * s);
|
||||
from_sagitta(a, b, apex)
|
||||
}
|
||||
|
||||
/// Ist Punkttyp `t` am Punkt `i` möglich? (Bogen/Spline brauchen beide Nachbarn.)
|
||||
pub fn can_set(g: &Poly, i: usize, t: VertexType) -> bool {
|
||||
if i >= g.pts.len() {
|
||||
return false;
|
||||
}
|
||||
if t == VertexType::Corner {
|
||||
return true;
|
||||
}
|
||||
let (prev, next) = g.neighbors(i);
|
||||
prev.is_some() && next.is_some()
|
||||
}
|
||||
|
||||
/// Aktueller Typ (Heuristik): beide Nachbarsegmente gerade → Eckpunkt, sonst None (gemischt).
|
||||
pub fn type_of(g: &Poly, i: usize) -> Option<VertexType> {
|
||||
if i >= g.pts.len() {
|
||||
return None;
|
||||
}
|
||||
let (in_seg, out_seg) = g.adjacent(i);
|
||||
if g.b(in_seg).abs() < 1e-9 && g.b(out_seg).abs() < 1e-9 {
|
||||
return Some(VertexType::Corner);
|
||||
}
|
||||
let (prev, next) = g.neighbors(i);
|
||||
let (Some(prev), Some(next), Some(_), Some(_)) = (prev, next, in_seg, out_seg) else { return None };
|
||||
let a1 = bulge_arc(prev, g.pts[i], g.b(in_seg));
|
||||
let a2 = bulge_arc(g.pts[i], next, g.b(out_seg));
|
||||
match (a1, a2) {
|
||||
(Some(a1), Some(a2)) if hypot2(a1[0] - a2[0], a1[1] - a2[1]) < 1e-6 * (1.0 + a1[2]) => Some(VertexType::Arc),
|
||||
_ => Some(VertexType::Spline),
|
||||
}
|
||||
}
|
||||
|
||||
/// Neue Bulge-Liste (je Segment) mit Punkttyp `t` an Punkt `i`.
|
||||
pub fn with_type(g: &Poly, i: usize, t: VertexType) -> Vec<f64> {
|
||||
let n = g.pts.len();
|
||||
let seg_count = if g.closed { n } else { n.saturating_sub(1) };
|
||||
let mut bulge: Vec<f64> = (0..seg_count).map(|k| g.b(Some(k))).collect();
|
||||
if !can_set(g, i, t) {
|
||||
return bulge;
|
||||
}
|
||||
let (in_seg, out_seg) = g.adjacent(i);
|
||||
let q = g.pts[i];
|
||||
let (prev, next) = g.neighbors(i);
|
||||
let mut put = |k: Option<usize>, v: f64| {
|
||||
if let Some(x) = k.and_then(|k| bulge.get_mut(k)) {
|
||||
*x = v;
|
||||
}
|
||||
};
|
||||
let (Some(p), Some(r)) = (prev, next) else {
|
||||
// Eckpunkt an einem offenen Ende.
|
||||
put(in_seg, 0.0);
|
||||
put(out_seg, 0.0);
|
||||
return bulge;
|
||||
};
|
||||
match t {
|
||||
VertexType::Corner => {
|
||||
put(in_seg, 0.0);
|
||||
put(out_seg, 0.0);
|
||||
}
|
||||
VertexType::Arc => match circumcenter(p, q, r) {
|
||||
None => {
|
||||
put(in_seg, 0.0);
|
||||
put(out_seg, 0.0);
|
||||
}
|
||||
Some(c) => {
|
||||
put(in_seg, bulge_on_circle(p, q, c, r));
|
||||
put(out_seg, bulge_on_circle(q, r, c, p));
|
||||
}
|
||||
},
|
||||
VertexType::Spline => {
|
||||
// Tangente parallel zu prev→next.
|
||||
let tv = sub(r, p);
|
||||
let tl = hypot2(tv.0, tv.1);
|
||||
if tl < EPS {
|
||||
return bulge;
|
||||
}
|
||||
let tu = (tv.0 / tl, tv.1 / tl);
|
||||
put(in_seg, bulge_with_tangent(p, q, tu, true));
|
||||
put(out_seg, bulge_with_tangent(q, r, tu, false));
|
||||
}
|
||||
}
|
||||
bulge
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const G: [P; 4] = [(0.0, 0.0), (2.0, 1.0), (4.0, 0.0), (6.0, 1.0)];
|
||||
|
||||
fn poly<'a>(pts: &'a [P], closed: bool, bulge: &'a [f64]) -> Poly<'a> {
|
||||
Poly { pts, closed, bulge }
|
||||
}
|
||||
|
||||
fn tangent(a: P, b: P, bulge: f64, at_end: bool) -> f64 {
|
||||
let arc = bulge_arc(a, b, bulge).unwrap();
|
||||
let ang = if at_end { arc[3] + arc[5] } else { arc[3] };
|
||||
let sg = sign(arc[5]);
|
||||
(ang.cos() * sg).atan2(-ang.sin() * sg)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eckpunkt_setzt_beide_nachbarsegmente_gerade() {
|
||||
assert_eq!(with_type(&poly(&G, false, &[0.3, -0.2, 0.1]), 1, VertexType::Corner), vec![0.0, 0.0, 0.1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bogenpunkt_beide_segmente_auf_einem_kreis() {
|
||||
let g = poly(&G, false, &[]);
|
||||
let b = with_type(&g, 1, VertexType::Arc);
|
||||
let a1 = bulge_arc(G[0], G[1], b[0]).unwrap();
|
||||
let a2 = bulge_arc(G[1], G[2], b[1]).unwrap();
|
||||
assert!(hypot2(a1[0] - a2[0], a1[1] - a2[1]) < 1e-6);
|
||||
assert!((a1[2] - a2[2]).abs() < 1e-6);
|
||||
assert_eq!(type_of(&poly(&G, false, &b), 1), Some(VertexType::Arc));
|
||||
// Der Bogen baucht NACH OBEN aus (Punkt 1 liegt oben): Scheitel über der Sehne.
|
||||
let pts = crate::bulge::arc_points(G[0].0, G[0].1, G[1].0, G[1].1, b[0]);
|
||||
let k = pts.len() / 4;
|
||||
assert!(pts[2 * k + 1] > 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn splinepunkt_tangenten_stimmen_ueberein() {
|
||||
let pts = [(0.0, 0.0), (2.0, 1.0), (5.0, 0.2)];
|
||||
let b = with_type(&poly(&pts, false, &[]), 1, VertexType::Spline);
|
||||
let t1 = tangent(pts[0], pts[1], b[0], true);
|
||||
let t2 = tangent(pts[1], pts[2], b[1], false);
|
||||
assert!((t1 - t2).abs() < 1e-6);
|
||||
assert!((t2 - 0.2f64.atan2(5.0)).abs() < 1e-6);
|
||||
assert_eq!(type_of(&poly(&pts, false, &b), 1), Some(VertexType::Spline));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offene_enden_und_geschlossene_polylinie() {
|
||||
let g = poly(&G, false, &[]);
|
||||
assert!(!can_set(&g, 0, VertexType::Arc));
|
||||
assert!(!can_set(&g, 3, VertexType::Spline));
|
||||
assert!(can_set(&g, 0, VertexType::Corner));
|
||||
assert!(!can_set(&g, 4, VertexType::Corner));
|
||||
let sq = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)];
|
||||
let b = with_type(&poly(&sq, true, &[]), 0, VertexType::Arc);
|
||||
assert_eq!(b.len(), 4);
|
||||
assert!(b[3] != 0.0 && b[0] != 0.0);
|
||||
assert_eq!(b[1], 0.0);
|
||||
// Kollinear: kein Kreis → gerade.
|
||||
let line = [(0.0, 0.0), (1.0, 0.0), (2.0, 0.0)];
|
||||
assert_eq!(with_type(&poly(&line, false, &[0.2, 0.3]), 1, VertexType::Arc), vec![0.0, 0.0]);
|
||||
assert_eq!(index_of(1.5, 4), None);
|
||||
assert_eq!(index_of(3.0, 4), Some(3));
|
||||
}
|
||||
}
|
||||
@@ -32,17 +32,7 @@ pub enum Parsed {
|
||||
Err(String),
|
||||
}
|
||||
|
||||
/// JS-`String(v)` für die Meldungen.
|
||||
fn js_string(v: &Value) -> String {
|
||||
match v {
|
||||
Value::Null => "null".into(),
|
||||
Value::Bool(b) => b.to_string(),
|
||||
Value::Number(n) => n.as_f64().map_or(n.to_string(), crate::js_fmt::js_number),
|
||||
Value::String(s) => s.clone(),
|
||||
Value::Array(a) => a.iter().map(|x| if x.is_null() { String::new() } else { js_string(x) }).collect::<Vec<_>>().join(","),
|
||||
Value::Object(_) => "[object Object]".into(),
|
||||
}
|
||||
}
|
||||
use crate::js_fmt::js_string;
|
||||
|
||||
/// 1 → 2: Legacy-Türen (`doors`) werden zu Öffnungen (`openings`, kind `door`).
|
||||
fn migrate_doors(mut raw: Map<String, Value>) -> Map<String, Value> {
|
||||
|
||||
@@ -62,7 +62,9 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result<String,
|
||||
}
|
||||
|
||||
/// Abfragen auf der rohen Projekt-Wurzel (JSON-Baum, verlustfrei; Antwort JSON). `text`: Argument als Text/JSON.
|
||||
pub fn run_root(root: &serde_json::Map<String, serde_json::Value>, name: &str, text: &str) -> Result<String, String> {
|
||||
/// Elemente per id sucht `lk` (im Dokument über dessen Positions-Index).
|
||||
pub fn run_root(lk: &crate::document::Lookup, name: &str, text: &str) -> Result<String, String> {
|
||||
let root = lk.root;
|
||||
match name {
|
||||
// Stiftsätze ([K4] S3, `pens.rs`): Ops statt Projekt-Kopien.
|
||||
"penRebakeOps" => json(&crate::pens::rebake_ops(root)),
|
||||
@@ -103,13 +105,13 @@ pub fn run_root(root: &serde_json::Map<String, serde_json::Value>, name: &str, t
|
||||
"cmdOps" => crate::commands::ops_json(root, text),
|
||||
"gripOps" => {
|
||||
let req: crate::grips::Request = serde_json::from_str(text).map_err(|e| format!("gripOps: {e}"))?;
|
||||
Ok(crate::grips::result_json(&crate::grips::run(root, &req)?))
|
||||
Ok(crate::grips::result_json(&crate::grips::run(lk, &req)?))
|
||||
}
|
||||
// Objekt-Info der Auswahl ([K4] S3, `selection_info.rs`): `text` = JSON der gewählten ids je Art; Antwort
|
||||
// `Selection` (TS) oder null, Zahlen mit Nicht-endlich-Marken.
|
||||
"selectionInfo" => {
|
||||
let a: crate::selection_info::SelArgs = serde_json::from_str(text).map_err(|e| format!("selectionInfo: {e}"))?;
|
||||
crate::selection_info::derive(root, &a).map(crate::selection_info::J::into_string)
|
||||
crate::selection_info::derive(lk, &a).map(crate::selection_info::J::into_string)
|
||||
}
|
||||
// Bounding-Boxen von Zeichnungen (Ausrichten/Verteilen): `text` = JSON der ids.
|
||||
"drawingBBoxes" => {
|
||||
|
||||
@@ -30,13 +30,7 @@ use crate::model::{Project, SiaCategory};
|
||||
|
||||
pub const DEFAULT_TOLERANCE: f64 = 0.05;
|
||||
|
||||
fn finite(v: f64) -> f64 {
|
||||
if v.is_finite() {
|
||||
v
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
use crate::jsnum::or_zero as finite;
|
||||
|
||||
fn cat_name(c: SiaCategory) -> &'static str {
|
||||
match c {
|
||||
|
||||
@@ -14,7 +14,9 @@
|
||||
//! Wo TS warf (unbekannter Wandtyp, Deckentyp oder Bauteil), kommt dieselbe Meldung als Fehler.
|
||||
//! Der B-Rep-Körper einer Extrusion (`spec`) bleibt in TS (truck-Pipeline, `plan/extrudedSolidSpec.ts`).
|
||||
|
||||
use crate::grips::{field, js_num, num_of, truthy, xy};
|
||||
use crate::document::Lookup;
|
||||
use crate::model::helpers::heights;
|
||||
use crate::grips::{arr, field, js_num, num_of, truthy, xy};
|
||||
use crate::jsmath::hypot2;
|
||||
use crate::jsnum;
|
||||
use crate::ops::id_of;
|
||||
@@ -40,9 +42,6 @@ pub struct SelArgs {
|
||||
pub column_id: Option<String>,
|
||||
pub roof_id: Option<String>,
|
||||
pub context_object_id: Option<String>,
|
||||
/// Lage der Elemente in ihren Listen (Liste → Index), von der Leseansicht; der Kern prüft die id an
|
||||
/// dieser Stelle und sucht sonst linear (die Suche über grosse Listen kostet je Element).
|
||||
pub at: std::collections::HashMap<String, f64>,
|
||||
}
|
||||
|
||||
// ── Hilfen ───────────────────────────────────────────────────────────────────
|
||||
@@ -136,21 +135,6 @@ impl O {
|
||||
}
|
||||
}
|
||||
|
||||
fn arr(v: Option<&Value>) -> &[Value] {
|
||||
v.and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[])
|
||||
}
|
||||
|
||||
/// Erstes Element mit `id` in einer Liste der Wurzel (`hint`: vermutete Lage, wird geprüft).
|
||||
fn find<'a>(root: &'a Map<String, Value>, list: &str, id: &str, hint: Option<f64>) -> Option<&'a Value> {
|
||||
let l = arr(root.get(list));
|
||||
if let Some(e) = hint.filter(|h| h.fract() == 0.0 && *h >= 0.0).and_then(|h| l.get(h as usize)) {
|
||||
if id_of(e) == Some(id) {
|
||||
return Some(e);
|
||||
}
|
||||
}
|
||||
l.iter().find(|e| id_of(e) == Some(id))
|
||||
}
|
||||
|
||||
/// Erstes Element, dessen Feld `key` gleich `val` ist (`===`; fehlend gleich fehlend).
|
||||
fn find_by<'a>(list: &'a [Value], key: &str, val: Option<&Value>) -> Option<&'a Value> {
|
||||
list.iter().find(|e| field(e, key) == val)
|
||||
@@ -165,17 +149,6 @@ fn str_of(v: Option<&Value>) -> Option<&str> {
|
||||
v.and_then(Value::as_str)
|
||||
}
|
||||
|
||||
/// `String(v)` für die Anzeige (Name eines Geschosses).
|
||||
fn js_string(v: &Value) -> Value {
|
||||
match v {
|
||||
Value::String(_) => v.clone(),
|
||||
Value::Number(n) => Value::from(crate::js_fmt::js_number(n.as_f64().unwrap_or(f64::NAN))),
|
||||
Value::Null => Value::from("null"),
|
||||
Value::Bool(b) => Value::from(if *b { "true" } else { "false" }),
|
||||
_ => Value::from("[object Object]"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Kategorie (Ebene) per Code: erster Treffer der Tiefensuche (`findCategory`).
|
||||
fn category<'a>(root: &'a Map<String, Value>, code: Option<&Value>) -> Option<&'a Value> {
|
||||
fn walk<'a>(list: &'a [Value], code: Option<&Value>) -> Option<&'a Value> {
|
||||
@@ -199,10 +172,7 @@ fn component<'a>(root: &'a Map<String, Value>, id: Option<&Value>) -> Result<&'a
|
||||
|
||||
/// Wert in einer Template-Zeichenkette (`${v}`).
|
||||
fn js_text(v: &Value) -> String {
|
||||
match js_string(v) {
|
||||
Value::String(s) => s,
|
||||
_ => String::new(),
|
||||
}
|
||||
crate::js_fmt::js_string(v)
|
||||
}
|
||||
|
||||
/// `x.color ?? cat?.color ?? fallback`.
|
||||
@@ -318,7 +288,7 @@ fn anchor(root: &Map<String, Value>, a: Option<&Value>) -> Option<f64> {
|
||||
return nn(field(a, "z")).map(|z| num_of(Some(z)));
|
||||
}
|
||||
let f = level(root, field(a, "floorId"))?;
|
||||
Some(num_or(field(f, "baseElevation"), 0.0) + num_or(field(a, "offset"), 0.0))
|
||||
Some(heights::floor_anchor(num_or(field(f, "baseElevation"), 0.0), num_or(field(a, "offset"), 0.0)))
|
||||
}
|
||||
|
||||
fn num_or(v: Option<&Value>, d: f64) -> f64 {
|
||||
@@ -332,18 +302,14 @@ fn num_or(v: Option<&Value>, d: f64) -> f64 {
|
||||
/// (UK, OK) einer Wand oder Stütze: UK aus `bottom` sonst Geschoss-Basis, OK aus `top` sonst UK + Höhe.
|
||||
fn vertical_extent(root: &Map<String, Value>, el: &Value) -> (f64, f64) {
|
||||
let floor_base = level(root, field(el, "floorId")).map_or(0.0, |f| num_or(field(f, "baseElevation"), 0.0));
|
||||
let zb = anchor(root, field(el, "bottom")).unwrap_or(floor_base);
|
||||
let zt = anchor(root, field(el, "top")).unwrap_or(zb + num_of(field(el, "height")));
|
||||
(zb, zt)
|
||||
heights::element(floor_base, anchor(root, field(el, "bottom")), anchor(root, field(el, "top")), num_of(field(el, "height")))
|
||||
}
|
||||
|
||||
/// (UK, OK) einer Decke (`ceilingVerticalExtent`): OK aus `top` sonst Geschoss-Oberkante (Basis + Höhe), UK aus
|
||||
/// `bottom` sonst OK − `thickness` (die Decke wächst nach unten).
|
||||
fn ceiling_extent(root: &Map<String, Value>, c: &Value, thickness: f64) -> (f64, f64) {
|
||||
let floor_top = level(root, field(c, "floorId")).map_or(0.0, |f| num_or(field(f, "baseElevation"), 0.0) + num_or(field(f, "floorHeight"), 0.0));
|
||||
let zt = anchor(root, field(c, "top")).unwrap_or(floor_top);
|
||||
let zb = anchor(root, field(c, "bottom")).unwrap_or(zt - thickness);
|
||||
(zb, zt)
|
||||
heights::ceiling(floor_top, anchor(root, field(c, "bottom")), anchor(root, field(c, "top")), || thickness)
|
||||
}
|
||||
|
||||
/// Anfrage `verticalExtents`: Wände und Decken als ganze Elemente (die 3D-Griffe zeigen auch gerade gezogene,
|
||||
@@ -433,43 +399,45 @@ fn effective(el: &Value, comp: Option<&Value>, cat: Option<&Value>) -> (Option<V
|
||||
// ── Abfrage ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Objekt-Info des ersten gewählten Elements (Vorrang wie `deriveSelection`); `Value::Null` = nichts.
|
||||
pub fn derive(root: &Map<String, Value>, a: &SelArgs) -> Result<J, String> {
|
||||
/// Gesucht wird über `lk` (im Dokument mit dessen Positions-Index, keine lineare Suche je Darstellung).
|
||||
pub fn derive(lk: &Lookup, a: &SelArgs) -> Result<J, String> {
|
||||
fn id(o: &Option<String>) -> Option<&str> {
|
||||
o.as_deref().filter(|s| !s.is_empty())
|
||||
}
|
||||
let root = lk.root;
|
||||
if let Some(i) = id(&a.context_object_id) {
|
||||
if let Some(o) = find(root, "context", i, a.at.get("context").copied()) {
|
||||
if let Some(o) = lk.find("context", i) {
|
||||
return Ok(context_selection(root, o));
|
||||
}
|
||||
}
|
||||
if let Some(i) = id(&a.drawing_id) {
|
||||
return Ok(find(root, "drawings2d", i, a.at.get("drawings2d").copied()).map_or(J::null(), |d| drawing_selection(root, d)));
|
||||
return Ok(lk.find("drawings2d", i).map_or(J::null(), |d| drawing_selection(root, d)));
|
||||
}
|
||||
if let Some(i) = id(&a.extruded_solid_id) {
|
||||
return Ok(find(root, "extrudedSolids", i, a.at.get("extrudedSolids").copied()).map_or(J::null(), |s| solid_selection(root, s)));
|
||||
return Ok(lk.find("extrudedSolids", i).map_or(J::null(), |s| solid_selection(root, s)));
|
||||
}
|
||||
if let Some(i) = id(&a.column_id) {
|
||||
return find(root, "columns", i, a.at.get("columns").copied()).map_or(Ok(J::null()), |c| column_selection(root, c));
|
||||
return lk.find("columns", i).map_or(Ok(J::null()), |c| column_selection(root, c));
|
||||
}
|
||||
if let Some(i) = id(&a.opening_id) {
|
||||
if let Some(o) = find(root, "openings", i, a.at.get("openings").copied()) {
|
||||
return opening_selection(root, o);
|
||||
if let Some(o) = lk.find("openings", i) {
|
||||
return opening_selection(lk, o);
|
||||
}
|
||||
}
|
||||
if let Some(i) = a.wall_ids.first().filter(|s| !s.is_empty()) {
|
||||
return find(root, "walls", i, a.at.get("walls").copied()).map_or(Ok(J::null()), |w| wall_selection(root, w));
|
||||
return lk.find("walls", i).map_or(Ok(J::null()), |w| wall_selection(root, w));
|
||||
}
|
||||
if let Some(i) = id(&a.ceiling_id) {
|
||||
return find(root, "ceilings", i, a.at.get("ceilings").copied()).map_or(Ok(J::null()), |c| ceiling_selection(root, c));
|
||||
return lk.find("ceilings", i).map_or(Ok(J::null()), |c| ceiling_selection(root, c));
|
||||
}
|
||||
if let Some(i) = id(&a.roof_id) {
|
||||
return find(root, "roofs", i, a.at.get("roofs").copied()).map_or(Ok(J::null()), |r| roof_selection(root, r));
|
||||
return lk.find("roofs", i).map_or(Ok(J::null()), |r| roof_selection(root, r));
|
||||
}
|
||||
if let Some(i) = id(&a.stair_id) {
|
||||
return find(root, "stairs", i, a.at.get("stairs").copied()).map_or(Ok(J::null()), |s| stair_selection(root, s));
|
||||
return lk.find("stairs", i).map_or(Ok(J::null()), |s| stair_selection(root, s));
|
||||
}
|
||||
if let Some(i) = id(&a.room_id) {
|
||||
return Ok(find(root, "rooms", i, a.at.get("rooms").copied()).map_or(J::null(), |r| room_selection(root, r)));
|
||||
return Ok(lk.find("rooms", i).map_or(J::null(), |r| room_selection(root, r)));
|
||||
}
|
||||
Ok(J::null())
|
||||
}
|
||||
@@ -698,16 +666,62 @@ fn roof_selection(root: &Map<String, Value>, r: &Value) -> Result<J, String> {
|
||||
.done())
|
||||
}
|
||||
|
||||
/// Gemerkte Firsthöhen, Schlüssel = Inhalts-Hash (Dach-JSON + Traufhöhe); je Eintrag Dach, Traufhöhe,
|
||||
/// Firsthöhe (bei einem Treffer wird der Inhalt verglichen, nie veraltet).
|
||||
type RidgeCache = std::collections::HashMap<u64, Vec<(Value, u64, f64)>>;
|
||||
|
||||
/// Höchstzahl gemerkter Firsthöhen (danach wird geleert).
|
||||
const RIDGE_CACHE_MAX: usize = 4096;
|
||||
|
||||
thread_local! {
|
||||
/// Zuletzt gerechnete Firsthöhen (Dach, Traufhöhe, Firsthöhe): die Objekt-Info fragt je Darstellung
|
||||
/// neu, das Skelett eines Dachs kostet aber ein Vielfaches der übrigen Abfrage (TS merkte sich die
|
||||
/// Geometrie je Dach-Objekt).
|
||||
static RIDGE_CACHE: std::cell::RefCell<Vec<(Value, f64, f64)>> = const { std::cell::RefCell::new(Vec::new()) };
|
||||
/// Gerechnete Firsthöhen: die Objekt-Info fragt je Darstellung neu, das Skelett eines Dachs kostet aber
|
||||
/// ein Vielfaches der übrigen Abfrage (TS merkte sich die Geometrie je Dach-Objekt). Nach Inhalt
|
||||
/// gemerkt, damit auch das Hin- und Herwählen zwischen vielen Dächern trifft.
|
||||
static RIDGE_CACHE: std::cell::RefCell<RidgeCache> = std::cell::RefCell::new(RidgeCache::new());
|
||||
}
|
||||
|
||||
/// Firsthöhe über der Traufe (Dach-Geometrie des Kerns, `roof.rs`), gemerkt für die letzten Dächer.
|
||||
/// FNV-1a über einen JSON-Wert (Struktur, Schlüssel, Zahlen-Bits, Texte).
|
||||
fn value_hash(v: &Value, h: &mut u64) {
|
||||
let mut put = |bytes: &[u8]| {
|
||||
for b in bytes {
|
||||
*h = (*h ^ *b as u64).wrapping_mul(0x0000_0100_0000_01b3);
|
||||
}
|
||||
};
|
||||
match v {
|
||||
Value::Null => put(b"n"),
|
||||
Value::Bool(b) => put(if *b { b"t" } else { b"f" }),
|
||||
Value::Number(n) => {
|
||||
put(b"#");
|
||||
put(&n.as_f64().unwrap_or(f64::NAN).to_bits().to_le_bytes());
|
||||
}
|
||||
Value::String(s) => {
|
||||
put(b"s");
|
||||
put(s.as_bytes());
|
||||
put(&[0]);
|
||||
}
|
||||
Value::Array(a) => {
|
||||
put(b"[");
|
||||
for x in a {
|
||||
value_hash(x, h);
|
||||
}
|
||||
*h = (*h ^ b']' as u64).wrapping_mul(0x0000_0100_0000_01b3);
|
||||
}
|
||||
Value::Object(m) => {
|
||||
put(b"{");
|
||||
for (k, x) in m {
|
||||
*h = k.bytes().fold(*h, |h, b| (h ^ b as u64).wrapping_mul(0x0000_0100_0000_01b3));
|
||||
value_hash(x, h);
|
||||
}
|
||||
*h = (*h ^ b'}' as u64).wrapping_mul(0x0000_0100_0000_01b3);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Firsthöhe über der Traufe (Dach-Geometrie des Kerns, `roof.rs`), nach Inhalt gemerkt.
|
||||
fn roof_ridge_height(r: &Value, eaves: f64) -> Result<f64, String> {
|
||||
let hit = RIDGE_CACHE.with(|c| c.borrow().iter().find(|(v, z, _)| z.to_bits() == eaves.to_bits() && v == r).map(|e| e.2));
|
||||
let mut key = 0xcbf2_9ce4_8422_2325u64 ^ eaves.to_bits();
|
||||
value_hash(r, &mut key);
|
||||
let hit = RIDGE_CACHE.with(|c| c.borrow().get(&key).and_then(|l| l.iter().find(|(v, z, _)| *z == eaves.to_bits() && v == r).map(|e| e.2)));
|
||||
if let Some(h) = hit {
|
||||
return Ok(h);
|
||||
}
|
||||
@@ -715,10 +729,10 @@ fn roof_ridge_height(r: &Value, eaves: f64) -> Result<f64, String> {
|
||||
let h = crate::roof::roof_geometry(&typed.params(), eaves).ridge_height;
|
||||
RIDGE_CACHE.with(|c| {
|
||||
let mut c = c.borrow_mut();
|
||||
if c.len() >= 16 {
|
||||
c.remove(0);
|
||||
if c.len() >= RIDGE_CACHE_MAX {
|
||||
c.clear();
|
||||
}
|
||||
c.push((r.clone(), eaves, h));
|
||||
c.entry(key).or_default().push((r.clone(), eaves.to_bits(), h));
|
||||
});
|
||||
Ok(h)
|
||||
}
|
||||
@@ -768,12 +782,17 @@ fn roof_edges(r: &Value) -> J {
|
||||
J::arr(out)
|
||||
}
|
||||
|
||||
fn opening_selection(root: &Map<String, Value>, o: &Value) -> Result<J, String> {
|
||||
fn opening_selection(lk: &Lookup, o: &Value) -> Result<J, String> {
|
||||
use crate::opening_geom::{opening_gap_quad, v, WallRef};
|
||||
let root = lk.root;
|
||||
let cat = category(root, field(o, "categoryCode"));
|
||||
let color = color_of(o, cat, WALL_FALLBACK_COLOR);
|
||||
let weight = lw_or(None, cat, WALL_FALLBACK_MM);
|
||||
let wall = find_by(arr(root.get("walls")), "id", field(o, "hostWallId"));
|
||||
let host = field(o, "hostWallId");
|
||||
let wall = match host.and_then(Value::as_str) {
|
||||
Some(i) => lk.find("walls", i),
|
||||
None => find_by(arr(root.get("walls")), "id", host),
|
||||
};
|
||||
let floor = wall.and_then(|w| level(root, field(w, "floorId")));
|
||||
let mut quad = None;
|
||||
if let Some(w) = wall {
|
||||
@@ -1213,7 +1232,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn sel(r: &Map<String, Value>, a: Value) -> Result<Value, String> {
|
||||
derive(r, &serde_json::from_value(a).unwrap()).map(|j| serde_json::from_str(&j.into_string()).unwrap())
|
||||
derive(&Lookup::plain(r), &serde_json::from_value(a).unwrap()).map(|j| serde_json::from_str(&j.into_string()).unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -27,11 +27,6 @@ pub fn bulge_from_sagitta_point(ax: f64, ay: f64, bx: f64, by: f64, px: f64, py:
|
||||
b::from_sagitta_point(ax, ay, bx, by, px, py)
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn bulge_between_angles(cx: f64, cy: f64, r: f64, a_from: f64, a_to: f64, sweep_sign: f64) -> f64 {
|
||||
b::between_angles(cx, cy, r, a_from, a_to, sweep_sign)
|
||||
}
|
||||
|
||||
/// `[x, y]` auf dem Bogen bei t∈[0,1].
|
||||
#[wasm_bindgen]
|
||||
pub fn bulge_point_at(ax: f64, ay: f64, bx: f64, by: f64, bulge: f64, t: f64) -> Vec<f64> {
|
||||
|
||||
@@ -87,7 +87,7 @@ fn problems_text(r: Option<Result<(), Vec<String>>>, parsed_err: Option<String>)
|
||||
pub fn doc_apply(h: u32, ops_json: &str) -> String {
|
||||
match parse_ops(ops_json) {
|
||||
Err(e) => problems_text(None, Some(e)),
|
||||
Ok(ops) => problems_text(with_doc(h, |d| d.apply_marked(&ops, may_have_marks(ops_json))), None),
|
||||
Ok(ops) => problems_text(with_doc(h, |d| d.apply_marked(ops, may_have_marks(ops_json))), None),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -174,15 +174,9 @@ pub fn doc_json(h: u32) -> String {
|
||||
with_doc(h, |d| d.to_json()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Abfrage auf dem typisierten Projekt; Ergebnis als JSON. Fehler (Dokument nicht offen, Modell
|
||||
/// passt nicht, unbekannte Abfrage, Rechenfehler) kommen als Text mit vorangestelltem `\u{1}`.
|
||||
/// Abfragen s. `crate::queries`.
|
||||
#[wasm_bindgen]
|
||||
pub fn doc_query(h: u32, name: &str) -> String {
|
||||
doc_query_args(h, name, &[], "")
|
||||
}
|
||||
|
||||
/// Wie [`doc_query`] mit Zahlen- und Textargument.
|
||||
/// Abfrage auf dem typisierten Projekt mit Zahlen- und Textargument; Ergebnis als JSON. Fehler (Dokument
|
||||
/// nicht offen, Modell passt nicht, unbekannte Abfrage, Rechenfehler) kommen als Text mit vorangestelltem
|
||||
/// `\u{1}`. Abfragen s. `crate::queries`.
|
||||
#[wasm_bindgen]
|
||||
pub fn doc_query_args(h: u32, name: &str, args: &[f64], text: &str) -> String {
|
||||
let result = with_doc(h, |d| {
|
||||
@@ -196,10 +190,10 @@ pub fn doc_query_args(h: u32, name: &str, args: &[f64], text: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Abfrage auf der rohen Projekt-Wurzel (`crate::queries::run_root`); Fehler wie bei [`doc_query`].
|
||||
/// Abfrage auf der rohen Projekt-Wurzel (`crate::queries::run_root`); Fehler wie bei [`doc_query_args`].
|
||||
#[wasm_bindgen]
|
||||
pub fn doc_query_root(h: u32, name: &str, text: &str) -> String {
|
||||
let result = with_doc(h, |d| crate::queries::run_root(d.root(), name, text)).unwrap_or_else(|| Err("Dokument nicht offen".to_string()));
|
||||
let result = with_doc(h, |d| crate::queries::run_root(&d.lookup(), name, text)).unwrap_or_else(|| Err("Dokument nicht offen".to_string()));
|
||||
match result {
|
||||
Ok(json) => json,
|
||||
Err(e) => format!("\u{1}{e}"),
|
||||
@@ -226,3 +220,11 @@ pub fn doc_query_bin(h: u32, name: &str, args: &[f64], text: &str) -> Vec<u8> {
|
||||
let result = with_doc(h, |d| crate::queries::run_bin_doc(d, name, args, text)).unwrap_or_else(|| Err("Dokument nicht offen".to_string()));
|
||||
result.unwrap_or_else(|e| crate::plan_buf::encode_error(&e))
|
||||
}
|
||||
|
||||
/// Je Op der zuletzt angewendeten Folge (`doc_commit`, `doc_apply`, `doc_grip_commit`, `doc_undo`,
|
||||
/// `doc_redo`) die Position des von `replace` getroffenen Elements, −1 = keine (TS führt die
|
||||
/// Leseansicht damit ohne Suche nach, `applyOps`).
|
||||
#[wasm_bindgen]
|
||||
pub fn doc_last_hits(h: u32) -> Vec<f64> {
|
||||
with_doc(h, |d| d.last_hits().iter().map(|p| p.map_or(-1.0, |i| i as f64)).collect()).unwrap_or_default()
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
//! Bindungen der 2D-Zeichnungen im 3D (`crate::drawing2d_3d`). Kodierung s. dort.
|
||||
|
||||
use crate::drawing2d_3d as d;
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
/// LineList-Vertices `[px, höhe, py, r, g, b]` (zwei je Segment) einer Charge.
|
||||
#[wasm_bindgen]
|
||||
pub fn drawing3d_line_verts(drawings: &[f64]) -> Vec<f32> {
|
||||
d::line_verts(drawings)
|
||||
}
|
||||
|
||||
/// Pick-Strecken `[ax, ay, bx, by, baseElevation, zeichnung]` einer Charge.
|
||||
#[wasm_bindgen]
|
||||
pub fn drawing3d_pick_segs(drawings: &[f64], tolerance: f64) -> Vec<f64> {
|
||||
d::pick_segs(drawings, tolerance)
|
||||
}
|
||||
@@ -19,7 +19,7 @@ pub fn doc_grip_commit(h: u32, req_json: &str, key: &str, now_ms: f64) -> String
|
||||
let key = (!key.is_empty()).then_some(key);
|
||||
let now = if now_ms.is_finite() { now_ms } else { 0.0 };
|
||||
let out = with_doc(h, |d| -> Result<String, String> {
|
||||
let res = crate::grips::run(d.root(), &req)?;
|
||||
let res = crate::grips::run(&d.lookup(), &req)?;
|
||||
let text = crate::grips::result_json(&res);
|
||||
if res.ops.is_empty() {
|
||||
return Ok(text);
|
||||
@@ -79,3 +79,16 @@ pub fn edge_grips(pts: &[f64], closed: bool, bulge: &[f64], use_bulge: bool) ->
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Punkttyp am Punkt `index` einer Polylinie (`crate::polyline_vertex`; `pts = [x0, y0, …]`, `bulge` je
|
||||
/// Segment): `[typ, ecke, bogen, spline]` mit typ −1 = gemischt bzw. kein Punkt, 0 Ecke, 1 Bogen,
|
||||
/// 2 Spline; danach je Typ 1/0, ob er sich setzen lässt.
|
||||
#[wasm_bindgen]
|
||||
pub fn polyline_vertex_info(pts: &[f64], bulge: &[f64], closed: bool, index: f64) -> Vec<f64> {
|
||||
use crate::polyline_vertex::{can_set, index_of, type_of, Poly, VertexType};
|
||||
let verts: Vec<(f64, f64)> = pts.chunks_exact(2).map(|c| (c[0], c[1])).collect();
|
||||
let g = Poly { pts: &verts, closed, bulge };
|
||||
let Some(i) = index_of(index, verts.len()) else { return vec![-1.0, 0.0, 0.0, 0.0] };
|
||||
let can = |t| if can_set(&g, i, t) { 1.0 } else { 0.0 };
|
||||
vec![type_of(&g, i).map_or(-1.0, VertexType::code), can(VertexType::Corner), can(VertexType::Arc), can(VertexType::Spline)]
|
||||
}
|
||||
@@ -75,16 +75,3 @@ pub fn hatch_line_family_flat(poly: &[f64], angle_rad: f64, spacing_m: f64, offs
|
||||
segs_out(&hatch::hatch_line_family(&pts(poly), angle_rad, spacing_m, offset_m, v2(ax, ay)))
|
||||
}
|
||||
|
||||
/// `len_min`/`len_max` NaN = nicht gesetzt.
|
||||
#[wasm_bindgen]
|
||||
pub fn scatter_strokes_flat(
|
||||
poly: &[f64],
|
||||
cell: f64,
|
||||
base_angle_rad: f64,
|
||||
seed: f64,
|
||||
stroke_len: f64,
|
||||
len_min: f64,
|
||||
len_max: f64,
|
||||
) -> Vec<f64> {
|
||||
runs_out(&hatch::scatter_strokes(&pts(poly), cell, base_angle_rad, seed, stroke_len, opt(len_min), opt(len_max)))
|
||||
}
|
||||
@@ -15,7 +15,6 @@ mod stair;
|
||||
mod room_area;
|
||||
mod room_boundary;
|
||||
mod polygon_holes;
|
||||
mod drawing2d_3d;
|
||||
mod plan_buf;
|
||||
mod project_format;
|
||||
mod gpu_compile;
|
||||
@@ -48,9 +47,3 @@ use wasm_bindgen::prelude::wasm_bindgen;
|
||||
pub fn start() {
|
||||
console_error_panic_hook::set_once();
|
||||
}
|
||||
|
||||
/// Version des Kern-Moduls (für Diagnose/Startprotokoll).
|
||||
#[wasm_bindgen]
|
||||
pub fn core_version() -> String {
|
||||
env!("CARGO_PKG_VERSION").to_string()
|
||||
}
|
||||
@@ -236,7 +236,7 @@ export class ProjectDocument {
|
||||
}
|
||||
return { problems };
|
||||
}
|
||||
const project = applyOps(base, ops);
|
||||
const project = applyOps(base, ops, core().doc_last_hits(this.handle));
|
||||
this.mirror = project;
|
||||
return { project };
|
||||
}
|
||||
@@ -255,7 +255,7 @@ export class ProjectDocument {
|
||||
const r = fromMarkedJson<{ ops: CoreOp[]; notice?: string } | { problems: string[] }>(out);
|
||||
if ("problems" in r) return r;
|
||||
if (r.ops.length === 0) return { project: base, ops: r.ops, notice: r.notice };
|
||||
const project = applyOps(base, r.ops);
|
||||
const project = applyOps(base, r.ops, core().doc_last_hits(this.handle));
|
||||
this.mirror = project;
|
||||
return { project, ops: r.ops, notice: r.notice };
|
||||
}
|
||||
@@ -338,7 +338,7 @@ export class ProjectDocument {
|
||||
}
|
||||
const json = core()[fn](this.handle);
|
||||
if (!json) return null;
|
||||
const project = applyOps(base, JSON.parse(json) as CoreOp[]);
|
||||
const project = applyOps(base, JSON.parse(json) as CoreOp[], core().doc_last_hits(this.handle));
|
||||
this.mirror = project;
|
||||
return project;
|
||||
}
|
||||
|
||||
+1
-1
@@ -18,7 +18,7 @@ export { exportObj, exportStl, exportGlb, exportGltf } from "../export/exportMes
|
||||
export { exportProjectStep } from "../export/exportStep";
|
||||
export { planToSvgString } from "../export/planToSvgString";
|
||||
export { setWasmBytesProvider } from "../engine/wasmSource";
|
||||
export { initCore, coreReady } from "../engine/coreWasm";
|
||||
export { initCore } from "../engine/coreWasm";
|
||||
export { applyOps, validateProject, validateOps } from "./ops";
|
||||
export { projectWarnings } from "./ops";
|
||||
export type { CoreOp } from "./ops";
|
||||
|
||||
@@ -9,7 +9,6 @@ export {
|
||||
bulgeArc,
|
||||
bulgeArcPoints,
|
||||
bulgePolylinePoints,
|
||||
bulgeBetweenAngles,
|
||||
bulgeFromSagittaPoint,
|
||||
bulgePointAt,
|
||||
bulgeThroughPoint,
|
||||
@@ -80,7 +79,6 @@ export {
|
||||
} from "../geometry/lineSegments";
|
||||
|
||||
export {
|
||||
openingVerticalExtent,
|
||||
} from "../geometry/opening";
|
||||
export { autoExteriorDimensions } from "../geometry/autoDimensions";
|
||||
export * as polygonBool from "../geometry/polygonBool";
|
||||
@@ -95,7 +93,6 @@ export {
|
||||
type PolylineVertexType,
|
||||
canSetVertexType,
|
||||
vertexTypeOf,
|
||||
withVertexType,
|
||||
} from "../geometry/polylineVertexType";
|
||||
|
||||
export {
|
||||
@@ -238,7 +235,6 @@ export {
|
||||
meetScale,
|
||||
mmToPx,
|
||||
pointInPolygon,
|
||||
pointSegDistPx,
|
||||
printStrokeVb,
|
||||
scaleFromView,
|
||||
toScreen,
|
||||
|
||||
@@ -128,3 +128,44 @@ describe("applyOps (schnelle Fassung) = Referenz", () => {
|
||||
expect(out.walls).toEqual([{ id: "a", z: 1 }, { id: "b" }, { id: "c" }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyOps: id-Index über die Aufrufe hinweg", () => {
|
||||
it("Ketten und Verzweigungen grosser Listen (geteilter Index) = Referenz", () => {
|
||||
const walls = Array.from({ length: 200 }, (_, i) => ({ ...sampleProject.walls[0], id: `w${i}` }));
|
||||
const big: Project = { ...sampleProject, walls, drawings2d: [] };
|
||||
const r = rng(7);
|
||||
const history: Project[] = [big];
|
||||
for (let step = 0; step < 600; step++) {
|
||||
// Meist auf dem letzten Stand weiter, manchmal auf einem älteren (Undo-Basis, fremde Projekte).
|
||||
const base = r() < 0.7 ? history[history.length - 1] : history[Math.floor(r() * history.length)];
|
||||
const ids = ["w0", "w5", "w199", "w150", `n${Math.floor(r() * 40)}`, `n${Math.floor(r() * 40)}`];
|
||||
const ops: CoreOp[] = [];
|
||||
for (let k = 0, n = 1 + Math.floor(r() * 4); k < n; k++) {
|
||||
const x = r();
|
||||
const id = ids[Math.floor(r() * ids.length)];
|
||||
if (x < 0.6) ops.push({ kind: "replace", collection: "walls", entity: { id, v: step } });
|
||||
else if (x < 0.8) ops.push({ kind: "add", collection: "walls", items: [{ id: `n${Math.floor(r() * 40)}` }] });
|
||||
else if (x < 0.9) ops.push({ kind: "add", collection: "walls", items: [{ id }], at: Math.floor(r() * 300) });
|
||||
else ops.push({ kind: "remove", collection: "walls", ids: [id] });
|
||||
}
|
||||
// Positions-Hinweise des Kerns (erstes Vorkommen, wie `Document::last_hits`): richtig, auf ein
|
||||
// anderes Element, ausserhalb oder fehlend — das Ergebnis bleibt gleich.
|
||||
let hits: number[] | undefined;
|
||||
if (r() < 0.6) {
|
||||
hits = [];
|
||||
let cur = base;
|
||||
for (const op of ops) {
|
||||
const list = cur.walls as unknown as Entity[];
|
||||
const first = op.kind === "replace" ? list.findIndex((e) => e.id === op.entity.id) : -1;
|
||||
const other = list.findIndex((e, i) => i >= Math.floor(r() * list.length) && op.kind === "replace" && e.id !== op.entity.id);
|
||||
const x = r();
|
||||
hits.push(x < 0.6 ? first : x < 0.8 ? other : x < 0.9 ? list.length + 3 : -1);
|
||||
cur = referenceApplyOps(cur, [op]);
|
||||
}
|
||||
}
|
||||
const a = applyOps(base, ops, hits);
|
||||
expect(JSON.stringify(a.walls)).toBe(JSON.stringify(referenceApplyOps(base, ops).walls));
|
||||
history.push(a);
|
||||
}
|
||||
});
|
||||
});
|
||||
+76
-35
@@ -37,25 +37,79 @@ export type CoreOp =
|
||||
|
||||
/**
|
||||
* Wendet eine Op-Folge rein an (kein Zugriff auf Store/UI). Unberührte Listen und Elemente behalten
|
||||
* ihre Identität. Innerhalb eines Aufrufs wird jede Liste höchstens einmal kopiert und für
|
||||
* `replace`-Serien (Auswahl verschieben: hunderte Elemente) über einen id-Index angesprochen —
|
||||
* Ergebnis gleich der einfachen Fassung (Test `ops.apply.test.ts`).
|
||||
* ihre Identität. Innerhalb eines Aufrufs wird jede Liste höchstens einmal kopiert. `replace` findet
|
||||
* sein Element über `hits` (je Op die Position, die der Kern beim Anwenden getroffen hat,
|
||||
* `ProjectDocument`; wird nachgeprüft) oder sonst über {@link indexOfId} — ein Griff-Schritt an einer
|
||||
* grossen Liste sucht so nicht linear. Ergebnis gleich der einfachen Fassung (Test `ops.apply.test.ts`).
|
||||
*/
|
||||
export function applyOps(project: Project, ops: readonly CoreOp[]): Project {
|
||||
export function applyOps(project: Project, ops: readonly CoreOp[], hits?: ArrayLike<number>): Project {
|
||||
if (ops.length === 0) return project;
|
||||
const st: ApplyState = { cur: { ...(project as unknown as Record<string, unknown>) }, owned: new Set(), index: new Map() };
|
||||
for (const op of ops) applyOne(st, op);
|
||||
const st: ApplyState = { cur: { ...(project as unknown as Record<string, unknown>) }, owned: new Set(), hit: -1 };
|
||||
for (let k = 0; k < ops.length; k++) {
|
||||
st.hit = hits?.[k] ?? -1;
|
||||
applyOne(st, ops[k]);
|
||||
}
|
||||
return st.cur as unknown as Project;
|
||||
}
|
||||
|
||||
/** Zustand eines `applyOps`-Aufrufs: `cur` ist eine eigene Kopie der obersten Ebene; Listen in
|
||||
* `owned` wurden in diesem Aufruf neu angelegt (dürfen verändert werden), `index` = id → Position
|
||||
* (erstes Vorkommen) solcher Listen. */
|
||||
* `owned` wurden in diesem Aufruf neu angelegt (dürfen verändert werden); `hit` = vermutete Position
|
||||
* des Elements der laufenden `replace`-Op (−1 = keine). */
|
||||
interface ApplyState {
|
||||
cur: Record<string, unknown>;
|
||||
owned: Set<string>;
|
||||
/** `null` = einmal linear gesucht, der Index wird bei der nächsten Suche gebaut. */
|
||||
index: Map<string, Map<string, number> | null>;
|
||||
hit: number;
|
||||
}
|
||||
|
||||
// ── id-Index der Listen ──────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* id → Position (erstes Vorkommen) je Liste, für Suchen ohne Positions-Hinweis des Kerns (Op-Bauer,
|
||||
* `findItem`). Listen der Leseansicht ändern sich nie (jede Änderung legt eine neue an); eine Kopie mit
|
||||
* denselben Positionen (`replace`, `add` am Ende) übernimmt den Index der Vorlage samt der neuen ids.
|
||||
* Teilen sich so mehrere Listen einen Index, enthält er die ids jeder von ihnen; ein Treffer wird an
|
||||
* der Liste nachgeprüft (sonst lineare Suche), kein Eintrag heisst „nicht enthalten". Der Index kostet
|
||||
* in V8 etwa das Zwanzigfache einer linearen Suche (20 000 Elemente ≈ 6 ms): gebaut wird er erst bei
|
||||
* der zweiten Suche in derselben Listen-Linie (`null` = einmal linear gesucht).
|
||||
*/
|
||||
const ID_INDEX = new WeakMap<readonly unknown[], Map<unknown, number> | null>();
|
||||
|
||||
/** Ab dieser Länge wird ein Index gebaut (darunter ist die lineare Suche billiger). */
|
||||
const INDEX_MIN_LEN = 32;
|
||||
|
||||
/** Position des ersten Elements mit `id` in `list` (−1 = keins); Index je Listen-Linie gemerkt. */
|
||||
export function indexOfId(list: readonly unknown[], id: unknown): number {
|
||||
const linear = () => list.findIndex((e) => (e as Entity | null)?.id === id);
|
||||
if (list.length < INDEX_MIN_LEN) return linear();
|
||||
let idx = ID_INDEX.get(list);
|
||||
if (idx === undefined) {
|
||||
ID_INDEX.set(list, null);
|
||||
return linear();
|
||||
}
|
||||
if (idx === null) {
|
||||
idx = new Map();
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
const k = (list[i] as Entity | null)?.id;
|
||||
if (!idx.has(k)) idx.set(k, i);
|
||||
}
|
||||
ID_INDEX.set(list, idx);
|
||||
}
|
||||
const i = idx.get(id);
|
||||
if (i === undefined) return -1;
|
||||
return (list[i] as Entity | null)?.id === id ? i : linear();
|
||||
}
|
||||
|
||||
/** `copy` hat dieselben Positionen wie `src` (plus Elemente am Ende): Index (bzw. Such-Marke) übernehmen. */
|
||||
function shareIndex(src: readonly unknown[], copy: readonly unknown[]): void {
|
||||
const idx = ID_INDEX.get(src);
|
||||
if (idx === undefined) return;
|
||||
if (idx !== null) {
|
||||
for (let i = src.length; i < copy.length; i++) {
|
||||
const k = (copy[i] as Entity | null)?.id;
|
||||
if (!idx.has(k)) idx.set(k, i);
|
||||
}
|
||||
}
|
||||
ID_INDEX.set(copy, idx);
|
||||
}
|
||||
|
||||
function listOf(cur: Record<string, unknown>, collection: string): Entity[] {
|
||||
@@ -63,11 +117,10 @@ function listOf(cur: Record<string, unknown>, collection: string): Entity[] {
|
||||
return Array.isArray(v) ? (v as Entity[]) : [];
|
||||
}
|
||||
|
||||
/** Setzt `collection` auf eine neue (eigene) Liste; ein vorhandener Index verfällt. */
|
||||
/** Setzt `collection` auf eine neue (eigene) Liste. */
|
||||
function putList(st: ApplyState, collection: string, list: Entity[]): void {
|
||||
st.cur[collection] = list;
|
||||
st.owned.add(collection);
|
||||
st.index.delete(collection);
|
||||
}
|
||||
|
||||
function applyOne(st: ApplyState, op: CoreOp): void {
|
||||
@@ -76,7 +129,6 @@ function applyOne(st: ApplyState, op: CoreOp): void {
|
||||
case "setField": {
|
||||
// Der Wert gehört dem Aufrufer: nie verändern.
|
||||
st.owned.delete(op.key);
|
||||
st.index.delete(op.key);
|
||||
if (op.value !== undefined && op.at !== undefined && !(op.key in cur)) {
|
||||
// Neues Feld an Position `at` (wie `shift_insert` im Kern).
|
||||
const entries = Object.entries(cur);
|
||||
@@ -91,7 +143,9 @@ function applyOne(st: ApplyState, op: CoreOp): void {
|
||||
case "add": {
|
||||
const list = listOf(cur, op.collection);
|
||||
const at = op.at === undefined ? list.length : Math.max(0, Math.min(list.length, op.at));
|
||||
putList(st, op.collection, [...list.slice(0, at), ...op.items, ...list.slice(at)]);
|
||||
const next = [...list.slice(0, at), ...op.items, ...list.slice(at)];
|
||||
if (at === list.length) shareIndex(list, next);
|
||||
putList(st, op.collection, next);
|
||||
return;
|
||||
}
|
||||
case "replace": {
|
||||
@@ -99,30 +153,17 @@ function applyOne(st: ApplyState, op: CoreOp): void {
|
||||
let list: Entity[];
|
||||
if (st.owned.has(c)) list = cur[c] as Entity[];
|
||||
else {
|
||||
list = listOf(cur, c).slice();
|
||||
const src = listOf(cur, c);
|
||||
list = src.slice();
|
||||
shareIndex(src, list);
|
||||
putList(st, c, list);
|
||||
}
|
||||
// Erste Suche in dieser Liste linear (ein Drag-Schritt), ab der zweiten über den Index.
|
||||
let idx = st.index.get(c);
|
||||
let at: number | undefined;
|
||||
if (idx === undefined) {
|
||||
st.index.set(c, null);
|
||||
const i = list.findIndex((e) => e?.id === op.entity.id);
|
||||
at = i < 0 ? undefined : i;
|
||||
} else {
|
||||
if (idx === null) {
|
||||
idx = new Map();
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
const id = list[i]?.id;
|
||||
if (!idx.has(id)) idx.set(id, i);
|
||||
}
|
||||
st.index.set(c, idx);
|
||||
}
|
||||
at = idx.get(op.entity.id);
|
||||
}
|
||||
if (at === undefined) {
|
||||
idx?.set(op.entity.id, list.length);
|
||||
const h = st.hit;
|
||||
const at = h >= 0 && h < list.length && list[h]?.id === op.entity.id ? h : indexOfId(list, op.entity.id);
|
||||
if (at < 0) {
|
||||
list.push(op.entity);
|
||||
const idx = ID_INDEX.get(list);
|
||||
if (idx && !idx.has(op.entity.id)) idx.set(op.entity.id, list.length - 1);
|
||||
} else list[at] = op.entity;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
// {@link opsMutation} die Ops mit — `setProject` nimmt dann die Ops ohne Differenz.
|
||||
|
||||
import type { Project } from "../model/types";
|
||||
import { applyOps } from "./ops";
|
||||
import { applyOps, indexOfId } from "./ops";
|
||||
import type { CoreOp } from "./ops";
|
||||
|
||||
/** Projekt-Felder, die Listen von Elementen mit `id` sind (walls, drawings2d, rooms, …). */
|
||||
@@ -34,7 +34,9 @@ export function itemsOf<K extends EntityCollection>(p: Project, collection: K):
|
||||
|
||||
/** Element `id` aus `collection` (erstes Vorkommen). */
|
||||
export function findItem<K extends EntityCollection>(p: Project, collection: K, id: string): EntityOf<K> | undefined {
|
||||
return itemsOf(p, collection).find((e) => (e as { id: string }).id === id);
|
||||
const list = itemsOf(p, collection);
|
||||
const i = indexOfId(list, id);
|
||||
return i < 0 ? undefined : list[i];
|
||||
}
|
||||
|
||||
/** Ersetzt ein Element (gleiche id, Position bleibt). */
|
||||
|
||||
@@ -24,10 +24,6 @@ export function initCoreSync(bytes: BufferSource): void {
|
||||
ready = true;
|
||||
}
|
||||
|
||||
export function coreReady(): boolean {
|
||||
return ready;
|
||||
}
|
||||
|
||||
/** Der geladene Kern; wirft, wenn `initCore()` noch nicht gelaufen ist (Programmierfehler). */
|
||||
export function core(): CoreModule {
|
||||
if (!ready) throw new Error("Rust-Kern nicht geladen: initCore() muss vor der ersten Kern-Funktion laufen.");
|
||||
|
||||
@@ -70,37 +70,6 @@ export async function extrudeCircle(
|
||||
return JSON.parse(json) as ExtrudedMesh;
|
||||
}
|
||||
|
||||
export type BooleanOp = "union" | "difference" | "intersection";
|
||||
|
||||
export interface BooleanMeshResult {
|
||||
positions: number[];
|
||||
indices: number[];
|
||||
empty: boolean;
|
||||
}
|
||||
|
||||
/** Boolesche Operation zweier Dreiecks-Meshes (Mesh-Ebenen-CSG via csgrs,
|
||||
* truck-Integration Phase 4). Beide Meshes müssen konsistent nach außen
|
||||
* gewundene Dreiecke haben (Rechte-Hand-Regel) — sonst liefert csgrs ein
|
||||
* falsches Ergebnis, ohne das zu erkennen. */
|
||||
export async function booleanMesh(
|
||||
a: ExtrudedMesh,
|
||||
b: ExtrudedMesh,
|
||||
op: BooleanOp,
|
||||
): Promise<BooleanMeshResult> {
|
||||
const json = await guarded((m) =>
|
||||
m.boolean_mesh(
|
||||
JSON.stringify({
|
||||
a_positions: a.positions,
|
||||
a_indices: a.indices,
|
||||
b_positions: b.positions,
|
||||
b_indices: b.indices,
|
||||
op,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return JSON.parse(json) as BooleanMeshResult;
|
||||
}
|
||||
|
||||
// ── B-Rep-Körper (truck 0.6): Spezifikation → Mesh / STEP ────────────────────
|
||||
|
||||
/** Ein Loft-Schnitt: Höhe + geschlossener Ring [x0,y0,x1,y1,…]. */
|
||||
|
||||
@@ -120,21 +120,6 @@ export function arcThroughPoints(a: Vec2, through: Vec2, b: Vec2): ArcParams | n
|
||||
return toArcParams(core().arc_through_points(a.x, a.y, through.x, through.y, b.x, b.y));
|
||||
}
|
||||
|
||||
/**
|
||||
* Bulge-Wert für den Teilbogen desselben Kreises (center, r) von Winkel `aFrom` zu `aTo`, in der
|
||||
* durch `sweepSign` vorgegebenen Schwenkrichtung (+1 = CCW, −1 = CW), z. B. beim Zuschneiden/
|
||||
* Offsetten eines Bogen-Segments.
|
||||
*/
|
||||
export function bulgeBetweenAngles(
|
||||
center: Vec2,
|
||||
r: number,
|
||||
aFrom: number,
|
||||
aTo: number,
|
||||
sweepSign: 1 | -1,
|
||||
): number {
|
||||
return core().bulge_between_angles(center.x, center.y, r, aFrom, aTo, sweepSign);
|
||||
}
|
||||
|
||||
/**
|
||||
* Kreisbogen durch zwei Endpunkte `a`→`b` mit vorgegebenem Radius `r` (Methode „Start-Ende-
|
||||
* Radius"). `near` (typischerweise der Cursor) wählt die Seite der Sehne; es entsteht immer der
|
||||
|
||||
@@ -32,44 +32,11 @@ export function normalizeOutline(pts: Vec2[]): Vec2[] | null {
|
||||
return isCCW(clean) ? clean : clean.slice().reverse();
|
||||
}
|
||||
|
||||
/** Ob ein Umriss ein gültiges (nicht entartetes) Deckenpolygon bildet. */
|
||||
export function isValidOutline(pts: Vec2[]): boolean {
|
||||
const norm = normalizeOutline(pts);
|
||||
return norm != null && ceilingArea(norm) >= MIN_CEILING_AREA;
|
||||
}
|
||||
|
||||
/** Fläche eines Deckenumrisses in m² (immer positiv). */
|
||||
export function ceilingArea(pts: Vec2[]): number {
|
||||
return Math.abs(signedArea(pts));
|
||||
}
|
||||
|
||||
/** Schwerpunkt (Zentroid) des Umriss-Polygons (für HUD/Beschriftung). */
|
||||
export function outlineCentroid(pts: Vec2[]): Vec2 {
|
||||
const a = signedArea(pts);
|
||||
if (Math.abs(a) < 1e-12) {
|
||||
// Entartet: einfacher Mittelwert der Punkte.
|
||||
let sx = 0,
|
||||
sy = 0;
|
||||
for (const p of pts) {
|
||||
sx += p.x;
|
||||
sy += p.y;
|
||||
}
|
||||
const n = pts.length || 1;
|
||||
return { x: sx / n, y: sy / n };
|
||||
}
|
||||
let cx = 0,
|
||||
cy = 0;
|
||||
for (let i = 0; i < pts.length; i++) {
|
||||
const p = pts[i];
|
||||
const q = pts[(i + 1) % pts.length];
|
||||
const cr = p.x * q.y - q.x * p.y;
|
||||
cx += (p.x + q.x) * cr;
|
||||
cy += (p.y + q.y) * cr;
|
||||
}
|
||||
const f = 1 / (6 * a);
|
||||
return { x: cx * f, y: cy * f };
|
||||
}
|
||||
|
||||
/**
|
||||
* Punkt-in-Polygon-Test (Ray-Casting) für einen geschlossenen Umriss — dient dem
|
||||
* Body-Select einer Decke im Grundriss/3D. Randpunkte gelten als innen genug.
|
||||
|
||||
@@ -28,6 +28,7 @@ export type GripRequest =
|
||||
| { op: "ceilingEdge" | "roomEdge"; id: string; a: number; b: number; delta: P }
|
||||
| { op: "insertPoint"; id: string; seg: number; pt: P }
|
||||
| { op: "deletePoint"; id: string; index: number }
|
||||
| { op: "vertexType"; id: string; index: number; vertexType: "corner" | "arc" | "spline" }
|
||||
| { op: "wallThickness" | "ceilingThickness"; id: string; thickness: number; newId: string; newName: string };
|
||||
|
||||
/** Punkt als Anfrage-Paar. */
|
||||
@@ -112,8 +113,8 @@ export interface VerticalExtent {
|
||||
}
|
||||
|
||||
/**
|
||||
* UK/OK von Wänden und Decken aus dem Kern (`selection_info.rs::vertical_extents`, Regeln wie
|
||||
* `wallVerticalExtent`/`ceilingVerticalExtent`): Geschoss-Bindungen und Deckentypen aus `project`, die
|
||||
* UK/OK von Wänden und Decken aus dem Kern (`selection_info.rs::vertical_extents`, Regeln
|
||||
* `model/helpers.rs::heights`): Geschoss-Bindungen und Deckentypen aus `project`, die
|
||||
* Elemente selbst als ganze Fassung (auch gerade gezogene, noch nicht übernommene — 3D-Griffe).
|
||||
*/
|
||||
export function verticalExtents(
|
||||
|
||||
+4
-34
@@ -1,7 +1,7 @@
|
||||
// Geometrie-Helfer für Öffnungen (Fenster/Türen) — reine Funktionen, die eine
|
||||
// `Opening` relativ zu ihrer Wirts-Wand in konkrete Welt-Geometrie auflösen:
|
||||
// • die Öffnungs-Lücke entlang der Wandachse (from/to in Metern),
|
||||
// • die vertikale Lage (UK/OK der Öffnung, absolut in Metern).
|
||||
// • die Öffnungs-Lücke entlang der Wandachse (from/to in Metern), die Pfosten.
|
||||
// (Die vertikale Lage rechnet der Kern: `model3d.rs`/`plan/section.rs`, UK/OK der Wand: `model/helpers.rs::heights`.)
|
||||
//
|
||||
// Da JEDE Größe aus der aktuellen Wandachse (`wall.start`/`wall.end`) abgeleitet
|
||||
// wird, folgt eine Öffnung ihrer Wand automatisch, sobald die Wand bewegt wird —
|
||||
@@ -9,9 +9,8 @@
|
||||
//
|
||||
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
|
||||
|
||||
import type { Opening, Project, Vec2, Wall } from "../model/types";
|
||||
import { along, leftNormal, normalize, sub } from "../model/geometry";
|
||||
import { wallVerticalExtent } from "../model/wall";
|
||||
import type { Opening, Vec2, Wall } from "../model/types";
|
||||
import { along } from "../model/geometry";
|
||||
|
||||
/** Achslänge einer Wand (Meter). */
|
||||
export function wallAxisLength(wall: Wall): number {
|
||||
@@ -34,29 +33,6 @@ export function openingInterval(
|
||||
return { from, to };
|
||||
}
|
||||
|
||||
/**
|
||||
* Vertikale Lage einer Öffnung (absolute Z-Werte in Metern) relativ zur Wand-UK.
|
||||
* Türen sitzen am Boden (sillHeight 0); Fenster ab Brüstung. Die OK wird auf die
|
||||
* Wand-OK geklemmt, damit die Öffnung nie über den Wandkopf hinausragt.
|
||||
*/
|
||||
export function openingVerticalExtent(
|
||||
project: Project,
|
||||
wall: Wall,
|
||||
o: Opening,
|
||||
): { zBottom: number; zTop: number } {
|
||||
const { zBottom, zTop } = wallVerticalExtent(project, wall);
|
||||
const sill = Math.max(0, o.sillHeight);
|
||||
const oBottom = zBottom + sill;
|
||||
const oTop = Math.min(zTop, oBottom + o.height);
|
||||
return { zBottom: oBottom, zTop: oTop };
|
||||
}
|
||||
|
||||
/** Einheits-Laufrichtung (u) und linke Normale (n) der Wandachse. */
|
||||
export function wallAxisFrame(wall: Wall): { u: Vec2; n: Vec2 } {
|
||||
const u = normalize(sub(wall.end, wall.start));
|
||||
return { u, n: leftNormal(u) };
|
||||
}
|
||||
|
||||
/** Die beiden Pfosten-Punkte (auf der Achse) einer Öffnung im Grundriss. */
|
||||
export function openingJambs(
|
||||
wall: Wall,
|
||||
@@ -70,9 +46,3 @@ export function openingJambs(
|
||||
};
|
||||
}
|
||||
|
||||
/** Mittelpunkt einer Öffnung im Grundriss (Achse) — für HUD/Auswahl-Anker. */
|
||||
export function openingCenter(wall: Wall, o: Opening): Vec2 | null {
|
||||
const iv = openingInterval(wall, o);
|
||||
if (!iv) return null;
|
||||
return along(wall.start, wall.end, (iv.from + iv.to) / 2);
|
||||
}
|
||||
@@ -1,59 +1,61 @@
|
||||
// Punkttypen einer Polylinie: Rechnung im Kern (`polyline_vertex.rs`, eigene Rust-Tests); hier die
|
||||
// Fassade für das Kontextmenü und die Store-Aktion `setPolylineVertexType` (Griff-Änderung im Kern).
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { bulgeArc, bulgeArcPoints } from "./bulge";
|
||||
import { canSetVertexType, vertexTypeOf, withVertexType } from "./polylineVertexType";
|
||||
import { canSetVertexType, vertexTypeOf } from "./polylineVertexType";
|
||||
import { getState } from "../state/appStore";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import type { Drawing2D, Vec2 } from "../model/types";
|
||||
|
||||
const g = { pts: [{ x: 0, y: 0 }, { x: 2, y: 1 }, { x: 4, y: 0 }, { x: 6, y: 1 }], closed: false };
|
||||
|
||||
/** Setzt den Punkttyp über den Store und liefert die Bulges (fehlend = alle gerade). */
|
||||
function setType(pts: Vec2[], closed: boolean, i: number, type: "corner" | "arc" | "spline", bulge?: number[]): number[] | undefined {
|
||||
const d = { id: "pl", levelId: sampleProject.drawingLevels[0].id, categoryCode: "01", geom: { shape: "polyline", pts, closed, ...(bulge ? { bulge } : {}) } };
|
||||
getState().loadProject({ ...structuredClone(sampleProject), drawings2d: [d as Drawing2D] });
|
||||
getState().setPolylineVertexType("pl", i, type);
|
||||
const geom = getState().project.drawings2d[0].geom;
|
||||
return geom.shape === "polyline" ? geom.bulge : undefined;
|
||||
}
|
||||
|
||||
describe("Punkttypen einer Polylinie", () => {
|
||||
it("Eckpunkt setzt beide Nachbarsegmente gerade", () => {
|
||||
const b = withVertexType({ ...g, bulge: [0.3, -0.2, 0.1] }, 1, "corner");
|
||||
expect(b).toEqual([0, 0, 0.1]);
|
||||
expect(setType(g.pts, false, 1, "corner", [0.3, -0.2, 0.1])).toEqual([0, 0, 0.1]);
|
||||
expect(setType(g.pts, false, 1, "corner", [0.3, -0.2, 0])).toBeUndefined();
|
||||
});
|
||||
|
||||
it("Bogenpunkt: beide Segmente liegen auf EINEM Kreis durch die drei Punkte", () => {
|
||||
const b = withVertexType(g, 1, "arc");
|
||||
const b = setType(g.pts, false, 1, "arc")!;
|
||||
const a1 = bulgeArc(g.pts[0], g.pts[1], b[0])!;
|
||||
const a2 = bulgeArc(g.pts[1], g.pts[2], b[1])!;
|
||||
expect(a1).not.toBeNull();
|
||||
expect(Math.hypot(a1.center.x - a2.center.x, a1.center.y - a2.center.y)).toBeLessThan(1e-6);
|
||||
expect(a1.r).toBeCloseTo(a2.r, 6);
|
||||
expect(vertexTypeOf({ ...g, bulge: b }, 1)).toBe("arc");
|
||||
// Die Bögen bauchen NACH OBEN aus (Punkt 1 liegt oben) — kein Zickzack über den Kreis
|
||||
const mid1 = bulgeArcPoints(g.pts[0], g.pts[1], b[0]);
|
||||
const apex = mid1[mid1.length / 2 | 0];
|
||||
expect(apex.y).toBeGreaterThan(0.5);
|
||||
expect(mid1[(mid1.length / 2) | 0].y).toBeGreaterThan(0.5);
|
||||
});
|
||||
|
||||
it("Splinepunkt: Tangenten beider Segmente im Punkt stimmen überein", () => {
|
||||
const g = { pts: [{ x: 0, y: 0 }, { x: 2, y: 1 }, { x: 5, y: 0.2 }], closed: false };
|
||||
const b = withVertexType(g, 1, "spline");
|
||||
// exakte Tangenten aus den Bögen (senkrecht zum Radius, Richtung nach Umlaufsinn)
|
||||
const tan = (a: { x: number; y: number }, c: { x: number; y: number }, bb: number, atEnd: boolean) => {
|
||||
const arc = bulgeArc(a, c, bb)!;
|
||||
const ang = atEnd ? arc.a0 + arc.sweep : arc.a0;
|
||||
const sg = Math.sign(arc.sweep);
|
||||
return Math.atan2(Math.cos(ang) * sg, -Math.sin(ang) * sg);
|
||||
};
|
||||
const t1 = tan(g.pts[0], g.pts[1], b[0], true);
|
||||
const t2 = tan(g.pts[1], g.pts[2], b[1], false);
|
||||
expect(Math.abs(t1 - t2)).toBeLessThan(1e-6);
|
||||
// Tangente = Richtung Vorgänger→Nachfolger
|
||||
expect(Math.abs(t2 - Math.atan2(0.2, 5))).toBeLessThan(1e-6);
|
||||
expect(vertexTypeOf({ ...g, bulge: b }, 1)).toBe("spline");
|
||||
});
|
||||
|
||||
it("offene Enden: Bogen/Spline nicht möglich, Ecke schon", () => {
|
||||
it("Splinepunkt: Typ wird erkannt, offene Enden lassen nur die Ecke zu", () => {
|
||||
const pts = [{ x: 0, y: 0 }, { x: 2, y: 1 }, { x: 5, y: 0.2 }];
|
||||
expect(vertexTypeOf({ pts, closed: false, bulge: setType(pts, false, 1, "spline") }, 1)).toBe("spline");
|
||||
expect(vertexTypeOf(g, 1)).toBe("corner");
|
||||
expect(canSetVertexType(g, 0, "arc")).toBe(false);
|
||||
expect(canSetVertexType(g, 3, "spline")).toBe(false);
|
||||
expect(canSetVertexType(g, 0, "corner")).toBe(true);
|
||||
expect(canSetVertexType(g, 1, "spline")).toBe(true);
|
||||
});
|
||||
|
||||
it("geschlossene Polylinie: erster Punkt hat beide Nachbarn", () => {
|
||||
const sq = { pts: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }, { x: 0, y: 1 }], closed: true };
|
||||
const b = withVertexType(sq, 0, "arc");
|
||||
it("geschlossene Polylinie: erster Punkt hat beide Nachbarn; gesperrt ändert nichts", () => {
|
||||
const sq = [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }, { x: 0, y: 1 }];
|
||||
const b = setType(sq, true, 0, "arc")!;
|
||||
expect(b.length).toBe(4);
|
||||
expect(b[3]).not.toBe(0);
|
||||
expect(b[0]).not.toBe(0);
|
||||
expect(b[1]).toBe(0);
|
||||
const depth = getState().undoDepth;
|
||||
getState().updateDrawing2D("pl", { locked: true });
|
||||
getState().setPolylineVertexType("pl", 0, "corner");
|
||||
expect(getState().undoDepth).toBe(depth + 1);
|
||||
});
|
||||
});
|
||||
@@ -1,19 +1,11 @@
|
||||
// Punkttypen einer Polylinie (ArchiCAD/Vectorworks-artig): Eckpunkt, Bogenpunkt,
|
||||
// Splinepunkt. Rein als Umrechnung der Segment-Bögen (`bulge`) der beiden am Punkt
|
||||
// anliegenden Segmente — alle Renderer/Exporte verstehen Bulges bereits, es gibt
|
||||
// also kein neues Geometrie-Feld.
|
||||
//
|
||||
// • Eckpunkt: beide Segmente gerade (bulge 0).
|
||||
// • Bogenpunkt: EIN Kreisbogen durch Vorgänger, Punkt und Nachfolger.
|
||||
// • Splinepunkt: tangential glatter Übergang — die Tangente im Punkt ist parallel
|
||||
// zur Verbindung Vorgänger→Nachfolger (wie bei einer Catmull-Rom-Kurve), beide
|
||||
// Segmente werden zu Bögen, die diese Tangente teilen.
|
||||
//
|
||||
// Die Bögen werden über ihren SCHEITELPUNKT bestimmt und mit `bulgeFromSagittaPoint`
|
||||
// in einen Bulge übersetzt — so bleibt die Vorzeichen-Konvention an EINER Stelle.
|
||||
// Punkttypen einer Polylinie (ArchiCAD/Vectorworks-artig): Eckpunkt, Bogenpunkt, Splinepunkt — als
|
||||
// Umrechnung der Segment-Bögen (`bulge`) der beiden am Punkt anliegenden Segmente. Gerechnet im
|
||||
// Rust-Kern (`src-tauri/core/src/polyline_vertex.rs`): das Setzen als Griff-Änderung auf dem Dokument
|
||||
// (Store `setPolylineVertexType`, Anfrage `vertexType`), die Abfrage für das Kontextmenü hier über die
|
||||
// Bindung `polyline_vertex_info`.
|
||||
|
||||
import type { Vec2 } from "../model/types";
|
||||
import { bulgeArc, bulgeFromSagittaPoint } from "./bulge";
|
||||
import { core } from "../engine/coreWasm";
|
||||
|
||||
export type PolylineVertexType = "corner" | "arc" | "spline";
|
||||
|
||||
@@ -23,160 +15,24 @@ interface PolylineLike {
|
||||
bulge?: number[];
|
||||
}
|
||||
|
||||
const EPS = 1e-9;
|
||||
const TYPES: PolylineVertexType[] = ["corner", "arc", "spline"];
|
||||
|
||||
/** Indizes des ein- und ausgehenden Segments von Punkt `i` (null = keins). */
|
||||
function adjacentSegments(n: number, closed: boolean, i: number): { inSeg: number | null; outSeg: number | null } {
|
||||
const inSeg = i > 0 ? i - 1 : closed ? n - 1 : null;
|
||||
const outSeg = i < n - 1 ? i : closed ? n - 1 : null;
|
||||
return { inSeg, outSeg };
|
||||
}
|
||||
|
||||
/** Nachbarpunkte von `i` (null an offenen Enden). */
|
||||
function neighbors(g: PolylineLike, i: number): { prev: Vec2 | null; next: Vec2 | null } {
|
||||
const n = g.pts.length;
|
||||
const prev = i > 0 ? g.pts[i - 1] : g.closed ? g.pts[n - 1] : null;
|
||||
const next = i < n - 1 ? g.pts[i + 1] : g.closed ? g.pts[0] : null;
|
||||
return { prev, next };
|
||||
}
|
||||
|
||||
const cross = (a: Vec2, b: Vec2) => a.x * b.y - a.y * b.x;
|
||||
const sub = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x - b.x, y: a.y - b.y });
|
||||
|
||||
/** Umkreismittelpunkt von a,b,c (null bei kollinearen Punkten). */
|
||||
function circumcenter(a: Vec2, b: Vec2, c: Vec2): Vec2 | null {
|
||||
const d = 2 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y));
|
||||
if (Math.abs(d) < EPS) return null;
|
||||
const a2 = a.x * a.x + a.y * a.y, b2 = b.x * b.x + b.y * b.y, c2 = c.x * c.x + c.y * c.y;
|
||||
return {
|
||||
x: (a2 * (b.y - c.y) + b2 * (c.y - a.y) + c2 * (a.y - b.y)) / d,
|
||||
y: (a2 * (c.x - b.x) + b2 * (a.x - c.x) + c2 * (b.x - a.x)) / d,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Bulge des Kreisbogens a→b auf dem Kreis um `c`, und zwar des Bogens, der NICHT
|
||||
* durch `other` läuft (Scheitel auf der anderen Seite der Sehne als `other`).
|
||||
*/
|
||||
function bulgeOnCircle(a: Vec2, b: Vec2, c: Vec2, other: Vec2): number {
|
||||
const r = Math.hypot(a.x - c.x, a.y - c.y);
|
||||
const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
|
||||
let u = sub(mid, c);
|
||||
let len = Math.hypot(u.x, u.y);
|
||||
if (len < EPS) {
|
||||
const d = sub(b, a);
|
||||
u = { x: -d.y, y: d.x };
|
||||
len = Math.hypot(u.x, u.y);
|
||||
/** `[typ, ecke, bogen, spline]` des Kerns (typ −1 = gemischt/kein Punkt; danach setzbar 1/0). */
|
||||
function info(g: PolylineLike, i: number): Float64Array {
|
||||
const pts = new Float64Array(g.pts.length * 2);
|
||||
for (let k = 0; k < g.pts.length; k++) {
|
||||
pts[2 * k] = g.pts[k].x;
|
||||
pts[2 * k + 1] = g.pts[k].y;
|
||||
}
|
||||
u = { x: u.x / len, y: u.y / len };
|
||||
const side = (p: Vec2) => Math.sign(cross(sub(b, a), sub(p, a)));
|
||||
const cand1 = { x: c.x + u.x * r, y: c.y + u.y * r };
|
||||
const cand2 = { x: c.x - u.x * r, y: c.y - u.y * r };
|
||||
const apex = side(cand1) !== side(other) ? cand1 : cand2;
|
||||
return bulgeFromSagittaPoint(a, b, apex);
|
||||
}
|
||||
|
||||
/** Tangente (Fahrtrichtung a→b) des Bulge-Bogens am Anfang bzw. Ende. */
|
||||
function arcTangent(a: Vec2, b: Vec2, bulge: number, atEnd: boolean): Vec2 {
|
||||
const arc = bulgeArc(a, b, bulge);
|
||||
if (!arc) {
|
||||
const d = sub(b, a);
|
||||
const l = Math.hypot(d.x, d.y) || 1;
|
||||
return { x: d.x / l, y: d.y / l };
|
||||
}
|
||||
const ang = atEnd ? arc.a0 + arc.sweep : arc.a0;
|
||||
const s = Math.sign(arc.sweep) || 1;
|
||||
return { x: -Math.sin(ang) * s, y: Math.cos(ang) * s };
|
||||
}
|
||||
|
||||
/**
|
||||
* Bulge des Bogens a→b mit gegebener Tangente `t` am Ende (atEnd) bzw. Anfang.
|
||||
* Betrag aus dem Winkel Sehne↔Tangente, Vorzeichen NUMERISCH gewählt (die
|
||||
* Variante, deren tatsächliche Tangente zu `t` passt).
|
||||
*/
|
||||
function bulgeWithTangent(a: Vec2, b: Vec2, t: Vec2, atEnd: boolean): number {
|
||||
const c = sub(b, a);
|
||||
const ang = Math.abs(Math.atan2(cross(c, t), c.x * t.x + c.y * t.y));
|
||||
const mag = Math.abs(bulgeFromApexAngle(a, b, ang));
|
||||
if (mag < 1e-9) return 0;
|
||||
const dot = (v: Vec2) => v.x * t.x + v.y * t.y;
|
||||
return dot(arcTangent(a, b, mag, atEnd)) >= dot(arcTangent(a, b, -mag, atEnd)) ? mag : -mag;
|
||||
}
|
||||
|
||||
const bulgeWithEndTangent = (a: Vec2, b: Vec2, t: Vec2) => bulgeWithTangent(a, b, t, true);
|
||||
const bulgeWithStartTangent = (a: Vec2, b: Vec2, t: Vec2) => bulgeWithTangent(a, b, t, false);
|
||||
|
||||
/**
|
||||
* Bogen über der Sehne a→b mit halbem Öffnungswinkel |half| (Sehne↔Tangente);
|
||||
* Vorzeichen: >0 Scheitel links der Sehne, <0 rechts. Über den Scheitelpunkt in
|
||||
* einen Bulge übersetzt.
|
||||
*/
|
||||
function bulgeFromApexAngle(a: Vec2, b: Vec2, half: number): number {
|
||||
if (Math.abs(half) < 1e-6) return 0;
|
||||
// Begrenzen: knapp unter einem Halbkreis je Segment (sonst kippt der Bogen).
|
||||
const h2 = Math.max(-Math.PI / 2 + 0.01, Math.min(Math.PI / 2 - 0.01, half));
|
||||
const d = sub(b, a);
|
||||
const chord = Math.hypot(d.x, d.y);
|
||||
if (chord < EPS) return 0;
|
||||
const left = { x: -d.y / chord, y: d.x / chord };
|
||||
const s = (chord / 2) * Math.tan(h2 / 2); // Pfeilhöhe
|
||||
const apex = { x: (a.x + b.x) / 2 + left.x * s, y: (a.y + b.y) / 2 + left.y * s };
|
||||
return bulgeFromSagittaPoint(a, b, apex);
|
||||
return core().polyline_vertex_info(pts, Float64Array.from(g.bulge ?? []), !!g.closed, i);
|
||||
}
|
||||
|
||||
/** Ist Punkttyp `type` am Punkt `i` möglich? (Bogen/Spline brauchen beide Nachbarn.) */
|
||||
export function canSetVertexType(g: PolylineLike, i: number, type: PolylineVertexType): boolean {
|
||||
if (i < 0 || i >= g.pts.length) return false;
|
||||
if (type === "corner") return true;
|
||||
const { prev, next } = neighbors(g, i);
|
||||
return !!prev && !!next;
|
||||
return info(g, i)[1 + TYPES.indexOf(type)] === 1;
|
||||
}
|
||||
|
||||
/** Aktueller Typ (Heuristik): beide Nachbarsegmente gerade → Eckpunkt, sonst null (gemischt). */
|
||||
export function vertexTypeOf(g: PolylineLike, i: number): PolylineVertexType | null {
|
||||
const { inSeg, outSeg } = adjacentSegments(g.pts.length, g.closed, i);
|
||||
const b = (k: number | null) => (k === null ? 0 : g.bulge?.[k] ?? 0);
|
||||
if (Math.abs(b(inSeg)) < 1e-9 && Math.abs(b(outSeg)) < 1e-9) return "corner";
|
||||
const { prev, next } = neighbors(g, i);
|
||||
if (!prev || !next || inSeg === null || outSeg === null) return null;
|
||||
const a1 = bulgeArc(prev, g.pts[i], b(inSeg));
|
||||
const a2 = bulgeArc(g.pts[i], next, b(outSeg));
|
||||
if (a1 && a2 && Math.hypot(a1.center.x - a2.center.x, a1.center.y - a2.center.y) < 1e-6 * (1 + a1.r)) return "arc";
|
||||
return "spline";
|
||||
}
|
||||
|
||||
/** Neue Bulge-Liste mit Punkttyp `type` an Punkt `i` (Eingabe bleibt unverändert). */
|
||||
export function withVertexType(g: PolylineLike, i: number, type: PolylineVertexType): number[] {
|
||||
const n = g.pts.length;
|
||||
const segCount = g.closed ? n : n - 1;
|
||||
const bulge = Array.from({ length: segCount }, (_, k) => g.bulge?.[k] ?? 0);
|
||||
if (!canSetVertexType(g, i, type)) return bulge;
|
||||
const { inSeg, outSeg } = adjacentSegments(n, g.closed, i);
|
||||
const q = g.pts[i];
|
||||
const { prev, next } = neighbors(g, i);
|
||||
if (type === "corner") {
|
||||
if (inSeg !== null) bulge[inSeg] = 0;
|
||||
if (outSeg !== null) bulge[outSeg] = 0;
|
||||
return bulge;
|
||||
}
|
||||
const p = prev!, r = next!;
|
||||
if (type === "arc") {
|
||||
const c = circumcenter(p, q, r);
|
||||
if (!c) {
|
||||
bulge[inSeg!] = 0;
|
||||
bulge[outSeg!] = 0;
|
||||
return bulge;
|
||||
}
|
||||
bulge[inSeg!] = bulgeOnCircle(p, q, c, r);
|
||||
bulge[outSeg!] = bulgeOnCircle(q, r, c, p);
|
||||
return bulge;
|
||||
}
|
||||
// spline: Tangente parallel zu prev→next
|
||||
const t = sub(r, p);
|
||||
const tl = Math.hypot(t.x, t.y);
|
||||
if (tl < EPS) return bulge;
|
||||
const tu = { x: t.x / tl, y: t.y / tl };
|
||||
bulge[inSeg!] = bulgeWithEndTangent(p, q, tu);
|
||||
bulge[outSeg!] = bulgeWithStartTangent(q, r, tu);
|
||||
return bulge;
|
||||
return TYPES[info(g, i)[0]] ?? null;
|
||||
}
|
||||
@@ -19,8 +19,6 @@
|
||||
import type { Stair, Vec2 } from "../model/types";
|
||||
import { core } from "../engine/coreWasm";
|
||||
|
||||
/** SIA-nahe Schrittregel: gute Steigungshöhe ≈ 0.17 m, Auftritt ≈ 0.29 m. */
|
||||
export const IDEAL_RISER = 0.17;
|
||||
export const IDEAL_TREAD = 0.29;
|
||||
export const MIN_STEPS = 2;
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { exportIfcSpf, ifcGuid } from "../export/exportIfc";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import { ceilingVerticalExtent } from "../model/wall";
|
||||
import { verticalExtents } from "../geometry/grips";
|
||||
import { polygonArea } from "../geometry/roomArea";
|
||||
import { wallMeshVolumes } from "../export/meshScene.testutil";
|
||||
import { formatIfcReport, handleIfcWorkerRequest, ifcToImportedMeshes, readIfc, type IfcProduct, type IfcWorkerRequest } from "./ifcImport";
|
||||
@@ -100,7 +100,7 @@ describe("IFC-Import: Rundreise mit dem eigenen Export", () => {
|
||||
const slabsExpected = (sampleProject.ceilings ?? [])
|
||||
.filter((c) => c.outline.length >= 3)
|
||||
.map((c) => {
|
||||
const { zBottom, zTop } = ceilingVerticalExtent(sampleProject, c);
|
||||
const { zBottom, zTop } = verticalExtents(sampleProject, [], [c]).ceilings[0];
|
||||
return Math.abs(polygonArea(c.outline)) * Math.max(zTop - zBottom, 0.001);
|
||||
})
|
||||
.sort((a, b) => a - b);
|
||||
|
||||
@@ -346,17 +346,6 @@ export function meshObjectsToImportedMeshes(objects: readonly MeshObject[], file
|
||||
});
|
||||
}
|
||||
|
||||
/** Datei-Bytes → Kontext-Meshes + Bericht. */
|
||||
export async function meshBytesToImportedMeshes(
|
||||
bytes: Uint8Array,
|
||||
fileName: string,
|
||||
read?: MeshReadOptions,
|
||||
place?: MeshToContextOptions,
|
||||
): Promise<{ meshes: ImportedMesh[]; report: MeshImportReport }> {
|
||||
const { objects, report } = await readMesh(bytes, fileName, read);
|
||||
return { meshes: meshObjectsToImportedMeshes(objects, fileName, place), report };
|
||||
}
|
||||
|
||||
/** Bericht als kurzer Text; `tr` übersetzt (Kern kennt kein i18n, die Hülle reicht `t` herein). */
|
||||
export function formatMeshReport(
|
||||
r: MeshImportReport,
|
||||
|
||||
@@ -18,7 +18,6 @@ import type {
|
||||
BuiltinPaletteBanks,
|
||||
Ceiling,
|
||||
CeilingType,
|
||||
Column,
|
||||
Component,
|
||||
DoorType,
|
||||
DrawingLevel,
|
||||
@@ -30,8 +29,6 @@ import type {
|
||||
RichTextDoc,
|
||||
Roof,
|
||||
SashDef,
|
||||
Stair,
|
||||
StairType,
|
||||
Vec2,
|
||||
Wall,
|
||||
WallType,
|
||||
@@ -204,35 +201,6 @@ export const glazingPanesOf = (wt: WindowType): 1 | 2 | 3 => {
|
||||
return wt.glazing === "dreifach" ? 3 : wt.glazing === "zweifach" ? 2 : 1;
|
||||
};
|
||||
|
||||
/** Löst den {@link StairType} einer Treppe auf, oder `undefined`. */
|
||||
export const getStairType = (project: Project, stair: Stair): StairType | undefined =>
|
||||
stair.typeId ? (project.stairTypes ?? []).find((t) => t.id === stair.typeId) : undefined;
|
||||
|
||||
/** Alle Öffnungen einer Wand (leere Liste, wenn keine oder `openings` fehlt). */
|
||||
export const openingsOfWall = (project: Project, wallId: string): Opening[] =>
|
||||
(project.openings ?? []).filter((o) => o.hostWallId === wallId);
|
||||
|
||||
/** Menschenlesbarer Standardname einer Öffnung (Fenster/Tür + Breite×Höhe). */
|
||||
export const openingLabel = (o: Opening): string =>
|
||||
`${o.kind === "door" ? "Tür" : "Fenster"} ${(o.width * 100).toFixed(0)}×${(
|
||||
o.height * 100
|
||||
).toFixed(0)}`;
|
||||
|
||||
/** Menschenlesbarer Standardname einer Stütze (Profil + Masse in cm). */
|
||||
export const columnLabel = (c: Column): string => {
|
||||
if (c.profile.kind === "round") {
|
||||
return `Stütze Ø${(c.profile.radius * 200).toFixed(0)}`;
|
||||
}
|
||||
return `Stütze ${(c.profile.width * 100).toFixed(0)}×${(c.profile.depth * 100).toFixed(0)}`;
|
||||
};
|
||||
|
||||
/** Liefert ein Bauteil-Material (Component) per ID oder wirft. */
|
||||
export const getComponent = (project: Project, id: string): Component => {
|
||||
const c = project.components.find((co) => co.id === id);
|
||||
if (!c) throw new Error(`Unbekanntes Bauteil-Material: ${id}`);
|
||||
return c;
|
||||
};
|
||||
|
||||
/** Liefert eine Schraffur (HatchStyle) per ID oder wirft. */
|
||||
export const getHatch = (project: Project, id: string): HatchStyle => {
|
||||
const h = project.hatches.find((ht) => ht.id === id);
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
// Unit-Tests für die Wand-/Decken-Resolver (wallVerticalExtent /
|
||||
// ceilingVerticalExtent): reine Datenschicht, kein React/Store.
|
||||
// Unit-Tests für die Wand-/Decken-Resolver: Referenzlinie (`wallReferenceOffset`) und die UK/OK der
|
||||
// Decken über den Kern (`verticalExtents`, Regeln `model/helpers.rs::heights`).
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { ceilingVerticalExtent, wallReferenceOffset } from "./wall";
|
||||
import { wallReferenceOffset } from "./wall";
|
||||
import { verticalExtents } from "../geometry/grips";
|
||||
import type { Ceiling, Project, Wall } from "./types";
|
||||
|
||||
/** Minimalprojekt mit einem Geschoss (baseElevation 0, floorHeight 2.6) und
|
||||
@@ -68,7 +69,10 @@ function makeCeiling(overrides?: Partial<Ceiling>): Ceiling {
|
||||
};
|
||||
}
|
||||
|
||||
describe("ceilingVerticalExtent", () => {
|
||||
/** UK/OK einer Decke (Kern-Abfrage). */
|
||||
const ceilingVerticalExtent = (p: Project, c: Ceiling) => verticalExtents(p, [], [c]).ceilings[0];
|
||||
|
||||
describe("UK/OK einer Decke", () => {
|
||||
it("ohne top/bottom: OK = Geschoss-Oberkante, UK = OK − Dicke (heutiges Verhalten)", () => {
|
||||
const project = makeProject();
|
||||
const ceiling = makeCeiling();
|
||||
|
||||
+3
-92
@@ -1,12 +1,9 @@
|
||||
// Wand-Resolver: leitet aus den (optionalen) Wand-Attributen die konkreten
|
||||
// geometrischen Größen ab — Versatz der Achse über die Dicke (Referenzlinie)
|
||||
// und die vertikale Ausdehnung (UK..OK). Alle Defaults entsprechen exakt dem
|
||||
// bisherigen Verhalten, sodass bestehende Wände unverändert rendern.
|
||||
// Wand-Resolver: Versatz der Achse über die Dicke (Referenzlinie). Die vertikale Ausdehnung (UK/OK)
|
||||
// rechnet der Kern (`model/helpers.rs::heights`; TS: Abfrage `verticalExtents`, `geometry/grips.ts`).
|
||||
//
|
||||
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
|
||||
|
||||
import type { Ceiling, Column, Project, VerticalAnchor, Wall } from "./types";
|
||||
import { ceilingThickness, getFloor } from "./types";
|
||||
import type { Wall } from "./types";
|
||||
|
||||
/**
|
||||
* Versatz der Schichtstapelung entlang der linken Normalen `+n` (leftNormal),
|
||||
@@ -38,89 +35,3 @@ export function wallReferenceOffset(
|
||||
if (ref === "right") return -half;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** Löst einen VerticalAnchor zu einem absoluten Z (Meter) auf oder `null`. */
|
||||
function resolveAnchor(
|
||||
project: Project,
|
||||
anchor: VerticalAnchor | undefined,
|
||||
): number | null {
|
||||
if (!anchor) return null;
|
||||
if (anchor.mode === "custom") return anchor.z;
|
||||
// "floor": baseElevation des gebundenen Geschosses (+ optionalem Offset).
|
||||
const floor = project.drawingLevels.find((z) => z.id === anchor.floorId);
|
||||
if (!floor) return null;
|
||||
return (floor.baseElevation ?? 0) + (anchor.offset ?? 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Vertikale Ausdehnung der Wand (absolute Z-Werte in Metern).
|
||||
* • zBottom: aus `wall.bottom`, sonst baseElevation des Wand-Geschosses
|
||||
* (= heutiges Verhalten).
|
||||
* • zTop: aus `wall.top`, sonst `zBottom + wall.height` (= heute).
|
||||
* Sind beide UK/OK ungesetzt, liefert dies exakt `[baseElevation, base+height]`.
|
||||
*/
|
||||
export function wallVerticalExtent(
|
||||
project: Project,
|
||||
wall: Wall,
|
||||
): { zBottom: number; zTop: number } {
|
||||
// Geschoss-baseElevation als Default-UK (heutiges Verhalten). Fehlt das
|
||||
// Geschoss, 0 als sicherer Rückfall.
|
||||
let floorBase = 0;
|
||||
try {
|
||||
floorBase = getFloor(project, wall.floorId).baseElevation ?? 0;
|
||||
} catch {
|
||||
floorBase = 0;
|
||||
}
|
||||
const zBottom = resolveAnchor(project, wall.bottom) ?? floorBase;
|
||||
const zTop = resolveAnchor(project, wall.top) ?? zBottom + wall.height;
|
||||
return { zBottom, zTop };
|
||||
}
|
||||
|
||||
/**
|
||||
* Vertikale Ausdehnung einer Decke (absolute Z-Werte in Metern).
|
||||
* • zTop: aus `ceiling.top`, sonst Oberkante des Geschosses
|
||||
* (baseElevation + floorHeight) — also bündig mit dem Wandkopf.
|
||||
* • zBottom: aus `ceiling.bottom`, sonst zTop − Deckendicke (die Decke
|
||||
* wächst nach UNTEN — heutiges Verhalten). Die `thickness` bleibt bei
|
||||
* gesetztem `bottom` rein informativ (dient nicht mehr der UK-Ableitung).
|
||||
* Fehlt das Geschoss, dient 0 als sicherer Rückfall für die Oberkante.
|
||||
*/
|
||||
export function ceilingVerticalExtent(
|
||||
project: Project,
|
||||
ceiling: Ceiling,
|
||||
): { zBottom: number; zTop: number } {
|
||||
let floorTop = 0;
|
||||
try {
|
||||
const floor = getFloor(project, ceiling.floorId);
|
||||
floorTop = (floor.baseElevation ?? 0) + (floor.floorHeight ?? 0);
|
||||
} catch {
|
||||
floorTop = 0;
|
||||
}
|
||||
const zTop = resolveAnchor(project, ceiling.top) ?? floorTop;
|
||||
const zBottom =
|
||||
resolveAnchor(project, ceiling.bottom) ??
|
||||
zTop - ceilingThickness(project, ceiling);
|
||||
return { zBottom, zTop };
|
||||
}
|
||||
|
||||
/**
|
||||
* Vertikale Ausdehnung einer Stütze (absolute Z-Werte in Metern) — dieselbe
|
||||
* Regel wie {@link wallVerticalExtent}:
|
||||
* • zBottom: aus `column.bottom`, sonst baseElevation des Geschosses.
|
||||
* • zTop: aus `column.top`, sonst `zBottom + column.height`.
|
||||
* Fehlt das Geschoss, dient 0 als sicherer Rückfall für die Unterkante.
|
||||
*/
|
||||
export function columnVerticalExtent(
|
||||
project: Project,
|
||||
column: Column,
|
||||
): { zBottom: number; zTop: number } {
|
||||
let floorBase = 0;
|
||||
try {
|
||||
floorBase = getFloor(project, column.floorId).baseElevation ?? 0;
|
||||
} catch {
|
||||
floorBase = 0;
|
||||
}
|
||||
const zBottom = resolveAnchor(project, column.bottom) ?? floorBase;
|
||||
const zTop = resolveAnchor(project, column.top) ?? zBottom + column.height;
|
||||
return { zBottom, zTop };
|
||||
}
|
||||
+1
-24
@@ -5,13 +5,12 @@
|
||||
* Querschnitt.
|
||||
* • 3D (projectToModel3d/emitColumns): eine Stütze wird zu einem Prisma-Mesh
|
||||
* (Rechteck-Box bzw. Kreis-Prisma) mit der erwarteten vertikalen Ausdehnung.
|
||||
* • Vertikale Lage (columnVerticalExtent): Geschoss-Default sowie UK/OK-Anker.
|
||||
* (Vertikale Lage: Rust-Tests `model/helpers.rs::heights`.)
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { generatePlan } from "./generatePlan";
|
||||
import { projectToModel3d } from "./toWalls3d";
|
||||
import { columnVerticalExtent } from "../model/wall";
|
||||
import { columnFootprint } from "../geometry/column";
|
||||
import type { Column, Project } from "../model/types";
|
||||
|
||||
@@ -125,28 +124,6 @@ describe("Stütze — 3D (projectToModel3d / emitColumns)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Stütze — vertikale Lage (columnVerticalExtent)", () => {
|
||||
it("nutzt Geschoss-UK + Höhe als Default", () => {
|
||||
const { zBottom, zTop } = columnVerticalExtent(
|
||||
projectWithColumn(rectColumn),
|
||||
rectColumn,
|
||||
);
|
||||
expect(zBottom).toBeCloseTo(0, 6);
|
||||
expect(zTop).toBeCloseTo(3, 6);
|
||||
});
|
||||
|
||||
it("bindet UK/OK an Anker (custom + floor)", () => {
|
||||
const anchored: Column = {
|
||||
...rectColumn,
|
||||
bottom: { mode: "custom", z: 0.5 },
|
||||
top: { mode: "floor", floorId: "og" }, // baseElevation OG = 3
|
||||
};
|
||||
const { zBottom, zTop } = columnVerticalExtent(projectWithColumn(anchored), anchored);
|
||||
expect(zBottom).toBeCloseTo(0.5, 6);
|
||||
expect(zTop).toBeCloseTo(3, 6);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Stütze — Footprint-Helfer (columnFootprint)", () => {
|
||||
it("tesselliert ein rundes Profil als 32-Eck um die Position", () => {
|
||||
const round: Column = { ...rectColumn, profile: { kind: "round", radius: 0.15 } };
|
||||
|
||||
@@ -42,9 +42,6 @@ export type DetailLevel = "grob" | "mittel" | "fein";
|
||||
/** Stroke-Farbe der Schicht-Polygone (neutrales Schwarz, geteilte Tinte mit der Schraffur). */
|
||||
export const POCHE_STROKE = "#1a1a1a";
|
||||
|
||||
/** Tinte für den Schwarz-Weiss-Modus: einheitliches Dunkel für alle Striche. */
|
||||
export const MONO_INK = "#111111";
|
||||
|
||||
// ── Linienstärken in PAPIER-Millimeter (vgl. docs/design/plans-output.md §3.2) ──
|
||||
// Alle Stricharten sind in mm Papier definiert; die PlanView rechnet sie über
|
||||
// dpi = 96 in konstante Bildschirm-Pixel um (non-scaling-stroke), damit Linien
|
||||
@@ -58,7 +55,6 @@ export const LAYER_LINE_MM = 0.02;
|
||||
// seit [K3d] im Kern (`src-tauri/core/src/plan/style.rs`).
|
||||
/** Default-Umrandungs-Strichstärke (mm), falls die Kategorie keine lw trägt
|
||||
(Grundeinstellung für „normale Elemente"). */
|
||||
export const WALL_FALLBACK_MM = 0.18;
|
||||
|
||||
/**
|
||||
* Aufgelöste Schraffur eines Polygons — alle Werte stammen aus einer
|
||||
|
||||
@@ -144,24 +144,6 @@ export function buildHatchRuns(poly: Vec2[], hatch: HatchRender): HatchRun[] {
|
||||
return toRuns(core().hatch_runs_flat(flat(poly), encodeHatch(hatch)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Streut kurze Striche deterministisch und MODELLRAUM-STABIL über ein Polygon (eine Zelle des
|
||||
* absoluten Gitters je Strich, Lage/Winkel/Länge aus `hash(ix, iy, seed)`), aufs Polygon geclippt.
|
||||
*/
|
||||
export function scatterStrokes(
|
||||
poly: Vec2[],
|
||||
cell: number,
|
||||
baseAngleRad: number,
|
||||
seed: number,
|
||||
strokeLen: number,
|
||||
lenMin?: number,
|
||||
lenMax?: number,
|
||||
): HatchRun[] {
|
||||
return toRuns(
|
||||
core().scatter_strokes_flat(flat(poly), cell, baseAngleRad, seed, strokeLen, lenMin ?? NaN, lenMax ?? NaN),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Random-Vektor-Schraffur eines Polygons (Kies/Splitt): Dichte und Strichlänge an die Kachel
|
||||
* (8·scale px) gekoppelt, Seed nur aus Muster-Parametern + `hatch.seed`.
|
||||
|
||||
@@ -16,30 +16,6 @@
|
||||
/** RGBA-Farbe, Komponenten in [0,1]. */
|
||||
export type Rgba = [number, number, number, number];
|
||||
|
||||
/** Shader-Programm mit kompiliertem Programm + Attribut-/Uniform-Orten. */
|
||||
export interface ShaderProgram {
|
||||
program: WebGLProgram;
|
||||
attribs: {
|
||||
position?: GLint;
|
||||
/** Bildschirm-Raum-Miter-Bisektor (Einheits-Versatzrichtung) für Linien. */
|
||||
normal?: GLint;
|
||||
/** Seite der Linie: +1 oder -1. */
|
||||
side?: GLint;
|
||||
/** Miter-Längenfaktor 1/cos(θ/2) (1 = gerade). */
|
||||
miter?: GLint;
|
||||
};
|
||||
uniforms: {
|
||||
viewProj?: WebGLUniformLocation | null;
|
||||
color?: WebGLUniformLocation | null;
|
||||
/** Basis-Strichbreite in Geräte-Pixeln (bei strokeScale=1). */
|
||||
strokePx?: WebGLUniformLocation | null;
|
||||
/** Zoom-Skalierung der Strichbreite (>1 = reingezoomt → dicker, Papier). */
|
||||
strokeScale?: WebGLUniformLocation | null;
|
||||
/** Zeichenpuffer-Größe in Geräte-Pixeln [w,h] (px→Clip-Umrechnung). */
|
||||
viewportPx?: WebGLUniformLocation | null;
|
||||
};
|
||||
}
|
||||
|
||||
/** Ein Zeichen-Batch: zusammenhängender Index-Bereich mit einer Farbe. */
|
||||
export interface FillBatch {
|
||||
startIndex: number;
|
||||
|
||||
@@ -207,21 +207,6 @@ export function pointInPolygon(pt: Vec2, poly: Vec2[]): boolean {
|
||||
return inside;
|
||||
}
|
||||
|
||||
/** Abstand Punkt→Strecke (alle in denselben Koordinaten, hier Client-Pixel). */
|
||||
export function pointSegDistPx(
|
||||
p: { x: number; y: number },
|
||||
a: { x: number; y: number },
|
||||
b: { x: number; y: number },
|
||||
): number {
|
||||
const dx = b.x - a.x;
|
||||
const dy = b.y - a.y;
|
||||
const len2 = dx * dx + dy * dy;
|
||||
if (len2 < 1e-9) return Math.hypot(p.x - a.x, p.y - a.y);
|
||||
let t = ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2;
|
||||
t = Math.max(0, Math.min(1, t));
|
||||
return Math.hypot(p.x - (a.x + dx * t), p.y - (a.y + dy * t));
|
||||
}
|
||||
|
||||
/** Achsenparalleles Rechteck in Modell-Metern (Auswahl-Marquee). */
|
||||
export interface ModelRect {
|
||||
minX: number;
|
||||
|
||||
@@ -243,10 +243,6 @@ export interface RModel3d {
|
||||
|
||||
/** Warmer, neutraler Wand-Grundton (wie render3d default). */
|
||||
export const WALL_RGB: RRgb = [0.82, 0.8, 0.76];
|
||||
/** Etwas hellerer, kühlerer Ton für Deckenplatten (heben sich von Wänden ab). */
|
||||
export const SLAB_RGB: RRgb = [0.86, 0.86, 0.88];
|
||||
/** Fallback-Farbe für 2D-Zeichnungen ohne color/lineStyle/Kategorie (wie drawing2DColor in Viewport3D.tsx, "#888888"). */
|
||||
export const DRAWING_LINE_FALLBACK_RGB: RRgb = [0x88 / 255, 0x88 / 255, 0x88 / 255];
|
||||
|
||||
/** Ignoriere entartete vertikale Ausschnitte (Rundungsrauschen). */
|
||||
export const EPS = 1e-4;
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
// [K4] Messung: Objekt-Info (`deriveSelection`), Griff-Schritte und grosse Polylinien auf einem grossen
|
||||
// Projekt (3000 Wände + 20 000 Zeichnungen, 40 Dächer) über den Store. Werte gehen nach stderr (TODO [K4]);
|
||||
// die Grenzen sind grosszügig (Container unter Last), geprüft wird vor allem das Ergebnis.
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getState } from "./appStore";
|
||||
import { deriveSelection } from "./selectionInfo";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import type { Drawing2D, Project, Roof, Wall } from "../model/types";
|
||||
|
||||
const st = () => getState();
|
||||
|
||||
function bigProject(): Project {
|
||||
const base = sampleProject.walls;
|
||||
const walls: Wall[] = Array.from({ length: 3000 }, (_, i) => ({
|
||||
...base[i % base.length],
|
||||
id: `w${i}`,
|
||||
start: { x: i, y: 0 },
|
||||
end: { x: i + 1, y: 0 },
|
||||
}));
|
||||
const level = sampleProject.drawingLevels[0].id;
|
||||
const drawings: Drawing2D[] = Array.from({ length: 20000 }, (_, i) => ({
|
||||
id: `d${i}`,
|
||||
levelId: level,
|
||||
categoryCode: "01",
|
||||
geom:
|
||||
i === 19000
|
||||
? {
|
||||
shape: "polyline",
|
||||
closed: false,
|
||||
pts: Array.from({ length: 5000 }, (_, k) => ({ x: k * 0.1, y: Math.sin(k / 50) })),
|
||||
}
|
||||
: { shape: "polyline", closed: false, pts: [{ x: i, y: 1 }, { x: i + 1, y: 2 }, { x: i + 2, y: 1 }] },
|
||||
})) as Drawing2D[];
|
||||
const roof = sampleProject.roofs![0];
|
||||
const roofs: Roof[] = Array.from({ length: 40 }, (_, i) => ({
|
||||
...roof,
|
||||
id: `r${i}`,
|
||||
outline: roof.outline.map((p) => ({ x: p.x + i * 10, y: p.y })),
|
||||
}));
|
||||
return { ...structuredClone(sampleProject), walls, drawings2d: drawings, roofs };
|
||||
}
|
||||
|
||||
/** Kleinster Mittelwert (µs) aus `rounds` Läufen à `n` Aufrufen. */
|
||||
function bench(n: number, fn: (i: number) => void, rounds = 3): number {
|
||||
let best = Infinity;
|
||||
for (let i = 0; i < Math.ceil(n / 4); i++) fn(i); // Aufwärmen (JIT, Caches)
|
||||
for (let r = 0; r < rounds; r++) {
|
||||
const t = performance.now();
|
||||
for (let i = 0; i < n; i++) fn(i);
|
||||
best = Math.min(best, ((performance.now() - t) * 1000) / n);
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
const sel = (p: Project, k: { wall?: string; drawing?: string; roof?: string }) =>
|
||||
deriveSelection(p, k.wall ? [k.wall] : [], k.drawing ?? null, null, null, null, null, null, null, k.roof ?? null);
|
||||
|
||||
describe("Messung Objekt-Info und Griffe, 3000 Wände + 20 000 Zeichnungen", () => {
|
||||
it("Objekt-Info, Griff-Schritte, Polylinien-Punkttyp", { timeout: 120000 }, () => {
|
||||
st().loadProject(bigProject());
|
||||
const p = st().project;
|
||||
const out: string[] = [];
|
||||
for (const i of [10, 1500, 2990]) {
|
||||
expect(sel(p, { wall: `w${i}` })?.kind).toBe("wall");
|
||||
out.push(`Info Wand ${i} ${bench(200, () => sel(p, { wall: `w${i}` })).toFixed(0)} µs`);
|
||||
}
|
||||
expect(sel(p, { drawing: "d10000" })?.kind).toBe("drawing2d");
|
||||
out.push(`Info Zeichnung 10000 ${bench(200, () => sel(p, { drawing: "d10000" })).toFixed(0)} µs`);
|
||||
expect(sel(p, { roof: "r20" })?.kind).toBe("roof");
|
||||
out.push(`Info Dach (40 im Wechsel) ${bench(200, (i) => sel(p, { roof: `r${i % 40}` })).toFixed(0)} µs`);
|
||||
|
||||
for (const i of [10, 1500, 2990]) {
|
||||
const us = bench(50, (k) => st().moveGripOf(null, `w${i}`, 0, { x: i + (k % 7) * 0.01, y: 0.5 }));
|
||||
out.push(`Griff Wand ${i} ${us.toFixed(0)} µs`);
|
||||
}
|
||||
expect(st().project.walls[1500].start.y).toBe(0.5);
|
||||
const big = (k: number) => st().moveGripOf("d19000", null, 2500, { x: 250 + (k % 5) * 0.01, y: 3 });
|
||||
out.push(`Griff Polylinie 5000 Punkte ${(bench(20, big) / 1000).toFixed(2)} ms`);
|
||||
out.push(`Griff Zeichnung 15000 ${bench(50, (k) => st().moveGripOf("d15000", null, 1, { x: 15001, y: 2 + (k % 5) * 0.01 })).toFixed(0)} µs`);
|
||||
|
||||
const types = ["arc", "spline", "corner"] as const;
|
||||
out.push(
|
||||
`Punkttyp Polylinie 5000 Punkte ${(bench(20, (k) => st().setPolylineVertexType("d19000", 100 + k, types[k % 3])) / 1000).toFixed(2)} ms`,
|
||||
);
|
||||
out.push(`Punkttyp kleine Polylinie ${bench(50, (k) => st().setPolylineVertexType("d12000", 1, types[k % 3])).toFixed(0)} µs`);
|
||||
st().setPolylineVertexType("d12000", 1, "arc");
|
||||
expect((st().project.drawings2d[12000].geom as { bulge?: number[] }).bulge?.length).toBe(2);
|
||||
st().setPolylineVertexType("d12000", 1, "corner");
|
||||
expect((st().project.drawings2d[12000].geom as { bulge?: number[] }).bulge).toBeUndefined();
|
||||
|
||||
process.stderr.write(`Objekt-Info/Griffe (Store): ${out.join(", ")}\n`);
|
||||
});
|
||||
});
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
setField,
|
||||
setFieldIfChanged,
|
||||
} from "../core";
|
||||
import { withVertexType, type PolylineVertexType } from "../core";
|
||||
import type { PolylineVertexType } from "../core";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import {
|
||||
addChildByCode,
|
||||
@@ -218,7 +218,7 @@ export interface ProjectSlice {
|
||||
deleteDrawingPoint: (drawingId: string, index: number) => void;
|
||||
/**
|
||||
* Punkttyp eines Polylinien-Stützpunkts setzen (Eckpunkt/Bogenpunkt/Splinepunkt),
|
||||
* s. `geometry/polylineVertexType.ts` — rechnet nur die Bulges der beiden
|
||||
* im Kern (`polyline_vertex.rs`, Griff-Änderung `vertexType`) — rechnet nur die Bulges der beiden
|
||||
* anliegenden Segmente um.
|
||||
*/
|
||||
setPolylineVertexType: (drawingId: string, index: number, type: PolylineVertexType) => void;
|
||||
@@ -1055,15 +1055,7 @@ export function createProjectSlice(
|
||||
applyGrip({ op: "insertPoint", id: drawingId, seg: segIndex, pt: gripPt(pt) }),
|
||||
|
||||
setPolylineVertexType: (drawingId, index, type) =>
|
||||
applyChange((p) =>
|
||||
patchItem(p, "drawings2d", drawingId, (d) => {
|
||||
if (d.geom.shape !== "polyline" || d.locked) return d;
|
||||
const g = d.geom;
|
||||
const bulge = withVertexType(g, index, type);
|
||||
const { bulge: _old, ...rest } = g;
|
||||
return { ...d, geom: bulge.some((b) => b !== 0) ? { ...rest, bulge } : rest };
|
||||
}),
|
||||
),
|
||||
applyGrip({ op: "vertexType", id: drawingId, index, vertexType: type }),
|
||||
|
||||
deleteDrawingPoint: (drawingId, index) => applyGrip({ op: "deletePoint", id: drawingId, index }),
|
||||
|
||||
|
||||
@@ -547,25 +547,8 @@ export function deriveSelection(
|
||||
columnId: selectedColumnId,
|
||||
roofId: selectedRoofId,
|
||||
contextObjectId: selectedContextObjectId,
|
||||
// Lage in der Leseansicht (= Reihenfolge im Dokument): erspart dem Kern die lineare Suche.
|
||||
at: {} as Record<string, number>,
|
||||
};
|
||||
const P = project as unknown as Record<string, { id: string }[] | undefined>;
|
||||
const hint = (list: string, id: string | null | undefined) => {
|
||||
if (!id) return;
|
||||
const i = (P[list] ?? []).findIndex((x) => x.id === id);
|
||||
if (i >= 0) args.at[list] = i;
|
||||
};
|
||||
hint("context", selectedContextObjectId);
|
||||
hint("drawings2d", selectedDrawingId);
|
||||
hint("extrudedSolids", selectedExtrudedSolidId);
|
||||
hint("columns", selectedColumnId);
|
||||
hint("openings", selectedOpeningId);
|
||||
hint("walls", selectedWallIds[0]);
|
||||
hint("ceilings", selectedCeilingId);
|
||||
hint("roofs", selectedRoofId);
|
||||
hint("stairs", selectedStairId);
|
||||
hint("rooms", selectedRoomId);
|
||||
// Das Element sucht der Kern über den Positions-Index des Dokuments (keine lineare Suche).
|
||||
let sel: Selection | null;
|
||||
try {
|
||||
sel = documentFor(project).queryRootMarked<Selection | null>("selectionInfo", JSON.stringify(args));
|
||||
|
||||
Reference in new issue
Block a user