spine_runtime 0.2.2

Unofficial native Rust port of the Spine 4.3 runtime. Renderer-agnostic.
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
// Spine Runtimes License Agreement
// Last updated April 5, 2025. Replaces all prior versions.
//
// Copyright (c) 2013-2025, Esoteric Software LLC
//
// Integration of the Spine Runtimes into software or otherwise creating
// derivative works of the Spine Runtimes is permitted under the terms and
// conditions of Section 2 of the Spine Editor License Agreement:
// http://esotericsoftware.com/spine-editor-license
//
// Otherwise, it is permitted to integrate the Spine Runtimes into software
// or otherwise create derivative works of the Spine Runtimes (collectively,
// "Products"), provided that each user of the Products must obtain their own
// Spine Editor license and redistribution of the Products in any form must
// include this license and copyright notice.
//
// THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
// BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

//! Attachments: what a slot shows or uses.
//!
//! [`RegionAttachment`] and [`MeshAttachment`] are textured and render;
//! their texture comes from a [`Sequence`] of [`TextureRegionRef`]s. The
//! others are geometry for constraints, clipping and hit tests.
//! Vertex-based attachments embed [`VertexData`].

use std::sync::atomic::{AtomicI32, Ordering};

use crate::data::{AttachmentId, AttachmentRef, SlotId};
use crate::math::Color;

/// Indices into a region's 8-float quad ([`Sequence::offsets`] and
/// [`Sequence::uvs`]): bottom-left, upper-left, upper-right, bottom-right,
/// x then y.
pub mod quad_corner {
    pub const BLX: usize = 0;
    pub const BLY: usize = 1;
    pub const ULX: usize = 2;
    pub const ULY: usize = 3;
    pub const URX: usize = 4;
    pub const URY: usize = 5;
    pub const BRX: usize = 6;
    pub const BRY: usize = 7;
}

/// Kind of an [`Attachment`]. `LinkedMesh` exists only in the export
/// format; a loaded linked mesh is a `Mesh` with
/// [`MeshAttachment::source_mesh`] set.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AttachmentType {
    Region,
    Mesh,
    LinkedMesh,
    BoundingBox,
    Path,
    Point,
    Clipping,
}

/// Any attachment. Data attachments live in
/// [`SkeletonData::attachments`](crate::data::SkeletonData::attachments);
/// runtime copies live in a [`Skin`](crate::data::Skin)'s arena.
#[derive(Debug, Clone, PartialEq)]
pub enum Attachment {
    Region(RegionAttachment),
    Mesh(MeshAttachment),
    BoundingBox(BoundingBoxAttachment),
    Path(PathAttachment),
    Point(PointAttachment),
    Clipping(ClippingAttachment),
}

/// Which attachment's timelines drive this one, and which other slots those
/// timelines also apply to. Linked meshes that inherit timelines point at
/// their source mesh, possibly in another slot.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct TimelineLink {
    /// `None` means the attachment itself.
    pub attachment: Option<AttachmentId>,
    /// Slots other than the keyed one that the timelines also apply to.
    pub slots: Vec<SlotId>,
}

impl Attachment {
    /// The attachment's own name, not the placeholder it is stored under.
    #[must_use]
    pub fn name(&self) -> &str {
        match self {
            Attachment::Region(a) => &a.name,
            Attachment::Mesh(a) => &a.name,
            Attachment::BoundingBox(a) => &a.name,
            Attachment::Path(a) => &a.name,
            Attachment::Point(a) => &a.name,
            Attachment::Clipping(a) => &a.name,
        }
    }

    #[must_use]
    pub fn kind(&self) -> AttachmentType {
        match self {
            Attachment::Region(_) => AttachmentType::Region,
            Attachment::Mesh(_) => AttachmentType::Mesh,
            Attachment::BoundingBox(_) => AttachmentType::BoundingBox,
            Attachment::Path(_) => AttachmentType::Path,
            Attachment::Point(_) => AttachmentType::Point,
            Attachment::Clipping(_) => AttachmentType::Clipping,
        }
    }

