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
use std::{ffi::CString, sync::Arc};

use crate::{
    bone::Bone,
    c::{
        spBone, spSkeleton, spSkeletonData, spSkeleton_create, spSkeleton_dispose,
        spSkeleton_getAttachmentForSlotIndex, spSkeleton_getAttachmentForSlotName,
        spSkeleton_setAttachment, spSkeleton_setBonesToSetupPose, spSkeleton_setSkin,
        spSkeleton_setSkinByName, spSkeleton_setSlotsToSetupPose, spSkeleton_setToSetupPose,
        spSkeleton_updateCache, spSkeleton_updateWorldTransform,
        spSkeleton_updateWorldTransformWith, spSkin, spSlot,
    },
    c_interface::{CTmpMut, CTmpRef, NewFromPtr, SyncPtr},
    error::SpineError,
    skeleton_data::SkeletonData,
    skin::Skin,
    slot::Slot,
    Attachment,
};

#[allow(unused_imports)]
use crate::{SkeletonBinary, SkeletonJson};

#[cfg(feature = "mint")]
use mint::Vector2;

/// A live Skeleton instance created from [`SkeletonData`].
///
/// [Spine API Reference](http://esotericsoftware.com/spine-api-reference#Skeleton)
#[derive(Debug)]
pub struct Skeleton {
    c_skeleton: SyncPtr<spSkeleton>,
    owns_memory: bool,
    _skeleton_data: Arc<SkeletonData>,
    _skin: Option<Skin>, // keep-alive for user created skins
}

impl Skeleton {
    /// Create a new instance of the skeleton loaded in [`SkeletonData`].
    ///
    /// See [`SkeletonJson`] or [`SkeletonBinary`] for a complete example of loading a skeleton.
    pub fn new(skeleton_data: Arc<SkeletonData>) -> Self {
        let c_skeleton = unsafe { spSkeleton_create(skeleton_data.c_ptr()) };
        Self {
            c_skeleton: SyncPtr(c_skeleton),
            owns_memory: true,
            _skeleton_data: skeleton_data,
            _skin: None, // keep alive user-created skins
        }
    }

    pub fn update_cache(&mut self) {
        unsafe {
            spSkeleton_updateCache(self.c_ptr());
        }
    }

    pub fn update_world_transform(&mut self) {
        unsafe {
            spSkeleton_updateWorldTransform(self.c_ptr());
        }
    }

    pub unsafe fn update_world_transform_with(&mut self, parent: &Bone) {
        spSkeleton_updateWorldTransformWith(self.c_ptr(), parent.c_ptr());
    }

    pub fn set_to_setup_pose(&mut self) {
        unsafe {
            spSkeleton_setToSetupPose(self.c_ptr());
        }
    }

    pub fn set_bones_to_setup_pose(&mut self) {
        unsafe {
            spSkeleton_setBonesToSetupPose(self.c_ptr());
        }
    }

    pub fn set_slots_to_setup_pose(&mut self) {
        unsafe {
            spSkeleton_setSlotsToSetupPose(self.c_ptr());
        }
    }

    /// Set the skeleton's skin. If the skin is a user-created one (via [`Skin::new`]), then a
    /// clone is created and used instead, to help ensure memory safety. If this behavior is not
    /// desired then [`Skeleton::set_skin_unchecked`] can be used instead.
    pub fn set_skin(&mut self, skin: &Skin) {
        if skin.owns_memory {
            let cloned_skin = skin.clone();
            unsafe { spSkeleton_setSkin(self.c_ptr(), cloned_skin.c_ptr()) };
            self._skin = Some(cloned_skin);
        } else {
            unsafe { spSkeleton_setSkin(self.c_ptr(), skin.c_ptr()) };
            self._skin = None;
        }
        self.set_to_setup_pose();
    }

    /// Set the skeleton's skin.
    ///
    /// # Safety
    ///
    /// The [`Skin`] struct will destroy the underlying C representation of the skin in its [`Drop`]
    /// implementation. Skins assigned to a skeleton must live as long as the skeletons using them
    /// or else the skeleton may cause a segfault.
    pub unsafe fn set_skin_unchecked(&mut self, skin: &Skin) {
        spSkeleton_setSkin(self.c_ptr(), skin.c_ptr());
    }

    /// Set the skeleton's skin by name.
    ///
    /// # Safety
    ///
    /// This function should only be called with valid skin names. It is faster than the safe
    /// alternative, [`Skeleton::set_skin_by_name`], but will likely segfault if the skin does not
    /// exist.
    pub unsafe fn set_skin_by_name_unchecked(&mut self, skin_name: &str) {
        let c_skin_name = CString::new(skin_name).unwrap();
        spSkeleton_setSkinByName(self.c_ptr(), c_skin_name.as_ptr());
        self._skin = None;
    }

    /// Set the skeleton's skin by name.
    pub fn set_skin_by_name(&mut self, skin_name: &str) -> Result<(), SpineError> {
        if self.data().skins().any(|skin| skin.name() == skin_name) {
            unsafe { self.set_skin_by_name_unchecked(skin_name) };
            Ok(())
        } else {
            Err(SpineError::new_not_found("Skin", skin_name))
        }
    }

    pub fn bone_root(&self) -> CTmpRef<Skeleton, Bone> {
        CTmpRef::new(self, unsafe { Bone::new_from_ptr(self.c_ptr_mut().root) })
    }

