agb 0.23.1

Library for Game Boy Advance Development
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
use core::alloc::Layout;

use crate::display::palette16::Palette16;

use super::{BYTES_PER_TILE_4BPP, BYTES_PER_TILE_8BPP};

/// Sprite data. Refers to the palette, pixel data, and the size of the sprite.
pub struct Sprite {
    pub(crate) palette: Palette,
    pub(crate) data: &'static [u8],
    pub(crate) size: Size,
}

#[derive(Clone, Copy)]
pub enum Palette {
    Single(&'static Palette16),
    Multi(&'static PaletteMulti),
}

impl Palette {
    pub(crate) fn is_multi(self) -> bool {
        matches!(self, Palette::Multi(_))
    }
}

/// A palette for 256 colour mode.
pub struct PaletteMulti {
    first_index: u32,
    palettes: &'static [Palette16],
}

impl PaletteMulti {
    #[must_use]
    /// Create a new palette. The first index is the index where the palette starts.
    pub const fn new(palettes: &'static [Palette16]) -> Self {
        assert!(palettes.len() <= 16);
        assert!(!palettes.is_empty());

        Self {
            first_index: (16 - palettes.len()) as u32,
            palettes,
        }
    }
    #[must_use]
    /// Gets the palettes, usually for coping to palette vram.
    pub const fn palettes(&self) -> &'static [Palette16] {
        self.palettes
    }

    #[must_use]
    /// Gets the first index of the palette. When copied to palette vram it is
    /// expected to be copied starting from this index.
    pub const fn first_index(&self) -> u32 {
        self.first_index
    }

    #[must_use]
    /// Gets the first colour from this palette
    pub const fn first_colour_index(&self) -> u8 {
        (self.first_index * 16) as u8
    }
}

impl Sprite {
    #[doc(hidden)]
    /// Creates a sprite from it's constituent data, used internally by
    /// [include_aseprite] and should generally not be used outside it.
    ///
    /// # Safety
    /// The data should be aligned to a 2 byte boundary
    #[must_use]
    pub const unsafe fn new(palette: &'static Palette16, data: &'static [u8], size: Size) -> Self {
        Self {
            palette: Palette::Single(palette),
            data,
            size,
        }
    }

    #[doc(hidden)]
    /// Creates a sprite that uses multiple palettes, this will use 256 colour
    /// mode, but can use fewer palettes. The palette location in palette vram
    /// is currently fixed by `first_index`.
    ///
    /// # Safety
    /// The data should be aligned to a 2 byte boundary
    #[must_use]
    pub const unsafe fn new_multi(
        palettes: &'static PaletteMulti,
        data: &'static [u8],
        size: Size,
    ) -> Self {
        Self {
            palette: Palette::Multi(palettes),
            data,
            size,
        }
    }

    #[must_use]
    /// Gives the size of the sprite
    pub fn size(&self) -> Size {
        self.size
    }
}

/// The sizes of sprite supported by the GBA.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
#[allow(missing_docs)]
pub enum Size {
    // stored as attr0 attr1
    S8x8 = 0b00_00,
    S16x16 = 0b00_01,
    S32x32 = 0b00_10,
    S64x64 = 0b00_11,

    S16x8 = 0b01_00,
    S32x8 = 0b01_01,
    S32x16 = 0b01_10,
    S64x32 = 0b01_11,

