spinal 0.0.1

A 2D animation engine for Spine.
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
mod animation;
mod bone;
mod skin;

use crate::binary::bone::bones;
use crate::color::Color;
use crate::skeleton::{
    AttachmentData, AttachmentType, Blend, Bone, ClippingAttachment, Event, Ik, Info,
    ParentTransform, Path, PathPositionMode, PathRotateMode, PathSpacingMode, RegionAttachment,
    Skin, Slot, Transform, Vertices,
};
use crate::{Skeleton, SpinalError};
use bevy_math::Vec2;
use bevy_utils::tracing::warn;
use nom::bytes::complete::take;
use nom::combinator::{eof, map_res};
use nom::multi::{count, length_count};
use nom::number::complete::{be_f32, be_i8, be_u32, be_u64, be_u8};
use nom::sequence::{pair, tuple};
use nom::IResult;
use tracing::{debug, instrument, trace};

/// Reads a binary skeleton file and returns a [Skeleton].
// If the code path doesn't need any information from [Parser] just use static functions.
pub struct BinaryParser {
    parse_non_essential: bool,
    skeleton: Skeleton,
}

impl BinaryParser {
    #[instrument(skip(b))]
    pub fn parse(b: &[u8]) -> Result<Skeleton, SpinalError> {
        debug!(len = ?b.len(), "Parsing binary skeleton.");
        let mut parser = BinaryParser {
            parse_non_essential: false,
            skeleton: Skeleton::default(),
        };
        let (_, skeleton) = parser.parser(b).unwrap(); // TODO: error
        Ok(skeleton)
    }

    #[instrument(skip(self, b))]
    fn parser(mut self, b: &[u8]) -> IResult<&[u8], Skeleton> {
        let (b, (parse_non_essential, info)) = Self::info(b)?;
        self.skeleton.info = info;
        self.parse_non_essential = parse_non_essential;
        trace!(?parse_non_essential);

        let (b, strings) = length_count(varint, str)(b)?;
        self.skeleton.strings = strings;

        let (b, bones) = bones(b)?;
        self.skeleton.bones = bones;
        self.skeleton.bones_tree = self.skeleton.build_bones_tree();

        let (b, slots) = length_count(varint, self.slot())(b)?;
        self.skeleton.slots = slots;

        let (b, ik) = length_count(varint, ik)(b)?;
        self.skeleton.ik = ik;

        let (b, transforms) = length_count(varint, transform)(b)?;
        self.skeleton.transforms = transforms;

        let (b, paths) = length_count(varint, path)(b)?;
        self.skeleton.paths = paths;

        let (b, skins) = self.skins(b)?;
        self.skeleton.skins = skins;

        let (b, events) = length_count(varint, self.event())(b)?;
        self.skeleton.events = events;

        // let (b, animations) = length_count(varint, self.animation())(b)?;

        // eof(b)?;

        Ok((b, self.skeleton))
    }

    fn info(b: &[u8]) -> IResult<&[u8], (bool, Info)> {
        let (b, (hash, version, bottom_left, size, parse_non_essential)) =
            tuple((be_u64, str, vec2, vec2, boolean))(b)?;

        let mut info = Info {
            hash: format!("{:x}", hash),
            version,
            bottom_left,
            size,
            fps: None,
            images: None,
            audio: None,
        };
        let b = if parse_non_essential {
            let (b, (fps, images, audio)) = tuple((float, str, str))(b)?;
            info.fps = Some(fps);
            info.images = Some(images.into());
            info.audio = Some(audio.into());
            b
        } else {
            b
        };

        Ok((b, (parse_non_essential, info)))
    }

