Skip to main content

bread_format/
ownership.rs

1/*
2 * SPDX-FileCopyrightText: 2026 SynrgStudio
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! Checks that an edit changed only what the editor owns (`SPEC.md`, section
7//! 7.4). Nothing in a file can stop a program from changing another
8//! program's data, but a program that writes through this crate can call
9//! [`check_edit`] before saving, and its tests can too.
10//!
11//! The scene, the meshes that leaves show, the metadata, the roles and the
12//! thumbnail are shared. The settings, the supports, the hollows and the
13//! support previews belong to Breadslicer ([`BREADSLICER`]). Each program
14//! data, surface paint and volume entry belongs to the program it names, and
15//! a mesh that no leaf shows to the owner of the entry that names it. Paint
16//! read from surface chunk version 1 names no program, so anyone may change
17//! it. The chunks this build does not know are kept as they were read,
18//! unless the edit removes or renumbers nodes or meshes.
19
20use std::collections::HashSet;
21use std::fmt;
22
23use crate::container::Chunk;
24use crate::file::BreadFile;
25use crate::scene::{NodeKind, Scene};
26
27/// The program name that owns the application chunks (`PROJ`, `SUPP`,
28/// `HOLW`) and the support preview (`SPRV`).
29pub const BREADSLICER: &str = "breadslicer";
30
31/// Who made an edit.
32#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33pub enum Editor<'a> {
34    /// A program, by its name, such as `nudl`: it may change what is shared
35    /// and what it owns.
36    Program(&'a str),
37    /// A program that only repairs meshes: it may change the vertices and
38    /// triangles of the meshes that leaves show, and the thumbnail.
39    MeshRepair,
40}
41
42/// Where each node and each mesh of the original file went in the edited
43/// one: `nodes[i]` is the new index of node `i`, or `None` if the edit
44/// removed it, and the same for `meshes`.
45#[derive(Clone, Debug, PartialEq, Eq)]
46pub struct Remap {
47    pub nodes: Vec<Option<usize>>,
48    pub meshes: Vec<Option<usize>>,
49}
50
51impl Remap {
52    /// Every node and mesh of `original` keeps its index.
53    pub fn identity(original: &BreadFile) -> Self {
54        Self {
55            nodes: (0..original.scene.nodes.len()).map(Some).collect(),
56            meshes: (0..original.scene.meshes.len()).map(Some).collect(),
57        }
58    }
59
60    /// Whether every node and mesh keeps its index.
61    pub fn is_identity(&self) -> bool {
62        let same = |list: &[Option<usize>]| list.iter().enumerate().all(|(i, &to)| to == Some(i));
63        same(&self.nodes) && same(&self.meshes)
64    }
65
66    fn node(&self, node: usize) -> Option<usize> {
67        self.nodes.get(node).copied().flatten()
68    }
69
70    fn mesh(&self, mesh: usize) -> Option<usize> {
71        self.meshes.get(mesh).copied().flatten()
72    }
73}
74
75/// A part of a file, named by its indices in the original file.
76#[derive(Clone, Debug, PartialEq, Eq)]
77pub enum Data {
78    /// The project settings (`PROJ`).
79    Settings,
80    /// The supports entry of a model (`SUPP`).
81    Supports { model: usize },
82    /// The hollows entry of a model (`HOLW`).
83    Hollow { model: usize },
84    /// The support preview of a support leaf (`SPRV`).
85    SupportPreview { leaf: usize },
86    /// A surface paint entry (`SURF`).
87    Surface { leaf: usize, kind: u8 },
88    /// A volume entry (`VOLM`).
89    Volume { model: usize, kind: u8, mesh: usize },
90    /// A program data entry (`PROG`), about a node or the whole file.
91    ProgramData { node: Option<usize> },
92    /// A mesh of the scene.
93    Mesh { mesh: usize },
94    /// The scene apart from what its meshes hold: its nodes, transforms and
95    /// mesh resources, and how many meshes it has.
96    Scene,
97    /// The roles (`ROLE`).
98    Roles,
99    /// The metadata (`META`).
100    Metadata,
101    /// A chunk this build does not know, by its tag.
102    Chunk { tag: [u8; 4] },
103}
104
105/// How data changed.
106#[derive(Clone, Copy, Debug, PartialEq, Eq)]
107pub enum Change {
108    /// It is in both files, but not the same.
109    Changed,
110    /// It is in the original only.
111    Dropped,
112    /// It is in the edited file only.
113    Added,
114}
115
116/// A change the editor may not make.
117#[derive(Clone, Debug, PartialEq, Eq)]
118pub enum Violation {
119    /// The editor changed data that another program owns.
120    NotOwned {
121        data: Data,
122        owner: String,
123        change: Change,
124    },
125    /// A mesh repair changed something other than the meshes that leaves
126    /// show and the thumbnail.
127    NotARepair { data: Data },
128    /// The remap does not fit the files: its lists are not as long as the
129    /// original's nodes and meshes, or it names an index the edited file does
130    /// not have, or it sends two nodes or two meshes to the same index.
131    BadRemap,
132}
133
134impl fmt::Display for Data {
135    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136        match self {
137            Self::Settings => f.write_str("the project settings"),
138            Self::Supports { model } => write!(f, "the supports of node {model}"),
139            Self::Hollow { model } => write!(f, "the hollow of node {model}"),
140            Self::SupportPreview { leaf } => write!(f, "the support preview of node {leaf}"),
141            Self::Surface { leaf, kind } => write!(f, "the paint of kind {kind} on node {leaf}"),
142            Self::Volume { model, kind, mesh } => {
143                write!(f, "the volume of kind {kind} on node {model}, mesh {mesh}")
144            }
145            Self::ProgramData { node: Some(node) } => {
146                write!(f, "the program data about node {node}")
147            }
148            Self::ProgramData { node: None } => {
149                f.write_str("the program data about the whole file")
150            }
151            Self::Mesh { mesh } => write!(f, "mesh {mesh}"),
152            Self::Scene => f.write_str("the scene"),
153            Self::Roles => f.write_str("the roles"),
154            Self::Metadata => f.write_str("the metadata"),
155            Self::Chunk { tag } => write!(f, "the chunk {}", String::from_utf8_lossy(tag)),
156        }
157    }
158}
159
160impl fmt::Display for Violation {
161    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162        match self {
163            Self::NotOwned {
164                data,
165                owner,
166                change,
167            } => {
168                let change = match change {
169                    Change::Changed => "changed",
170                    Change::Dropped => "dropped",
171                    Change::Added => "added",
172                };
173                write!(f, "{data}, which belongs to {owner}, was {change}")
174            }
175            Self::NotARepair { data } => {
176                write!(f, "{data} changed, which a mesh repair may not change")
177            }
178            Self::BadRemap => f.write_str("the remap does not fit the files"),
179        }
180    }
181}
182
183/// Checks that `edited` changes `original` only where `editor` may, with
184/// every node and mesh keeping its index. Returns every change it may not
185/// make.
186pub fn check_edit(
187    original: &BreadFile,
188    edited: &BreadFile,
189    editor: Editor<'_>,
190) -> Result<(), Vec<Violation>> {
191    check_edit_remapped(original, edited, editor, &Remap::identity(original))
192}
193
194/// Checks that `edited` changes `original` only where `editor` may, with
195/// the nodes and meshes moved or removed as `remap` says. Entries about a
196/// removed node may be gone, whoever owns them; an entry that names a moved
197/// node or mesh must name its new index. A mesh repair keeps every index, so
198/// for [`Editor::MeshRepair`] a remap other than the identity is a
199/// violation.
200pub fn check_edit_remapped(
201    original: &BreadFile,
202    edited: &BreadFile,
203    editor: Editor<'_>,
204    remap: &Remap,
205) -> Result<(), Vec<Violation>> {
206    let violations = match editor {
207        Editor::Program(program) => {
208            if !remap_fits(original, edited, remap) {
209                return Err(vec![Violation::BadRemap]);
210            }
211            check_program(original, edited, program, remap)
212        }
213        Editor::MeshRepair => {
214            if !remap_fits(original, edited, remap) || !remap.is_identity() {
215                return Err(vec![Violation::BadRemap]);
216            }
217            check_repair(original, edited)
218        }
219    };
220    if violations.is_empty() {
221        Ok(())
222    } else {
223        Err(violations)
224    }
225}
226
227fn remap_fits(original: &BreadFile, edited: &BreadFile, remap: &Remap) -> bool {
228    let fits = |list: &[Option<usize>], from: usize, to: usize| {
229        let mut seen = HashSet::new();
230        list.len() == from && list.iter().flatten().all(|&i| i < to && seen.insert(i))
231    };
232    fits(
233        &remap.nodes,
234        original.scene.nodes.len(),
235        edited.scene.nodes.len(),
236    ) && fits(
237        &remap.meshes,
238        original.scene.meshes.len(),
239        edited.scene.meshes.len(),
240    )
241}
242
243/// The meshes that a leaf of `scene` shows.
244fn shown_meshes(scene: &Scene) -> HashSet<usize> {
245    scene
246        .nodes
247        .iter()
248        .filter_map(|node| match node.kind {
249            NodeKind::Leaf { mesh } => Some(mesh),
250            NodeKind::SharedLeaf { resource } => scene.mesh_resources.get(resource).copied(),
251            NodeKind::Group { .. } | NodeKind::Reference { .. } => None,
252        })
253        .collect()
254}
255
256/// Compares the entries `before`, already remapped and without those about a
257/// removed part, with `after`, as lists in any order, and reports each one
258/// that changed, was dropped or was added. An entry of `before` with no equal
259/// in `after` but one in the same place, as `same_place` says, changed.
260fn compare<T: PartialEq>(
261    before: &[(T, Data)],
262    after: &[(T, Data)],
263    same_place: impl Fn(&T, &T) -> bool,
264    report: &mut impl FnMut(Data, Change),
265) {
266    let mut left: Vec<bool> = vec![true; after.len()];
267    let mut unmatched = Vec::new();
268    for (entry, data) in before {
269        match (0..after.len()).find(|&i| left[i] && after[i].0 == *entry) {
270            Some(i) => left[i] = false,
271            None => unmatched.push((entry, data)),
272        }
273    }
274    for (entry, data) in unmatched {
275        match (0..after.len()).find(|&i| left[i] && same_place(&after[i].0, entry)) {
276            Some(i) => {
277                left[i] = false;
278                report(data.clone(), Change::Changed);
279            }
280            None => report(data.clone(), Change::Dropped),
281        }
282    }
283    for (i, (_, data)) in after.iter().enumerate() {
284        if left[i] {
285            report(data.clone(), Change::Added);
286        }
287    }
288}
289
290fn check_program(
291    original: &BreadFile,
292    edited: &BreadFile,
293    program: &str,
294    remap: &Remap,
295) -> Vec<Violation> {
296    let mut found: Vec<(Data, String, Change)> = Vec::new();
297
298    if program != BREADSLICER {
299        let mut push = |data, change| found.push((data, BREADSLICER.to_string(), change));
300        if original.settings != edited.settings {
301            push(Data::Settings, Change::Changed);
302        }
303        let supports = |file: &BreadFile, remapped: bool| {
304            file.supports
305                .iter()
306                .filter_map(|entry| {
307                    let mut entry = entry.clone();
308                    let data = Data::Supports { model: entry.model };
309                    if remapped {
310                        entry.model = remap.node(entry.model)?;
311                        entry.support = remap.node(entry.support)?;
312                    }
313                    Some((entry, data))
314                })
315                .collect::<Vec<_>>()
316        };
317        compare(
318            &supports(original, true),
319            &supports(edited, false),
320            |a, b| a.model == b.model,
321            &mut push,
322        );
323        let hollows = |file: &BreadFile, remapped: bool| {
324            file.hollows
325                .iter()
326                .filter_map(|entry| {
327                    let mut entry = entry.clone();
328                    let data = Data::Hollow { model: entry.model };
329                    if remapped {
330                        entry.model = remap.node(entry.model)?;
331                        entry.original = remap.mesh(entry.original)?;
332                    }
333                    Some((entry, data))
334                })
335                .collect::<Vec<_>>()
336        };
337        compare(
338            &hollows(original, true),
339            &hollows(edited, false),
340            |a, b| a.model == b.model,
341            &mut push,
342        );
343        let previews = |file: &BreadFile, remapped: bool| {
344            file.support_previews
345                .iter()
346                .filter_map(|entry| {
347                    let mut entry = entry.clone();
348                    let data = Data::SupportPreview { leaf: entry.leaf };
349                    if remapped {
350                        entry.leaf = remap.node(entry.leaf)?;
351                    }
352                    Some((entry, data))
353                })
354                .collect::<Vec<_>>()
355        };
356        compare(
357            &previews(original, true),
358            &previews(edited, false),
359            |a, b| a.leaf == b.leaf,
360            &mut push,
361        );
362    }
363
364    // Program data, paint and volumes of every other program, one owner at
365    // a time.
366    let mut owners: Vec<&str> = Vec::new();
367    for file in [original, edited] {
368        owners.extend(file.program_data.iter().map(|e| e.program.as_str()));
369        owners.extend(file.surface.iter().filter_map(|e| e.program.as_deref()));
370        owners.extend(file.volumes.iter().map(|e| e.program.as_str()));
371    }
372    owners.sort_unstable();
373    owners.dedup();
374    for owner in owners.into_iter().filter(|&owner| owner != program) {
375        let mut push = |data, change| found.push((data, owner.to_string(), change));
376
377        let entries = |file: &BreadFile, remapped: bool| {
378            file.program_data
379                .iter()
380                .filter(|entry| entry.program == owner)
381                .filter_map(|entry| {
382                    let mut entry = entry.clone();
383                    let data = Data::ProgramData { node: entry.node };
384                    if remapped && let Some(node) = entry.node {
385                        entry.node = Some(remap.node(node)?);
386                    }
387                    Some((entry, data))
388                })
389                .collect::<Vec<_>>()
390        };
391        compare(
392            &entries(original, true),
393            &entries(edited, false),
394            |a, b| a.node == b.node,
395            &mut push,
396        );
397
398        let paint = |file: &BreadFile, remapped: bool| {
399            file.surface
400                .iter()
401                .filter(|entry| entry.program.as_deref() == Some(owner))
402                .filter_map(|entry| {
403                    let mut entry = entry.clone();
404                    let data = Data::Surface {
405                        leaf: entry.leaf,
406                        kind: entry.kind,
407                    };
408                    if remapped {
409                        entry.leaf = remap.node(entry.leaf)?;
410                    }
411                    Some((entry, data))
412                })
413                .collect::<Vec<_>>()
414        };
415        let mut after = paint(edited, false);
416        // Paint read from chunk version 1 names no program: a program that
417        // writes it back may name the program that painted it.
418        let mut unowned: Vec<_> = original
419            .surface
420            .iter()
421            .filter(|entry| entry.program.is_none())
422            .filter_map(|entry| Some((remap.node(entry.leaf)?, entry)))
423            .collect();
424        after.retain(|(entry, _)| {
425            let claimed = unowned.iter().position(|(leaf, old)| {
426                *leaf == entry.leaf
427                    && old.kind == entry.kind
428                    && old.version == entry.version
429                    && old.document == entry.document
430            });
431            claimed.map(|i| unowned.swap_remove(i)).is_none()
432        });
433        compare(
434            &paint(original, true),
435            &after,
436            |a, b| a.leaf == b.leaf && a.kind == b.kind,
437            &mut push,
438        );
439
440        let volumes = |file: &BreadFile, remapped: bool| {
441            file.volumes
442                .iter()
443                .filter(|entry| entry.program == owner)
444                .filter_map(|entry| {
445                    let mut entry = entry.clone();
446                    let data = Data::Volume {
447                        model: entry.model,
448                        kind: entry.kind,
449                        mesh: entry.mesh,
450                    };
451                    if remapped {
452                        entry.model = remap.node(entry.model)?;
453                        entry.mesh = remap.mesh(entry.mesh)?;
454                    }
455                    Some((entry, data))
456                })
457                .collect::<Vec<_>>()
458        };
459        compare(
460            &volumes(original, true),
461            &volumes(edited, false),
462            |a, b| a.model == b.model && a.kind == b.kind && a.mesh == b.mesh,
463            &mut push,
464        );
465    }
466
467    // A mesh that no leaf shows belongs to the owner of the entry that names
468    // it: its contents stay, wherever it went.
469    let shown = shown_meshes(&original.scene);
470    let mut hidden: Vec<(usize, &str)> = Vec::new();
471    if program != BREADSLICER {
472        hidden.extend(original.hollows.iter().map(|e| (e.original, BREADSLICER)));
473    }
474    hidden.extend(
475        original
476            .volumes
477            .iter()
478            .filter(|e| e.program != program)
479            .map(|e| (e.mesh, e.program.as_str())),
480    );
481    hidden.sort_unstable();
482    hidden.dedup_by_key(|(mesh, _)| *mesh);
483    for (mesh, owner) in hidden {
484        if shown.contains(&mesh) {
485            continue;
486        }
487        // A mesh dropped with the entries that named it is not reported: those
488        // entries are reported if they should have stayed.
489        let Some(to) = remap.mesh(mesh) else { continue };
490        if original.scene.meshes.get(mesh) != edited.scene.meshes.get(to) {
491            found.push((Data::Mesh { mesh }, owner.to_string(), Change::Changed));
492        }
493    }
494
495    // Chunks this build does not know: kept as they were read, unless the
496    // edit removed or renumbered nodes or meshes, when they may be dropped,
497    // though not changed. Chunks the edited file adds are the editor's own.
498    let mut left: Vec<&Chunk> = edited.other_chunks.iter().collect();
499    for chunk in &original.other_chunks {
500        match left.iter().position(|&c| c == chunk) {
501            Some(i) => {
502                left.remove(i);
503            }
504            None if remap.is_identity() => found.push((
505                Data::Chunk { tag: chunk.tag.0 },
506                "the program that wrote it".to_string(),
507                Change::Dropped,
508            )),
509            None => {}
510        }
511    }
512
513    found
514        .into_iter()
515        .map(|(data, owner, change)| Violation::NotOwned {
516            data,
517            owner,
518            change,
519        })
520        .collect()
521}
522
523fn check_repair(original: &BreadFile, edited: &BreadFile) -> Vec<Violation> {
524    let mut violations = Vec::new();
525    let mut push = |data| violations.push(Violation::NotARepair { data });
526    let shown = shown_meshes(&original.scene);
527    let (before, after) = (&original.scene, &edited.scene);
528    if before.meshes.len() != after.meshes.len() {
529        push(Data::Scene);
530    }
531    for (i, (old, new)) in before.meshes.iter().zip(&after.meshes).enumerate() {
532        let changed = if shown.contains(&i) {
533            old.meta != new.meta
534        } else {
535            old != new
536        };
537        if changed {
538            push(Data::Mesh { mesh: i });
539        }
540    }
541    let rest = |scene: &Scene| Scene {
542        meshes: Vec::new(),
543        ..scene.clone()
544    };
545    if rest(before) != rest(after) {
546        push(Data::Scene);
547    }
548    if original.settings != edited.settings {
549        push(Data::Settings);
550    }
551    for entry in diff(&original.supports, &edited.supports) {
552        push(Data::Supports { model: entry.model });
553    }
554    for entry in diff(&original.hollows, &edited.hollows) {
555        push(Data::Hollow { model: entry.model });
556    }
557    for entry in diff(&original.support_previews, &edited.support_previews) {
558        push(Data::SupportPreview { leaf: entry.leaf });
559    }
560    for entry in diff(&original.surface, &edited.surface) {
561        push(Data::Surface {
562            leaf: entry.leaf,
563            kind: entry.kind,
564        });
565    }
566    for entry in diff(&original.volumes, &edited.volumes) {
567        push(Data::Volume {
568            model: entry.model,
569            kind: entry.kind,
570            mesh: entry.mesh,
571        });
572    }
573    for entry in diff(&original.program_data, &edited.program_data) {
574        push(Data::ProgramData { node: entry.node });
575    }
576    if !same_entries(&original.roles, &edited.roles) {
577        push(Data::Roles);
578    }
579    if !same_entries(&original.metadata, &edited.metadata) {
580        push(Data::Metadata);
581    }
582    for chunk in diff(&original.other_chunks, &edited.other_chunks) {
583        push(Data::Chunk { tag: chunk.tag.0 });
584    }
585    // An entry that changed is in both lists of a diff: report it once.
586    let mut once = Vec::new();
587    for violation in violations {
588        if !once.contains(&violation) {
589            once.push(violation);
590        }
591    }
592    once
593}
594
595/// Whether `a` and `b` hold the same entries, in any order.
596fn same_entries<T: PartialEq>(a: &[T], b: &[T]) -> bool {
597    a.len() == b.len() && diff(a, b).is_empty()
598}
599
600/// The entries of `a` that `b` lacks, and those of `b` that `a` lacks, each
601/// entry matched once.
602fn diff<'a, T: PartialEq>(a: &'a [T], b: &'a [T]) -> Vec<&'a T> {
603    let mut left: Vec<&T> = b.iter().collect();
604    let mut out = Vec::new();
605    for entry in a {
606        match left.iter().position(|&e| e == entry) {
607            Some(i) => {
608                left.remove(i);
609            }
610            None => out.push(entry),
611        }
612    }
613    out.extend(left);
614    out
615}