    S8x16 = 0b10_00,
    S8x32 = 0b10_01,
    S16x32 = 0b10_10,
    S32x64 = 0b10_11,
}

#[doc(hidden)]
#[macro_export]
macro_rules! align_bytes {
    ($align_ty:ty, $data:literal) => {{
        #[repr(C)] // guarantee 'bytes' comes after '_align'
        struct AlignedAs<Align, Bytes: ?Sized> {
            pub _align: [Align; 0],
            pub bytes: Bytes,
        }

        const ALIGNED: &AlignedAs<$align_ty, [u8]> = &AlignedAs {
            _align: [],
            bytes: *$data,
        };

        &ALIGNED.bytes
    }};
}

/// Includes sprites found in the referenced aseprite files.
///
/// Can include multiple at once and optimises palettes of all included in the
/// single call together. See [Size] for supported sizes.
///
/// This generates a module given by the first argument, you can control the
/// visibility of the module using the normal means. The generated module
/// exports each Tag in the aseprite file as a static, the static will be all
/// caps and have spaces and dashes converted to underscores.
///
/// ```rust,no_run
/// # #![no_std]
/// # #![no_main]
/// use agb::include_aseprite;
/// include_aseprite!(
///     mod sprites,
///     "examples/gfx/chicken.aseprite"
/// );
///
/// use sprites::{JUMP, WALK, IDLE};
/// ```
/// The tags from the aseprite file are included so you can refer to sprites by
/// name in code. You should ensure tags are unique as this is not enforced by
/// aseprite.
///
/// Including from the out directory is supported through the `$OUT_DIR` token.
///
/// ```rust,ignore
/// # #![no_std]
/// # #![no_main]
/// use agb::include_aseprite;
/// include_aseprite!(
///     mod sprites,
///     "$OUT_DIR/generated_sprite.aseprite"
/// );
/// ```
///
/// You may pass multiple aseprite files in. This is particularly useful if you
/// have multiple sprites with different sizes since aseprite files require
/// that every frame has the same size.
///
/// ```rust,no_run
/// # #![no_std]
/// # #![no_main]
/// use agb::include_aseprite;
/// include_aseprite!(
///     mod sprites,
///     "examples/gfx/crab.aseprite",
///     "examples/gfx/crab-small.aseprite"
/// );
/// ```
///
/// You can optionally specify a target sprite size before a file path to split
/// each frame into multiple smaller sprites. The size is given as `WIDTHxHEIGHT`
/// and must be a valid GBA sprite size. The frame dimensions must be evenly
/// divisible by the target size.
///
/// Sub-frames are generated in row-major order (left-to-right, top-to-bottom),
/// and tags are automatically adjusted to cover all sub-frames. Note that
/// [`Tag::animation_sprite`] and [`Tag::animation_frame`] will iterate over
/// individual sub-frames, not complete original frames. You will likely want
/// to use [`Tag::sprite`] directly to display all sub-frames for a given
/// original frame yourself.
///
/// ```rust,ignore
/// # #![no_std]
/// # #![no_main]
/// use agb::include_aseprite;
/// include_aseprite!(
///     mod sprites,
///     32x16 "examples/gfx/big_character.aseprite",
///     "examples/gfx/small_item.aseprite"
/// );
/// ```
#[macro_export]
macro_rules! include_aseprite {
    ($v: vis mod $module: ident, $($aseprite_args: tt)*) => {
        $v mod $module {
            #[allow(unused_imports)]
            use $crate::display::object::{Size, Sprite, Tag};
            use $crate::display::{Palette16, Rgb15};
            use $crate::align_bytes;

            $crate::include_aseprite_inner!($($aseprite_args)*);
        }
    };
}

/// Includes sprites found in the referenced aseprite files.
///
/// This will optimise to a single multi palette, 256 colour sprites.
///
/// ```rust,no_run
/// # #![no_std]
/// # #![no_main]
/// use agb::include_aseprite_256;
/// include_aseprite_256!(
///     mod sprites,
///     "examples/gfx/chicken.aseprite"
/// );
///
/// use sprites::{JUMP, WALK, IDLE};
/// ```
///
/// Like [`include_aseprite!`], you can specify a target sprite size before a
/// file path to split frames into smaller sprites. See [`include_aseprite!`]
/// for details.
#[macro_export]
macro_rules! include_aseprite_256 {
    ($v: vis mod $module: ident, $($aseprite_args: tt)*) => {
        $v mod $module {
            #[allow(unused_imports)]
            use $crate::display::object::{Size, Sprite, Tag, PaletteMulti};
            use $crate::display::{Palette16, Rgb15};
            use $crate::align_bytes;

            $crate::include_aseprite_256_inner!($($aseprite_args)*);
        }
    }
}

pub use include_aseprite;

#[derive(Clone, Copy)]
enum Direction {
    Forward,
    Backward,
    PingPong,
}

impl Direction {
    const fn from_usize(a: usize) -> Self {
        match a {
            0 => Direction::Forward,
            1 => Direction::Backward,
            2 => Direction::PingPong,
            _ => panic!("Invalid direction, this is a bug in image converter or agb"),
        }
    }
}

/// A sequence of sprites from aseprite.
pub struct Tag {
    sprites: &'static [Sprite],
    direction: Direction,
}

unsafe impl Sync for Tag {}

impl Tag {
    /// The individual sprites that make up the animation themselves.
    #[must_use]
    pub fn sprites(&self) -> &'static [Sprite] {
        self.sprites
    }