    fn slot(&self) -> impl FnMut(&[u8]) -> IResult<&[u8], Slot> + '_ {
        move |b: &[u8]| {
            let (b, name) = str(b)?;
            let (b, bone) = varint_usize(b)?;
            let (b, color) = col(b)?;
            let (b, dark) = col_opt(b)?;
            let (b, attachment) = self.str_table_opt()(b)?;
            let attachment = attachment.map(|s| s.to_string());

            let (b, blend) = varint(b)?;
            let blend = blend.try_into().unwrap(); // TODO: error
            let blend = Blend::from_repr(blend).unwrap(); // TODO: error

            let slot = Slot {
                name,
                bone,
                color,
                dark,
                attachment,
                blend,
            };
            trace!(?slot);
            Ok((b, slot))
        }
    }

    fn event(&self) -> impl FnMut(&[u8]) -> IResult<&[u8], Event> + '_ {
        |b: &[u8]| {
            let (b, name) = self.str_table()(b)?;
            let (b, int_val) = varint_signed(b)?;
            let (b, float_val) = float(b)?;
            let (b, str_val) = str_opt(b)?;
            let (b, audio_path) = str_opt(b)?;
            let (b, audio_volume) = float(b)?;
            let (b, audio_balance) = float(b)?;
            let event = Event {
                name: name.to_string(),
                int: int_val,
                float: float_val,
                string: str_val.map(|s| s.to_string()),
                audio_path,
                audio_volume,
                audio_balance,
            };
            trace!(?event);
            Ok((b, event))
        }
    }

    fn str_lookup_internal(&self, idx: usize) -> Result<Option<&str>, SpinalError> {
        Ok(match idx {
            0 => None,
            _ => Some(
                &self
                    .skeleton
                    .strings
                    .get(idx - 1)
                    .map(|s| s.as_str())
                    .ok_or_else(|| SpinalError::InvalidStringIndex(idx))?,
            ),
        })
    }

    fn str_table_opt<'a>(&'a self) -> impl FnMut(&[u8]) -> IResult<&[u8], Option<&'a str>> {
        |b: &[u8]| {
            let (b, idx) = varint_usize(b)?;
            let s = self.str_lookup_internal(idx).unwrap(); // TODO: error
            Ok((b, s))
        }
    }

    fn str_table<'a>(&'a self) -> impl FnMut(&[u8]) -> IResult<&[u8], &'a str> {
        |b: &[u8]| {
            let (b, opt_str) = self.str_table_opt()(b)?;
            let s = opt_str.unwrap(); // TODO: error handling
            Ok((b, s))
        }
    }
}

fn ik(b: &[u8]) -> IResult<&[u8], Ik> {
    let (b, (name, order, skin)) = tuple((str, varint, boolean))(b)?;
    let (b, bones) = length_count(varint, varint)(b)?;
    assert!(bones.len() == 1 || bones.len() == 2); // TODO: error
    let bones = bones.into_iter().map(|v| v as usize).collect();
    let (b, (target, mix, softness, bend_direction, compress, stretch, uniform)) =
        tuple((varint, float, float, be_i8, boolean, boolean, boolean))(b)?;
    let target = target as usize;
    let bend_positive = match bend_direction {
        -1 => false,
        1 => true,
        _ => panic!("Invalid bend direction"), // TODO: error
    };

    let ik = Ik {
        name,
        order,
        skin,
        bones,
        target,
        mix,
        softness,
        bend_positive,
        compress,
        stretch,
        uniform,
    };
    Ok((b, ik))
}

fn transform(b: &[u8]) -> IResult<&[u8], Transform> {
    let (b, (name, order_index, skin_required, bones, target)) = tuple((
        str,
        varint,
        boolean,
        length_count(varint, varint_usize),
        varint_usize,
    ))(b)?;
    let (b, (local, relative, offset_rotation, offset_distance, offset_scale, offset_shear_y)) =
        tuple((boolean, boolean, float, vec2, vec2, float))(b)?;
    let (b, (rotate_mix, translate_mix, scale_mix, shear_mix_y)) =
        tuple((float, vec2, vec2, float))(b)?;
    let transform = Transform {
        name,
        order_index,
        skin_required,
        bones,
        target,
        local,
        relative,
        offset_rotation,
        offset_distance,
        offset_scale,
        offset_shear_y,
        rotate_mix,
        translate_mix,
        scale_mix,
        shear_mix_y,
    };
    Ok((b, transform))
}

