1#![cfg_attr(test, allow(clippy::unwrap_used))]
3mod annotations;
105mod appearance;
106mod archive;
107mod assembly;
108mod brep;
109mod carchive;
110mod classification;
111mod container;
112mod decode;
113mod dialect;
114pub mod exact_ledger;
115mod feature_schema;
116mod framed_string;
117#[doc(hidden)]
118pub mod fuzz;
119mod history;
120mod lane_refusal;
121mod layout;
123mod loss;
124mod metadata;
125mod native;
126mod parasolid;
127mod pmi;
128mod records;
129mod resolved_features;
130mod swift;
131mod tessellation;
132mod writer;
133mod writer_patch;
134mod writer_transform;
135
136use cadmpeg_core::decode::{DecodeContext, DecodeDepth, View};
137use cadmpeg_core::dialect::DialectId;
138use cadmpeg_core::CodecError;
139use cadmpeg_ir::ContainerSummary;
140use std::io::Write;
141
142use cadmpeg_ir::codec::write::{
143 target::{Catalog, ResolvedWrite},
144 ArenaCoverage, ArenaDispositions, Consumption, DepthNeed, EncodeInput, EncoderBackend,
145 ExportBody, PatchConsumption, WritePath,
146};
147use cadmpeg_ir::codec::{CodecBackend, Confidence, Decoded, FormatId};
148use cadmpeg_ir::document::CadIr;
149use cadmpeg_ir::hash::DOCUMENT_LOCAL_DIGEST_ATTRIBUTE;
150use cadmpeg_ir::ids::UnknownId;
151use cadmpeg_ir::{report::check::Finding, Annotations, SourceFidelity};
152
153const SOURCE_IMAGE_ID: &str = "sldprt:file:source-image#0";
155
156fn source_image_id() -> UnknownId {
158 UnknownId::compose(
159 &cadmpeg_ir::identity_namespace!("sldprt", "file", "source-image"),
160 cadmpeg_ir::identity_key!("0"),
161 )
162}
163
164#[derive(Debug, Default, Clone, Copy)]
166pub struct SldprtCodec;
167
168struct SourceRecord<'a> {
171 id: UnknownId,
172 data: Option<&'a [u8]>,
173}
174
175impl SldprtCodec {
176 fn write_preserved_with_annotations(
191 ir: &CadIr,
192 annotations: &Annotations,
193 records: &[SourceRecord<'_>],
194 writer: &mut dyn Write,
195 ) -> Result<Written, CodecError> {
196 let expected = ir
197 .source
198 .as_ref()
199 .and_then(|source| source.attributes.get(DOCUMENT_LOCAL_DIGEST_ATTRIBUTE));
200 let Some(expected) = expected else {
201 return Self::write_semantic(
202 ir,
203 annotations,
204 records,
205 SemanticFidelity::ReplaySkipped(ReplaySkipped::BaselineMissing),
206 writer,
207 );
208 };
209 if decode::document_local_sha256(ir)? != *expected {
210 return Self::write_semantic(
211 ir,
212 annotations,
213 records,
214 SemanticFidelity::ReplaySkipped(ReplaySkipped::DigestMismatch),
215 writer,
216 );
217 }
218 let Some(record) = records
219 .iter()
220 .find(|record| record.id.as_str() == SOURCE_IMAGE_ID)
221 else {
222 return Self::write_semantic(
223 ir,
224 annotations,
225 records,
226 SemanticFidelity::ReplaySkipped(ReplaySkipped::ImageMissing),
227 writer,
228 );
229 };
230 let Some(data) = record.data.as_ref() else {
231 return Self::write_semantic(
232 ir,
233 annotations,
234 records,
235 SemanticFidelity::ReplaySkipped(ReplaySkipped::ImageMissing),
236 writer,
237 );
238 };
239 writer.write_all(data)?;
240 Ok(Written::Replayed)
241 }
242
243 fn write_semantic(
247 ir: &CadIr,
248 annotations: &Annotations,
249 records: &[SourceRecord<'_>],
250 fidelity: SemanticFidelity,
251 writer: &mut dyn Write,
252 ) -> Result<Written, CodecError> {
253 let writer::SemanticOutput {
254 dialect,
255 coverage,
256 omitted_envelope_bytes,
257 } = writer::write_semantic_with_records(ir, annotations, records, writer)?;
258 let native = ir
259 .native
260 .namespace("sldprt")
261 .map(|namespace| native::SldprtNative::load(namespace).map_err(CodecError::from))
262 .transpose()?;
263 let source_arena = cadmpeg_core::decode::DecodeArena::new();
264 let source_context = records
265 .iter()
266 .find(|record| record.id.as_str() == SOURCE_IMAGE_ID)
267 .and_then(|record| record.data)
268 .map(|bytes| {
269 cadmpeg_core::decode::DecodeContext::from_root_bytes(
270 bytes,
271 &source_arena,
272 &cadmpeg_core::decode::DecodePolicy::desktop(),
273 )
274 })
275 .transpose()?;
276 let source_scan = source_context
277 .as_ref()
278 .map(|(ctx, root)| container::scan(ctx, *root))
279 .transpose()?;
280 history::write::brep_agreement::validate(ir, native.as_ref(), source_scan.as_ref())?;
281 Ok(Written::Semantic {
282 path: if records.is_empty() {
283 SemanticPath::Synthesized
284 } else {
285 SemanticPath::Patched
286 },
287 dialect,
288 fidelity,
289 coverage,
290 omitted_envelope_bytes,
291 })
292 }
293}
294
295#[derive(Debug, Clone, Copy, PartialEq, Eq)]
297enum ReplaySkipped {
298 BaselineMissing,
299 DigestMismatch,
300 ImageMissing,
301}
302
303impl ReplaySkipped {
304 fn consumption(self) -> Consumption {
305 Consumption::Degraded {
306 reason: match self {
307 Self::BaselineMissing => "preserved SLDPRT source digest baseline is unavailable",
308 Self::DigestMismatch => {
309 "decoded model no longer matches the preserved SLDPRT source digest"
310 }
311 Self::ImageMissing => "preserved SLDPRT source image is unavailable",
312 }
313 .into(),
314 }
315 }
316}
317
318enum SemanticFidelity {
322 NotConsumed,
323 ReplaySkipped(ReplaySkipped),
324}
325
326impl SemanticFidelity {
327 fn consumption(&self) -> Consumption {
328 match self {
329 Self::NotConsumed => Consumption::NotConsumed,
330 Self::ReplaySkipped(reason) => reason.consumption(),
331 }
332 }
333}
334
335#[derive(Debug, Clone, Copy, PartialEq, Eq)]
338enum SemanticPath {
339 Patched,
341 Synthesized,
343}
344
345impl SemanticPath {
346 fn write_path(self, consumption: Consumption) -> WritePath {
347 match self {
348 Self::Patched => WritePath::Patched {
349 consumption: PatchConsumption::Independent(consumption),
350 },
351 Self::Synthesized => WritePath::Synthesized { consumption },
352 }
353 }
354}
355
356enum Written {
358 Replayed,
361 Semantic {
364 path: SemanticPath,
365 dialect: DialectId,
366 fidelity: SemanticFidelity,
367 coverage: ArenaDispositions,
368 omitted_envelope_bytes: usize,
369 },
370}
371
372impl Written {
373 fn path(&self) -> WritePath {
376 match self {
377 Self::Replayed => WritePath::VerbatimReplay,
378 Self::Semantic { path, fidelity, .. } => path.write_path(fidelity.consumption()),
379 }
380 }
381
382 fn coverage(&self) -> ArenaCoverage {
385 match self {
386 Self::Replayed => ArenaCoverage::Complete,
387 Self::Semantic { coverage, .. } => ArenaCoverage::Declared(*coverage),
388 }
389 }
390
391 fn replay_skipped(&self) -> Option<(SemanticPath, ReplaySkipped)> {
393 match self {
394 Self::Semantic {
395 path,
396 fidelity: SemanticFidelity::ReplaySkipped(reason),
397 ..
398 } => Some((*path, *reason)),
399 _ => None,
400 }
401 }
402}
403
404impl CodecBackend for SldprtCodec {
405 const FORMAT: FormatId = FormatId::new(dialect::FORMAT);
406
407 fn validate_native(
408 ctx: &DecodeContext<'_>,
409 ir: &CadIr,
410 _source: Option<&cadmpeg_ir::SourceFidelity>,
411 ) -> Result<Vec<Finding>, CodecError> {
412 resolved_features::validate::validate_native(ctx, ir)
413 }
414
415 fn detect_impl(
416 &self,
417 ctx: &cadmpeg_core::decode::DecodeContext<'_>,
418 prefix: cadmpeg_core::decode::View<'_>,
419 ) -> Result<Confidence, cadmpeg_core::CodecError> {
420 let prefix = prefix.window();
421 if container::looks_like_sldprt(ctx, prefix)? {
422 Ok(Confidence::High)
423 } else {
424 Ok(Confidence::No)
425 }
426 }
427
428 fn inspect_impl(
429 &self,
430 ctx: &DecodeContext<'_>,
431 root: View<'_>,
432 ) -> Result<ContainerSummary, CodecError> {
433 let scan = container::scan(ctx, root)?;
434 let classification = dialect::classify_layers(&scan)?;
435 let mut summary = container::summarize(&scan, classification.layers().clone());
436 classification.append_losses(&mut summary.losses);
437 Ok(summary)
438 }
439
440 fn decode_impl(&self, ctx: &DecodeContext<'_>, root: View<'_>) -> Result<Decoded, CodecError> {
441 decode::decode(ctx, root)
442 }
443}
444
445impl EncoderBackend for SldprtCodec {
446 const FORMAT: FormatId = <Self as CodecBackend>::FORMAT;
447 const NEEDS: DepthNeed = DepthNeed::AtLeast(DecodeDepth::Full);
450 type Target = Catalog;
451 const TARGET: Catalog = Catalog::new(dialect::TARGETS, Some(0));
452
453 fn plan_resolved(
454 &self,
455 input: EncodeInput<'_>,
456 target: ResolvedWrite<'_>,
457 ) -> Result<ExportBody, CodecError> {
458 writer::target::plan(input, &target)
459 }
460}
461
462fn source_records<'a>(
463 ir: &CadIr,
464 source_fidelity: &'a SourceFidelity,
465) -> Result<Vec<SourceRecord<'a>>, CodecError> {
466 let mut records = ir
467 .native_unknowns_iter("sldprt")
468 .map(|reference| {
469 let reference = reference?;
470 let retained = source_fidelity
471 .retained_record(reference.id.as_str())
472 .ok_or_else(|| {
473 cadmpeg_ir::native::NativeConvertError::MissingRetainedSourceRecord(
474 reference.id.as_str().to_owned(),
475 )
476 })?;
477 Ok(SourceRecord {
478 id: reference.id,
479 data: retained.data(),
480 })
481 })
482 .collect::<Result<Vec<_>, cadmpeg_ir::native::NativeConvertError>>()?;
483 if let Some(source) = source_fidelity.retained_record(SOURCE_IMAGE_ID) {
484 records.push(SourceRecord {
485 id: source_image_id(),
486 data: source.data(),
487 });
488 }
489 Ok(records)
490}
491
492#[cfg(test)]
493mod golden_tests;
494#[cfg(test)]
495mod integration_tests;
496#[cfg(test)]
497mod test_support;
498
499#[cfg(test)]
500mod tests {
501 use super::SOURCE_IMAGE_ID;
502
503 #[test]
504 fn source_record_join_borrows_the_retained_source_image() {
505 let payload = vec![0x5a; 4096];
506 let payload_ptr = payload.as_ptr();
507 let mut fidelity = cadmpeg_ir::SourceFidelity::default();
508 let id: cadmpeg_ir::ids::UnknownId = SOURCE_IMAGE_ID
509 .to_owned()
510 .try_into()
511 .expect("source image identity");
512 let record = cadmpeg_ir::source_fidelity::RetainedSourceRecord::from_bytes(
513 "source",
514 0,
515 cadmpeg_ir::source_fidelity::RetainedBytes::Inline { data: payload },
516 )
517 .expect("source image extent");
518 fidelity
519 .insert_retained_record(id, record)
520 .expect("source image identity is unique");
521
522 let records = crate::source_records(
523 &cadmpeg_ir::examples::unit_cube().expect("unit cube fixture is admitted"),
524 &fidelity,
525 )
526 .unwrap();
527 let retained = records[0].data.expect("retained source bytes");
528 assert_eq!(retained.as_ptr(), payload_ptr);
529 }
530}