    /// `None` for point attachments, which no timeline drives.
    #[must_use]
    pub fn timeline_link(&self) -> Option<&TimelineLink> {
        match self {
            Attachment::Region(a) => Some(&a.timeline),
            Attachment::Mesh(a) => Some(&a.vertex_data.timeline),
            Attachment::BoundingBox(a) => Some(&a.vertex_data.timeline),
            Attachment::Path(a) => Some(&a.vertex_data.timeline),
            Attachment::Clipping(a) => Some(&a.vertex_data.timeline),
            Attachment::Point(_) => None,
        }
    }

    pub fn timeline_link_mut(&mut self) -> Option<&mut TimelineLink> {
        match self {
            Attachment::Region(a) => Some(&mut a.timeline),
            Attachment::Mesh(a) => Some(&mut a.vertex_data.timeline),
            Attachment::BoundingBox(a) => Some(&mut a.vertex_data.timeline),
            Attachment::Path(a) => Some(&mut a.vertex_data.timeline),
            Attachment::Clipping(a) => Some(&mut a.vertex_data.timeline),
            Attachment::Point(_) => None,
        }
    }

    /// The data attachment whose timelines apply to this one. `this` is how
    /// the caller refers to `self`. `None` for an owned attachment not
    /// copied from data.
    #[must_use]
    pub fn timeline_attachment(&self, this: AttachmentRef) -> Option<AttachmentId> {
        self.timeline_link()
            .and_then(|t| t.attachment)
            .or(match this {
                AttachmentRef::Data(id) => Some(id),
                AttachmentRef::Owned(_) => None,
            })
    }

    /// The caller-defined tag. See [`RegionAttachment::tag`].
    #[must_use]
    pub fn tag(&self) -> u32 {
        match self {
            Attachment::Region(a) => a.tag,
            Attachment::Mesh(a) => a.tag,
            Attachment::BoundingBox(a) => a.tag,
            Attachment::Path(a) => a.tag,
            Attachment::Point(a) => a.tag,
            Attachment::Clipping(a) => a.tag,
        }
    }

    pub fn set_tag(&mut self, tag: u32) {
        match self {
            Attachment::Region(a) => a.tag = tag,
            Attachment::Mesh(a) => a.tag = tag,
            Attachment::BoundingBox(a) => a.tag = tag,
            Attachment::Path(a) => a.tag = tag,
            Attachment::Point(a) => a.tag = tag,
            Attachment::Clipping(a) => a.tag = tag,
        }
    }

    /// A copy driven by the same timelines as this attachment. `this` is how
    /// the caller refers to `self`. Sequences get fresh ids, as in spine-cpp.
    #[must_use]
    pub fn copy(&self, this: AttachmentRef) -> Attachment {
        let timeline = self.timeline_attachment(this);
        let mut copy = self.clone();
        match &mut copy {
            Attachment::Region(a) => a.sequence = a.sequence.copy(),
            Attachment::Mesh(a) => a.sequence = a.sequence.copy(),
            _ => {}
        }
        if let Some(link) = copy.timeline_link_mut() {
            link.attachment = timeline;
        }
        copy
    }

    /// Points every sequence frame at `region` and recomputes UVs and region
    /// offsets. Returns `false`, changing nothing, for attachments without a
    /// texture.
    pub fn set_region(&mut self, region: TextureRegionRef) -> bool {
        match self {
            Attachment::Region(a) => {
                a.sequence.regions.fill(Some(region));
                a.update_sequence();
            }
            Attachment::Mesh(a) => {
                a.sequence.regions.fill(Some(region));
                a.update_sequence();
            }
            _ => return false,
        }
        true
    }

