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
// Aldaron's Format Interface
// Copyright (c) 2017 Plop Grizzly, Jeron Lau <jeron.lau@plopgrizzly.com>
// Licensed under the MIT LICENSE

//! Aldaron's Format Interface is a library developed by Plop Grizzly for
//! providing memory structures for graphics, audio, video and text.

#![no_std]
#![warn(missing_docs)]
#![doc(html_logo_url = "http://plopgrizzly.com/afi/icon.png",
	html_favicon_url = "http://plopgrizzly.com/afi/icon.ico",
	html_root_url = "http://plopgrizzly.com/afi/")]

extern crate ami;

use ami::Vec;

/// Builder for `Graphic`
pub struct GraphicBuilder;

impl GraphicBuilder {
	/// Create a new `GraphicBuilder`
	pub fn new() -> GraphicBuilder {
		GraphicBuilder
	}

	/// Create a WH,[RGBA] graphic
	pub fn rgba(self, rgba: Vec<u32>) -> Graphic {
		Graphic { bgra: false, data: rgba }
	}

	/// Create an WH,[BGRA] graphic
	pub fn bgra(self, bgra: Vec<u32>) -> Graphic {
		Graphic { bgra: true, data: bgra }
	}
}

/// A graphic (image)
pub struct Graphic {
	bgra: bool,
	data: Vec<u32>,
}

impl Graphic {
	/// Convert `self` into a BGRA graphic.
	pub fn bgra(&mut self) {
		if !self.bgra {
			for i in &mut self.data.as_mut_slice()[2..] {
				*i = i.swap_bytes().rotate_right(8);
			}
		}

		self.bgra = true;
	}

	/// Convert `self` into a RGBA graphic.
	pub fn rgba(&mut self) {
		if self.bgra {
			for i in &mut self.data.as_mut_slice()[2..] {
				*i = i.swap_bytes().rotate_right(8);
			}
		}

		self.bgra = false;
	}

	/// Get the graphic as a slice `(w, h, [pixels])`
	pub fn as_slice(&self) -> &[u32] {
		self.data.as_slice()
	}
}

/// A sound or music.
pub struct Audio {
	hz: u16,
	samples: Vec<u16>,
}

impl Audio {
	/// Create a new `Audio` from samples.
	pub fn new(hz: u16, samples: Vec<u16>) -> Audio {
		Audio { hz, samples }
	}

	/// Get a sample at a specific index.
	pub fn sample(&self, index: usize) -> u16 {
		self.samples[index]
	}

	/// Get an index for a specific point in time since the beginning of the
	/// sound.
	pub fn index(&self, seconds: f32) -> usize {
		(seconds / (self.hz as f32)) as usize
	}
}

/// Some text.
pub struct Text {
	bytes: Vec<u8>
}

impl Text {
	/// Create a new `Text` from bytes.
	pub fn new(bytes: Vec<u8>) -> Text {
		Text { bytes }
	}

	/// Get bytes from the `Text`.
	pub fn bytes(&self) -> &[u8] {
		self.bytes.as_slice()
	}
}