minifb_wrapper 0.1.1

A wrapper around minifb to make managing windows easier than ever
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
471
472
473
474
//!A wrapper around [minifb] that makes managing windows as simple as possible, with hexidecimal RGB rather than raw u32.
//!
//!Window elements like buffers and dimensions are linked together in the [WindowContainer] struct. To keep the window alive, call update() from within a loop. This has a built-in graceful exit by pressing ESC.
//!
//!```rust
//!let window = window!(?500, 500, "Window", "FFFFFF");
//!
//!loop {
//!    window.update();
//!}
//!```
//! 
//!Heres an example of a UV map generated from pixel coordinates:
//!```rust
//!let window = window!(?500, 500, "Window", "FFFFFF");
//!
//!//iterates with the value and position
//!for (_, pos) in window.iter() {
//!    let r = to_hex2(pos.0 as u8).unwrap();
//!    let g = to_hex2(pos.1 as u8).unwrap();
//!    let string = format!("{r}{g}00");
//!
//!    window.set(pos, &string)?;
//!}
//!
//!//pressing escape will close the window
//!loop {
//!    window.update();
//!}
//!```
//! 
//! 
//! 
//!Note with the hexidecimal conversions: functions that take hexidecimal will take a &str for convenience, but functions that return hexidecimal will return a [String].
//! 














//use minifb;
use std::{process, ops::Range};
fn from_u8_rgb(r: u8, g: u8, b: u8) -> u32 {
    let (r, g, b) = (r as u32, g as u32, b as u32);
    (r << 16) | (g << 8) | b
}

type Unit = Result<(), WinErr>;

macro_rules! unit {
    () => {
        Ok(())
    };
}
///Initializes a [WindowContainer]. Optional background color. Begin with ? to unwrap.
#[macro_export] macro_rules! window {
    ($width:expr, $height:expr, $name:tt) => {
        WindowContainer::new($width, $height, $name, "FFFFFF")
    };
    (?$width:expr, $height:expr, $name:tt) => {
        WindowContainer::new($width, $height, $name, "FFFFFF").unwrap()
    };

    ($width:expr, $height:expr, $name:tt, $color:tt) => {
        WindowContainer::new($width, $height, $name, $color)
    };
    (?$width:expr, $height:expr, $name:tt, $color:tt) => {
        WindowContainer::new($width, $height, $name, $color).unwrap()
    };

}

///converts a 0F0F0F format hex string into a u32.
pub fn hex_to_rgb(code:String) -> Result<u32, WinErr> {
    if code.len() != 6 {return Err(WinErr::InvalidHexCode(code))}

    let (r, gb) = code.split_at(2);
    let (g, b) = gb.split_at(2);
    
    let out = from_u8_rgb(
    from_hex8(r.to_string())? as u8,
    from_hex8(g.to_string())? as u8,
    from_hex8(b.to_string())? as u8
    );

    Ok(out)
}



fn hex2num_code(c: char) -> Result<u8, WinErr> {
    c.to_digit(16)
        .map(|n| n as u8)
        .ok_or(WinErr::InvalidHexChar(c))
}
///Converts an (up to) 8-wide hexidecimal string to a u8.
pub fn from_hex8(input:String) -> Result<u32, WinErr> {
    if input.len() > 8 {return Err(WinErr::InvalidHexCode(input))}

    let mut output = 0_u32;
    
    let iterator = input.chars().rev().enumerate();

    for (i, c) in iterator {
        let val = hex2num_code(c)? as u32;
        output += val * 16_u32.pow(i as u32);
    }

    Ok(output)
}
fn num2hex_code(num: u8) -> Result<char, WinErr> {
    match num {
        0..=9 => Ok((num + 48) as char),
        10..=15 => Ok((num + 55) as char),
        _ => Err(WinErr::InvalidNumCode(num))
    }
}
///Converts a u32 to a 6-wide hexidecimal string. Note that this includes leading zeros.
pub fn to_hex6(num: u32) -> Result<String, WinErr> {
    if num > 16777215 {return Err(WinErr::OverflowNum(num))}    

    let mut hex_string = String::new();

    for i in (0..6).rev() {
        let shift = i * 4;
        let hex_digit = ((num >> shift) & 0xF) as u8;
        let hex_char = num2hex_code(hex_digit)?;

        hex_string.push(hex_char);
    }

    Ok(hex_string)
}
///Converts a u8 to a 2-wide hexidecimal string, to concatenate into a RGB hex string. Note that this includes leading zero.
pub fn to_hex2(num: u8) -> Result<String, WinErr> {
    let mut hex_string = String::new();

    for i in (0..2).rev() {
        let shift = i * 4;
        let hex_digit = (num >> shift) & 0xF;
        let hex_char = num2hex_code(hex_digit)?;

        hex_string.push(hex_char);
    }

    Ok(hex_string)
}




