//! A model as a design file keeps it: every feature's result and the state after it, so a design
//! opens without evaluating its timeline again (docs/design-container.md, "Model cache").
//!
//! The records are JSON; the kernel bodies they hold are a separate list ([`SavedModel::bodies`]),
//! which the file stores in SolidCraft's exact native B-rep encoding. A body that several states
//! hold (one that later features pass through unchanged) is recorded once, as are its face names
//! and the solved sketches the states share. Face names are kept as worked out, not as the
//! history they were worked out from: a model taken from a file names every face as the model
//! that was saved did. A file without room for every state keeps fewer
//! ([`SavedModel::thinned`]); opening evaluates the features whose state it left out again.
use super::*;
use crate::history_names::{FaceInfo, Names};
use serde_json::{Value as Json, json};
use std::collections::HashMap;
/// A model's results and states as records, and the kernel bodies they refer to by index.
pub struct SavedModel {
pub records: Json,
pub bodies: Vec
,
}
/// Records refer to these at most.
const MAX_ITEMS: usize = 1_000_000;
/// Bodies, sketches, sheet bodies and sketch keys all the states hold together, at most (a state is
/// a list of clones).
const MAX_HELD: usize = 50_000_000;
/// Longest text a record holds (bytes). A feature's warning can quote every generated name of
/// the edges it picked: 122,701 characters in one design, whose saved model was refused, so it
/// evaluated again on every open (#8541).
const MAX_TEXT: usize = 1 << 24;
fn hex(v: u64) -> String {
format!("{v:016x}")
}
fn unhex(v: &Json) -> Result {
v.as_str().and_then(|s| u64::from_str_radix(s, 16).ok()).ok_or_else(|| bad("saved model: key"))
}
/// A sketch-key set's list `key` (`set` or `drop`).
fn keys_list<'a>(set: &'a Json, key: &str) -> Result<&'a Vec> {
set.get(key).and_then(Json::as_array).filter(|l| l.len() <= MAX_ITEMS).ok_or_else(|| bad("saved model: sketch keys"))
}
fn bad(what: &str) -> DocError {
DocError::Invalid(what.into())
}
/// A design holding a face or edge name saved before format 14 (marked
/// [`crate::naming::LEGACY_MARK`]): it saves without a model.
fn has_legacy_names(doc: &Document) -> bool {
let mark = format!("\"{}", crate::naming::LEGACY_MARK);
doc.features.iter().any(|f| match &f.kind {
FeatureKind::Import { .. } => f.face_names.iter().any(|n| n.starts_with(crate::naming::LEGACY_MARK)),
_ => serde_json::to_string(f).is_ok_and(|j| j.contains(&mark)),
})
}
/// What tells two model bodies apart in a record: a body a feature passes through unchanged is a
/// clone sharing its mesh cell and names, so this finds it without writing its record again.
#[derive(PartialEq, Eq, Hash)]
struct BodyKey {
mesh: usize,
names: usize,
imported: usize,
key: u64,
feature: u64,
component: u64,
transferred: bool,
name: String,
source_name: Option,
source_transform: [u64; 16],
}
impl BodyKey {
fn of(b: &ModelBody) -> Self {
let mut source_transform = [0; 16];
for (bits, v) in source_transform.iter_mut().zip(b.source_transform.iter().flatten()) {
*bits = v.to_bits();
}
BodyKey {
mesh: Arc::as_ptr(&b.mesh) as usize,
names: b.names.id(),
imported: b.imported.as_ref().map_or(0, |l| Arc::as_ptr(l) as usize),
key: b.key,
feature: b.feature,
component: b.component,
transferred: b.transferred,
name: b.name.clone(),
source_name: b.source_name.clone(),
source_transform,
}
}
}
/// Indices as runs of consecutive ones (`[first, count]`): a state lists mostly the bodies of the
/// state before it, in order.
fn runs(indices: &[usize]) -> Vec<[usize; 2]> {
let mut out: Vec<[usize; 2]> = Vec::new();
for &i in indices {
match out.last_mut() {
Some([first, count]) if *first + *count == i => *count += 1,
_ => out.push([i, 1]),
}
}
out
}
#[derive(Default)]
struct Writer {
bodies: Vec,
model_bodies: Vec,
model_body_index: HashMap,
names: Vec,
names_index: HashMap,
sketches: Vec,
sketch_index: HashMap,
/// Sheet bodies by their record: most features leave the sheets as they were, so the states
/// share them (writing them with every state made a sheet-metal design's model too large to keep).
sheets: Vec,
sheet_index: HashMap,
states: Vec,
state_index: HashMap,
/// Each kernel body's place in `bodies`, by its record.
body_index: HashMap,
/// The rounds that made bodies (`Body::rounds`): the body, the body they were made on (both
/// places in `bodies`), and the edges they rounded there with their radii.
rounds: Vec,
/// The states' sketch keys, each distinct map once, written as the changes from the set
/// written before it: every state used to repeat the whole map (one entry per solved sketch),
/// 85 % of a 5,484-feature design's records, which then did not fit the cache's manifest.
sketch_key_sets: Vec,
sketch_key_index: HashMap, usize>,
last_sketch_keys: Option<(BTreeMap, usize)>,
}
impl Writer {
/// The place of `keys` among the sketch-key sets, written the first time a state holds them
/// (as the changes from the set written last: a later state mostly adds a sketch or two).
fn sketch_key_set(&mut self, keys: &BTreeMap) -> usize {
if let Some(i) = self.sketch_key_index.get(keys) {
return *i;
}
let record = match &self.last_sketch_keys {
Some((base, at)) => {
let set: Vec = keys.iter().filter(|(f, k)| base.get(f) != Some(k)).map(|(f, k)| json!([f, hex(*k)])).collect();
let drop: Vec = base.keys().filter(|f| !keys.contains_key(f)).copied().collect();
json!({"base": at, "set": set, "drop": drop})
}
None => json!({"set": keys.iter().map(|(f, k)| json!([f, hex(*k)])).collect::>(), "drop": []}),
};
self.sketch_key_sets.push(record);
let i = self.sketch_key_sets.len() - 1;
self.sketch_key_index.insert(keys.clone(), i);
self.last_sketch_keys = Some((keys.clone(), i));
i
}
fn names(&mut self, b: &ModelBody) -> usize {
let id = b.names.id();
if let Some(i) = self.names_index.get(&id) {
return *i;
}
let names = crate::naming::names(b);
let info: Vec = names.info.iter().map(|i| json!([i.aliases, i.bounds, i.verified, i.synonyms])).collect();
self.names.push(json!({"faces": *names.faces, "info": info}));
self.names_index.insert(id, self.names.len() - 1);
self.names.len() - 1
}
fn model_body(&mut self, b: &ModelBody) -> Option {
let key = BodyKey::of(b);
if let Some(i) = self.model_body_index.get(&key) {
return Some(*i);
}
let names = self.names(b);
let mut r = json!({
"name": b.name, "feature": b.feature, "component": b.component, "key": hex(b.key), "names": names,
});
if let Some(depth) = b.names.depth() {
r["depth"] = json!(depth);
}
if let Some(source) = &b.source_name {
r["source_name"] = json!(source);
}
if b.source_transform != crate::IDENTITY {
r["source_transform"] = json!(b.source_transform);
}
if b.transferred {
r["transferred"] = json!(true);
}
if let Some(look) = &b.imported {
let faces: Vec = look.faces.iter().map(|(name, (color, opacity))| json!([name, color, opacity])).collect();
r["imported"] = json!({"color": look.color, "opacity": look.opacity, "faces": faces});
}
r["body"] = json!(self.body(&b.body));
self.model_bodies.push(r);
self.model_body_index.insert(key, self.model_bodies.len() - 1);
Some(self.model_bodies.len() - 1)
}
/// The place of a model body's kernel body: its own (a placed copy shares its record with
/// the part's other copies, but not its display), with the bodies the rounds that made it
/// were made on, each written once though no state holds it: a later round at a corner where
/// they meet blends them again, in a model opened from the file as in one evaluated anew.
fn body(&mut self, body: &Body) -> usize {
let key = |b: &Body| std::ptr::from_ref(b.record()).addr();
self.bodies.push(body.clone());
let first = self.bodies.len() - 1;
self.body_index.entry(key(body)).or_insert(first);
let (mut at, mut of) = (body.clone(), first);
// Down the rounds, until a body made on one already written.
while let Some((before, edges)) = at.rounds().map(|(b, e)| (b.clone(), e.to_vec())) {
let (i, new) = match self.body_index.get(&key(&before)) {
Some(i) => (*i, false),
None => {
self.bodies.push(before.clone());
self.body_index.insert(key(&before), self.bodies.len() - 1);
(self.bodies.len() - 1, true)
}
};
self.rounds.push(json!({"body": of, "before": i, "edges": edges}));
if !new {
break;
}
(at, of) = (before, i);
}
first
}
fn sketch(&mut self, s: &Arc) -> Option {
let id = Arc::as_ptr(s) as usize;
if let Some(i) = self.sketch_index.get(&id) {
return Some(*i);
}
let r = json!({
"feature": s.feature, "name": s.name, "plane": serde_json::to_value(s.plane).ok()?,
"sketch": serde_json::to_value(&s.sketch).ok()?, "report": serde_json::to_value(&s.report).ok()?,
});
self.sketches.push(r);
self.sketch_index.insert(id, self.sketches.len() - 1);
Some(self.sketches.len() - 1)
}
fn sheet(&mut self, sheet: &crate::sheet::SheetBody) -> Option {
// Keyed by the sheet written as text, straight from the sheet: every state asks for each
// of its sheets, and building the record (a JSON tree) each time only to find it written
// already took most of a sheet-metal design's save (906 states, 300 sheets: 0.8 s). Two
// sheets are the same text exactly when they are the same record.
let key = serde_json::to_string(sheet).ok()?;
if let Some(i) = self.sheet_index.get(&key) {
return Some(*i);
}
let record = serde_json::to_value(sheet).ok()?;
self.sheets.push(record);
self.sheet_index.insert(key, self.sheets.len() - 1);
Some(self.sheets.len() - 1)
}
fn state(&mut self, st: &Arc) -> Option {
let id = Arc::as_ptr(st) as usize;
if let Some(i) = self.state_index.get(&id) {
return Some(*i);
}
let bodies = st.bodies.iter().map(|b| self.model_body(b)).collect::