    /// `None` for region and point attachments.
    #[must_use]
    pub fn vertex_data(&self) -> Option<&VertexData> {
        match self {
            Attachment::Mesh(a) => Some(&a.vertex_data),
            Attachment::BoundingBox(a) => Some(&a.vertex_data),
            Attachment::Path(a) => Some(&a.vertex_data),
            Attachment::Clipping(a) => Some(&a.vertex_data),
            Attachment::Region(_) | Attachment::Point(_) => None,
        }
    }

    /// `Some` for region and mesh attachments only.
    #[must_use]
    pub fn sequence(&self) -> Option<&Sequence> {
        match self {
            Attachment::Region(a) => Some(&a.sequence),
            Attachment::Mesh(a) => Some(&a.sequence),
            _ => None,
        }
    }
}

/// Vertices of a mesh, bounding box, path or clipping attachment, either
/// relative to the slot's bone or weighted across several bones.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct VertexData {
    /// Empty when unweighted. Otherwise, per vertex: bone count, then that
    /// many bone indices.
    pub bones: Vec<i32>,
    /// Unweighted: x,y pairs. Weighted: x,y,weight triples per bone.
    pub vertices: Vec<f32>,
    /// Floats in the computed world vertices: vertex count × 2.
    pub world_vertices_length: u32,
    pub timeline: TimelineLink,
}

/// How a sequence timeline steps through frames.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum SequenceMode {
    #[default]
    Hold,
    Once,
    Loop,
    PingPong,
    OnceReverse,
    LoopReverse,
    PingPongReverse,
}

impl SequenceMode {
    /// Decodes the wire value; `None` if out of range.
    #[must_use]
    pub fn from_index(v: i32) -> Option<Self> {
        Some(match v {
            0 => Self::Hold,
            1 => Self::Once,
            2 => Self::Loop,
            3 => Self::PingPong,
            4 => Self::OnceReverse,
            5 => Self::LoopReverse,
            6 => Self::PingPongReverse,
            _ => return None,
        })
    }
}

static NEXT_SEQUENCE_ID: AtomicI32 = AtomicI32::new(0);

/// Frames of a region or mesh attachment. Every region and mesh has one; a
/// plain attachment is a one-frame sequence without a path suffix. Per-frame
/// UVs and region offsets are filled by [`RegionAttachment::update_sequence`]
/// and [`MeshAttachment::update_sequence`].
#[derive(Debug, Clone, PartialEq)]
pub struct Sequence {
    /// Unique per sequence; timelines use it as their property id.
    pub id: i32,
    /// Number appended to the path for the first frame.
    pub start: i32,
    /// Minimum digits in the appended frame number, zero-padded.
    pub digits: i32,
    /// Frame shown in the setup pose.
    pub setup_index: i32,
    /// Whether frame paths get a frame number appended. `false` for a
    /// plain one-frame attachment.
    pub path_suffix: bool,
    /// One region per frame; `None` where the loader found none.
    pub regions: Vec<Option<TextureRegionRef>>,
    /// Frame-major; each frame is `uvs.len() / regions.len()` floats.
    uvs: Vec<f32>,
    /// Region attachments only.
    offsets: Vec<[f32; 8]>,
}

impl Sequence {
    /// `count` frames with no regions resolved yet, and a fresh id.
    #[must_use]
    pub fn new(count: usize, path_suffix: bool) -> Self {
        Self {
            id: NEXT_SEQUENCE_ID.fetch_add(1, Ordering::Relaxed),
            start: 0,
            digits: 0,
            setup_index: 0,
            path_suffix,
            regions: vec![None; count],
            uvs: Vec::new(),
            offsets: Vec::new(),
        }
    }

    /// Copy with a fresh id, matching spine-cpp's copy constructor.
    #[must_use]
    pub fn copy(&self) -> Self {
        Self {
            id: NEXT_SEQUENCE_ID.fetch_add(1, Ordering::Relaxed),
            ..self.clone()
        }
    }

    /// Number of frames.
    #[must_use]
    pub fn count(&self) -> usize {
        self.regions.len()
    }

