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
//! # Specs ECS Rendering System
//!
//! This library exposes a 2D rendering system to be used in [specs](https://github.com/amethyst/specs).
//! It is based around the [blit](https://github.com/tversteeg/blit) library.
//! All the images will be rendered to a buffer which can be used in various
//! graphics libraries, e.g. minifb.
//!
//! All sprites are loaded onto a big array on the heap.
//! ```rust
//! use anyhow::Result;
//! use blit::{BlitBuffer, Color};
//! use specs::prelude::*;
//! use specs_blit::{load, PixelBuffer, RenderSystem, Sprite};
//! use rotsprite::rotsprite;
//!
//! const WIDTH: usize = 800;
//! const HEIGHT: usize = 800;
//! const MASK_COLOR: u32 = 0xFF00FF;
//!
//! fn main() -> Result<()> {
//!     // Setup the specs world
//!     let mut world = World::new();
//!
//!     // Load the blit components into the world
//!     world.register::<Sprite>();
//!
//!     // Add the pixel buffer as a resource so it can be accessed from the RenderSystem later
//!     world.insert(PixelBuffer::new(WIDTH, HEIGHT));
//!
//!     let sprite_ref = {
//!         // Create a sprite of 4 pixels
//!         let sprite = BlitBuffer::from_buffer(&[0, MASK_COLOR, 0, 0], 2, MASK_COLOR);
//!
//!         // Load the sprite and get a reference
//!         load(sprite)?
//!     };
//!
//!     // Create a new sprite entity in the ECS system
//!     world.create_entity()
//!         .with(Sprite::new(sprite_ref))
//!         .build();
//!
//!     // Setup the dispatcher with the blit system
//!     let mut dispatcher = DispatcherBuilder::new()
//!         .with_thread_local(RenderSystem)
//!         .build();
//!
//!     Ok(())
//! }
//! ```

pub extern crate blit;
pub extern crate specs;

use anyhow::Result;
use blit::BlitBuffer;
use lazy_static::lazy_static;
#[cfg(feature = "parallel")]
use rayon::prelude::*;
use specs::prelude::*;
use std::sync::RwLock;

// The heap allocated array of sprites
// It's wrapped in a RwLock so all threads can access it
lazy_static! {
    static ref SPRITES: RwLock<Vec<BlitBuffer>> = RwLock::new(vec![]);
}

/// Specs component representing a sprite that can be drawn.
///
/// ```rust
/// use blit::{BlitBuffer, Color};
/// use specs::prelude::*;
/// use specs_blit::{load, Sprite};
///
/// const MASK_COLOR: u32 = 0xFF00FF;
///
/// # fn main() -> anyhow::Result<()> {
/// // Setup the specs world
/// let mut world = World::new();
///
/// // Load the blit components into the world
/// world.register::<Sprite>();
///
/// let sprite_ref = {
///     // Create a sprite of 4 pixels
///     let sprite = BlitBuffer::from_buffer(&[0, MASK_COLOR, 0, 0], 2, MASK_COLOR);
///
///     // Load the sprite and get a reference
///     load(sprite)?
/// };
///
/// // Create a new sprite entity in the ECS system
/// world.create_entity()
///     .with(Sprite::new(sprite_ref))
///     .build();
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct Sprite {
    /// The reference to the heap allocated array of sprites.
    pub(crate) reference: SpriteRef,
    /// Where on the screen the sprite needs to be rendered.
    pos: (i32, i32),
    /// The current rotation of the sprite, it will match the nearest rotating divisor of the
    /// loaded version.
    rot: i16,
}

impl Component for Sprite {
    type Storage = VecStorage<Self>;
}

impl Sprite {
    /// Instantiate a new sprite from a loaded sprite index.
    ///
    /// ```rust
    /// use blit::{BlitBuffer, Color};
    /// use specs_blit::{load, Sprite};
    ///
    /// const MASK_COLOR: u32 = 0xFF00FF;
    ///
    /// # fn main() -> anyhow::Result<()> {
    /// let sprite_ref = {
    ///     // Create a sprite of 4 pixels
    ///     let sprite = BlitBuffer::from_buffer(&[0, MASK_COLOR, 0, 0], 2, MASK_COLOR);
    ///
    ///     // Load the sprite and get a reference
    ///     load(sprite)?
    /// };
    ///
    /// // Create a specs sprite from the image
    /// let sprite = Sprite::new(sprite_ref);
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(sprite_reference: SpriteRef) -> Self {
        Self {
            reference: sprite_reference,
            pos: (0, 0),
            rot: 0,
        }
    }

    /// Set the pixel position of where the sprite needs to be rendered.
    pub fn set_pos(&mut self, x: i32, y: i32) {
        self.pos.0 = x;
        self.pos.1 = y;
    }

