[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
+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()
|
||||
}
|
||||
Reference in new issue
Block a user