    /// The frame to show for a slot's `sequence_index` (-1 means
    /// `setup_index`), clamped to the frame range.
    #[must_use]
    pub fn resolve_index(&self, sequence_index: i32) -> usize {
        let mut index = sequence_index;
        if index == -1 {
            index = self.setup_index;
        }
        let last = self.regions.len() as i32 - 1;
        if index >= last {
            index = last;
        }
        index.max(0) as usize
    }

    /// Region of frame `index`; `None` if unresolved or out of range.
    #[must_use]
    pub fn region(&self, index: usize) -> Option<&TextureRegionRef> {
        self.regions.get(index).and_then(Option::as_ref)
    }

    /// UVs of frame `index`, as u,v pairs. Empty until `update_sequence`
    /// has run.
    ///
    /// # Panics
    /// If `index` is out of range after `update_sequence` has run.
    #[must_use]
    pub fn uvs(&self, index: usize) -> &[f32] {
        let stride = self.uvs.len() / self.regions.len().max(1);
        &self.uvs[index * stride..(index + 1) * stride]
    }

    /// Quad vertex offsets of frame `index`, indexed by [`quad_corner`], in
    /// the bone's local space.
    ///
    /// # Panics
    /// If `index` is out of range or this is not a region attachment's
    /// sequence.
    #[must_use]
    pub fn offsets(&self, index: usize) -> &[f32; 8] {
        &self.offsets[index]
    }

    /// Atlas path of frame `index`: `base_path` plus the zero-padded frame
    /// number `start + index` when [`Self::path_suffix`] is set.
    #[must_use]
    pub fn path(&self, base_path: &str, index: usize) -> String {
        if !self.path_suffix {
            return base_path.to_owned();
        }
        let frame = (self.start + index as i32).to_string();
        let pad = (self.digits.max(0) as usize).saturating_sub(frame.len());
        let mut out = String::with_capacity(base_path.len() + pad + frame.len());
        out.push_str(base_path);
        out.extend(std::iter::repeat_n('0', pad));
        out.push_str(&frame);
        out
    }
}

/// A textured quad placed relative to the slot's bone.
#[derive(Debug, Clone, PartialEq)]
pub struct RegionAttachment {
    pub name: String,
    /// Caller-defined; kept by [`Attachment::copy`] and emitted per vertex
    /// in [`RenderCommand::tags`](crate::render::RenderCommand::tags).
    pub tag: u32,
    /// Atlas path the regions were looked up by.
    pub path: String,
    pub color: Color,
    /// Center offset from the bone, in bone space.
    pub x: f32,
    pub y: f32,
    /// Degrees.
    pub rotation: f32,
    pub scale_x: f32,
    pub scale_y: f32,
    /// Size in skeleton units, before scale.
    pub width: f32,
    pub height: f32,
    pub sequence: Sequence,
    pub timeline: TimelineLink,
}

impl RegionAttachment {
    /// An identity-transform, zero-size, white region. Call
    /// [`Self::update_sequence`] once its fields and regions are set.
    #[must_use]
    pub fn new(name: impl Into<String>, sequence: Sequence) -> Self {
        Self {
            name: name.into(),
            tag: 0,
            path: String::new(),
            color: Color::WHITE,
            x: 0.0,
            y: 0.0,
            rotation: 0.0,
            scale_x: 1.0,
            scale_y: 1.0,
            width: 0.0,
            height: 0.0,
            sequence,
            timeline: TimelineLink::default(),
        }
    }