    /// Get the pixel position as an (x, y) tuple of where the sprite will be rendered.
    pub fn pos(&self) -> (i32, i32) {
        self.pos
    }

    /// Set the rotation in degrees of the sprite.
    /// The rotation will attempt to match the nearest degrees of rotation divisor.
    pub fn set_rot(&mut self, rotation: i16) {
        let mut rotation = rotation;
        while rotation < 0 {
            rotation += 360;
        }
        while rotation > 360 {
            rotation -= 360;
        }

        self.rot = rotation;
    }

    /// Get the pixel rotation as degrees.
    pub fn rot(&self) -> i16 {
        self.rot
    }

    /// Get the data needed for rendering this sprite.
    pub(crate) fn render_info(&self) -> (usize, i32, i32) {
        self.reference.render_info(self.rot)
    }
}

/// Reference to a heap-allocated sprite.
/// Contains the index of the vector, only this crate is allowed to access this.
#[derive(Debug, Clone)]
pub struct SpriteRef {
    /// Start point of the rotation.
    rot_range_start: i16,
    /// In how many degrees the rotation is divided.
    rot_divisor: f64,
    /// Array of different rotations sprite references with their position offsets.
    sprites: Vec<(usize, i32, i32)>,
}

impl SpriteRef {
    // Return the reference index and the offsets of the position.
    pub(crate) fn render_info(&self, rotation: i16) -> (usize, i32, i32) {
        let rotation_index = (((rotation - self.rot_range_start) % 360) as f64) / self.rot_divisor;

        // Return the proper sprite depending on the rotation
        *self
            .sprites
            .get(rotation_index as usize)
            // Get the sprite at the index or the first if that's not valid
            .unwrap_or(&self.sprites[0])
    }
}

/// Array of pixels resource that can be written to from the [`RenderSystem`] system.
///
/// ```rust
/// use specs::prelude::*;
/// use specs_blit::PixelBuffer;
///
/// const WIDTH: usize = 800;
/// const HEIGHT: usize = 800;
///
/// // Setup the specs world
/// let mut world = World::new();
///
/// // Add the pixel buffer as a resource so it can be accessed from the RenderSystem later
/// world.insert(PixelBuffer::new(WIDTH, HEIGHT));
/// ```
#[derive(Debug, Default)]
pub struct PixelBuffer {
    pub(crate) pixels: Vec<u32>,
    pub(crate) width: usize,
    pub(crate) height: usize,
}

impl PixelBuffer {
    /// Create a new buffer filled with black pixels.
    pub fn new(width: usize, height: usize) -> Self {
        Self {
            pixels: vec![0; width * height],
            width,
            height,
        }
    }

    /// Get the array of pixels.
    pub fn pixels(&self) -> &Vec<u32> {
        &self.pixels
    }

    /// Get the array so that it can be mutated manually.
    pub fn pixels_mut(&mut self) -> &mut Vec<u32> {
        &mut self.pixels
    }

    /// Get the width in pixels.
    pub fn width(&self) -> usize {
        self.width
    }

    /// Get the height in pixels.
    pub fn height(&self) -> usize {
        self.height
    }

    /// Set all the pixels to the passed color.
    pub fn clear(&mut self, color: u32) {
        for pixel in self.pixels.iter_mut() {
            *pixel = color;
        }
    }
}

/// Specs system for rendering sprites to a buffer.
///
/// *Note*: This can only be used in conjunction with a `.with_thread_local()`
/// function in specs and not with a normal `.with()` call.
///
/// ```rust
/// use specs::prelude::*;
/// use specs_blit::RenderSystem;
///
/// let mut dispatcher = DispatcherBuilder::new()
///     // Expose the sprite render system to specs
///     .with_thread_local(RenderSystem)
///     .build();
/// ```
pub struct RenderSystem;
impl<'a> System<'a> for RenderSystem {
    type SystemData = (Write<'a, PixelBuffer>, ReadStorage<'a, Sprite>);

    fn run(&mut self, (mut buffer, sprites): Self::SystemData) {
        let width = buffer.width;

        for sprite_component in sprites.join() {
            let (index, x_offset, y_offset) = sprite_component.render_info();

            // Get the sprite from the array
            let sprite = &SPRITES.read().unwrap()[index];

            let pos = (
                sprite_component.pos.0 + x_offset,
                sprite_component.pos.1 + y_offset,
            );

            // Draw the sprite on the buffer
            sprite.blit(&mut buffer.pixels, width, pos);
        }
    }
}