    /// A single sprite referred to by index in the animation sequence.
    #[must_use]
    pub const fn sprite(&self, idx: usize) -> &'static Sprite {
        &self.sprites[idx]
    }

    /// A sprite that follows the animation sequence. For instance, in aseprite
    /// tags can be specified to animate:
    /// * Forward
    /// * Backward
    /// * Ping pong
    ///
    /// This takes the animation type in account and returns the correct sprite
    /// following these requirements.
    #[inline]
    #[must_use]
    pub fn animation_sprite(&self, idx: usize) -> &'static Sprite {
        let len_sub_1 = self.sprites.len() - 1;
        match self.direction {
            Direction::Forward => self.sprite(idx % self.sprites.len()),
            Direction::Backward => self.sprite(len_sub_1 - (idx % self.sprites.len())),
            Direction::PingPong => self.sprite(
                (((idx + len_sub_1) % (len_sub_1 * 2)) as isize - len_sub_1 as isize)
                    .unsigned_abs(),
            ),
        }
    }

    /// Takes an index shifts by the divider, if the index is out of bounds of
    /// the Tag then it will be reset to zero. This is incredibly useful for
    /// animating sprites efficiently.
    pub fn animation_frame(&self, idx: &mut usize, divider: u32) -> &'static Sprite {
        let divided = *idx >> divider;
        let idx = match self.direction {
            Direction::Forward => {
                if divided >= self.sprites.len() {
                    *idx = 0;
                    0
                } else {
                    divided
                }
            }
            Direction::Backward => {
                if divided >= self.sprites.len() {
                    *idx = 0;
                    self.sprites.len() - 1
                } else {
                    self.sprites.len() - 1 - divided
                }
            }
            Direction::PingPong => {
                if divided >= (self.sprites.len() - 1) * 2 {
                    *idx = 0;
                    0
                } else if divided >= self.sprites.len() {
                    (self.sprites.len() - 1) * 2 - divided
                } else {
                    divided
                }
            }
        };

        &self.sprites[idx]
    }

    #[doc(hidden)]
    /// Creates a new sprite from it's constituent parts. Used internally by
    /// [include_aseprite] and should generally not be used elsewhere.
    #[must_use]
    pub const fn new(sprites: &'static [Sprite], direction: usize) -> Self {
        Self {
            sprites,
            direction: Direction::from_usize(direction),
        }
    }
}

impl Size {
    pub(crate) const fn number_of_tiles(self) -> usize {
        match self {
            Size::S8x8 => 1,
            Size::S16x16 => 4,
            Size::S32x32 => 16,
            Size::S64x64 => 64,
            Size::S16x8 => 2,
            Size::S32x8 => 4,
            Size::S32x16 => 8,
            Size::S64x32 => 32,
            Size::S8x16 => 2,
            Size::S8x32 => 4,
            Size::S16x32 => 8,
            Size::S32x64 => 32,
        }
    }
    pub(crate) const fn shape_size(self) -> (u16, u16) {
        (self as u16 >> 2, self as u16 & 0b11)
    }

    pub(crate) fn layout(self, multi_palette: bool) -> Layout {
        Layout::from_size_align(
            self.number_of_tiles() * BYTES_PER_TILE_4BPP * (multi_palette as usize + 1),
            8,
        )
        .unwrap()
    }

    /// The size in bytes for a sprite of this size in 16 colour mode
    #[must_use]
    pub fn size_bytes_16(self) -> usize {
        self.number_of_tiles() * BYTES_PER_TILE_4BPP
    }

    /// The size in bytes for a sprite of this size in 256 colour mode
    #[must_use]
    pub fn size_bytes_256(self) -> usize {
        self.number_of_tiles() * BYTES_PER_TILE_8BPP
    }

    #[must_use]
    /// Creates a size from width and height in pixels, panics if the width and
    /// height is not representable by GBA sprites.
    ///
    /// # Panics
    /// Panics if the given size is not representable by the GBA
    pub const fn from_width_height(width: usize, height: usize) -> Self {
        match (width, height) {
            (8, 8) => Size::S8x8,
            (16, 16) => Size::S16x16,
            (32, 32) => Size::S32x32,
            (64, 64) => Size::S64x64,
            (16, 8) => Size::S16x8,
            (32, 8) => Size::S32x8,
            (32, 16) => Size::S32x16,
            (64, 32) => Size::S64x32,
            (8, 16) => Size::S8x16,
            (8, 32) => Size::S8x32,
            (16, 32) => Size::S16x32,
            (32, 64) => Size::S32x64,
            (_, _) => panic!("Bad width and height!"),
        }
    }

    #[must_use]
    /// Returns the width and height of the size in pixels.
    pub const fn to_width_height(self) -> (usize, usize) {
        match self {
            Size::S8x8 => (8, 8),
            Size::S16x16 => (16, 16),
            Size::S32x32 => (32, 32),
            Size::S64x64 => (64, 64),
            Size::S16x8 => (16, 8),
            Size::S32x8 => (32, 8),
            Size::S32x16 => (32, 16),
            Size::S64x32 => (64, 32),
            Size::S8x16 => (8, 16),
            Size::S8x32 => (8, 32),
            Size::S16x32 => (16, 32),
            Size::S32x64 => (32, 64),
        }
    }

    #[must_use]
    /// Returns the width and height of the size in pixels.
    pub const fn to_tiles_width_height(self) -> (usize, usize) {
        let wh = self.to_width_height();
        (wh.0 / 8, wh.1 / 8)
    }
}