fn dist(p1:(usize, usize), p2:(usize, usize)) -> f64 {
    let fp1 = (p1.0 as f64, p1.1 as f64);
    let fp2 = (p2.0 as f64, p2.1 as f64);
    ((fp2.0 - fp1.0).powi(2) + (fp2.1 - fp1.1).powi(2)).sqrt()

}

fn tupf64(tup:(usize, usize)) -> (f64, f64) {
    (tup.0 as f64, tup.1 as f64)
}

fn perpendicular_line(slope: f64, midpoint: (f64, f64), length: f64) -> ((f64, f64), (f64, f64)) {
    let m_perp = -1.0 / slope;
    let dx = length / (2.0 * (1.0 + m_perp.powi(2)).sqrt());
    let dy = m_perp * dx;
    let start = (midpoint.0 - dx, midpoint.1 - dy);
    let end = (midpoint.0 + dx, midpoint.1 + dy);
    (start, end)
}

///Contains a Window, pixel buffer, and properties.
pub struct WindowContainer {
    buffer:Vec<u32>,
    window:minifb::Window,

    width:usize,
    height:usize,
    pub bg_color:u32,

    length:usize,

}

impl WindowContainer {
    ///Initalizes a new WindowContainer.
    pub fn new(width:usize, height:usize, name:&str, color:&str) -> Result<Self, WinErr> {
        let bg_color = hex_to_rgb(color.to_string())?;
        if bg_color > 16777215 {return Err(WinErr::InvalidRGBValue(bg_color))}

        let buffer = vec![bg_color; width * height];
        let window = minifb::Window::new(name, width, height, minifb::WindowOptions::default()).unwrap();

        let length = buffer.len();

        Ok(WindowContainer {buffer, window, width, height, bg_color, length})
    }

    ///Updates the window with its pixel buffer. Pressing ESC will gracefully exit the program.
    ///```rust
    ///let mut window = window!(?500, 500, "Window", "FFFFFF");
    ///
    ///loop {//can close by pressing ESC
    ///    window.update();
    ///}
    ///```
    pub fn update(&mut self) -> Unit {
        if self.window.is_key_down(minifb::Key::Escape) {process::exit(1)}


        self.window.update_with_buffer(&self.buffer, self.width, self.height)?;
        unit!()
    }
    ///clears the screen to the background color.
    ///```rust
    ///let mut window = window!(?500, 500, "Window", "FF00FF");
    /// 
    ///loop {
    ///    window.clear();//clears to "FF00FF"
    /// 
    ///    //drawing code
    /// 
    ///    window.update();
    ///}
    ///```
    pub fn clear(&mut self) {
        self.buffer = self.buffer.iter().map(|_| self.bg_color).collect();
    }

    //inputs should be converted from &str -> String so that inputing params is easier
    ///Returns the hexidecimal value of a pixel at a position.
    pub fn get(&self, pos:(usize, usize)) -> Result<String, WinErr> {
        if pos.0 >= self.width  {return Err(WinErr::InvalidPos(pos))}
        if pos.1 >= self.height {return Err(WinErr::InvalidPos(pos))}

        let i = (pos.1 * self.width) + pos.0;
        let val = self.buffer[i];
        
        to_hex6(val)
    }
    ///Sets a pixel to a hexidecimal value.
    pub fn set(&mut self, pos:(usize, usize), val:&str) -> Result<(), WinErr> {
        if pos.0 >= self.width  {return Err(WinErr::InvalidPos(pos))}
        if pos.1 >= self.height {return Err(WinErr::InvalidPos(pos))}

        let i = (pos.1 * self.width) + pos.0;
        self.buffer[i] = hex_to_rgb(val.to_string())?;

        unit!()
    }

    ///returns an iterator over the pixel buffer, holding the hex value and position. Note that the iterator pulled from the buffer is no longer linked to the window, and modifying it will do nothing.
    ///```rust
    ///let window = window!(?500, 500, "Window", "FFFFFF");
    ///
    /////val:String, pos:(usize, usize)
    ///for (val, pos) in window.iter() {
    ///    let r = to_hex2(pos.0 as u8).unwrap();
    ///    let g = to_hex2(pos.1 as u8).unwrap();
    ///    let string = format!("{r}{g}00");
    ///
    ///    window.set(pos, &string)?;
    ///}
    ///
    /////pressing escape will close the window
    ///loop {
    ///    window.update();
    ///}
    ///```
    pub fn iter(&self) -> std::vec::IntoIter<(String, (usize, usize))> {
        let mut table:Vec<(String, (usize, usize))> = vec![];
        
        for i in 0..self.length {
            let string = to_hex6(self.buffer[i]).unwrap();

            table.push((string, self.nth_to_pos(i)));
        }

        table.into_iter()
    }


