renamite-behavior-common 0.3.12

ToolContext, selection, snapping, and view transforms shared by renamite behaviors.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
//! Pure Pathfinder authoring: boolean, divide, combine and break-apart.
//!
//! UI-agnostic by design. Each entry point reads a document, a selection and a
//! frame, and answers the `EditorCommand`s that perform the operation plus the
//! selection to leave behind, with no reference to a `Session`. The editor
//! shell and the MCP server therefore run the same code and cannot diverge.
//!
//! Every operation folds its commands into one undo step: callers wrap them in
//! `ToolOutput::BeginTransaction` / `CommitTransaction`, or `History::begin` /
//! `History::commit` around a `History::apply` of each.

use std::collections::HashSet;

use glam::DVec2;

use renamite_animation::Animated;
use renamite_geometry::{BooleanOp, VectorPath, boolean_bez, contours_to_bez, split_bez_subpaths};
use renamite_history::{EditorCommand, NodeTree, SelectionChange};
use renamite_model::{CompId, Document, Node, NodeId, NodeKind, Overrides, Parent, ShapeKind};

/// Which Pathfinder operation to run over the selected shape roots.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ShapeBoolean {
    Union,
    Difference,
    Intersection,
    Xor,
}

/// Z-order holes: a shape root is a shape node whose ancestors include a group
/// or layer, with no group/layer/comp descendant between the selection and it.
pub fn shape_roots_in_z_order(doc: &Document, comp: CompId, ids: &[NodeId]) -> Vec<NodeId> {
    fn visit(
        doc: &Document,
        children: &[NodeId],
        sel: &[NodeId],
        inherited_selected: bool,
        out: &mut Vec<NodeId>,
    ) {
        for &id in children.iter().rev() {
            let Some(node) = doc.nodes.get(id) else {
                continue;
            };
            let selected = inherited_selected || sel.contains(&id);

            match &node.kind {
                NodeKind::Shape(_) => {
                    if selected {
                        out.push(id);
                    }
                }
                NodeKind::Group | NodeKind::Layer(_) => {
                    visit(doc, &node.children, sel, selected, out);
                }
                _ => {}
            }
        }
    }

    let mut out = Vec::new();
    if let Some(composition) = doc.compositions.get(comp) {
        visit(doc, &composition.children, ids, false, &mut out);
    }
    out
}

/// Z-order holes: any node id (checked against the mask) is a painting target.
pub fn selection_roots(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
    let attached: Vec<NodeId> = ids
        .iter()
        .copied()
        .filter(|&id| node_is_attached(doc, id))
        .collect();
    let selected: HashSet<NodeId> = attached.iter().copied().collect();
    attached
        .into_iter()
        .filter(|&id| {
            let mut current = id;
            let mut seen = HashSet::new();
            while let Some(node) = doc.nodes.get(current) {
                if !seen.insert(current) {
                    return false;
                }
                let Some(parent) = node.parent else {
                    break;
                };
                if selected.contains(&parent) {
                    return false;
                }
                current = parent;
            }
            true
        })
        .collect()
}

/// A shape's contours expressed in the subject's space, at `frame`.
///
/// The subject is the first selected root and stays put; every other shape is
/// transformed into its coordinate space so booleans compose without nesting.
pub fn contours_in_subject_space(
    doc: &Document,
    id: NodeId,
    subject: NodeId,
    frame: f64,
) -> Result<Vec<VectorPath>, String> {
    let Some(node) = doc.nodes.get(id) else {
        return Err("Selected node no longer exists".into());
    };
    let local: kurbo::BezPath = match &node.kind {
        NodeKind::Shape(ShapeKind::CompoundPath(compound)) => compound.to_bez_path(frame),
        NodeKind::Shape(shape) => {
            renamite_model::shape_path(shape, id, frame, &Overrides::default())
        }
        _ => return Err("Selection contains non-shape nodes".into()),
    };

    let Some(from) = renamite_model::node_transform_context(doc, id, frame) else {
        return Err("Cannot resolve transforms for the selection".into());
    };
    let Some(to) = renamite_model::node_transform_context(doc, subject, frame) else {
        return Err("Cannot resolve transforms for the selection".into());
    };
    let to_subject_space = to.world.inverse() * from.world;

    let mapped = to_subject_space * local;
    Ok(split_bez_subpaths(&mapped))
}