    /// Recomputes every frame's vertex offsets and UVs. Call after changing
    /// the transform, size or regions. A frame with no region gets 0..1 UVs.
    pub fn update_sequence(&mut self) {
        let n = self.sequence.regions.len();
        self.sequence.uvs.clear();
        self.sequence.uvs.resize(n * 8, 0.0);
        self.sequence.offsets.clear();
        self.sequence.offsets.resize(n, [0.0; 8]);
        for i in 0..n {
            let region = self.sequence.regions[i];
            let mut offsets = [0.0; 8];
            let mut uvs = [0.0; 8];
            compute_region_uvs(region.as_ref(), self, &mut offsets, &mut uvs);
            self.sequence.offsets[i] = offsets;
            self.sequence.uvs[i * 8..i * 8 + 8].copy_from_slice(&uvs);
        }
    }
}

fn compute_region_uvs(
    region: Option<&TextureRegionRef>,
    a: &RegionAttachment,
    offset: &mut [f32; 8],
    uvs: &mut [f32; 8],
) {
    use quad_corner::{BLX, BLY, BRX, BRY, ULX, ULY, URX, URY};

    let (width, height) = (a.width, a.height);
    let mut local_x2 = width / 2.0;
    let mut local_y2 = height / 2.0;
    let mut local_x = -local_x2;
    let mut local_y = -local_y2;
    let mut rotated = false;
    if let Some(r) = region.filter(|r| r.atlas) {
        local_x += r.offset_x / r.original_width * width;
        local_y += r.offset_y / r.original_height * height;
        if r.degrees == 90 {
            rotated = true;
            local_x2 -=
                (r.original_width - r.offset_x - r.packed_height) / r.original_width * width;
            local_y2 -=
                (r.original_height - r.offset_y - r.packed_width) / r.original_height * height;
        } else {
            local_x2 -= (r.original_width - r.offset_x - r.packed_width) / r.original_width * width;
            local_y2 -=
                (r.original_height - r.offset_y - r.packed_height) / r.original_height * height;
        }
    }
    local_x *= a.scale_x;
    local_y *= a.scale_y;
    local_x2 *= a.scale_x;
    local_y2 *= a.scale_y;
    let rad = a.rotation.to_radians();
    let cos = rad.cos();
    let sin = rad.sin();
    let local_x_cos = local_x * cos + a.x;
    let local_x_sin = local_x * sin;
    let local_y_cos = local_y * cos + a.y;
    let local_y_sin = local_y * sin;
    let local_x2_cos = local_x2 * cos + a.x;
    let local_x2_sin = local_x2 * sin;
    let local_y2_cos = local_y2 * cos + a.y;
    let local_y2_sin = local_y2 * sin;
    offset[BLX] = local_x_cos - local_y_sin;
    offset[BLY] = local_y_cos + local_x_sin;
    offset[ULX] = local_x_cos - local_y2_sin;
    offset[ULY] = local_y2_cos + local_x_sin;
    offset[URX] = local_x2_cos - local_y2_sin;
    offset[URY] = local_y2_cos + local_x2_sin;
    offset[BRX] = local_x2_cos - local_y_sin;
    offset[BRY] = local_y_cos + local_x2_sin;
    match region {
        None => {
            uvs[BLX] = 0.0;
            uvs[BLY] = 0.0;
            uvs[ULX] = 0.0;
            uvs[ULY] = 1.0;
            uvs[URX] = 1.0;
            uvs[URY] = 1.0;
            uvs[BRX] = 1.0;
            uvs[BRY] = 0.0;
        }
        Some(r) => {
            uvs[BLX] = r.u2;
            uvs[ULY] = r.v2;
            uvs[URX] = r.u;
            uvs[BRY] = r.v;
            if rotated {
                uvs[BLY] = r.v;
                uvs[ULX] = r.u2;
                uvs[URY] = r.v2;
                uvs[BRX] = r.u;
            } else {
                uvs[BLY] = r.v2;
                uvs[ULX] = r.u;
                uvs[URY] = r.v;
                uvs[BRX] = r.u2;
            }
        }
    }
}