    fn pos_to_nth(&self, pos:(usize, usize)) -> usize {
        (pos.1 * self.width) + pos.0
    }
    fn nth_to_pos(&self, i:usize) -> (usize, usize) {
        (i / self.width, i % self.width)
    }

    //drawing
    ///Draws a circle at a given position with a radius and color.
    pub fn circle(&mut self, pos:(usize, usize), r:usize, color:&str) -> Unit {
        if pos.0 >= self.width  {return Err(WinErr::InvalidPos(pos))}
        if pos.1 >= self.height {return Err(WinErr::InvalidPos(pos))}

        let y_range = pos.1-r..pos.1+r;

        let mut range_table: Vec<Range<usize>> = vec![];
        
        for i in y_range {
            range_table.push((pos.0+(self.width*i))-r..(pos.0+(self.width*i))+r)
        }

        for range in range_table {
            for i in range {
                let loc = self.nth_to_pos(i);

                if dist(loc, pos) < r as f64 {self.buffer[i] = hex_to_rgb(color.to_string())?}
            }
        }


        unit!()
    }
    ///Draws a line between 2 points, with a thickness and color.
    pub fn line(&mut self, p1:(usize, usize), p2:(usize, usize), t:f64, color:&str) -> Unit {
        let fp1 = tupf64(p1);
        let fp2 = tupf64(p2);

        //let normal_p1 = (0.0, 0.0);
        let normal = (fp2.0-fp1.0, fp2.1-fp1.1);
        
        let m = (fp2.1 - fp1.1) / (fp2.0 - fp1.0);
        let p_line = perpendicular_line(m, fp1, t);
        let p_normal = (p_line.1.0 - p_line.0.0, p_line.1.1 - p_line.0.1);

        //this should make the step smaller the longer the line is
        let step = (1.0/dist(p1, p2)) * 0.9999;
        let p_step = 0.5/t;
        let mut t = 0.0;
        println!("{step}");
            while t <= 1.0 {
                let point = ((normal.0*t)+fp1.0, (normal.1*t)+fp1.1);
                let usize_p = (point.0 as usize, point.1 as usize);

                let loc = self.pos_to_nth(usize_p);
                

                if usize_p.0 < self.width && usize_p.1 < self.height {
                    self.buffer[loc] = hex_to_rgb(color.to_string())?;
                }

                let p_line = perpendicular_line(m, point, t);

                let mut j = 0.0;
                while j <= 1.0 {
                    let p_point = ((p_normal.0*j) + p_line.0.0, (p_normal.1*j) + p_line.0.1);
                    let usize_p_point = (p_point.0 as usize, p_point.1 as usize);

                    let p_loc = self.pos_to_nth(usize_p_point);
                    
                    if usize_p_point.0 < self.width && usize_p_point.1 < self.height {
                        self.buffer[p_loc] = hex_to_rgb(color.to_string())?;
                    }

                    j += p_step;
                }

                t += step;
            }


        unit!()
    }

}



























#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        //const escape = UpdateOptions::escape;
        let mut window = window!(?255, 255, "Window", "FF00FF");
        println!("{:?}", from_hex8(String::from("FFFFFF")));
        loop {
            window.update();
        }
    }
    #[test]
    fn uv_map() -> Unit {
        let mut window = window!(?500, 500, "Window", "FFFFFF");

        for (_val, pos) in window.iter() {
            let r = to_hex2(pos.0 as u8).unwrap();
            let g = to_hex2(pos.1 as u8).unwrap();
            let string = format!("{r}{g}00");
            //println!("{string}");
            window.set(pos, &string)?;
        }

        loop {
            window.update();
        }

        unit!()
    }
    
    #[test]
    fn shapes() -> Unit {
        let mut window = WindowContainer::new(1000, 1000, "Window", "FFFFFF").unwrap();

        window.circle((100, 100), 50, "CC00FF");
        
        window.line((800, 1000), (800, 0), 50.0, "FF0000");
        window.line((200, 200), (150, 230), 10.0, "0000FF");
        //window.line((10, 170), (3000, 170), 3.0, "FF00FF");
        
        loop {
            window.update();
        }

        unit!()
    }
}

///Errors concerning the WindowContainer.
#[derive(Debug)]
pub enum WinErr {
    MinifbError(minifb::Error),

    InvalidHexCode(String),
    InvalidHexChar(char),
    InvalidNumCode(u8),
    OverflowNum(u32),
    InvalidRGBValue(u32),


    InvalidIndex(usize),
    InvalidPos((usize, usize)),
}

impl From<minifb::Error> for WinErr {
    fn from(cause:minifb::Error) -> Self {
        WinErr::MinifbError(cause)
    }
}