/// Wrap contours back into the tightest shape kind: one contour is a plain
/// `Path`, several are a `CompoundPath`.
pub fn shape_kind_from_contours(contours: Vec<VectorPath>) -> Option<ShapeKind> {
    match contours.len() {
        0 => None,
        1 => contours
            .into_iter()
            .next()
            .map(|c| ShapeKind::Path(Animated::new(c))),
        _ => Some(ShapeKind::CompoundPath(renamite_model::CompoundPath {
            contours: contours.into_iter().map(Animated::new).collect(),
        })),
    }
}

/// An anchor's world bounds, for aligning to the page.
pub fn page_bounds_world(size: (u32, u32)) -> (DVec2, DVec2) {
    (DVec2::ZERO, DVec2::new(size.0 as f64, size.1 as f64))
}

/// Roots that can carry a geometric edit (align/distribute/flip/nudge): style
/// and modifier nodes have no honored transform (see
/// `renamite_model::node_supports_transform`), so resolve them to the shape they
/// paint or affect instead of writing dead values. Returns `None` when the node
/// is not a geometric carrier and no carrier exists.
pub fn geometric_target(doc: &Document, id: NodeId) -> Option<NodeId> {
    let node = doc.nodes.get(id)?;
    if renamite_model::node_supports_transform(&node.kind) {
        return Some(id);
    }
    match &node.kind {
        NodeKind::Style(_) => painted_shape_for(doc, id),
        NodeKind::Modifier(_) => {
            let parent = node.parent?;
            let parent_node = doc.nodes.get(parent)?;
            if renamite_model::node_supports_transform(&parent_node.kind) {
                Some(parent)
            } else {
                geometric_target(doc, parent)
            }
        }
        _ => None,
    }
}

/// The shape a paint node affects: the nearest preceding sibling that paints.
fn painted_shape_for(doc: &Document, id: NodeId) -> Option<NodeId> {
    let node = doc.nodes.get(id)?;
    if !matches!(node.kind, NodeKind::Style(_)) {
        return None;
    }
    let (parent, idx) = doc.locate(id)?;
    let siblings: Vec<NodeId> = match parent {
        Parent::Comp(c) => doc.compositions.get(c)?.children.clone(),
        Parent::Node(n) => doc.nodes.get(n)?.children.clone(),
    };
    for &sid in siblings[..idx].iter().rev() {
        match doc.nodes.get(sid).map(|n| &n.kind) {
            Some(NodeKind::Shape(_) | NodeKind::Text(_) | NodeKind::Image(_)) => return Some(sid),
            Some(NodeKind::Style(_) | NodeKind::Modifier(_)) => continue,
            _ => break,
        }
    }
    None
}

/// The parent and index a node occupies, for inserting siblings after it.
fn locate(doc: &Document, id: NodeId) -> Option<(Parent, usize)> {
    match doc.locate(id)? {
        (Parent::Node(p), i) => Some((Parent::Node(p), i)),
        (Parent::Comp(c), i) => Some((Parent::Comp(c), i)),
    }
}

fn node_name(doc: &Document, id: NodeId, fallback: &str) -> String {
    doc.nodes
        .get(id)
        .map(|n| n.name.clone())
        .unwrap_or_else(|| fallback.into())
}

/// One folder of Pathfinder work: a label for the undo step, the commands to
/// apply, and what should be selected once they land.
pub struct PathfinderEdit {
    pub label: String,
    pub commands: Vec<EditorCommand>,
    pub selection: SelectionChange,
}