    pub fn bone_root_mut(&mut self) -> CTmpMut<Skeleton, Bone> {
        CTmpMut::new(self, unsafe { Bone::new_from_ptr(self.c_ptr_mut().root) })
    }

    pub fn find_bone(&self, name: &str) -> Option<CTmpRef<Skeleton, Bone>> {
        self.bones().find(|bone| bone.data().name() == name)
    }

    pub fn find_bone_mut(&mut self, name: &str) -> Option<CTmpMut<Skeleton, Bone>> {
        self.bones_mut().find(|bone| bone.data().name() == name)
    }

    pub fn find_slot(&self, name: &str) -> Option<CTmpRef<Skeleton, Slot>> {
        self.slots().find(|slot| slot.data().name() == name)
    }

    pub fn find_slot_mut(&mut self, name: &str) -> Option<CTmpMut<Skeleton, Slot>> {
        self.slots_mut().find(|slot| slot.data().name() == name)
    }

    pub fn set_attachment(&mut self, slot_name: &str, attachment_name: Option<&str>) -> bool {
        let c_slot_name = CString::new(slot_name).unwrap();
        if let Some(attachment_name) = attachment_name {
            let c_attachment_name = CString::new(attachment_name).unwrap();
            unsafe {
                spSkeleton_setAttachment(
                    self.c_ptr(),
                    c_slot_name.as_ptr(),
                    c_attachment_name.as_ptr(),
                ) != 0
            }
        } else {
            unsafe {
                spSkeleton_setAttachment(self.c_ptr(), c_slot_name.as_ptr(), std::ptr::null()) != 0
            }
        }
    }

    pub fn get_attachment_for_slot_name(
        &mut self,
        slot_name: &str,
        attachment_name: &str,
    ) -> Option<Attachment> {
        let c_slot_name = CString::new(slot_name).unwrap();
        let c_attachment_name = CString::new(attachment_name).unwrap();
        unsafe {
            let c_attachment = spSkeleton_getAttachmentForSlotName(
                self.c_ptr(),
                c_slot_name.as_ptr(),
                c_attachment_name.as_ptr(),
            );
            if !c_attachment.is_null() {
                Some(Attachment::new_from_ptr(c_attachment))
            } else {
                None
            }
        }
    }

    pub fn get_attachment_for_slot_index(
        &mut self,
        slot_index: i32,
        attachment_name: &str,
    ) -> Option<Attachment> {
        let c_attachment_name = CString::new(attachment_name).unwrap();
        unsafe {
            let c_attachment = spSkeleton_getAttachmentForSlotIndex(
                self.c_ptr(),
                slot_index,
                c_attachment_name.as_ptr(),
            );
            if !c_attachment.is_null() {
                Some(Attachment::new_from_ptr(c_attachment))
            } else {
                None
            }
        }
    }

    // TODO: iterators for ik, transform, path constraints

    c_accessor_tmp_ptr!(data, data_mut, data, SkeletonData, spSkeletonData);
    c_accessor_color_mut!(color, color_mut, color);
    c_accessor!(bones_count, bonesCount, i32);
    c_accessor!(slots_count, slotsCount, i32);
    c_accessor!(ik_contraints_count, ikConstraintsCount, i32);
    c_accessor!(transform_contraints_count, transformConstraintsCount, i32);
    c_accessor!(path_contraints_count, pathConstraintsCount, i32);
    c_accessor_mut!(scale_x, set_scale_x, scaleX, f32);
    c_accessor_mut!(scale_y, set_scale_y, scaleY, f32);
    c_accessor_mut!(x, set_x, x, f32);
    c_accessor_mut!(y, set_y, y, f32);
    c_accessor_array!(
        bones,
        bones_mut,
        bone_at_index,
        bone_at_index_mut,
        Skeleton,
        Bone,
        spBone,
        bones,
        bones_count
    );
    c_accessor_array!(
        slots,
        slots_mut,
        slot_at_index,
        slot_at_index_mut,
        Skeleton,
        Slot,
        spSlot,
        slots,
        slots_count
    );
    c_accessor_array!(
        draw_order,
        draw_order_mut,
        draw_order_at_index,
        draw_order_at_index_mut,
        Skeleton,
        Slot,
        spSlot,
        drawOrder,
        slots_count
    );
    c_accessor_tmp_ptr_optional!(skin, skin_mut, skin, Skin, spSkin);
    c_ptr!(c_skeleton, spSkeleton);
}

/// Functions available if using the `mint` feature.
#[cfg(feature = "mint")]
impl Skeleton {
    pub fn position(&self) -> Vector2<f32> {
        Vector2 {
            x: self.x(),
            y: self.y(),
        }
    }

    pub fn set_position(&mut self, position: impl Into<Vector2<f32>>) {
        let position: Vector2<f32> = position.into();
        self.set_x(position.x);
        self.set_y(position.y);
    }

    pub fn scale(&self) -> Vector2<f32> {
        Vector2 {
            x: self.scale_x(),
            y: self.scale_y(),
        }
    }

    pub fn set_scale(&mut self, scale: impl Into<Vector2<f32>>) {
        let scale: Vector2<f32> = scale.into();
        self.set_scale_x(scale.x);
        self.set_scale_y(scale.y);
    }
}

impl Drop for Skeleton {
    fn drop(&mut self) {
        if self.owns_memory {
            unsafe {
                spSkeleton_dispose(self.c_skeleton.0);
            }
        }
    }
}