fn compute_mesh_uvs(region: Option<&TextureRegionRef>, region_uvs: &[f32], uvs: &mut [f32]) {
    let n = uvs.len();
    let (u, v, width, height);
    match region {
        Some(r) if r.atlas => {
            let mut u0 = r.u;
            let mut v0 = r.v;
            let texture_width = r.page_width;
            let texture_height = r.page_height;
            match r.degrees {
                90 => {
                    u0 -= (r.original_height - r.offset_y - r.packed_width) / texture_width;
                    v0 -= (r.original_width - r.offset_x - r.packed_height) / texture_height;
                    let w = r.original_height / texture_width;
                    let h = r.original_width / texture_height;
                    for i in (0..n).step_by(2) {
                        uvs[i] = u0 + region_uvs[i + 1] * w;
                        uvs[i + 1] = v0 + (1.0 - region_uvs[i]) * h;
                    }
                    return;
                }
                180 => {
                    u0 -= (r.original_width - r.offset_x - r.packed_width) / texture_width;
                    v0 -= r.offset_y / texture_height;
                    let w = r.original_width / texture_width;
                    let h = r.original_height / texture_height;
                    for i in (0..n).step_by(2) {
                        uvs[i] = u0 + (1.0 - region_uvs[i]) * w;
                        uvs[i + 1] = v0 + (1.0 - region_uvs[i + 1]) * h;
                    }
                    return;
                }
                270 => {
                    u0 -= r.offset_y / texture_width;
                    v0 -= r.offset_x / texture_height;
                    let w = r.original_height / texture_width;
                    let h = r.original_width / texture_height;
                    for i in (0..n).step_by(2) {
                        uvs[i] = u0 + (1.0 - region_uvs[i + 1]) * w;
                        uvs[i + 1] = v0 + region_uvs[i] * h;
                    }
                    return;
                }
                _ => {
                    u0 -= r.offset_x / texture_width;
                    v0 -= (r.original_height - r.offset_y - r.packed_height) / texture_height;
                    u = u0;
                    v = v0;
                    width = r.original_width / texture_width;
                    height = r.original_height / texture_height;
                }
            }
        }
        None => {
            u = 0.0;
            v = 0.0;
            width = 1.0;
            height = 1.0;
        }
        Some(r) => {
            u = r.u;
            v = r.v;
            width = r.u2 - u;
            height = r.v2 - v;
        }
    }
    for i in (0..n).step_by(2) {
        uvs[i] = u + region_uvs[i] * width;
        uvs[i + 1] = v + region_uvs[i + 1] * height;
    }
}

/// A textured, optionally weighted and deformable triangle mesh.
#[derive(Debug, Clone, PartialEq)]
pub struct MeshAttachment {
    pub name: String,
    /// Caller-defined; kept by [`Attachment::copy`] and emitted per vertex
    /// in [`RenderCommand::tags`](crate::render::RenderCommand::tags).
    pub tag: u32,
    /// Atlas path the regions were looked up by.
    pub path: String,
    pub color: Color,
    pub vertex_data: VertexData,
    /// Per-vertex u,v pairs, 0..1 within the region. Frame UVs on the page
    /// are derived from these by [`Self::update_sequence`].
    pub region_uvs: Vec<f32>,
    /// Triangle list indexing vertices.
    pub triangles: Vec<u16>,
    /// Hull vertex count × 2. The hull vertices come first.
    pub hull_length: u32,
    pub sequence: Sequence,
    /// Set for linked meshes; geometry is copied from it at link time.
    pub source_mesh: Option<AttachmentId>,

    /// Nonessential: edge index pairs, for editor display.
    pub edges: Vec<u16>,
    /// Nonessential: size in skeleton units.
    pub width: f32,
    pub height: f32,
}

impl MeshAttachment {
    /// An empty white mesh. Call [`Self::update_sequence`] once its
    /// geometry and regions are set.
    #[must_use]
    pub fn new(name: impl Into<String>, sequence: Sequence) -> Self {
        Self {
            name: name.into(),
            tag: 0,
            path: String::new(),
            color: Color::WHITE,
            vertex_data: VertexData::default(),
            region_uvs: Vec::new(),
            triangles: Vec::new(),
            hull_length: 0,
            sequence,
            source_mesh: None,
            edges: Vec::new(),
            width: 0.0,
            height: 0.0,
        }
    }