/// Union / Difference / Intersection / Xor across the selected shape roots.
///
/// The subject keeps its position and receives the result; the other shapes are
/// removed. A result with no geometry deletes every selected shape instead.
pub fn boolean(
    doc: &Document,
    comp: CompId,
    selection: &[NodeId],
    frame: f64,
    operation: ShapeBoolean,
) -> Result<PathfinderEdit, String> {
    let ids = shape_roots_in_z_order(doc, comp, selection);
    if ids.len() < 2 {
        return Err("Select at least two closed shapes".into());
    }

    let subject = ids[0];
    let mut accumulated = contours_in_subject_space(doc, subject, subject, frame)?;
    if accumulated.is_empty() {
        return Err("The subject has no geometry".into());
    }

    let op = match operation {
        ShapeBoolean::Union => BooleanOp::Union,
        ShapeBoolean::Difference => BooleanOp::Difference,
        ShapeBoolean::Intersection => BooleanOp::Intersection,
        ShapeBoolean::Xor => BooleanOp::Xor,
    };

    for cutter in ids.iter().copied().skip(1) {
        let rhs = contours_in_subject_space(doc, cutter, subject, frame)?;
        let result = boolean_bez(&contours_to_bez(&accumulated), &contours_to_bez(&rhs), op)
            .map_err(|e| e.to_string())?;
        accumulated = result;
    }

    let label = format!("{operation:?}");

    if accumulated.is_empty() {
        return Ok(PathfinderEdit {
            label,
            commands: ids
                .iter()
                .copied()
                .map(|id| EditorCommand::RemoveNode { id })
                .collect(),
            selection: SelectionChange::Set(Vec::new()),
        });
    }

    let mut commands = vec![EditorCommand::SetNodeKind {
        id: subject,
        kind: NodeKind::Shape(
            shape_kind_from_contours(accumulated).ok_or("Boolean produced no geometry")?,
        ),
    }];
    for id in ids.iter().copied().skip(1) {
        commands.push(EditorCommand::RemoveNode { id });
    }

    Ok(PathfinderEdit {
        label,
        commands,
        selection: SelectionChange::Set(vec![subject]),
    })
}

/// Cut the subject by every other selected shape; each cut becomes a piece.
pub fn divide(
    doc: &Document,
    comp: CompId,
    selection: &[NodeId],
    frame: f64,
) -> Result<PathfinderEdit, String> {
    let ids = shape_roots_in_z_order(doc, comp, selection);
    if ids.len() < 2 {
        return Err("Select at least two closed shapes to divide".into());
    }
    let subject = ids[0];

    for &id in &ids {
        let closed = match doc.nodes.get(id).map(|n| &n.kind) {
            Some(NodeKind::Shape(ShapeKind::Path(p))) => p.value_at(frame).closed,
            Some(NodeKind::Shape(ShapeKind::CompoundPath(c))) => {
                c.contours.iter().all(|p| p.value_at(frame).closed)
            }
            Some(NodeKind::Shape(_)) => true,
            _ => false,
        };
        if !closed {
            return Err("Division requires closed shapes (open cutting not supported)".into());
        }
    }

    let mut pieces: Vec<Vec<VectorPath>> = Vec::new();
    let mut remaining = contours_in_subject_space(doc, subject, subject, frame)?;

    for cutter in ids.iter().copied().skip(1) {
        let rhs = contours_in_subject_space(doc, cutter, subject, frame)?;
        let rhs_bez = contours_to_bez(&rhs);

        let current = std::mem::take(&mut remaining);
        if current.is_empty() {
            break;
        }
        let cur_bez = contours_to_bez(&current);

        let (inside, outside) = (
            boolean_bez(&cur_bez, &rhs_bez, BooleanOp::Intersection).map_err(|e| e.to_string())?,
            boolean_bez(&cur_bez, &rhs_bez, BooleanOp::Difference).map_err(|e| e.to_string())?,
        );
        if !inside.is_empty() {
            pieces.push(inside);
        }
        remaining = outside;

        if remaining.is_empty() {
            break;
        }
    }
    if !remaining.is_empty() {
        pieces.push(remaining);
    }

    let output_kinds: Vec<ShapeKind> = pieces
        .into_iter()
        .filter_map(shape_kind_from_contours)
        .collect();
    if output_kinds.is_empty() {
        return Err("Division produced no geometry".into());
    }

    let (parent, index) =
        locate(doc, subject).ok_or_else(|| "Subject is not attached".to_string())?;
    let template_name = node_name(doc, subject, "Piece");

    let mut commands = vec![EditorCommand::SetNodeKind {
        id: subject,
        kind: NodeKind::Shape(output_kinds[0].clone()),
    }];

    for (k, kind) in output_kinds.iter().enumerate().skip(1) {
        let mut node = doc
            .nodes
            .get(subject)
            .cloned()
            .unwrap_or_else(|| Node::new(template_name.as_str(), NodeKind::Group));
        node.name = format!("{template_name} {}", k + 1);
        node.parent = None;
        node.children.clear();
        node.kind = NodeKind::Shape(kind.clone());
        commands.push(EditorCommand::InsertNode {
            parent,
            index: index + k,
            tree: NodeTree::leaf(node),
        });
    }

    for id in ids.iter().copied().skip(1) {
        commands.push(EditorCommand::RemoveNode { id });
    }

    Ok(PathfinderEdit {
        label: "Division".into(),
        commands,
        selection: SelectionChange::Set(vec![subject]),
    })
}