fn path(b: &[u8]) -> IResult<&[u8], Path> {
    let (b, (name, order_index, skin_required, bones, target_slot)) = tuple((
        str,
        varint,
        boolean,
        length_count(varint, varint_usize),
        varint_usize,
    ))(b)?;
    let (b, (position_mode, spacing_mode, rotate_mode)) =
        tuple((varint_usize, varint_usize, varint_usize))(b)?;
    let position_mode = PathPositionMode::from_repr(position_mode).unwrap(); // TODO: error
    let spacing_mode = PathSpacingMode::from_repr(spacing_mode).unwrap(); // TODO: error
    let rotate_mode = PathRotateMode::from_repr(rotate_mode).unwrap(); // TODO: error
    let (b, (offset_rotation, position, spacing, rotate_mix, translate_mix)) =
        tuple((float, float, float, float, float))(b)?;

    let path = Path {
        name,
        order_index,
        skin_required,
        bones,
        target_slot,
        position_mode,
        spacing_mode,
        rotate_mode,
        offset_rotation,
        position,
        spacing,
        rotate_mix,
        translate_mix,
    };
    Ok((b, path))
}

// TODO: I can't find docs on how this works so ignoring this chunk for now.
#[instrument(skip(b))]
fn seq(b: &[u8]) -> IResult<&[u8], ()> {
    let (b, is_sequence) = boolean(b)?;
    if !is_sequence {
        return Ok((b, ()));
    }

    warn!("Ignoring sequence in attachment.");
    let (b, _) = tuple((varint, varint, varint))(b)?;
    Ok((b, ()))
}

fn col(b: &[u8]) -> IResult<&[u8], Color> {
    let (b, v) = be_u32(b)?;
    Ok((b, Color(v)))
}

// TODO: How can white be a representation of no color? It was mentioned in the docs somewhere.
fn col_opt(b: &[u8]) -> IResult<&[u8], Option<Color>> {
    let (b, v) = be_u32(b)?;
    Ok((b, if v == u32::MAX { None } else { Some(Color(v)) }))
}

fn vec2(b: &[u8]) -> IResult<&[u8], Vec2> {
    let (b, (x, y)) = tuple((float, float))(b)?;
    Ok((b, Vec2::new(x, y)))
}

/// A string is a varint+ length followed by zero or more UTF-8 characters.
///
/// If the length is 0, the string is null (which can be considered the same as empty for most
/// purposes). If the length is 1, the string is empty.
///
/// Otherwise, the length is followed by length - 1 bytes.
fn str_opt(bytes: &[u8]) -> IResult<&[u8], Option<String>> {
    let (bytes, strlen) = varint(bytes)?;
    match strlen {
        0 => Ok((bytes, None)),
        1 => Ok((bytes, Some(String::new()))),
        _ => {
            let (bytes, taken) = take(strlen - 1)(bytes)?;
            // TODO: std::str::from_utf8 ?
            let s: String = String::from_utf8(taken.to_vec()).unwrap(); // TODO: nom error
            Ok((bytes, Some(s)))
        }
    }
}

fn str(b: &[u8]) -> IResult<&[u8], String> {
    let (b, s) = str_opt(b)?;
    match s {
        Some(s) => Ok((b, s)),
        None => todo!(),
    }
}

fn boolean(b: &[u8]) -> IResult<&[u8], bool> {
    let (b, byte) = be_u8(b)?;
    match byte {
        0 => Ok((b, false)),
        1 => Ok((b, true)),
        _ => panic!(),
    }
}

fn float(b: &[u8]) -> IResult<&[u8], f32> {
    be_f32(b)
}

/// A varint is an int but it is stored as 1 to 5 bytes, depending on the value.
///
/// There are two kinds of varints, varint+ is optimized to take up less space for small positive
/// values and varint- for small negative (and positive) values.
///
/// For each byte in the varint, the MSB is set if there are additional bytes. If the result is
/// optimized for small negative values, it is shifted.
fn varint(b: &[u8]) -> IResult<&[u8], u32> {
    let mut offset = 0;
    let mut value: u32 = 0;
    loop {
        let b = b
            .get(offset)
            .ok_or(nom::Err::Incomplete(nom::Needed::new(1)))?;
        value |= ((b & 0x7F) as u32) << (offset as u32 * 7);
        offset += 1;
        if b & 0x80 == 0 || offset == 5 {
            break;
        }
    }
    return Ok((&b[offset..], value));
}

fn varint_usize(b: &[u8]) -> IResult<&[u8], usize> {
    let (b, v) = varint(b)?;
    Ok((b, v as usize))
}