    /// Recomputes every frame's UVs from `region_uvs`. A frame with no
    /// region uses `region_uvs` as is.
    pub fn update_sequence(&mut self) {
        let n = self.sequence.regions.len();
        let stride = self.region_uvs.len();
        self.sequence.offsets.clear();
        self.sequence.uvs.clear();
        self.sequence.uvs.resize(n * stride, 0.0);
        for i in 0..n {
            compute_mesh_uvs(
                self.sequence.regions[i].as_ref(),
                &self.region_uvs,
                &mut self.sequence.uvs[i * stride..(i + 1) * stride],
            );
        }
    }

    /// Links to `source`, copying its geometry. Call
    /// [`Self::update_sequence`] afterwards.
    pub fn set_source_mesh(&mut self, id: AttachmentId, source: &MeshAttachment) {
        self.source_mesh = Some(id);
        self.vertex_data.bones.clone_from(&source.vertex_data.bones);
        self.vertex_data
            .vertices
            .clone_from(&source.vertex_data.vertices);
        self.vertex_data.world_vertices_length = source.vertex_data.world_vertices_length;
        self.region_uvs.clone_from(&source.region_uvs);
        self.triangles.clone_from(&source.triangles);
        self.hull_length = source.hull_length;
        self.edges.clone_from(&source.edges);
        self.width = source.width;
        self.height = source.height;
    }
}

/// A polygon for hit testing; see
/// [`SkeletonBounds`](crate::skeleton::SkeletonBounds).
#[derive(Debug, Clone, PartialEq)]
pub struct BoundingBoxAttachment {
    pub name: String,
    /// Caller-defined; kept by [`Attachment::copy`].
    pub tag: u32,
    pub vertex_data: VertexData,
    pub color: Color,
}

impl BoundingBoxAttachment {
    /// An empty attachment with the editor's default color.
    #[must_use]
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            tag: 0,
            vertex_data: VertexData::default(),
            color: Color::new(0.38, 0.94, 0.0, 1.0),
        }
    }
}

/// A cubic Bezier spline that path constraints move bones along. Vertices
/// are control points, three per curve joint.
#[derive(Debug, Clone, PartialEq)]
pub struct PathAttachment {
    pub name: String,
    /// Caller-defined; kept by [`Attachment::copy`].
    pub tag: u32,
    pub vertex_data: VertexData,
    pub color: Color,
    /// The last curve joins back to the first.
    pub closed: bool,
    /// Positions are spaced by arc length computed each frame, rather than
    /// by the precomputed [`Self::lengths`].
    pub constant_speed: bool,
    /// Cumulative length at the end of each curve, in skeleton units.
    pub lengths: Vec<f32>,
}

impl PathAttachment {
    /// An empty attachment with the editor's default color.
    #[must_use]
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            tag: 0,
            vertex_data: VertexData::default(),
            color: Color::new(0.0, 0.0, 0.0, 0.0),
            closed: false,
            constant_speed: false,
            lengths: Vec::new(),
        }
    }
}

/// A single point and direction relative to the slot's bone, for spawning
/// effects or attaching objects.
#[derive(Debug, Clone, PartialEq)]
pub struct PointAttachment {
    pub name: String,
    /// Caller-defined; kept by [`Attachment::copy`].
    pub tag: u32,
    /// Position in bone space.
    pub x: f32,
    pub y: f32,
    /// Degrees, relative to the bone.
    pub rotation: f32,
    pub color: Color,
}

impl PointAttachment {
    /// A point at the bone origin with the editor's default color.
    #[must_use]
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            tag: 0,
            x: 0.0,
            y: 0.0,
            rotation: 0.0,
            color: Color::new(0.9451, 0.9451, 0.0, 1.0),
        }
    }
}