/// Flatten a compound path into its contours; the subject keeps the first.
pub fn break_apart(
    doc: &Document,
    selection: &[NodeId],
    frame: f64,
) -> Result<PathfinderEdit, String> {
    if selection.len() != 1 {
        return Err("Select one combined path to break apart".into());
    }
    let id = selection[0];

    let Some(contours) = (match doc.nodes.get(id).map(|n| &n.kind) {
        Some(NodeKind::Shape(ShapeKind::CompoundPath(compound))) => Some(
            compound
                .contours
                .iter()
                .map(|c| c.value_at(frame))
                .collect::<Vec<_>>(),
        ),
        _ => None,
    }) else {
        return Err("Break apart requires a compound path".into());
    };
    if contours.len() < 2 {
        return Err("The compound path has a single contour".into());
    }

    let (parent, index) = locate(doc, id).ok_or_else(|| "Node is not attached".to_string())?;
    let name = node_name(doc, id, "Path");

    let mut commands = vec![EditorCommand::SetNodeKind {
        id,
        kind: NodeKind::Shape(ShapeKind::Path(Animated::new(contours[0].clone()))),
    }];

    for (k, contour) in contours.iter().enumerate().skip(1) {
        let mut node = doc
            .nodes
            .get(id)
            .cloned()
            .unwrap_or_else(|| Node::new(name.as_str(), NodeKind::Group));
        node.name = format!("{name} {}", k + 1);
        node.parent = None;
        node.children.clear();
        node.kind = NodeKind::Shape(ShapeKind::Path(Animated::new(contour.clone())));
        commands.push(EditorCommand::InsertNode {
            parent,
            index: index + k,
            tree: NodeTree::leaf(node),
        });
    }

    Ok(PathfinderEdit {
        label: "Break apart".into(),
        commands,
        selection: SelectionChange::Set(vec![id]),
    })
}

/// Merge every selected shape into one compound path; the subject keeps it.
pub fn combine(
    doc: &Document,
    comp: CompId,
    selection: &[NodeId],
    frame: f64,
) -> Result<PathfinderEdit, String> {
    let ids = shape_roots_in_z_order(doc, comp, selection);
    if ids.len() < 2 {
        return Err("Select at least two objects to combine".into());
    }
    let bottom = ids[0];

    let mut contours: Vec<VectorPath> = Vec::new();
    for id in &ids {
        contours.extend(contours_in_subject_space(doc, *id, bottom, frame)?);
    }
    if contours.is_empty() {
        return Err("Nothing to combine".into());
    }

    let mut commands = vec![EditorCommand::SetNodeKind {
        id: bottom,
        kind: NodeKind::Shape(ShapeKind::CompoundPath(renamite_model::CompoundPath {
            contours: contours.into_iter().map(Animated::new).collect(),
        })),
    }];
    for id in ids.iter().copied().skip(1) {
        commands.push(EditorCommand::RemoveNode { id });
    }

    Ok(PathfinderEdit {
        label: "Combine".into(),
        commands,
        selection: SelectionChange::Set(vec![bottom]),
    })
}

/// Whether a node still hangs off exactly one composition. Cycles stop the
/// walk, and a node with both a parent and a composition membership is corrupt.
pub fn node_is_attached(doc: &Document, id: NodeId) -> bool {
    let mut current = id;
    let mut visited = HashSet::new();
    loop {
        if !visited.insert(current) {
            return false;
        }
        let Some(node) = doc.nodes.get(current) else {
            return false;
        };
        let root_memberships: usize = doc
            .compositions
            .values()
            .map(|composition| {
                composition
                    .children
                    .iter()
                    .filter(|&&child| child == current)
                    .count()
            })
            .sum();
        if node.parent.is_some() && root_memberships != 0 {
            return false;
        }
        let Some(parent) = node.parent else {
            return root_memberships == 1;
        };
        let Some(parent_node) = doc.nodes.get(parent) else {
            return false;
        };
        if parent_node
            .children
            .iter()
            .filter(|&&child| child == current)
            .count()
            != 1
        {
            return false;
        }
        current = parent;
    }
}