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
use crate::prelude::SpecialChar;
use crate::prelude::*;
use super::super::{CharFlags, Character, Color, Point, Size, Surface};
use super::{StringFormatError, StringFormatParser};
use std::str::FromStr;
/// How a [`BitTile`] is drawn onto a [`Surface`](crate::graphics::Surface).
#[derive(Copy, Clone, Eq, PartialEq, Debug, EnumSelector)]
#[repr(u8)]
pub enum BitTileRenderMethod {
/// Half-block characters (`▀`), packing two vertical pixels into one cell.
#[VariantInfo(name = "Small Blocks", description = "Small blocks with half-block characters")]
SmallBlocks,
/// Full-width cells filled with background color (two columns per pixel).
#[VariantInfo(name = "Large Blocks", description = "Large blocks with full-block characters")]
LargeBlocks,
/// Braille dots (`⣿`), packing a 2×4 pixel grid into one cell.
#[VariantInfo(name = "Braille", description = "Braille characters")]
Braille,
}
/// A bit tile is a 2D array of bits. It is used to store a 2D image in a compact way (where a pixel is represented by a single bit that can be either set or unset)
/// The size of the bit tile is the STORAGE_BYTES generic parameter plus 2 bytes for the width and height.
/// Since the width and height are stored in 2 bytes, the maximum size of the bit tile is 255 x 255 pixels.
/// However, the STORAGE_BYTES parameter is limited to 1024 bytes, so the size of the tile should fit in this space.
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct BitTile<const STORAGE_BYTES: usize> {
width: u8,
height: u8,
data: [u8; STORAGE_BYTES],
}
impl<const STORAGE_BYTES: usize> BitTile<STORAGE_BYTES> {
const _ASSERT_CHECK_STORAGE_BITS_: () = assert!(STORAGE_BYTES >= 2 && STORAGE_BYTES <= 1024);
/// Creates a new bit tile with the specified width and height.
///
/// # Arguments
///
/// * `width` - The width of the bit tile in pixels.
/// * `height` - The height of the bit tile in pixels.
///
/// # Returns
///
/// * `Some(BitTile)` - If the bit tile was created successfully.
/// * `None` - If the width or height is 0 or if the bit tile does not fit in the allocated space.
pub fn new(width: u8, height: u8) -> Option<Self> {
if (width == 0) || (height == 0) {
return None;
}
if (width as usize) * (height as usize) > (STORAGE_BYTES << 3) {
return None;
}
Some(Self {
width,
height,
data: [0; STORAGE_BYTES],
})
}
/// Returns the width of the bit tile in pixels.
#[inline(always)]
pub fn width(&self) -> u8 {
self.width
}
/// Returns the height of the bit tile in pixels.
#[inline(always)]
pub fn height(&self) -> u8 {
self.height
}
/// Returns the size of the bit tile in pixels.
#[inline(always)]
pub fn size(&self) -> Size {
Size::new(self.width as u32, self.height as u32)
}
/// Returns the value of the pixel (set or unset) at the specified coordinates.
///
/// # Arguments
///
/// * `x` - The x coordinate of the pixel.
/// * `y` - The y coordinate of the pixel.
///
/// # Returns
///
/// * `Some(bool)` - If the pixel is set.
/// * `None` - If the coordinates are outside the bounds of the bit tile.
#[inline(always)]
pub fn get(&self, x: u32, y: u32) -> Option<bool> {
if (x >= self.width as u32) || (y >= self.height as u32) {
None
} else {
let pos = (x as usize) + (y as usize) * (self.width as usize);
Some((self.data[pos >> 3] & (1 << (pos & 7))) != 0)
}
}
/// Sets the value of the pixel (set or unset) at the specified coordinates. If the coordinates are outside the bounds of the bit tile, the operation is silently ignored.
///
/// # Arguments
///
/// * `x` - The x coordinate of the pixel.
/// * `y` - The y coordinate of the pixel.
/// * `value` - The value of the pixel (set or unset).
#[inline(always)]
pub fn set(&mut self, x: u32, y: u32, value: bool) {
if (x < self.width as u32) && (y < self.height as u32) {
let pos = (x as usize) + (y as usize) * (self.width as usize);
let idx = pos >> 3;
let mask = 1 << (pos & 7);
if value {
self.data[idx] |= mask;
} else {
self.data[idx] &= !mask;
}
}
}
/// Clears the bit tile by setting all pixels to the specified value.
///
/// # Arguments
///
/// * `value` - The value to set all pixels to (set or unset).
pub fn clear(&mut self, value: bool) {
self.data.fill(if value { u8::MAX } else { 0 });
}
/// Returns a string representation of the bit tile in the format of:
/// ```no_compile
/// |...XX....XX...|
/// |..XXXX..XXXX..|
/// |.XXXXXXXXXXXX.|
/// |.XXXXXXXXXXXX.|
/// |..XXXXXXXXXX..|
/// |...XXXXXXXX...|
/// |....XXXXXX....|
/// |.....XXXX.....|
/// |......XX......|
/// ```
///where:
/// * `X` - a pixel that is set
/// * `.` - a pixel that is unset
/// * `|` - the start and end of a row
///
/// # Returns
///
/// * `String` - The string representation of the bit tile.
pub fn to_string_format(&self) -> String {
let mut s = String::with_capacity((self.width as usize + 4) * self.height as usize);
for y in 0..self.height as u32 {
s.push('|');
for x in 0..self.width as u32 {
s.push(if self.get(x, y).unwrap_or(false) { 'X' } else { '.' });
}
s.push('|');
s.push('\n');
}
s
}
pub(in super::super) fn paint_large(&self, surface: &mut Surface, pos: Point, set_pixel_color: Color, unset_pixel_color: Color) {
let mut ch = Character::new(' ', Color::White, Color::Transparent, CharFlags::None);
for y in 0..self.height {
let mut x_pos = pos.x;
for x in 0..self.width {
if let Some(is_set) = self.get(x as u32, y as u32) {
if is_set {
if set_pixel_color != Color::Transparent {
ch.background = set_pixel_color;
surface.write_char(x_pos, pos.y + y as i32, ch);
surface.write_char(x_pos + 1, pos.y + y as i32, ch);
}
} else if unset_pixel_color != Color::Transparent {
ch.background = unset_pixel_color;
surface.write_char(x_pos, pos.y + y as i32, ch);
surface.write_char(x_pos + 1, pos.y + y as i32, ch);
}
}
x_pos += 2;
}
}
}
pub(in super::super) fn paint_small(&self, surface: &mut Surface, pos: Point, set_pixel_color: Color, unset_pixel_color: Color) {
let mut ch = Character::new(' ', set_pixel_color, unset_pixel_color, CharFlags::None);
let mut y = 0u32;
let h = self.height as u32;
let mut y_pos = pos.y;
while y < h {
for x in 0..self.width {
ch.code = match (self.get(x as u32, y).unwrap_or(false), self.get(x as u32, y + 1).unwrap_or(false)) {
(true, true) => SpecialChar::Block100.into(),
(true, false) => SpecialChar::BlockUpperHalf.into(),
(false, true) => SpecialChar::BlockLowerHalf.into(),
(false, false) => ' ',
};
surface.write_char(pos.x + x as i32, y_pos, ch);
}
y += 2;
y_pos += 1;
}
}
pub(in super::super) fn paint_braille(&self, surface: &mut Surface, pos: Point, set_pixel_color: Color, unset_pixel_color: Color) {
let mut ch = Character::new(' ', set_pixel_color, unset_pixel_color, CharFlags::None);
let mut y = 0u32;
let h = self.height as u32;
let w = self.width as u32;
let mut y_pos = pos.y;
while y < h {
let mut x = 0u32;
let mut x_pos = pos.x;
while x < w {
let mut code = 0;
if self.get(x, y).unwrap_or(false) {
code |= 1;
}
if self.get(x, y + 1).unwrap_or(false) {
code |= 2;
}
if self.get(x, y + 2).unwrap_or(false) {
code |= 4;
}
if self.get(x, y + 3).unwrap_or(false) {
code |= 64;
}
if self.get(x + 1, y).unwrap_or(false) {
code |= 8;
}
if self.get(x + 1, y + 1).unwrap_or(false) {
code |= 16;
}
if self.get(x + 1, y + 2).unwrap_or(false) {
code |= 32;
}
if self.get(x + 1, y + 3).unwrap_or(false) {
code |= 128;
}
ch.code = unsafe { char::from_u32_unchecked(0x2800 + code) };
surface.write_char(x_pos, y_pos, ch);
x += 2;
x_pos += 1;
}
y += 4;
y_pos += 1;
}
}
}
impl<const STORAGE_BYTES: usize> FromStr for BitTile<STORAGE_BYTES> {
type Err = StringFormatError;
/// Creates a new bit tile from a string.
/// The format uses pipes (characters `|`) to delimit rows, and single characters to represent different colored pixels.
/// Since a tile is basically a black and white image, the characters used to represent the pixels are:
/// * ` ` (space), `.` (point) - unset pixels
/// * everything else - set pixels
///
/// For example, the following string will create a bit tile with a width of 14 and a height of 9:
/// ```rust
/// use appcui::prelude::*;
/// use std::str::FromStr;
///
/// const HEART_TILE: &str = r#"
/// |...rr....rr...|
/// |..rrrr..rrrr..|
/// |.rrrrrrrrrrrr.|
/// |.rrrrrrrrrrrr.|
/// |..rrrrrrrrrr..|
/// | rrrrrrrr |
/// |....rrrrrr....|
/// |.....rrrr.....|
/// |......rr......|
/// "#;
///
/// // use 16 bytes to store the bit tile (14 x 9 = 126 pixels)
/// // a BitTile<16> implies 16 bytes x 8 bits/byte = 128 bits (128 pixels) maximum storage capacity.
/// // since 14 x 9 = 126 pixels, this is well within the maximum storage capacity.
/// let bit_tile: BitTile<16> = BitTile::from_str(HEART_TILE).unwrap();
/// ```
///
/// # Arguments
///
/// * `image` - The string to create the bit tile from.
///
/// # Returns
///
/// * `Ok(BitTile)` - If the bit tile was created successfully.
/// * `Err(StringFormatError)` - If the string is not a valid bit tile.
fn from_str(image: &str) -> Result<Self, Self::Err> {
let mut f = StringFormatParser::new(image);
let size = f.size()?;
if (size.width > 0xFF) || (size.height > 0xFF) {
return Err(StringFormatError::ImageTooLarge);
}
if ((size.width as usize) * (size.height as usize)) > STORAGE_BYTES * 8 {
return Err(StringFormatError::ImageDoesNotFitInAllocatedSpace);
}
let mut tile = Self {
width: size.width as u8,
height: size.height as u8,
data: [0; STORAGE_BYTES],
};
let mut idx = 0;
let mut mask = 1;
while let Some(line) = f.next_line() {
for b in line {
if ((*b) != b' ') && ((*b) != b'.') {
// not a 0 - put 1
tile.data[idx] |= mask;
}
if mask < 0x80 {
mask <<= 1;
} else {
mask = 1;
idx += 1;
}
}
}
Ok(tile)
}
}
macro_rules! unsigned_int_implementation {
($name:ident,$int:ty,$bytes:expr,$from_fn:ident,$to_fn:ident) => {
#[doc = concat!(
"A [`BitTile`] stored in a `", stringify!($int), "` (`", stringify!($bytes),
"` bytes, at most `", stringify!($int), "::BITS` pixels)."
)]
pub type $name = BitTile<$bytes>;
impl BitTile<$bytes> {
#[doc = concat!(
"Creates a [`BitTile`] from a packed `", stringify!($int), "` value.\n\n",
"Pixels are stored in native-endian byte order. Returns `None` if `width` or ",
"`height` is `0`, or if `width * height` is larger than `", stringify!($int), "::BITS`.\n\n",
"# Examples\n\n",
"```rust\n",
"use appcui::prelude::*;\n\n",
"let tile = ", stringify!($name), "::", stringify!($from_fn),
"(4, 4, 0b1001_0110_1001_0110).unwrap();\n",
"assert_eq!(tile.", stringify!($to_fn), "(), 0b1001_0110_1001_0110);\n",
"```"
)]
pub fn $from_fn(width: u8, height: u8, bits: $int) -> Option<Self> {
if width == 0 || height == 0 {
return None;
}
if (width as usize) * (height as usize) > <$int>::BITS as usize {
return None;
}
Some(Self {
width,
height,
data: bits.to_ne_bytes(),
})
}
#[doc = concat!(
"Returns the packed `", stringify!($int), "` stored in this tile (native-endian).\n\n",
"# Examples\n\n",
"```rust\n",
"use appcui::prelude::*;\n\n",
"let tile = ", stringify!($name), "::", stringify!($from_fn),
"(4, 4, 0b1111_0000_1111_0000).unwrap();\n",
"assert_eq!(tile.", stringify!($to_fn), "(), 0b1111_0000_1111_0000);\n",
"```"
)]
pub fn $to_fn(&self) -> $int {
<$int>::from_ne_bytes(self.data)
}
#[doc = concat!(
"Replaces the packed `", stringify!($int), "` bits without changing width or height.\n\n",
"# Examples\n\n",
"```rust\n",
"use appcui::prelude::*;\n\n",
"let mut tile = ", stringify!($name), "::", stringify!($from_fn), "(4, 4, 0).unwrap();\n",
"tile.reset(0b1111_0000_1111_0000);\n",
"assert_eq!(tile.", stringify!($to_fn), "(), 0b1111_0000_1111_0000);\n",
"```"
)]
pub fn reset(&mut self, bits: $int) {
self.data = bits.to_ne_bytes();
}
}
};
}
unsigned_int_implementation!(BitTileU16, u16, 2, from_u16, to_u16);
unsigned_int_implementation!(BitTileU32, u32, 4, from_u32, to_u32);
unsigned_int_implementation!(BitTileU64, u64, 8, from_u64, to_u64);
unsigned_int_implementation!(BitTileU128, u128, 16, from_u128, to_u128);