/// Load a sprite buffer and place it onto the heap.
///
/// Returns an index that can be used in sprite components.
///
/// ```rust
/// use blit::{BlitBuffer, Color};
/// use specs_blit::load;
///
/// const MASK_COLOR: u32 = 0xFF00FF;
///
/// # fn main() -> anyhow::Result<()> {
/// // Create a sprite of 4 pixels
/// let sprite = BlitBuffer::from_buffer(&[0, MASK_COLOR, 0, 0], 2, MASK_COLOR);
///
/// // Load the sprite and get a reference
/// let sprite_ref = load(sprite)?;
/// # Ok(())
/// # }
/// ```
pub fn load(sprite: BlitBuffer) -> Result<SpriteRef> {
    load_rotations(sprite, 1)
}

/// Load a sprite buffer and place it onto the heap with a set amount of rotations.
///
/// Calls `load_rotations_range` with a range of `(0.0, 360.0)`.
///
/// Returns an index that can be used in sprite components.
pub fn load_rotations(sprite: BlitBuffer, rotations: u16) -> Result<SpriteRef> {
    load_rotations_range(sprite, rotations, (0, 360))
}

/// Load a sprite buffer and place it onto the heap with a set amount of rotations.
///
/// Returns an index that can be used in sprite components.
///
/// ```rust
/// use blit::{BlitBuffer, Color};
/// use specs_blit::load;
///
/// const MASK_COLOR: u32 = 0xFF00FF;
///
/// # fn main() -> anyhow::Result<()> {
/// // Create a sprite of 4 pixels
/// let sprite = BlitBuffer::from_buffer(&[0, MASK_COLOR, 0, 0], 2, MASK_COLOR);
///
/// // Load the sprite in rotations of -15, 0, 15 degrees and get a reference
/// let sprite_ref = load_rotations_range(sprite, 3, (-15.0, 15.0))?;
/// # Ok(())
/// # }
/// ```
#[cfg(not(feature = "parallel"))]
pub fn load_rotations_range(
    sprite: BlitBuffer,
    rotations: u16,
    range: (i16, i16),
) -> Result<SpriteRef> {
    let rotations = if rotations == 0 { 1 } else { rotations };

    let rot_divisor = (range.1 - range.0) as f64 / (rotations as f64);
    let raw_buffer = sprite.to_raw_buffer();

    // Create a rotation sprite for all rotations
    let sprites = (0..rotations)
        .into_iter()
        .map(|r| {
            let (rotated_width, rotated_height, rotated) = rotsprite::rotsprite(
                &raw_buffer,
                &sprite.mask_color().u32(),
                sprite.size().0 as usize,
                range.0 as f64 + (r as f64 * rot_divisor),
            )?;

            let rotated_sprite =
                BlitBuffer::from_buffer(&rotated, rotated_width as i32, sprite.mask_color());

            let mut sprites_vec = SPRITES.write().unwrap();
            sprites_vec.push(rotated_sprite);

            let index = sprites_vec.len() - 1;

            let x_offset = (sprite.width() - rotated_width as i32) / 2;
            let y_offset = (sprite.height() - rotated_height as i32) / 2;

            Ok((index, x_offset, y_offset))
        })
        .collect::<Result<Vec<_>>>()?
        // Return the first error
        .into_iter()
        .collect::<_>();

    Ok(SpriteRef {
        rot_range_start: range.0,
        rot_divisor,
        sprites,
    })
}

#[cfg(feature = "parallel")]
pub fn load_rotations_range(
    sprite: BlitBuffer,
    rotations: u16,
    range: (i16, i16),
) -> Result<SpriteRef> {
    let rotations = if rotations == 0 { 1 } else { rotations };

    let rot_divisor = (range.1 - range.0) as f64 / (rotations as f64);
    let raw_buffer = sprite.to_raw_buffer();

    // Create a rotation sprite for all rotations
    let sprites = (0..rotations)
        .into_par_iter()
        .map(|r| {
            let (rotated_width, rotated_height, rotated) = rotsprite::rotsprite(
                &raw_buffer,
                &sprite.mask_color().u32(),
                sprite.size().0 as usize,
                range.0 as f64 + (r as f64 * rot_divisor),
            )?;

            let rotated_sprite =
                BlitBuffer::from_buffer(&rotated, rotated_width as i32, sprite.mask_color());

            let mut sprites_vec = SPRITES.write().unwrap();
            sprites_vec.push(rotated_sprite);

            let index = sprites_vec.len() - 1;

            let x_offset = (sprite.width() - rotated_width as i32) / 2;
            let y_offset = (sprite.height() - rotated_height as i32) / 2;

            Ok((index, x_offset, y_offset))
        })
        .collect::<Result<Vec<_>>>()?
        // Return the first error
        .into_iter()
        .collect::<_>();

    Ok(SpriteRef {
        rot_range_start: range.0,
        rot_divisor,
        sprites,
    })
}

/// Delete all cached buffers.
///
/// Marked unsafe because it will invalidate all sprite references.
pub unsafe fn clear_all() {
    SPRITES.write().unwrap().clear();
}