/// If the lowest bit is set, the value is negative.
fn varint_signed(b: &[u8]) -> IResult<&[u8], i32> {
    let (b, value) = varint(b)?;
    let negative = value & 1 == 1;
    let shifted = (value >> 1) as i32;
    let value = if negative { -(shifted + 1) } else { shifted };
    Ok((b, value))
}

#[cfg(test)]
mod tests {
    use super::*;
    // use tracing_test::traced_test;
    use test_log::test;

    #[test]
    // #[traced_test]
    fn parser() {
        let b = include_bytes!("../../assets/spineboy-pro-4.1/spineboy-pro.skel");
        // let b = include_bytes!("../../assets/test/skeleton.skel");
        let skeleton = BinaryParser::parse(b).unwrap();
        dbg!(&skeleton);
        assert_eq!(skeleton.info.version, "4.1.06".to_string());
        assert_eq!(skeleton.bones.len(), 67);
        assert_eq!(skeleton.slots.len(), 52);
        assert_eq!(skeleton.ik.len(), 7);
    }

    #[test]
    fn varint_pos() {
        assert_eq!(varint(&[0b00000000]).unwrap().0.len(), 0);
        assert_eq!(varint(&[0b00000000]).unwrap().1, 0);
        assert_eq!(varint(&[0b00000001]).unwrap().1, 1);
        assert_eq!(varint(&[0b01111111]).unwrap().1, 127);
        assert_eq!(varint(&[0b11111111, 0b00000000]).unwrap().1, 127);
        assert_eq!(varint(&[0b11111111, 0b00000001]).unwrap().1, 255);
        let v = varint(&[0b11111111, 0b01111111]).unwrap();
        assert_eq!(v.1, 0x3FFF);
        let v = varint(&[0b11111111, 0b11111111, 0b11111111, 0b01111111]).unwrap();
        assert_eq!(v.1, 0xFFF_FFFF);

        // Leave an extra byte at the end to see if we have a remainder.
        let v = varint(&[0b11111111, 0b11111111, 0b11111111, 0b01111111, 0x42]).unwrap();
        assert_eq!(v.0, &[0x42]);
        assert_eq!(v.1, 0xFFF_FFFF);

        // 5 bytes!
        let v = varint(&[0b11111111, 0b11111111, 0b11111111, 0b11111111, 0b00000001]).unwrap();
        assert_eq!(v.1, 0x1FFF_FFFF);
        let v = varint(&[0b11111111, 0b11111111, 0b11111111, 0b11111111, 0b00000011]).unwrap();
        assert_eq!(v.0.len(), 0);
        assert_eq!(v.1, 0x3FFF_FFFF);
        let v = varint(&[0b11111111, 0b11111111, 0b11111111, 0b11111111, 0b01111111]).unwrap();
        assert_eq!(v.0.len(), 0);
        assert_eq!(v.1, 0xFFFF_FFFF);

        // 5 bytes with overflow.
        let v = varint(&[
            0b11111111, 0b11111111, 0b11111111, 0b11111111, 0b01111111, 0x42,
        ])
        .unwrap();
        assert_eq!(v.0.len(), 1);
        assert_eq!(v.1, 0xFFFF_FFFF);
    }

    #[test]
    fn varint_neg() {
        assert_eq!(varint_signed(&[0b00000000]).unwrap().1, 0);
        assert_eq!(varint_signed(&[0b00000001]).unwrap().1, -1);
        assert_eq!(varint_signed(&[0b00000010]).unwrap().1, 1);
        assert_eq!(varint_signed(&[0b00000011]).unwrap().1, -2);
        assert_eq!(varint_signed(&[0b01111110]).unwrap().1, 63);
        assert_eq!(varint_signed(&[0b01111111]).unwrap().1, -64);
        let v = varint_signed(&[0b11111111, 0b11111111, 0b11111111, 0b01111111]).unwrap();
        assert_eq!(v.1, -0x800_0000);
        let v = varint_signed(&[0b11111110, 0b11111111, 0b11111111, 0b01111111]).unwrap();
        assert_eq!(v.1, 0x7FF_FFFF);
        let v =
            varint_signed(&[0b11111110, 0b11111111, 0b11111111, 0b11111111, 0b11111111]).unwrap();
        assert_eq!(v.1, 0x7FFF_FFFF);
    }
}