/// A polygon that clips the slots drawn after it, up to and including
/// `end_slot`.
#[derive(Debug, Clone, PartialEq)]
pub struct ClippingAttachment {
    pub name: String,
    /// Caller-defined; kept by [`Attachment::copy`].
    pub tag: u32,
    pub vertex_data: VertexData,
    pub color: Color,
    /// Last slot clipped; `None` clips to the end of the draw order.
    pub end_slot: Option<SlotId>,
    /// Clip against the polygon's convex hull instead of splitting a
    /// concave polygon into convex parts.
    pub convex: bool,
    /// Keep what lies outside the polygon instead of inside.
    pub inverse: bool,
}

impl ClippingAttachment {
    /// An empty attachment with the editor's default color.
    #[must_use]
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            tag: 0,
            vertex_data: VertexData::default(),
            color: Color::new(0.0, 0.0, 0.0, 0.0),
            end_slot: None,
            convex: false,
            inverse: false,
        }
    }
}

/// A resolved texture region. `atlas` regions carry packing data (offsets,
/// original size, rotation); plain regions map straight to `u..u2, v..v2`.
/// Pixel fields are in page pixels.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TextureRegionRef {
    /// Becomes the [`TextureId`](crate::render::TextureId) of commands
    /// drawing this region.
    pub page_index: u32,
    /// Whether the packing fields below are meaningful.
    pub atlas: bool,
    /// UV rect on the page, 0..1.
    pub u: f32,
    pub v: f32,
    pub u2: f32,
    pub v2: f32,
    /// Packed size with width and height swapped for 90° regions, as
    /// spine-cpp's atlas loader leaves them.
    pub packed_width: f32,
    pub packed_height: f32,
    /// See [`AtlasRegion`](crate::atlas::AtlasRegion).
    pub original_width: f32,
    pub original_height: f32,
    pub offset_x: f32,
    pub offset_y: f32,
    /// Packing rotation in degrees. Meshes handle 0, 90, 180 and 270;
    /// regions only 0 and 90.
    pub degrees: i32,
    pub page_width: f32,
    pub page_height: f32,
}

impl TextureRegionRef {
    /// A plain region: `u..u2, v..v2` of page `page_index`, with no packing.
    #[must_use]
    pub fn plain(page_index: u32, u: f32, v: f32, u2: f32, v2: f32) -> Self {
        Self {
            page_index,
            atlas: false,
            u,
            v,
            u2,
            v2,
            packed_width: 0.0,
            packed_height: 0.0,
            original_width: 0.0,
            original_height: 0.0,
            offset_x: 0.0,
            offset_y: 0.0,
            degrees: 0,
            page_width: 0.0,
            page_height: 0.0,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn sequence_ids_are_unique_and_copy_renews() {
        let a = Sequence::new(1, false);
        let b = Sequence::new(1, false);
        assert_ne!(a.id, b.id);
        assert_ne!(a.copy().id, a.id);
    }

    #[test]
    fn sequence_path_suffix() {
        let mut s = Sequence::new(3, true);
        s.start = 1;
        s.digits = 2;
        assert_eq!(s.path("run", 0), "run01");
        assert_eq!(Sequence::new(1, false).path("run", 0), "run");
    }

    #[test]
    fn resolve_index_uses_setup_and_clamps() {
        let mut s = Sequence::new(3, true);
        s.setup_index = 1;
        assert_eq!(s.resolve_index(-1), 1);
        assert_eq!(s.resolve_index(7), 2);
    }

    #[test]
    fn regionless_mesh_uvs_pass_through() {
        let mut m = MeshAttachment::new("m", Sequence::new(1, false));
        m.region_uvs = vec![0.25, 0.5, 1.0, 0.0];
        m.update_sequence();
        assert_eq!(m.sequence.uvs(0), &[0.25, 0.5, 1.0, 0.0]);
    }
}