//! 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 and sheet bodies 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;
/// A feature's boolean retries as saved. The kernel leaves `rejected` out when it is empty, and
/// the field has no default when read, so a saved model whose booleans retried was refused and
/// the design evaluated on every open (#5286): an absent list is an empty one.
fn saved_diagnostics(d: &Json) -> Result {
let mut d = d.clone();
if let Some(fields) = d.as_object_mut() {
fields.entry("rejected").or_insert_with(|| json!([]));
}
serde_json::from_value(d).map_err(|_| bad("saved model: diagnostics"))
}
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"))
}
fn bad(what: &str) -> DocError {
DocError::Invalid(what.into())
}
/// A design whose stored face or edge names were saved before format 14 (marked
/// [`crate::naming::LEGACY_MARK`]) finds them through names worked out from geometry on demand,
/// which a saved model does not keep.
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,
}
impl Writer {
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])).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 {
if b.body.is_mesh() {
return None;
}
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.bodies.len());
self.bodies.push(b.body.clone());
self.model_bodies.push(r);
self.model_body_index.insert(key, self.model_bodies.len() - 1);
Some(self.model_bodies.len() - 1)
}
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 {
let record = serde_json::to_value(sheet).ok()?;
let key = record.to_string();
if let Some(i) = self.sheet_index.get(&key) {
return Some(*i);
}
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::