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
use image::GenericImageView;
use romy_core::output::*;

/// Decode a .png, returning a Image
pub fn decode_png(data: &[u8]) -> Image {
    let image = image::load_from_memory(data).unwrap();
    let rah = image.to_rgba().into_raw();
    Image::from_data(
        image.dimensions().0 as i32,
        image.dimensions().1 as i32,
        &rah,
    )
}

pub trait ImageEngine {
    fn is_inside(&self, x: i32, y: i32) -> bool;
    fn blit(&mut self, x: i32, y: i32, image: &Image);
}

impl ImageEngine for Image {
    fn is_inside(&self, x: i32, y: i32) -> bool {
        x >= 0 && x < self.width() && y >= 0 && y < self.height()
    }

    fn blit(&mut self, x: i32, y: i32, image: &Image) {
        for image_x in 0..image.width() {
            for image_y in 0..image.height() {
                let to_x = x + image_x;
                let to_y = y + image_y;
                if !self.is_inside(to_x, to_y) {
                    continue;
                }
                let color = image.get_pixel(image_x, image_y);
                if color.alpha() <= 0.0 {
                    continue;
                }
                self.set_pixel(to_x, to_y, color);
            }
        }
    }
}

// Decode a .ogg file, retuning a sound for each channel
pub fn decode_ogg(data: &[u8]) -> Vec<Sound> {
    let cursor = std::io::Cursor::new(data);
    let mut srr = lewton::inside_ogg::OggStreamReader::new(cursor).unwrap();
    let channels = srr.ident_hdr.audio_channels;
    let sample_rate = srr.ident_hdr.audio_sample_rate;

    let mut samples = Vec::with_capacity(channels as usize);
    for _ in 0..channels {
        samples.push(Vec::new());
    }

    while let Some(pck_samples) = srr.read_dec_packet().unwrap() {
        for (channel, element) in pck_samples.iter().enumerate() {
            for element in element {
                let frac = f32::from(*element) / f32::from(std::i16::MAX);
                samples[channel].push(frac);
            }
        }
    }

    let mut sounds = Vec::with_capacity(channels as usize);
    for s in samples {
        sounds.push(Sound::from_data(sample_rate as i32, &s));
    }

    sounds
}